DB sessions
A session is a unit of work — track changes, commit, rollback. One per request.
Code example
db = SessionLocal()
try:
user = User(username='ada')
db.add(user)
db.commit() # writes to DB
db.refresh(user) # loads the new id
except:
db.rollback() # undoes partial changes
finally:
db.close()
How it works
A DB session is a holding area for objects you're working with. When you `db.add(obj)`, the row isn't written yet — it's tracked in memory. `db.commit()` flushes all pending changes to the DB in a single transaction. If anything goes wrong, `db.rollback()` undoes everything since the last commit. The `get_db()` dependency wraps this in try/finally so every request gets a fresh session and the session is always closed, even on exception.
🔍 Where this is used in OpenBenchML
app/database/db.py — SessionLocal() is the session factory. get_db() yields one per request.