diff --git a/docs/guide/database/mysql.md b/docs/guide/database/mysql.md index 2ec3a9bc9..97f35562e 100644 --- a/docs/guide/database/mysql.md +++ b/docs/guide/database/mysql.md @@ -50,6 +50,14 @@ void db migrate void deploy ``` +### Auth date columns + +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)`. + +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`. + +### Applying migrations on Cloudflare + 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. Only one migration run changes a database at a time, whether it comes from `void db migrate`, `void db reset`, the reset that `void db seed` does before it loads data, `void deploy --platform cloudflare`, or a `void deploy` of any project that uses the database. Better Auth's table changes run inside the same run. Another run waits for it, up to about 20 seconds for a command that connects with `DATABASE_URL` and about 2 minutes for a `void deploy` to the Void platform, then stops with an error that asks you to try again. diff --git a/docs/reference/config.md b/docs/reference/config.md index 6ccea2f5c..440b5d672 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -144,7 +144,7 @@ Database backend. Omit for D1/SQLite (default). Set to `"pg"` or `"mysql"` for a | `"pg"` | PostgreSQL via Hyperdrive; bring your own database | | `"mysql"` | MySQL via Hyperdrive; bring your own database | -Use an object to also set how Drizzle names columns declared without a name: +Use an object to set database options: ```json { @@ -157,6 +157,7 @@ Use an object to also set how Drizzle names columns declared without a name: | `dialect` | `"sqlite"` (default), `"pg"`, `"mysql"` | Database backend. `"sqlite"` is D1 | | `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 | | `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 | +| `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"`. | When using an external database: diff --git a/packages/void/schema.json b/packages/void/schema.json index 05c3da654..486c2043d 100644 --- a/packages/void/schema.json +++ b/packages/void/schema.json @@ -437,10 +437,21 @@ "readReplication": { "type": "boolean", "description": "Enable or disable D1 read replication during deployment. Omit to preserve existing settings; new databases default to replication off." + }, + "authDateType": { + "type": "string", + "enum": ["timestamp", "datetime"], + "description": "MySQL column type for generated auth dates. Defaults to timestamp when omitted." } }, "if": { "required": ["readReplication"] }, "then": { "properties": { "dialect": { "const": "sqlite" } } }, + "allOf": [ + { + "if": { "required": ["authDateType"] }, + "then": { "required": ["dialect"], "properties": { "dialect": { "const": "mysql" } } } + } + ], "additionalProperties": false } ] diff --git a/packages/void/src/auth/drizzle.ts b/packages/void/src/auth/drizzle.ts index 7bca7bfe3..a91b50c43 100644 --- a/packages/void/src/auth/drizzle.ts +++ b/packages/void/src/auth/drizzle.ts @@ -1,6 +1,7 @@ import type { BetterAuthOptions } from 'better-auth'; import { getAuthTables, getSchema as getBetterAuthSchema } from 'better-auth/db'; import type { BetterAuthDBSchema, DBFieldAttribute } from 'better-auth/db'; +import type { MySqlAuthDateType } from '../config.ts'; import type { VoidAuthRuntimeOptions } from '../runtime/auth/better-auth-shared.ts'; import type { VoidAuthConfig } from '../runtime/auth/index.ts'; import { VOID_EMAIL_AUTH_PROVIDER, isVoidSocialAuthProvider } from './providers.ts'; @@ -222,6 +223,7 @@ function createColumnBuilder( defaultFieldName: string, fieldName: string, field: DBFieldAttribute, + authDateType: MySqlAuthDateType, ): string { const useIdType = fieldName === 'id' || field.references?.field === 'id'; @@ -241,7 +243,7 @@ function createColumnBuilder( case 'boolean': return `boolean(${JSON.stringify(fieldName)})`; case 'date': - return `timestamp(${JSON.stringify(fieldName)}, { mode: "date", fsp: 3 })`; + return `${authDateType}(${JSON.stringify(fieldName)}, { mode: "date", fsp: 3 })`; case 'number': return field.bigint ? `bigint(${JSON.stringify(fieldName)}, { mode: "number" })` @@ -331,6 +333,7 @@ function createColumnDefinition( defaultModelName: string, defaultFieldName: string, field: DBFieldAttribute, + authDateType: MySqlAuthDateType, ): string { const actualFieldName = resolveFieldName(defaultFieldName, field); const parts = [ @@ -341,6 +344,7 @@ function createColumnDefinition( defaultFieldName, actualFieldName, field, + authDateType, ), ]; @@ -403,6 +407,7 @@ function collectCoreImports( dialect: 'sqlite' | 'postgresql' | 'mysql', schema: BetterAuthDBSchema, idStrategy: AuthIdStrategy, + authDateType: MySqlAuthDateType, ): Array { const imports = new Set([ dialect === 'postgresql' ? 'pgTable' : dialect === 'mysql' ? 'mysqlTable' : 'sqliteTable', @@ -450,7 +455,9 @@ function collectCoreImports( continue; } if (field.type === 'date') { - imports.add(dialect === 'sqlite' ? 'integer' : 'timestamp'); + imports.add( + dialect === 'sqlite' ? 'integer' : dialect === 'mysql' ? authDateType : 'timestamp', + ); continue; } if (field.type === 'number') { @@ -492,7 +499,8 @@ export function generateVoidAuthDrizzleSchema( : runtime.dialect === 'mysql' ? 'void/schema-mysql' : 'void/schema-d1'; - const imports = collectCoreImports(runtime.dialect, schema, idStrategy); + const authDateType = runtime.authDateType ?? 'timestamp'; + const imports = collectCoreImports(runtime.dialect, schema, idStrategy, authDateType); const lines = [ '// Auto-generated by void — do not edit', `import { ${imports.join(', ')} } from ${JSON.stringify(importPath)};`, @@ -515,6 +523,7 @@ export function generateVoidAuthDrizzleSchema( defaultModelName, 'id', { type: idStrategy === 'serial' ? 'number' : 'string', required: true }, + authDateType, )},`, ...fieldEntries.map(([defaultFieldName, field]) => { const actualFieldName = resolveFieldName(defaultFieldName, field); @@ -527,6 +536,7 @@ export function generateVoidAuthDrizzleSchema( defaultModelName, defaultFieldName, field, + authDateType, )},`; }), ]; diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index 4bd910a9e..f7c587c01 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -1285,7 +1285,7 @@ async function promptStarterMode(starter?: ScaffoldStarterMode): Promise | null; }; diff --git a/packages/void/src/runtime/auth/better-auth-shared.ts b/packages/void/src/runtime/auth/better-auth-shared.ts index ab03df7ee..5e8a24815 100644 --- a/packages/void/src/runtime/auth/better-auth-shared.ts +++ b/packages/void/src/runtime/auth/better-auth-shared.ts @@ -12,6 +12,7 @@ import { } from '../../auth/providers.ts'; import type { VoidAuthProvider, VoidSocialAuthProvider } from '../../auth/providers.ts'; import { Buffer } from '../../cli/node-buffer.ts'; +import type { MySqlAuthDateType } from '../../config.ts'; import { isUnchangedStaticAsset } from '../routing/static-asset-marker.ts'; import { authContext } from './index.ts'; import type { AuthState, VoidAuthConfig } from './index.ts'; @@ -21,6 +22,7 @@ export type VoidAuthDialect = 'sqlite' | 'postgresql' | 'mysql'; export type VoidAuthRuntimeOptions = { dialect: VoidAuthDialect; + authDateType?: MySqlAuthDateType; providers: Array | null; userConfig?: VoidAuthConfig; dev?: boolean; diff --git a/packages/void/test/unit/auth-drizzle.test.ts b/packages/void/test/unit/auth-drizzle.test.ts index a75bcd683..e75039d96 100644 --- a/packages/void/test/unit/auth-drizzle.test.ts +++ b/packages/void/test/unit/auth-drizzle.test.ts @@ -102,13 +102,24 @@ describe('Better Auth Drizzle codegen', () => { expect(code).toContain('"name": "members"'); }); - it('generates MySQL auth tables with native column types', () => { - const code = generateVoidAuthDrizzleSchema({ dialect: 'mysql', providers: null }); + it.each(['timestamp', 'datetime'] as const)('generates MySQL auth dates as %s', (dateType) => { + const code = generateVoidAuthDrizzleSchema({ + dialect: 'mysql', + providers: null, + ...(dateType === 'datetime' && { authDateType: dateType }), + userConfig: { + user: { additionalFields: { birthday: { type: 'date', required: false } } }, + }, + }); - expect(code).toContain('mysqlTable'); - expect(code).toContain('from "void/schema-mysql"'); + expect(code).toContain( + `import { ${['boolean', dateType, 'index', 'mysqlTable', 'text', 'varchar'].sort().join(', ')} } from "void/schema-mysql"`, + ); expect(code).toContain('boolean("emailVerified")'); - expect(code).toContain('timestamp("createdAt", { mode: "date", fsp: 3 })'); + expect(code).toContain( + `"createdAt": ${dateType}("createdAt", { mode: "date", fsp: 3 }).notNull(),`, + ); + expect(code).toContain(`"birthday": ${dateType}("birthday", { mode: "date", fsp: 3 }),`); expect(code).toContain('"dialect": "mysql"'); }); diff --git a/packages/void/test/unit/config.test.ts b/packages/void/test/unit/config.test.ts index 9b39d4b40..f6faaae4c 100644 --- a/packages/void/test/unit/config.test.ts +++ b/packages/void/test/unit/config.test.ts @@ -1604,6 +1604,8 @@ describe('database config', () => { it.each([ [{ dialect: 'pg', casing: 'snake_case' }, 'postgresql', 'snake_case'], [{ dialect: 'mysql', casing: 'camelCase' }, 'mysql', 'camelCase'], + [{ dialect: 'mysql', authDateType: 'datetime' }, 'mysql', undefined], + [{ dialect: 'mysql', authDateType: 'timestamp' }, 'mysql', undefined], [{ dialect: 'sqlite', casing: 'snake_case' }, 'sqlite', 'snake_case'], [{ casing: 'snake_case' }, 'sqlite', 'snake_case'], [{ dialect: 'pg' }, 'postgresql', undefined], @@ -1635,9 +1637,12 @@ describe('database config', () => { [{ readReplication: null }, '"database.readReplication" in void.json must be a boolean'], [{ dialect: 'pg', readReplication: true }, 'only supported for D1 (sqlite)'], [{ dialect: 'mysql', readReplication: false }, 'only supported for D1 (sqlite)'], + [{ dialect: 'mysql', authDateType: 'date' }, 'must be "timestamp" or "datetime"'], + [{ dialect: 'pg', authDateType: 'datetime' }, 'only supported for MySQL'], + [{ authDateType: 'datetime' }, 'only supported for MySQL'], [ { dialect: 'pg', url: 'x' }, - "Unknown key 'database.url' in void.json. Valid: dialect, casing, readReplication.", + "Unknown key 'database.url' in void.json. Valid: dialect, casing, readReplication, authDateType.", ], ])('rejects %j', (database, message) => { setup(JSON.stringify({ database })); @@ -1660,11 +1665,23 @@ describe('database config', () => { const schema = JSON.parse(readFileSync(join(import.meta.dirname, '../../schema.json'), 'utf8')); const [shorthand, object] = schema.properties.database.oneOf; expect(shorthand.enum).toEqual(['pg', 'mysql']); - expect(Object.keys(object.properties)).toEqual(['dialect', 'casing', 'readReplication']); + expect(Object.keys(object.properties)).toEqual([ + 'dialect', + 'casing', + 'readReplication', + 'authDateType', + ]); expect(object.properties.readReplication).toMatchObject({ type: 'boolean' }); expect(object.properties.readReplication).not.toHaveProperty('default'); expect(object.if).toEqual({ required: ['readReplication'] }); expect(object.then).toEqual({ properties: { dialect: { const: 'sqlite' } } }); + expect(object.properties.authDateType.enum).toEqual(['timestamp', 'datetime']); + expect(object.allOf).toEqual([ + { + if: { required: ['authDateType'] }, + then: { required: ['dialect'], properties: { dialect: { const: 'mysql' } } }, + }, + ]); expect(object.properties.dialect.enum).toEqual(['sqlite', 'pg', 'mysql']); expect(object.properties.casing.enum).toEqual(['snake_case', 'camelCase']); expect(object.additionalProperties).toBe(false); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index 543d210a1..ae8bb331b 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -2596,7 +2596,7 @@ describe('isScaffoldableEmptyProject', () => { { value: 'mysql', label: 'MySQL', - hint: 'Scaffolds the same starter with MySQL, a generated migration, a seed file, and writes database: "mysql" to void.config.ts.', + hint: 'Scaffolds the same starter with MySQL, a generated migration, a seed file, and writes MySQL settings to void.config.ts.', }, { value: 'static', @@ -2609,6 +2609,29 @@ describe('isScaffoldableEmptyProject', () => { } }); + it('opts a newly scaffolded MySQL starter into DATETIME auth columns without enabling auth', async () => { + await withTempDirAsync(async (root) => { + await runInitCommand( + root, + parseInitArgs([ + '--framework', + 'react', + '--toolchain', + 'vite', + '--starter', + 'mysql', + '--deploy', + 'none', + '--no-git', + '--no-install', + ]), + ); + const config = readConfig(root); + expect(config.database).toEqual({ dialect: 'mysql', authDateType: 'datetime' }); + expect(config.auth).toBeUndefined(); + }); + }); + it('scaffolds a static Pages starter without database files', async () => { const root = mkdtempSync(join(tmpdir(), 'void-init-')); try { diff --git a/packages/void/test/unit/plugin-routing.test.ts b/packages/void/test/unit/plugin-routing.test.ts index 265ed6cd1..93611f96f 100644 --- a/packages/void/test/unit/plugin-routing.test.ts +++ b/packages/void/test/unit/plugin-routing.test.ts @@ -17,6 +17,7 @@ import { analyzeApplicationSync } from '../../src/application-analysis.ts'; import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts'; // oxlint-disable-next-line import/no-namespace -- The test replaces or spies on members of the module object. import * as authConfig from '../../src/auth/config.ts'; +import { prepareProject } from '../../src/codegen/prepare.ts'; import { ensureProjectTsconfig } from '../../src/codegen/project-tsconfig.ts'; import { readConfig } from '../../src/config.ts'; import { routingPlugin } from '../../src/plugin-routing.ts'; @@ -170,6 +171,30 @@ describe('routingPlugin', () => { ); }); + it.each([ + ['mysql', 'timestamp'], + [{ dialect: 'mysql', authDateType: 'datetime' }, 'datetime'], + ] as const)( + 'prepares and builds the same auth schema with database %j', + async (database, dateType) => { + const root = createTempRoot(); + writeFileSync( + join(root, 'void.json'), + JSON.stringify({ database, auth: { providers: ['email'] } }), + ); + await prepareProject(root); + const schemaPath = join(root, '.void', 'better-auth-schema.ts'); + const prepared = readFileSync(schemaPath, 'utf8'); + expect(prepared).toContain(`"expiresAt": ${dateType}("expiresAt", { mode: "date", fsp: 3 })`); + + const plugin = createRoutingPlugin(root, { isAuthEnabled: () => true }); + resolveConfig(plugin, 'build'); + rmSync(schemaPath); + await runBuildStart(plugin); + expect(readFileSync(schemaPath, 'utf8')).toBe(prepared); + }, + ); + it('uses the configured D1 binding for the auth database', async () => { const root = createTempRoot(); const plugin = createRoutingPlugin(root, {