Skip to content

Commit dabf761

Browse files
karthickeyan-devclaudecpojer
authored
fix(auth): carry Better Auth update hooks and defaults onto generated columns (#764)
Closes #756 ## Problem Better Auth applies `onUpdate` and `defaultValue` itself on its own writes, but the Drizzle columns in `.void/better-auth-schema.ts` had neither. Writes that go directly through Drizzle missed them: `db.update()` on an auth table left `updatedAt` unchanged, and a row inserted without `banned` stored `null` instead of `false`. ## Changes `createColumnDefinition` now emits: - `.$onUpdate(() => new Date())` for Better Auth's built-in `updatedAt` fields, unless overridden through additional fields or a plugin - `.$defaultFn(() => <literal>)` for string, number and boolean defaults, on optional fields too ```ts "emailVerified": integer("emailVerified", { mode: "boolean" }).notNull().$defaultFn(() => false), "updatedAt": integer("updatedAt", { mode: "timestamp_ms" }).notNull().$onUpdate(() => new Date()), "banned": integer("banned", { mode: "boolean" }).$defaultFn(() => false), ``` Both are runtime-only Drizzle modifiers, so existing apps need no migration. `resolveFixedDefault` still returns only required fields' defaults, so `migrationSchema` is unchanged. Custom update callbacks remain handled by Better Auth and are omitted from the generated Drizzle columns. Function defaults such as `createdAt`'s `() => new Date()` are left out, as are date and JSON literals, matching the existing exclusions. Drizzle also runs `$onUpdate` on insert when the value is omitted, and treats the column as optional in insert types. For `updatedAt` this fills in the current time rather than failing the `NOT NULL` constraint. ## Verification - New cases in `packages/void/test/unit/auth-drizzle.test.ts` cover update hooks in all three dialects, required and optional literal defaults, excluded function/date/JSON defaults, and unchanged migration metadata. - Ran the generated schemas through real Drizzle and drizzle-kit: snapshots are identical with and without the modifiers on SQLite, PostgreSQL and MySQL; the generated code typechecks in all three; on SQLite a direct `update` sets `updatedAt` and an insert gets the literal defaults. - `vp run check` passes. - `vp test run` locally: 16,453 passed, 8 failed. - 5 are `api-webhooks` timeouts that also fail on `main` in a full run on this machine. - 3 are in `cf-build-output` (timeout) and `plugin-cloudflare-v2` (inspector port `EADDRINUSE`). These did not fail on `main`, but passed 3 of 3 runs in isolation on this branch and do not reference the auth generator. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Christoph Nakazawa <cnakazawa@cloudflare.com>
1 parent 1003bc9 commit dabf761

2 files changed

Lines changed: 200 additions & 9 deletions

File tree

‎packages/void/src/auth/drizzle.ts‎

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -180,21 +180,27 @@ function usesUnboundedMySqlText(
180180
}
181181

182182
/**
183-
* The default of a required field when the database can store it as a literal.
183+
* The default of a field when it can be written as a literal.
184184
* Function, date and JSON defaults have none.
185185
*/
186-
function resolveFixedDefault(
187-
field: DBFieldAttribute,
188-
): Pick<VoidAuthMigrationField, 'defaultValue'> {
189-
if (field.required === false || field.type === 'date' || isJsonField(field)) {
190-
return {};
186+
function resolveLiteralDefault(field: DBFieldAttribute): string | number | boolean | undefined {
187+
if (field.type === 'date' || isJsonField(field)) {
188+
return undefined;
191189
}
192190
const value = field.defaultValue;
193191
return typeof value === 'string' ||
194192
typeof value === 'boolean' ||
195193
(typeof value === 'number' && Number.isFinite(value))
196-
? { defaultValue: value }
197-
: {};
194+
? value
195+
: undefined;
196+
}
197+
198+
/** The default of a required field when the database can store it as a literal. */
199+
function resolveFixedDefault(
200+
field: DBFieldAttribute,
201+
): Pick<VoidAuthMigrationField, 'defaultValue'> {
202+
const value = field.required === false ? undefined : resolveLiteralDefault(field);
203+
return value === undefined ? {} : { defaultValue: value };
198204
}
199205

200206
function resolveReferenceFieldName(
@@ -301,7 +307,23 @@ function createColumnBuilder(
301307
}
302308
}
303309

310+
function hasBuiltInUpdateHook(options: BetterAuthOptions, model: string, field: string): boolean {
311+
if (
312+
field !== 'updatedAt' ||
313+
(model !== 'user' && model !== 'session' && model !== 'account' && model !== 'verification')
314+
) {
315+
return false;
316+
}
317+
// Only Better Auth's built-in hooks are known to mean the current time.
318+
// A configured field replaces that definition, including its callback.
319+
return (
320+
options[model]?.additionalFields?.updatedAt === undefined &&
321+
!options.plugins?.some((plugin) => plugin.schema?.[model]?.fields.updatedAt !== undefined)
322+
);
323+
}
324+
304325
function createColumnDefinition(
326+
options: BetterAuthOptions,
305327
dialect: 'sqlite' | 'postgresql' | 'mysql',
306328
schema: BetterAuthDBSchema,
307329
idStrategy: AuthIdStrategy,
@@ -360,6 +382,19 @@ function createColumnDefinition(
360382
if (field.unique && actualFieldName !== 'id') {
361383
parts.push('.unique()');
362384
}
385+
// Better Auth applies these on its own writes. Direct Drizzle writes need them on the column,
386+
// and these runtime-only modifiers leave the DDL, and so existing migrations, unchanged.
387+
const literalDefault = resolveLiteralDefault(field);
388+
if (literalDefault !== undefined) {
389+
parts.push(`.$defaultFn(() => ${JSON.stringify(literalDefault)})`);
390+
}
391+
if (
392+
field.onUpdate &&
393+
field.type === 'date' &&
394+
hasBuiltInUpdateHook(options, defaultModelName, defaultFieldName)
395+
) {
396+
parts.push('.$onUpdate(() => new Date())');
397+
}
363398

364399
return parts.join('');
365400
}
@@ -466,6 +501,7 @@ export function generateVoidAuthDrizzleSchema(
466501
const fieldEntries = Object.entries(table.fields);
467502
const renderedFields = [
468503
` "id": ${createColumnDefinition(
504+
options,
469505
runtime.dialect,
470506
schema,
471507
idStrategy,
@@ -477,6 +513,7 @@ export function generateVoidAuthDrizzleSchema(
477513
...fieldEntries.map(([defaultFieldName, field]) => {
478514
const actualFieldName = resolveFieldName(defaultFieldName, field);
479515
return ` ${JSON.stringify(actualFieldName)}: ${createColumnDefinition(
516+
options,
480517
runtime.dialect,
481518
schema,
482519
idStrategy,

‎packages/void/test/unit/auth-drizzle.test.ts‎

Lines changed: 155 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { describe, expect, it } from 'vite-plus/test';
1+
import { describe, expect, it, vi } from 'vite-plus/test';
22
import {
33
generateVoidAuthDatabaseModule,
44
generateVoidAuthDrizzleSchema,
5+
resolveVoidAuthMigrationSchema,
56
} from '../../src/auth/drizzle.ts';
67

78
describe('Better Auth Drizzle codegen', () => {
@@ -106,6 +107,159 @@ describe('Better Auth Drizzle codegen', () => {
106107
);
107108
});
108109

110+
it('carries Better Auth update hooks and literal defaults onto the Drizzle columns', () => {
111+
const code = generateVoidAuthDrizzleSchema({
112+
dialect: 'sqlite',
113+
providers: null,
114+
userConfig: ({ defaults }) => ({
115+
...defaults,
116+
user: {
117+
additionalFields: {
118+
banned: { type: 'boolean', required: false, defaultValue: false },
119+
plan: { type: 'string', required: false, defaultValue: 'free' },
120+
credits: { type: 'number', required: false, defaultValue: 10 },
121+
trialEndsAt: { type: 'date', required: false, defaultValue: () => new Date() },
122+
tags: { type: 'string[]', required: false, defaultValue: '[]' },
123+
},
124+
},
125+
}),
126+
});
127+
128+
expect(code).toContain(
129+
'"emailVerified": integer("emailVerified", { mode: "boolean" }).notNull().$defaultFn(() => false)',
130+
);
131+
expect(code).toContain(
132+
'"updatedAt": integer("updatedAt", { mode: "timestamp_ms" }).notNull().$onUpdate(() => new Date())',
133+
);
134+
expect(code).toContain(
135+
'"banned": integer("banned", { mode: "boolean" }).$defaultFn(() => false)',
136+
);
137+
expect(code).toContain('"plan": text("plan").$defaultFn(() => "free")');
138+
expect(code).toContain('"credits": integer("credits").$defaultFn(() => 10)');
139+
expect(code).toContain('"trialEndsAt": integer("trialEndsAt", { mode: "timestamp_ms" }),');
140+
expect(code).toContain('"tags": text("tags", { mode: "json" }),');
141+
expect(code).toContain(
142+
'"createdAt": integer("createdAt", { mode: "timestamp_ms" }).notNull(),',
143+
);
144+
});
145+
146+
it('emits update hooks in every dialect', () => {
147+
expect(generateVoidAuthDrizzleSchema({ dialect: 'postgresql', providers: null })).toContain(
148+
'"updatedAt": timestamp("updatedAt", { mode: "date", withTimezone: true }).notNull().$onUpdate(() => new Date())',
149+
);
150+
expect(generateVoidAuthDrizzleSchema({ dialect: 'mysql', providers: null })).toContain(
151+
'"updatedAt": timestamp("updatedAt", { mode: "date", fsp: 3 }).notNull().$onUpdate(() => new Date())',
152+
);
153+
});
154+
155+
it.each(['sqlite', 'postgresql', 'mysql'] as const)(
156+
'leaves custom date update hooks out of the generated %s schema',
157+
(dialect) => {
158+
const onUpdate = vi.fn(() => new Date('2035-01-01T00:00:00.000Z'));
159+
const code = generateVoidAuthDrizzleSchema({
160+
dialect,
161+
providers: null,
162+
userConfig: ({ defaults }) => ({
163+
...defaults,
164+
user: {
165+
additionalFields: {
166+
expiresAt: { type: 'date', required: false, onUpdate },
167+
},
168+
},
169+
plugins: [
170+
{
171+
id: 'custom-dates',
172+
schema: {
173+
audit: {
174+
fields: { updatedAt: { type: 'date', onUpdate } },
175+
},
176+
},
177+
},
178+
],
179+
}),
180+
});
181+
182+
expect(code.split('\n').find((line) => line.includes('"expiresAt":'))).not.toContain(
183+
'.$onUpdate',
184+
);
185+
const audit = code.slice(code.indexOf('export const auditTable'));
186+
expect(audit.split('\n').find((line) => line.includes('"updatedAt":'))).not.toContain(
187+
'.$onUpdate',
188+
);
189+
expect(code.match(/\.\$onUpdate\(/g)).toHaveLength(4);
190+
expect(onUpdate).not.toHaveBeenCalled();
191+
},
192+
);
193+
194+
it.each(['user', 'session', 'account', 'verification'] as const)(
195+
'does not replace a configured %s.updatedAt hook',
196+
(model) => {
197+
const onUpdate = vi.fn(() => new Date('2035-01-01T00:00:00.000Z'));
198+
for (const source of ['additionalFields', 'plugin'] as const) {
199+
const field = { type: 'date' as const, onUpdate };
200+
const code = generateVoidAuthDrizzleSchema({
201+
dialect: 'sqlite',
202+
providers: null,
203+
userConfig: ({ defaults }) => ({
204+
...defaults,
205+
...(source === 'additionalFields'
206+
? { [model]: { additionalFields: { updatedAt: field } } }
207+
: {
208+
plugins: [
209+
{
210+
id: 'custom-updated-at',
211+
schema: { [model]: { fields: { updatedAt: field } } },
212+
},
213+
],
214+
}),
215+
}),
216+
});
217+
218+
const table = code.slice(code.indexOf(`export const ${model}Table`));
219+
expect(table.split('\n').find((line) => line.includes('"updatedAt":'))).not.toContain(
220+
'.$onUpdate',
221+
);
222+
expect(code.match(/\.\$onUpdate\(/g)).toHaveLength(3);
223+
}
224+
expect(onUpdate).not.toHaveBeenCalled();
225+
},
226+
);
227+
228+
it('keeps the built-in update hook when its table and column are renamed', () => {
229+
const code = generateVoidAuthDrizzleSchema({
230+
dialect: 'sqlite',
231+
providers: null,
232+
userConfig: ({ defaults }) => ({
233+
...defaults,
234+
user: { modelName: 'members', fields: { updatedAt: 'modifiedAt' } },
235+
}),
236+
});
237+
238+
expect(code).toContain(
239+
'"modifiedAt": integer("modifiedAt", { mode: "timestamp_ms" }).notNull().$onUpdate(() => new Date())',
240+
);
241+
expect(code.match(/\.\$onUpdate\(/g)).toHaveLength(4);
242+
});
243+
244+
it('keeps optional defaults out of the migration metadata', () => {
245+
const schema = resolveVoidAuthMigrationSchema({
246+
dialect: 'sqlite',
247+
providers: null,
248+
userConfig: ({ defaults }) => ({
249+
...defaults,
250+
user: {
251+
additionalFields: {
252+
banned: { type: 'boolean', required: false, defaultValue: false },
253+
},
254+
},
255+
}),
256+
});
257+
const user = schema.tables.find((table) => table.name === 'user');
258+
259+
expect(user?.fields.banned).not.toHaveProperty('defaultValue');
260+
expect(user?.fields.emailVerified).toHaveProperty('defaultValue', false);
261+
});
262+
109263
it('does not add MySQL storage metadata to PostgreSQL or SQLite schemas', () => {
110264
for (const dialect of ['postgresql', 'sqlite'] as const) {
111265
const code = generateVoidAuthDrizzleSchema({ dialect, providers: ['google'] });

0 commit comments

Comments
 (0)