Skip to content
Open
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
6 changes: 5 additions & 1 deletion docs/reference/cli/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ outline: deep

## `void db push` {#void-db-push}

Apply your Drizzle schema directly to the development database without creating migration files. D1 updates the local database; PostgreSQL and MySQL use `DATABASE_URL` from `.env`.
Apply your Drizzle schema directly to the development database without creating migration files. D1 updates the local database. PostgreSQL and MySQL use `DATABASE_URL` from `.env`.

Schema changes that need confirmation require an interactive terminal. Selecting `No, abort` exits with a nonzero status.

Use this for quick schema iteration while prototyping. Before deploying, generate and review migration files with `void db generate`.

Expand All @@ -17,6 +19,8 @@ Generate SQL migration files from schema changes.

Compares your schema with the last Drizzle snapshot and writes migrations under `db/migrations/`. It includes Void-managed auth tables and configured auth plugins, even without an application schema. Review and commit the generated files before deploying.

Rename prompts require an interactive terminal. The command exits with a nonzero status if a prompt cannot open or is cancelled.

For SQLite, Void checks that the migration history applies to a fresh database. If generation fails this check, the previous SQL, snapshots, and journal are restored. If an existing migration fails, repair that unapplied migration first: rerunning generation compares snapshots and does not repair existing SQL. This check does not verify that a migration preserves existing data; review table rebuilds and foreign-key actions carefully.

