|
| 1 | +"""add_team_id_to_config_table |
| 2 | +
|
| 3 | +Revision ID: c78d76a6d65c |
| 4 | +Revises: 1f7cb465d15a |
| 5 | +Create Date: 2025-12-04 11:23:22.165544 |
| 6 | +
|
| 7 | +""" |
| 8 | + |
| 9 | +from typing import Sequence, Union |
| 10 | + |
| 11 | +from alembic import op |
| 12 | +import sqlalchemy as sa |
| 13 | + |
| 14 | + |
| 15 | +# revision identifiers, used by Alembic. |
| 16 | +revision: str = "c78d76a6d65c" |
| 17 | +down_revision: Union[str, Sequence[str], None] = "1f7cb465d15a" |
| 18 | +branch_labels: Union[str, Sequence[str], None] = None |
| 19 | +depends_on: Union[str, Sequence[str], None] = None |
| 20 | + |
| 21 | + |
| 22 | +def upgrade() -> None: |
| 23 | + """Upgrade schema.""" |
| 24 | + connection = op.get_bind() |
| 25 | + |
| 26 | + # Check existing columns |
| 27 | + column_result = connection.execute(sa.text("PRAGMA table_info(config)")) |
| 28 | + existing_columns = [row[1] for row in column_result.fetchall()] |
| 29 | + |
| 30 | + # Get existing indexes by querying SQLite directly |
| 31 | + # SQLite stores unique constraints as unique indexes |
| 32 | + index_result = connection.execute( |
| 33 | + sa.text("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='config'") |
| 34 | + ) |
| 35 | + existing_index_names = [row[0] for row in index_result.fetchall()] |
| 36 | + |
| 37 | + # Add columns first (outside batch mode to avoid circular dependency) |
| 38 | + # Only add if they don't already exist |
| 39 | + if "user_id" not in existing_columns: |
| 40 | + op.add_column("config", sa.Column("user_id", sa.String(), nullable=True)) |
| 41 | + if "team_id" not in existing_columns: |
| 42 | + op.add_column("config", sa.Column("team_id", sa.String(), nullable=True)) |
| 43 | + |
| 44 | + # Handle indexes outside of batch mode to avoid type inference issues |
| 45 | + # Drop existing unique index on key if it exists (to recreate as non-unique) |
| 46 | + if "ix_config_key" in existing_index_names: |
| 47 | + # Check if it's unique by querying the index definition |
| 48 | + index_info = connection.execute( |
| 49 | + sa.text("SELECT sql FROM sqlite_master WHERE type='index' AND name='ix_config_key'") |
| 50 | + ).fetchone() |
| 51 | + if index_info and index_info[0] and "UNIQUE" in index_info[0].upper(): |
| 52 | + # Drop the unique index using raw SQL to avoid batch mode issues |
| 53 | + connection.execute(sa.text("DROP INDEX IF EXISTS ix_config_key")) |
| 54 | + existing_index_names.remove("ix_config_key") # Update our list |
| 55 | + |
| 56 | + # Create new indexes (non-unique) - these can be done outside batch mode |
| 57 | + if "ix_config_key" not in existing_index_names: |
| 58 | + op.create_index("ix_config_key", "config", ["key"], unique=False) |
| 59 | + if "ix_config_user_id" not in existing_index_names: |
| 60 | + op.create_index("ix_config_user_id", "config", ["user_id"], unique=False) |
| 61 | + if "ix_config_team_id" not in existing_index_names: |
| 62 | + op.create_index("ix_config_team_id", "config", ["team_id"], unique=False) |
| 63 | + |
| 64 | + # For SQLite, unique constraints are stored as unique indexes |
| 65 | + # Create the unique constraint as a unique index using raw SQL to avoid batch mode issues |
| 66 | + if "uq_config_user_team_key" not in existing_index_names: |
| 67 | + connection.execute( |
| 68 | + sa.text("CREATE UNIQUE INDEX IF NOT EXISTS uq_config_user_team_key ON config(user_id, team_id, key)") |
| 69 | + ) |
| 70 | + |
| 71 | + # Migrate existing configs to admin user's first team |
| 72 | + # Note: Don't call connection.commit() - Alembic manages transactions |
| 73 | + connection = op.get_bind() |
| 74 | + # Find admin user's first team |
| 75 | + admin_team_result = connection.execute( |
| 76 | + sa.text(""" |
| 77 | + SELECT ut.team_id |
| 78 | + FROM users_teams ut |
| 79 | + JOIN user u ON ut.user_id = u.id |
| 80 | + WHERE u.email = 'admin@example.com' |
| 81 | + LIMIT 1 |
| 82 | + """) |
| 83 | + ) |
| 84 | + admin_team_row = admin_team_result.fetchone() |
| 85 | + |
| 86 | + if admin_team_row: |
| 87 | + admin_team_id = admin_team_row[0] |
| 88 | + # Update all existing configs (where team_id is NULL) to use admin team |
| 89 | + connection.execute( |
| 90 | + sa.text("UPDATE config SET team_id = :team_id WHERE team_id IS NULL"), {"team_id": admin_team_id} |
| 91 | + ) |
| 92 | + print(f"✅ Migrated existing configs to team {admin_team_id}") |
| 93 | + else: |
| 94 | + # If no admin team found, try to get any user's first team |
| 95 | + any_team_result = connection.execute(sa.text("SELECT team_id FROM users_teams LIMIT 1")) |
| 96 | + any_team_row = any_team_result.fetchone() |
| 97 | + if any_team_row: |
| 98 | + any_team_id = any_team_row[0] |
| 99 | + connection.execute( |
| 100 | + sa.text("UPDATE config SET team_id = :team_id WHERE team_id IS NULL"), {"team_id": any_team_id} |
| 101 | + ) |
| 102 | + print(f"✅ Migrated existing configs to team {any_team_id}") |
| 103 | + else: |
| 104 | + # No teams found, delete existing configs |
| 105 | + deleted_count = connection.execute(sa.text("DELETE FROM config WHERE team_id IS NULL")).rowcount |
| 106 | + print(f"⚠️ No teams found, deleted {deleted_count} config entries") |
| 107 | + # ### end Alembic commands ### |
| 108 | + |
| 109 | + |
| 110 | +def downgrade() -> None: |
| 111 | + """Downgrade schema.""" |
| 112 | + connection = op.get_bind() |
| 113 | + |
| 114 | + # Check existing indexes |
| 115 | + index_result = connection.execute( |
| 116 | + sa.text("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='config'") |
| 117 | + ) |
| 118 | + existing_index_names = [row[0] for row in index_result.fetchall()] |
| 119 | + |
| 120 | + # Check existing columns |
| 121 | + column_result = connection.execute(sa.text("PRAGMA table_info(config)")) |
| 122 | + existing_columns = [row[1] for row in column_result.fetchall()] |
| 123 | + |
| 124 | + # Drop indexes and constraints outside of batch mode to avoid type inference issues |
| 125 | + # Drop unique constraint (stored as unique index in SQLite) |
| 126 | + if "uq_config_user_team_key" in existing_index_names: |
| 127 | + connection.execute(sa.text("DROP INDEX IF EXISTS uq_config_user_team_key")) |
| 128 | + |
| 129 | + # Drop indexes |
| 130 | + if "ix_config_team_id" in existing_index_names: |
| 131 | + op.drop_index("ix_config_team_id", table_name="config") |
| 132 | + if "ix_config_user_id" in existing_index_names: |
| 133 | + op.drop_index("ix_config_user_id", table_name="config") |
| 134 | + if "ix_config_key" in existing_index_names: |
| 135 | + op.drop_index("ix_config_key", table_name="config") |
| 136 | + |
| 137 | + # Drop columns using raw SQL to avoid batch mode type inference issues |
| 138 | + # SQLite doesn't support DROP COLUMN directly, so we recreate the table |
| 139 | + if "team_id" in existing_columns or "user_id" in existing_columns: |
| 140 | + # Create new table without user_id and team_id columns |
| 141 | + connection.execute( |
| 142 | + sa.text(""" |
| 143 | + CREATE TABLE config_new ( |
| 144 | + id INTEGER NOT NULL PRIMARY KEY, |
| 145 | + key VARCHAR NOT NULL, |
| 146 | + value VARCHAR |
| 147 | + ) |
| 148 | + """) |
| 149 | + ) |
| 150 | + # Copy data from old table to new table (only id, key, value columns) |
| 151 | + connection.execute(sa.text("INSERT INTO config_new (id, key, value) SELECT id, key, value FROM config")) |
| 152 | + # Drop old table (this also drops all indexes) |
| 153 | + connection.execute(sa.text("DROP TABLE config")) |
| 154 | + # Rename new table to original name |
| 155 | + connection.execute(sa.text("ALTER TABLE config_new RENAME TO config")) |
| 156 | + # Recreate the original unique index on key (it was dropped with the old table) |
| 157 | + op.create_index("ix_config_key", "config", ["key"], unique=True) |
| 158 | + else: |
| 159 | + # If we're not dropping columns, just recreate the unique index on key |
| 160 | + op.create_index("ix_config_key", "config", ["key"], unique=True) |
| 161 | + # ### end Alembic commands ### |
0 commit comments