# 36 · 数据库与 SQLAlchemy

> 学完这章，你能选 Core 还是 ORM，并识别 N+1、事务边界、连接池耗尽三大类问题。

## 本章目标

- [ ] 能区分 SQLAlchemy Core 与 ORM 的职责
- [ ] 能用 `Engine`/`Connection`/`begin()` 管理事务
- [ ] 能用 `select`/`insert`/`update` 构造参数化 SQL
- [ ] 能定义 ORM 模型与一对多关系，用 `selectinload` 预加载
- [ ] 能用 SQL 语句计数复现/修复 N+1
- [ ] 能诊断 `DetachedInstanceError`、连接池超时、批量插入低效

## 前置知识

- 第 31 章（sqlite3/事务/锁）、第 33/34 章（数据形状）、第 29 章（测试）
- 基本 SQL（SELECT/JOIN/事务）

## 从你熟悉的语言出发

| 概念 | Go | Java | Rust | Python |
| --- | --- | --- | --- | --- |
| SQL 构造 | 手写/sqlx | JPA Criteria | diesel | SQLAlchemy Core |
| ORM | GORM | Hibernate | SeaORM | SQLAlchemy ORM |
| 事务 | `BeginTx` | `@Transactional` | `transaction` | `engine.begin()`/`Session` |
| 连接池 | `database/sql` | HikariCP | r2d2 | `QueuePool` |
| 预加载 | `Preload` | `join fetch` | `with` | `selectinload` |
| 身份映射 | 手写 | 一级缓存 | 手写 | `Session` identity map |

**类比一：Core 像「类型安全的 SQL 构造器」，ORM 像「把表映射成对象」。** Core 不隐藏 SQL；ORM 管理对象生命周期、关系与单位工作（Unit of Work）。

**类比二：`Session` 像「一级缓存 + 工作单元」。** 同一主键只查一次，修改先累积，`commit` 时统一 flush；关闭后对象 detached。

## 正文

### 36.1 Core 与 ORM 的分工

| 场景 | 推荐 |
| --- | --- |
| 复杂报表/批量/明确 SQL | Core |
| 领域模型/关系导航/CRUD | ORM |
| 混合 | ORM 为主，热点查询用 Core/`text` |

Core 的 `select(users.c.name).where(...)` 生成参数化 SQL；ORM 的 `select(User)` 返回对象并维护 identity map。

### 36.2 Engine、连接与事务

```python
engine = create_engine("sqlite:///:memory:")
with engine.begin() as conn:
    conn.execute(insert(table), rows)
```

- `Engine` 是连接池 + 方言，不是连接；不要长期持有 `Connection`。
- `engine.begin()`：开事务、成功提交、异常回滚、归还连接。
- `engine.connect()`：只借连接，DML 后要自己 `commit()`。
- `Session`：ORM 的工作单元，`with Session(engine)` 关闭；`commit`/`rollback` 明确。
- SQLite 内存库用 `SingletonThreadPool`；文件库才用 `QueuePool`（见 05）。

### 36.3 Core 表达式

```python
stmt = select(users.c.name, users.c.age).where(users.c.age >= 30).order_by(users.c.name)
rows = conn.execute(stmt).all()
```

- 列引用 `table.c.column`；条件用 Python 运算符重载。
- 参数绑定自动完成，不要 f-string 拼 SQL。
- `insert(table)` 可传单行 dict 或多行 list（executemany）。
- `update(table).where(...).values(...)`、`delete(table).where(...)`。

### 36.4 ORM 模型与关系

```python
class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String)
    posts: Mapped[list[Post]] = relationship(back_populates="author")
```

- `DeclarativeBase` + `Mapped`/`mapped_column` 是 2.0 风格。
- `relationship` 默认懒加载；`back_populates` 双向同步。
- `session.add(...)` 后对象在 identity map；`flush` 发 SQL，`commit` 提交。
- `expire_on_commit=True`（默认）会让 commit 后属性过期，访问时重新查。

### 36.5 N+1 与预加载

```python
select(User).options(selectinload(User.posts))
```

- 不预加载：1 条查用户 + N 条查 posts = N+1。
- `selectinload`：额外 1 条 `IN (...)` 查 posts；`joinedload`：JOIN 一次查完（可能放大行数）。
- 用 `before_cursor_execute` 事件计数，别靠感觉。
- 列表页/API 序列化最容易触发 N+1。

### 36.6 Session 生命周期与 detached

- `Session` 关闭后对象 detached；访问未加载关系抛 `DetachedInstanceError`。
- 在 `Session` 内完成序列化/预加载，或 `expire_on_commit=False` + 显式加载。
- identity map：同一 session 内同主键返回同一对象；跨 session 不共享。
- `flush` ≠ `commit`：flush 发 SQL 但可回滚。

### 36.7 连接池

- `pool_size` 常驻连接数，`max_overflow` 临时上限，`pool_timeout` 等待上限。
- 泄漏连接（未 close/rollback）会耗尽池；`pool_timeout` 到点抛 `TimeoutError`。
- `pool_pre_ping` 检查失效连接；`pool_recycle` 定期回收。
- 用 `with engine.connect()`/`engine.begin()`/`Session` 保证归还。

### 36.8 批量写入

- 逐条 `execute(insert(...))` 是 N 条语句；`execute(insert(table), rows)` 是 1 条 executemany。
- 批量包在事务里；失败整体回滚。
- ORM 批量：`session.execute(insert(Model), rows)`、`session.add_all` + 单次 commit。
- 超大导入分批（如每 1000 行 commit），避免长事务/内存峰值。

