diff --git a/backend/migrations/versions/f7a8b9c0d1e2_ensure_agents_primary_key.py b/backend/migrations/versions/f7a8b9c0d1e2_ensure_agents_primary_key.py new file mode 100644 index 00000000..12b96795 --- /dev/null +++ b/backend/migrations/versions/f7a8b9c0d1e2_ensure_agents_primary_key.py @@ -0,0 +1,71 @@ +"""ensure agents table has primary key on id + +Revision ID: f7a8b9c0d1e2 +Revises: f6d4e5f6a7b8 +Create Date: 2026-05-20 00:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +revision = 'f7a8b9c0d1e2' +down_revision = 'f6d4e5f6a7b8' +branch_labels = None +depends_on = None + + +def upgrade(): + conn = op.get_bind() + inspector = sa.inspect(conn) + + if 'agents' not in inspector.get_table_names(): + return + + pk = inspector.get_pk_constraint('agents') or {} + constrained_columns = pk.get('constrained_columns') or [] + if constrained_columns: + return + + duplicate_count = conn.execute( + sa.text( + """ + SELECT COUNT(*) + FROM ( + SELECT id + FROM agents + GROUP BY id + HAVING COUNT(*) > 1 + ) t + """ + ) + ).scalar_one() + if duplicate_count > 0: + raise RuntimeError( + "Cannot add PRIMARY KEY to agents.id because duplicate id values exist. " + "Please deduplicate agents.id first, then rerun migration." + ) + + null_count = conn.execute( + sa.text("SELECT COUNT(*) FROM agents WHERE id IS NULL") + ).scalar_one() + if null_count > 0: + raise RuntimeError( + "Cannot add PRIMARY KEY to agents.id because NULL id values exist. " + "Please fix NULL ids first, then rerun migration." + ) + + op.execute('ALTER TABLE agents ADD CONSTRAINT agents_pkey PRIMARY KEY (id)') + + +def downgrade(): + conn = op.get_bind() + inspector = sa.inspect(conn) + if 'agents' not in inspector.get_table_names(): + return + + pk = inspector.get_pk_constraint('agents') or {} + pk_name = pk.get('name') + cols = pk.get('constrained_columns') or [] + if pk_name == 'agents_pkey' and cols == ['id']: + op.drop_constraint('agents_pkey', 'agents', type_='primary') diff --git a/backend/migrations/versions/f8b9c0d1e2f3_merge_heads_after_agents_pk_fix.py b/backend/migrations/versions/f8b9c0d1e2f3_merge_heads_after_agents_pk_fix.py new file mode 100644 index 00000000..3d0a16fb --- /dev/null +++ b/backend/migrations/versions/f8b9c0d1e2f3_merge_heads_after_agents_pk_fix.py @@ -0,0 +1,21 @@ +"""merge heads after agents pk fix + +Revision ID: f8b9c0d1e2f3 +Revises: c0ae052bd24e, f7a8b9c0d1e2 +Create Date: 2026-05-20 00:30:00.000000 + +""" + + +revision = 'f8b9c0d1e2f3' +down_revision = ('c0ae052bd24e', 'f7a8b9c0d1e2') +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass