this time using pydantic-settings as a base - removed all os.getenv calls - removed the secret_key default option - reworked database loading, creating tables - prob. something else also but its 4:30 and i have to sleep
53 lines
1.3 KiB
Python
53 lines
1.3 KiB
Python
import logging
|
|
from functools import lru_cache
|
|
|
|
from sqlalchemy import inspect
|
|
from sqlmodel import Session, SQLModel, create_engine
|
|
|
|
from app.services.settings import settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@lru_cache
|
|
def get_engine():
|
|
return create_engine(
|
|
settings.sqlalchemy_database_url, connect_args={"check_same_thread": False}
|
|
)
|
|
|
|
|
|
def create_db_and_tables():
|
|
inspector = inspect(get_engine())
|
|
existing_tables = inspector.get_table_names()
|
|
if not existing_tables:
|
|
SQLModel.metadata.create_all(get_engine())
|
|
from alembic.config import Config
|
|
|
|
from alembic import command
|
|
|
|
alembic_cfg = Config(settings.alembic_config)
|
|
alembic_cfg.set_main_option("sqlalchemy.url", str(get_engine().url))
|
|
alembic_cfg.attributes["sqlalchemy.url"] = settings.sqlalchemy_database_url
|
|
command.stamp(alembic_cfg, "head")
|
|
logger.info("Database created and tables initialized.")
|
|
else:
|
|
logger.info(
|
|
"Database already initialized (%d tables found).", len(existing_tables)
|
|
)
|
|
|
|
|
|
def get_session():
|
|
with Session(get_engine()) as db:
|
|
yield db
|
|
|
|
|
|
def get_db_session():
|
|
return Session(get_engine())
|
|
|
|
|
|
def add_and_refresh(db: Session, obj):
|
|
db.add(obj)
|
|
db.commit()
|
|
db.refresh(obj)
|
|
return obj
|