# All files / src/db ensure-schema.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 2/2
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39

    24x

    239x

    239x

    239x
    239x
    239x

     /**
     * 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 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));
      // From src/db/ or dist/db/, go up two levels to package root, then into drizzle/
      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');
    }