71 lines
1.7 KiB
Python
71 lines
1.7 KiB
Python
from logging.config import fileConfig
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from alembic import context
|
|
from sqlalchemy import engine_from_config, pool
|
|
from sqlalchemy.engine import URL
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "app"))
|
|
|
|
from models import Base
|
|
|
|
config = context.config
|
|
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
def get_url() -> str:
|
|
url = URL.create(
|
|
drivername="postgresql+psycopg",
|
|
username=os.environ["DATABASE_USER"],
|
|
password=os.environ["DATABASE_PASSWORD"],
|
|
host=os.environ.get("DATABASE_HOST", "127.0.0.1"),
|
|
port=int(os.environ.get("DATABASE_PORT", "5432")),
|
|
database=os.environ["DATABASE_NAME"],
|
|
)
|
|
|
|
return url.render_as_string(hide_password=False)
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
context.configure(
|
|
url=get_url(),
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
compare_type=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
configuration = config.get_section(config.config_ini_section) or {}
|
|
configuration["sqlalchemy.url"] = get_url()
|
|
|
|
connectable = engine_from_config(
|
|
configuration,
|
|
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()
|