# Generated by Django 3.2.12 on 2022-04-20 21:27

from django.db import connection, migrations

import baserow.contrib.database.fields.fields


def forward(apps, schema_editor):
    LinkRowField = apps.get_model("database", "LinkRowField")

    db_table = LinkRowField._meta.db_table
    db_column = "link_row_relation_id"

    sequence_name = (
        baserow.contrib.database.fields.fields.SerialField.get_sequence_name(
            db_table, db_column
        )
    )

    with connection.cursor() as cursor:
        cursor.execute(f"CREATE SEQUENCE IF NOT EXISTS {sequence_name};")
        cursor.execute(
            f"ALTER TABLE {db_table} ALTER COLUMN {db_column} SET DEFAULT nextval('{sequence_name}');"
        )
        cursor.execute(
            f"ALTER SEQUENCE {sequence_name} OWNED BY {db_table}.{db_column};"
        )


def reverse(apps, schema_editor):
    ...


class Migration(migrations.Migration):
    dependencies = [
        ("database", "0070_trashedrows"),
    ]

    operations = [
        migrations.AlterField(
            model_name="linkrowfield",
            name="link_row_relation_id",
            field=baserow.contrib.database.fields.fields.SerialField(null=True),
        ),
        migrations.RunPython(forward, reverse),
    ]
