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

from django.db import migrations, models


class Migration(migrations.Migration):

    constraint_args = {
        'table': 'evaluations_criterion',
        'constraint': 'evaluations_criterion_sort_order_id_key',
    }

    dependencies = [
        ('evaluations', '0014_add_missing_verbose_name'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
             name='criterion',
             unique_together=set([]),
         ),
        # we can have duplicate in sort order. So before adding the unique constraints we need to
        # clean the sort order.

        # the inner query is ordered by sort_order and id to be sure the order is unique.
        # because we use OVER(PARTITION BY exercise_id) the row_number is calculated per exercise
        # we then use this row_number to update
        # all the evaluations_criterion.sort_order in one call

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

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

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

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