shutro 0.0.0-stage → 0.1.0
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 +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +60 -0
- package/dist/core/money/fx.js +109 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Planning, versioned migration files, the ledger, and module data-migration hooks.
|
|
3
|
+
*/
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { compareVersions } from '../core/index.js';
|
|
8
|
+
import { compile, sql } from '../sql/index.js';
|
|
9
|
+
import { readLiveSchema } from './catalog.js';
|
|
10
|
+
import { diffSchema } from './diff.js';
|
|
11
|
+
import { DestructiveMigrationError, MigrationChecksumError, MigrationFileError } from './errors.js';
|
|
12
|
+
import { renderOperation } from './render.js';
|
|
13
|
+
import { desiredSchema } from './schema.js';
|
|
14
|
+
/** Compares the registry with the live database and plans the changes. */
|
|
15
|
+
export async function planMigration(options) {
|
|
16
|
+
const live = await readLiveSchema(options.driver, options.schema ?? 'public');
|
|
17
|
+
const operations = diffSchema(desiredSchema(options.registry), live);
|
|
18
|
+
return {
|
|
19
|
+
operations,
|
|
20
|
+
destructive: operations.filter((o) => o.destructive),
|
|
21
|
+
statements: operations.map((o) => ({ sql: renderOperation(o), destructive: o.destructive })),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
|
|
25
|
+
const DESTRUCTIVE_MARK = '-- destructive';
|
|
26
|
+
function listFiles(dir) {
|
|
27
|
+
if (!existsSync(dir))
|
|
28
|
+
return [];
|
|
29
|
+
return readdirSync(dir)
|
|
30
|
+
.filter((f) => FILE.test(f))
|
|
31
|
+
.sort()
|
|
32
|
+
.map((f) => {
|
|
33
|
+
const m = FILE.exec(f);
|
|
34
|
+
return { version: m[1], name: m[2], path: join(dir, f) };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/** Writes the plan as the next versioned file (`0001_name.sql`). */
|
|
38
|
+
export async function writeMigrationFile(options) {
|
|
39
|
+
const { dir, name, plan } = options;
|
|
40
|
+
if (!/^[a-z0-9_]+$/.test(name))
|
|
41
|
+
throw new MigrationFileError(`${JSON.stringify(name)} is not a migration name.`, 'Use lower-case letters, digits and underscores, e.g. "add_sale_margin".');
|
|
42
|
+
mkdirSync(dir, { recursive: true });
|
|
43
|
+
const existing = listFiles(dir);
|
|
44
|
+
const version = String(Number(existing.at(-1)?.version ?? '0') + 1).padStart(4, '0');
|
|
45
|
+
const lines = [
|
|
46
|
+
`-- shutro migration ${version}: ${name} (generated ${new Date().toISOString()})`,
|
|
47
|
+
`-- ${plan.statements.length} statement(s), ${plan.destructive.length} destructive`,
|
|
48
|
+
'',
|
|
49
|
+
];
|
|
50
|
+
for (const s of plan.statements) {
|
|
51
|
+
if (s.destructive)
|
|
52
|
+
lines.push(DESTRUCTIVE_MARK);
|
|
53
|
+
lines.push(`${s.sql};`, '');
|
|
54
|
+
}
|
|
55
|
+
const path = join(dir, `${version}_${name}.sql`);
|
|
56
|
+
writeFileSync(path, `${lines.join('\n')}\n`);
|
|
57
|
+
return { version, name, path };
|
|
58
|
+
}
|
|
59
|
+
/** Parses a migration file into statements (comments dropped; `-- destructive` marks the next statement). */
|
|
60
|
+
export function parseMigrationFile(content) {
|
|
61
|
+
const statements = [];
|
|
62
|
+
let buffer = [];
|
|
63
|
+
let destructive = false;
|
|
64
|
+
for (const raw of content.split('\n')) {
|
|
65
|
+
const line = raw.trimEnd();
|
|
66
|
+
if (line.trim() === DESTRUCTIVE_MARK) {
|
|
67
|
+
destructive = true;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (line.trim().startsWith('--') || line.trim() === '')
|
|
71
|
+
continue;
|
|
72
|
+
buffer.push(line);
|
|
73
|
+
if (line.endsWith(';')) {
|
|
74
|
+
statements.push({ sql: buffer.join('\n').slice(0, -1), destructive });
|
|
75
|
+
buffer = [];
|
|
76
|
+
destructive = false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (buffer.length > 0)
|
|
80
|
+
statements.push({ sql: buffer.join('\n'), destructive });
|
|
81
|
+
return statements;
|
|
82
|
+
}
|
|
83
|
+
function checksum(content) {
|
|
84
|
+
return createHash('sha256').update(content).digest('hex');
|
|
85
|
+
}
|
|
86
|
+
async function ensureLedger(conn) {
|
|
87
|
+
await conn.query({
|
|
88
|
+
text: 'CREATE TABLE IF NOT EXISTS "shutro_migration" ("version" text PRIMARY KEY, "name" text NOT NULL, "checksum" text NOT NULL, "applied_at" timestamp with time zone NOT NULL DEFAULT now())',
|
|
89
|
+
params: [],
|
|
90
|
+
});
|
|
91
|
+
await conn.query({
|
|
92
|
+
text: 'CREATE TABLE IF NOT EXISTS "shutro_module" ("name" text PRIMARY KEY, "version" text NOT NULL, "installed_at" timestamp with time zone NOT NULL DEFAULT now(), "updated_at" timestamp with time zone NOT NULL DEFAULT now())',
|
|
93
|
+
params: [],
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/** Reads the ledger and the directory. @throws {MigrationChecksumError} when an applied file was edited. */
|
|
97
|
+
export async function migrationStatus(options) {
|
|
98
|
+
const files = listFiles(options.dir);
|
|
99
|
+
return options.driver.transaction({ isolation: 'read committed' }, async (conn) => {
|
|
100
|
+
await ensureLedger(conn);
|
|
101
|
+
const rows = await conn.query(compile(sql `SELECT version, name, checksum, applied_at FROM ${sql.id('shutro_migration')} ORDER BY version`));
|
|
102
|
+
const byVersion = new Map(rows.map((r) => [r.version, r]));
|
|
103
|
+
for (const file of files) {
|
|
104
|
+
const row = byVersion.get(file.version);
|
|
105
|
+
if (row !== undefined && row.checksum !== checksum(readFileSync(file.path, 'utf8')))
|
|
106
|
+
throw new MigrationChecksumError(file.path);
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
applied: rows.map((r) => ({ version: r.version, name: r.name, appliedAt: r.applied_at })),
|
|
110
|
+
pending: files.filter((f) => !byVersion.has(f.version)),
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Applies pending migration files in order (each in its own transaction, recorded in `shutro_migration`), then runs
|
|
116
|
+
* the data-migration hooks of upgraded modules and records module versions in `shutro_module`.
|
|
117
|
+
*
|
|
118
|
+
* @throws {DestructiveMigrationError} for a file with destructive statements unless `allowDestructive` is set.
|
|
119
|
+
* @throws {MigrationChecksumError} when an applied file was edited.
|
|
120
|
+
*/
|
|
121
|
+
export async function applyMigrations(options) {
|
|
122
|
+
const { driver, registry } = options;
|
|
123
|
+
const status = await migrationStatus({ driver, dir: options.dir });
|
|
124
|
+
const applied = [];
|
|
125
|
+
for (const file of status.pending) {
|
|
126
|
+
const content = readFileSync(file.path, 'utf8');
|
|
127
|
+
const statements = parseMigrationFile(content);
|
|
128
|
+
const destructive = statements.filter((s) => s.destructive).map((s) => s.sql);
|
|
129
|
+
if (destructive.length > 0 && options.allowDestructive !== true)
|
|
130
|
+
throw new DestructiveMigrationError(file.path, destructive);
|
|
131
|
+
await driver.transaction({ isolation: 'read committed' }, async (conn) => {
|
|
132
|
+
for (const s of statements)
|
|
133
|
+
await conn.query({ text: s.sql, params: [] });
|
|
134
|
+
await conn.query(compile(sql `INSERT INTO ${sql.id('shutro_migration')} (version, name, checksum) VALUES (${file.version}, ${file.name}, ${checksum(content)})`));
|
|
135
|
+
});
|
|
136
|
+
applied.push(file);
|
|
137
|
+
}
|
|
138
|
+
const modules = [];
|
|
139
|
+
const hooks = [];
|
|
140
|
+
for (const module of registry.modules) {
|
|
141
|
+
await driver.transaction({ isolation: 'read committed' }, async (conn) => {
|
|
142
|
+
await ensureLedger(conn);
|
|
143
|
+
const [row] = await conn.query(compile(sql `SELECT version FROM ${sql.id('shutro_module')} WHERE name = ${module.name}`));
|
|
144
|
+
if (row === undefined) {
|
|
145
|
+
await conn.query(compile(sql `INSERT INTO ${sql.id('shutro_module')} (name, version) VALUES (${module.name}, ${module.version})`));
|
|
146
|
+
modules.push({ module: module.name, from: null, to: module.version });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (compareVersions(row.version, module.version) >= 0)
|
|
150
|
+
return;
|
|
151
|
+
const ctx = {
|
|
152
|
+
registry,
|
|
153
|
+
sql: (strings, ...values) => conn.query(compile(sql(strings, ...values))),
|
|
154
|
+
};
|
|
155
|
+
for (const hook of module.migrations) {
|
|
156
|
+
if (compareVersions(hook.version, row.version) <= 0 ||
|
|
157
|
+
compareVersions(hook.version, module.version) > 0)
|
|
158
|
+
continue;
|
|
159
|
+
await hook.up(ctx);
|
|
160
|
+
hooks.push({ module: module.name, version: hook.version });
|
|
161
|
+
}
|
|
162
|
+
await conn.query(compile(sql `UPDATE ${sql.id('shutro_module')} SET version = ${module.version}, updated_at = now() WHERE name = ${module.name}`));
|
|
163
|
+
modules.push({ module: module.name, from: row.version, to: module.version });
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return { applied, modules, hooks };
|
|
167
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the live schema of a PostgreSQL schema (namespace) from `pg_catalog` into the same shape as the desired
|
|
3
|
+
* schema. The migration ledger tables (`shutro_*`) are left out.
|
|
4
|
+
*/
|
|
5
|
+
import type { Driver } from '../driver-pg/index.js';
|
|
6
|
+
import type { LiveSchema } from './schema.js';
|
|
7
|
+
/** `'x'::character varying` → `'x'`, `(0)::numeric` → `0`, `now()` unchanged. */
|
|
8
|
+
export declare function normalizeDefault(expression: string | null): string | null;
|
|
9
|
+
/** Reads tables, columns, constraints and indexes of `schema` (default `public`). */
|
|
10
|
+
export declare function readLiveSchema(driver: Driver, schema?: string): Promise<LiveSchema>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { compile, sql } from '../sql/index.js';
|
|
2
|
+
const ON_DELETE = {
|
|
3
|
+
a: 'NO ACTION',
|
|
4
|
+
r: 'RESTRICT',
|
|
5
|
+
c: 'CASCADE',
|
|
6
|
+
n: 'SET NULL',
|
|
7
|
+
};
|
|
8
|
+
/** `'x'::character varying` → `'x'`, `(0)::numeric` → `0`, `now()` unchanged. */
|
|
9
|
+
export function normalizeDefault(expression) {
|
|
10
|
+
if (expression === null)
|
|
11
|
+
return null;
|
|
12
|
+
let e = expression.trim();
|
|
13
|
+
e = e.replace(/::[a-z_ ]+(\([^)]*\))?(\[\])?$/i, '');
|
|
14
|
+
while (e.startsWith('(') && e.endsWith(')'))
|
|
15
|
+
e = e.slice(1, -1);
|
|
16
|
+
return e;
|
|
17
|
+
}
|
|
18
|
+
/** Reads tables, columns, constraints and indexes of `schema` (default `public`). */
|
|
19
|
+
export async function readLiveSchema(driver, schema = 'public') {
|
|
20
|
+
const tables = {};
|
|
21
|
+
const tableRows = await driver.query(compile(sql `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${schema} AND c.relkind IN ('r', 'p') AND NOT c.relispartition ORDER BY c.relname`));
|
|
22
|
+
for (const { name } of tableRows) {
|
|
23
|
+
if (name.startsWith('shutro_'))
|
|
24
|
+
continue;
|
|
25
|
+
tables[name] = {
|
|
26
|
+
columns: {},
|
|
27
|
+
primaryKey: [],
|
|
28
|
+
foreignKeys: {},
|
|
29
|
+
uniques: {},
|
|
30
|
+
checks: {},
|
|
31
|
+
indexes: {},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const columnRows = await driver.query(compile(sql `SELECT c.relname AS "table", a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS notnull, a.attidentity AS identity,
|
|
35
|
+
pg_get_expr(d.adbin, d.adrelid) AS def
|
|
36
|
+
FROM pg_attribute a
|
|
37
|
+
JOIN pg_class c ON c.oid = a.attrelid
|
|
38
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
39
|
+
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
|
|
40
|
+
WHERE n.nspname = ${schema} AND c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped
|
|
41
|
+
ORDER BY c.relname, a.attnum`));
|
|
42
|
+
for (const row of columnRows) {
|
|
43
|
+
const table = tables[row.table];
|
|
44
|
+
if (table === undefined)
|
|
45
|
+
continue;
|
|
46
|
+
table.columns[row.name] = {
|
|
47
|
+
name: row.name,
|
|
48
|
+
type: row.type,
|
|
49
|
+
nullable: !row.notnull,
|
|
50
|
+
default: normalizeDefault(row.def),
|
|
51
|
+
identity: row.identity === 'a' || row.identity === 'd',
|
|
52
|
+
backfill: null,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const constraintRows = await driver.query(compile(sql `SELECT c.relname AS "table", con.conname AS name, con.contype AS type, pg_get_constraintdef(con.oid) AS def, con.confdeltype AS ondelete,
|
|
56
|
+
(SELECT array_agg(a.attname ORDER BY k.ordinality) FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum, ordinality)
|
|
57
|
+
JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum) AS columns,
|
|
58
|
+
fc.relname AS ftable
|
|
59
|
+
FROM pg_constraint con
|
|
60
|
+
JOIN pg_class c ON c.oid = con.conrelid
|
|
61
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
62
|
+
LEFT JOIN pg_class fc ON fc.oid = con.confrelid
|
|
63
|
+
WHERE n.nspname = ${schema}
|
|
64
|
+
ORDER BY c.relname, con.conname`));
|
|
65
|
+
for (const row of constraintRows) {
|
|
66
|
+
const table = tables[row.table];
|
|
67
|
+
if (table === undefined)
|
|
68
|
+
continue;
|
|
69
|
+
const columns = row.columns ?? [];
|
|
70
|
+
switch (row.type) {
|
|
71
|
+
case 'p':
|
|
72
|
+
table.primaryKey = columns;
|
|
73
|
+
break;
|
|
74
|
+
case 'f':
|
|
75
|
+
table.foreignKeys[row.name] = {
|
|
76
|
+
column: columns[0] ?? '',
|
|
77
|
+
references: row.ftable ?? '',
|
|
78
|
+
onDelete: ON_DELETE[row.ondelete ?? 'a'] ?? 'NO ACTION',
|
|
79
|
+
};
|
|
80
|
+
break;
|
|
81
|
+
case 'u':
|
|
82
|
+
table.uniques[row.name] = columns;
|
|
83
|
+
break;
|
|
84
|
+
case 'c':
|
|
85
|
+
table.checks[row.name] = row.def.replace(/^CHECK \((.*)\)$/s, '$1');
|
|
86
|
+
break;
|
|
87
|
+
default:
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const indexRows = await driver.query(compile(sql `SELECT t.relname AS "table", i.relname AS name, ix.indisunique AS "unique", am.amname AS method,
|
|
92
|
+
(SELECT array_agg(a.attname ORDER BY k.ordinality) FROM unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ordinality)
|
|
93
|
+
JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum) AS columns,
|
|
94
|
+
pg_get_indexdef(ix.indexrelid) AS def, ix.indpred IS NOT NULL AS partial
|
|
95
|
+
FROM pg_index ix
|
|
96
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
97
|
+
JOIN pg_class t ON t.oid = ix.indrelid
|
|
98
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
99
|
+
JOIN pg_am am ON am.oid = i.relam
|
|
100
|
+
WHERE n.nspname = ${schema} AND NOT ix.indisprimary
|
|
101
|
+
AND NOT EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = ix.indexrelid)
|
|
102
|
+
ORDER BY t.relname, i.relname`));
|
|
103
|
+
for (const row of indexRows) {
|
|
104
|
+
const table = tables[row.table];
|
|
105
|
+
if (table === undefined)
|
|
106
|
+
continue;
|
|
107
|
+
const opclass = /gin_trgm_ops/.test(row.def) ? 'gin_trgm_ops' : undefined;
|
|
108
|
+
const where = row.partial ? (/ WHERE \((.*)\)$/s.exec(row.def)?.[1] ?? '') : undefined;
|
|
109
|
+
table.indexes[row.name] = {
|
|
110
|
+
columns: row.columns ?? [],
|
|
111
|
+
unique: row.unique,
|
|
112
|
+
method: row.method,
|
|
113
|
+
...(opclass === undefined ? {} : { opclass }),
|
|
114
|
+
...(where === undefined ? {} : { where }),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const extensionRows = await driver.query(compile(sql `SELECT extname AS name FROM pg_extension ORDER BY extname`));
|
|
118
|
+
const result = {};
|
|
119
|
+
for (const [name, t] of Object.entries(tables))
|
|
120
|
+
result[name] = { name, ...t };
|
|
121
|
+
return { tables: result, extensions: extensionRows.map((r) => r.name) };
|
|
122
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diffs the desired schema against the live one into an ordered list of operations. Destructive operations
|
|
3
|
+
* (drops, type changes) are marked so that applying them needs explicit consent.
|
|
4
|
+
*/
|
|
5
|
+
import type { ColumnSpec, ForeignKeySpec, IndexSpec, LiveSchema, Schema, TableSpec } from './schema.js';
|
|
6
|
+
/** One schema change. */
|
|
7
|
+
export type Operation = {
|
|
8
|
+
readonly kind: 'createExtension';
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly destructive: false;
|
|
11
|
+
} | {
|
|
12
|
+
readonly kind: 'createTable';
|
|
13
|
+
readonly table: TableSpec;
|
|
14
|
+
readonly destructive: false;
|
|
15
|
+
} | {
|
|
16
|
+
readonly kind: 'dropTable';
|
|
17
|
+
readonly table: string;
|
|
18
|
+
readonly destructive: true;
|
|
19
|
+
} | {
|
|
20
|
+
readonly kind: 'addColumn';
|
|
21
|
+
readonly table: string;
|
|
22
|
+
readonly column: ColumnSpec;
|
|
23
|
+
readonly destructive: false;
|
|
24
|
+
} | {
|
|
25
|
+
readonly kind: 'dropColumn';
|
|
26
|
+
readonly table: string;
|
|
27
|
+
readonly column: string;
|
|
28
|
+
readonly destructive: true;
|
|
29
|
+
} | {
|
|
30
|
+
readonly kind: 'alterType';
|
|
31
|
+
readonly table: string;
|
|
32
|
+
readonly column: string;
|
|
33
|
+
readonly from: string;
|
|
34
|
+
readonly to: string;
|
|
35
|
+
readonly destructive: true;
|
|
36
|
+
} | {
|
|
37
|
+
readonly kind: 'setDefault';
|
|
38
|
+
readonly table: string;
|
|
39
|
+
readonly column: string;
|
|
40
|
+
readonly default: string;
|
|
41
|
+
readonly destructive: false;
|
|
42
|
+
} | {
|
|
43
|
+
readonly kind: 'dropDefault';
|
|
44
|
+
readonly table: string;
|
|
45
|
+
readonly column: string;
|
|
46
|
+
readonly destructive: false;
|
|
47
|
+
} | {
|
|
48
|
+
readonly kind: 'backfill';
|
|
49
|
+
readonly table: string;
|
|
50
|
+
readonly column: string;
|
|
51
|
+
readonly default: string;
|
|
52
|
+
readonly destructive: false;
|
|
53
|
+
} | {
|
|
54
|
+
readonly kind: 'setNotNull';
|
|
55
|
+
readonly table: string;
|
|
56
|
+
readonly column: string;
|
|
57
|
+
readonly destructive: false;
|
|
58
|
+
} | {
|
|
59
|
+
readonly kind: 'dropNotNull';
|
|
60
|
+
readonly table: string;
|
|
61
|
+
readonly column: string;
|
|
62
|
+
readonly destructive: false;
|
|
63
|
+
} | {
|
|
64
|
+
readonly kind: 'addForeignKey';
|
|
65
|
+
readonly table: string;
|
|
66
|
+
readonly name: string;
|
|
67
|
+
readonly foreignKey: ForeignKeySpec;
|
|
68
|
+
readonly destructive: false;
|
|
69
|
+
} | {
|
|
70
|
+
readonly kind: 'addUnique';
|
|
71
|
+
readonly table: string;
|
|
72
|
+
readonly name: string;
|
|
73
|
+
readonly columns: readonly string[];
|
|
74
|
+
readonly destructive: false;
|
|
75
|
+
} | {
|
|
76
|
+
readonly kind: 'addCheck';
|
|
77
|
+
readonly table: string;
|
|
78
|
+
readonly name: string;
|
|
79
|
+
readonly expression: string;
|
|
80
|
+
readonly destructive: false;
|
|
81
|
+
} | {
|
|
82
|
+
readonly kind: 'dropConstraint';
|
|
83
|
+
readonly table: string;
|
|
84
|
+
readonly name: string;
|
|
85
|
+
readonly destructive: false;
|
|
86
|
+
} | {
|
|
87
|
+
readonly kind: 'createIndex';
|
|
88
|
+
readonly table: string;
|
|
89
|
+
readonly name: string;
|
|
90
|
+
readonly index: IndexSpec;
|
|
91
|
+
readonly destructive: false;
|
|
92
|
+
} | {
|
|
93
|
+
readonly kind: 'dropIndex';
|
|
94
|
+
readonly name: string;
|
|
95
|
+
readonly destructive: false;
|
|
96
|
+
};
|
|
97
|
+
/** Computes the operations that turn `live` into `desired`, in a safe order. */
|
|
98
|
+
export declare function diffSchema(desired: Schema, live: LiveSchema): Operation[];
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
function sameIndex(a, b) {
|
|
2
|
+
return (a.unique === b.unique &&
|
|
3
|
+
a.method === b.method &&
|
|
4
|
+
a.columns.join(',') === b.columns.join(',') &&
|
|
5
|
+
(a.opclass ?? '') === (b.opclass ?? '') &&
|
|
6
|
+
(a.where ?? '') === (b.where ?? ''));
|
|
7
|
+
}
|
|
8
|
+
function sameForeignKey(a, b) {
|
|
9
|
+
return a.column === b.column && a.references === b.references && a.onDelete === b.onDelete;
|
|
10
|
+
}
|
|
11
|
+
/** Computes the operations that turn `live` into `desired`, in a safe order. */
|
|
12
|
+
export function diffSchema(desired, live) {
|
|
13
|
+
const early = []; // extensions, tables, columns
|
|
14
|
+
const constraints = []; // drops of changed constraints/indexes, then adds (FKs after all tables exist)
|
|
15
|
+
const indexes = [];
|
|
16
|
+
const late = []; // destructive drops last
|
|
17
|
+
for (const ext of desired.extensions)
|
|
18
|
+
if (!live.extensions.includes(ext))
|
|
19
|
+
early.push({ kind: 'createExtension', name: ext, destructive: false });
|
|
20
|
+
for (const [name, table] of Object.entries(desired.tables)) {
|
|
21
|
+
const current = live.tables[name];
|
|
22
|
+
if (current === undefined) {
|
|
23
|
+
early.push({ kind: 'createTable', table, destructive: false });
|
|
24
|
+
for (const [fkName, fk] of Object.entries(table.foreignKeys))
|
|
25
|
+
constraints.push({
|
|
26
|
+
kind: 'addForeignKey',
|
|
27
|
+
table: name,
|
|
28
|
+
name: fkName,
|
|
29
|
+
foreignKey: fk,
|
|
30
|
+
destructive: false,
|
|
31
|
+
});
|
|
32
|
+
for (const [uName, columns] of Object.entries(table.uniques))
|
|
33
|
+
constraints.push({
|
|
34
|
+
kind: 'addUnique',
|
|
35
|
+
table: name,
|
|
36
|
+
name: uName,
|
|
37
|
+
columns,
|
|
38
|
+
destructive: false,
|
|
39
|
+
});
|
|
40
|
+
for (const [cName, expression] of Object.entries(table.checks))
|
|
41
|
+
constraints.push({
|
|
42
|
+
kind: 'addCheck',
|
|
43
|
+
table: name,
|
|
44
|
+
name: cName,
|
|
45
|
+
expression,
|
|
46
|
+
destructive: false,
|
|
47
|
+
});
|
|
48
|
+
for (const [iName, index] of Object.entries(table.indexes))
|
|
49
|
+
indexes.push({ kind: 'createIndex', table: name, name: iName, index, destructive: false });
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
for (const [colName, column] of Object.entries(table.columns)) {
|
|
53
|
+
const existing = current.columns[colName];
|
|
54
|
+
if (existing === undefined) {
|
|
55
|
+
early.push({ kind: 'addColumn', table: name, column, destructive: false });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (existing.type !== column.type)
|
|
59
|
+
early.push({
|
|
60
|
+
kind: 'alterType',
|
|
61
|
+
table: name,
|
|
62
|
+
column: colName,
|
|
63
|
+
from: existing.type,
|
|
64
|
+
to: column.type,
|
|
65
|
+
destructive: true,
|
|
66
|
+
});
|
|
67
|
+
if ((existing.default ?? null) !== (column.default ?? null)) {
|
|
68
|
+
if (column.default === null)
|
|
69
|
+
early.push({ kind: 'dropDefault', table: name, column: colName, destructive: false });
|
|
70
|
+
else
|
|
71
|
+
early.push({
|
|
72
|
+
kind: 'setDefault',
|
|
73
|
+
table: name,
|
|
74
|
+
column: colName,
|
|
75
|
+
default: column.default,
|
|
76
|
+
destructive: false,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (existing.nullable && !column.nullable) {
|
|
80
|
+
if (column.backfill !== null)
|
|
81
|
+
early.push({
|
|
82
|
+
kind: 'backfill',
|
|
83
|
+
table: name,
|
|
84
|
+
column: colName,
|
|
85
|
+
default: column.backfill,
|
|
86
|
+
destructive: false,
|
|
87
|
+
});
|
|
88
|
+
early.push({ kind: 'setNotNull', table: name, column: colName, destructive: false });
|
|
89
|
+
}
|
|
90
|
+
else if (!existing.nullable && column.nullable) {
|
|
91
|
+
early.push({ kind: 'dropNotNull', table: name, column: colName, destructive: false });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const colName of Object.keys(current.columns)) {
|
|
95
|
+
if (table.columns[colName] === undefined)
|
|
96
|
+
late.push({ kind: 'dropColumn', table: name, column: colName, destructive: true });
|
|
97
|
+
}
|
|
98
|
+
for (const [fkName, fk] of Object.entries(current.foreignKeys)) {
|
|
99
|
+
const wanted = table.foreignKeys[fkName];
|
|
100
|
+
if (wanted === undefined || !sameForeignKey(wanted, fk))
|
|
101
|
+
constraints.push({ kind: 'dropConstraint', table: name, name: fkName, destructive: false });
|
|
102
|
+
}
|
|
103
|
+
for (const [fkName, fk] of Object.entries(table.foreignKeys)) {
|
|
104
|
+
const existing = current.foreignKeys[fkName];
|
|
105
|
+
if (existing === undefined || !sameForeignKey(existing, fk))
|
|
106
|
+
constraints.push({
|
|
107
|
+
kind: 'addForeignKey',
|
|
108
|
+
table: name,
|
|
109
|
+
name: fkName,
|
|
110
|
+
foreignKey: fk,
|
|
111
|
+
destructive: false,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
for (const [uName, columns] of Object.entries(current.uniques)) {
|
|
115
|
+
const wanted = table.uniques[uName];
|
|
116
|
+
if (wanted === undefined || wanted.join(',') !== columns.join(','))
|
|
117
|
+
constraints.push({ kind: 'dropConstraint', table: name, name: uName, destructive: false });
|
|
118
|
+
}
|
|
119
|
+
for (const [uName, columns] of Object.entries(table.uniques)) {
|
|
120
|
+
const existing = current.uniques[uName];
|
|
121
|
+
if (existing === undefined || existing.join(',') !== columns.join(','))
|
|
122
|
+
constraints.push({
|
|
123
|
+
kind: 'addUnique',
|
|
124
|
+
table: name,
|
|
125
|
+
name: uName,
|
|
126
|
+
columns,
|
|
127
|
+
destructive: false,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
for (const cName of Object.keys(current.checks)) {
|
|
131
|
+
if (table.checks[cName] === undefined)
|
|
132
|
+
constraints.push({ kind: 'dropConstraint', table: name, name: cName, destructive: false });
|
|
133
|
+
}
|
|
134
|
+
for (const [cName, expression] of Object.entries(table.checks)) {
|
|
135
|
+
if (current.checks[cName] === undefined)
|
|
136
|
+
constraints.push({
|
|
137
|
+
kind: 'addCheck',
|
|
138
|
+
table: name,
|
|
139
|
+
name: cName,
|
|
140
|
+
expression,
|
|
141
|
+
destructive: false,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
for (const [iName, index] of Object.entries(current.indexes)) {
|
|
145
|
+
const wanted = table.indexes[iName];
|
|
146
|
+
if (wanted === undefined || !sameIndex(wanted, index))
|
|
147
|
+
constraints.push({ kind: 'dropIndex', name: iName, destructive: false });
|
|
148
|
+
}
|
|
149
|
+
for (const [iName, index] of Object.entries(table.indexes)) {
|
|
150
|
+
const existing = current.indexes[iName];
|
|
151
|
+
if (existing === undefined || !sameIndex(existing, index))
|
|
152
|
+
indexes.push({ kind: 'createIndex', table: name, name: iName, index, destructive: false });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for (const name of Object.keys(live.tables)) {
|
|
156
|
+
if (desired.tables[name] === undefined)
|
|
157
|
+
late.push({ kind: 'dropTable', table: name, destructive: true });
|
|
158
|
+
}
|
|
159
|
+
return [...early, ...constraints, ...indexes, ...late];
|
|
160
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Machine-readable reason for a {@link MigrationError}. */
|
|
2
|
+
export type MigrationErrorCode = 'MIGRATION' | 'MIGRATION_DESTRUCTIVE' | 'MIGRATION_CHECKSUM' | 'MIGRATION_FILE';
|
|
3
|
+
/** Base class of `@shutro/migrate` errors: the message says what went wrong and ends with `hint`. */
|
|
4
|
+
export declare class MigrationError extends Error {
|
|
5
|
+
readonly code: MigrationErrorCode;
|
|
6
|
+
readonly hint: string;
|
|
7
|
+
constructor(problem: string, hint: string, code?: MigrationErrorCode);
|
|
8
|
+
}
|
|
9
|
+
/** A migration file contains destructive statements and `allowDestructive` is not set. */
|
|
10
|
+
export declare class DestructiveMigrationError extends MigrationError {
|
|
11
|
+
readonly statements: readonly string[];
|
|
12
|
+
constructor(file: string, statements: readonly string[]);
|
|
13
|
+
}
|
|
14
|
+
/** An applied migration file was edited afterwards. */
|
|
15
|
+
export declare class MigrationChecksumError extends MigrationError {
|
|
16
|
+
constructor(file: string);
|
|
17
|
+
}
|
|
18
|
+
/** A migration file name or content that can't be used. */
|
|
19
|
+
export declare class MigrationFileError extends MigrationError {
|
|
20
|
+
constructor(problem: string, hint: string);
|
|
21
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Base class of `@shutro/migrate` errors: the message says what went wrong and ends with `hint`. */
|
|
2
|
+
export class MigrationError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
hint;
|
|
5
|
+
constructor(problem, hint, code = 'MIGRATION') {
|
|
6
|
+
super(`${problem} ${hint}`);
|
|
7
|
+
this.name = new.target.name;
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.hint = hint;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** A migration file contains destructive statements and `allowDestructive` is not set. */
|
|
13
|
+
export class DestructiveMigrationError extends MigrationError {
|
|
14
|
+
statements;
|
|
15
|
+
constructor(file, statements) {
|
|
16
|
+
super(`Migration ${file} contains ${statements.length} destructive statement(s): ${statements.join('; ')}.`, 'Review the data loss, then apply with { allowDestructive: true }, or edit the migration file.', 'MIGRATION_DESTRUCTIVE');
|
|
17
|
+
this.statements = statements;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** An applied migration file was edited afterwards. */
|
|
21
|
+
export class MigrationChecksumError extends MigrationError {
|
|
22
|
+
constructor(file) {
|
|
23
|
+
super(`Migration ${file} was changed after it was applied.`, 'Applied migrations are immutable: restore the file, or write a new migration for the change.', 'MIGRATION_CHECKSUM');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** A migration file name or content that can't be used. */
|
|
27
|
+
export class MigrationFileError extends MigrationError {
|
|
28
|
+
constructor(problem, hint) {
|
|
29
|
+
super(problem, hint, 'MIGRATION_FILE');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* `@shutro/migrate`: schema diff against the live database, versioned SQL migrations, and per-module data-migration
|
|
4
|
+
* hooks (`CLAUDE.md` layer 12).
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* const plan = await planMigration({ driver, registry });
|
|
9
|
+
* await writeMigrationFile({ dir: 'migrations', name: 'add_margin', plan });
|
|
10
|
+
* await applyMigrations({ driver, dir: 'migrations', registry });
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export { applyMigrations, type MigrationFile, type MigrationPlan, type MigrationResult, type MigrationStatus, migrationStatus, parseMigrationFile, planMigration, writeMigrationFile, } from './apply.js';
|
|
14
|
+
export { normalizeDefault, readLiveSchema } from './catalog.js';
|
|
15
|
+
export { diffSchema, type Operation } from './diff.js';
|
|
16
|
+
export { DestructiveMigrationError, MigrationChecksumError, MigrationError, type MigrationErrorCode, MigrationFileError, } from './errors.js';
|
|
17
|
+
export { renderOperation, renderOperations } from './render.js';
|
|
18
|
+
export { type ColumnSpec, canonicalType, columnName, desiredSchema, type ForeignKeySpec, type IndexSpec, type LiveSchema, literalOf, type Schema, type TableSpec, } from './schema.js';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* `@shutro/migrate`: schema diff against the live database, versioned SQL migrations, and per-module data-migration
|
|
4
|
+
* hooks (`CLAUDE.md` layer 12).
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* const plan = await planMigration({ driver, registry });
|
|
9
|
+
* await writeMigrationFile({ dir: 'migrations', name: 'add_margin', plan });
|
|
10
|
+
* await applyMigrations({ driver, dir: 'migrations', registry });
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export { applyMigrations, migrationStatus, parseMigrationFile, planMigration, writeMigrationFile, } from './apply.js';
|
|
14
|
+
export { normalizeDefault, readLiveSchema } from './catalog.js';
|
|
15
|
+
export { diffSchema } from './diff.js';
|
|
16
|
+
export { DestructiveMigrationError, MigrationChecksumError, MigrationError, MigrationFileError, } from './errors.js';
|
|
17
|
+
export { renderOperation, renderOperations } from './render.js';
|
|
18
|
+
export { canonicalType, columnName, desiredSchema, literalOf, } from './schema.js';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Operation } from './diff.js';
|
|
2
|
+
/** Renders one operation as a statement. */
|
|
3
|
+
export declare function renderOperation(op: Operation): string;
|
|
4
|
+
/** Renders every operation, in order. */
|
|
5
|
+
export declare function renderOperations(operations: readonly Operation[]): string[];
|