Files
Codewalkers/apps/server/db/ensure-schema.ts
Lukas May b11cae998c refactor: Co-locate server artifacts under apps/server/
Move drizzle/, dist/, and coverage/ into apps/server/ so all
server-specific artifacts live alongside the source they belong to.

- git mv drizzle/ → apps/server/drizzle/
- drizzle.config.ts: out → ./apps/server/drizzle
- tsconfig.json: outDir → ./apps/server/dist, exclude drizzle dir
- package.json: main/bin/clean point to apps/server/dist/
- vitest.config.ts: reportsDirectory → ./apps/server/coverage
- .gitignore: add coverage/ entry
- ensure-schema.ts: update getMigrationsPath() for new layout
- docs/database-migrations.md: update drizzle/ references
2026-03-03 11:55:12 +01:00

43 lines
1.4 KiB
TypeScript

/**
* Database Migration
*
* Runs drizzle-kit migrations from the drizzle/ directory.
* Safe to call on every startup - only applies pending migrations.
*/
import { migrate } from 'drizzle-orm/better-sqlite3/migrator';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { existsSync } from 'node:fs';
import type { DrizzleDatabase } from './index.js';
import { createModuleLogger } from '../logger/index.js';
const log = createModuleLogger('db');
/**
* Resolve the migrations directory relative to the package root.
* Works both in development (src/) and after build (dist/).
*/
function getMigrationsPath(): string {
const currentDir = dirname(fileURLToPath(import.meta.url));
// Dev: apps/server/db/ → 1 up → apps/server/drizzle/
// Dist: apps/server/dist/db/ → 2 up → apps/server/drizzle/
const upOne = join(currentDir, '..', 'drizzle');
if (existsSync(upOne)) return upOne;
return join(currentDir, '..', '..', 'drizzle');
}
/**
* Run all pending database migrations.
*
* Uses drizzle-kit's migration system which tracks applied migrations
* in a __drizzle_migrations table. Safe to call on every startup.
*
* @param db - Drizzle database instance
*/
export function ensureSchema(db: DrizzleDatabase): void {
log.info('applying database migrations');
migrate(db, { migrationsFolder: getMigrationsPath() });
log.info('database migrations complete');
}