Python sqlite3 游标分页实战:用 created_at 与 id 避免 OFFSET 位置漂移

10-20 4阅读

文章列表按发布时间倒序显示,用户不断点“下一页”。如果每次都把页码换算成 OFFSET,前面插入或删除一条记录,后面的编号位置就可能变化。更合适的做法往往是记住上页最后一条记录的排序位置,继续取它后面的数据。这就是 keyset pagination,也常被叫作游标分页。

本文用 Python 标准库 sqlite3 实现一个只向后浏览的列表:按 created_at DESC、id DESC 排序,使用参数绑定、联合索引和多取一条记录的方式判断是否还有下一页。重点不是宣传“分页永不重复”,而是把它成立的前提、并发写入的边界和可运行测试讲清楚。

Python sqlite3 游标分页实战:用 created_at 与 id 避免 OFFSET 位置漂移
独立模型生成的概念示意图,不是真实软件截图。卡片编号仅表示记录身份,不对应下文倒序样例的实际数据。

一、先把排序规则变成唯一的位置

只按 created_at 排序不够:同一秒甚至同一微秒都可能有多篇文章。如果下一页只查询 created_at 小于上页时间,同时间戳但尚未显示的记录会被漏掉;如果改成小于等于,又会把上一页的数据带回来。这里用唯一 id 打破时间相同的平局,游标保存完整的二元组 (created_at, id)。

倒序的下一页条件是 (created_at, id) < (?, ?)。比较先看时间,时间相同才比较 id。例如游标是 (1000, 7),(1000, 6) 应当出现,(1000, 8) 不应再次出现。SQLite 从 3.15.0 起支持这种行值比较;官方的滚动窗口例子也解释了为什么较大的 OFFSET 会额外跳过许多记录。见 SQLite 行值与滚动窗口文档。

以下实现约定:created_at 保存 UTC Unix 微秒整数,不允许 NULL;id 唯一;应用在一轮翻页中不修改排序键,也不把已删除记录的身份重新分配给其他记录。普通 INTEGER PRIMARY KEY 并不自动替应用保证“永不复用”,因此这条约束必须纳入数据写入设计。测试时间戳是固定样本,故意每三条使用相同时间。

二、完整实现:pagination.py

代码按 Python 3.10 及以上语法编写,所链接 SQLite 至少为 3.15.0。本次实际验证环境为 Python 3.12.14、SQLite 3.53.1,不代表已经逐一测试所有版本。无需 pip 安装第三方包。将下列内容保存为 pagination.py。

"""Forward-only keyset pagination. Python 3.10+, SQLite 3.15+."""
import sqlite3
from dataclasses import dataclass
from typing import Optional

Cursor = tuple[int, int]  # (created_at: UTC Unix microseconds, id)

FIRST_SQL = """
SELECT id, created_at, title FROM posts
ORDER BY created_at DESC, id DESC
LIMIT ?
"""
NEXT_SQL = """
SELECT id, created_at, title FROM posts
WHERE (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT ?
"""


@dataclass(frozen=True)
class Page:
    items: list[sqlite3.Row]
    next_cursor: Optional[Cursor]
    has_more: bool


def connect(path: str = ":memory:") -> sqlite3.Connection:
    if sqlite3.sqlite_version_info < (3, 15, 0):
        raise RuntimeError("SQLite 3.15.0 or newer is required")
    # Explicit SQLite transaction control, including on Python 3.12+.
    options = {"isolation_level": None}
    if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
        options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
    con = sqlite3.connect(path, **options)
    con.row_factory = sqlite3.Row
    return con


def create_schema(con: sqlite3.Connection) -> None:
    con.executescript("""
        CREATE TABLE posts (
            id INTEGER PRIMARY KEY,
            created_at INTEGER NOT NULL
                CHECK (typeof(created_at) = 'integer'),
            title TEXT NOT NULL
        );
        CREATE INDEX idx_posts_created_id
        ON posts(created_at DESC, id DESC);
    """)


