Inkdown
Start writing

Python

4 files·0 subfolders

Shared Workspace

Python
Alembic

SQLAlchemy overview

Shared from "Python" on Inkdown

SQLAlchemy — Overview & Quick Reference


What Is SQLAlchemy?

SQLAlchemy is two tools in one:

Plain text

Most FastAPI apps use the ORM layer. Core runs underneath it silently. Think: Core = engine, ORM = steering wheel.


Project Structure

Plain text
Basics
sqlalchemy - fastapi
SQLAlchemy overview

Engine & Session

Engine = the one connection to your DB. Created once, lives for the app's lifetime.
Session = a "unit of work" per request. Like a shopping cart — you stage changes, then commit.

Python

expire_on_commit=False — without this, SQLAlchemy clears object data after commit. In async FastAPI, your response serializer would crash trying to read cleared attributes.


Defining Models

Python
Python
Two-Layer Mental Model
Plain text

Relationships

One-to-Many (most common)

One user → many posts. Use back_populates to create a two-way link.

Python
Many-to-Many (association table)
Python
One-to-One
Python
Lazy vs Eager Loading (critical in async)

In async SQLAlchemy, accessing user.posts without eager loading raises MissingGreenlet. Always explicitly load relationships.

Python

Pydantic Schemas vs SQLAlchemy Models

These are two different things. Don't confuse them.

SQLAlchemy ModelPydantic Schema
Lives inmodels/schemas/
PurposeTalks to DBValidates HTTP data
Inherits fromBaseBaseModel
Python

from_attributes = True lets Pydantic read SQLAlchemy model attributes instead of expecting a plain dict.


flush vs commit vs rollback

Plain text
The Google Doc Analogy
  • flush = typing on screen (not saved yet, browser crash = gone)
  • commit = clicking Save (permanent)
When to Use What
SituationUse
Need auto-generated ID to create a related objectflush() first, then continue
End of a complete operation, everything succeededcommit()
Something went wrongrollback()
Need server-set values (created_at, id) after flush/commitrefresh(obj)
The Decision Rule
Plain text
Example: flush in action
Python

CRUD Operations (Async)

Python

Advanced Queries

Python

Production Patterns

Reusable Timestamp Mixin
Python
Soft Deletes
Python
Repository Pattern
Python

Common Gotchas

GotchaFix
Forgetting await on DB callsEvery DB call is async — always await db.execute(...)
Accessing user.posts in async without eager loadingUse selectinload or joinedload
N+1 query problem (looping + accessing relationships)Eager load everything upfront in one query
Sharing one session across concurrent requestsget_db creates one session per request — don't share
Alembic not detecting a new modelImport all models in alembic/env.py