mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
feat(db): move a SQLite install into an empty Postgres database
npm run db:move-to-postgres (dist/move-to-postgres.js in the image) copies a SQLite file at this build's migration level into an empty Postgres database. It refuses a file at another level, rows whose references point at nothing and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap, then in one transaction copies every table in foreign key order (setting a self-reference once its rows are in), converts each value to its column's type and refuses one Postgres cannot hold exactly, copies each plugin's plugin.db into its schema, moves the sequences past the copied ids and compares every table's row count and an order-free checksum over all rows before it commits. A failure drops the schema again. The SQLite files and the uploads are never written.
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
import { SqliteSource, type SqliteColumn, type SqliteIndex } from '../../sqlite/sqlite-source';
|
||||
import { isPluginId, pluginSchemaName, quotePluginSchema } from '../plugin-schema';
|
||||
import { portableDefault } from '../schema-adjust';
|
||||
import { inOrder, quoteIdentifier, run, type CopiedSequence, type TableSpec, type Trx } from './copy';
|
||||
import type { ColumnKind } from './values';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* A plugin's own database (`db:own`) moved from its `plugin.db` file into the
|
||||
* schema TREK gives it on Postgres (`plugin-schema.ts`), so a plugin finds its
|
||||
* rows where the Postgres store (`plugin-data-store.ts`) reads them.
|
||||
*
|
||||
* A plugin's tables are its own, created by its own SQL, so the move derives
|
||||
* each Postgres table from the SQLite one: the column's type from SQLite's
|
||||
* type affinity (and from the values it holds where the affinity leaves it
|
||||
* open), NOT NULL, the primary key, a default that has a Postgres spelling,
|
||||
* and the indexes over plain columns. The plugin's migration record
|
||||
* (`_plugin_migrations`) is copied as it is, so the plugin does not run its
|
||||
* migrations again over the copied tables. What has no Postgres counterpart
|
||||
* here (foreign keys between its tables, views, triggers, partial or
|
||||
* expression indexes, other defaults) is not created and is listed in the
|
||||
* summary. The file itself stays where it is, untouched.
|
||||
*/
|
||||
|
||||
/** The plugin store's own record of the migrations it ran, created exactly as the store creates it. */
|
||||
const LEDGER = '_plugin_migrations';
|
||||
const LEDGER_DDL = (schema: string) => `create table ${schema}.${LEDGER} (id text primary key, applied_at bigint)`;
|
||||
|
||||
/** The Postgres type the move gives each kind. */
|
||||
const PG_TYPE: Record<ColumnKind, string> = {
|
||||
integer: 'bigint',
|
||||
float: 'double precision',
|
||||
text: 'text',
|
||||
json: 'jsonb',
|
||||
bytes: 'bytea',
|
||||
};
|
||||
|
||||
/**
|
||||
* The kind of a plugin's column, by SQLite's affinity rules (the declared
|
||||
* type's text decides, in this order: INT, then CHAR/CLOB/TEXT, then BLOB or
|
||||
* none, then REAL/FLOA/DOUB, else NUMERIC). Where the affinity leaves the
|
||||
* storage open (none, or NUMERIC), the values the column holds decide, and
|
||||
* text is the answer that holds every one of them.
|
||||
*/
|
||||
export function pluginColumnKind(declaredType: string, storage: ReadonlySet<string>): ColumnKind {
|
||||
const declared = declaredType.toUpperCase();
|
||||
const only = (...classes: string[]) => storage.size > 0 && [...storage].every((value) => classes.includes(value));
|
||||
if (declared.includes('INT')) return 'integer';
|
||||
if (/CHAR|CLOB|TEXT/.test(declared)) return 'text';
|
||||
if (declared.includes('BLOB')) return only('blob', 'text') ? 'bytes' : 'text';
|
||||
if (/REAL|FLOA|DOUB/.test(declared)) return only('integer', 'real') || storage.size === 0 ? 'float' : 'text';
|
||||
if (only('integer')) return 'integer';
|
||||
if (only('integer', 'real')) return 'float';
|
||||
if (only('blob')) return 'bytes';
|
||||
return 'text';
|
||||
}
|
||||
|
||||
const NUMBER_LITERAL = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const STRING_LITERAL = /^'(?:[^']|'')*'$/s;
|
||||
|
||||
/** The Postgres spelling of a column default, or null when it has none the move can trust. */
|
||||
export function pluginDefault(sql: string | null, kind: ColumnKind): string | null {
|
||||
if (sql === null) return null;
|
||||
const text = sql
|
||||
.trim()
|
||||
.replace(/^\((.*)\)$/s, '$1')
|
||||
.trim();
|
||||
const ported = portableDefault(text);
|
||||
if (ported !== text) return ported;
|
||||
if (/^null$/i.test(text)) return 'null';
|
||||
if (NUMBER_LITERAL.test(text)) return kind === 'text' ? `'${text}'` : text;
|
||||
if (/^(true|false)$/i.test(text)) return kind === 'integer' ? (/^true$/i.test(text) ? '1' : '0') : null;
|
||||
if (STRING_LITERAL.test(text)) return text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One plugin's database as the move plans to copy it. */
|
||||
export interface PluginPlan {
|
||||
pluginId: string;
|
||||
file: string;
|
||||
schema: string;
|
||||
/** The DDL that creates its tables and indexes, in order. */
|
||||
ddl: string[];
|
||||
specs: TableSpec[];
|
||||
sequences: CopiedSequence[];
|
||||
/** What the move does not carry over, for the summary. */
|
||||
notCarried: string[];
|
||||
}
|
||||
|
||||
function columnDdl(column: SqliteColumn, kind: ColumnKind, identity: boolean, notes: string[], table: string): string {
|
||||
const parts = [quoteIdentifier(column.name), PG_TYPE[kind]];
|
||||
if (identity) parts.push('generated by default as identity');
|
||||
if (column.notNull && !identity) parts.push('not null');
|
||||
if (column.defaultSql !== null && !identity) {
|
||||
const value = pluginDefault(column.defaultSql, kind);
|
||||
if (value === null) notes.push(`the default ${column.defaultSql} of ${table}.${column.name}`);
|
||||
else parts.push(`default ${value}`);
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
function indexDdl(index: SqliteIndex, target: string, notes: string[], table: string): string | null {
|
||||
if (index.origin === 'pk') return null;
|
||||
if (index.partial || index.columns === null) {
|
||||
notes.push(`the index ${index.name} on ${table} (partial or over an expression)`);
|
||||
return null;
|
||||
}
|
||||
const columns = index.columns.map(quoteIdentifier).join(', ');
|
||||
return `create ${index.unique ? 'unique ' : ''}index on ${target} (${columns})`;
|
||||
}
|
||||
|
||||
/** Plans the copy of one plugin's `plugin.db`: what to create in its schema and what to fill. */
|
||||
export function planPluginData(pluginId: string, source: SqliteSource): PluginPlan {
|
||||
const schemaName = pluginSchemaName(pluginId);
|
||||
const schema = quotePluginSchema(schemaName);
|
||||
const plan: PluginPlan = {
|
||||
pluginId,
|
||||
file: source.file,
|
||||
schema: schemaName,
|
||||
ddl: [`create schema ${schema}`],
|
||||
specs: [],
|
||||
sequences: [],
|
||||
notCarried: [],
|
||||
};
|
||||
for (const item of source.viewsAndTriggers()) plan.notCarried.push(`the ${item.type} ${item.name}`);
|
||||
const tables = source.tables();
|
||||
if (!tables.includes(LEDGER)) plan.ddl.push(LEDGER_DDL(schema));
|
||||
for (const table of tables) {
|
||||
const target = `${schema}.${quoteIdentifier(table)}`;
|
||||
const label = `plugin ${pluginId}: ${table}`;
|
||||
const columns = source.columns(table);
|
||||
if (table === LEDGER) {
|
||||
plan.ddl.push(LEDGER_DDL(schema));
|
||||
plan.specs.push({
|
||||
source: table,
|
||||
target,
|
||||
label,
|
||||
columns: [
|
||||
{ name: 'id', kind: 'text' },
|
||||
{ name: 'applied_at', kind: 'integer' },
|
||||
],
|
||||
deferred: [],
|
||||
primaryKey: ['id'],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const keys = columns.filter((column) => column.primaryKey > 0).sort((a, b) => a.primaryKey - b.primaryKey);
|
||||
const kinds = columns.map((column) =>
|
||||
pluginColumnKind(column.declaredType, source.storageClasses(table, column.name)),
|
||||
);
|
||||
// SQLite's rowid alias: the one INTEGER PRIMARY KEY column, which hands out its own ids.
|
||||
const rowid = keys.length === 1 && keys[0].declaredType.toUpperCase() === 'INTEGER' ? keys[0].name : null;
|
||||
const definitions = columns.map((column, index) =>
|
||||
columnDdl(column, kinds[index], column.name === rowid, plan.notCarried, table),
|
||||
);
|
||||
if (keys.length > 0) definitions.push(`primary key (${keys.map((key) => quoteIdentifier(key.name)).join(', ')})`);
|
||||
plan.ddl.push(`create table ${target} (${definitions.join(', ')})`);
|
||||
for (const index of source.indexes(table)) {
|
||||
const ddl = indexDdl(index, target, plan.notCarried, table);
|
||||
if (ddl) plan.ddl.push(ddl);
|
||||
}
|
||||
plan.specs.push({
|
||||
source: table,
|
||||
target,
|
||||
label,
|
||||
columns: columns.map((column, index) => ({ name: column.name, kind: kinds[index] })),
|
||||
deferred: [],
|
||||
primaryKey: keys.map((key) => key.name),
|
||||
});
|
||||
// The identity's sequence is named by Postgres; resolveIdentitySequences reads it once the table exists.
|
||||
if (rowid) plan.sequences.push({ table, target, column: rowid, sequence: '' });
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** A plugin's data file under the plugins' data directory, by plugin id. */
|
||||
interface PluginDataFile {
|
||||
pluginId: string;
|
||||
file: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `plugin.db` files under `root`, one per plugin directory. A directory
|
||||
* whose name is no plugin id cannot have a schema, and is reported instead.
|
||||
*/
|
||||
export function findPluginDataFiles(root: string): { files: PluginDataFile[]; skipped: string[] } {
|
||||
if (!fs.existsSync(root)) return { files: [], skipped: [] };
|
||||
const files: PluginDataFile[] = [];
|
||||
const skipped: string[] = [];
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const file = path.join(root, entry.name, 'plugin.db');
|
||||
if (!entry.isDirectory() || !fs.existsSync(file)) continue;
|
||||
if (isPluginId(entry.name)) files.push({ pluginId: entry.name, file });
|
||||
else skipped.push(file);
|
||||
}
|
||||
return { files, skipped };
|
||||
}
|
||||
|
||||
/** Creates a plugin's schema, tables and indexes in the move's transaction. */
|
||||
export async function createPluginSchema(trx: Trx, plan: PluginPlan): Promise<void> {
|
||||
await inOrder(plan.ddl, async (statement) => {
|
||||
try {
|
||||
await run(trx, statement);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Postgres refused the table of plugin ${plan.pluginId} (${statement}): ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The plan's identity columns with the sequence Postgres gave each, read from the catalog. */
|
||||
export async function resolveIdentitySequences(trx: Trx, plan: PluginPlan): Promise<CopiedSequence[]> {
|
||||
const resolved: CopiedSequence[] = [];
|
||||
await inOrder(plan.sequences, async (entry) => {
|
||||
const [row] = await run<{ sequence: string | null }>(trx, 'select pg_get_serial_sequence($1, $2) as sequence', [
|
||||
entry.target,
|
||||
entry.column,
|
||||
]);
|
||||
if (row?.sequence) resolved.push({ ...entry, sequence: row.sequence });
|
||||
});
|
||||
return resolved;
|
||||
}
|
||||
Reference in New Issue
Block a user