# NOTE: the foreign key checks are disabled and re-enabled in this migration
# see the following resources as to why
#
# https://arc.net/l/quote/hgqztayk
# https://dba.stackexchange.com/a/316683
#
# tldr;
# The INPLACE algorithm is supported when foreign_key_checks is disabled. Otherwise, only the COPY algorithm is supported
#
# which means that creating this foreign key constraint, without this, on a large table would take foreverz

# Generated by Django 4.2.16 on 2024-11-22 12:36

import logging

from django.db import migrations, models
import django.db.models.deletion
import django_migration_linter as linter

logger = logging.getLogger(__name__)


def disable_foreign_key_checks(apps, schema_editor):
    if schema_editor.connection.vendor == 'mysql':
        with schema_editor.connection.cursor() as cursor:
            cursor.execute('SET SESSION foreign_key_checks = OFF;')
            logger.info("Disabled foreign key checks.")
    else:
        logger.info("Skipping disabling foreign key checks for non-MySQL database.")


def enable_foreign_key_checks(apps, schema_editor):
    if schema_editor.connection.vendor == 'mysql':
        with schema_editor.connection.cursor() as cursor:
            cursor.execute('SET SESSION foreign_key_checks = ON;')
            logger.info("Re-enabled foreign key checks.")
    else:
        logger.info("Skipping enabling foreign key checks for non-MySQL database.")


class Migration(migrations.Migration):

    dependencies = [
        ('slack', '0005_slackteamidentity__unified_slack_app_installed'),
    ]

    operations = [
        linter.IgnoreMigration(),
        migrations.RenameField(
            model_name='slackmessage',
            old_name='channel_id',
            new_name='_channel_id',
        ),
        migrations.RunPython(disable_foreign_key_checks, reverse_code=migrations.RunPython.noop),
        migrations.AddField(
            model_name='slackmessage',
            name='channel',
            field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='slack_messages', to='slack.slackchannel'),
        ),
        migrations.RunPython(enable_foreign_key_checks, reverse_code=migrations.RunPython.noop),
    ]
