实现说明
底层就是函数 page_by_cursor。
List、Optional、Tuple 是从 sqlite3 借来的全部符号——耦合显式而窄。代码不会带着坏状态静默继续,守卫一命中就抛 ValueError。
使用要点
- 依赖外部包
sqlite3,运行前需要先安装。 - 守卫
limit <= 0 or limit > 100满足时靠提前的raise短路流程。 page_by_cursor是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
前置条件不成立会发生什么?
在真正开工之前就会抛出 ValueError(守卫:limit <= 0 or limit > 100)——请在调用点处理,或有意向上传播。
有第三方依赖吗?
sqlite3——运行前用包管理器装上。
签名一览:def page_by_cursor( connection: sqlite3.Connection, after_id: Optional[int], limit: int, ) -> Tuple[List[Tu…
核心语句
if after_id is None:
rows = connection.execute(
"SELECT id, name FROM items ORDER BY id ASC LIMIT ?", (limit,)
).fetchall()
def page_by_cursor(
connection: sqlite3.Connection,
after_id: Optional[int],
limit: int,
) -> Tuple[List[Tuple[int, str]], Optional[int]]:
代码示例
import sqlite3
from typing import List, Optional, Tuple
def page_by_cursor(
connection: sqlite3.Connection,
after_id: Optional[int],
limit: int,
) -> Tuple[List[Tuple[int, str]], Optional[int]]:
if limit <= 0 or limit > 100:
raise ValueError("limit must be between 1 and 100")
if after_id is None:
rows = connection.execute(
"SELECT id, name FROM items ORDER BY id ASC LIMIT ?", (limit,)
).fetchall()
else:
rows = connection.execute(
"SELECT id, name FROM items WHERE id > ? ORDER BY id ASC LIMIT ?",
(after_id, limit),
).fetchall()
next_cursor = rows[-1][0] if len(rows) == limit else None
return rows, next_cursor