import pg from 'pg'; import { Kysely, PostgresDialect } from 'kysely'; import { Migrator } from 'kysely/migration'; import migrations from './migrations/index.js'; export const MIN_SERVER_VERSION_NUM = 180000; // Erzeugt Pool + Kysely-Instanz. `searchPath` (optional) setzt das Schema, z. B. für Tests. export const createDb = ({ url, poolMax = 10, searchPath })=>{ const pool = new pg.Pool({ connectionString : url, max : poolMax, ...(searchPath ? { options: `-c search_path=${searchPath}` } : {}) }); const db = new Kysely({ dialect: new PostgresDialect({ pool }) }); return { pool, db }; }; export const checkServerVersion = async (pool)=>{ const { rows } = await pool.query('SHOW server_version_num'); const num = parseInt(rows[0].server_version_num, 10); if(num < MIN_SERVER_VERSION_NUM) throw new Error(`PostgreSQL ≥ 18 erforderlich, Server meldet server_version_num=${num}`); return num; }; // Kysely sperrt über die eigene Lock-Tabelle, parallele Starts migrieren nicht gleichzeitig. export const migrateToLatest = async (db)=>{ const migrator = new Migrator({ db, provider: { getMigrations: async ()=>migrations } }); const { error, results } = await migrator.migrateToLatest(); for (const r of results ?? []) console.log(`Migration ${r.migrationName}: ${r.status}`); if(error) throw error; };