# Generated by Django 5.2.4 on 2025-08-11 09:45

from django.db import migrations, models, connection




def add_allow_download_to_existing_documents(apps, schema_editor):

    # 使用原生SQL进行批量更新，避免加载大量对象到内存
    with connection.cursor() as cursor:
        # 为meta为null的记录设置初始值
        cursor.execute("""
                       UPDATE document
                       SET meta = '{"allow_download": true}'::jsonb
                       WHERE meta IS NULL
                       """)

        # 为meta不包含allow_download键的记录添加该字段
        cursor.execute("""
                       UPDATE document
                       SET meta = meta || '{"allow_download": true}'::jsonb
                       WHERE meta IS NOT NULL
                         AND NOT (meta ? 'allow_download')
                       """)


class Migration(migrations.Migration):

    dependencies = [
        ('knowledge', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='file',
            name='source_type',
            field=models.CharField(choices=[('KNOWLEDGE', 'Knowledge'), ('APPLICATION', 'Application'), ('TOOL', 'Tool'), ('DOCUMENT', 'Document'), ('CHAT', 'Chat'), ('SYSTEM', 'System'), ('TEMPORARY_30_MINUTE', 'Temporary 30 Minute'), ('TEMPORARY_120_MINUTE', 'Temporary 120 Minute'), ('TEMPORARY_1_DAY', 'Temporary 1 Day')], db_index=True, default='TEMPORARY_120_MINUTE', verbose_name='资源类型'),
        ),
        migrations.RunPython(add_allow_download_to_existing_documents)
    ]
