Initial commit
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
Database engine/session management.
|
||||
|
||||
Uses SQLAlchemy so the storage backend is a config change, not a code
|
||||
change. Today DB_URL points at a local SQLite file. When you're ready
|
||||
to move to the MariaDB LXC, set DB_URL in .env to something like:
|
||||
|
||||
mysql+pymysql://user:[email protected]:3306/order_manager
|
||||
|
||||
and install PyMySQL (pip install pymysql). Nothing else in the app
|
||||
needs to change.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
|
||||
from app import config
|
||||
from app.models import Base
|
||||
|
||||
_engine = None
|
||||
_SessionLocal = None
|
||||
|
||||
|
||||
def get_engine():
|
||||
global _engine
|
||||
if _engine is None:
|
||||
db_url = config.get("DB_URL", config.DEFAULT_DB_URL)
|
||||
connect_args = {}
|
||||
if db_url.startswith("sqlite"):
|
||||
# allow use across the QThread worker and the UI thread
|
||||
connect_args = {"check_same_thread": False}
|
||||
_engine = create_engine(db_url, connect_args=connect_args, future=True)
|
||||
return _engine
|
||||
|
||||
|
||||
def get_session_factory():
|
||||
global _SessionLocal
|
||||
if _SessionLocal is None:
|
||||
_SessionLocal = sessionmaker(bind=get_engine(), future=True, expire_on_commit=False)
|
||||
return _SessionLocal
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
"""Create tables that don't exist yet. Safe to call every startup."""
|
||||
Base.metadata.create_all(get_engine())
|
||||
|
||||
|
||||
def get_session() -> Session:
|
||||
return get_session_factory()()
|
||||
Reference in New Issue
Block a user