Initial public ModelForge release
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from alembic import context
|
||||
from modelforge_api.persistence.models import Base
|
||||
from modelforge_api.settings import get_settings
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
"""Where the migration runs, in order of explicitness.
|
||||
|
||||
1. `-x db_url=...` on the command line
|
||||
2. a URL the caller set programmatically, or in alembic.ini
|
||||
3. MODELFORGE_MIGRATION_DATABASE_URL
|
||||
4. MODELFORGE_DATABASE_URL only outside production
|
||||
|
||||
env.py used to overwrite whatever the caller had set with the settings default
|
||||
unconditionally, so both explicit forms were silently discarded. A bootstrap or upgrade
|
||||
rehearsal aimed at an isolated copy would have migrated the deployment's own database while
|
||||
reporting success against the copy.
|
||||
"""
|
||||
|
||||
supplied = context.get_x_argument(as_dictionary=True).get("db_url")
|
||||
if supplied:
|
||||
return str(supplied)
|
||||
configured = config.get_main_option("sqlalchemy.url", None)
|
||||
if configured:
|
||||
return configured
|
||||
settings = get_settings()
|
||||
if settings.migration_database_url is not None:
|
||||
return settings.migration_database_url.get_secret_value()
|
||||
if settings.env == "production":
|
||||
raise RuntimeError(
|
||||
"production migrations require MODELFORGE_MIGRATION_DATABASE_URL; the API runtime "
|
||||
"credential is intentionally not a migration credential"
|
||||
)
|
||||
return settings.database_url
|
||||
|
||||
|
||||
config.set_main_option("sqlalchemy.url", _database_url())
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=config.get_main_option("sqlalchemy.url"),
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
Reference in New Issue
Block a user