Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/guide/database/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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:

Expand Down
11 changes: 11 additions & 0 deletions packages/void/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
]
Expand Down
16 changes: 13 additions & 3 deletions packages/void/src/auth/drizzle.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -222,6 +223,7 @@ function createColumnBuilder(
defaultFieldName: string,
fieldName: string,
field: DBFieldAttribute,
authDateType: MySqlAuthDateType,
): string {
const useIdType = fieldName === 'id' || field.references?.field === 'id';

Expand All @@ -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" })`
Expand Down Expand Up @@ -331,6 +333,7 @@ function createColumnDefinition(
defaultModelName: string,
defaultFieldName: string,
field: DBFieldAttribute,
authDateType: MySqlAuthDateType,
): string {
const actualFieldName = resolveFieldName(defaultFieldName, field);
const parts = [
Expand All @@ -341,6 +344,7 @@ function createColumnDefinition(
defaultFieldName,
actualFieldName,
field,
authDateType,
),
];

Expand Down Expand Up @@ -403,6 +407,7 @@ function collectCoreImports(
dialect: 'sqlite' | 'postgresql' | 'mysql',
schema: BetterAuthDBSchema,
idStrategy: AuthIdStrategy,
authDateType: MySqlAuthDateType,
): Array<string> {
const imports = new Set<string>([
dialect === 'postgresql' ? 'pgTable' : dialect === 'mysql' ? 'mysqlTable' : 'sqliteTable',
Expand Down Expand Up @@ -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') {
Expand Down Expand Up @@ -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)};`,
Expand All @@ -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);
Expand All @@ -527,6 +536,7 @@ export function generateVoidAuthDrizzleSchema(
defaultModelName,
defaultFieldName,
field,
authDateType,
)},`;
}),
];
Expand Down
2 changes: 1 addition & 1 deletion packages/void/src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1285,7 +1285,7 @@ async function promptStarterMode(starter?: ScaffoldStarterMode): Promise<Scaffol
{
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',
Expand Down
7 changes: 6 additions & 1 deletion packages/void/src/cli/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,12 @@ export function createPagesStarterTemplate(options: {
const files: PagesStarterTemplate['files'] = {
// Later init steps add `database` and `worker` to this generated config.
'void.config.ts': renderVoidConfig(
{ routing: { typedRoutes: true } },
{
routing: { typedRoutes: true },
...(starterMode === 'mysql' && {
database: { dialect: 'mysql', authDateType: 'datetime' },
}),
},
'// Generated by void init.',
),
[getGeneratedViteConfigPath(packageType)]: getViteConfig(framework, config, toolchain),
Expand Down
3 changes: 2 additions & 1 deletion packages/void/src/codegen/prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { join } from 'pathslash';
import { analyzeApplication } from '../application-routing.ts';
import { loadVoidAuthConfig, projectAuthConfigImporter } from '../auth/config.ts';
import { generateVoidAuthDatabaseModule, generateVoidAuthDrizzleSchema } from '../auth/drizzle.ts';
import { getDatabaseCasing, readConfig } from '../config.ts';
import { getDatabaseAuthDateType, getDatabaseCasing, readConfig } from '../config.ts';
import { discoverSchema } from '../drizzle/discover.ts';
import { loadLocalEnv } from '../shared/env.ts';
import { generateAuthTypes } from './auth-types.ts';
Expand Down Expand Up @@ -121,6 +121,7 @@ export async function prepareProject(root: string): Promise<PrepareProjectResult
if (authEnabled) {
const authRuntime = {
dialect,
authDateType: getDatabaseAuthDateType(config),
providers: config.auth?.providers ?? null,
userConfig: await loadVoidAuthConfig(authConfigPath, projectAuthConfigImporter(root)),
};
Expand Down
32 changes: 29 additions & 3 deletions packages/void/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export type DatabaseDialect = 'sqlite' | 'postgresql' | 'mysql';
/** Drizzle's `casing`: how a column declared without a name is named in the database. */
export type DatabaseCasing = 'snake_case' | 'camelCase';

export type MySqlAuthDateType = 'timestamp' | 'datetime';

/** Object form of `database`, for options next to the dialect. */
export type DatabaseConfig = {
/** Database backend. Defaults to `"sqlite"` (D1). */
Expand All @@ -27,6 +29,8 @@ export type DatabaseConfig = {
casing?: DatabaseCasing;
/** Enable or disable D1 read replication during deployment. Omit to preserve existing settings. */
readReplication?: boolean;
/** MySQL column type for generated auth dates. Defaults to "timestamp" for existing projects. */
authDateType?: MySqlAuthDateType;
};

/** Curated Worker fields accepted by the `worker` config field. */
Expand Down Expand Up @@ -965,9 +969,14 @@ function validateConfigObject(obj: unknown): VoidConfig {
if (isRecord(obj.database)) {
const databaseCfg = obj.database;
for (const key of Object.keys(databaseCfg)) {
if (key !== 'dialect' && key !== 'casing' && key !== 'readReplication') {
if (
key !== 'dialect' &&
key !== 'casing' &&
key !== 'readReplication' &&
key !== 'authDateType'
) {
throw new Error(
`config: Unknown key 'database.${key}' in ${CONFIG_FILE}. Valid: dialect, casing, readReplication.`,
`config: Unknown key 'database.${key}' in ${CONFIG_FILE}. Valid: dialect, casing, readReplication, authDateType.`,
);
}
}
Expand Down Expand Up @@ -1000,9 +1009,21 @@ function validateConfigObject(obj: unknown): VoidConfig {
);
}
}
if (databaseCfg.authDateType !== undefined) {
if (databaseCfg.authDateType !== 'timestamp' && databaseCfg.authDateType !== 'datetime') {
throw new Error(
`config: "database.authDateType" in ${CONFIG_FILE} must be "timestamp" or "datetime".`,
);
}
if (databaseCfg.dialect !== 'mysql') {
throw new Error(
`config: "database.authDateType" in ${CONFIG_FILE} is only supported for MySQL.`,
);
}
}
} else if (typeof obj.database !== 'string' || !VALID_DATABASE_VALUES.has(obj.database)) {
throw new Error(
`config: "database" in ${CONFIG_FILE} must be "pg", "mysql" or an object with "dialect", "casing" and "readReplication".`,
`config: "database" in ${CONFIG_FILE} must be "pg", "mysql" or an object with "dialect", "casing", "readReplication" or "authDateType".`,
);
}
}
Expand Down Expand Up @@ -1137,6 +1158,11 @@ export function getDatabaseCasing(config: VoidConfig): DatabaseCasing | undefine
return typeof database === 'object' && database !== null ? database.casing : undefined;
}

export function getDatabaseAuthDateType(config: VoidConfig): MySqlAuthDateType | undefined {
const database = config.database;
return typeof database === 'object' && database !== null ? database.authDateType : undefined;
}

/**
* The `database` value for a dialect that keeps the configured casing. Without casing it is
* the string shorthand, or undefined for the default D1 (SQLite).
Expand Down
4 changes: 3 additions & 1 deletion packages/void/src/plugin-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { syncAuthTypesInProjectTsconfig } from './codegen/project-tsconfig.ts';
import { generateQueueTypes } from './codegen/queue-types.ts';
import { generateRouteTypes } from './codegen/route-types.ts';
import { writeFileIfChanged } from './codegen/write-if-changed.ts';
import { readConfig, getDatabaseDialect } from './config.ts';
import { getDatabaseAuthDateType, getDatabaseDialect, readConfig } from './config.ts';
import type { VoidConfig } from './config.ts';
import { collectPages, collectRevalidate, hasRevalidate } from './isr-config.ts';
import type { VoidMdPlugin } from './pages/islands-plugin.ts';
Expand Down Expand Up @@ -317,6 +317,7 @@ export function routingPlugin(
authDatabasePath: join(outDir, 'better-auth-db.ts'),
authSchemaPath: join(outDir, 'better-auth-schema.ts'),
dialect,
authDateType: getDatabaseAuthDateType(config),
providers: config.auth?.providers ?? null,
};
}
Expand Down Expand Up @@ -385,6 +386,7 @@ export function routingPlugin(
await import('./auth/drizzle.ts');
const authRuntime: VoidAuthRuntimeOptions = {
dialect: compileOptions.auth.dialect,
authDateType: compileOptions.auth.authDateType,
providers: compileOptions.auth.providers,
userConfig: await loadAuthConfig(compileOptions.auth.authConfigPath),
};
Expand Down
3 changes: 2 additions & 1 deletion packages/void/src/router/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url';
import { relative } from 'pathslash';
import type { VoidAuthProvider } from '../auth/providers.ts';
import type { DevRedirectRule, HeaderRule } from '../cli/types.ts';
import type { NotFoundHandling } from '../config.ts';
import type { MySqlAuthDateType, NotFoundHandling } from '../config.ts';
import type { MigrationPlanBundle } from '../migrations/plan.ts';
import { createBoundaryManifest } from '../pages/boundary-plans.ts';
import { resolveLayoutIds } from '../pages/layout-resolution.ts';
Expand Down Expand Up @@ -30,6 +30,7 @@ export type AuthCompileOptions = {
authConfigPath: string | null;
authDatabasePath: string;
authSchemaPath: string;
authDateType?: MySqlAuthDateType;
dialect: 'sqlite' | 'postgresql' | 'mysql';
providers: Array<VoidAuthProvider> | null;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/void/src/runtime/auth/better-auth-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -21,6 +22,7 @@ export type VoidAuthDialect = 'sqlite' | 'postgresql' | 'mysql';

export type VoidAuthRuntimeOptions = {
dialect: VoidAuthDialect;
authDateType?: MySqlAuthDateType;
providers: Array<VoidAuthProvider> | null;
userConfig?: VoidAuthConfig;
dev?: boolean;
Expand Down
21 changes: 16 additions & 5 deletions packages/void/test/unit/auth-drizzle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"');
});

Expand Down
21 changes: 19 additions & 2 deletions packages/void/test/unit/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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 }));
Expand All @@ -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);
Expand Down
Loading