Skip to content

Commit bccc12c

Browse files
committed
fix: reset PostgreSQL sequences after sync import to prevent IntegrityError
Sync import deletes and re-creates rows (NotificationRule, StageApprovalGroup, PostSubmissionAction, etc.) which leaves PostgreSQL auto-increment sequences behind the actual max ID in the table. The next admin-created record then hits a duplicate key IntegrityError (500 error). Added _reset_sequences() called at the end of import_payload() that resets sequences for all models that sync may delete/recreate. Safely skips non-PostgreSQL backends.
1 parent a1df06f commit bccc12c

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

django_forms_workflows/sync_api.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -922,4 +922,41 @@ def import_payload(payload, conflict="update"):
922922
form_data, conflict=conflict, category_cache=category_cache
923923
)
924924
results.append(result)
925+
926+
# ── 4. Reset PostgreSQL sequences ─────────────────────────────────────────
927+
# Sync deletes and re-creates rows (e.g. NotificationRule, StageApprovalGroup,
928+
# PostSubmissionAction) which can leave auto-increment sequences behind the
929+
# actual max ID in the table, causing IntegrityError on the next insert.
930+
_reset_sequences()
931+
925932
return results
933+
934+
935+
def _reset_sequences():
936+
"""Reset PostgreSQL sequences for all models that sync may delete/recreate.
937+
938+
Safe to call on any database backend — silently skips non-PostgreSQL.
939+
"""
940+
from django.db import connection
941+
942+
if connection.vendor != "postgresql":
943+
return
944+
945+
models_to_reset = [
946+
NotificationRule,
947+
StageApprovalGroup,
948+
PostSubmissionAction,
949+
WebhookEndpoint,
950+
WorkflowStage,
951+
FormField,
952+
]
953+
with connection.cursor() as cursor:
954+
for model in models_to_reset:
955+
table = model._meta.db_table
956+
pk_col = model._meta.pk.column
957+
cursor.execute(
958+
f"SELECT setval("
959+
f"pg_get_serial_sequence('{table}', '{pk_col}'), "
960+
f"COALESCE(MAX({pk_col}), 1)) "
961+
f"FROM {table}"
962+
)

0 commit comments

Comments
 (0)