示例工程 36-sqlalchemy-databases
36-sqlalchemy-databases/03-n-plus-one/n_plus_one.py
"""用 SQL 语句计数证明 N+1,并用 join 修复。"""
from __future__ import annotations
from sqlalchemy import (
Column,
Engine,
ForeignKey,
Integer,
MetaData,
String,
Table,
create_engine,
event,
insert,
select,
)
USERS = 5
def build() -> tuple[Engine, Table, Table]:
engine = create_engine("sqlite:///:memory:")
metadata = MetaData()
users = Table(
"users",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String, nullable=False),
)
posts = Table(
"posts",
metadata,
Column("id", Integer, primary_key=True),
Column("user_id", Integer, ForeignKey("users.id"), nullable=False),
Column("title", String, nullable=False),
)
metadata.create_all(engine)
with engine.begin() as connection:
connection.execute(
insert(users),
[{"name": f"user{i}"} for i in range(USERS)],
)
connection.execute(
insert(posts),
[{"user_id": index + 1, "title": f"post{index}"} for index in range(USERS)],
)
return engine, users, posts
def count_statements(engine: Engine, users: Table, posts: Table) -> tuple[int, int, int]:
statements: list[str] = []
def before_cursor_execute(*args: object) -> None:
statements.append("sql")
event.listen(engine, "before_cursor_execute", before_cursor_execute)
try:
with engine.connect() as connection:
user_rows = connection.execute(select(users)).all()
for user in user_rows:
connection.execute(select(posts).where(posts.c.user_id == user.id)).all()
naive = len(statements)
statements.clear()
with engine.connect() as connection:
connection.execute(
select(users.c.name, posts.c.title).join(posts, posts.c.user_id == users.c.id)
).all()
joined = len(statements)
finally:
event.remove(engine, "before_cursor_execute", before_cursor_execute)
return len(user_rows), naive, joined
def main() -> None:
engine, users, posts = build()
users_count, naive, joined = count_statements(engine, users, posts)
print(f"users: {users_count}")
print(f"naive_statements: {naive}")
print(f"joined_statements: {joined}")
if __name__ == "__main__":
main()