# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    constraint_args = {
        'table': 'evaluations_exercise',
        'constraint': 'evaluations_exercise_sort_order_id_key',
    }

    dependencies = [
        ('evaluations', '0015_add_unique_together_sort_order_exercise'),
    ]

    operations = [

        migrations.AlterUniqueTogether(
             name='exercise',
             unique_together=set([]),
         ),

        migrations.RunSQL(
            """
            UPDATE evaluations_exercise SET sort_order=row_number
            FROM (
                SELECT id, row_number()
                    OVER(PARTITION BY evaluation_id)
                FROM evaluations_exercise
                ORDER BY sort_order, id) as new_orders
            WHERE evaluations_exercise.id=new_orders.id;
            """,
            ""
        ),

        migrations.RunSQL(
            'ALTER TABLE %(table)s ADD CONSTRAINT "%(constraint)s" '
            'UNIQUE (sort_order, evaluation_id) DEFERRABLE INITIALLY DEFERRED;' % constraint_args,

            'ALTER TABLE %(table)s DROP CONSTRAINT %(constraint)s' % constraint_args,
        ),

        migrations.AlterUniqueTogether(
            name='exercise',
            unique_together=set([('sort_order', 'evaluation')]),
        ),
    ]
