Python sqlite3 键集分页:双字段倒序游标、重复时间与跨页增删
“下一页”不一定要记住跳过了多少行。日志或消息列表按时间倒序浏览时,可以把上一页最后一条记录的排序键带回来,继续查它后面的记录。本文用 Python 标准库 sqlite3 实现键集分页,重点不是宣称提速,而是把同秒记录、结束条件和跨页数据变化讲清楚。
配图为独立模型生成的概念示意图,卡片仅表示记录与分页边界,不是数据库截图,也不是查询结果或性能测试图。
一、游标必须覆盖完整排序规则
约定 created_at 是非空、有符号 64 位整数,业务统一按 Unix 秒写入;id 是正整数且全表唯一。排序固定为 created_at DESC, id DESC。时间相同就继续比较 id,因此每条记录都有确定位置。只有时间,没有唯一的第二排序键,页边界切在同秒记录中间时就容易漏掉余项。SQLite 的 SELECT 文档也明确说明,所有排序表达式都相等时,行间次序未定义。
上一页最后一条为 (200, 7),下一页条件是 (created_at, id) < (200, 7):要么时间小于 200,要么时间等于 200 且 id 小于 7。因为两个字段都是降序,向后翻页才使用小于号;不能把这条规则原样套到升降序混合的排序上。SQLite 的行值比较文档给出了从左到右比较及滚动查询的规则。
二、先约束输入,再绑定 SQL 参数
函数只接受 1 到 100 的 Python 原生 int 页长,明确拒绝 bool、浮点数、数字字符串和负数。这里用 type(value) is int,是因为 True 在 Python 中也能被视为整数。SQLite 自身允许负 LIMIT 表示不设上限,所以应用不能只依赖 SQL 能否执行来判断页长是否合法。
游标只能是 None 或二元 tuple,两个成员都进行整数类型和范围检查;None 表示从头开始,不代表“继续上一页”。两个游标值以及 limit + 1 全部通过问号占位符绑定,表名、字段名和排序方向固定,不从用户输入拼接。参数绑定遵循 Python sqlite3 官方说明。
三、完整实现:多读一条判断是否还有下一页
保存为 keyset.py。返回行的字段顺序是 created_at、id、title。多取的一条只用于判断是否还有记录,不放进本页,也不能拿它做下一页游标,否则会跳过它。代码只依赖标准库,演示数据库完全位于内存中。
"""Descending keyset pagination; sort keys are an application invariant."""
from dataclasses import dataclass
import sqlite3
MIN_I64 = -(1 << 63)
MAX_I64 = (1 << 63) - 1
MAX_PAGE = 100
Cursor = tuple[int, int]
Row = tuple[int, int, str] # created_at, id, title
@dataclass(frozen=True)
class Page:
rows: tuple[Row, ...]
next_cursor: Cursor | None
def require_int(value, name, low, high):
if type(value) is not int:
raise TypeError(f'{name} must be an int, not bool or text')
if not low <= value <= high:
raise ValueError(f'{name} is out of range')
return value
def insert_event(con, event_id, created_at, title):
require_int(event_id, 'id', 1, MAX_I64)
require_int(created_at, 'created_at', MIN_I64, MAX_I64)
if type(title) is not str:
raise TypeError('title must be str')
con.execute(
'INSERT INTO events(id, created_at, title) VALUES (?, ?, ?)',
(event_id, created_at, title),
)
def make_db():
# Autocommit: each call sees current data, not one cross-page snapshot.
con = sqlite3.connect(':memory:', isolation_level=None)
con.execute('''CREATE TABLE events (
id INTEGER PRIMARY KEY CHECK(id > 0),
created_at INTEGER NOT NULL CHECK(typeof(created_at) = 'integer'),
title TEXT NOT NULL
)''')
return con
def fetch_page(con, limit=3, cursor=None):
require_int(limit, 'limit', 1, MAX_PAGE)
if cursor is not None:
if type(cursor) is not tuple or len(cursor) != 2:
raise TypeError('cursor must be a 2-item tuple or None')
require_int(cursor[0], 'cursor timestamp', MIN_I64, MAX_I64)
require_int(cursor[1], 'cursor id', 1, MAX_I64)
sql = '''SELECT created_at, id, title FROM events
WHERE (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC LIMIT ?'''
params = (*cursor, limit + 1)
else:
sql = '''SELECT created_at, id, title FROM events
ORDER BY created_at DESC, id DESC LIMIT ?'''
params = (limit + 1,)
# One extra row answers whether another page existed at this query.
found = con.execute(sql, params).fetchall()
rows = tuple(found[:limit])
next_cursor = rows[-1][:2] if len(found) > limit else None
return Page(rows, next_cursor)
def demo():
con = make_db()
try:
for event_id, stamp in [(9, 300), (8, 300), (7, 200),
(6, 200), (5, 200), (4, 100)]:
insert_event(con, event_id, stamp, f'event-{event_id}')
cursor = None
while True:
page = fetch_page(con, limit=2, cursor=cursor)
print(page)
if page.next_cursor is None:
break
cursor = page.next_cursor
finally:
con.close()
if __name__ == '__main__':
demo()运行 python keyset.py,三页的 id 依次为 [9, 8]、[7, 6]、[5, 4],前两页游标分别是 (300, 8)、(200, 6),最后一页为 None。即使最后一页刚好装满,也能通过多取一条判断结束。空表、游标之后没有记录时,返回空 tuple 和 None。调用方看到 next_cursor 为 None 就应结束;把它重新传入会再次打开首页。
四、翻页期间插入和删除,会发生什么
本例每次查询都会读完结果,连接使用自动提交模式,没有跨页保留读事务。它是“从这个键继续”,不是“冻结第一次查询时的全表”。下面的行为已经由测试覆盖:
新记录排在游标之前:继续向后翻页不会看见它;想看最新记录,应重新读取首页。
补写的旧记录排在游标之后:后续页面可能读到它。同一时间的新 id,也要按完整二元组判断在哪一边。
删除已读记录或游标所指记录:不需要重新定位那条记录,保存下来的两个数仍能作为边界。
删除尚未读取的记录:它不再出现。上一页曾返回非空游标,也不保证下一次请求一定有数据。
这些结论来自同一连接上顺序执行的插入、删除与翻页测试,不是并发压力测试。跨连接可见性还取决于事务和日志模式,参见 SQLite 隔离说明。如果需求是可审计导出的一致数据集合,应另外设计快照或固定结果集,不能把游标误当快照凭证。
五、“排序键不变”是必须守住的业务契约
本例要求记录存活期间 created_at 和 id 不改变,也不把已删除的 id 复用于另一条业务记录;表结构本身并未禁止 UPDATE。测试故意违反约定:把已读记录时间改小,它可能落到游标之后而再次出现;把未读记录时间改大,它可能越过游标而被漏掉。更新标题不改变位置,但正文内容仍可能变化。需要改展示时间时,宜保留专用、不可变的分页排序字段。
游标值可以公开携带,但它不是权限凭据。若实际接口加入用户、租户或筛选条件,每次查询仍须重新授权,并保证游标对应同一组筛选与排序规则;本例没有实现 HTTP 参数解析、令牌编码或签名。
六、可直接运行的 38 项测试
下面保存为同目录的 test_keyset.py,再运行 python -m unittest -v test_keyset。本次在 Python 3.12.14、其 sqlite3 连接到的 SQLite 3.53.1 上实际执行,38 项测试全部通过。数量按测试方法统计,部分方法另含多组子测试;这里没有把它们再单独累加。
import sqlite3
import unittest
from unittest.mock import Mock
from keyset import MAX_I64, MIN_I64, fetch_page, insert_event, make_db
class KeysetTests(unittest.TestCase):
def setUp(self):
self.con = make_db()
self.addCleanup(self.con.close)
for event_id, stamp in [(3, 100), (8, 300), (6, 200), (2, 0),
(9, 300), (5, 200), (4, 100), (7, 200)]:
insert_event(self.con, event_id, stamp, f'event-{event_id}')
def ids(self, page):
return [row[1] for row in page.rows]
def scan(self, limit):
result, cursor = [], None
while True:
page = fetch_page(self.con, limit, cursor)
result.extend(self.ids(page))
if page.next_cursor is None:
return result
cursor = page.next_cursor
def test_first_page_order(self):
page = fetch_page(self.con)
self.assertEqual(self.ids(page), [9, 8, 7])
self.assertEqual(page.next_cursor, (200, 7))
def test_timestamp_tie_crosses_page(self):
page = fetch_page(self.con, 3, (200, 7))
self.assertEqual(self.ids(page), [6, 5, 4])
def test_complete_traversal(self):
self.assertEqual(self.scan(3), [9, 8, 7, 6, 5, 4, 3, 2])
def test_page_size_one(self):
self.assertEqual(self.scan(1), [9, 8, 7, 6, 5, 4, 3, 2])
def test_max_page_size(self):
page = fetch_page(self.con, 100)
self.assertEqual(len(page.rows), 8)
self.assertIsNone(page.next_cursor)
def test_empty_table(self):
self.con.execute('DELETE FROM events')
page = fetch_page(self.con)
self.assertEqual(page.rows, ())
self.assertIsNone(page.next_cursor)
def test_exact_full_last_page(self):
page = fetch_page(self.con, 2, (100, 4))
self.assertEqual(self.ids(page), [3, 2])
self.assertIsNone(page.next_cursor)
def test_short_last_page(self):
page = fetch_page(self.con, 3, (100, 4))
self.assertEqual(self.ids(page), [3, 2])
self.assertIsNone(page.next_cursor)
def test_cursor_at_end(self):
page = fetch_page(self.con, 3, (0, 2))
self.assertEqual(page.rows, ())
self.assertIsNone(page.next_cursor)
def test_nonexistent_boundary(self):
self.assertEqual(self.ids(fetch_page(self.con, 3, (250, 50))),
[7, 6, 5])
def test_integer_boundaries(self):
insert_event(self.con, MAX_I64, MAX_I64, 'highest')
insert_event(self.con, 1, MIN_I64, 'lowest')
self.assertEqual(self.scan(2), [MAX_I64, 9, 8, 7, 6, 5, 4, 3, 2, 1])
def test_limit_zero(self):
with self.assertRaises(ValueError):
fetch_page(self.con, 0)
def test_limit_negative(self):
with self.assertRaises(ValueError):
fetch_page(self.con, -1)
def test_limit_over_cap(self):
with self.assertRaises(ValueError):
fetch_page(self.con, 101)
def test_limit_bool(self):
with self.assertRaises(TypeError):
fetch_page(self.con, True)
def test_limit_float(self):
with self.assertRaises(TypeError):
fetch_page(self.con, 3.0)
def test_limit_sql_text(self):
with self.assertRaises(TypeError):
fetch_page(self.con, '1; DROP TABLE events;')
self.assertEqual(len(fetch_page(self.con, 100).rows), 8)
def test_cursor_list_rejected(self):
with self.assertRaises(TypeError):
fetch_page(self.con, cursor=[200, 7])
def test_cursor_wrong_shape(self):
for cursor in [(), (200,), (200, 7, 0), '200,7']:
with self.subTest(cursor=cursor), self.assertRaises(TypeError):
fetch_page(self.con, cursor=cursor)
def test_cursor_bool_rejected(self):
for cursor in [(True, 7), (200, True)]:
with self.subTest(cursor=cursor), self.assertRaises(TypeError):
fetch_page(self.con, cursor=cursor)
def test_cursor_timestamp_overflow(self):
for stamp in [MIN_I64 - 1, MAX_I64 + 1]:
with self.subTest(stamp=stamp), self.assertRaises(ValueError):
fetch_page(self.con, cursor=(stamp, 7))
def test_cursor_noninteger_timestamp(self):
for stamp in [200.0, '200', None]:
with self.subTest(stamp=stamp), self.assertRaises(TypeError):
fetch_page(self.con, cursor=(stamp, 7))
def test_cursor_id_out_of_range(self):
for event_id in [0, -1, MAX_I64 + 1]:
with self.subTest(event_id=event_id), self.assertRaises(ValueError):
fetch_page(self.con, cursor=(200, event_id))
def test_cursor_sql_text(self):
with self.assertRaises(TypeError):
fetch_page(self.con, cursor=(200, '7 OR 1=1'))
self.assertEqual(len(fetch_page(self.con, 100).rows), 8)
def test_insert_new_head_between_pages(self):
cursor = fetch_page(self.con).next_cursor
insert_event(self.con, 10, 400, 'new head')
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [6, 5, 4])
def test_insert_below_cursor_is_visible(self):
cursor = fetch_page(self.con).next_cursor
insert_event(self.con, 10, 150, 'backfill')
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [6, 5, 10])
def test_insert_same_time_above_cursor_not_visible(self):
cursor = fetch_page(self.con).next_cursor
insert_event(self.con, 10, 200, 'same time newer id')
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [6, 5, 4])
def test_insert_same_time_below_cursor_is_visible(self):
cursor = fetch_page(self.con).next_cursor
insert_event(self.con, 1, 200, 'same time smaller id')
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [6, 5, 1])
def test_delete_already_seen_row(self):
cursor = fetch_page(self.con).next_cursor
self.con.execute('DELETE FROM events WHERE id = ?', (9,))
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [6, 5, 4])
def test_delete_cursor_row(self):
cursor = fetch_page(self.con).next_cursor
self.con.execute('DELETE FROM events WHERE id = ?', (7,))
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [6, 5, 4])
def test_delete_unseen_row(self):
cursor = fetch_page(self.con).next_cursor
self.con.execute('DELETE FROM events WHERE id = ?', (6,))
self.assertEqual(self.ids(fetch_page(self.con, 3, cursor)), [5, 4, 3])
def test_delete_remaining_rows(self):
cursor = fetch_page(self.con).next_cursor
self.con.execute('DELETE FROM events WHERE (created_at, id) < (?, ?)',
cursor)
self.assertEqual(fetch_page(self.con, 3, cursor).rows, ())
def test_mutating_seen_sort_key_can_repeat_row(self):
# Deliberately violate the immutable-sort-key contract.
first = fetch_page(self.con)
self.con.execute('UPDATE events SET created_at = 150 WHERE id = 9')
second = fetch_page(self.con, 3, first.next_cursor)
self.assertIn(9, self.ids(first))
self.assertIn(9, self.ids(second))
def test_mutating_unseen_sort_key_can_skip_row(self):
cursor = fetch_page(self.con).next_cursor
self.con.execute('UPDATE events SET created_at = 400 WHERE id = 6')
self.assertNotIn(6, self.ids(fetch_page(self.con, 100, cursor)))
def test_insert_validation_and_duplicate_id(self):
for args in [(True, 200, 'x'), (10, '200', 'x'), (10, 200, None)]:
with self.subTest(args=args), self.assertRaises(TypeError):
insert_event(self.con, *args)
with self.assertRaises(ValueError):
insert_event(self.con, 0, 200, 'x')
with self.assertRaises(sqlite3.IntegrityError):
insert_event(self.con, 9, 200, 'duplicate')
def test_optional_index_preserves_results(self):
expected = self.scan(3)
self.con.execute('CREATE INDEX events_page ON events'
'(created_at DESC, id DESC)')
self.assertEqual(self.scan(3), expected)
def test_limit_and_cursor_are_bound_parameters(self):
con = Mock()
con.execute.return_value.fetchall.return_value = []
fetch_page(con, 3, (200, 7))
sql, params = con.execute.call_args.args
self.assertIn('(created_at, id) < (?, ?)', sql)
self.assertIn('LIMIT ?', sql)
self.assertEqual(params, (200, 7, 4))
fetch_page(con, 3)
self.assertEqual(con.execute.call_args.args[1], (4,))
def test_database_rejects_invalid_stored_timestamp(self):
for stamp in [None, 'bad', 1.5]:
with self.subTest(stamp=stamp), self.assertRaises(sqlite3.IntegrityError):
self.con.execute('INSERT INTO events VALUES (?, ?, ?)',
(10, stamp, 'invalid'))
if __name__ == '__main__':
unittest.main(verbosity=2)七、索引与验证边界
需要时可执行 CREATE INDEX events_page ON events(created_at DESC, id DESC),为范围条件和排序提供匹配索引。上面的索引测试只验证添加前后结果一致,不测耗时,不保证查询规划器永远选择该索引。实际应结合数据规模、过滤条件和查询计划评估,原理见 SQLite 查询规划文档。
本次验证范围是单进程、单连接、内存数据库、整数边界和确定性样例;没有验证多进程并发、磁盘故障、HTTP 服务、生产负载或其他运行时版本。SQLite 的普通类型声明也不等于严格的入参校验,示例用应用校验加存储类型检查共同约束时间值,参见官方数据类型说明。先明确排序与数据变化契约,再谈分页优化,通常比只把 OFFSET 替换掉更重要。


