Right way to make UpdatedAt column in Drizzle?

I'm trying to copy the way prisma was able to create a column that would update to the newest time when a row is changed. Is this a good implementation below or have people had issues with this that have tried to implement it?
export const users = pgTable("users", {
id: text("id")
.$defaultFn(() => createId())
.primaryKey()
.notNull(),
kindeUserId: text("kinde_user_id").unique(),
email: text("email").unique(),
firstName: text("first_name"),
lastName: text("last_name"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at") // <-- HERE
.notNull()
.default(sql`(CURRENT_TIMESTAMP)`)
.$onUpdate(() => sql`(CURRENT_TIMESTAMP)`),
});
export const users = pgTable("users", {
id: text("id")
.$defaultFn(() => createId())
.primaryKey()
.notNull(),
kindeUserId: text("kinde_user_id").unique(),
email: text("email").unique(),
firstName: text("first_name"),
lastName: text("last_name"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at") // <-- HERE
.notNull()
.default(sql`(CURRENT_TIMESTAMP)`)
.$onUpdate(() => sql`(CURRENT_TIMESTAMP)`),
});
A reference example the way Prisma had it
model User {
id Int @id @default(autoincrement())
name String?
email String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt // <-- HERE
}
model User {
id Int @id @default(autoincrement())
name String?
email String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt // <-- HERE
}
1 Reply
rphlmr ⚡
rphlmr ⚡4mo ago
I use () => sql<string>now() but yeah this is the good implementation!
import { sql } from "drizzle-orm/sql";

export function now() {
return sql<string>`now()`;
}


updatedAt: timestamp("updated_at", {
mode: "string",
precision: 3,
})
.notNull()
.$onUpdate(now),
import { sql } from "drizzle-orm/sql";

export function now() {
return sql<string>`now()`;
}


updatedAt: timestamp("updated_at", {
mode: "string",
precision: 3,
})
.notNull()
.$onUpdate(now),
Want results from more Discord servers?
Add your server