13 位 Unix 毫秒时间戳下的游标分页与排序问题
结论
13 位毫秒时间戳不能直接传给 to_timestamp()。to_timestamp(double precision) 的参数单位是秒,因此必须除以 1000.0,例如:
to_timestamp(${after}::double precision / 1000.0)
created_at 是 TIMESTAMP WITH TIME ZONE,to_timestamp() 返回 timestamptz,两者比较没有时区换算问题。不要直接写 to_timestamp(${after}),也不要只包一层 Number(after),因为值仍然是毫秒。
分页方向不能看 before 有没有值来决定。要分清 first/after 的向前分页和 last/before 的向后分页:向前用 ORDER BY created_at ASC, id ASC,向后用 ORDER BY created_at DESC, id DESC,返回前再反转结果。只拿 created_at 当游标,遇到相同时间戳时可能重复或漏数据,建议改用 created_at + id 的复合游标。如果需要严格保证顺序,游标还应保留 created_at 的完整精度,不能只留 13 位毫秒。
毫秒时间戳的正确转换
错误写法:
created_at > to_timestamp(${after})
created_at > to_timestamp(${Number(after)})
正确写法:
created_at > to_timestamp(${after}::double precision / 1000.0)
created_at < to_timestamp(${before}::double precision / 1000.0)
这里使用 1000.0,不要写 1000,避免整数除法截断。若游标值可能为空字符串,先在外层校验,避免 ''::double precision 报错。
只用毫秒游标的可用写法
如果暂时必须保持 after/before 只包含 13 位毫秒字符串,可以这样写。注意这仍不能彻底解决同一毫秒内多条记录的分页边界问题:
async getPosts(
first?: number | null,
after?: string | null,
last?: number | null,
before?: string | null
) {
if (first != null && last != null) {
throw new Error('first and last cannot be used together');
}
const isBackward = last != null;
const direction = isBackward ? this.dbConnection`desc` : this.dbConnection`asc`;
const limit = first ?? last ?? 10;
const rows = await this.dbConnection`
select
content, created_at, creator, detected_language, id,
is_suspended, response_root_post, type
from posts
where is_suspended = false
and type = 'public'
${
after
? this.dbConnection`
and created_at > to_timestamp(${after}::double precision / 1000.0)
`
: this.dbConnection``
}
${
before
? this.dbConnection`
and created_at < to_timestamp(${before}::double precision / 1000.0)
`
: this.dbConnection``
}
order by created_at ${direction}, id ${direction}
limit ${limit}
`;
return isBackward ? rows.reverse() : rows;
}
说明:
after只表示游标之后的时间,也就是created_at > ...。before只表示游标之前的时间,也就是created_at < ...。last表示从游标方向倒着取 N 条,所以 SQL 用DESC,返回前再反转。ORDER BY created_at ..., id ...中两个方向要一致,避免同一时间戳下顺序不稳定。direction不能直接拼接来自客户端的字符串。上面的direction来自代码内部布尔值,使用 postgres.js 的 SQL fragment 是安全的。
推荐的复合游标写法
更稳妥的做法是把游标做成不透明字符串,里面同时包含完整时间戳和 id。例如用 base64url 编码 created_at 的 ISO 字符串 + id,或者使用数据库中的微秒时间戳。不要只把 13 位毫秒和 id 拼在一起还继续按毫秒截断比较,因为 PostgreSQL 的 timestamptz 默认可能带微秒精度,截断后在同一毫秒内仍可能错序。
下面用 created_at 的 ISO 字符串和 id 组成游标示例:
function encodeCursor(row: { created_at: string; id: number }) {
const raw = `${row.created_at}|${row.id}`;
return Buffer.from(raw, 'utf8').toString('base64url');
}
function decodeCursor(cursor?: string | null) {
if (!cursor) return null;
const raw = Buffer.from(cursor, 'base64url').toString('utf8');
const [createdAt, id] = raw.split('|');
return { createdAt, id: Number(id) };
}
查询时使用行值比较:
const afterCursor = decodeCursor(after);
const beforeCursor = decodeCursor(before);
const isBackward = last != null;
const direction = isBackward ? this.dbConnection`desc` : this.dbConnection`asc`;
const limit = first ?? last ?? 10;
const rows = await this.dbConnection`
select
content, created_at, creator, detected_language, id,
is_suspended, response_root_post, type
from posts
where is_suspended = false
and type = 'public'
${
afterCursor
? this.dbConnection`
and (created_at, id) > (
${afterCursor.createdAt}::timestamptz,
${afterCursor.id}
)
`
: this.dbConnection``
}
${
beforeCursor
? this.dbConnection`
and (created_at, id) < (
${beforeCursor.createdAt}::timestamptz,
${beforeCursor.id}
)
`
: this.dbConnection``
}
order by created_at ${direction}, id ${direction}
limit ${limit}
`;
return isBackward ? rows.reverse() : rows;
如果游标使用微秒整数,则比较条件类似:
and (created_at, id) > (
to_timestamp(${afterUs}::double precision / 1000000.0),
${afterId}
)
关于 ORDER BY 和 postgres.js
你原来的表达式:
order by created_at ${last ?? before ? this.dbConnection`desc` : this.dbConnection`asc`}
这里有两个问题。第一,它把 before 是否存在当成降序条件,但真正决定取数方向的是 last 还是 first。第二,last ?? before ? ... : ... 的优先级容易让人看错,应显式写成布尔变量:
const isBackward = last != null;
const direction = isBackward ? this.dbConnection`desc` : this.dbConnection`asc`;
然后:
order by created_at ${direction}, id ${direction}
不要用字符串模板直接拼接 ORDER BY created_at ${userInput}。方向值应由服务端枚举决定,例如只允许 asc 或 desc。
注意事项
created_at建议加NOT NULL约束,否则(created_at, id)行值比较会跳过NULL行。after和before同时存在时可以同时过滤;first和last不应同时使用。- 向后分页
last + before在 SQL 中先按DESC取 N 条,再在应用层.reverse()后返回,客户端看到的顺序仍然稳定。 - 如果业务要求严格游标分页,应把
created_at的完整数据库精度写入游标,并包含id。只使用created_at或只使用 13 位毫秒,在相同时间戳或同一毫秒内有多条记录时,都可能出现重复或漏项。
备注:内容仅供参考。
