init commit
This commit is contained in:
72
app/migrations/env.py
Normal file
72
app/migrations/env.py
Normal file
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
from alembic import context
|
||||
|
||||
# Сделаем проект импортируемым при запуске alembic из корня
|
||||
sys.path.append(os.getcwd())
|
||||
|
||||
from app.db.base import Base # noqa
|
||||
from app.db import models # noqa: F401 # важно импортировать, чтобы metadata увидела модели
|
||||
|
||||
# Alembic Config
|
||||
config = context.config
|
||||
|
||||
# Логирование из alembic.ini
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def get_url() -> str:
|
||||
"""Берём URL БД из env или собираем из DB_* переменных."""
|
||||
url = os.getenv("DATABASE_URL", "").strip()
|
||||
if url:
|
||||
return url
|
||||
host = os.getenv("DB_HOST", "db")
|
||||
port = os.getenv("DB_PORT", "5432")
|
||||
name = os.getenv("DB_NAME", "tg_poster")
|
||||
user = os.getenv("DB_USER", "postgres")
|
||||
pwd = os.getenv("DB_PASSWORD", "postgres")
|
||||
return f"postgresql+psycopg://{user}:{pwd}@{host}:{port}/{name}"
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Запуск миграций в оффлайн-режиме (генерация SQL)."""
|
||||
url = get_url()
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Запуск миграций в онлайн-режиме с активным соединением."""
|
||||
configuration = config.get_section(config.config_ini_section) or {}
|
||||
# ВАЖНО: используем ключ sqlalchemy.url и prefix="sqlalchemy."
|
||||
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)
|
||||
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