35 lines
808 B
Python
35 lines
808 B
Python
"""Database connection module"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base, Mapped
|
|
from typing import Generator
|
|
|
|
from luxx.config import config
|
|
|
|
|
|
# Create database engine
|
|
engine = create_engine(
|
|
config.database_url,
|
|
connect_args={"check_same_thread": False} if "sqlite" in config.database_url else {},
|
|
echo=config.debug
|
|
)
|
|
|
|
# Create session factory
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Create base class
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db() -> Generator:
|
|
"""Dependency to get database session"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db() -> None:
|
|
"""Initialize database, create all tables"""
|
|
Base.metadata.create_all(bind=engine)
|