2024-12-13 16:45:21 +03:00
|
|
|
from app.src.config import PG_HOST, PG_PORT, PG_USER, PG_PASSWORD, PG_DB
|
2024-12-12 22:12:00 +03:00
|
|
|
from pathlib import Path
|
2024-12-13 16:45:21 +03:00
|
|
|
from starlette.requests import Request
|
2024-12-12 22:12:00 +03:00
|
|
|
import asyncpg
|
|
|
|
from asyncpg_trek import plan, execute, Direction
|
|
|
|
from asyncpg_trek.asyncpg import AsyncpgBackend
|
|
|
|
|
|
|
|
|
|
|
|
DB_URL = f'postgresql://{PG_USER}:{str(PG_PASSWORD)}@{PG_HOST}:{PG_PORT}/{PG_DB}'
|
2024-12-13 16:45:21 +03:00
|
|
|
MIGRATIONS_DIR = Path(__file__).parent.resolve() / "migrations"
|
2024-12-12 22:12:00 +03:00
|
|
|
|
|
|
|
|
2024-12-13 16:45:21 +03:00
|
|
|
async def connect_pg() -> asyncpg.Pool:
|
2024-12-12 22:12:00 +03:00
|
|
|
return await asyncpg.create_pool(DB_URL)
|
|
|
|
|
|
|
|
|
2024-12-13 16:45:21 +03:00
|
|
|
async def get_pg(request: Request) -> asyncpg.Connection:
|
|
|
|
async with request.app.state.pg_pool.acquire() as conn:
|
2024-12-12 22:12:00 +03:00
|
|
|
yield conn
|
|
|
|
|
|
|
|
|
|
|
|
async def migrate(
|
2024-12-13 16:45:21 +03:00
|
|
|
target_revision: str,
|
2024-12-12 22:12:00 +03:00
|
|
|
) -> None:
|
2024-12-13 16:45:21 +03:00
|
|
|
pool = await connect_pg()
|
2024-12-12 22:12:00 +03:00
|
|
|
async with pool.acquire() as conn:
|
|
|
|
backend = AsyncpgBackend(conn)
|
2024-12-13 16:45:21 +03:00
|
|
|
planned = await plan(backend, MIGRATIONS_DIR, target_revision=target_revision, direction=Direction.up)
|
|
|
|
await execute(backend, planned)
|