def seed(con: sqlite3.Connection) -> None:
    # Three equal timestamps per group deliberately test tie-breaking.
    base = 1_700_000_000_000_000
    con.executemany(
        "INSERT INTO posts(id, created_at, title) VALUES (?, ?, ?)",
        [(i, base + (i - 1) // 3, f"post-{i}")
         for i in (5, 1, 9, 2, 8, 3, 7, 4, 6)],
    )


def get_page(
    con: sqlite3.Connection,
    page_size: int = 3,
    after: Optional[Cursor] = None,
) -> Page:
    if type(page_size) is not int or not 1 <= page_size <= 100:
        raise ValueError("page_size must be an integer from 1 to 100")
    if after is None:
        rows = con.execute(FIRST_SQL, (page_size + 1,)).fetchall()
    else:
        if (not isinstance(after, tuple) or len(after) != 2
                or any(type(v) is not int or not -(2**63) <= v < 2**63
                       for v in after)):
            raise ValueError("after must contain two signed 64-bit integers")
        rows = con.execute(NEXT_SQL, (*after, page_size + 1)).fetchall()
    items = rows[:page_size]
    has_more = len(rows) > page_size
    next_cursor = None
    if has_more:
        last = items[-1]  # Never use the extra look-ahead row.
        next_cursor = (last["created_at"], last["id"])
    return Page(items, next_cursor, has_more)


def main() -> None:
    con = connect()
    try:
        create_schema(con)
        seed(con)
        after = None
        while True:
            page = get_page(con, page_size=4, after=after)
            print([row["id"] for row in page.items], page.has_more)
            if not page.has_more:
                break
            after = page.next_cursor
        print("SQLite:", sqlite3.sqlite_version)
        for row in con.execute(
            "EXPLAIN QUERY PLAN " + NEXT_SQL,
            (1_700_000_000_000_001, 6, 5),
        ):
            print(row["detail"])
    finally:
        con.close()


if __name__ == "__main__":
    main()

在该文件所在目录运行 python pagination.py。本次实际输出如下,其中前三行是每页的 id 列表与 has_more:

[9, 8, 7, 6] True
[5, 4, 3, 2] True
[1] False
SQLite: 3.53.1
SEARCH posts USING INDEX idx_posts_created_id (created_at<?)

LIMIT 取 page_size + 1 条,只向调用方返回前 page_size 条。多出的那一条仅用来判断 has_more,不能拿来当下一页游标,否则会把它跳过去。next_cursor 取的是本页最后一条已经返回的记录。到达末页时 next_cursor 为 None,调用方应当根据 has_more 停止,而不是把 None 又传进去重新开始第一页。

created_at、id 和 LIMIT 都通过问号占位符绑定,不能用 f-string 拼接用户输入。表名、排序列和排序方向在本例中是固定 SQL;占位符不能替代列名,若要让用户选择排序,应当映射到服务端允许的固定 SQL。参数绑定用法可查 Python sqlite3 官方文档。

connect() 刻意采用显式 SQL 事务控制:isolation_level=None,并在支持 autocommit 参数的 Python 上显式选择 LEGACY_TRANSACTION_CONTROL。这让演示中没有 BEGIN 的查询各自读取当时可见的数据,测试里的 BEGIN/COMMIT 则由代码明确管理;不能把它与 autocommit=False 的连接行为混为一谈。参见 Python 事务控制说明。生产批量写入通常还应使用明确事务,本例 seed() 只是九条演示数据。

三、索引要与查询一起设计,不要只换分页语法

联合索引 idx_posts_created_id 的两列及方向与 ORDER BY 对应。实测 EXPLAIN QUERY PLAN 显示 SEARCH posts USING INDEX idx_posts_created_id (created_at<?),说明这次后续页查询采用了该索引。计划摘要只显示时间范围,并不意味着 SQL 忽略了 id 的条件:同时间戳的正确性仍由完整谓词保障,后面的测试会检验它。

这里没有做大规模性能基准,因此不声称“快多少倍”或“恒定耗时”。查询计划会受数据分布、统计信息和 SQLite 版本影响;计划文本本身也不是稳定接口,不适合写死为业务逻辑判断。可参考 SQLite 联合索引说明与 EXPLAIN QUERY PLAN 文档。

如果真实列表按 tenant_id、status 筛选,第一页和后续页必须使用相同筛选条件,并重新评估以这些等值过滤列开头的索引,而不是无条件照搬本文索引。本文每次只读取 id、created_at、title,避免把正文等大字段一起拖进列表请求。

四、完整测试:test_pagination.py

下面的测试文件与 pagination.py 放在同一目录,执行 python -m unittest -v test_pagination.py。测试不仅检查“能返回三条”,还针对相同时间戳、删除、插入、输入校验以及跨连接快照做断言。

import os
import tempfile
import unittest
from pagination import connect, create_schema, get_page, seed


def ids(page):
    return [row["id"] for row in page.items]


class PaginationTests(unittest.TestCase):
    def setUp(self):
        self.con = connect()
        create_schema(self.con)
        seed(self.con)

    def tearDown(self):
        self.con.close()

    def test_all_page_sizes_no_gaps_or_duplicates(self):
        for size in range(1, 101):
            with self.subTest(size=size):
                seen, cursor = [], None
                while True:
                    page = get_page(self.con, size, cursor)
                    seen.extend(ids(page))
                    if not page.has_more:
                        self.assertIsNone(page.next_cursor)
                        break
                    self.assertEqual(
                        page.next_cursor,
                        (page.items[-1]["created_at"], page.items[-1]["id"]),
                    )
                    cursor = page.next_cursor
                self.assertEqual(seen, list(range(9, 0, -1)))

    def test_empty_and_past_end(self):
        self.assertEqual(ids(get_page(self.con, 3, (0, 0))), [])
        self.con.execute("DELETE FROM posts")
        page = get_page(self.con)
        self.assertEqual(ids(page), [])
        self.assertFalse(page.has_more)
        self.assertIsNone(page.next_cursor)

    def test_invalid_inputs(self):
        for size in (0, -1, 101, True, 2.5, "3"):
            with self.subTest(size=size), self.assertRaises(ValueError):
                get_page(self.con, size)
        for cursor in ((1,), (1, True), ("0 OR 1=1", 1),
                       (2**63, 1), [1, 2]):
            with self.subTest(cursor=cursor), self.assertRaises(ValueError):
                get_page(self.con, after=cursor)

    def test_delete_seen_and_cursor_rows(self):
        first = get_page(self.con, 3)  # 9, 8, 7
        self.con.execute("DELETE FROM posts WHERE id IN (9, 7)")
        self.assertEqual(ids(get_page(self.con, 3, first.next_cursor)),
                         [6, 5, 4])
        offset_rows = self.con.execute(
            "SELECT id FROM posts ORDER BY created_at DESC, id DESC "
            "LIMIT ? OFFSET ?", (3, 3)
        ).fetchall()
        self.assertEqual([row["id"] for row in offset_rows], [4, 3, 2])

    def test_insert_before_cursor_does_not_repeat_seen_rows(self):
        first = get_page(self.con, 3)
        self.con.execute(
            "INSERT INTO posts VALUES (?, ?, ?)",
            (10, 1_700_000_000_000_003, "newest"),
        )
        self.assertEqual(ids(get_page(self.con, 3, first.next_cursor)),
                         [6, 5, 4])
        self.assertEqual(ids(get_page(self.con, 3)), [10, 9, 8])
        offset_rows = self.con.execute(
            "SELECT id FROM posts ORDER BY created_at DESC, id DESC "
            "LIMIT ? OFFSET ?", (3, 3)
        ).fetchall()
        self.assertEqual([row["id"] for row in offset_rows], [7, 6, 5])

    def test_backdated_insert_is_visible_without_snapshot(self):
        first = get_page(self.con, 3)
        self.con.execute(
            "INSERT INTO posts VALUES (?, ?, ?)",
            (10, 1_700_000_000_000_001, "backdated"),
        )
        self.assertEqual(ids(get_page(self.con, 3, first.next_cursor)),
                         [10, 6, 5])

    def test_sort_key_update_can_repeat_an_item(self):
        first = get_page(self.con, 3)
        self.con.execute(
            "UPDATE posts SET created_at = ? WHERE id = ?",
            (1_700_000_000_000_001, 9),
        )
        # This is a documented limitation, not a desired API guarantee.
        self.assertEqual(ids(get_page(self.con, 3, first.next_cursor)),
                         [9, 6, 5])

    def test_parameterized_text_is_data(self):
        title = "x'); DROP TABLE posts; --"
        self.con.execute(
            "INSERT INTO posts VALUES (?, ?, ?)", (10, 2**62, title)
        )
        self.assertEqual(get_page(self.con, 1).items[0]["title"], title)
        self.assertEqual(
            self.con.execute("SELECT count(*) FROM posts").fetchone()[0], 10
        )

    def test_wal_snapshot_across_two_connections(self):
        with tempfile.TemporaryDirectory() as directory:
            path = os.path.join(directory, "snapshot.db")
            reader, writer = connect(path), connect(path)
            try:
                mode = reader.execute("PRAGMA journal_mode=WAL").fetchone()[0]
                self.assertEqual(mode, "wal")
                create_schema(reader)
                seed(reader)
                reader.execute("BEGIN")
                first = get_page(reader, 3)  # Establish the read snapshot.
                writer.execute("BEGIN")
                writer.execute("DELETE FROM posts WHERE id = ?", (6,))
                writer.execute(
                    "INSERT INTO posts VALUES (?, ?, ?)",
                    (10, 1_700_000_000_000_001, "backdated"),
                )
                writer.execute("COMMIT")
                self.assertEqual(ids(get_page(reader, 3, first.next_cursor)),
                                 [6, 5, 4])
                reader.execute("COMMIT")
                self.assertEqual(ids(get_page(reader, 3, first.next_cursor)),
                                 [10, 5, 4])
            finally:
                reader.close()
                writer.close()


if __name__ == "__main__":
    unittest.main(verbosity=2)

本次实际执行 9 项测试全部通过。其中完整遍历测试覆盖了 1 到 100 的每一种页大小,既包括整除记录数的边界,也包括页面容量大于总记录数的情况。无第三方数据库服务,也没有用模拟返回值代替真实 SQLite 查询。

删除测试先读到 9、8、7,再删除 9 和游标记录 7。keyset 仍正确接到 6、5、4;同一时刻使用 OFFSET 3 会得到 4、3、2,漏过 6 和 5。新增测试则在最前面插入 10,keyset 接到 6、5、4,而 OFFSET 3 得到 7、6、5,把已经看过的 7 带了回来。这两个例子说明的是位置偏移问题,不是数据库读取出错。

五、它不是快照:四种变化必须分别理解

  • 在游标之前新增记录:当前向后遍历不会回头读取它。用户刷新第一页才能看到新内容,这是信息流常见的合理行为。

  • 在游标之后回填旧记录:下一次查询可能看到这条新增记录。测试中的 backdated 插入就会让后续页变成 10、6、5,所以 keyset 不等于“固定住首次查询时的集合”。

  • 删除尚未显示的记录:该记录不会凭空被保留下来;删除已显示的记录通常不会造成 OFFSET 那样的位置跳动,但这不意味着能读到所有历史数据。

  • 修改排序键:已经显示的记录若被移到游标后方,可能再次出现;尚未显示的记录若被移到游标前方,也可能被错过。因此稳定键与唯一平局键同样重要。

has_more 也只是本次查询的观察结果。它为 True 后,下一页数据仍可能被全部删除;它为 False 后,仍可能出现新的回填数据。接口不能把这个布尔值解释成对未来数据的承诺。

若导出任务确实要看到同一数据库视图,可以在同一连接中开启读取事务,并把所有分页查询放在该事务内。测试特意在临时文件数据库开启 WAL:读连接 BEGIN 后先执行第一页查询建立快照,写连接随后删除 id=6 并插入 id=10;读事务内下一页仍为 6、5、4,提交读事务后再查则为 10、5、4。这个差别实际验证了“游标边界”和“事务快照”不是一回事。隔离行为见 SQLite Isolation 文档。

不要为了网页用户几分钟后的下一次点击,长期占着数据库读事务。WAL 模式下长时间读事务会影响检查点推进;大型导出应权衡事务时长、资源占用与一致性需求。相关限制见 SQLite WAL 与检查点文档。每个 HTTP 请求重新连接、重新查询,不会因为复用了同一个游标就自动恢复旧快照。

六、接成接口前还要补哪些约束

  • 游标编码:本文直接使用 Python tuple,便于理解和测试。HTTP 接口可以传递带版本号的编码结构,但 Base64 不是加密,也不是防篡改签名;不得把游标当作授权凭证。

  • 绑定查询上下文:同一个游标只能用于同一筛选范围与排序规则。服务端每次都要重新检查用户的数据访问权限,不能让客户端提交的 tenant_id 决定权限。

  • 限制资源:页大小上限设为 100,并拒绝布尔值、负数和超范围整数。真实接口还需要限制游标字符串长度、校验解码格式,并将格式错误转换成明确的客户端错误响应。

  • 不要混用方向:这里两列都是 DESC,所以继续向后用小于号;两列都是 ASC 时才对应大于号。混合升降序不能机械套用同一个二元组比较,必须重新推导条件。

  • 不要伪装页码能力:这个实现服务于“下一页”“加载更多”。随机跳到第 500 页、返回上一页和准确总页数均不在实现范围内,不能只给响应加一个页码就声称支持。

结语:先确定列表语义,再选择分页方式

当产品主要是按稳定顺序持续向后浏览时,复合键 keyset 分页能避免依赖不断移动的行位置,且便于利用匹配的索引。它需要的不是一段神奇 SQL,而是统一的排序规则、完整游标、稳定数据键和清楚的一致性约定。小型后台列表需要随机页码时,OFFSET 仍可能更直接;需要严格导出快照时,事务或单独保存结果集才是另一半设计。

资料核验与代码运行日期:2026年10月20日。本文代码和测试为独立编写,配图为模型生成概念图;没有宣称未经测试的跨版本结果或性能提升幅度。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。