Skip to content

Commit a6c915c

Browse files
committed
fix: tag composite pk in migration
1 parent 3493ffa commit a6c915c

1 file changed

Lines changed: 14 additions & 11 deletions

File tree

backend/open_webui/migrations/versions/461111b60977_add_missing_primary_keys_to_legacy_.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,41 +19,44 @@
1919
# Tables bootstrapped by the old Peewee migration layer that may have
2020
# UNIQUE(id) but no PRIMARY KEY constraint. Fresh Alembic installs
2121
# already have correct PKs from 7e5b5dc7342b_init.py.
22-
LEGACY_TABLES = [
23-
'auth', 'chat', 'chatidtag', 'document', 'file',
24-
'function', 'memory', 'model', 'prompt', 'tag', 'tool', 'user',
25-
]
22+
# 'tag' uses a composite PK since the same tag name can exist for multiple users.
23+
LEGACY_TABLES = {
24+
'auth': ['id'], 'chat': ['id'], 'chatidtag': ['id'], 'document': ['id'],
25+
'file': ['id'], 'function': ['id'], 'memory': ['id'], 'model': ['id'],
26+
'prompt': ['id'], 'tag': ['id', 'user_id'], 'tool': ['id'], 'user': ['id'],
27+
}
2628

2729

2830
def upgrade() -> None:
2931
conn = op.get_bind()
3032
inspector = sa.inspect(conn)
3133
existing_tables = set(inspector.get_table_names())
3234

33-
for table_name in LEGACY_TABLES:
35+
for table_name, pk_columns in LEGACY_TABLES.items():
3436
if table_name not in existing_tables:
3537
continue
3638

3739
pk = inspector.get_pk_constraint(table_name)
3840
pk_cols = pk.get('constrained_columns', [])
3941

40-
# Already has a proper PK on 'id' — nothing to do
41-
if pk_cols == ['id']:
42+
# Already has the correct PK — nothing to do
43+
if sorted(pk_cols) == sorted(pk_columns):
4244
continue
4345

44-
# Check that an 'id' column actually exists
46+
# Check that all PK columns exist
4547
columns = {c['name'] for c in inspector.get_columns(table_name)}
46-
if 'id' not in columns:
48+
if not all(c in columns for c in pk_columns):
4749
continue
4850

49-
print(f"Promoting UNIQUE(id) PRIMARY KEY for '{table_name}'")
51+
print(f"Promoting UNIQUE(id) -> PRIMARY KEY({', '.join(pk_columns)}) for '{table_name}'")
5052

53+
conn.execute(sa.text(f'DROP TABLE IF EXISTS _alembic_tmp_{table_name}'))
5154
with op.batch_alter_table(table_name) as batch_op:
5255
# Drop existing PK if any (e.g. on wrong column)
5356
if pk_cols and pk.get('name'):
5457
batch_op.drop_constraint(pk['name'], type_='primary')
5558

56-
batch_op.create_primary_key(f'pk_{table_name}_id', ['id'])
59+
batch_op.create_primary_key(f'pk_{table_name}', pk_columns)
5760

5861

5962
def downgrade() -> None:

0 commit comments

Comments
 (0)