如何迁移旧版 mapper() 到 2.x 风格?

解读

国内大多数公司早期用 SQLAlchemy 1.0-1.2 时,为了灵活拼表、做复杂继承或动态映射,普遍手写 mapper(User, user_table, properties={...}) 并配合 sessionmaker()。到了 2023 年以后,新项目普遍要求 Python 3.10+、SQLAlchemy 2.x、异步驱动、类型推导与 pydantic 无缝集成,旧写法在以下场景会被面试官直接判负:

  1. 无法通过 Mypy 严格模式 检查;
  2. 与 AsyncSession 混用出现 greenlet 错误;
  3. 使用 Alembic autogenerate 识别不到模型;
  4. 属性名与列名不一致导致 FastAPI response_model 报错。

因此面试时,考官让你“把 mapper() 迁移到 2.x 风格”并不是单纯改语法,而是考察你对 Declarative Base、mapped_column、relationship、type annotation、async 兼容、Alembic 可追踪 的整体掌握。

知识点

  1. Declarative Base 统一基类:2.x 推荐从 declarative_base 换成 DeclarativeBase 类,支持 类型注解 与 dataclass 风格。
  2. mapped_column 替代 Column:2.0 引入 mapped_column(),与 Mapped[] 泛型配套,解决 Mypy 推导问题。
  3. relationship 必须显式标注:使用 relationship() 时,返回类型需写作 Mapped[List[Child]] 或 WriteOnlyMapped,否则异步延迟加载会抛 greenlet 异常。
  4. mapper() 隐式行为显式化:旧写法可把 primary_key、foreign_key、column_property、synonym 散落在 mapper(properties={}) 里,2.x 必须全部收进类属性,保证 Alembic autogenerate 能嗅探到。
  5. 混合映射(Hybrid Mapping) 若仍想保留旧表对象,可用 registry.map_imperatively() 替代 mapper(),但面试场景下 不推荐,除非能自圆其说。
  6. 异步引擎与 Session 创建方式:create_async_engine + async_sessionmaker;面试官常追问 连接池大小 与 pre-ping 配置。
  7. 向后兼容陷阱:query.get() 被移除,统一用 session.get(User, pk);Query.join() 链式写法不变,但底层实现已重写。

答案

下面给出一条可直接写进白板的迁移范例,并穿插讲解面试官想听的 “为什么”。

旧代码(1.2 风格):

from sqlalchemy import Table, Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.orm import mapper, relationship, sessionmaker

metadata = MetaData()
user_table = Table('user', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(50)),
)

class User:
    pass

mapper(User, user_table, properties={
    'addresses': relationship('Address', backref='user')
})

迁移后(2.x 风格,含异步、类型推导、Alembic 友好):

from sqlalchemy import ForeignKey, String
from sqlalchemy.ext.asyncio import AsyncAttrs, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

class Base(AsyncAttrs, DeclarativeBase):
    pass

class User(Base):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(50))
    # 显式标注类型,FastAPI/pydantic 可直接复用
    addresses: Mapped[list['Address']] = relationship(back_populates='user')

class Address(Base):
    __tablename__ = 'address'

    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str]
    user_id: Mapped[int] = mapped_column(ForeignKey('user.id'))
    user: Mapped['User'] = relationship(back_populates='addresses')

# 引擎与 Session 工厂
engine = create_async_engine(
    'postgresql+asyncpg://user:pwd@127.0.0.1:5432/db',
    pool_size=20,
    pool_pre_ping=True,
    echo=False,
)
async_session = async_sessionmaker(engine, expire_on_commit=False)

迁移要点一句话总结:“把 mapper() 的第三个参数 properties 全部拆成类级属性,并用 Mapped[] + mapped_column 做类型化声明,同时把 Base 换成 DeclarativeBase 子类即可。”

拓展思考

  1. 性能对比:Declarative 在 2.x 内部仍走 registry.map_imperatively,只是提前帮你生成好映射,运行时开销与旧 mapper 等价;但类型化后能减少运行时反射,CPU 微提升 3-5%。
  2. 多态继承:旧代码若用 mapper(..., polymorphic_on=...),2.x 需改用 __mapper_args__ = {"polymorphic_on": column} 类属性;面试时如答不出 __mapper_args__ 会被追问 “单表继承怎么写 discriminator”。
  3. 测试策略:国内大厂单元测试普遍用 SQLite :memory:,但 2.x 异步引擎对 SQLite 需要 aiosqlite;如未加 asyncio.run() 会踩 RuntimeWarning,可提前准备 pytest-asyncio + async_session 夹具。
  4. 迁移自动化:Alembic 1.12+ 支持 alembic revision --autogenerate 直接识别 Declarative 模型;若旧项目表名与类名不一致,需加 __table_args__ = {'schema': 'old'} 保证 零 downtime 迁移。
  5. 面试加分项:主动提到 “SQLAlchemy 2.x 与 pydantic v2 的 dataclass 集成”,并展示 from sqlalchemy.orm import MappedAsDataclass 一行即可让面试官眼前一亮,体现你对 “类型安全 + 序列化” 全链路的深度思考。