22 lines
1.3 KiB
TypeScript
22 lines
1.3 KiB
TypeScript
|
|
import mysql from 'mysql2/promise';
|
||
|
|
import { readFileSync, readdirSync } from 'node:fs';
|
||
|
|
import { join } from 'node:path';
|
||
|
|
import '../src/core/config.js';
|
||
|
|
|
||
|
|
/** Legt eine frische Testdatenbank an (niemals die produktive) und wendet alle Migrationen an. */
|
||
|
|
export default async function setup() {
|
||
|
|
const base = { host: process.env.DB_HOST ?? '127.0.0.1', user: process.env.DB_USER!, password: process.env.DB_PASSWORD! };
|
||
|
|
const admin = await mysql.createConnection(base);
|
||
|
|
await admin.query('DROP DATABASE IF EXISTS kundencenter_test');
|
||
|
|
await admin.query('CREATE DATABASE kundencenter_test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
|
||
|
|
await admin.end();
|
||
|
|
const c = await mysql.createConnection({ ...base, database: 'kundencenter_test' });
|
||
|
|
await c.query('CREATE TABLE IF NOT EXISTS schema_migrations (name VARCHAR(200) PRIMARY KEY, applied_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3))');
|
||
|
|
const dir = join(process.cwd(), '../../migrations');
|
||
|
|
for (const f of readdirSync(dir).filter((n) => n.endsWith('.sql')).sort()) {
|
||
|
|
await c.query('INSERT INTO schema_migrations (name) VALUES (?)', [f]);
|
||
|
|
for (const st of readFileSync(join(dir, f), 'utf8').replace(/^\s*--.*$/gm, '').split(/;\s*\n/).map((s) => s.trim()).filter(Boolean)) await c.query(st);
|
||
|
|
}
|
||
|
|
await c.end();
|
||
|
|
}
|