Make migration 34 idempotent

This commit is contained in:
CREDO23 2026-01-13 20:13:13 +02:00
parent 60a7269ce8
commit e99e2134fa

View file

@ -10,6 +10,8 @@ Revises: 33
from collections.abc import Sequence from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op from alembic import op
# revision identifiers # revision identifiers
@ -19,42 +21,59 @@ branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None
def table_exists(table_name: str) -> bool:
"""Check if a table exists in the database."""
conn = op.get_bind()
result = conn.execute(
sa.text(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = :table_name)"
),
{"table_name": table_name},
)
return result.scalar()
def upgrade() -> None: def upgrade() -> None:
"""Add columns only if they don't already exist (safe for re-runs).""" """Add columns only if they don't already exist (safe for re-runs)."""
# Add 'state_version' column to chats table (default 1) # Add 'state_version' column to chats table (default 1)
op.execute(""" # Skip if chats table doesn't exist (fresh database)
ALTER TABLE chats if table_exists("chats"):
ADD COLUMN IF NOT EXISTS state_version BIGINT DEFAULT 1 NOT NULL op.execute("""
""") ALTER TABLE chats
ADD COLUMN IF NOT EXISTS state_version BIGINT DEFAULT 1 NOT NULL
""")
# Add 'chat_state_version' column to podcasts table # Add 'chat_state_version' column to podcasts table
op.execute(""" if table_exists("podcasts"):
ALTER TABLE podcasts op.execute("""
ADD COLUMN IF NOT EXISTS chat_state_version BIGINT ALTER TABLE podcasts
""") ADD COLUMN IF NOT EXISTS chat_state_version BIGINT
""")
# Add 'chat_id' column to podcasts table # Add 'chat_id' column to podcasts table
op.execute(""" op.execute("""
ALTER TABLE podcasts ALTER TABLE podcasts
ADD COLUMN IF NOT EXISTS chat_id INTEGER ADD COLUMN IF NOT EXISTS chat_id INTEGER
""") """)
def downgrade() -> None: def downgrade() -> None:
"""Remove columns only if they exist.""" """Remove columns only if they exist."""
op.execute(""" if table_exists("podcasts"):
ALTER TABLE podcasts op.execute("""
DROP COLUMN IF EXISTS chat_state_version ALTER TABLE podcasts
""") DROP COLUMN IF EXISTS chat_state_version
""")
op.execute(""" op.execute("""
ALTER TABLE podcasts ALTER TABLE podcasts
DROP COLUMN IF EXISTS chat_id DROP COLUMN IF EXISTS chat_id
""") """)
op.execute(""" if table_exists("chats"):
ALTER TABLE chats op.execute("""
DROP COLUMN IF EXISTS state_version ALTER TABLE chats
""") DROP COLUMN IF EXISTS state_version
""")