45 lines
1.1 KiB
Python
45 lines
1.1 KiB
Python
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from app.config import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
# SQLite-specific configuration
|
|
connect_args = {"check_same_thread": False}
|
|
|
|
engine = create_engine(
|
|
settings.database_url,
|
|
connect_args=connect_args,
|
|
poolclass=StaticPool,
|
|
echo=False,
|
|
)
|
|
|
|
# Enable WAL mode for better concurrent access
|
|
@event.listens_for(engine, "connect")
|
|
def set_sqlite_pragma(dbapi_connection, connection_record):
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA journal_mode=WAL")
|
|
cursor.execute("PRAGMA synchronous=NORMAL")
|
|
cursor.execute("PRAGMA foreign_keys=ON")
|
|
cursor.close()
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db():
|
|
"""Create all tables."""
|
|
from app.models import species, image, job, api_key, export, cached_stats # noqa
|
|
Base.metadata.create_all(bind=engine)
|