Inkdown
Start writing

Study

70 files·12 subfolders

Shared Workspace

Study
AI eng

SQLAlchemy overview

Shared from "Study" 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
basic-ques
core
Revision w/ Whiteboard
CN Basics - 1
CN Basics - 2
DNS
Event loop
programming-language-concepts.md
zero-language-explanation.md
DB
Quick
databases-deep-dive.md
01-introduction.md
02-relational-databases.md
03-database-design.md
04-indexing.md
05-transactions-acid.md
06-nosql-databases.md
07-query-optimization.md
08-replication-ha.md
09-sharding-partitioning.md
10-caching-strategies.md
11-cap-theorem.md
12-connection-pooling.md
13-backup-recovery.md
14-monitoring.md
15-database-selection.md
README.md
JS
core topics
Event loop
Merlin Backend
01-Orchestration.md
02-DeepResearch.md
03-Search.md
04-Scraping.md
05-Streaming.md
06-MultiProviderLLM.md
07-MemoryAndContext.md
08-ErrorHandling.md
09-RateLimiting.md
10-TaskQueue.md
11-SecurityAndAuth.md
Orchestration-2nd-draft
Mobile
Build Alternative
Bundling
metro-bundler-deep-dive.md
OpenAI Agents Python
00_OVERVIEW.md
01_AGENT_SYSTEM.md
02_RUNNER_SYSTEM.md
03_TOOL_SYSTEM.md
04_ITEMS_SYSTEM.md
05_GUARDRAILS.md
06_HANDOFFS.md
07_MEMORY_SESSIONS.md
08_MODEL_PROVIDERS.md
09_SANDBOX_SYSTEM.md
10_TRACING.md
11_RUN_STATE.md
12_CONTEXT.md
13_LIFECYCLE_HOOKS.md
14_CONFIGURATION.md
15_ERROR_HANDLING.md
16_STREAMING.md
17_EXTENSIONS.md
18_MCP_INTEGRATION.md
19_BEST_PRACTICES.md
20_ARCHITECTURE_PATTERNS.md
opencode-study
context-handling
core
Python
Alembic
Basics
sqlalchemy - fastapi
SQLAlchemy overview
tweets
system_design_for_agentic_apps.md
Agent Loop

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