import { drizzle } from 'drizzle-orm/postgres-js'; import { migrate } from 'drizzle-orm/postgres-js/migrator'; import postgres from 'postgres'; /** Creates the test database if needed and applies migrations, once per run. */ export async function setup() { const url = new URL(process.env.TEST_DATABASE_URL ?? 'postgres://musicshare:musicshare@localhost:5447/musicshare_test'); const dbName = url.pathname.slice(1); if (!dbName.endsWith('_test')) throw new Error(`Refusing to use non-test database "${dbName}"`); const admin = postgres({ ...parse(url), database: 'postgres', max: 1, onnotice: () => {} }); const [exists] = await admin`select 1 from pg_database where datname = ${dbName}`; if (!exists) await admin.unsafe(`create database "${dbName}"`); await admin.end(); const sql = postgres(url.toString(), { max: 1, onnotice: () => {} }); await migrate(drizzle(sql), { migrationsFolder: new URL('../drizzle', import.meta.url).pathname }); await sql.end(); } function parse(url: URL) { return { host: url.hostname, port: Number(url.port || 5432), username: decodeURIComponent(url.username), password: decodeURIComponent(url.password), }; }