Spaces:
Sleeping
Sleeping
| """Alembic env — URL lấy từ env `DATABASE_URL`, metadata từ `app.db`. | |
| Repo KHÔNG cài package (quy ước CLAUDE.md): phải tự đẩy gốc repo vào sys.path | |
| trước khi import `app.db`. `app.db` cố ý không import pooltool/poolcoach_rl — | |
| lệnh migrate không được kéo 40s JIT vào. | |
| """ | |
| import os | |
| import sys | |
| from logging.config import fileConfig | |
| from pathlib import Path | |
| from sqlalchemy import engine_from_config | |
| from sqlalchemy import pool | |
| from alembic import context | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from app.db import Base # noqa: E402 | |
| config = context.config | |
| if config.config_file_name is not None: | |
| fileConfig(config.config_file_name) | |
| # DATABASE_URL đè lên alembic.ini (ini để trống — không hardcode DSN vào git). | |
| _env_url = os.environ.get("DATABASE_URL") | |
| if _env_url: | |
| # escape %: ConfigParser của alembic hiểu % là interpolation | |
| config.set_main_option("sqlalchemy.url", _env_url.replace("%", "%%")) | |
| elif not config.get_main_option("sqlalchemy.url"): | |
| raise SystemExit( | |
| "Thiếu DATABASE_URL — set env rồi chạy lại, ví dụ:\n" | |
| " set DATABASE_URL=postgresql+psycopg://poolcoach:poolcoach@localhost:5432/poolcoach" | |
| ) | |
| target_metadata = Base.metadata | |
| def run_migrations_offline() -> None: | |
| """Run migrations in 'offline' mode.""" | |
| url = config.get_main_option("sqlalchemy.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: | |
| """Run migrations in 'online' mode.""" | |
| 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 | |
| ) | |
| with context.begin_transaction(): | |
| context.run_migrations() | |
| if context.is_offline_mode(): | |
| run_migrations_offline() | |
| else: | |
| run_migrations_online() | |