feat: add SQLAlchemy database layer with get_db dependency
This commit is contained in:
parent
f6587b813e
commit
ca2c9d4e18
22
app/core/database.py
Normal file
22
app/core/database.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||||
|
|
||||||
|
from app.core.config import get_settings
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
|
||||||
|
_connect_args = {"check_same_thread": False} if settings.DATABASE_URL.startswith("sqlite") else {}
|
||||||
|
engine = create_engine(settings.DATABASE_URL, connect_args=_connect_args)
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Session:
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
16
tests/test_database.py
Normal file
16
tests/test_database.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.core.database import Base, get_db
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_db_yields_session():
|
||||||
|
gen = get_db()
|
||||||
|
db = next(gen)
|
||||||
|
assert isinstance(db, Session)
|
||||||
|
try:
|
||||||
|
next(gen)
|
||||||
|
except StopIteration:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_base_has_metadata():
|
||||||
|
assert Base.metadata is not None
|
||||||
Loading…
x
Reference in New Issue
Block a user