# Generated by Django 3.2.5 on 2021-07-28 14:59
import random

from django.db import migrations, models

assigned_ids = set()

def try_saving_random_id():
    while True:
        id = random.getrandbits(32)
        if id not in assigned_ids:
            break
    assigned_ids.add(id)
    return id

def generate_random_id(apps, schema_editor):
    CaseMetadata = apps.get_model('capdb', 'CaseMetadata')

    fields = ['random_id']
    chunk = []
    for i, case in enumerate(CaseMetadata.objects.only(*fields).iterator(chunk_size=2000)):
        case.random_id = try_saving_random_id()
        chunk.append(case)
        if i % 2000 == 0 and chunk:
            CaseMetadata.objects.bulk_update(chunk, fields)
            chunk = []
    CaseMetadata.objects.bulk_update(chunk, fields)

class Migration(migrations.Migration):

    dependencies = [
        ('capdb', '0115_auto_20210527_2040'),
    ]

    operations = [
        migrations.AddField(
            model_name='casemetadata',
            name='random_id',
            field=models.BigIntegerField(null=True, unique=True),
        ),
        migrations.AddField(
            model_name='historicalcasemetadata',
            name='random_id',
            field=models.BigIntegerField(db_index=True, null=True),
        ),
        migrations.RunPython(generate_random_id, migrations.RunPython.noop)
    ]
