From 191a6fb4c4eb3cfccc940652f2947747f87b23eb Mon Sep 17 00:00:00 2001 From: Agent Zero Date: Fri, 24 Jul 2026 01:50:11 +0200 Subject: [PATCH] fix(migration): handle existing contact_id column in mails table --- .../versions/0027_unify_company_to_contact.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/alembic/versions/0027_unify_company_to_contact.py b/alembic/versions/0027_unify_company_to_contact.py index 177e030..21eadcc 100644 --- a/alembic/versions/0027_unify_company_to_contact.py +++ b/alembic/versions/0027_unify_company_to_contact.py @@ -38,10 +38,16 @@ def upgrade(): ) # Rename company_id to contact_id in mails (if column exists) conn = op.get_bind() - result = conn.execute( + has_company_id = conn.execute( sa.text("SELECT 1 FROM information_schema.columns WHERE table_name='mails' AND column_name='company_id'") ).fetchone() - if result: + has_contact_id = conn.execute( + sa.text("SELECT 1 FROM information_schema.columns WHERE table_name='mails' AND column_name='contact_id'") + ).fetchone() + if has_company_id and has_contact_id: + # Both columns exist: drop company_id (contact_id already present) + op.drop_column("mails", "company_id") + elif has_company_id: op.alter_column("mails", "company_id", new_column_name="contact_id") @@ -62,10 +68,13 @@ def downgrade(): op.execute( "UPDATE addresses SET entity_type = 'company' WHERE entity_type = 'contact'" ) - # Rename contact_id back to company_id in mails + # Rename contact_id back to company_id in mails (only if contact_id exists and company_id doesn't) conn = op.get_bind() - result = conn.execute( + has_contact_id = conn.execute( sa.text("SELECT 1 FROM information_schema.columns WHERE table_name='mails' AND column_name='contact_id'") ).fetchone() - if result: + has_company_id = conn.execute( + sa.text("SELECT 1 FROM information_schema.columns WHERE table_name='mails' AND column_name='company_id'") + ).fetchone() + if has_contact_id and not has_company_id: op.alter_column("mails", "contact_id", new_column_name="company_id")