Skip to content

Commit b6af283

Browse files
committed
Opt new MySQL starters into DATETIME auth columns.
1 parent f3b713e commit b6af283

15 files changed

Lines changed: 152 additions & 23 deletions

File tree

‎docs/guide/database/mysql.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,13 @@ void db migrate
5050
void deploy
5151
```
5252

53-
Void generates Better Auth's date columns as `DATETIME(3)`. If your Drizzle snapshot still has them as `TIMESTAMP(3)`, `void deploy` stops on schema drift and asks you to run `void db generate` and commit the migration that converts them. Apply that migration with `void db migrate`, not `void db push`, which can offer to empty or drop auth tables. The dates keep their values, milliseconds included, when the migration connects with the same session time zone the app wrote them with.
53+
### Auth date columns
54+
55+
New MySQL starters set `database.authDateType` to `"datetime"` in `void.config.ts`. Generated Better Auth columns then use `DATETIME(3)`, which supports dates before 1970, such as birthdays. Projects that omit the setting continue to generate `TIMESTAMP(3)`.
56+
57+
If your database already has `TIMESTAMP(3)` auth columns and you choose to switch, generate and review a migration with `void db generate`. Test it on a copy of your database and verify that stored dates, including session expirations, are preserved using the same session time zone as your app. Commit the migration and apply it with `void db migrate`.
58+
59+
### Applying migrations on Cloudflare
5460

5561
For direct Cloudflare deploys, export the production `DATABASE_URL` in the shell running `void deploy --platform cloudflare`. Void uses it to provision Hyperdrive and apply pending checked-in migrations before uploading the Worker; it is not written to the Worker config.
5662

‎docs/reference/config.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ Database backend. Omit for D1/SQLite (default). Set to `"pg"` or `"mysql"` for a
144144
| `"pg"` | PostgreSQL via Hyperdrive; bring your own database |
145145
| `"mysql"` | MySQL via Hyperdrive; bring your own database |
146146

147-
Use an object to also set how Drizzle names columns declared without a name:
147+
Use an object to set database options:
148148

149149
```json
150150
{
@@ -157,6 +157,7 @@ Use an object to also set how Drizzle names columns declared without a name:
157157
| `dialect` | `"sqlite"` (default), `"pg"`, `"mysql"` | Database backend. `"sqlite"` is D1 |
158158
| `casing` | `"snake_case"`, `"camelCase"` | [Drizzle casing](https://orm.drizzle.team/docs/sql-schema-declaration#camel-and-snake-casing) for `void/db` queries and `void db` commands. Omit to use each key as its column name |
159159
| `readReplication` | `boolean` (optional) | D1 only. Enable (`true`) or disable (`false`) [read replication](../guide/database/d1.md#read-replication) on deployment. Omit to preserve existing settings; new databases default to off |
160+
| `authDateType` | `"timestamp"`, `"datetime"` | MySQL only. Type used for generated [auth date columns](../guide/database/mysql.md#auth-date-columns). Omit to use `TIMESTAMP(3)`. New MySQL starters set `"datetime"`. |
160161

161162
When using an external database:
162163

‎packages/void/schema.json‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,10 +437,21 @@
437437
"readReplication": {
438438
"type": "boolean",
439439
"description": "Enable or disable D1 read replication during deployment. Omit to preserve existing settings; new databases default to replication off."
440+
},
441+
"authDateType": {
442+
"type": "string",
443+
"enum": ["timestamp", "datetime"],
444+
"description": "MySQL column type for generated auth dates. Defaults to timestamp when omitted."
440445
}
441446
},
442447
"if": { "required": ["readReplication"] },
443448
"then": { "properties": { "dialect": { "const": "sqlite" } } },
449+
"allOf": [
450+
{
451+
"if": { "required": ["authDateType"] },
452+
"then": { "required": ["dialect"], "properties": { "dialect": { "const": "mysql" } } }
453+
}
454+
],
444455
"additionalProperties": false
445456
}
446457
]

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { BetterAuthOptions } from 'better-auth';
22
import { getAuthTables, getSchema as getBetterAuthSchema } from 'better-auth/db';
33
import type { BetterAuthDBSchema, DBFieldAttribute } from 'better-auth/db';
4+
import type { MySqlAuthDateType } from '../config.ts';
45
import type { VoidAuthRuntimeOptions } from '../runtime/auth/better-auth-shared.ts';
56
import type { VoidAuthConfig } from '../runtime/auth/index.ts';
67
import { VOID_EMAIL_AUTH_PROVIDER, isVoidSocialAuthProvider } from './providers.ts';
@@ -222,6 +223,7 @@ function createColumnBuilder(
222223
defaultFieldName: string,
223224
fieldName: string,
224225
field: DBFieldAttribute,
226+
authDateType: MySqlAuthDateType,
225227
): string {
226228
const useIdType = fieldName === 'id' || field.references?.field === 'id';
227229

@@ -241,7 +243,7 @@ function createColumnBuilder(
241243
case 'boolean':
242244
return `boolean(${JSON.stringify(fieldName)})`;
243245
case 'date':
244-
return `datetime(${JSON.stringify(fieldName)}, { mode: "date", fsp: 3 })`;
246+
return `${authDateType}(${JSON.stringify(fieldName)}, { mode: "date", fsp: 3 })`;
245247
case 'number':
246248
return field.bigint
247249
? `bigint(${JSON.stringify(fieldName)}, { mode: "number" })`
@@ -331,6 +333,7 @@ function createColumnDefinition(
331333
defaultModelName: string,
332334
defaultFieldName: string,
333335
field: DBFieldAttribute,
336+
authDateType: MySqlAuthDateType,
334337
): string {
335338
const actualFieldName = resolveFieldName(defaultFieldName, field);
336339
const parts = [
@@ -341,6 +344,7 @@ function createColumnDefinition(
341344
defaultFieldName,
342345
actualFieldName,
343346
field,
347+
authDateType,
344348
),
345349
];
346350

@@ -403,6 +407,7 @@ function collectCoreImports(
403407
dialect: 'sqlite' | 'postgresql' | 'mysql',
404408
schema: BetterAuthDBSchema,
405409
idStrategy: AuthIdStrategy,
410+
authDateType: MySqlAuthDateType,
406411
): Array<string> {
407412
const imports = new Set<string>([
408413
dialect === 'postgresql' ? 'pgTable' : dialect === 'mysql' ? 'mysqlTable' : 'sqliteTable',
@@ -451,7 +456,7 @@ function collectCoreImports(
451456
}
452457
if (field.type === 'date') {
453458
imports.add(
454-
dialect === 'sqlite' ? 'integer' : dialect === 'mysql' ? 'datetime' : 'timestamp',
459+
dialect === 'sqlite' ? 'integer' : dialect === 'mysql' ? authDateType : 'timestamp',
455460
);
456461
continue;
457462
}
@@ -494,7 +499,8 @@ export function generateVoidAuthDrizzleSchema(
494499
: runtime.dialect === 'mysql'
495500
? 'void/schema-mysql'
496501
: 'void/schema-d1';
497-
const imports = collectCoreImports(runtime.dialect, schema, idStrategy);
502+
const authDateType = runtime.authDateType ?? 'timestamp';
503+
const imports = collectCoreImports(runtime.dialect, schema, idStrategy, authDateType);
498504
const lines = [
499505
'// Auto-generated by void — do not edit',
500506
`import { ${imports.join(', ')} } from ${JSON.stringify(importPath)};`,
@@ -517,6 +523,7 @@ export function generateVoidAuthDrizzleSchema(
517523
defaultModelName,
518524
'id',
519525
{ type: idStrategy === 'serial' ? 'number' : 'string', required: true },
526+
authDateType,
520527
)},`,
521528
...fieldEntries.map(([defaultFieldName, field]) => {
522529
const actualFieldName = resolveFieldName(defaultFieldName, field);
@@ -529,6 +536,7 @@ export function generateVoidAuthDrizzleSchema(
529536
defaultModelName,
530537
defaultFieldName,
531538
field,
539+
authDateType,
532540
)},`;
533541
}),
534542
];

‎packages/void/src/cli/init.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1285,7 +1285,7 @@ async function promptStarterMode(starter?: ScaffoldStarterMode): Promise<Scaffol
12851285
{
12861286
value: 'mysql',
12871287
label: 'MySQL',
1288-
hint: 'Scaffolds the same starter with MySQL, a generated migration, a seed file, and writes database: "mysql" to void.config.ts.',
1288+
hint: 'Scaffolds the same starter with MySQL, a generated migration, a seed file, and writes MySQL settings to void.config.ts.',
12891289
},
12901290
{
12911291
value: 'static',

‎packages/void/src/cli/template.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,12 @@ export function createPagesStarterTemplate(options: {
213213
const files: PagesStarterTemplate['files'] = {
214214
// Later init steps add `database` and `worker` to this generated config.
215215
'void.config.ts': renderVoidConfig(
216-
{ routing: { typedRoutes: true } },
216+
{
217+
routing: { typedRoutes: true },
218+
...(starterMode === 'mysql' && {
219+
database: { dialect: 'mysql', authDateType: 'datetime' },
220+
}),
221+
},
217222
'// Generated by void init.',
218223
),
219224
[getGeneratedViteConfigPath(packageType)]: getViteConfig(framework, config, toolchain),

‎packages/void/src/codegen/prepare.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { join } from 'pathslash';
44
import { analyzeApplication } from '../application-routing.ts';
55
import { loadVoidAuthConfig, projectAuthConfigImporter } from '../auth/config.ts';
66
import { generateVoidAuthDatabaseModule, generateVoidAuthDrizzleSchema } from '../auth/drizzle.ts';
7-
import { getDatabaseCasing, readConfig } from '../config.ts';
7+
import { getDatabaseAuthDateType, getDatabaseCasing, readConfig } from '../config.ts';
88
import { discoverSchema } from '../drizzle/discover.ts';
99
import { loadLocalEnv } from '../shared/env.ts';
1010
import { generateAuthTypes } from './auth-types.ts';
@@ -121,6 +121,7 @@ export async function prepareProject(root: string): Promise<PrepareProjectResult
121121
if (authEnabled) {
122122
const authRuntime = {
123123
dialect,
124+
authDateType: getDatabaseAuthDateType(config),
124125
providers: config.auth?.providers ?? null,
125126
userConfig: await loadVoidAuthConfig(authConfigPath, projectAuthConfigImporter(root)),
126127
};

‎packages/void/src/config.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ export type DatabaseDialect = 'sqlite' | 'postgresql' | 'mysql';
1919
/** Drizzle's `casing`: how a column declared without a name is named in the database. */
2020
export type DatabaseCasing = 'snake_case' | 'camelCase';
2121

22+
export type MySqlAuthDateType = 'timestamp' | 'datetime';
23+
2224
/** Object form of `database`, for options next to the dialect. */
2325
export type DatabaseConfig = {
2426
/** Database backend. Defaults to `"sqlite"` (D1). */
@@ -27,6 +29,8 @@ export type DatabaseConfig = {
2729
casing?: DatabaseCasing;
2830
/** Enable or disable D1 read replication during deployment. Omit to preserve existing settings. */
2931
readReplication?: boolean;
32+
/** MySQL column type for generated auth dates. Defaults to "timestamp" for existing projects. */
33+
authDateType?: MySqlAuthDateType;
3034
};
3135

3236
/** Curated Worker fields accepted by the `worker` config field. */
@@ -965,9 +969,14 @@ function validateConfigObject(obj: unknown): VoidConfig {
965969
if (isRecord(obj.database)) {
966970
const databaseCfg = obj.database;
967971
for (const key of Object.keys(databaseCfg)) {
968-
if (key !== 'dialect' && key !== 'casing' && key !== 'readReplication') {
972+
if (
973+
key !== 'dialect' &&
974+
key !== 'casing' &&
975+
key !== 'readReplication' &&
976+
key !== 'authDateType'
977+
) {
969978
throw new Error(
970-
`config: Unknown key 'database.${key}' in ${CONFIG_FILE}. Valid: dialect, casing, readReplication.`,
979+
`config: Unknown key 'database.${key}' in ${CONFIG_FILE}. Valid: dialect, casing, readReplication, authDateType.`,
971980
);
972981
}
973982
}
@@ -1000,9 +1009,21 @@ function validateConfigObject(obj: unknown): VoidConfig {
10001009
);
10011010
}
10021011
}
1012+
if (databaseCfg.authDateType !== undefined) {
1013+
if (databaseCfg.authDateType !== 'timestamp' && databaseCfg.authDateType !== 'datetime') {
1014+
throw new Error(
1015+
`config: "database.authDateType" in ${CONFIG_FILE} must be "timestamp" or "datetime".`,
1016+
);
1017+
}
1018+
if (databaseCfg.dialect !== 'mysql') {
1019+
throw new Error(
1020+
`config: "database.authDateType" in ${CONFIG_FILE} is only supported for MySQL.`,
1021+
);
1022+
}
1023+
}
10031024
} else if (typeof obj.database !== 'string' || !VALID_DATABASE_VALUES.has(obj.database)) {
10041025
throw new Error(
1005-
`config: "database" in ${CONFIG_FILE} must be "pg", "mysql" or an object with "dialect", "casing" and "readReplication".`,
1026+
`config: "database" in ${CONFIG_FILE} must be "pg", "mysql" or an object with "dialect", "casing", "readReplication" or "authDateType".`,
10061027
);
10071028
}
10081029
}
@@ -1137,6 +1158,11 @@ export function getDatabaseCasing(config: VoidConfig): DatabaseCasing | undefine
11371158
return typeof database === 'object' && database !== null ? database.casing : undefined;
11381159
}
11391160

1161+
export function getDatabaseAuthDateType(config: VoidConfig): MySqlAuthDateType | undefined {
1162+
const database = config.database;
1163+
return typeof database === 'object' && database !== null ? database.authDateType : undefined;
1164+
}
1165+
11401166
/**
11411167
* The `database` value for a dialect that keeps the configured casing. Without casing it is
11421168
* the string shorthand, or undefined for the default D1 (SQLite).

‎packages/void/src/plugin-routing.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { syncAuthTypesInProjectTsconfig } from './codegen/project-tsconfig.ts';
2828
import { generateQueueTypes } from './codegen/queue-types.ts';
2929
import { generateRouteTypes } from './codegen/route-types.ts';
3030
import { writeFileIfChanged } from './codegen/write-if-changed.ts';
31-
import { readConfig, getDatabaseDialect } from './config.ts';
31+
import { getDatabaseAuthDateType, getDatabaseDialect, readConfig } from './config.ts';
3232
import type { VoidConfig } from './config.ts';
3333
import { collectPages, collectRevalidate, hasRevalidate } from './isr-config.ts';
3434
import type { VoidMdPlugin } from './pages/islands-plugin.ts';
@@ -317,6 +317,7 @@ export function routingPlugin(
317317
authDatabasePath: join(outDir, 'better-auth-db.ts'),
318318
authSchemaPath: join(outDir, 'better-auth-schema.ts'),
319319
dialect,
320+
authDateType: getDatabaseAuthDateType(config),
320321
providers: config.auth?.providers ?? null,
321322
};
322323
}
@@ -385,6 +386,7 @@ export function routingPlugin(
385386
await import('./auth/drizzle.ts');
386387
const authRuntime: VoidAuthRuntimeOptions = {
387388
dialect: compileOptions.auth.dialect,
389+
authDateType: compileOptions.auth.authDateType,
388390
providers: compileOptions.auth.providers,
389391
userConfig: await loadAuthConfig(compileOptions.auth.authConfigPath),
390392
};

‎packages/void/src/router/compile.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url';
22
import { relative } from 'pathslash';
33
import type { VoidAuthProvider } from '../auth/providers.ts';
44
import type { DevRedirectRule, HeaderRule } from '../cli/types.ts';
5-
import type { NotFoundHandling } from '../config.ts';
5+
import type { MySqlAuthDateType, NotFoundHandling } from '../config.ts';
66
import type { MigrationPlanBundle } from '../migrations/plan.ts';
77
import { createBoundaryManifest } from '../pages/boundary-plans.ts';
88
import { resolveLayoutIds } from '../pages/layout-resolution.ts';
@@ -30,6 +30,7 @@ export type AuthCompileOptions = {
3030
authConfigPath: string | null;
3131
authDatabasePath: string;
3232
authSchemaPath: string;
33+
authDateType?: MySqlAuthDateType;
3334
dialect: 'sqlite' | 'postgresql' | 'mysql';
3435
providers: Array<VoidAuthProvider> | null;
3536
};

0 commit comments

Comments
 (0)