# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-02-13 10:49
from __future__ import unicode_literals

from django.db import connection, migrations, transaction


FIND_CONSTRAINT_NAME_QUERY = """
SELECT tc.constraint_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE
tc.table_name = 'inventory_machinesnapshotcommit'
AND kcu.column_name = 'parent_id'
AND ccu.table_name = 'inventory_machinesnapshotcommit'
AND ccu.column_name = 'id'
"""

DROP_CONSTRAINT_QUERY = """
ALTER TABLE inventory_machinesnapshotcommit
DROP CONSTRAINT {}
"""

ADD_CONSTRAINT_QUERY = """
ALTER TABLE inventory_machinesnapshotcommit
ADD CONSTRAINT {}
FOREIGN KEY (parent_id)
REFERENCES inventory_machinesnapshotcommit(id)
ON DELETE SET NULL
DEFERRABLE INITIALLY DEFERRED
"""


def alter_constraint(apps, schema_editor):
    with transaction.atomic():
        with connection.cursor() as cursor:
            cursor.execute(FIND_CONSTRAINT_NAME_QUERY)
            t = cursor.fetchone()
            constraint_name = t[0]
            cursor.execute(DROP_CONSTRAINT_QUERY.format(constraint_name))
            cursor.execute(ADD_CONSTRAINT_QUERY.format(constraint_name))


class Migration(migrations.Migration):

    dependencies = [
        ('inventory', '0035_auto_20180211_1908'),
    ]

    operations = [
        migrations.RunPython(alter_constraint)
    ]
