/* * Copyright (c) 2026 by Christian Kellner. * Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause */ /** * Migration Runner for better-sqlite3 * I know there are external libs out there, but * a) most of them are pretty bloated * b) I wanted to have something that fit's this limited use-case * c) I was searching for justifications anyway to build a migration system on my own. Don't judge me ;) * * Executes all migration files in lib/services/storage/migrations/sql in natural order. * Each migration runs in its own transaction. If a migration fails, only that * migration is rolled back and the process stops with a non-zero exit code. * Already applied migrations are skipped using the schema_migrations table. * * Usage: * CLI: yarn run migratedb * Programmatic: * import { runMigrations } from './lib/services/storage/migrations/migrate.js'; * await runMigrations(); * * Migration file format (example: lib/services/storage/migrations/sql/1.add-users.js): * export function up(db) { * db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"); * } * */ import fs from 'fs'; import path from 'path'; import { pathToFileURL } from 'url'; import crypto from 'crypto'; import SqliteConnection from '../SqliteConnection.js'; import logger from '../../logger.js'; const ROOT = path.resolve('.'); /** * Absolute path to the migrations directory (lib/services/storage/migrations/sql). * @type {string} */ export const MIGRATIONS_DIR = path.join(ROOT, 'lib', 'services', 'storage', 'migrations', 'sql'); /** * Ensures that the given directory exists, creating it recursively if needed. * @param {string} p - Path to the directory. */ function ensureDir(p) { if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true }); } /** * Lists all migration files in the migrations directory. * Migration files must follow the format: .