NGU-Web/server/src/admin-schema-sync.js
Zaldimmar 5274e09571 Clean up code found in the audit
- Replace every em-dash in src and server/src with a colon, comma or hyphen
- Give every relative import its file extension (.jsx imports of .tsx fixed)
- Delete old-historyMock.ts, unused exports, unused CSS utilities, the
  unused @ alias and the fallback option nothing passed
- One copy each of initials, capitalize, byName and the server's marks()
- Move the organization, chapter and event hooks from src/data to src/lib
- Schema sync always throws on a mismatch (strict was never turned off)
- Replace the placeholder README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 22:02:03 -05:00

143 lines
4.9 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
DESCRIPTOR / SCHEMA RECONCILIATION
The CRUD engine trusts admin-schema.js about which fields are
required. The database is the one that actually enforces it. When
those two disagree the gap shows up as a 500 on somebody's save,
which is how organizations.country was found.
Run this once at boot. For every table a descriptor touches it
compares the declared columns against PRAGMA table_info and:
- marks a descriptor column required when the table says
NOT NULL with no DEFAULT, so validation catches it as a named
field instead of SQLite catching it as a 500;
- reports a descriptor column the table doesn't have;
- reports a NOT NULL, no-DEFAULT column that no descriptor
column and no engine-supplied column covers: nothing can
ever set it, so every insert through the admin will fail.
The first is a silent repair. The other two are deployment bugs,
so they stop the service starting rather
than waiting to surface one row at a time.
═══════════════════════════════════════════════════════════════ */
function tableMeta(db, table) {
const rows = db.prepare(`PRAGMA table_info(${table})`).all();
if (!rows.length) return null;
const meta = new Map();
for (const row of rows) {
meta.set(row.name, {
// A NOT NULL column with no default and no engine to fill it
// has to arrive in the payload or the insert dies.
mustSupply: row.notnull === 1 && row.dflt_value === null && row.pk === 0,
notNullable: row.notnull === 1 && row.pk === 0,
});
}
return meta;
}
/* Every table the descriptor writes to, with the columns it
declares and the ones the engine fills in on its own. */
function collectGroups(entity) {
const groups = [
{
table: entity.table,
columns: entity.columns ?? [],
engineSupplied: [entity.idColumn],
},
];
for (const ext of entity.extensions ?? []) {
groups.push({
table: ext.table,
columns: ext.columns ?? [],
// An extension is keyed either by the parent's own id or by an
// owner block, the same one children use. Both sets of columns
// are filled in by the engine, never by the form.
engineSupplied: [
ext.idColumn,
ext.owner?.column,
ext.owner?.kindColumn,
...(ext.touch ? ["updated_at"] : []),
].filter(Boolean),
});
}
const walk = (child) => {
groups.push({
table: child.table,
columns: child.columns ?? [],
engineSupplied: [
child.owner.column,
child.owner.kindColumn,
"sort_order",
...Object.keys(child.owner.inherit ?? {}),
].filter(Boolean),
});
for (const nested of child.children ?? []) walk(nested);
};
for (const child of entity.children ?? []) walk(child);
return groups;
}
export function syncDescriptorsWithSchema(db, entities) {
const list = Array.isArray(entities) ? entities.map((e) => [e.name ?? e.table, e]) : Object.entries(entities);
const inferred = [];
const problems = [];
for (const [name, entity] of list) {
for (const group of collectGroups(entity)) {
const meta = tableMeta(db, group.table);
if (!meta) {
problems.push(`${name}: table "${group.table}" does not exist.`);
continue;
}
const declared = new Set(group.columns.map((column) => column.name));
for (const column of group.columns) {
const info = meta.get(column.name);
if (!info) {
problems.push(
`${name}: ${group.table}.${column.name} is in the descriptor but not in the table.`,
);
continue;
}
if (info.mustSupply && !column.required) {
column.required = true;
inferred.push(`${name}: ${group.table}.${column.name}`);
}
if (info.notNullable) column.notNullable = true;
}
for (const [columnName, info] of meta) {
if (!info.mustSupply) continue;
if (declared.has(columnName)) continue;
if (group.engineSupplied.includes(columnName)) continue;
problems.push(
`${name}: ${group.table}.${columnName} is NOT NULL with no default, ` +
`but no descriptor column covers it, so every insert will fail.`,
);
}
}
}
if (inferred.length) {
console.warn(
`[admin-schema] marked required from the schema (add required: true to the descriptor):\n ${inferred.join("\n ")}`,
);
}
if (problems.length) {
const report = `[admin-schema] descriptor does not match the database:\n ${problems.join("\n ")}`;
throw new Error(report);
}
return { inferred, problems };
}