首页
/ Kysely 项目中处理 PostgreSQL 时间戳类型的正确方式

Kysely 项目中处理 PostgreSQL 时间戳类型的正确方式

2025-05-19 04:33:34作者:盛欣凯Ernestine

在使用 Kysely 这个 TypeScript SQL 查询构建器时,处理 PostgreSQL 的时间戳类型可能会遇到一些类型定义上的困惑。本文将通过一个实际案例,详细解析如何正确定义和使用时间戳类型。

问题背景

在 PostgreSQL 中创建包含时间戳字段的表时,开发者通常会这样定义迁移:

await db.schema
  .createTable('accounts').ifNotExists()
  .addColumn('id', 'integer', col => col.primaryKey().generatedByDefaultAsIdentity())
  .addColumn('login_last', 'timestamp')
  .execute();

当尝试为这个时间戳字段定义 TypeScript 类型时,可能会遇到类型不匹配的问题。

类型定义分析

Kysely 提供了几种核心类型定义:

// 基础类型定义
export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>
  ? ColumnType<S, I | undefined, U>
  : ColumnType<T, T | undefined, T>;

// 时间戳类型定义
export type Timestamp = ColumnType<Date, Date | string, Date | string>;

正确的表类型定义

对于包含时间戳字段的表,正确的类型定义应该是:

export interface AccountTable {
  id: Generated<number>;
  login_last: Timestamp | null;  // 注意这里不再嵌套Generated
};

关键点在于:

  1. 不要将 Timestamp 类型嵌套在 Generated
  2. 将可为空的标记 | null 放在类型的最外层

使用示例

定义好类型后,可以这样使用更新操作:

const updateLastLogin = async ({
  id,
  login_last
}: Pick<AccountUpdateable, 'id' | 'login_last'>): Promise<void> => {
  await db
    .updateTable('accounts')
    .set({ login_last })
    .where('id', '=', id)
    .executeTakeFirstOrThrow();
}

// 调用方式
updateLastLogin({
  id: 5,
  login_last: new Date()  // 也可以使用字符串如 new Date().toISOString()
});

常见错误

开发者可能会遇到以下两种常见错误:

  1. 错误嵌套 Generated 类型

    login_last: Generated<Timestamp> | null  // 错误方式
    

    这会导致类型系统无法正确识别 Date 或 string 类型的值。

  2. 错误的位置放置可为空标记

    login_last: Generated<Timestamp | null>  // 不推荐方式
    

    虽然可能工作,但不是最佳实践。

最佳实践总结

  1. 对于时间戳字段,直接使用 Timestamp 类型
  2. 将可为空标记 | null 放在类型最外层
  3. 避免不必要的 Generated 类型嵌套
  4. 可以使用 Date 对象或 ISO 格式字符串作为值

通过遵循这些实践,可以确保类型系统正确工作,同时保持代码的清晰和可维护性。

登录后查看全文
热门项目推荐
相关项目推荐