# Generated by Django 2.2.11 on 2021-06-14 09:08
from django.db import connection, migrations, models


def forward(apps, schema_editor):
    # noinspection PyPep8Naming
    Table = apps.get_model("database", "Table")

    with connection.schema_editor(atomic=False) as tables_schema_editor:
        for table in Table.objects.all():
            table_name = f"database_table_{table.id}"
            # Make the forward migration more idempotent / resilient to partially
            # applied migrations due to the lack of a transaction by using IF NOT
            # EXISTS.
            tables_schema_editor.execute(
                f"ALTER TABLE {table_name} "
                f"ADD COLUMN IF NOT EXISTS trashed boolean not null default false"
            )


def reverse(apps, schema_editor):
    # noinspection PyPep8Naming
    Table = apps.get_model("database", "Table")

    with connection.schema_editor(atomic=False) as tables_schema_editor:
        # apps.get_model doesn't return a model using our custom overridden managers
        # so we can safely use .objects which will return all trashed tables also
        for table in Table.objects.all():
            table_name = f"database_table_{table.id}"
            # Make the reverse migration more idempotent / resilient to partially
            # applied migrations due to the lack of a transaction by using IF EXISTS.
            tables_schema_editor.execute(
                f"ALTER TABLE {table_name} DROP COLUMN IF EXISTS trashed"
            )


class Migration(migrations.Migration):
    atomic = False
    dependencies = [
        ("database", "0031_fix_url_field_max_length"),
    ]

    operations = [
        migrations.AddField(
            model_name="field",
            name="trashed",
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name="table",
            name="trashed",
            field=models.BooleanField(default=False),
        ),
        migrations.RunPython(forward, reverse),
    ]
