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,581 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes (RFC 0004 §7.6): `create()` inserts immediately, `write()` goes through the unit of work and is flushed in
|
|
3
|
+
* set-based statements, `unlink()` deletes immediately. Every change is journaled for savepoint rollback and
|
|
4
|
+
* recorded as a compute trigger (RFC 0008 §7.2).
|
|
5
|
+
*/
|
|
6
|
+
import { compile, sql } from '../../sql/index.js';
|
|
7
|
+
import { MissingRecordError } from '../errors.js';
|
|
8
|
+
import { targetOf } from '../registry/registry.js';
|
|
9
|
+
import { trackChange, trackedKeys, trackSnapshot } from './audit.js';
|
|
10
|
+
import { junctionTable } from './relations.js';
|
|
11
|
+
import { assertAccess, assertFields, assertRecords, storedValue } from './security.js';
|
|
12
|
+
import { fillSequences, UNNUMBERED } from './sequences.js';
|
|
13
|
+
import { arrayType, fail, normalize, valueRef } from './values.js';
|
|
14
|
+
function translationOf(internals) {
|
|
15
|
+
return { lang: internals.env.lang, source: internals.sourceLang };
|
|
16
|
+
}
|
|
17
|
+
const CHUNK = 1000;
|
|
18
|
+
function isX2Many(field) {
|
|
19
|
+
return field.kind === 'one2many' || field.kind === 'many2many';
|
|
20
|
+
}
|
|
21
|
+
/** Resolves a field default (a value or `(env) => value`). */
|
|
22
|
+
function defaultOf(field, env) {
|
|
23
|
+
return typeof field.default === 'function'
|
|
24
|
+
? field.default(env)
|
|
25
|
+
: field.default;
|
|
26
|
+
}
|
|
27
|
+
/** A many2one of `model` changed: the one2many lists of the old / new parents changed too (RFC 0008 §7.1). */
|
|
28
|
+
function triggerParents(internals, model, key, parents) {
|
|
29
|
+
const ids = parents.filter((p) => typeof p === 'number');
|
|
30
|
+
if (ids.length === 0)
|
|
31
|
+
return;
|
|
32
|
+
const target = targetOf(model.fields[key]);
|
|
33
|
+
if (target === undefined)
|
|
34
|
+
return;
|
|
35
|
+
const parentModel = internals.registry.get(target).model;
|
|
36
|
+
for (const [pKey, pField] of Object.entries(parentModel.fields)) {
|
|
37
|
+
if (pField.kind === 'one2many' &&
|
|
38
|
+
pField.inverseField === key &&
|
|
39
|
+
targetOf(pField) === model.name)
|
|
40
|
+
internals.trigger(parentModel.name, pKey, ids);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Splits a row into normalized stored values and x2many commands, validating keys. */
|
|
44
|
+
function splitRow(model, row, mode, host, id) {
|
|
45
|
+
const stored = new Map();
|
|
46
|
+
const commands = new Map();
|
|
47
|
+
const siblings = (key) => stored.has(key)
|
|
48
|
+
? stored.get(key)
|
|
49
|
+
: id === undefined
|
|
50
|
+
? undefined
|
|
51
|
+
: host.values(model.name, id)?.get(key);
|
|
52
|
+
for (const [key, value] of Object.entries(row)) {
|
|
53
|
+
if (value === undefined)
|
|
54
|
+
continue;
|
|
55
|
+
const field = model.fields[key];
|
|
56
|
+
if (field === undefined || key === 'id')
|
|
57
|
+
fail(model, [key], `'${key}' is not a writable field.`, `Fields: ${Object.keys(model.fields)
|
|
58
|
+
.filter((k) => k !== 'id')
|
|
59
|
+
.join(', ')}.`);
|
|
60
|
+
if (field.readonly && !(mode === 'create' && field.sequence !== undefined)) {
|
|
61
|
+
fail(model, [key], `field '${key}' is readonly.`, field.kind === 'state'
|
|
62
|
+
? 'State changes through transitions.'
|
|
63
|
+
: field.computed
|
|
64
|
+
? 'It is computed; write the fields it depends on instead.'
|
|
65
|
+
: 'It is maintained by the ORM.');
|
|
66
|
+
}
|
|
67
|
+
if (isX2Many(field)) {
|
|
68
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
69
|
+
fail(model, [key], `field '${key}' expects x2many commands.`, 'Use { create: [...], link: [...], set: [...], unlink: [...], delete: [...], update: [...], clear: true }.');
|
|
70
|
+
commands.set(key, value);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (model.columns[key] === undefined)
|
|
74
|
+
fail(model, [key], `field '${key}' is not stored.`, 'Non-stored computed fields cannot be written.');
|
|
75
|
+
stored.set(key, normalize(model, key, field, value, siblings, translationOf(host.internals)));
|
|
76
|
+
}
|
|
77
|
+
return { stored, commands };
|
|
78
|
+
}
|
|
79
|
+
// ------------------------------------------------------------------------------------------------- create
|
|
80
|
+
/** Inserts `rows` and returns their ids in input order. Children and links are created too. */
|
|
81
|
+
export async function createRecords(host, model, rows, options = {}) {
|
|
82
|
+
const { internals } = host;
|
|
83
|
+
if (rows.length === 0)
|
|
84
|
+
return [];
|
|
85
|
+
assertAccess(internals, model, 'create');
|
|
86
|
+
if (options.copy === true)
|
|
87
|
+
assertAccess(internals, model, 'import');
|
|
88
|
+
for (const row of rows)
|
|
89
|
+
assertFields(internals, model, Object.keys(row), 'write');
|
|
90
|
+
// The default projection leaves out binary fields: add every stored key a row gives explicitly.
|
|
91
|
+
const given = new Set(rows.flatMap((r) => Object.keys(r).filter((k) => r[k] !== undefined)));
|
|
92
|
+
const columns = [...new Set([...host.defaults(model), ...given])].filter((k) => k !== 'id' && model.columns[k] !== undefined);
|
|
93
|
+
const prepared = rows.map((row) => {
|
|
94
|
+
const { stored, commands } = splitRow(model, row, 'create', host, undefined);
|
|
95
|
+
const missing = [];
|
|
96
|
+
for (const key of columns) {
|
|
97
|
+
if (stored.has(key))
|
|
98
|
+
continue;
|
|
99
|
+
const field = model.fields[key];
|
|
100
|
+
if (field === undefined)
|
|
101
|
+
continue;
|
|
102
|
+
let value;
|
|
103
|
+
if (key === 'createdAt' || key === 'updatedAt')
|
|
104
|
+
value = internals.now;
|
|
105
|
+
else if (key === 'createdBy' || key === 'updatedBy')
|
|
106
|
+
value = internals.uid;
|
|
107
|
+
else
|
|
108
|
+
value = defaultOf(field, internals.env) ?? null;
|
|
109
|
+
// Stored computes are filled after the insert (RFC 0008 §7.6); sequences before it (RFC 0012 §7.4).
|
|
110
|
+
if (value === null && field.sequence?.on === 'manual' && field.required)
|
|
111
|
+
value = UNNUMBERED;
|
|
112
|
+
if (value === null && field.required && !field.computed && field.sequence === undefined)
|
|
113
|
+
missing.push(key);
|
|
114
|
+
stored.set(key, value === null
|
|
115
|
+
? null
|
|
116
|
+
: normalize(model, key, field, value, (k) => stored.get(k), translationOf(internals)));
|
|
117
|
+
}
|
|
118
|
+
if (missing.length > 0)
|
|
119
|
+
fail(model, missing, `required field(s) ${missing.map((m) => `'${m}'`).join(', ')} are missing.`, 'Provide a value, or give the field a default in its definition.');
|
|
120
|
+
return { stored, commands };
|
|
121
|
+
});
|
|
122
|
+
await fillSequences(internals, model, prepared);
|
|
123
|
+
const ids = [];
|
|
124
|
+
if (options.copy === true)
|
|
125
|
+
ids.push(...(await copyRows(internals, model, columns, prepared)));
|
|
126
|
+
for (let i = 0; i < (options.copy === true ? 0 : prepared.length); i += CHUNK) {
|
|
127
|
+
const chunk = prepared.slice(i, i + CHUNK);
|
|
128
|
+
const arrays = columns.map((key) => sql.array(chunk.map((p) => storedValue(internals, model.fields[key], p.stored.get(key))), arrayType(model.fields[key])));
|
|
129
|
+
const rowsOut = await internals.query(compile(sql `INSERT INTO ${sql.id(model.table)} (${sql.join(columns.map((k) => sql.id(model.columns[k] ?? '')))}) SELECT ${sql.join(columns.map((k) => valueRef(model.fields[k], model.columns[k] ?? '')))} FROM unnest(${sql.join(arrays)}) AS ${sql.id('v')}(${sql.join(columns.map((k) => sql.id(model.columns[k] ?? '')))}) RETURNING ${sql.id('id')}`));
|
|
130
|
+
if (rowsOut.length !== chunk.length)
|
|
131
|
+
throw new MissingRecordError(model.name, []);
|
|
132
|
+
for (const r of rowsOut)
|
|
133
|
+
ids.push(Number(r.id));
|
|
134
|
+
}
|
|
135
|
+
const parentsByKey = new Map();
|
|
136
|
+
prepared.forEach((p, i) => {
|
|
137
|
+
const id = ids[i];
|
|
138
|
+
const values = host.values(model.name, id, true);
|
|
139
|
+
for (const [key, value] of p.stored) {
|
|
140
|
+
// Stored computes are not cached yet: reading one before the flush point says so (RFC 0008 §7.2).
|
|
141
|
+
if (!model.fields[key].computed)
|
|
142
|
+
values.set(key, value);
|
|
143
|
+
if (model.fields[key].kind === 'many2one' && value !== null)
|
|
144
|
+
parentsByKey.set(key, [...(parentsByKey.get(key) ?? []), value]);
|
|
145
|
+
}
|
|
146
|
+
internals.journal({ kind: 'created', model: model.name, id });
|
|
147
|
+
});
|
|
148
|
+
await host.ensureValueObjects(model, ids, new Set(columns));
|
|
149
|
+
await assertRecords(internals, model, ids, 'create'); // create rules apply to the inserted rows (RFC 0014 §7.3)
|
|
150
|
+
prepared.forEach((p, i) => {
|
|
151
|
+
trackSnapshot(internals, model, ids[i], 'create', p.stored);
|
|
152
|
+
});
|
|
153
|
+
// Triggers: every stored value of a new record "changed"; its own stored computes are computed at the next flush point.
|
|
154
|
+
for (const key of columns) {
|
|
155
|
+
const field = model.fields[key];
|
|
156
|
+
if (field.computed)
|
|
157
|
+
continue;
|
|
158
|
+
internals.trigger(model.name, key, ids);
|
|
159
|
+
}
|
|
160
|
+
for (const [key, parents] of parentsByKey)
|
|
161
|
+
triggerParents(internals, model, key, parents);
|
|
162
|
+
for (const f of internals.registry.compute.stored(model.name))
|
|
163
|
+
internals.markToCompute(model.name, f.key, ids);
|
|
164
|
+
// one2many `create` commands of every new parent become one child insert per field (no INSERT per parent).
|
|
165
|
+
const batched = new Map();
|
|
166
|
+
for (const [i, p] of prepared.entries()) {
|
|
167
|
+
for (const [key, commands] of p.commands) {
|
|
168
|
+
const field = model.fields[key];
|
|
169
|
+
const onlyCreate = Object.entries(commands).every(([c, v]) => c === 'create' || v === undefined);
|
|
170
|
+
if (field.kind === 'one2many' && onlyCreate && Array.isArray(commands['create'])) {
|
|
171
|
+
const list = batched.get(key) ?? [];
|
|
172
|
+
list.push({ parent: ids[i], rows: commands['create'] });
|
|
173
|
+
batched.set(key, list);
|
|
174
|
+
}
|
|
175
|
+
else
|
|
176
|
+
await applyCommands(host, model, ids[i], key, commands, 'create');
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
for (const [key, parents] of batched) {
|
|
180
|
+
const field = model.fields[key];
|
|
181
|
+
const target = internals.registry.get(field.target).model;
|
|
182
|
+
const inverse = field.inverseField ?? '';
|
|
183
|
+
const childRows = parents.flatMap(({ parent, rows: rs }) => rs.map((r) => ({ ...r, [inverse]: parent })));
|
|
184
|
+
const childIds = await createRecords(host, target, childRows);
|
|
185
|
+
let at = 0;
|
|
186
|
+
for (const { parent, rows: rs } of parents) {
|
|
187
|
+
host.values(model.name, parent, true).set(key, childIds.slice(at, at + rs.length));
|
|
188
|
+
at += rs.length;
|
|
189
|
+
}
|
|
190
|
+
internals.trigger(model.name, key, parents.map((p) => p.parent));
|
|
191
|
+
}
|
|
192
|
+
return ids;
|
|
193
|
+
}
|
|
194
|
+
// ---------------------------------------------------------------------------------------------------- copy
|
|
195
|
+
/** One value in COPY text format: \N for null, backslash escapes, bytea as hex (RFC 0015 §7.1). */
|
|
196
|
+
export function copyField(value) {
|
|
197
|
+
if (value === null || value === undefined)
|
|
198
|
+
return '\\N';
|
|
199
|
+
let text;
|
|
200
|
+
if (typeof value === 'boolean')
|
|
201
|
+
text = value ? 't' : 'f';
|
|
202
|
+
else if (value instanceof Uint8Array)
|
|
203
|
+
text = `\\x${Buffer.from(value).toString('hex')}`;
|
|
204
|
+
else
|
|
205
|
+
text = String(value);
|
|
206
|
+
return text
|
|
207
|
+
.replace(/\\/g, '\\\\')
|
|
208
|
+
.replace(/\n/g, '\\n')
|
|
209
|
+
.replace(/\r/g, '\\r')
|
|
210
|
+
.replace(/\t/g, '\\t');
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Bulk insert through `COPY ... FROM STDIN`: ids are reserved from the identity sequence in one query (COPY writes
|
|
214
|
+
* identity values as given), then every row streams in one statement. Returns the ids in input order.
|
|
215
|
+
*/
|
|
216
|
+
async function copyRows(internals, model, columns, prepared) {
|
|
217
|
+
const reserved = await internals.query(compile(sql `SELECT nextval(pg_get_serial_sequence(${model.table}, ${'id'})) AS ${sql.id('id')} FROM generate_series(1, ${prepared.length})`));
|
|
218
|
+
const ids = reserved.map((r) => Number(r.id));
|
|
219
|
+
const fields = columns.map((k) => model.fields[k]);
|
|
220
|
+
const lines = prepared.map((p, i) => [
|
|
221
|
+
String(ids[i]),
|
|
222
|
+
...columns.map((k, c) => copyField(storedValue(internals, fields[c], p.stored.get(k)))),
|
|
223
|
+
].join('\t'));
|
|
224
|
+
const names = [sql.id('id'), ...columns.map((k) => sql.id(model.columns[k] ?? ''))];
|
|
225
|
+
const count = await internals.copyIn(compile(sql `COPY ${sql.id(model.table)} (${sql.join(names)}) FROM STDIN`), lines);
|
|
226
|
+
if (count !== prepared.length)
|
|
227
|
+
throw new MissingRecordError(model.name, []);
|
|
228
|
+
return ids;
|
|
229
|
+
}
|
|
230
|
+
// -------------------------------------------------------------------------------------------------- write
|
|
231
|
+
/** Applies `values` to `ids` in the cache and marks them dirty; x2many commands run immediately. */
|
|
232
|
+
export async function writeRecords(host, model, ids, values) {
|
|
233
|
+
const { internals } = host;
|
|
234
|
+
if (ids.length === 0)
|
|
235
|
+
return;
|
|
236
|
+
assertAccess(internals, model, 'write');
|
|
237
|
+
assertFields(internals, model, Object.keys(values), 'write');
|
|
238
|
+
await assertRecords(internals, model, ids, 'write');
|
|
239
|
+
// Money / Quantity checks need the sibling currency / uom values; a moved record needs its old parent.
|
|
240
|
+
const needed = new Set();
|
|
241
|
+
for (const key of Object.keys(values)) {
|
|
242
|
+
const field = model.fields[key];
|
|
243
|
+
if (field?.currencyField !== undefined)
|
|
244
|
+
needed.add(field.currencyField);
|
|
245
|
+
if (field?.uomField !== undefined)
|
|
246
|
+
needed.add(field.uomField);
|
|
247
|
+
if (field?.kind === 'many2one' && internals.registry.compute.inverseKeys(model.name).has(key))
|
|
248
|
+
needed.add(key);
|
|
249
|
+
}
|
|
250
|
+
// The audit trail needs the exact old values of tracked fields (RFC 0013 §7.2).
|
|
251
|
+
if (internals.env.flags.tracking) {
|
|
252
|
+
const tracked = trackedKeys(model);
|
|
253
|
+
for (const key of Object.keys(values)) {
|
|
254
|
+
if (!tracked.has(key))
|
|
255
|
+
continue;
|
|
256
|
+
needed.add(key);
|
|
257
|
+
const field = model.fields[key];
|
|
258
|
+
if (field?.currencyField !== undefined)
|
|
259
|
+
needed.add(field.currencyField);
|
|
260
|
+
if (field?.uomField !== undefined)
|
|
261
|
+
needed.add(field.uomField);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (needed.size > 0)
|
|
265
|
+
await host.fetch(model, ids, needed);
|
|
266
|
+
const changedByKey = new Map();
|
|
267
|
+
const parentsByKey = new Map();
|
|
268
|
+
const inverses = new Set();
|
|
269
|
+
for (const id of ids) {
|
|
270
|
+
const { stored, commands } = splitRow(model, values, 'write', host, id);
|
|
271
|
+
const cached = host.values(model.name, id, true);
|
|
272
|
+
for (const [key, value] of stored) {
|
|
273
|
+
const field = model.fields[key];
|
|
274
|
+
if (field.kind === 'many2one') {
|
|
275
|
+
invalidateInverseLists(host, model, key, cached.get(key), value);
|
|
276
|
+
parentsByKey.set(key, [...(parentsByKey.get(key) ?? []), cached.get(key), value]);
|
|
277
|
+
}
|
|
278
|
+
internals.journal({
|
|
279
|
+
kind: 'value',
|
|
280
|
+
model: model.name,
|
|
281
|
+
id,
|
|
282
|
+
key,
|
|
283
|
+
had: cached.has(key),
|
|
284
|
+
prev: cached.get(key),
|
|
285
|
+
wasDirty: internals.isDirty(model.name, id, key),
|
|
286
|
+
});
|
|
287
|
+
trackChange(internals, model, id, key, cached.get(key), value, (k) => k === key ? value : (stored.get(k) ?? cached.get(k)));
|
|
288
|
+
cached.set(key, value);
|
|
289
|
+
internals.markDirty(model.name, id, key);
|
|
290
|
+
changedByKey.set(key, [...(changedByKey.get(key) ?? []), id]);
|
|
291
|
+
if (field.computed && field.inverse !== undefined)
|
|
292
|
+
inverses.add(key);
|
|
293
|
+
}
|
|
294
|
+
for (const [key, cmds] of commands)
|
|
295
|
+
await applyCommands(host, model, id, key, cmds, 'write');
|
|
296
|
+
}
|
|
297
|
+
for (const [key, changed] of changedByKey)
|
|
298
|
+
internals.trigger(model.name, key, changed);
|
|
299
|
+
for (const [key, parents] of parentsByKey)
|
|
300
|
+
triggerParents(internals, model, key, parents);
|
|
301
|
+
for (const key of inverses) {
|
|
302
|
+
const inverse = model.fields[key].inverse;
|
|
303
|
+
await inverse(host.recordset(model, ids));
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/** A many2one changed: the cached child lists of the old and new parents are stale. */
|
|
307
|
+
function invalidateInverseLists(host, model, key, oldParent, newParent) {
|
|
308
|
+
const target = targetOf(model.fields[key]);
|
|
309
|
+
if (target === undefined)
|
|
310
|
+
return;
|
|
311
|
+
const parentModel = host.internals.registry.get(target).model;
|
|
312
|
+
for (const [pKey, pField] of Object.entries(parentModel.fields)) {
|
|
313
|
+
if (pField.kind !== 'one2many' ||
|
|
314
|
+
pField.inverseField !== key ||
|
|
315
|
+
targetOf(pField) !== model.name)
|
|
316
|
+
continue;
|
|
317
|
+
for (const parent of [oldParent, newParent]) {
|
|
318
|
+
if (typeof parent === 'number')
|
|
319
|
+
host.values(parentModel.name, parent)?.delete(pKey);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
// ------------------------------------------------------------------------------------------------- unlink
|
|
324
|
+
/** Deletes `ids` now and removes them from the cache (and from any cached x2many lists). */
|
|
325
|
+
export async function unlinkRecords(host, model, ids) {
|
|
326
|
+
const { internals } = host;
|
|
327
|
+
if (ids.length === 0)
|
|
328
|
+
return;
|
|
329
|
+
assertAccess(internals, model, 'unlink');
|
|
330
|
+
await internals.flush(model.name);
|
|
331
|
+
await assertRecords(internals, model, ids, 'unlink');
|
|
332
|
+
// The parents of deleted children recompute (RFC 0008 §7.1): remember them before the rows go.
|
|
333
|
+
const inverseKeys = [...internals.registry.compute.inverseKeys(model.name)];
|
|
334
|
+
const tracked = internals.env.flags.tracking ? trackedKeys(model) : new Set();
|
|
335
|
+
const toFetch = new Set([...inverseKeys, ...tracked]);
|
|
336
|
+
if (toFetch.size > 0)
|
|
337
|
+
await host.fetch(model, ids, toFetch);
|
|
338
|
+
const parentsByKey = new Map();
|
|
339
|
+
for (const key of inverseKeys) {
|
|
340
|
+
parentsByKey.set(key, ids.map((id) => host.values(model.name, id)?.get(key)));
|
|
341
|
+
}
|
|
342
|
+
for (let i = 0; i < ids.length; i += CHUNK) {
|
|
343
|
+
const chunk = ids.slice(i, i + CHUNK);
|
|
344
|
+
const rows = await internals.query(compile(sql `DELETE FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array(chunk, 'bigint')}) RETURNING ${sql.id('id')}`));
|
|
345
|
+
const deleted = new Set(rows.map((r) => Number(r.id)));
|
|
346
|
+
const absent = chunk.filter((id) => !deleted.has(id));
|
|
347
|
+
if (absent.length > 0)
|
|
348
|
+
throw new MissingRecordError(model.name, absent);
|
|
349
|
+
}
|
|
350
|
+
for (const id of ids) {
|
|
351
|
+
const values = host.values(model.name, id);
|
|
352
|
+
if (values !== undefined)
|
|
353
|
+
trackSnapshot(internals, model, id, 'unlink', values);
|
|
354
|
+
internals.journal({
|
|
355
|
+
kind: 'deleted',
|
|
356
|
+
model: model.name,
|
|
357
|
+
id,
|
|
358
|
+
values: new Map(values ?? []),
|
|
359
|
+
dirty: internals.dirtyFields(model.name, id),
|
|
360
|
+
});
|
|
361
|
+
internals.forget(model.name, id);
|
|
362
|
+
}
|
|
363
|
+
// Cached x2many lists pointing at this model are stale for the deleted ids.
|
|
364
|
+
for (const { model: other } of internals.registry.models.values()) {
|
|
365
|
+
for (const [key, field] of Object.entries(other.fields)) {
|
|
366
|
+
if (!isX2Many(field) || targetOf(field) !== model.name)
|
|
367
|
+
continue;
|
|
368
|
+
for (const values of internals.cachedValues(other.name)) {
|
|
369
|
+
const list = values.get(key);
|
|
370
|
+
if (Array.isArray(list))
|
|
371
|
+
values.set(key, list.filter((c) => !ids.includes(Number(c))));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
for (const [key, parents] of parentsByKey)
|
|
376
|
+
triggerParents(internals, model, key, parents);
|
|
377
|
+
}
|
|
378
|
+
// --------------------------------------------------------------------------------------------- x2many ops
|
|
379
|
+
async function applyCommands(host, model, parentId, key, commands, mode) {
|
|
380
|
+
const { internals } = host;
|
|
381
|
+
const field = model.fields[key];
|
|
382
|
+
const target = internals.registry.get(field.target).model;
|
|
383
|
+
const parentValues = host.values(model.name, parentId, true);
|
|
384
|
+
const asIds = (v, what) => {
|
|
385
|
+
if (!Array.isArray(v) || !v.every((x) => typeof x === 'number'))
|
|
386
|
+
fail(model, [key], `x2many command '${what}' expects an array of ids.`, 'Pass record ids.');
|
|
387
|
+
return v;
|
|
388
|
+
};
|
|
389
|
+
const asRows = (v, what) => {
|
|
390
|
+
if (!Array.isArray(v))
|
|
391
|
+
fail(model, [key], `x2many command '${what}' expects an array.`, 'Pass an array of records.');
|
|
392
|
+
return v;
|
|
393
|
+
};
|
|
394
|
+
if (field.kind === 'one2many') {
|
|
395
|
+
const inverse = field.inverseField ?? '';
|
|
396
|
+
const inverseField = target.fields[inverse];
|
|
397
|
+
const linked = mode === 'create' ? [] : await host.children(model, parentId, key);
|
|
398
|
+
const current = new Set(linked);
|
|
399
|
+
for (const [cmd, arg] of Object.entries(commands)) {
|
|
400
|
+
if (arg === undefined)
|
|
401
|
+
continue;
|
|
402
|
+
switch (cmd) {
|
|
403
|
+
case 'create': {
|
|
404
|
+
const created = await createRecords(host, target, asRows(arg, cmd).map((r) => ({ ...r, [inverse]: parentId })));
|
|
405
|
+
for (const id of created)
|
|
406
|
+
current.add(id);
|
|
407
|
+
break;
|
|
408
|
+
}
|
|
409
|
+
case 'update':
|
|
410
|
+
for (const u of asRows(arg, cmd))
|
|
411
|
+
await writeRecords(host, target, [Number(u['id'])], (u['values'] ?? {}));
|
|
412
|
+
break;
|
|
413
|
+
case 'delete': {
|
|
414
|
+
const ids = asIds(arg, cmd);
|
|
415
|
+
await unlinkRecords(host, target, ids);
|
|
416
|
+
for (const id of ids)
|
|
417
|
+
current.delete(id);
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
case 'link': {
|
|
421
|
+
const ids = asIds(arg, cmd);
|
|
422
|
+
await writeRecords(host, target, ids, { [inverse]: parentId });
|
|
423
|
+
for (const id of ids)
|
|
424
|
+
current.add(id);
|
|
425
|
+
break;
|
|
426
|
+
}
|
|
427
|
+
case 'unlink':
|
|
428
|
+
case 'clear':
|
|
429
|
+
case 'set': {
|
|
430
|
+
const keep = cmd === 'set' ? new Set(asIds(arg, cmd)) : new Set();
|
|
431
|
+
const remove = cmd === 'unlink' ? asIds(arg, cmd) : [...current].filter((id) => !keep.has(id));
|
|
432
|
+
if (remove.length > 0) {
|
|
433
|
+
if (inverseField.required)
|
|
434
|
+
fail(model, [key], `cannot unlink from '${key}': the inverse '${inverse}' is required.`, 'Delete the records instead (delete: [...]), or make the inverse optional.');
|
|
435
|
+
await writeRecords(host, target, remove, { [inverse]: null });
|
|
436
|
+
for (const id of remove)
|
|
437
|
+
current.delete(id);
|
|
438
|
+
}
|
|
439
|
+
if (cmd === 'set') {
|
|
440
|
+
const add = [...keep].filter((id) => !current.has(id));
|
|
441
|
+
if (add.length > 0)
|
|
442
|
+
await writeRecords(host, target, add, { [inverse]: parentId });
|
|
443
|
+
for (const id of add)
|
|
444
|
+
current.add(id);
|
|
445
|
+
}
|
|
446
|
+
break;
|
|
447
|
+
}
|
|
448
|
+
default:
|
|
449
|
+
fail(model, [key], `'${cmd}' is not an x2many command.`, 'Use create, update, delete, link, unlink, set or clear.');
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
parentValues.set(key, [...current]);
|
|
453
|
+
internals.trigger(model.name, key, [parentId]);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
// many2many: junction table changes are immediate.
|
|
457
|
+
const j = junctionTable(model, field, target);
|
|
458
|
+
const rel = sql.id(j.table);
|
|
459
|
+
const src = sql.id(j.sourceColumn);
|
|
460
|
+
const tgt = sql.id(j.targetColumn);
|
|
461
|
+
const link = async (ids) => {
|
|
462
|
+
if (ids.length === 0)
|
|
463
|
+
return;
|
|
464
|
+
await internals.query(compile(sql `INSERT INTO ${rel} (${src}, ${tgt}) SELECT * FROM unnest(${sql.array(ids.map(() => parentId), 'bigint')}, ${sql.array(ids, 'bigint')}) ON CONFLICT DO NOTHING`));
|
|
465
|
+
};
|
|
466
|
+
const linked = mode === 'create' ? [] : await host.children(model, parentId, key);
|
|
467
|
+
const current = new Set(linked);
|
|
468
|
+
for (const [cmd, arg] of Object.entries(commands)) {
|
|
469
|
+
if (arg === undefined)
|
|
470
|
+
continue;
|
|
471
|
+
switch (cmd) {
|
|
472
|
+
case 'create': {
|
|
473
|
+
const created = await createRecords(host, target, asRows(arg, cmd));
|
|
474
|
+
await link(created);
|
|
475
|
+
for (const id of created)
|
|
476
|
+
current.add(id);
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
case 'update':
|
|
480
|
+
for (const u of asRows(arg, cmd))
|
|
481
|
+
await writeRecords(host, target, [Number(u['id'])], (u['values'] ?? {}));
|
|
482
|
+
break;
|
|
483
|
+
case 'link': {
|
|
484
|
+
const ids = asIds(arg, cmd);
|
|
485
|
+
await link(ids);
|
|
486
|
+
for (const id of ids)
|
|
487
|
+
current.add(id);
|
|
488
|
+
break;
|
|
489
|
+
}
|
|
490
|
+
case 'unlink': {
|
|
491
|
+
const ids = asIds(arg, cmd);
|
|
492
|
+
await internals.query(compile(sql `DELETE FROM ${rel} WHERE ${src} = ${parentId} AND ${tgt} = ANY(${sql.array(ids, 'bigint')})`));
|
|
493
|
+
for (const id of ids)
|
|
494
|
+
current.delete(id);
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
case 'delete': {
|
|
498
|
+
const ids = asIds(arg, cmd);
|
|
499
|
+
await unlinkRecords(host, target, ids);
|
|
500
|
+
for (const id of ids)
|
|
501
|
+
current.delete(id);
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
case 'set': {
|
|
505
|
+
const ids = asIds(arg, cmd);
|
|
506
|
+
await internals.query(compile(sql `DELETE FROM ${rel} WHERE ${src} = ${parentId} AND ${tgt} <> ALL(${sql.array(ids, 'bigint')})`));
|
|
507
|
+
await link(ids.filter((id) => !current.has(id)));
|
|
508
|
+
current.clear();
|
|
509
|
+
for (const id of ids)
|
|
510
|
+
current.add(id);
|
|
511
|
+
break;
|
|
512
|
+
}
|
|
513
|
+
case 'clear':
|
|
514
|
+
await internals.query(compile(sql `DELETE FROM ${rel} WHERE ${src} = ${parentId}`));
|
|
515
|
+
current.clear();
|
|
516
|
+
break;
|
|
517
|
+
default:
|
|
518
|
+
fail(model, [key], `'${cmd}' is not an x2many command.`, 'Use create, update, delete, link, unlink, set or clear.');
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
parentValues.set(key, [...current]);
|
|
522
|
+
internals.trigger(model.name, key, [parentId]);
|
|
523
|
+
}
|
|
524
|
+
// -------------------------------------------------------------------------------------------------- flush
|
|
525
|
+
/** Writes dirty records of `modelName` (or all models) in one `UPDATE … FROM unnest(...)` per (model, field set). */
|
|
526
|
+
export async function flushDirty(host, modelName) {
|
|
527
|
+
const { internals } = host;
|
|
528
|
+
const names = modelName === undefined ? internals.dirtyModels() : [modelName];
|
|
529
|
+
for (const name of names) {
|
|
530
|
+
const dirty = internals.takeDirty(name);
|
|
531
|
+
if (dirty === undefined || dirty.size === 0)
|
|
532
|
+
continue;
|
|
533
|
+
const model = internals.registry.get(name).model;
|
|
534
|
+
const groups = new Map();
|
|
535
|
+
for (const [id, fields] of dirty) {
|
|
536
|
+
if (id < 0)
|
|
537
|
+
continue; // a draft (RFC 0009 §7.4)
|
|
538
|
+
// A value invalidated by a trigger and not recomputed yet must not be written as null.
|
|
539
|
+
const sorted = [...fields].filter((k) => host.values(name, id)?.has(k)).sort();
|
|
540
|
+
if (sorted.length === 0)
|
|
541
|
+
continue;
|
|
542
|
+
const key = sorted.join(',');
|
|
543
|
+
let group = groups.get(key);
|
|
544
|
+
if (group === undefined) {
|
|
545
|
+
group = { fields: sorted, ids: [] };
|
|
546
|
+
groups.set(key, group);
|
|
547
|
+
}
|
|
548
|
+
group.ids.push(id);
|
|
549
|
+
}
|
|
550
|
+
for (const group of groups.values()) {
|
|
551
|
+
const fields = group.fields.map((k) => ({
|
|
552
|
+
key: k,
|
|
553
|
+
field: model.fields[k],
|
|
554
|
+
column: model.columns[k] ?? '',
|
|
555
|
+
}));
|
|
556
|
+
for (let i = 0; i < group.ids.length; i += CHUNK) {
|
|
557
|
+
const chunk = group.ids.slice(i, i + CHUNK);
|
|
558
|
+
const arrays = [
|
|
559
|
+
sql.array(chunk, 'bigint'),
|
|
560
|
+
...fields.map((f) => sql.array(chunk.map((id) => storedValue(internals, f.field, host.values(name, id)?.get(f.key))), arrayType(f.field))),
|
|
561
|
+
];
|
|
562
|
+
const names = [sql.id('id'), ...fields.map((f) => sql.id(f.column))];
|
|
563
|
+
const sets = [
|
|
564
|
+
...fields.map((f) => sql `${sql.id(f.column)} = ${valueRef(f.field, f.column)}`),
|
|
565
|
+
sql `${sql.id('updated_at')} = ${internals.now}`,
|
|
566
|
+
sql `${sql.id('updated_by_id')} = ${internals.uid}`,
|
|
567
|
+
];
|
|
568
|
+
const rows = await internals.query(compile(sql `UPDATE ${sql.id(model.table)} AS ${sql.id('x')} SET ${sql.join(sets)} FROM unnest(${sql.join(arrays)}) AS ${sql.id('v')}(${sql.join(names)}) WHERE ${sql.id('x', 'id')} = ${sql.id('v', 'id')} RETURNING ${sql.id('x', 'id')}`));
|
|
569
|
+
const updated = new Set(rows.map((r) => Number(r.id)));
|
|
570
|
+
const absent = chunk.filter((id) => !updated.has(id));
|
|
571
|
+
if (absent.length > 0)
|
|
572
|
+
throw new MissingRecordError(name, absent);
|
|
573
|
+
for (const id of chunk) {
|
|
574
|
+
const values = host.values(name, id);
|
|
575
|
+
values?.set('updatedAt', internals.now);
|
|
576
|
+
values?.set('updatedBy', internals.uid);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal DDL from models: tables, primary keys, NOT NULL, foreign keys, junction tables. A stopgap until
|
|
3
|
+
* `@shutro/migrate` exists (Phase 2); used by tests and examples to create a schema from a registry.
|
|
4
|
+
*
|
|
5
|
+
* DDL can't take bind parameters, so statements are built as text from pieces that are validated individually:
|
|
6
|
+
* identifiers through `sql.id` (quoted), type names through a strict pattern, keywords from a fixed table.
|
|
7
|
+
*/
|
|
8
|
+
import { type CompiledSql } from '../../sql/index.js';
|
|
9
|
+
import type { Field } from '../model/field.js';
|
|
10
|
+
import { type Registry } from './registry.js';
|
|
11
|
+
/**
|
|
12
|
+
* The database-level `DEFAULT` of a column (feedback #3), in the form PostgreSQL's catalog shows it once casts are
|
|
13
|
+
* stripped, so the migrator's diff is stable: `true` / `false`, unquoted non-negative numbers, quoted strings,
|
|
14
|
+
* `now()` for the timestamps. `null` when the default is a function, the field is translated, encrypted, numbered,
|
|
15
|
+
* computed, or a relation: those stay in the ORM.
|
|
16
|
+
*/
|
|
17
|
+
export declare function columnDefault(key: string, field: Field): string | null;
|
|
18
|
+
/**
|
|
19
|
+
* `CREATE TABLE` statements for every model in the registry, then `ALTER TABLE … ADD FOREIGN KEY` for every
|
|
20
|
+
* many2one, then junction tables for many2many fields. Execute them in order.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createTableStatements(registry: Registry): readonly CompiledSql[];
|