SQLite auto-update timestamp

I'm trying to auto-update timestamp when using SQLite. This is my try, but it doesn't work:
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),

updatedAt: integer('updated_at', { mode: 'timestamp' })
.notNull()
.default(sql`(unixepoch())`)
.$onUpdateFn(() => sql`(unixepoch())`),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),

updatedAt: integer('updated_at', { mode: 'timestamp' })
.notNull()
.default(sql`(unixepoch())`)
.$onUpdateFn(() => sql`(unixepoch())`),
Can you tell me how to make it work? The createdAt one works correctly. updatedAt gives:
Error occurred in handler for ...: Error: value.getTime is not a function
at Worker.<anonymous> at Worker.emit (node:events:518:28)
at MessagePort.<anonymous> (node:internal/worker:268:53)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:827:20)
at MessagePort.<anonymous> (node:internal/per_context/messageport:23:28)
Error occurred in handler for ...: Error: value.getTime is not a function
at Worker.<anonymous> at Worker.emit (node:events:518:28)
at MessagePort.<anonymous> (node:internal/worker:268:53)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:827:20)
at MessagePort.<anonymous> (node:internal/per_context/messageport:23:28)
2 Replies
Isaiah Smith
Isaiah Smith4w ago
For $onUpdateFn you’ll want to just pass a JS date object:
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
updatedAt: integer("updated_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`)
.$onUpdate(() => new Date()),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
updatedAt: integer("updated_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`)
.$onUpdate(() => new Date()),
hyperknot
hyperknotOP3w ago
thanks!

Did you find this page helpful?