SQLAlchemy
SQLAlchemy is the main Python SQL toolkit: a Core expression language that compiles to SQL, and an optional ORM that maps classes to tables. You choose how much of it to use.
Detailed Explanation
Core is select, insert, update, table.c.column, and an Engine that holds a connection pool. You write Python that looks like SQL and still pass bound parameters. The ORM is Session, Mapped, relationship, and identity maps. A session tracks objects, flushes SQL on commit, and expires attributes after commit by default.
The 2.0 style is select(Order).where(Order.id == oid) executed with session.execute or session.scalars. The 1.x session.query(Order) still exists and is in maintenance. New code should use 2.0.
An Engine is created once (create_engine(url, pool_size=..., pool_pre_ping=True)). A Session is created per request or per unit of work. Do not keep a session as a global. Do not share a session across threads. FastAPI dependencies that yield a session are the usual pattern.
The ORM is not magic. order.items can be a lazy query. Accessing it after the session closes raises, or emits a query you did not expect (N+1). selectinload and joinedload are how you ask for related rows up front.
Alembic is the sibling migration tool. Models and the database drift without it. Generate revisions, review the SQL, then apply.
Use Core when you have a report query the ORM would mangle. Use the ORM when you load graphs of objects and mutate them. Use neither when a 10-line sqlite3 script is the whole program.
Code Examples
from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[str] = mapped_column(primary_key=True)
cents: Mapped[int]
engine = create_engine("sqlite+pysqlite:///:memory:")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add(Order(id="11", cents=2500))
session.commit()
row = session.scalars(select(Order).where(Order.id == "11")).one()
print(row.cents) # 2500Common Gotchas
Using a session after close
`DetachedInstanceError` or implicit IO. Keep the session open for the request, or map to a dataclass.
N+1
a loop over `order.items` without a loader option. Watch the SQL log in development.
One global `Session`
threads and requests will leak identity-map state. Create per unit of work.
`create_all` is not migrations
it will not alter existing tables. Use Alembic.