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,16 +21,31 @@ 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)
# Skip if chats table doesn't exist (fresh database)
if table_exists("chats"):
op.execute(""" op.execute("""
ALTER TABLE chats ALTER TABLE chats
ADD COLUMN IF NOT EXISTS state_version BIGINT DEFAULT 1 NOT NULL 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
if table_exists("podcasts"):
op.execute(""" op.execute("""
ALTER TABLE podcasts ALTER TABLE podcasts
ADD COLUMN IF NOT EXISTS chat_state_version BIGINT ADD COLUMN IF NOT EXISTS chat_state_version BIGINT
@ -44,6 +61,7 @@ def upgrade() -> None:
def downgrade() -> None: def downgrade() -> None:
"""Remove columns only if they exist.""" """Remove columns only if they exist."""
if table_exists("podcasts"):
op.execute(""" op.execute("""
ALTER TABLE podcasts ALTER TABLE podcasts
DROP COLUMN IF EXISTS chat_state_version DROP COLUMN IF EXISTS chat_state_version
@ -54,6 +72,7 @@ def downgrade() -> None:
DROP COLUMN IF EXISTS chat_id DROP COLUMN IF EXISTS chat_id
""") """)
if table_exists("chats"):
op.execute(""" op.execute("""
ALTER TABLE chats ALTER TABLE chats
DROP COLUMN IF EXISTS state_version DROP COLUMN IF EXISTS state_version