/* * Maakt de promotie-database aan (als die er nog niet is) en voert db/promotie/schema.sql uit. * * npm run db:promotie * * Los van `npm run db:setup`, en dat is het punt: die gooit het schema van de app weg en bouwt * het opnieuw op, want de gegevens van de app zijn wegwerpbaar. De ledenlijst van het * promotieteam is dat niet. Dit script kent geen `drop` en geen seed; het is veilig om te * herhalen en voegt hooguit toe wat nog ontbrak. * * Waarheen: PROMOTIE_DATABASE_URL, standaard postgres://postgres@localhost:5432/promotie. */ import { readFile } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import path from "node:path"; import pg from "pg"; const here = path.dirname(fileURLToPath(import.meta.url)); const url = new URL(process.env.PROMOTIE_DATABASE_URL ?? "postgres://postgres@localhost:5432/promotie"); const dbName = url.pathname.slice(1); /* 1. Database aanmaken indien nodig (via de standaard 'postgres'-database) */ { const admin = new pg.Client({ connectionString: new URL("/postgres", url).toString() }); await admin.connect(); const { rowCount } = await admin.query("select 1 from pg_database where datname = $1", [dbName]); if (rowCount === 0) { await admin.query(`create database "${dbName.replace(/"/g, '""')}"`); console.log(`database ${dbName} aangemaakt`); } else { console.log(`database ${dbName} bestond al — de gegevens blijven staan`); } await admin.end(); } /* 2. Schema uitvoeren en vertellen wat erin staat */ { const client = new pg.Client({ connectionString: url.toString() }); await client.connect(); await client.query(await readFile(path.join(here, "schema.sql"), "utf8")); const { rows } = await client.query( "select count(*) filter (where left_on is null) as actief, count(*) as totaal from promoters" ); console.log(`schema.sql uitgevoerd — ${rows[0].actief} actieve leden, ${rows[0].totaal} in totaal`); await client.end(); }