@softure-ai/db 0.0.0-stage → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +189 -2
- package/dist/cli/bin.d.ts +3 -0
- package/dist/cli/bin.d.ts.map +1 -0
- package/dist/cli/bin.js +5 -0
- package/dist/cli/bin.js.map +1 -0
- package/dist/cli/command.d.ts +8 -0
- package/dist/cli/command.d.ts.map +1 -0
- package/dist/cli/command.js +38 -0
- package/dist/cli/command.js.map +1 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +4 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/run.d.ts +20 -0
- package/dist/cli/run.d.ts.map +1 -0
- package/dist/cli/run.js +155 -0
- package/dist/cli/run.js.map +1 -0
- package/dist/client.d.ts +42 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +34 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/adopt.d.ts +26 -0
- package/dist/migrations/adopt.d.ts.map +1 -0
- package/dist/migrations/adopt.js +131 -0
- package/dist/migrations/adopt.js.map +1 -0
- package/dist/migrations/export.d.ts +10 -0
- package/dist/migrations/export.d.ts.map +1 -0
- package/dist/migrations/export.js +58 -0
- package/dist/migrations/export.js.map +1 -0
- package/dist/migrations/exported.d.ts +20 -0
- package/dist/migrations/exported.d.ts.map +1 -0
- package/dist/migrations/exported.js +61 -0
- package/dist/migrations/exported.js.map +1 -0
- package/dist/migrations/files.d.ts +21 -0
- package/dist/migrations/files.d.ts.map +1 -0
- package/dist/migrations/files.js +112 -0
- package/dist/migrations/files.js.map +1 -0
- package/dist/migrations/introspect.d.ts +6 -0
- package/dist/migrations/introspect.d.ts.map +1 -0
- package/dist/migrations/introspect.js +117 -0
- package/dist/migrations/introspect.js.map +1 -0
- package/dist/migrations/ledger.d.ts +27 -0
- package/dist/migrations/ledger.d.ts.map +1 -0
- package/dist/migrations/ledger.js +45 -0
- package/dist/migrations/ledger.js.map +1 -0
- package/dist/migrations/migrator.d.ts +69 -0
- package/dist/migrations/migrator.d.ts.map +1 -0
- package/dist/migrations/migrator.js +217 -0
- package/dist/migrations/migrator.js.map +1 -0
- package/dist/migrations/problems.d.ts +84 -0
- package/dist/migrations/problems.d.ts.map +1 -0
- package/dist/migrations/problems.js +56 -0
- package/dist/migrations/problems.js.map +1 -0
- package/dist/migrations/session.d.ts +14 -0
- package/dist/migrations/session.d.ts.map +1 -0
- package/dist/migrations/session.js +39 -0
- package/dist/migrations/session.js.map +1 -0
- package/dist/shared.d.ts +9 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +32 -0
- package/dist/shared.js.map +1 -0
- package/dist/testing.d.ts +14 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +43 -0
- package/dist/testing.js.map +1 -0
- package/package.json +56 -4
- package/src/cli/bin.ts +5 -0
- package/src/cli/command.ts +47 -0
- package/src/cli/index.ts +3 -0
- package/src/cli/run.ts +189 -0
- package/src/client.ts +79 -0
- package/src/index.ts +37 -0
- package/src/migrations/adopt.ts +171 -0
- package/src/migrations/export.ts +66 -0
- package/src/migrations/exported.ts +82 -0
- package/src/migrations/files.ts +129 -0
- package/src/migrations/introspect.ts +165 -0
- package/src/migrations/ledger.ts +75 -0
- package/src/migrations/migrator.ts +285 -0
- package/src/migrations/problems.ts +91 -0
- package/src/migrations/session.ts +48 -0
- package/src/shared.ts +36 -0
- package/src/testing.ts +52 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The migration ledger `softure.migrations` (docs/02-module-standard.md §4). It is owned by the
|
|
2
|
+
// pseudo-module `softure` and created by its own migration, which ships as code so a bundled
|
|
3
|
+
// runner needs no file for it. While the table does not exist the journal reads as empty, so the
|
|
4
|
+
// first run bootstraps through the normal path.
|
|
5
|
+
//
|
|
6
|
+
// NEVER edit LEDGER_MIGRATION: deployed databases hold its checksum (a test pins it). A change to
|
|
7
|
+
// the ledger is a new file, `0002_…`, appended to LEDGER_FILES.
|
|
8
|
+
import { createMigrationFile, type MigrationFile } from "./files.js";
|
|
9
|
+
import type { MigrationSession } from "./session.js";
|
|
10
|
+
|
|
11
|
+
export const LEDGER_MODULE_ID = "softure";
|
|
12
|
+
export const LEDGER_SCHEMA = "softure";
|
|
13
|
+
/** The ledger's own format version, recorded as `module_version` of its rows. */
|
|
14
|
+
export const LEDGER_VERSION = "1.0.0";
|
|
15
|
+
|
|
16
|
+
const LEDGER_MIGRATION = `-- Rollback: DROP SCHEMA softure CASCADE; this forgets which module migrations ran, the module schemas and their data stay.
|
|
17
|
+
CREATE TABLE softure.migrations (
|
|
18
|
+
id bigint GENERATED ALWAYS AS IDENTITY UNIQUE,
|
|
19
|
+
module text NOT NULL CHECK (module ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'),
|
|
20
|
+
version integer NOT NULL CHECK (version > 0),
|
|
21
|
+
name text NOT NULL CHECK (name ~ '^[a-z0-9]+(_[a-z0-9]+)*$'),
|
|
22
|
+
checksum text NOT NULL CHECK (checksum ~ '^[0-9a-f]{64}$'),
|
|
23
|
+
module_version text NOT NULL,
|
|
24
|
+
method text NOT NULL CHECK (method IN ('applied', 'adopted')),
|
|
25
|
+
applied_at timestamptz NOT NULL DEFAULT now(),
|
|
26
|
+
PRIMARY KEY (module, version)
|
|
27
|
+
);
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
function createLedgerFiles(): MigrationFile[] {
|
|
31
|
+
const file = createMigrationFile("0001_ledger.sql", LEDGER_MIGRATION);
|
|
32
|
+
if (typeof file === "string") {
|
|
33
|
+
throw new Error(`ledger: the built-in migration is invalid: ${file}`);
|
|
34
|
+
}
|
|
35
|
+
return [file];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const LEDGER_FILES: readonly MigrationFile[] = createLedgerFiles();
|
|
39
|
+
|
|
40
|
+
export type MigrationMethod = "applied" | "adopted";
|
|
41
|
+
|
|
42
|
+
export interface JournalRow {
|
|
43
|
+
readonly module: string;
|
|
44
|
+
readonly version: number;
|
|
45
|
+
readonly name: string;
|
|
46
|
+
readonly checksum: string;
|
|
47
|
+
readonly method: MigrationMethod;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface LedgerEntry {
|
|
51
|
+
readonly module: string;
|
|
52
|
+
readonly version: number;
|
|
53
|
+
readonly name: string;
|
|
54
|
+
readonly checksum: string;
|
|
55
|
+
readonly moduleVersion: string;
|
|
56
|
+
readonly method: MigrationMethod;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Every ledger row, or none while the ledger table does not exist yet. */
|
|
60
|
+
export async function readJournal(session: MigrationSession): Promise<JournalRow[]> {
|
|
61
|
+
const [table] = await session.query<{ exists: boolean }>("SELECT to_regclass('softure.migrations') IS NOT NULL AS exists");
|
|
62
|
+
if (table?.exists !== true) {
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
return session.query<JournalRow>(
|
|
66
|
+
"SELECT module, version, name, checksum, method FROM softure.migrations ORDER BY id",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function recordMigration(session: MigrationSession, entry: LedgerEntry): Promise<void> {
|
|
71
|
+
await session.query(
|
|
72
|
+
"INSERT INTO softure.migrations (module, version, name, checksum, module_version, method) VALUES ($1, $2, $3, $4, $5, $6)",
|
|
73
|
+
[entry.module, entry.version, entry.name, entry.checksum, entry.moduleVersion, entry.method],
|
|
74
|
+
);
|
|
75
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
// The module migrator (docs/02-module-standard.md §4). Every enabled module's SQL files run in the
|
|
2
|
+
// module's own schema, dependencies first, one transaction per file together with its ledger row.
|
|
3
|
+
// Everything that can be checked (names, numbering, checksums, order) is checked for all modules
|
|
4
|
+
// before the first file runs, so a problem in one module never leaves another half-migrated.
|
|
5
|
+
import { ok, sortModulesByDependencies, type AnySoftureModule } from "@softure-ai/core";
|
|
6
|
+
import type { DatabaseHandle } from "../client.js";
|
|
7
|
+
import { readMigrationFiles, type MigrationFile } from "./files.js";
|
|
8
|
+
import {
|
|
9
|
+
LEDGER_FILES,
|
|
10
|
+
LEDGER_MODULE_ID,
|
|
11
|
+
LEDGER_SCHEMA,
|
|
12
|
+
LEDGER_VERSION,
|
|
13
|
+
readJournal,
|
|
14
|
+
recordMigration,
|
|
15
|
+
type JournalRow,
|
|
16
|
+
type MigrationMethod,
|
|
17
|
+
} from "./ledger.js";
|
|
18
|
+
import { failWith, type MigrationProblem, type MigrationResult } from "./problems.js";
|
|
19
|
+
import { withSession, type MigrationSession } from "./session.js";
|
|
20
|
+
|
|
21
|
+
export interface MigrateOptions {
|
|
22
|
+
/** The enabled modules, in any order; dependencies are applied first. */
|
|
23
|
+
readonly modules: readonly AnySoftureModule[];
|
|
24
|
+
/**
|
|
25
|
+
* Read each module's files from `<migrationsDir>/<module id>/` instead of the module's own
|
|
26
|
+
* folder: the container path, where a bundle cannot locate package folders.
|
|
27
|
+
*/
|
|
28
|
+
readonly migrationsDir?: URL;
|
|
29
|
+
/** Called after each file is committed, e.g. to print progress. */
|
|
30
|
+
readonly onApplied?: (step: MigrationStep) => void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface MigrationStep {
|
|
34
|
+
readonly module: string;
|
|
35
|
+
readonly schema: string;
|
|
36
|
+
readonly version: number;
|
|
37
|
+
readonly name: string;
|
|
38
|
+
readonly checksum: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface MigrationPlan {
|
|
42
|
+
/** What `migrate` would apply, in order. */
|
|
43
|
+
readonly pending: readonly MigrationStep[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface MigrationReport {
|
|
47
|
+
readonly applied: readonly MigrationStep[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One migration owner: the ledger itself or an enabled module with a schema. */
|
|
51
|
+
export interface MigrationUnit {
|
|
52
|
+
readonly module: string;
|
|
53
|
+
readonly schema: string;
|
|
54
|
+
readonly moduleVersion: string;
|
|
55
|
+
readonly files: readonly MigrationFile[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Any constant works; it only has to be the same for every runner of every app.
|
|
59
|
+
const MIGRATION_LOCK_KEY = "73012026";
|
|
60
|
+
const RESERVED_SCHEMAS = new Set([LEDGER_SCHEMA, "public", "information_schema"]);
|
|
61
|
+
const MAX_IDENTIFIER_BYTES = 63;
|
|
62
|
+
|
|
63
|
+
/** The dry run: what `migrate` would apply. Takes no lock and writes nothing. */
|
|
64
|
+
export async function planMigrations(handle: DatabaseHandle, options: MigrateOptions): Promise<MigrationResult<MigrationPlan>> {
|
|
65
|
+
const units = await prepareUnits(options.modules, options.migrationsDir);
|
|
66
|
+
if (!units.ok) {
|
|
67
|
+
return units;
|
|
68
|
+
}
|
|
69
|
+
const journal = await withSession(handle, readJournal);
|
|
70
|
+
const comparison = compareJournal(units.value, journal);
|
|
71
|
+
return comparison.problems.length > 0 ? failWith(comparison.problems) : ok({ pending: comparison.pending });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Applies every pending migration under the advisory lock. */
|
|
75
|
+
export async function migrate(handle: DatabaseHandle, options: MigrateOptions): Promise<MigrationResult<MigrationReport>> {
|
|
76
|
+
const units = await prepareUnits(options.modules, options.migrationsDir);
|
|
77
|
+
if (!units.ok) {
|
|
78
|
+
return units;
|
|
79
|
+
}
|
|
80
|
+
return withSession(handle, (session) =>
|
|
81
|
+
withMigrationLock(session, async () => {
|
|
82
|
+
// Read after the lock: a runner that waited sees what the first one applied.
|
|
83
|
+
const comparison = compareJournal(units.value, await readJournal(session));
|
|
84
|
+
if (comparison.problems.length > 0) {
|
|
85
|
+
return failWith(comparison.problems);
|
|
86
|
+
}
|
|
87
|
+
const applied: MigrationStep[] = [];
|
|
88
|
+
for (const step of comparison.pending) {
|
|
89
|
+
const unit = units.value.find((candidate) => candidate.module === step.module);
|
|
90
|
+
const file = unit?.files.find((candidate) => candidate.version === step.version);
|
|
91
|
+
if (unit === undefined || file === undefined) {
|
|
92
|
+
throw new Error(`migrate: step ${step.module} ${step.version} has no file; compareJournal is broken`);
|
|
93
|
+
}
|
|
94
|
+
const failure = await applyFile(session, { unit, file, method: "applied" });
|
|
95
|
+
if (failure !== null) {
|
|
96
|
+
return failWith([failure]);
|
|
97
|
+
}
|
|
98
|
+
applied.push(step);
|
|
99
|
+
options.onApplied?.(step);
|
|
100
|
+
}
|
|
101
|
+
return ok({ applied });
|
|
102
|
+
}),
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Validates the module list and reads every file: the ledger first, then the modules with a
|
|
108
|
+
* schema in dependency order. Fails with every problem found.
|
|
109
|
+
*/
|
|
110
|
+
export async function prepareUnits(
|
|
111
|
+
modules: readonly AnySoftureModule[],
|
|
112
|
+
migrationsDir: URL | undefined,
|
|
113
|
+
): Promise<MigrationResult<MigrationUnit[]>> {
|
|
114
|
+
const problems = modules.flatMap(checkModule);
|
|
115
|
+
const sorted = sortModulesByDependencies(modules);
|
|
116
|
+
if (!sorted.ok) {
|
|
117
|
+
problems.push({ code: "db.dependency_cycle", modules: modules.map((module) => module.id) });
|
|
118
|
+
}
|
|
119
|
+
if (problems.length > 0 || !sorted.ok) {
|
|
120
|
+
return failWith(problems);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const units: MigrationUnit[] = [
|
|
124
|
+
{ module: LEDGER_MODULE_ID, schema: LEDGER_SCHEMA, moduleVersion: LEDGER_VERSION, files: LEDGER_FILES },
|
|
125
|
+
];
|
|
126
|
+
for (const module of sorted.value) {
|
|
127
|
+
const schema = module.manifest.dbSchema;
|
|
128
|
+
if (schema === null || module.migrations === null) {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const dir = migrationsDir === undefined ? module.migrations.dir : new URL(`${module.id}/`, ensureFolderUrl(migrationsDir));
|
|
132
|
+
const files = await readMigrationFiles(module.id, dir);
|
|
133
|
+
if (files.ok) {
|
|
134
|
+
units.push({ module: module.id, schema, moduleVersion: module.manifest.version, files: files.value });
|
|
135
|
+
} else {
|
|
136
|
+
problems.push(...files.problems);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return problems.length > 0 ? failWith(problems) : ok(units);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Checks applied files against the folder and lists the pending ones in run order. */
|
|
143
|
+
export function compareJournal(
|
|
144
|
+
units: readonly MigrationUnit[],
|
|
145
|
+
journal: readonly JournalRow[],
|
|
146
|
+
): { problems: MigrationProblem[]; pending: MigrationStep[] } {
|
|
147
|
+
const problems: MigrationProblem[] = [];
|
|
148
|
+
const pending: MigrationStep[] = [];
|
|
149
|
+
for (const unit of units) {
|
|
150
|
+
const rows = journal.filter((row) => row.module === unit.module);
|
|
151
|
+
const appliedVersions = new Set(rows.map((row) => row.version));
|
|
152
|
+
const lastApplied = Math.max(0, ...rows.map((row) => row.version));
|
|
153
|
+
|
|
154
|
+
for (const row of rows) {
|
|
155
|
+
const file = unit.files.find((candidate) => candidate.version === row.version);
|
|
156
|
+
if (file === undefined) {
|
|
157
|
+
problems.push({ code: "db.migration_missing", module: unit.module, version: row.version, name: row.name });
|
|
158
|
+
} else if (file.checksum !== row.checksum || file.name !== row.name) {
|
|
159
|
+
problems.push({ code: "db.migration_changed", module: unit.module, version: row.version, name: row.name });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
for (const file of unit.files) {
|
|
163
|
+
if (appliedVersions.has(file.version)) {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (file.version < lastApplied) {
|
|
167
|
+
problems.push({ code: "db.migration_out_of_order", module: unit.module, version: file.version, appliedVersion: lastApplied });
|
|
168
|
+
} else {
|
|
169
|
+
pending.push({ module: unit.module, schema: unit.schema, version: file.version, name: file.name, checksum: file.checksum });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { problems, pending };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Runs one file and its ledger row in one transaction, inside the unit's schema. Returns the
|
|
178
|
+
* problem when the SQL fails; the transaction is rolled back first.
|
|
179
|
+
*/
|
|
180
|
+
export async function applyFile(
|
|
181
|
+
session: MigrationSession,
|
|
182
|
+
input: { unit: MigrationUnit; file: MigrationFile; method: MigrationMethod },
|
|
183
|
+
): Promise<MigrationProblem | null> {
|
|
184
|
+
const { unit, file, method } = input;
|
|
185
|
+
// The schema passed the manifest's lower_snake_case rule and checkModule; quoting is a second line.
|
|
186
|
+
const schema = quoteIdentifier(unit.schema);
|
|
187
|
+
try {
|
|
188
|
+
await session.exec(`BEGIN; CREATE SCHEMA IF NOT EXISTS ${schema}; SET LOCAL search_path TO ${schema}, public;`);
|
|
189
|
+
const transactionId = await readTransactionId(session);
|
|
190
|
+
if (method === "applied") {
|
|
191
|
+
await session.exec(file.sql);
|
|
192
|
+
}
|
|
193
|
+
// Second line behind findTransactionControl: a file that still ended the transaction left
|
|
194
|
+
// part of itself committed, so it must not be reported as cleanly rolled back.
|
|
195
|
+
if ((await readTransactionId(session)) !== transactionId) {
|
|
196
|
+
throw new TransactionEndedError();
|
|
197
|
+
}
|
|
198
|
+
await recordMigration(session, {
|
|
199
|
+
module: unit.module,
|
|
200
|
+
version: file.version,
|
|
201
|
+
name: file.name,
|
|
202
|
+
checksum: file.checksum,
|
|
203
|
+
moduleVersion: unit.moduleVersion,
|
|
204
|
+
method,
|
|
205
|
+
});
|
|
206
|
+
await session.exec("COMMIT");
|
|
207
|
+
return null;
|
|
208
|
+
} catch (error) {
|
|
209
|
+
const reason = await rollBack(session, error);
|
|
210
|
+
return { code: "db.migration_failed", module: unit.module, version: file.version, name: file.name, reason };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
class TransactionEndedError extends Error {
|
|
215
|
+
constructor() {
|
|
216
|
+
super("the file ended the migrator's transaction, so the statements before that point may be committed; check the schema by hand");
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// The transaction id, not now(): two transactions can share a start time (PGlite's clock ticks in
|
|
221
|
+
// milliseconds), but never an id.
|
|
222
|
+
async function readTransactionId(session: MigrationSession): Promise<string> {
|
|
223
|
+
const [row] = await session.query<{ id: string }>("SELECT pg_current_xact_id()::text AS id");
|
|
224
|
+
return row?.id ?? "";
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Rolls the open transaction back and returns the reason to report. A failing ROLLBACK (a lost
|
|
229
|
+
* connection) is added to the reason instead of hiding the original error.
|
|
230
|
+
*/
|
|
231
|
+
export async function rollBack(session: MigrationSession, error: unknown): Promise<string> {
|
|
232
|
+
const reason = describeError(error);
|
|
233
|
+
try {
|
|
234
|
+
await session.exec("ROLLBACK");
|
|
235
|
+
return reason;
|
|
236
|
+
} catch (rollbackError) {
|
|
237
|
+
return `${reason} (and ROLLBACK failed: ${describeError(rollbackError)})`;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Holds the session-level advisory lock while `run` runs; a second runner waits for it. */
|
|
242
|
+
export async function withMigrationLock<T>(session: MigrationSession, run: () => Promise<T>): Promise<T> {
|
|
243
|
+
await session.query("SELECT pg_advisory_lock($1)", [MIGRATION_LOCK_KEY]);
|
|
244
|
+
let result: T;
|
|
245
|
+
try {
|
|
246
|
+
result = await run();
|
|
247
|
+
} catch (error) {
|
|
248
|
+
// The run's own error wins; an unlock failure here is secondary (the session is discarded).
|
|
249
|
+
await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]).catch((unlockError: unknown) => {
|
|
250
|
+
throw new Error(`migration run failed (${describeError(error)}) and releasing the lock failed: ${describeError(unlockError)}`, {
|
|
251
|
+
cause: error,
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
await session.query("SELECT pg_advisory_unlock($1)", [MIGRATION_LOCK_KEY]);
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function checkModule(module: AnySoftureModule): MigrationProblem[] {
|
|
261
|
+
const schema = module.manifest.dbSchema;
|
|
262
|
+
if (module.id === LEDGER_MODULE_ID || (schema !== null && isReservedSchema(schema))) {
|
|
263
|
+
return [{ code: "db.reserved_module", module: module.id }];
|
|
264
|
+
}
|
|
265
|
+
if (schema === null && module.migrations !== null) {
|
|
266
|
+
return [{ code: "db.migrations_without_schema", module: module.id }];
|
|
267
|
+
}
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function isReservedSchema(schema: string): boolean {
|
|
272
|
+
return RESERVED_SCHEMAS.has(schema) || schema.startsWith("pg_") || Buffer.byteLength(schema, "utf8") > MAX_IDENTIFIER_BYTES;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function quoteIdentifier(name: string): string {
|
|
276
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function ensureFolderUrl(url: URL): URL {
|
|
280
|
+
return url.href.endsWith("/") ? url : new URL(`${url.href}/`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function describeError(error: unknown): string {
|
|
284
|
+
return error instanceof Error ? error.message : String(error);
|
|
285
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Every expected migration failure, as a value (AGENTS.md: expected failures are results). Each
|
|
2
|
+
// problem names the module and file it is about; `describeProblem` turns it into the English line
|
|
3
|
+
// the CLI prints and `createTestDatabase` throws.
|
|
4
|
+
import type { Err, Ok } from "@softure-ai/core";
|
|
5
|
+
|
|
6
|
+
export type MigrationProblem =
|
|
7
|
+
| { readonly code: "db.invalid_migration_file"; readonly module: string; readonly file: string; readonly reason: string }
|
|
8
|
+
| { readonly code: "db.migrations_unreadable"; readonly module: string; readonly dir: string; readonly reason: string }
|
|
9
|
+
| { readonly code: "db.migration_changed"; readonly module: string; readonly version: number; readonly name: string }
|
|
10
|
+
| { readonly code: "db.migration_missing"; readonly module: string; readonly version: number; readonly name: string }
|
|
11
|
+
| { readonly code: "db.migration_out_of_order"; readonly module: string; readonly version: number; readonly appliedVersion: number }
|
|
12
|
+
| { readonly code: "db.migration_failed"; readonly module: string; readonly version: number; readonly name: string; readonly reason: string }
|
|
13
|
+
| { readonly code: "db.reserved_module"; readonly module: string }
|
|
14
|
+
| { readonly code: "db.migrations_without_schema"; readonly module: string }
|
|
15
|
+
| { readonly code: "db.dependency_cycle"; readonly modules: readonly string[] }
|
|
16
|
+
| { readonly code: "db.adopt_unknown_module"; readonly module: string }
|
|
17
|
+
| { readonly code: "db.adopt_version_mismatch"; readonly module: string; readonly requested: string; readonly enabled: string }
|
|
18
|
+
| { readonly code: "db.adopt_already_applied"; readonly module: string }
|
|
19
|
+
| { readonly code: "db.adopt_dependency_pending"; readonly module: string; readonly dependency: string }
|
|
20
|
+
| { readonly code: "db.adopt_no_schema"; readonly module: string }
|
|
21
|
+
| { readonly code: "db.adopt_reference_failed"; readonly module: string; readonly reason: string }
|
|
22
|
+
| { readonly code: "db.export_target_not_empty"; readonly module: string; readonly dir: string; readonly entries: readonly string[] }
|
|
23
|
+
| { readonly code: "db.schema_mismatch"; readonly module: string; readonly schema: string; readonly differences: readonly string[] };
|
|
24
|
+
|
|
25
|
+
export type MigrationErrorCode = MigrationProblem["code"];
|
|
26
|
+
|
|
27
|
+
/** A failed migration operation: the code of its first problem, and every problem found. */
|
|
28
|
+
export interface MigrationFailure extends Err<MigrationErrorCode> {
|
|
29
|
+
readonly problems: readonly MigrationProblem[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type MigrationResult<T> = Ok<T> | MigrationFailure;
|
|
33
|
+
|
|
34
|
+
export function failWith(problems: readonly MigrationProblem[]): MigrationFailure {
|
|
35
|
+
const [first] = problems;
|
|
36
|
+
if (first === undefined) {
|
|
37
|
+
throw new Error("failWith: a migration failure needs at least one problem");
|
|
38
|
+
}
|
|
39
|
+
return { ok: false, error: first.code, problems };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One English line per problem, naming the module and the file or object involved. */
|
|
43
|
+
export function describeProblem(problem: MigrationProblem): string {
|
|
44
|
+
switch (problem.code) {
|
|
45
|
+
case "db.invalid_migration_file":
|
|
46
|
+
return `${problem.module}: migration file ${problem.file} is invalid: ${problem.reason}`;
|
|
47
|
+
case "db.migrations_unreadable":
|
|
48
|
+
return `${problem.module}: cannot read the migrations folder ${problem.dir}: ${problem.reason}`;
|
|
49
|
+
case "db.migration_changed":
|
|
50
|
+
return `${problem.module}: applied migration ${formatFile(problem.version, problem.name)} was edited (checksum differs); add a new migration instead`;
|
|
51
|
+
case "db.migration_missing":
|
|
52
|
+
return `${problem.module}: applied migration ${formatFile(problem.version, problem.name)} is missing from the module`;
|
|
53
|
+
case "db.migration_out_of_order":
|
|
54
|
+
return `${problem.module}: migration ${formatVersion(problem.version)} is pending but ${formatVersion(problem.appliedVersion)} is already applied`;
|
|
55
|
+
case "db.migration_failed":
|
|
56
|
+
return `${problem.module}: migration ${formatFile(problem.version, problem.name)} failed and was rolled back: ${problem.reason}`;
|
|
57
|
+
case "db.reserved_module":
|
|
58
|
+
return `${problem.module}: uses a reserved id or schema (the id "softure"; the schemas softure, public, information_schema, pg_* and names over 63 bytes)`;
|
|
59
|
+
case "db.migrations_without_schema":
|
|
60
|
+
return `${problem.module}: has migrations but no dbSchema in its manifest`;
|
|
61
|
+
case "db.dependency_cycle":
|
|
62
|
+
return `modules ${problem.modules.join(", ")} depend on each other in a cycle`;
|
|
63
|
+
case "db.adopt_unknown_module":
|
|
64
|
+
return `${problem.module}: cannot adopt a module that is not enabled in the config`;
|
|
65
|
+
case "db.adopt_version_mismatch":
|
|
66
|
+
return `${problem.module}: --adopt asks for ${problem.requested} but ${problem.enabled} is enabled`;
|
|
67
|
+
case "db.adopt_already_applied":
|
|
68
|
+
return `${problem.module}: already has migrations in the ledger; adopt only works on a module the ledger has never seen`;
|
|
69
|
+
case "db.adopt_dependency_pending":
|
|
70
|
+
return `${problem.module}: depends on ${problem.dependency}, which has migrations still pending; migrate or adopt ${problem.dependency} first`;
|
|
71
|
+
case "db.adopt_no_schema":
|
|
72
|
+
return `${problem.module}: has no dbSchema, so there is nothing to adopt`;
|
|
73
|
+
case "db.adopt_reference_failed":
|
|
74
|
+
return `${problem.module}: could not build the reference schema: ${problem.reason}`;
|
|
75
|
+
case "db.export_target_not_empty":
|
|
76
|
+
return `${problem.module}: ${problem.dir} holds other files (${problem.entries.join(", ")}); export into an empty folder`;
|
|
77
|
+
case "db.schema_mismatch":
|
|
78
|
+
return [
|
|
79
|
+
`${problem.module}: schema "${problem.schema}" differs from what its migrations create:`,
|
|
80
|
+
...problem.differences.map((difference) => ` ${difference}`),
|
|
81
|
+
].join("\n");
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function formatVersion(version: number): string {
|
|
86
|
+
return String(version).padStart(4, "0");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function formatFile(version: number, name: string): string {
|
|
90
|
+
return `${formatVersion(version)}_${name}.sql`;
|
|
91
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// One raw connection for a migration run. The advisory lock is session-level, so the lock, every
|
|
2
|
+
// transaction and every statement of a run must share this connection (never `pool.query`).
|
|
3
|
+
import type { DatabaseHandle } from "../client.js";
|
|
4
|
+
|
|
5
|
+
export interface MigrationSession {
|
|
6
|
+
/** A parameterised statement; returns its rows. */
|
|
7
|
+
readonly query: <T>(text: string, params?: readonly unknown[]) => Promise<T[]>;
|
|
8
|
+
/** One or more statements without parameters (a migration file). */
|
|
9
|
+
readonly exec: (sql: string) => Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Runs `run` on one dedicated connection. A pg client is destroyed afterwards instead of going
|
|
14
|
+
* back to the pool, so a `SET` inside a migration file or a lock that failed to release cannot
|
|
15
|
+
* leak into the app's queries. PGlite has one connection, so its settings are reset instead.
|
|
16
|
+
*/
|
|
17
|
+
export async function withSession<T>(handle: DatabaseHandle, run: (session: MigrationSession) => Promise<T>): Promise<T> {
|
|
18
|
+
if (handle.kind === "pglite") {
|
|
19
|
+
const { client } = handle;
|
|
20
|
+
try {
|
|
21
|
+
return await run({
|
|
22
|
+
query: async <R>(text: string, params?: readonly unknown[]) => (await client.query<R>(text, params ? [...params] : undefined)).rows,
|
|
23
|
+
exec: async (sql) => {
|
|
24
|
+
await client.exec(sql);
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
} finally {
|
|
28
|
+
await client.exec("RESET ALL");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const client = await handle.pool.connect();
|
|
33
|
+
// A dropped connection makes pg emit 'error' on the client; without a listener Node crashes the
|
|
34
|
+
// process. The pending query rejects on its own, so the listener only has to exist.
|
|
35
|
+
const ignoreClientError = (): void => undefined;
|
|
36
|
+
client.on("error", ignoreClientError);
|
|
37
|
+
try {
|
|
38
|
+
return await run({
|
|
39
|
+
query: async <R>(text: string, params?: readonly unknown[]) => (await client.query(text, params ? [...params] : undefined)).rows as R[],
|
|
40
|
+
exec: async (sql) => {
|
|
41
|
+
await client.query(sql);
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
} finally {
|
|
45
|
+
client.release(true);
|
|
46
|
+
client.off("error", ignoreClientError);
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/shared.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// One database handle per URL for the whole server process, shared by every module's Next.js
|
|
2
|
+
// adapter and the app. Package code cannot import the app's own handle, and `next dev` re-evaluates
|
|
3
|
+
// modules on every change, so the handles live on `globalThis` under a `Symbol.for` key: each
|
|
4
|
+
// reload, and each copy of this file in separate server bundles, finds the same pool.
|
|
5
|
+
import { createDatabase, type CreateDatabaseOptions, type DatabaseHandle } from "./client.js";
|
|
6
|
+
|
|
7
|
+
const HANDLES_KEY = Symbol.for("@softure-ai/db/shared-handles");
|
|
8
|
+
|
|
9
|
+
type HandleHost = Record<typeof HANDLES_KEY, Map<string, Promise<DatabaseHandle>> | undefined>;
|
|
10
|
+
|
|
11
|
+
const host = globalThis as unknown as HandleHost;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The process-wide handle for `url`, opened on first use. `options` apply only to that first call.
|
|
15
|
+
* A failed open is not kept, so the next call tries again.
|
|
16
|
+
*/
|
|
17
|
+
export function getSharedDatabase(url: string, options: CreateDatabaseOptions = {}): Promise<DatabaseHandle> {
|
|
18
|
+
const handles = (host[HANDLES_KEY] ??= new Map<string, Promise<DatabaseHandle>>());
|
|
19
|
+
let handle = handles.get(url);
|
|
20
|
+
if (handle === undefined) {
|
|
21
|
+
handle = createDatabase(url, options);
|
|
22
|
+
handles.set(url, handle);
|
|
23
|
+
handle.catch(() => handles.delete(url));
|
|
24
|
+
}
|
|
25
|
+
return handle;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Closes and forgets every shared handle. For tests and graceful shutdown. */
|
|
29
|
+
export async function closeSharedDatabases(): Promise<void> {
|
|
30
|
+
const handles = host[HANDLES_KEY];
|
|
31
|
+
if (handles === undefined) return;
|
|
32
|
+
const opened = [...handles.values()];
|
|
33
|
+
handles.clear();
|
|
34
|
+
const results = await Promise.allSettled(opened);
|
|
35
|
+
await Promise.all(results.flatMap((result) => (result.status === "fulfilled" ? [result.value.close()] : [])));
|
|
36
|
+
}
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Test databases for module unit tests (docs/02-module-standard.md §10): a real Postgres (PGlite)
|
|
2
|
+
// with the real migrations of the given modules. Migrating costs about two seconds, so each
|
|
3
|
+
// module set is migrated once per test worker into a template, and every call starts from a copy
|
|
4
|
+
// of the template's data folder (FIRE_TRACKER `src/db/test-db.ts`).
|
|
5
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
6
|
+
import type { AnySoftureModule } from "@softure-ai/core";
|
|
7
|
+
import { createPgliteHandle, type PgliteClientDatabase } from "./client.js";
|
|
8
|
+
import { migrate } from "./migrations/migrator.js";
|
|
9
|
+
import { describeProblem } from "./migrations/problems.js";
|
|
10
|
+
|
|
11
|
+
export interface TestDatabase {
|
|
12
|
+
readonly db: PgliteClientDatabase;
|
|
13
|
+
readonly client: PGlite;
|
|
14
|
+
readonly close: () => Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const templates = new Map<string, Promise<Blob | File>>();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A fresh, migrated, in-memory database per call. List the module under test and the modules it
|
|
21
|
+
* depends on. Throws when a migration is invalid or fails: that is a bug in the module package.
|
|
22
|
+
*/
|
|
23
|
+
export async function createTestDatabase(modules: readonly AnySoftureModule[] = []): Promise<TestDatabase> {
|
|
24
|
+
const client = new PGlite({ loadDataDir: await getTemplate(modules) });
|
|
25
|
+
const handle = await createPgliteHandle(client);
|
|
26
|
+
return { db: handle.db, client, close: handle.close };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function getTemplate(modules: readonly AnySoftureModule[]): Promise<Blob | File> {
|
|
30
|
+
const key = modules.map((module) => `${module.id}@${module.migrations?.dir.href ?? "-"}`).join("|");
|
|
31
|
+
let template = templates.get(key);
|
|
32
|
+
if (template === undefined) {
|
|
33
|
+
template = buildTemplate(modules);
|
|
34
|
+
templates.set(key, template);
|
|
35
|
+
// A failed build is not cached: the next call reports the problem again.
|
|
36
|
+
template.catch(() => templates.delete(key));
|
|
37
|
+
}
|
|
38
|
+
return template;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function buildTemplate(modules: readonly AnySoftureModule[]): Promise<Blob | File> {
|
|
42
|
+
const handle = await createPgliteHandle(new PGlite());
|
|
43
|
+
try {
|
|
44
|
+
const result = await migrate(handle, { modules });
|
|
45
|
+
if (!result.ok) {
|
|
46
|
+
throw new Error(`createTestDatabase: migrations failed:\n${result.problems.map(describeProblem).join("\n")}`);
|
|
47
|
+
}
|
|
48
|
+
return await handle.client.dumpDataDir("none");
|
|
49
|
+
} finally {
|
|
50
|
+
await handle.close();
|
|
51
|
+
}
|
|
52
|
+
}
|