|
| 1 | +from django.db import migrations, models |
| 2 | + |
| 3 | + |
| 4 | +def migrate_to_jsonb(apps, schema_editor): |
| 5 | + if schema_editor.connection.vendor != "postgresql": |
| 6 | + return |
| 7 | + with schema_editor.connection.cursor() as cursor: |
| 8 | + cursor.execute( |
| 9 | + "DROP INDEX IF EXISTS monitoring_metric_main_tags_2d8550ae_like; " |
| 10 | + "DROP INDEX IF EXISTS monitoring_metric_main_tags_2d8550ae;" |
| 11 | + ) |
| 12 | + cursor.execute( |
| 13 | + "ALTER TABLE monitoring_metric ALTER COLUMN main_tags TYPE jsonb USING main_tags::jsonb; " |
| 14 | + "ALTER TABLE monitoring_metric ALTER COLUMN extra_tags TYPE jsonb USING extra_tags::jsonb;" |
| 15 | + ) |
| 16 | + cursor.execute( |
| 17 | + "CREATE INDEX IF NOT EXISTS main_tags_gin_idx ON monitoring_metric USING gin (main_tags); " |
| 18 | + "CREATE INDEX IF NOT EXISTS extra_tags_gin_idx ON monitoring_metric USING gin (extra_tags);" |
| 19 | + ) |
| 20 | + |
| 21 | + |
| 22 | +def rollback_jsonb(apps, schema_editor): |
| 23 | + if schema_editor.connection.vendor != "postgresql": |
| 24 | + return |
| 25 | + with schema_editor.connection.cursor() as cursor: |
| 26 | + cursor.execute( |
| 27 | + "DROP INDEX IF EXISTS main_tags_gin_idx; DROP INDEX IF EXISTS extra_tags_gin_idx;" |
| 28 | + ) |
| 29 | + cursor.execute( |
| 30 | + "ALTER TABLE monitoring_metric ALTER COLUMN main_tags TYPE text; " |
| 31 | + "ALTER TABLE monitoring_metric ALTER COLUMN extra_tags TYPE text;" |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +class Migration(migrations.Migration): |
| 36 | + dependencies = [ |
| 37 | + ("monitoring", "0012_migrate_signal_metrics"), |
| 38 | + ] |
| 39 | + |
| 40 | + operations = [ |
| 41 | + migrations.SeparateDatabaseAndState( |
| 42 | + state_operations=[ |
| 43 | + migrations.AlterField( |
| 44 | + model_name="metric", |
| 45 | + name="main_tags", |
| 46 | + field=models.JSONField( |
| 47 | + blank=True, |
| 48 | + default=dict, |
| 49 | + help_text="main tags", |
| 50 | + verbose_name="main tags", |
| 51 | + ), |
| 52 | + ), |
| 53 | + migrations.AlterField( |
| 54 | + model_name="metric", |
| 55 | + name="extra_tags", |
| 56 | + field=models.JSONField( |
| 57 | + blank=True, |
| 58 | + default=dict, |
| 59 | + help_text="extra tags", |
| 60 | + verbose_name="extra tags", |
| 61 | + ), |
| 62 | + ), |
| 63 | + ], |
| 64 | + database_operations=[ |
| 65 | + migrations.RunPython(migrate_to_jsonb, reverse_code=rollback_jsonb), |
| 66 | + ], |
| 67 | + ), |
| 68 | + ] |
0 commit comments