# Generated by Django 3.0.5 on 2020-05-27 12:41

from django.conf import settings
from django.db import connections
from django.db import migrations


def migrate_tables(apps, schema_editor):
    # Some tables in our dev machines, staging and production had latin1. Initially they were utf8mb4
    # then it was latin1. It might have been a Docker upgrade if the setting was done at Docker level.
    # In this migration:
    # -It sets the database character set to utf8mb4
    # -It migrates each table to utf8mb4

    if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
        # sqlite3 is used at the moment for unit testing using Github Actions.
        # This is not needed in sqlite3 (it's specific for Mysql/Mariadb)
        return

    conn = connections['default']

    cursor = conn.cursor()
    cursor.execute('ALTER DATABASE projects default CHARACTER SET utf8mb4')

    for app_name in ['colours', 'comments', 'evaluation', 'grant_management', 'project_core', 'variable_templates']:
        for model_name in apps.all_models[app_name].keys():
            model = apps.get_model(app_name, model_name)
            if not model._meta.abstract:
                table_name = model._meta.db_table
                sql = f'ALTER TABLE {table_name} convert to character set utf8mb4'
                cursor.execute(sql)

                # Recommended https://mathiasbynens.be/notes/mysql-utf8mb4
                cursor.execute(f'REPAIR TABLE {table_name}')
                cursor.execute(f'OPTIMIZE TABLE {table_name}')


class Migration(migrations.Migration):
    dependencies = [
        ('project_core', '0124_financialkey_funding_instrument'),
    ]

    operations = [
        migrations.RunPython(migrate_tables),
    ]
