|
| 1 | +"""Alembic migration environment configuration.""" |
| 2 | + |
| 3 | +import os |
| 4 | + |
| 5 | +# pylint: disable=no-member |
| 6 | +from logging.config import fileConfig |
| 7 | +from urllib.parse import quote |
| 8 | + |
| 9 | +from sqlalchemy import pool |
| 10 | + |
| 11 | +from alembic import context |
| 12 | + |
| 13 | +# Import Base metadata for autogenerate support |
| 14 | +# Note: We import from app.models.base which is side-effect free |
| 15 | +# (doesn't create database connections or read environment variables) |
| 16 | +from app.models.base import Base |
| 17 | + |
| 18 | + |
| 19 | +def get_sync_database_url() -> str: |
| 20 | + """ |
| 21 | + Get synchronous database URL for Alembic migrations. |
| 22 | +
|
| 23 | + Alembic uses synchronous database connections, so we need to convert |
| 24 | + the async URL (postgresql+asyncpg://) to sync format (postgresql+psycopg://). |
| 25 | +
|
| 26 | + Returns: |
| 27 | + str: Synchronous database connection URL |
| 28 | + """ |
| 29 | + # First try DATABASE_URL from environment |
| 30 | + database_url = os.getenv("DATABASE_URL") |
| 31 | + if database_url: |
| 32 | + # Normalize common PostgreSQL DSNs to use the psycopg (sync) driver. |
| 33 | + # Handle bare postgres:// and postgresql:// URLs that don't specify a driver. |
| 34 | + if database_url.startswith("postgres://"): |
| 35 | + # postgres://user:pass@host/db -> postgresql+psycopg://user:pass@host/db |
| 36 | + database_url = "postgresql+psycopg://" + database_url[len("postgres://") :] |
| 37 | + elif database_url.startswith("postgresql://") and not database_url.startswith("postgresql+"): |
| 38 | + # postgresql://user:pass@host/db -> postgresql+psycopg://user:pass@host/db |
| 39 | + database_url = "postgresql+psycopg://" + database_url[len("postgresql://") :] |
| 40 | + |
| 41 | + # Convert async driver to sync driver if needed |
| 42 | + # postgresql+asyncpg:// -> postgresql+psycopg:// |
| 43 | + if database_url.startswith("postgresql+asyncpg://"): |
| 44 | + database_url = "postgresql+psycopg://" + database_url[len("postgresql+asyncpg://") :] |
| 45 | + |
| 46 | + return database_url |
| 47 | + |
| 48 | + # Construct from individual variables |
| 49 | + db_host = os.getenv("DATABASE_HOST") |
| 50 | + db_port = os.getenv("DATABASE_PORT", "5432") # Default PostgreSQL port |
| 51 | + db_user = os.getenv("DATABASE_USER") |
| 52 | + db_pass = os.getenv("DATABASE_PASSWORD") |
| 53 | + db_name = os.getenv("DATABASE_NAME") |
| 54 | + |
| 55 | + # Validate required environment variables (consistent with app/database.py) |
| 56 | + missing_vars = [ |
| 57 | + name |
| 58 | + for name, value in [ |
| 59 | + ("DATABASE_HOST", db_host), |
| 60 | + ("DATABASE_USER", db_user), |
| 61 | + ("DATABASE_PASSWORD", db_pass), |
| 62 | + ("DATABASE_NAME", db_name), |
| 63 | + ] |
| 64 | + if not value |
| 65 | + ] |
| 66 | + |
| 67 | + if missing_vars: |
| 68 | + raise RuntimeError( |
| 69 | + f"Database configuration is incomplete. Missing environment variables: {', '.join(missing_vars)}" |
| 70 | + ) |
| 71 | + |
| 72 | + # At this point, we know these are not None |
| 73 | + assert db_host is not None |
| 74 | + assert db_user is not None |
| 75 | + assert db_pass is not None |
| 76 | + assert db_name is not None |
| 77 | + |
| 78 | + # URL-encode username and password to handle special characters |
| 79 | + # Use quote(..., safe="") instead of quote_plus() for URL userinfo section |
| 80 | + db_user_encoded = quote(db_user, safe="") |
| 81 | + db_pass_encoded = quote(db_pass, safe="") |
| 82 | + |
| 83 | + # Use psycopg (sync) for Alembic migrations |
| 84 | + return f"postgresql+psycopg://{db_user_encoded}:{db_pass_encoded}@{db_host}:{db_port}/{db_name}" |
| 85 | + |
| 86 | + |
| 87 | +# this is the Alembic Config object, which provides |
| 88 | +# access to the values within the .ini file in use. |
| 89 | +config = context.config |
| 90 | + |
| 91 | +# Interpret the config file for Python logging. |
| 92 | +# This line sets up loggers basically. |
| 93 | +if config.config_file_name is not None: |
| 94 | + fileConfig(config.config_file_name) |
| 95 | + |
| 96 | +target_metadata = Base.metadata |
| 97 | + |
| 98 | +# other values from the config, defined by the needs of env.py, |
| 99 | +# can be acquired: |
| 100 | +# my_important_option = config.get_main_option("my_important_option") |
| 101 | +# ... etc. |
| 102 | + |
| 103 | + |
| 104 | +def run_migrations_offline() -> None: |
| 105 | + """Run migrations in 'offline' mode. |
| 106 | +
|
| 107 | + This configures the context with just a URL |
| 108 | + and not an Engine, though an Engine is acceptable |
| 109 | + here as well. By skipping the Engine creation |
| 110 | + we don't even need a DBAPI to be available. |
| 111 | +
|
| 112 | + Calls to context.execute() here emit the given string to the |
| 113 | + script output. |
| 114 | +
|
| 115 | + """ |
| 116 | + # Get URL from environment variables |
| 117 | + url = get_sync_database_url() |
| 118 | + context.configure( |
| 119 | + url=url, |
| 120 | + target_metadata=target_metadata, |
| 121 | + literal_binds=True, |
| 122 | + dialect_opts={"paramstyle": "named"}, |
| 123 | + ) |
| 124 | + |
| 125 | + with context.begin_transaction(): |
| 126 | + context.run_migrations() |
| 127 | + |
| 128 | + |
| 129 | +def run_migrations_online() -> None: |
| 130 | + """Run migrations in 'online' mode. |
| 131 | +
|
| 132 | + In this scenario we need to create an Engine |
| 133 | + and associate a connection with the context. |
| 134 | +
|
| 135 | + """ |
| 136 | + from sqlalchemy import create_engine |
| 137 | + |
| 138 | + # Get URL from environment variables and create engine directly |
| 139 | + url = get_sync_database_url() |
| 140 | + connectable = create_engine(url, poolclass=pool.NullPool) |
| 141 | + |
| 142 | + with connectable.connect() as connection: |
| 143 | + context.configure(connection=connection, target_metadata=target_metadata) |
| 144 | + |
| 145 | + with context.begin_transaction(): |
| 146 | + context.run_migrations() |
| 147 | + |
| 148 | + |
| 149 | +if context.is_offline_mode(): |
| 150 | + run_migrations_offline() |
| 151 | +else: |
| 152 | + run_migrations_online() |
0 commit comments