66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
"""Alembic: синхронный движок SQLAlchemy + psycopg3 (отдельно от asyncpg в рантайме)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from logging.config import fileConfig
|
|
from pathlib import Path
|
|
|
|
from alembic import context
|
|
from dotenv import load_dotenv
|
|
from sqlalchemy import create_engine, pool
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
load_dotenv(ROOT / ".env")
|
|
|
|
config = context.config
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
target_metadata = None
|
|
|
|
|
|
def _ensure_psycopg_client_encoding(url: str) -> str:
|
|
"""Иначе psycopg3 при SQL_ASCII на сервере отдаёт version() как bytes → падает SQLAlchemy re.match."""
|
|
if "+psycopg" not in url or "client_encoding=" in url:
|
|
return url
|
|
join = "&" if "?" in url else "?"
|
|
return f"{url}{join}client_encoding=utf8"
|
|
|
|
|
|
def get_sync_url() -> str:
|
|
url = os.environ.get("DATABASE_URL", "").strip()
|
|
if not url:
|
|
raise RuntimeError("Задай DATABASE_URL для alembic upgrade")
|
|
if url.startswith("postgres://"):
|
|
url = url.replace("postgres://", "postgresql://", 1)
|
|
if url.startswith("postgresql://") and "+psycopg" not in url and "+asyncpg" not in url:
|
|
url = url.replace("postgresql://", "postgresql+psycopg://", 1)
|
|
if "+asyncpg" in url:
|
|
url = url.replace("+asyncpg", "+psycopg")
|
|
return _ensure_psycopg_client_encoding(url)
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
context.configure(
|
|
url=get_sync_url(),
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
connectable = create_engine(get_sync_url(), poolclass=pool.NullPool)
|
|
with connectable.connect() as connection:
|
|
context.configure(connection=connection)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|