# Generated by Django 2.2.24 on 2021-08-27 17:56

from django.db import migrations, models

def force_unique_title(apps, schema_editor):
    # I've verified there are no duplicates in Stage and Prod.
    # This was brought up as a thing devs might need for their local devstack.
    EnterpriseCatalogQuery = apps.get_model('enterprise', 'EnterpriseCatalogQuery')
    duplicate_queries = EnterpriseCatalogQuery.objects.raw(
        'SELECT cq1.title, cq1.id from enterprise_enterprisecatalogquery cq1 '
        'JOIN (select count(*), title from enterprise_enterprisecatalogquery GROUP BY title having count(*) > 1) cq2 '
        'ON cq1.title=cq2.title'
    )
    for query in duplicate_queries:
        query.title = f'{query.title}{query.id}'
        query.save(update_fields=['title'])


class Migration(migrations.Migration):
    dependencies = [
        ('enterprise', '0140_update_enrollment_sources'),
    ]
    operations = [
        migrations.RunPython(
            code=force_unique_title,
            reverse_code=migrations.RunPython.noop
        ),
        migrations.AlterField(
            model_name='enterprisecatalogquery',
            name='title',
            field=models.CharField(blank=True, max_length=255, null=True, unique=True),
        ),
    ]
