|
| 1 | +from django.db import connection, migrations |
| 2 | + |
| 3 | +from netbox.plugins import get_plugin_config |
| 4 | +from netbox_branching.choices import BranchStatusChoices |
| 5 | + |
| 6 | + |
| 7 | +def copy_migrations(apps, schema_editor): |
| 8 | + """ |
| 9 | + Create a copy of the migrations table in each active branch. |
| 10 | + """ |
| 11 | + Branch = apps.get_model('netbox_branching', 'Branch') |
| 12 | + |
| 13 | + table = 'django_migrations' |
| 14 | + schema_prefix = get_plugin_config('netbox_branching', 'schema_prefix') |
| 15 | + |
| 16 | + with connection.cursor() as cursor: |
| 17 | + main_table = f'public.{table}' |
| 18 | + |
| 19 | + for branch in Branch.objects.filter(status=BranchStatusChoices.READY): |
| 20 | + print(f'\n Copying migrations for branch {branch.name} ({branch.schema_id})...', end='') |
| 21 | + schema_name = f'{schema_prefix}{branch.schema_id}' |
| 22 | + schema_table = f'{schema_name}.{table}' |
| 23 | + |
| 24 | + # Copy the migrations table to the branch schema |
| 25 | + cursor.execute(f"CREATE TABLE {schema_table} ( LIKE {main_table} INCLUDING INDEXES )") |
| 26 | + |
| 27 | + # Copy table data |
| 28 | + cursor.execute(f"INSERT INTO {schema_table} SELECT * FROM {main_table}") |
| 29 | + |
| 30 | + # Designate id as an identity column |
| 31 | + cursor.execute(f"ALTER TABLE {schema_table} ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY") |
| 32 | + |
| 33 | + # Set the next value for the ID sequence |
| 34 | + cursor.execute("SELECT MAX(id) from django_migrations") |
| 35 | + starting_id = cursor.fetchone()[0] + 1 |
| 36 | + cursor.execute(f"ALTER SEQUENCE {schema_name}.django_migrations_id_seq RESTART WITH {starting_id}") |
| 37 | + |
| 38 | + print('\n ', end='') # Padding for final "OK" |
| 39 | + |
| 40 | + |
| 41 | +class Migration(migrations.Migration): |
| 42 | + |
| 43 | + dependencies = [ |
| 44 | + ('netbox_branching', '0003_rename_indexes'), |
| 45 | + ] |
| 46 | + |
| 47 | + operations = [ |
| 48 | + migrations.RunPython( |
| 49 | + code=copy_migrations, |
| 50 | + reverse_code=migrations.RunPython.noop |
| 51 | + ), |
| 52 | + ] |
0 commit comments