## 报错现场

Session 关闭后访问懒加载关系：

```text
Traceback (most recent call last):
  ...
  File "/…/sqlalchemy/orm/strategies.py", line 957, in _load_for_state
    raise orm_exc.DetachedInstanceError(
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <User at 0x...> is not bound to a Session;
lazy load operation of attribute 'posts' cannot proceed
```

逐行读：

- 对象曾在 `Session` 中加载，但 session 已关闭 → detached。
- 访问 `user.posts` 触发懒加载，没有 session 可用。
- 修法：在 session 内 `selectinload`/访问关系，或 `expire_on_commit=False` 并预加载，或重新 attach。
- 另一个常见错误是 `OperationalError: no such table`：忘了 `Base.metadata.create_all(engine)` 或连错数据库。

## 反直觉差异：identity map 让查询不查库，懒加载在循环里爆 N+1

**你的直觉**：每次 `session.get(User, 1)` 都会查数据库；ORM 会自动优化关系加载。

**实际行为**：

1. 同一 session 内，identity map 命中直接返回对象，不再发 SQL（可能读到旧值）。
2. 关系默认懒加载；循环访问 `user.posts` 会 1+N 条 SQL。
3. `flush` 发 SQL 但未提交；`commit` 才持久化，`expire_on_commit` 还会让属性过期。
4. 连接池不是无限；不归还连接会让后续请求超时。

**为什么这样设计**：identity map/Unit of Work 保证对象一致性与事务性；懒加载让简单查询不必一次拉全图，但把成本转移到访问时。ORM 不猜你的访问模式，所以预加载要显式。

**正确写法**：

- 列表/序列化前用 `selectinload`/`joinedload` 明确加载关系。
- 用 SQL 计数/`echo=True` 验证语句数，不靠猜。
- 事务边界清晰：一个请求一个 session；异常回滚。
- 批量写用 executemany/分批；监控连接池。

## 性能与复杂度

| 场景（3.12.9 + SQLAlchemy 2.1.9） | 结果 | 说明 |
| --- | --- | --- |
| 5 用户 + 逐个查 posts | 6 条 SQL | N+1 |
| 同样数据 join | 1 条 SQL | 修复后 |
| 200 行逐条 insert | 200 条语句 | 循环 execute |
| 200 行 executemany | 1 条语句 | 批量 |
| 池大小 1 + 借第二次 | 0.1s 后超时 | `pool_timeout` |
| 事务中途异常 | 余额不变 | `engine.begin` 回滚 |

ORM 的性能问题通常不是「ORM 慢」，而是查询次数/数据量；先数 SQL，再谈优化。

## 示例索引

| 目录 | 演示什么 | 预期看到 |
| --- | --- | --- |
| `examples/36-sqlalchemy-databases/01-core-expressions/` | Core 查询 | Ada/Cara |
| `examples/36-sqlalchemy-databases/02-orm-relationships/` | 一对多 + selectinload | Ada→[A1,A2] |
| `examples/36-sqlalchemy-databases/03-n-plus-one/` | N+1 计数 | 6 vs 1 |
| `examples/36-sqlalchemy-databases/04-transaction-rollback/` | 事务回滚 | `[90,60]` 两次 |
| `examples/36-sqlalchemy-databases/05-pool-exhaustion/` | 连接池超时 | `timed_out: True` |
| `examples/36-sqlalchemy-databases/06-bulk-insert/` | 批量插入 | 200 vs 1 条语句 |

## 练习题

1. 用 Core 查询满足年龄条件的名字。见 `exercises/36/01-core-select/`。
2. 定义 ORM 一对多并用 `selectinload` 加载。见 `exercises/36/02-orm-load/`。
3. 实现事务回滚的转账。见 `exercises/36/03-rollback/`。
4. 统计逐条与批量插入的语句数。见 `exercises/36/04-bulk-count/`。

<details><summary>参考答案</summary>

1. `select(users.c.name).where(users.c.age >= minimum).order_by(...)`。
2. `Mapped`/`relationship` + `select(User).options(selectinload(User.posts))`。
3. `with engine.begin()`，失败抛异常；余额恢复。
4. 事件计数：逐条 N、批量 1。

</details>

## 章末自检

1. Core 与 ORM 各适合什么？
2. `engine.begin()` 与 `engine.connect()` 的区别？
3. `flush` 与 `commit` 的区别？
4. 什么是 N+1？`selectinload`/`joinedload` 怎么修？
5. identity map 会带来什么影响？
6. `DetachedInstanceError` 的原因与修法？
7. 连接池耗尽的常见原因？如何监控？
8. 批量插入为什么快？要注意什么？

<details><summary>答案要点</summary>

1. 复杂 SQL/批量 vs 领域模型/关系。
2. 自动事务/归还 vs 手动 commit。
3. flush 发 SQL，commit 持久化；都可回滚（commit 前）。
4. 1+N 查询；预加载（IN/JOIN）。
5. 同 session 同主键复用，可能读旧值。
6. session 关闭后懒加载；在 session 内加载/重新 attach。
7. 未 close/rollback/长事务；看 `pool.checkedout()`/超时。
8. executemany 减少语句/往返；事务/分批/内存。

</details>

## 延伸阅读

- SQLAlchemy 文档：*Unified Tutorial*、*Core*、*ORM*、*Session Basics*、*Relationship Loading Techniques*
- SQLAlchemy 文档：*Connection Pooling*、*Transactions*
- Python 文档：`sqlite3`（第 31 章，底层对照）
- SQLite 文档：*Write-Ahead Logging*、*Transaction*