## `void db status` {#void-db-status}
Expand Down
85 changes: 70 additions & 15 deletions packages/void/src/cli/db.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { execFileSync } from 'node:child_process';
import { spawnSync } from 'node:child_process';
import {
existsSync,
mkdirSync,
Expand Down Expand Up @@ -100,18 +100,75 @@ function configuredD1Binding(root: string): string {
return resolveBindingNames(readConfig(root).inference?.bindings)?.d1 ?? 'DB';
}

function runDrizzleKit(root: string, args: Array<string>): void {
execFileSync(process.execPath, [drizzleKitBin, ...args], {
cwd: root,
stdio: 'inherit',
});
const DRIZZLE_UNCHANGED = 2;

// Drizzle Kit 0.31 can exit 0 after an error or an aborted prompt.
const DRIZZLE_COMPLETION_SCRIPT = String.raw`
const { stripVTControlCharacters } = require('node:util');
const generating = process.argv[2] === 'generate';
const noChanges = generating ? 'No schema changes, nothing to migrate 😴' : '[i] No changes detected';
const migrationWritten = /^\[✓\] Your SQL migration file ➜ .+\.sql 🚀$/su;

let result = 1;
function recordCompletion(chunk) {
if (typeof chunk !== 'string') return;
const line = stripVTControlCharacters(chunk).trim();
if (line === noChanges) {
result = ${DRIZZLE_UNCHANGED};
} else if (generating ? migrationWritten.test(line) : line === '[✓] Changes applied') {
result = 0;
}
}

const write = process.stdout.write.bind(process.stdout);
process.stdout.write = (chunk, ...args) => {
recordCompletion(chunk);
return write(chunk, ...args);
};

const log = console.log.bind(console);
console.log = (...args) => {
if (args.length === 1) recordCompletion(args[0]);
return log(...args);
};

process.on('exit', (code) => {
process.exitCode = code === 0 ? result : 1;
});

require(process.argv[1]);
`;

function runDrizzleKit(
root: string,
command: 'push' | 'generate' | 'studio',
configPath: string,
): void {
const args = [drizzleKitBin, command, '--config', configPath];
const { status, error } = spawnSync(
process.execPath,
command === 'studio'
? args
: ['--input-type=commonjs', '--eval', DRIZZLE_COMPLETION_SCRIPT, '--', ...args],
{ cwd: root, stdio: 'inherit' },
);
if (error || (status !== 0 && (command === 'studio' || status !== DRIZZLE_UNCHANGED))) {
if (command === 'push') {
console.error(
'Database schema push did not complete. For prompts, run `void db push` in a terminal. To review changes, use `void db generate` and `void db migrate`.',
);
}
throw error ?? new Error(`Drizzle Kit ${command} did not complete.`);
}
if (command === 'push' && status === 0) {
printSuccess('Database schema pushed.');
}
}

/**
* Run a drizzle-kit command against a real database URL. The config holding
* the URL lives in a private temp directory outside the project and is
* removed afterwards. Exits with code 1 when drizzle-kit fails; it has
* already printed its own error.
* removed afterwards.
*/
async function runDrizzleKitWithDatabaseUrl(
root: string,
Expand All @@ -122,7 +179,7 @@ async function runDrizzleKitWithDatabaseUrl(
const { withPrivateDrizzleConfig } = await import('../drizzle/config.ts');
const succeeded = withPrivateDrizzleConfig(root, url, dialect, (configPath) => {
try {
runDrizzleKit(root, [command, '--config', configPath]);
runDrizzleKit(root, command, configPath);
return true;
} catch {
return false;
Expand Down Expand Up @@ -401,7 +458,6 @@ async function runPush(root: string, dialect: DatabaseDialect): Promise<void> {
if (dialect !== 'sqlite') {
const url = getLocalDatabaseUrl(root, dialect);
await runDrizzleKitWithDatabaseUrl(root, url, dialect, 'push');
printSuccess('Database schema pushed.');
return;
}

Expand All @@ -411,11 +467,10 @@ async function runPush(root: string, dialect: DatabaseDialect): Promise<void> {
const configPath = writeDrizzleConfig(root, dbPath);

try {
runDrizzleKit(root, ['push', '--config', configPath]);
runDrizzleKit(root, 'push', configPath);
} catch {
process.exit(1);
}
printSuccess('Database schema pushed.');
}

async function runGenerate(root: string, dialect: DatabaseDialect): Promise<void> {
Expand All @@ -437,10 +492,10 @@ async function runGenerate(root: string, dialect: DatabaseDialect): Promise<void
if (dialect === 'sqlite') {
const { generateValidatedSqliteMigrations } = await import('../drizzle/generate.ts');
await generateValidatedSqliteMigrations(readProjectPaths(root).migrationsDir, () => {
runDrizzleKit(root, ['generate', '--config', configPath]);
runDrizzleKit(root, 'generate', configPath);
});
} else {
runDrizzleKit(root, ['generate', '--config', configPath]);
runDrizzleKit(root, 'generate', configPath);
}
} catch (error) {
log.error(getErrorMessage(error));
Expand Down Expand Up @@ -1786,7 +1841,7 @@ async function runStudio(root: string, dialect: DatabaseDialect, remote?: boolea

log.info('Opening Drizzle Studio...');
try {
runDrizzleKit(root, ['studio', '--config', configPath]);
runDrizzleKit(root, 'studio', configPath);
} catch {
process.exit(1);
}
Expand Down
7 changes: 7 additions & 0 deletions packages/void/src/drizzle/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ export const PLACEHOLDER_DB_URL: Record<DrizzleDialect, string> = {
mysql: 'mysql://dummy',
};

const PUSH_TABLES_FILTER: Record<DrizzleDialect, Array<string>> = {
sqlite: ['!_void_migrations', '!_migrations'],
postgresql: ['!_void_migrations'],
mysql: ['!_void_migrations', '!_void_migration_lock'],
};

/**
* Write a temporary drizzle-kit config, by default to `.void/drizzle.config.json`.
* Schema and migration paths are relative to the project root: drizzle-kit
Expand Down Expand Up @@ -54,6 +60,7 @@ export function writeDrizzleConfig(
...(casing ? { casing } : {}),
schema: schemaPaths.length === 1 ? schemaPaths[0] : schemaPaths,
out: `./${relative(root, paths.migrationsDir)}`,
tablesFilter: PUSH_TABLES_FILTER[dialect],
migrations: { prefix: 'timestamp' },
dbCredentials: { url: dbPath },
};
Expand Down
7 changes: 6 additions & 1 deletion packages/void/src/drizzle/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,10 @@ export async function generateValidatedSqliteMigrations(

const existed = existsSync(migrationsDir);
const previous = snapshotFiles(migrationsDir);
let generated = false;
try {
generate();
generated = true;
(await openMigrationValidationDatabase(collectMigrations(migrationsDir))).close();
} catch (cause) {
if (!existed) {
Expand All @@ -105,9 +107,12 @@ export async function generateValidatedSqliteMigrations(
writeFileSync(path, contents);
}
}
const advice = generated
? ' Review the schema change before retrying. For additive changes, use an additive migration rather than rebuilding existing tables.'
: '';
throw new Error(
`${cause instanceof Error ? cause.message : String(cause)}\n` +
'Migration generation failed; previous SQL, snapshots and journal were restored. Review the schema change before retrying. For additive changes, use an additive migration rather than rebuilding existing tables.',
`Migration generation failed. The previous SQL, snapshots and journal were restored.${advice}`,
{ cause },
);
}
Expand Down
24 changes: 15 additions & 9 deletions packages/void/test/unit/db-commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import { toSlash } from 'pathslash';
import { afterEach, beforeEach, describe, it, expect, vi } from 'vite-plus/test';
import type { MockInstance } from 'vite-plus/test';

const mockExecFileSync = vi.hoisted(() =>
vi.fn<(...args: Array<unknown>) => string | Buffer | undefined>(),
const mockSpawnSync = vi.hoisted(() =>
vi.fn<(file: string, args: Array<string>, options: unknown) => { status: number }>(() => ({
status: 0,
})),
);
const mockPgQuery = vi.hoisted(() =>
vi.fn(async (_sql: string) => ({ rows: [] as Array<Record<string, unknown>> })),
Expand All @@ -30,7 +32,7 @@ const mockRunMigrations = vi.fn<typeof import('../../src/migrations/runner.ts').
const mockWriteJournal = vi.fn<typeof import('../../src/migrations/collect.ts').writeJournal>();

vi.mock('node:child_process', () => ({
execFileSync: (...args: Parameters<typeof mockExecFileSync>) => mockExecFileSync(...args),
spawnSync: (...args: Parameters<typeof mockSpawnSync>) => mockSpawnSync(...args),
}));

vi.mock('pg', async (importOriginal) => {
Expand Down Expand Up @@ -254,7 +256,7 @@ describe('void db drizzle-kit subprocesses', () => {

afterEach(() => {
vi.restoreAllMocks();
mockExecFileSync.mockReset();
mockSpawnSync.mockReset();
mockGetMiniflareDatabasePath.mockReset();
for (const root of rootsToClean.splice(0, rootsToClean.length)) {
rmSync(root, { recursive: true, force: true });
Expand All @@ -266,10 +268,10 @@ describe('void db drizzle-kit subprocesses', () => {

await runDbCommand(root, { action: 'generate' });

expect(mockExecFileSync).toHaveBeenCalledTimes(1);
const [command, args, options] = mockExecFileSync.mock.calls[0];
expect(mockSpawnSync).toHaveBeenCalledTimes(1);
const [command, args, options] = mockSpawnSync.mock.calls[0];
expect(command).toBe(process.execPath);
expect(args).toEqual([
expect(args.slice(-4)).toEqual([
expect.stringContaining(toSlash(join('drizzle-kit', 'bin.cjs'))),
'generate',
'--config',
Expand Down Expand Up @@ -299,14 +301,18 @@ describe('void db drizzle-kit subprocesses', () => {
it('rejects invalid generated SQLite SQL and restores migration artifacts', async () => {
const root = createDrizzleProjectRoot();
const migrations = join(root, 'db', 'migrations');
mockExecFileSync.mockImplementation(() => {
mockSpawnSync.mockImplementationOnce(() => {
mkdirSync(join(migrations, 'meta'), { recursive: true });
writeFileSync(join(migrations, '0000.sql'), 'THIS IS NOT SQL;');
writeFileSync(join(migrations, 'meta', '_journal.json'), '{}');
return { status: 0 };
});

await expect(runDbCommand(root, { action: 'generate' })).rejects.toThrow('process.exit:1');
expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('0000.sql'));
expect(mockLog.error).toHaveBeenCalledWith(
expect.stringContaining('Review the schema change before retrying.'),
);
expect(existsSync(migrations)).toBe(false);
});

Expand All @@ -322,7 +328,7 @@ describe('void db drizzle-kit subprocesses', () => {

const config = JSON.parse(readFileSync(join(root, '.void', 'drizzle.config.json'), 'utf8'));
expect(config.schema).toBe('./.void/better-auth-schema.ts');
expect(mockExecFileSync).toHaveBeenCalledOnce();
expect(mockSpawnSync).toHaveBeenCalledOnce();
});

it('resolves function-based Better Auth schemas with local env values', async () => {
Expand Down
Loading