From dc1daf0a2ddd6a74be0f2c06473a6ad16596d10b Mon Sep 17 00:00:00 2001 From: Pierre-antoine Comby Date: Tue, 2 Jun 2020 10:46:08 +0200 Subject: [PATCH] add command to synchronize db sequences --- management/commands/import_nk15.py | 1 + management/commands/syncsql.py | 43 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 management/commands/syncsql.py diff --git a/management/commands/import_nk15.py b/management/commands/import_nk15.py index 519a1b5..12d7164 100644 --- a/management/commands/import_nk15.py +++ b/management/commands/import_nk15.py @@ -16,3 +16,4 @@ class Command(BaseCommand): call_command('import_activities', chunk=5000, map="map.json") call_command('import_transaction', chunk=5000, buttons=True, map="map.json") call_command('make_su','-sS', 'Coq', 'erdnaxe', 'PAC', 'Pollion', 'ÿnérant') + call_command('syncsql') diff --git a/management/commands/syncsql.py b/management/commands/syncsql.py new file mode 100644 index 0000000..92a908d --- /dev/null +++ b/management/commands/syncsql.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +from django.core.management.base import BaseCommand +from django.apps import apps +from django.db import connection + + +from polymorphic.models import PolymorphicModel + +NO_SEQ = [ + "Session", + "Token", + "WEIRole", # dirty fix +] + +class Command(BaseCommand): + """ + Command to synchronise primary sequence of postgres after bulk insert of django. + """ + + def add_arguments(self,parser): + parser.add_argument('apps', type=str,nargs='*',help='applications which table would be resynchronized') + return parser + + def handle(self, *args, **kwargs): + app_list = kwargs["apps"] + if len(app_list): + model_classes = list() + for app in app_list: + model_classes += apps.get_app_config(app).get_models() + else: + # no app specified, sync everything + model_classes = apps.get_models(include_auto_created=True) + + db_names = [ m._meta.db_table for m in model_classes if m.__base__.__base__ is not PolymorphicModel and m.__name__ not in NO_SEQ and m.objects.count()>1] + com = "BEGIN;\n" + for db_name in db_names: + com += f'SELECT setval(pg_get_serial_sequence(\'"{db_name}"\',\'id\'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "{db_name}";\n' + com += "COMMIT;" + print(com) + cur = connection.cursor() + cur.execute(com) + cur.close()