40 lines
947 B
Python
40 lines
947 B
Python
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
|
|
|
from app.config import settings
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
connect_args = {}
|
|
if settings.database_url.startswith("sqlite"):
|
|
connect_args = {"check_same_thread": False, "timeout": 30}
|
|
|
|
engine = create_engine(
|
|
settings.database_url,
|
|
connect_args=connect_args,
|
|
pool_pre_ping=True,
|
|
)
|
|
|
|
if settings.database_url.startswith("sqlite"):
|
|
|
|
@event.listens_for(engine, "connect")
|
|
def _sqlite_pragmas(dbapi_connection, _connection_record):
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA journal_mode=WAL")
|
|
cursor.execute("PRAGMA foreign_keys=ON")
|
|
cursor.close()
|
|
|
|
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|