#!/usr/bin/env node import { promises as fs, mkdirSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import Database from 'better-sqlite3' import { Kysely, SqliteDialect } from 'kysely' import { FileMigrationProvider, Migrator } from 'kysely/migration' const migration_folder = fileURLToPath( new URL('../migrations', import.meta.url) ) // this script ships with the deploy and runs on the server before the app // starts, so it can't import the app's bundled db helper — build the same // connection inline from the two runtime deps the app already depends on function create_db(db_path = 'app.db'): Kysely> { if (db_path !== ':memory:') mkdirSync(path.dirname(db_path), { recursive: true }) const sqlite = new Database(db_path) sqlite.pragma('journal_mode = WAL') return new Kysely({ dialect: new SqliteDialect({ database: sqlite }) }) } async function main() { const db = create_db(process.env.DATABASE_PATH) const migrator = new Migrator({ db, provider: new FileMigrationProvider({ fs, path, migrationFolder: migration_folder }) }) const { error, results } = await migrator.migrateToLatest() for (const r of results ?? []) { if (r.status === 'Success') { console.log(`done ${r.migrationName}`) } else if (r.status === 'Error') { console.error(`failed ${r.migrationName}`) } } await db.destroy() if (error) { console.error('migration failed:', error) process.exit(1) } } main()