feat: 添加 UUID 支持及待办事项数据表定义

- 添加 uuid 依赖以支持唯一标识符生成
- 移除对 todoTable 的导出,不再从数据库模式文件中暴露该表定义。
- 导出 todo 模式定义文件中的所有内容
- 添加待办事项数据表定义,包含标题和完成状态字段,并集成自动生成字段。
- 添加用于定义主键、创建时间和更新时间字段的实用工具函数,并支持不同 PostgreSQL 版本的 UUID 生成策略,同时提供生成字段的键名映射。
- 添加 uuid 依赖到项目中
This commit is contained in:
2026-01-21 16:33:03 +08:00
parent f1608c3546
commit da5f08f8c1
6 changed files with 69 additions and 1 deletions

View File

@@ -0,0 +1,58 @@
import { sql } from 'drizzle-orm'
import { timestamp, uuid } from 'drizzle-orm/pg-core'
import { v7 as uuidv7 } from 'uuid'
// id
export const id = (name: string) => uuid(name)
export const pk = (name: string, strategy?: 'native' | 'extension') => {
switch (strategy) {
// PG 18+
case 'native':
return id(name).primaryKey().default(sql`uuidv7()`)
// PG 13+ with extension
case 'extension':
return id(name).primaryKey().default(sql`uuid_generate_v7()`)
// Any PG version
default:
return id(name)
.primaryKey()
.$defaultFn(() => uuidv7())
}
}
// timestamp
export const createdAt = (name = 'created_at') =>
timestamp(name, { withTimezone: true }).notNull().defaultNow()
export const updatedAt = (name = 'updated_at') =>
timestamp(name, { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdateFn(() => new Date())
// generated fields
export const generatedFields = {
id: pk('id'),
createdAt: createdAt('created_at'),
updatedAt: updatedAt('updated_at'),
}
// Helper to create omit keys from generatedFields
const createGeneratedFieldKeys = <T extends Record<string, unknown>>(
fields: T,
): Record<keyof T, true> => {
return Object.keys(fields).reduce(
(acc, key) => {
acc[key as keyof T] = true
return acc
},
{} as Record<keyof T, true>,
)
}
export const generatedFieldKeys = createGeneratedFieldKeys(generatedFields)