69 lines
2.2 KiB
JavaScript
69 lines
2.2 KiB
JavaScript
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
|
|
const root = path.resolve(import.meta.dirname, '..');
|
|
const schemaPath = path.join(root, 'database/schema.sql');
|
|
const columnSql = ' activated_at DATETIME NULL';
|
|
|
|
function hasActivatedAt(schema) {
|
|
return /\bactivated_at\s+DATETIME\s+NULL\b/i.test(schema);
|
|
}
|
|
|
|
function splitRouteTableBody(body) {
|
|
const lines = body.split('\n');
|
|
const trailing = [];
|
|
while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
|
|
trailing.unshift(lines.pop());
|
|
}
|
|
return { lines, trailing };
|
|
}
|
|
|
|
function isTableConstraint(line) {
|
|
return /^\s*,?\s*(?:PRIMARY\s+KEY|CONSTRAINT|FOREIGN\s+KEY|UNIQUE\s*\()/i.test(line);
|
|
}
|
|
|
|
function hasLeadingComma(line) {
|
|
return /^\s*,/.test(line);
|
|
}
|
|
|
|
function ensureCommaBeforeInsert(lines, targetIndex) {
|
|
const previousIndex = targetIndex - 1;
|
|
if (previousIndex < 0) return;
|
|
const previous = lines[previousIndex].trimEnd();
|
|
if (!previous.endsWith(',')) lines[previousIndex] = `${previous},`;
|
|
}
|
|
|
|
function columnForTarget(lines, insertBefore) {
|
|
if (insertBefore === -1) return columnSql;
|
|
return hasLeadingComma(lines[insertBefore]) ? columnSql : `${columnSql},`;
|
|
}
|
|
|
|
function insertActivatedAt(schema) {
|
|
if (hasActivatedAt(schema)) return schema;
|
|
|
|
const routeTable = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?routes\s*\((?<body>[\s\S]*?)\);/i.exec(schema);
|
|
if (!routeTable?.groups?.body) {
|
|
throw new Error('Die routes-Tabelle wurde in database/schema.sql nicht gefunden.');
|
|
}
|
|
|
|
const tableSql = routeTable[0];
|
|
const body = routeTable.groups.body;
|
|
const { lines, trailing } = splitRouteTableBody(body);
|
|
const insertBefore = lines.findIndex(isTableConstraint);
|
|
const targetIndex = insertBefore === -1 ? lines.length : insertBefore;
|
|
|
|
ensureCommaBeforeInsert(lines, targetIndex);
|
|
lines.splice(targetIndex, 0, columnForTarget(lines, insertBefore));
|
|
|
|
return schema.replace(tableSql, tableSql.replace(body, [...lines, ...trailing].join('\n')));
|
|
}
|
|
|
|
const schema = await fs.readFile(schemaPath, 'utf8');
|
|
const next = insertActivatedAt(schema);
|
|
if (next === schema) {
|
|
console.log('database/schema.sql enthält activated_at bereits.');
|
|
} else {
|
|
await fs.writeFile(schemaPath, next);
|
|
console.log('database/schema.sql wurde um routes.activated_at ergänzt.');
|
|
}
|