如何设置 Drizzle Schema 让 SQLite 支持自动填入创建时间

背景

之前用下面的Schema创建了表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export const tasks = sqliteTable("tasks", {
id: integer("id", { mode: "number" })
.primaryKey({ autoIncrement: true }),
name: text("name")
.notNull(),
done: integer("done", { mode: "boolean" })
.notNull()
.default(false),
createdAt: integer("created_at", { mode: "timestamp" })
.$defaultFn(() => new Date()),
updatedAt: integer("updated_at", { mode: "timestamp" })
.$defaultFn(() => new Date())
.$onUpdate(() => new Date()),
});

发现这个创建时间和更新时间并没有生效,研究了一下,这样写可能有问题。

解决方案

查询了一下,修改为下面的语句:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { sql } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { createSelectSchema } from "drizzle-zod";

export const tasks = sqliteTable("tasks", {
id: integer("id", { mode: "number" })
.primaryKey({ autoIncrement: true }),
name: text("name")
.notNull(),
done: integer("done", { mode: "boolean" })
.notNull()
.default(false),
createdAt: text('created_at')
.notNull()
.default(sql`(current_timestamp)`),
updatedAt:text('updated_at')
.notNull()
.default(sql`(current_timestamp)`)
});

export const selectTasksSchema = createSelectSchema(tasks);

updateAt字段无效,需要更新时主动更新。

效果

修改完后,利用 drizzle-kit 重新生成数据库:

1
2
bun drizzle-kit generate
bun drizzle-kit push

试了一下,插入数据后自动产生了时间:

1
1|Hello Hone|0|2025-02-24 06:13:34|2025-02-24 06:13:34

作者:Bearalise
出处:如何设置 Drizzle Schema 让 SQLite 支持自动填入创建时间
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信