All checks were successful
Build and Deploy Log Center / build-and-deploy (push) Successful in 1m31s
43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
from sqlmodel import SQLModel, create_engine
|
|
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy import text
|
|
import os
|
|
from dotenv import load_dotenv
|
|
|
|
load_dotenv()
|
|
|
|
DB_USER = os.getenv("DB_USER")
|
|
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
|
DB_HOST = os.getenv("DB_HOST")
|
|
DB_PORT = os.getenv("DB_PORT", "5432")
|
|
DB_NAME = os.getenv("DB_NAME")
|
|
|
|
DATABASE_URL = f"postgresql+asyncpg://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
|
|
|
engine = create_async_engine(DATABASE_URL, echo=True, future=True)
|
|
|
|
async def init_db():
|
|
async with engine.begin() as conn:
|
|
# await conn.run_sync(SQLModel.metadata.drop_all)
|
|
await conn.run_sync(SQLModel.metadata.create_all)
|
|
|
|
# Migrate: add new columns to existing repairtask table
|
|
migrations = [
|
|
"ALTER TABLE repairtask ADD COLUMN repair_round INTEGER DEFAULT 1",
|
|
"ALTER TABLE repairtask ADD COLUMN failure_reason TEXT",
|
|
]
|
|
for sql in migrations:
|
|
try:
|
|
await conn.execute(text(sql))
|
|
except Exception:
|
|
pass # Column already exists
|
|
|
|
async def get_session() -> AsyncSession:
|
|
async_session = sessionmaker(
|
|
engine, class_=AsyncSession, expire_on_commit=False
|
|
)
|
|
async with async_session() as session:
|
|
yield session
|