init commit
This commit is contained in:
87
migrations/env.py
Normal file
87
migrations/env.py
Normal file
@@ -0,0 +1,87 @@
|
||||
# migrations/env.py
|
||||
import os
|
||||
from logging.config import fileConfig
|
||||
from dotenv import load_dotenv
|
||||
from alembic import context
|
||||
from sqlalchemy import create_engine, pool
|
||||
|
||||
# 1) Берём Base из session.py
|
||||
from app.db.session import Base
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# 2) Импортируем сборщик моделей, чтобы metadata увидело всё
|
||||
import app.db.base # noqa: F401
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def build_sync_url() -> str:
|
||||
"""
|
||||
Возвращает sync-URL для Alembic.
|
||||
Приоритет:
|
||||
1) DATABASE_URL_SYNC (полная строка)
|
||||
2) Конструктор из DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD
|
||||
"""
|
||||
env_url = os.getenv("DATABASE_URL_SYNC")
|
||||
if env_url and "://" in env_url:
|
||||
return env_url
|
||||
|
||||
host = os.getenv("DB_HOST")
|
||||
port = os.getenv("DB_PORT", "3306")
|
||||
name = os.getenv("DB_NAME")
|
||||
user = os.getenv("DB_USER")
|
||||
pwd = os.getenv("DB_PASSWORD")
|
||||
|
||||
if host and name and user is not None and pwd is not None:
|
||||
# ВАЖНО: для Alembic нужна sync-строка с PyMySQL
|
||||
return f"mariadb+pymysql://{user}:{pwd}@{host}:{port}/{name}"
|
||||
|
||||
raise RuntimeError(
|
||||
"No valid sync DB URL. Set DATABASE_URL_SYNC or DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD."
|
||||
)
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
url = build_sync_url()
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "pyformat"},
|
||||
compare_type=True,
|
||||
compare_server_default=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
url = build_sync_url()
|
||||
|
||||
connectable = create_engine(
|
||||
url,
|
||||
future=True,
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
compare_type=True,
|
||||
compare_server_default=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