shutro 0.0.0-stage → 0.2.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 +99 -2
- package/dist/audit/index.d.ts +59 -0
- package/dist/audit/index.js +96 -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 +164 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +49 -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 +84 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +249 -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/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/data/data.d.ts +59 -0
- package/dist/core/data/data.js +119 -0
- package/dist/core/data/load.d.ts +37 -0
- package/dist/core/data/load.js +236 -0
- package/dist/core/env/env.d.ts +468 -0
- package/dist/core/env/env.js +916 -0
- package/dist/core/env/identity.d.ts +43 -0
- package/dist/core/env/identity.js +65 -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 +256 -0
- package/dist/core/errors.js +360 -0
- package/dist/core/events/events.d.ts +44 -0
- package/dist/core/events/events.js +58 -0
- package/dist/core/events/workers.d.ts +56 -0
- package/dist/core/events/workers.js +155 -0
- package/dist/core/index.d.ts +51 -0
- package/dist/core/index.js +42 -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 +479 -0
- package/dist/core/model/field.js +461 -0
- package/dist/core/model/generated.d.ts +77 -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 +387 -0
- package/dist/core/model/model.js +566 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/model/related.d.ts +17 -0
- package/dist/core/model/related.js +60 -0
- package/dist/core/model/typed.d.ts +107 -0
- package/dist/core/model/typed.js +46 -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 +68 -0
- package/dist/core/money/fx.js +124 -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/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +33 -0
- package/dist/core/recordset/audit.js +262 -0
- package/dist/core/recordset/compute.d.ts +36 -0
- package/dist/core/recordset/compute.js +414 -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 +31 -0
- package/dist/core/recordset/domain.js +300 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +240 -0
- package/dist/core/recordset/recordset.d.ts +110 -0
- package/dist/core/recordset/recordset.js +789 -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 +56 -0
- package/dist/core/recordset/security.js +269 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -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 +80 -0
- package/dist/core/recordset/types.d.ts +415 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +33 -0
- package/dist/core/recordset/values.js +177 -0
- package/dist/core/recordset/writes.d.ts +42 -0
- package/dist/core/recordset/writes.js +786 -0
- package/dist/core/registry/ddl.d.ts +31 -0
- package/dist/core/registry/ddl.js +174 -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 +89 -0
- package/dist/core/registry/module.js +98 -0
- package/dist/core/registry/registry.d.ts +130 -0
- package/dist/core/registry/registry.js +591 -0
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +88 -0
- package/dist/driver-pg/driver.js +177 -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 +233 -0
- package/dist/security/index.d.ts +147 -0
- package/dist/security/index.js +278 -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 +47 -0
- package/dist/sql/tag.js +123 -0
- package/package.json +82 -4
|
@@ -0,0 +1,786 @@
|
|
|
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 { Decimal as DecimalJs } from 'decimal.js';
|
|
8
|
+
import { SYSTEM_UID } from '../env/identity.js';
|
|
9
|
+
import { MissingRecordError, StaleRecordError } from '../errors.js';
|
|
10
|
+
import { targetOf } from '../registry/registry.js';
|
|
11
|
+
import { trackChange, trackedKeys, trackSnapshot } from './audit.js';
|
|
12
|
+
import { junctionTable } from './relations.js';
|
|
13
|
+
import { assertAccess, assertBackdate, assertFields, assertRecords, storedValue, } from './security.js';
|
|
14
|
+
import { fillSequences, UNNUMBERED } from './sequences.js';
|
|
15
|
+
import { arrayType, fail, normalize, valueRef } from './values.js';
|
|
16
|
+
/**
|
|
17
|
+
* Many2one fields without a database foreign key (`foreignKey: false`): the written ids must exist in the target
|
|
18
|
+
* (one query per field). @throws {MissingRecordError}
|
|
19
|
+
*/
|
|
20
|
+
async function assertReferencesExist(internals, model, rows) {
|
|
21
|
+
for (const [key, field] of Object.entries(model.fields)) {
|
|
22
|
+
const keyless = field.foreignKey === false || field.companyDependent;
|
|
23
|
+
if (field.kind !== 'many2one' || !keyless)
|
|
24
|
+
continue;
|
|
25
|
+
const company = String(internals.env.companyId);
|
|
26
|
+
const ids = [
|
|
27
|
+
...new Set(rows
|
|
28
|
+
.map((r) => field.companyDependent
|
|
29
|
+
? (r.get(key) ?? {})[company]
|
|
30
|
+
: r.get(key))
|
|
31
|
+
.filter((v) => typeof v === 'number' && v > 0)),
|
|
32
|
+
];
|
|
33
|
+
if (ids.length === 0)
|
|
34
|
+
continue;
|
|
35
|
+
const target = internals.registry.get(targetOf(field) ?? '').model;
|
|
36
|
+
const found = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(target.table)} WHERE ${sql.id('id')} = ANY(${sql.array(ids, 'bigint')})`));
|
|
37
|
+
const existing = new Set(found.map((r) => Number(r.id)));
|
|
38
|
+
const missing = ids.filter((id) => !existing.has(id));
|
|
39
|
+
if (missing.length > 0)
|
|
40
|
+
throw new MissingRecordError(target.name, missing);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Fills the materialized paths of new records of a hierarchical model, parents first (a batch may contain its own
|
|
45
|
+
* parents), and caches them. One statement per tree depth among the new records.
|
|
46
|
+
*/
|
|
47
|
+
async function fillPaths(internals, model, ids) {
|
|
48
|
+
const spec = model.hierarchy;
|
|
49
|
+
if (spec === undefined || ids.length === 0)
|
|
50
|
+
return;
|
|
51
|
+
const t = sql.id(model.table);
|
|
52
|
+
const path = sql.id(model.columns[spec.path] ?? '');
|
|
53
|
+
const parent = sql.id(model.columns[spec.parent] ?? '');
|
|
54
|
+
const h = sql.id('h');
|
|
55
|
+
let pending = ids.length;
|
|
56
|
+
while (pending > 0) {
|
|
57
|
+
const rows = await internals.query(compile(sql `UPDATE ${t} SET ${path} = coalesce((SELECT ${h}.${path} FROM ${t} AS ${h} WHERE ${h}.${sql.id('id')} = ${t}.${parent}), '') || ${t}.${sql.id('id')}::text || '/'
|
|
58
|
+
WHERE ${t}.${sql.id('id')} = ANY(${sql.array([...ids], 'bigint')}) AND ${t}.${path} IS NULL
|
|
59
|
+
AND (${t}.${parent} IS NULL OR EXISTS (SELECT 1 FROM ${t} AS ${h} WHERE ${h}.${sql.id('id')} = ${t}.${parent} AND ${h}.${path} IS NOT NULL))
|
|
60
|
+
RETURNING ${t}.${sql.id('id')} AS ${sql.id('id')}, ${path} AS ${sql.id('path')}`));
|
|
61
|
+
if (rows.length === 0)
|
|
62
|
+
break;
|
|
63
|
+
for (const r of rows)
|
|
64
|
+
internals.cache.records.get(model.name)?.get(Number(r.id))?.set(spec.path, r.path);
|
|
65
|
+
pending -= rows.length;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A record of a hierarchy moved: refuses cycles, then rewrites the paths of its subtree in one statement each.
|
|
70
|
+
* @throws {ValidationError} when the new parent is the record or one of its descendants.
|
|
71
|
+
*/
|
|
72
|
+
async function movePaths(host, model, ids, newParent) {
|
|
73
|
+
const spec = model.hierarchy;
|
|
74
|
+
if (spec === undefined)
|
|
75
|
+
return;
|
|
76
|
+
const { internals } = host;
|
|
77
|
+
const t = sql.id(model.table);
|
|
78
|
+
const path = sql.id(model.columns[spec.path] ?? '');
|
|
79
|
+
if (typeof newParent === 'number') {
|
|
80
|
+
const [p] = await internals.query(compile(sql `SELECT ${path} AS ${sql.id('path')} FROM ${t} WHERE ${sql.id('id')} = ${newParent}`));
|
|
81
|
+
const ancestors = new Set((p?.path ?? '')
|
|
82
|
+
.split('/')
|
|
83
|
+
.filter((x) => x !== '')
|
|
84
|
+
.map(Number));
|
|
85
|
+
const looping = ids.filter((id) => id === newParent || ancestors.has(id));
|
|
86
|
+
if (looping.length > 0)
|
|
87
|
+
fail(model, [spec.parent], `record(s) ${looping.join(', ')} cannot move under ${newParent}: it is the record itself or one of its descendants.`, 'A hierarchy cannot contain cycles; choose a parent outside the subtree.');
|
|
88
|
+
}
|
|
89
|
+
await internals.flush(model.name); // the new parent column reaches the database first
|
|
90
|
+
for (const id of ids) {
|
|
91
|
+
const rows = await internals.query(compile(sql `WITH ${sql.id('old')} AS (SELECT ${path} AS ${sql.id('p')} FROM ${t} WHERE ${sql.id('id')} = ${id}),
|
|
92
|
+
${sql.id('new')} AS (SELECT coalesce((SELECT ${sql.id('h')}.${path} FROM ${t} AS ${sql.id('h')} WHERE ${sql.id('h')}.${sql.id('id')} = (SELECT ${sql.id(model.columns[spec.parent] ?? '')} FROM ${t} WHERE ${sql.id('id')} = ${id})), '') || ${String(id)} || '/' AS ${sql.id('p')})
|
|
93
|
+
UPDATE ${t} SET ${path} = (SELECT ${sql.id('p')} FROM ${sql.id('new')}) || substr(${t}.${path}, length((SELECT ${sql.id('p')} FROM ${sql.id('old')})) + 1)
|
|
94
|
+
WHERE ${t}.${path} LIKE (SELECT ${sql.id('p')} FROM ${sql.id('old')}) || '%'
|
|
95
|
+
RETURNING ${t}.${sql.id('id')} AS ${sql.id('id')}, ${path} AS ${sql.id('path')}`));
|
|
96
|
+
for (const r of rows)
|
|
97
|
+
internals.cache.records.get(model.name)?.get(Number(r.id))?.set(spec.path, r.path);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Delegation: values of the parents' fields go to the parent records. A row without its delegate many2one gets a new
|
|
102
|
+
* parent (one create per delegate for the whole batch); a row with one updates that parent.
|
|
103
|
+
*/
|
|
104
|
+
async function createDelegates(host, model, rows) {
|
|
105
|
+
const out = rows.map((r) => ({ ...r }));
|
|
106
|
+
for (const key of model.delegates) {
|
|
107
|
+
const target = host.internals.registry.get(model.fields[key].target ?? '').model;
|
|
108
|
+
const own = Object.entries(model.fields)
|
|
109
|
+
.filter(([, f]) => f.delegated === key)
|
|
110
|
+
.map(([k]) => k);
|
|
111
|
+
const fresh = [];
|
|
112
|
+
for (const [index, row] of out.entries()) {
|
|
113
|
+
const values = {};
|
|
114
|
+
for (const k of own)
|
|
115
|
+
if (row[k] !== undefined) {
|
|
116
|
+
values[k] = row[k];
|
|
117
|
+
delete row[k];
|
|
118
|
+
}
|
|
119
|
+
if (row[key] === undefined || row[key] === null)
|
|
120
|
+
fresh.push({ index, values });
|
|
121
|
+
else if (Object.keys(values).length > 0)
|
|
122
|
+
await writeRecords(host, target, [row[key]], values);
|
|
123
|
+
}
|
|
124
|
+
if (fresh.length === 0)
|
|
125
|
+
continue;
|
|
126
|
+
const ids = await createRecords(host, target, fresh.map((f) => f.values));
|
|
127
|
+
fresh.forEach((f, i) => {
|
|
128
|
+
out[f.index][key] = ids[i];
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
function same(field, current, expected) {
|
|
134
|
+
if (expected === null || expected === undefined)
|
|
135
|
+
return current === null || current === undefined;
|
|
136
|
+
if (current === null || current === undefined)
|
|
137
|
+
return false;
|
|
138
|
+
if (expected instanceof Date || current instanceof Date)
|
|
139
|
+
return (new Date(current).getTime() === new Date(expected).getTime());
|
|
140
|
+
if (field.kind === 'many2one') {
|
|
141
|
+
const id = typeof expected === 'object' && 'id' in expected
|
|
142
|
+
? expected.id
|
|
143
|
+
: expected;
|
|
144
|
+
return Number(current) === Number(id);
|
|
145
|
+
}
|
|
146
|
+
if (DecimalJs.isDecimal(current) || field.kind === 'decimal' || field.kind === 'monetary') {
|
|
147
|
+
const amount = typeof expected === 'object' && 'amount' in expected
|
|
148
|
+
? expected.amount
|
|
149
|
+
: expected;
|
|
150
|
+
return new DecimalJs(String(current)).equals(new DecimalJs(String(amount)));
|
|
151
|
+
}
|
|
152
|
+
return JSON.stringify(current) === JSON.stringify(expected);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Compare-and-set (RFC 0018 §7.1): locks the records and checks their stored values against `expect` before a write.
|
|
156
|
+
* @throws {StaleRecordError} for records whose values differ (someone else saved first).
|
|
157
|
+
*/
|
|
158
|
+
export async function assertExpected(internals, model, ids, expect) {
|
|
159
|
+
const keys = Object.keys(expect);
|
|
160
|
+
if (keys.length === 0 || ids.length === 0)
|
|
161
|
+
return;
|
|
162
|
+
for (const key of keys)
|
|
163
|
+
if (model.columns[key] === undefined || model.fields[key]?.companyDependent === true)
|
|
164
|
+
fail(model, [key], `'${key}' cannot be expected: it is not a stored column.`, 'Expect stored fields, e.g. { updatedAt }.');
|
|
165
|
+
assertFields(internals, model, keys, 'read');
|
|
166
|
+
await internals.flush(model.name); // this transaction's own pending writes count
|
|
167
|
+
const rows = await internals.query(compile(sql `SELECT ${sql.id('id')}, ${sql.join(keys.map((k) => sql.id(model.columns[k] ?? '')))} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array([...ids], 'bigint')}) FOR UPDATE`));
|
|
168
|
+
const stale = new Set();
|
|
169
|
+
const records = [];
|
|
170
|
+
for (const row of rows) {
|
|
171
|
+
const changed = keys.filter((k) => !same(model.fields[k], row[model.columns[k] ?? ''], expect[k]));
|
|
172
|
+
if (changed.length > 0) {
|
|
173
|
+
records.push(Number(row['id']));
|
|
174
|
+
for (const k of changed)
|
|
175
|
+
stale.add(k);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (records.length > 0)
|
|
179
|
+
throw new StaleRecordError(model.name, records, [...stale]);
|
|
180
|
+
}
|
|
181
|
+
/** The `created_by` / `updated_by` value: `NULL` for the system ({@link SYSTEM_UID}, bootstrap scopes). */
|
|
182
|
+
function actor(internals) {
|
|
183
|
+
return internals.uid === SYSTEM_UID ? null : internals.uid;
|
|
184
|
+
}
|
|
185
|
+
function translationOf(internals) {
|
|
186
|
+
return {
|
|
187
|
+
lang: internals.env.lang,
|
|
188
|
+
source: internals.sourceLang,
|
|
189
|
+
company: internals.env.companyId,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
const CHUNK = 1000;
|
|
193
|
+
function isX2Many(field) {
|
|
194
|
+
return field.kind === 'one2many' || field.kind === 'many2many';
|
|
195
|
+
}
|
|
196
|
+
/** Resolves a field default (a value or `(env) => value`). */
|
|
197
|
+
function defaultOf(field, env) {
|
|
198
|
+
return typeof field.default === 'function'
|
|
199
|
+
? field.default(env)
|
|
200
|
+
: field.default;
|
|
201
|
+
}
|
|
202
|
+
/** A many2one of `model` changed: the one2many lists of the old / new parents changed too (RFC 0008 §7.1). */
|
|
203
|
+
function triggerParents(internals, model, key, parents) {
|
|
204
|
+
const ids = parents.filter((p) => typeof p === 'number');
|
|
205
|
+
if (ids.length === 0)
|
|
206
|
+
return;
|
|
207
|
+
const target = targetOf(model.fields[key]);
|
|
208
|
+
if (target === undefined)
|
|
209
|
+
return;
|
|
210
|
+
const parentModel = internals.registry.get(target).model;
|
|
211
|
+
for (const [pKey, pField] of Object.entries(parentModel.fields)) {
|
|
212
|
+
if (pField.kind === 'one2many' &&
|
|
213
|
+
pField.inverseField === key &&
|
|
214
|
+
targetOf(pField) === model.name)
|
|
215
|
+
internals.trigger(parentModel.name, pKey, ids);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** Splits a row into normalized stored values and x2many commands, validating keys. */
|
|
219
|
+
function splitRow(model, row, mode, host, id) {
|
|
220
|
+
const stored = new Map();
|
|
221
|
+
const commands = new Map();
|
|
222
|
+
const siblings = (key) => stored.has(key)
|
|
223
|
+
? stored.get(key)
|
|
224
|
+
: id === undefined
|
|
225
|
+
? undefined
|
|
226
|
+
: host.values(model.name, id)?.get(key);
|
|
227
|
+
for (const [key, value] of Object.entries(row)) {
|
|
228
|
+
if (value === undefined)
|
|
229
|
+
continue;
|
|
230
|
+
const field = model.fields[key];
|
|
231
|
+
if (field === undefined || key === 'id')
|
|
232
|
+
fail(model, [key], `'${key}' is not a writable field.`, `Fields: ${Object.keys(model.fields)
|
|
233
|
+
.filter((k) => k !== 'id')
|
|
234
|
+
.join(', ')}.`);
|
|
235
|
+
if (field.readonly && !(mode === 'create' && field.sequence !== undefined)) {
|
|
236
|
+
fail(model, [key], `field '${key}' is readonly.`, field.kind === 'state'
|
|
237
|
+
? 'State changes through transitions.'
|
|
238
|
+
: field.computed
|
|
239
|
+
? 'It is computed; write the fields it depends on instead.'
|
|
240
|
+
: 'It is maintained by the ORM.');
|
|
241
|
+
}
|
|
242
|
+
if (isX2Many(field)) {
|
|
243
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
244
|
+
fail(model, [key], `field '${key}' expects x2many commands.`, 'Use { create: [...], link: [...], set: [...], unlink: [...], delete: [...], update: [...], clear: true }.');
|
|
245
|
+
commands.set(key, value);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
// A non-stored computed field is writable through its inverse (related fields with writable: true).
|
|
249
|
+
if (model.columns[key] === undefined && !(field.computed && field.inverse !== undefined))
|
|
250
|
+
fail(model, [key], `field '${key}' is not stored.`, 'Non-stored computed fields cannot be written unless they have an inverse.');
|
|
251
|
+
stored.set(key, normalize(model, key, field, value, siblings, translationOf(host.internals)));
|
|
252
|
+
}
|
|
253
|
+
return { stored, commands };
|
|
254
|
+
}
|
|
255
|
+
// ------------------------------------------------------------------------------------------------- create
|
|
256
|
+
/** Inserts `rows` and returns their ids in input order. Children and links are created too. */
|
|
257
|
+
export async function createRecords(host, model, input, options = {}) {
|
|
258
|
+
const { internals } = host;
|
|
259
|
+
if (input.length === 0)
|
|
260
|
+
return [];
|
|
261
|
+
if (host.internals.asOf !== undefined)
|
|
262
|
+
fail(model, [], 'cannot be written in an asOf() scope.', 'The past is read-only: write outside env.asOf().');
|
|
263
|
+
const rows = model.delegates.length > 0 ? await createDelegates(host, model, input) : input;
|
|
264
|
+
assertAccess(internals, model, 'create');
|
|
265
|
+
if (options.copy === true)
|
|
266
|
+
assertAccess(internals, model, 'import');
|
|
267
|
+
for (const row of rows)
|
|
268
|
+
assertFields(internals, model, Object.keys(row), 'write');
|
|
269
|
+
// The default projection leaves out binary fields: add every stored key a row gives explicitly.
|
|
270
|
+
const given = new Set(rows.flatMap((r) => Object.keys(r).filter((k) => r[k] !== undefined)));
|
|
271
|
+
const columns = [...new Set([...host.defaults(model), ...given])].filter((k) => k !== 'id' && model.columns[k] !== undefined);
|
|
272
|
+
const prepared = rows.map((row) => {
|
|
273
|
+
const { stored, commands } = splitRow(model, row, 'create', host, undefined);
|
|
274
|
+
const missing = [];
|
|
275
|
+
for (const key of columns) {
|
|
276
|
+
if (stored.has(key))
|
|
277
|
+
continue;
|
|
278
|
+
const field = model.fields[key];
|
|
279
|
+
if (field === undefined)
|
|
280
|
+
continue;
|
|
281
|
+
if (field.companyDependent) {
|
|
282
|
+
stored.set(key, Object.freeze({})); // companies without a value read the default
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
let value;
|
|
286
|
+
if (key === 'createdAt' || key === 'updatedAt')
|
|
287
|
+
value = internals.now;
|
|
288
|
+
else if (key === 'createdBy' || key === 'updatedBy')
|
|
289
|
+
value = actor(internals);
|
|
290
|
+
else
|
|
291
|
+
value = defaultOf(field, internals.env) ?? null;
|
|
292
|
+
// Stored computes are filled after the insert (RFC 0008 §7.6); sequences before it (RFC 0012 §7.4).
|
|
293
|
+
if (value === null && field.sequence?.on === 'manual' && field.required)
|
|
294
|
+
value = UNNUMBERED;
|
|
295
|
+
if (value === null && field.required && !field.computed && field.sequence === undefined)
|
|
296
|
+
missing.push(key);
|
|
297
|
+
stored.set(key, value === null
|
|
298
|
+
? null
|
|
299
|
+
: normalize(model, key, field, value, (k) => stored.get(k), translationOf(internals)));
|
|
300
|
+
}
|
|
301
|
+
if (missing.length > 0)
|
|
302
|
+
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.');
|
|
303
|
+
return { stored, commands };
|
|
304
|
+
});
|
|
305
|
+
await assertReferencesExist(internals, model, prepared.map((p) => p.stored));
|
|
306
|
+
if (model.backdate !== undefined)
|
|
307
|
+
assertBackdate(internals, model, prepared.map((p) => p.stored.get(model.backdate?.field ?? '')));
|
|
308
|
+
await fillSequences(internals, model, prepared);
|
|
309
|
+
const ids = [];
|
|
310
|
+
if (options.copy === true)
|
|
311
|
+
ids.push(...(await copyRows(internals, model, columns, prepared)));
|
|
312
|
+
for (let i = 0; i < (options.copy === true ? 0 : prepared.length); i += CHUNK) {
|
|
313
|
+
const chunk = prepared.slice(i, i + CHUNK);
|
|
314
|
+
const arrays = columns.map((key) => sql.array(chunk.map((p) => storedValue(internals, model.fields[key], p.stored.get(key))), arrayType(model.fields[key])));
|
|
315
|
+
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')}`));
|
|
316
|
+
if (rowsOut.length !== chunk.length)
|
|
317
|
+
throw new MissingRecordError(model.name, []);
|
|
318
|
+
for (const r of rowsOut)
|
|
319
|
+
ids.push(Number(r.id));
|
|
320
|
+
}
|
|
321
|
+
await fillPaths(internals, model, ids);
|
|
322
|
+
const parentsByKey = new Map();
|
|
323
|
+
prepared.forEach((p, i) => {
|
|
324
|
+
const id = ids[i];
|
|
325
|
+
const values = host.values(model.name, id, true);
|
|
326
|
+
for (const [key, value] of p.stored) {
|
|
327
|
+
// Stored computes are not cached yet: reading one before the flush point says so (RFC 0008 §7.2).
|
|
328
|
+
if (!model.fields[key].computed)
|
|
329
|
+
values.set(key, value);
|
|
330
|
+
if (model.fields[key].kind === 'many2one' && value !== null)
|
|
331
|
+
parentsByKey.set(key, [...(parentsByKey.get(key) ?? []), value]);
|
|
332
|
+
}
|
|
333
|
+
internals.journal({ kind: 'created', model: model.name, id });
|
|
334
|
+
});
|
|
335
|
+
await host.ensureValueObjects(model, ids, new Set(columns));
|
|
336
|
+
await assertRecords(internals, model, ids, 'create'); // create rules apply to the inserted rows (RFC 0014 §7.3)
|
|
337
|
+
prepared.forEach((p, i) => {
|
|
338
|
+
trackSnapshot(internals, model, ids[i], 'create', p.stored);
|
|
339
|
+
});
|
|
340
|
+
// Triggers: every stored value of a new record "changed"; its own stored computes are computed at the next flush point.
|
|
341
|
+
for (const key of columns) {
|
|
342
|
+
const field = model.fields[key];
|
|
343
|
+
if (field.computed)
|
|
344
|
+
continue;
|
|
345
|
+
internals.trigger(model.name, key, ids);
|
|
346
|
+
}
|
|
347
|
+
for (const [key, parents] of parentsByKey)
|
|
348
|
+
triggerParents(internals, model, key, parents);
|
|
349
|
+
for (const f of internals.registry.compute.stored(model.name))
|
|
350
|
+
internals.markToCompute(model.name, f.key, ids);
|
|
351
|
+
// one2many `create` commands of every new parent become one child insert per field (no INSERT per parent).
|
|
352
|
+
const batched = new Map();
|
|
353
|
+
for (const [i, p] of prepared.entries()) {
|
|
354
|
+
for (const [key, commands] of p.commands) {
|
|
355
|
+
const field = model.fields[key];
|
|
356
|
+
const onlyCreate = Object.entries(commands).every(([c, v]) => c === 'create' || v === undefined);
|
|
357
|
+
if (field.kind === 'one2many' && onlyCreate && Array.isArray(commands['create'])) {
|
|
358
|
+
const list = batched.get(key) ?? [];
|
|
359
|
+
list.push({ parent: ids[i], rows: commands['create'] });
|
|
360
|
+
batched.set(key, list);
|
|
361
|
+
}
|
|
362
|
+
else
|
|
363
|
+
await applyCommands(host, model, ids[i], key, commands, 'create');
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
for (const [key, parents] of batched) {
|
|
367
|
+
const field = model.fields[key];
|
|
368
|
+
const target = internals.registry.get(field.target).model;
|
|
369
|
+
const inverse = field.inverseField ?? '';
|
|
370
|
+
const childRows = parents.flatMap(({ parent, rows: rs }) => rs.map((r) => ({ ...r, [inverse]: parent })));
|
|
371
|
+
// COPY loads COPY their children too (feedback #20): one COPY per child model, ids in order.
|
|
372
|
+
const childIds = await createRecords(host, target, childRows, options);
|
|
373
|
+
let at = 0;
|
|
374
|
+
for (const { parent, rows: rs } of parents) {
|
|
375
|
+
host.values(model.name, parent, true).set(key, childIds.slice(at, at + rs.length));
|
|
376
|
+
at += rs.length;
|
|
377
|
+
}
|
|
378
|
+
internals.trigger(model.name, key, parents.map((p) => p.parent));
|
|
379
|
+
}
|
|
380
|
+
return ids;
|
|
381
|
+
}
|
|
382
|
+
// ---------------------------------------------------------------------------------------------------- copy
|
|
383
|
+
/** One value in COPY text format: \N for null, backslash escapes, bytea as hex (RFC 0015 §7.1). */
|
|
384
|
+
export function copyField(value) {
|
|
385
|
+
if (value === null || value === undefined)
|
|
386
|
+
return '\\N';
|
|
387
|
+
let text;
|
|
388
|
+
if (typeof value === 'boolean')
|
|
389
|
+
text = value ? 't' : 'f';
|
|
390
|
+
else if (value instanceof Uint8Array)
|
|
391
|
+
text = `\\x${Buffer.from(value).toString('hex')}`;
|
|
392
|
+
else
|
|
393
|
+
text = String(value);
|
|
394
|
+
return text
|
|
395
|
+
.replace(/\\/g, '\\\\')
|
|
396
|
+
.replace(/\n/g, '\\n')
|
|
397
|
+
.replace(/\r/g, '\\r')
|
|
398
|
+
.replace(/\t/g, '\\t');
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Bulk insert through `COPY ... FROM STDIN`: ids are reserved from the identity sequence in one query (COPY writes
|
|
402
|
+
* identity values as given), then every row streams in one statement. Returns the ids in input order.
|
|
403
|
+
*/
|
|
404
|
+
async function copyRows(internals, model, columns, prepared) {
|
|
405
|
+
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})`));
|
|
406
|
+
const ids = reserved.map((r) => Number(r.id));
|
|
407
|
+
const fields = columns.map((k) => model.fields[k]);
|
|
408
|
+
const lines = prepared.map((p, i) => [
|
|
409
|
+
String(ids[i]),
|
|
410
|
+
...columns.map((k, c) => copyField(storedValue(internals, fields[c], p.stored.get(k)))),
|
|
411
|
+
].join('\t'));
|
|
412
|
+
const names = [sql.id('id'), ...columns.map((k) => sql.id(model.columns[k] ?? ''))];
|
|
413
|
+
const count = await internals.copyIn(compile(sql `COPY ${sql.id(model.table)} (${sql.join(names)}) FROM STDIN`), lines);
|
|
414
|
+
if (count !== prepared.length)
|
|
415
|
+
throw new MissingRecordError(model.name, []);
|
|
416
|
+
return ids;
|
|
417
|
+
}
|
|
418
|
+
// -------------------------------------------------------------------------------------------------- write
|
|
419
|
+
/** Applies `values` to `ids` in the cache and marks them dirty; x2many commands run immediately. */
|
|
420
|
+
export async function writeRecords(host, model, ids, values) {
|
|
421
|
+
const { internals } = host;
|
|
422
|
+
if (ids.length === 0)
|
|
423
|
+
return;
|
|
424
|
+
if (internals.asOf !== undefined)
|
|
425
|
+
fail(model, [], 'cannot be written in an asOf() scope.', 'The past is read-only: write outside env.asOf().');
|
|
426
|
+
assertAccess(internals, model, 'write');
|
|
427
|
+
assertFields(internals, model, Object.keys(values), 'write');
|
|
428
|
+
if (model.backdate !== undefined && model.backdate.field in values)
|
|
429
|
+
assertBackdate(internals, model, [values[model.backdate.field]]);
|
|
430
|
+
await assertReferencesExist(internals, model, [new Map(Object.entries(values))]);
|
|
431
|
+
await assertRecords(internals, model, ids, 'write');
|
|
432
|
+
// Money / Quantity checks need the sibling currency / uom values; a moved record needs its old parent.
|
|
433
|
+
const needed = new Set();
|
|
434
|
+
for (const key of Object.keys(values)) {
|
|
435
|
+
const field = model.fields[key];
|
|
436
|
+
if (field?.currencyField !== undefined)
|
|
437
|
+
needed.add(field.currencyField);
|
|
438
|
+
if (field?.uomField !== undefined)
|
|
439
|
+
needed.add(field.uomField);
|
|
440
|
+
if (field?.kind === 'many2one' && internals.registry.compute.inverseKeys(model.name).has(key))
|
|
441
|
+
needed.add(key);
|
|
442
|
+
if (field?.companyDependent === true)
|
|
443
|
+
needed.add(key); // merged into the other companies' values
|
|
444
|
+
}
|
|
445
|
+
// The audit trail needs the exact old values of tracked fields (RFC 0013 §7.2).
|
|
446
|
+
if (internals.env.flags.tracking) {
|
|
447
|
+
const tracked = trackedKeys(model);
|
|
448
|
+
for (const key of Object.keys(values)) {
|
|
449
|
+
if (!tracked.has(key))
|
|
450
|
+
continue;
|
|
451
|
+
needed.add(key);
|
|
452
|
+
const field = model.fields[key];
|
|
453
|
+
if (field?.currencyField !== undefined)
|
|
454
|
+
needed.add(field.currencyField);
|
|
455
|
+
if (field?.uomField !== undefined)
|
|
456
|
+
needed.add(field.uomField);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (needed.size > 0)
|
|
460
|
+
await host.fetch(model, ids, needed);
|
|
461
|
+
const changedByKey = new Map();
|
|
462
|
+
const parentsByKey = new Map();
|
|
463
|
+
const inverses = new Set();
|
|
464
|
+
for (const id of ids) {
|
|
465
|
+
const { stored, commands } = splitRow(model, values, 'write', host, id);
|
|
466
|
+
const cached = host.values(model.name, id, true);
|
|
467
|
+
for (const [key, value] of stored) {
|
|
468
|
+
const field = model.fields[key];
|
|
469
|
+
if (model.columns[key] === undefined) {
|
|
470
|
+
// Non-stored with an inverse: the value lives in the cache for the inverse to read; nothing to flush.
|
|
471
|
+
cached.set(key, value);
|
|
472
|
+
inverses.add(key);
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
if (field.kind === 'many2one') {
|
|
476
|
+
invalidateInverseLists(host, model, key, cached.get(key), value);
|
|
477
|
+
parentsByKey.set(key, [...(parentsByKey.get(key) ?? []), cached.get(key), value]);
|
|
478
|
+
}
|
|
479
|
+
internals.journal({
|
|
480
|
+
kind: 'value',
|
|
481
|
+
model: model.name,
|
|
482
|
+
id,
|
|
483
|
+
key,
|
|
484
|
+
had: cached.has(key),
|
|
485
|
+
prev: cached.get(key),
|
|
486
|
+
wasDirty: internals.isDirty(model.name, id, key),
|
|
487
|
+
});
|
|
488
|
+
trackChange(internals, model, id, key, cached.get(key), value, (k) => k === key ? value : (stored.get(k) ?? cached.get(k)));
|
|
489
|
+
cached.set(key, value);
|
|
490
|
+
internals.markDirty(model.name, id, key);
|
|
491
|
+
changedByKey.set(key, [...(changedByKey.get(key) ?? []), id]);
|
|
492
|
+
if (field.computed && field.inverse !== undefined)
|
|
493
|
+
inverses.add(key);
|
|
494
|
+
}
|
|
495
|
+
for (const [key, cmds] of commands)
|
|
496
|
+
await applyCommands(host, model, id, key, cmds, 'write');
|
|
497
|
+
}
|
|
498
|
+
for (const [key, changed] of changedByKey)
|
|
499
|
+
internals.trigger(model.name, key, changed);
|
|
500
|
+
for (const [key, parents] of parentsByKey)
|
|
501
|
+
triggerParents(internals, model, key, parents);
|
|
502
|
+
if (model.hierarchy !== undefined && model.hierarchy.parent in values)
|
|
503
|
+
await movePaths(host, model, ids, values[model.hierarchy.parent]);
|
|
504
|
+
for (const key of inverses) {
|
|
505
|
+
const inverse = model.fields[key].inverse;
|
|
506
|
+
await inverse(host.recordset(model, ids), key);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/** A many2one changed: the cached child lists of the old and new parents are stale. */
|
|
510
|
+
function invalidateInverseLists(host, model, key, oldParent, newParent) {
|
|
511
|
+
const target = targetOf(model.fields[key]);
|
|
512
|
+
if (target === undefined)
|
|
513
|
+
return;
|
|
514
|
+
const parentModel = host.internals.registry.get(target).model;
|
|
515
|
+
for (const [pKey, pField] of Object.entries(parentModel.fields)) {
|
|
516
|
+
if (pField.kind !== 'one2many' ||
|
|
517
|
+
pField.inverseField !== key ||
|
|
518
|
+
targetOf(pField) !== model.name)
|
|
519
|
+
continue;
|
|
520
|
+
for (const parent of [oldParent, newParent]) {
|
|
521
|
+
if (typeof parent === 'number')
|
|
522
|
+
host.values(parentModel.name, parent)?.delete(pKey);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
// ------------------------------------------------------------------------------------------------- unlink
|
|
527
|
+
/** Deletes `ids` now and removes them from the cache (and from any cached x2many lists). */
|
|
528
|
+
export async function unlinkRecords(host, model, ids) {
|
|
529
|
+
const { internals } = host;
|
|
530
|
+
if (ids.length === 0)
|
|
531
|
+
return;
|
|
532
|
+
if (internals.asOf !== undefined)
|
|
533
|
+
fail(model, [], 'cannot be deleted in an asOf() scope.', 'The past is read-only: delete outside env.asOf().');
|
|
534
|
+
assertAccess(internals, model, 'unlink');
|
|
535
|
+
await internals.flush(model.name);
|
|
536
|
+
await assertRecords(internals, model, ids, 'unlink');
|
|
537
|
+
// The parents of deleted children recompute (RFC 0008 §7.1): remember them before the rows go.
|
|
538
|
+
const inverseKeys = [...internals.registry.compute.inverseKeys(model.name)];
|
|
539
|
+
const tracked = internals.env.flags.tracking ? trackedKeys(model) : new Set();
|
|
540
|
+
const toFetch = new Set([...inverseKeys, ...tracked]);
|
|
541
|
+
if (toFetch.size > 0)
|
|
542
|
+
await host.fetch(model, ids, toFetch);
|
|
543
|
+
const parentsByKey = new Map();
|
|
544
|
+
for (const key of inverseKeys) {
|
|
545
|
+
parentsByKey.set(key, ids.map((id) => host.values(model.name, id)?.get(key)));
|
|
546
|
+
}
|
|
547
|
+
for (let i = 0; i < ids.length; i += CHUNK) {
|
|
548
|
+
const chunk = ids.slice(i, i + CHUNK);
|
|
549
|
+
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')}`));
|
|
550
|
+
const deleted = new Set(rows.map((r) => Number(r.id)));
|
|
551
|
+
const absent = chunk.filter((id) => !deleted.has(id));
|
|
552
|
+
if (absent.length > 0)
|
|
553
|
+
throw new MissingRecordError(model.name, absent);
|
|
554
|
+
}
|
|
555
|
+
for (const id of ids) {
|
|
556
|
+
const values = host.values(model.name, id);
|
|
557
|
+
if (values !== undefined)
|
|
558
|
+
trackSnapshot(internals, model, id, 'unlink', values);
|
|
559
|
+
internals.journal({
|
|
560
|
+
kind: 'deleted',
|
|
561
|
+
model: model.name,
|
|
562
|
+
id,
|
|
563
|
+
values: new Map(values ?? []),
|
|
564
|
+
dirty: internals.dirtyFields(model.name, id),
|
|
565
|
+
});
|
|
566
|
+
internals.forget(model.name, id);
|
|
567
|
+
}
|
|
568
|
+
// Cached x2many lists pointing at this model are stale for the deleted ids.
|
|
569
|
+
for (const { model: other } of internals.registry.models.values()) {
|
|
570
|
+
for (const [key, field] of Object.entries(other.fields)) {
|
|
571
|
+
if (!isX2Many(field) || targetOf(field) !== model.name)
|
|
572
|
+
continue;
|
|
573
|
+
for (const values of internals.cachedValues(other.name)) {
|
|
574
|
+
const list = values.get(key);
|
|
575
|
+
if (Array.isArray(list))
|
|
576
|
+
values.set(key, list.filter((c) => !ids.includes(Number(c))));
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
for (const [key, parents] of parentsByKey)
|
|
581
|
+
triggerParents(internals, model, key, parents);
|
|
582
|
+
}
|
|
583
|
+
// --------------------------------------------------------------------------------------------- x2many ops
|
|
584
|
+
async function applyCommands(host, model, parentId, key, commands, mode) {
|
|
585
|
+
const { internals } = host;
|
|
586
|
+
const field = model.fields[key];
|
|
587
|
+
const target = internals.registry.get(field.target).model;
|
|
588
|
+
const parentValues = host.values(model.name, parentId, true);
|
|
589
|
+
const asIds = (v, what) => {
|
|
590
|
+
if (!Array.isArray(v) || !v.every((x) => typeof x === 'number'))
|
|
591
|
+
fail(model, [key], `x2many command '${what}' expects an array of ids.`, 'Pass record ids.');
|
|
592
|
+
return v;
|
|
593
|
+
};
|
|
594
|
+
const asRows = (v, what) => {
|
|
595
|
+
if (!Array.isArray(v))
|
|
596
|
+
fail(model, [key], `x2many command '${what}' expects an array.`, 'Pass an array of records.');
|
|
597
|
+
return v;
|
|
598
|
+
};
|
|
599
|
+
if (field.kind === 'one2many') {
|
|
600
|
+
const inverse = field.inverseField ?? '';
|
|
601
|
+
const inverseField = target.fields[inverse];
|
|
602
|
+
const linked = mode === 'create' ? [] : await host.children(model, parentId, key);
|
|
603
|
+
const current = new Set(linked);
|
|
604
|
+
for (const [cmd, arg] of Object.entries(commands)) {
|
|
605
|
+
if (arg === undefined)
|
|
606
|
+
continue;
|
|
607
|
+
switch (cmd) {
|
|
608
|
+
case 'create': {
|
|
609
|
+
const created = await createRecords(host, target, asRows(arg, cmd).map((r) => ({ ...r, [inverse]: parentId })));
|
|
610
|
+
for (const id of created)
|
|
611
|
+
current.add(id);
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
case 'update':
|
|
615
|
+
for (const u of asRows(arg, cmd))
|
|
616
|
+
await writeRecords(host, target, [Number(u['id'])], (u['values'] ?? {}));
|
|
617
|
+
break;
|
|
618
|
+
case 'delete': {
|
|
619
|
+
const ids = asIds(arg, cmd);
|
|
620
|
+
await unlinkRecords(host, target, ids);
|
|
621
|
+
for (const id of ids)
|
|
622
|
+
current.delete(id);
|
|
623
|
+
break;
|
|
624
|
+
}
|
|
625
|
+
case 'link': {
|
|
626
|
+
const ids = asIds(arg, cmd);
|
|
627
|
+
await writeRecords(host, target, ids, { [inverse]: parentId });
|
|
628
|
+
for (const id of ids)
|
|
629
|
+
current.add(id);
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
case 'unlink':
|
|
633
|
+
case 'clear':
|
|
634
|
+
case 'set': {
|
|
635
|
+
const keep = cmd === 'set' ? new Set(asIds(arg, cmd)) : new Set();
|
|
636
|
+
const remove = cmd === 'unlink' ? asIds(arg, cmd) : [...current].filter((id) => !keep.has(id));
|
|
637
|
+
if (remove.length > 0) {
|
|
638
|
+
if (inverseField.required)
|
|
639
|
+
fail(model, [key], `cannot unlink from '${key}': the inverse '${inverse}' is required.`, 'Delete the records instead (delete: [...]), or make the inverse optional.');
|
|
640
|
+
await writeRecords(host, target, remove, { [inverse]: null });
|
|
641
|
+
for (const id of remove)
|
|
642
|
+
current.delete(id);
|
|
643
|
+
}
|
|
644
|
+
if (cmd === 'set') {
|
|
645
|
+
const add = [...keep].filter((id) => !current.has(id));
|
|
646
|
+
if (add.length > 0)
|
|
647
|
+
await writeRecords(host, target, add, { [inverse]: parentId });
|
|
648
|
+
for (const id of add)
|
|
649
|
+
current.add(id);
|
|
650
|
+
}
|
|
651
|
+
break;
|
|
652
|
+
}
|
|
653
|
+
default:
|
|
654
|
+
fail(model, [key], `'${cmd}' is not an x2many command.`, 'Use create, update, delete, link, unlink, set or clear.');
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
parentValues.set(key, [...current]);
|
|
658
|
+
internals.trigger(model.name, key, [parentId]);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
// many2many: junction table changes are immediate.
|
|
662
|
+
const j = junctionTable(model, field, target);
|
|
663
|
+
const rel = sql.id(j.table);
|
|
664
|
+
const src = sql.id(j.sourceColumn);
|
|
665
|
+
const tgt = sql.id(j.targetColumn);
|
|
666
|
+
const link = async (ids) => {
|
|
667
|
+
if (ids.length === 0)
|
|
668
|
+
return;
|
|
669
|
+
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`));
|
|
670
|
+
};
|
|
671
|
+
const linked = mode === 'create' ? [] : await host.children(model, parentId, key);
|
|
672
|
+
const current = new Set(linked);
|
|
673
|
+
for (const [cmd, arg] of Object.entries(commands)) {
|
|
674
|
+
if (arg === undefined)
|
|
675
|
+
continue;
|
|
676
|
+
switch (cmd) {
|
|
677
|
+
case 'create': {
|
|
678
|
+
const created = await createRecords(host, target, asRows(arg, cmd));
|
|
679
|
+
await link(created);
|
|
680
|
+
for (const id of created)
|
|
681
|
+
current.add(id);
|
|
682
|
+
break;
|
|
683
|
+
}
|
|
684
|
+
case 'update':
|
|
685
|
+
for (const u of asRows(arg, cmd))
|
|
686
|
+
await writeRecords(host, target, [Number(u['id'])], (u['values'] ?? {}));
|
|
687
|
+
break;
|
|
688
|
+
case 'link': {
|
|
689
|
+
const ids = asIds(arg, cmd);
|
|
690
|
+
await link(ids);
|
|
691
|
+
for (const id of ids)
|
|
692
|
+
current.add(id);
|
|
693
|
+
break;
|
|
694
|
+
}
|
|
695
|
+
case 'unlink': {
|
|
696
|
+
const ids = asIds(arg, cmd);
|
|
697
|
+
await internals.query(compile(sql `DELETE FROM ${rel} WHERE ${src} = ${parentId} AND ${tgt} = ANY(${sql.array(ids, 'bigint')})`));
|
|
698
|
+
for (const id of ids)
|
|
699
|
+
current.delete(id);
|
|
700
|
+
break;
|
|
701
|
+
}
|
|
702
|
+
case 'delete': {
|
|
703
|
+
const ids = asIds(arg, cmd);
|
|
704
|
+
await unlinkRecords(host, target, ids);
|
|
705
|
+
for (const id of ids)
|
|
706
|
+
current.delete(id);
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
709
|
+
case 'set': {
|
|
710
|
+
const ids = asIds(arg, cmd);
|
|
711
|
+
await internals.query(compile(sql `DELETE FROM ${rel} WHERE ${src} = ${parentId} AND ${tgt} <> ALL(${sql.array(ids, 'bigint')})`));
|
|
712
|
+
await link(ids.filter((id) => !current.has(id)));
|
|
713
|
+
current.clear();
|
|
714
|
+
for (const id of ids)
|
|
715
|
+
current.add(id);
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
case 'clear':
|
|
719
|
+
await internals.query(compile(sql `DELETE FROM ${rel} WHERE ${src} = ${parentId}`));
|
|
720
|
+
current.clear();
|
|
721
|
+
break;
|
|
722
|
+
default:
|
|
723
|
+
fail(model, [key], `'${cmd}' is not an x2many command.`, 'Use create, update, delete, link, unlink, set or clear.');
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
parentValues.set(key, [...current]);
|
|
727
|
+
internals.trigger(model.name, key, [parentId]);
|
|
728
|
+
}
|
|
729
|
+
// -------------------------------------------------------------------------------------------------- flush
|
|
730
|
+
/** Writes dirty records of `modelName` (or all models) in one `UPDATE … FROM unnest(...)` per (model, field set). */
|
|
731
|
+
export async function flushDirty(host, modelName) {
|
|
732
|
+
const { internals } = host;
|
|
733
|
+
const names = modelName === undefined ? internals.dirtyModels() : [modelName];
|
|
734
|
+
for (const name of names) {
|
|
735
|
+
const dirty = internals.takeDirty(name);
|
|
736
|
+
if (dirty === undefined || dirty.size === 0)
|
|
737
|
+
continue;
|
|
738
|
+
const model = internals.registry.get(name).model;
|
|
739
|
+
const groups = new Map();
|
|
740
|
+
for (const [id, fields] of dirty) {
|
|
741
|
+
if (id < 0)
|
|
742
|
+
continue; // a draft (RFC 0009 §7.4)
|
|
743
|
+
// A value invalidated by a trigger and not recomputed yet must not be written as null.
|
|
744
|
+
const sorted = [...fields].filter((k) => host.values(name, id)?.has(k)).sort();
|
|
745
|
+
if (sorted.length === 0)
|
|
746
|
+
continue;
|
|
747
|
+
const key = sorted.join(',');
|
|
748
|
+
let group = groups.get(key);
|
|
749
|
+
if (group === undefined) {
|
|
750
|
+
group = { fields: sorted, ids: [] };
|
|
751
|
+
groups.set(key, group);
|
|
752
|
+
}
|
|
753
|
+
group.ids.push(id);
|
|
754
|
+
}
|
|
755
|
+
for (const group of groups.values()) {
|
|
756
|
+
const fields = group.fields.map((k) => ({
|
|
757
|
+
key: k,
|
|
758
|
+
field: model.fields[k],
|
|
759
|
+
column: model.columns[k] ?? '',
|
|
760
|
+
}));
|
|
761
|
+
for (let i = 0; i < group.ids.length; i += CHUNK) {
|
|
762
|
+
const chunk = group.ids.slice(i, i + CHUNK);
|
|
763
|
+
const arrays = [
|
|
764
|
+
sql.array(chunk, 'bigint'),
|
|
765
|
+
...fields.map((f) => sql.array(chunk.map((id) => storedValue(internals, f.field, host.values(name, id)?.get(f.key))), arrayType(f.field))),
|
|
766
|
+
];
|
|
767
|
+
const names = [sql.id('id'), ...fields.map((f) => sql.id(f.column))];
|
|
768
|
+
const sets = [
|
|
769
|
+
...fields.map((f) => sql `${sql.id(f.column)} = ${valueRef(f.field, f.column)}`),
|
|
770
|
+
sql `${sql.id('updated_at')} = ${internals.now}`,
|
|
771
|
+
sql `${sql.id('updated_by_id')} = ${actor(internals)}`,
|
|
772
|
+
];
|
|
773
|
+
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')}`));
|
|
774
|
+
const updated = new Set(rows.map((r) => Number(r.id)));
|
|
775
|
+
const absent = chunk.filter((id) => !updated.has(id));
|
|
776
|
+
if (absent.length > 0)
|
|
777
|
+
throw new MissingRecordError(name, absent);
|
|
778
|
+
for (const id of chunk) {
|
|
779
|
+
const values = host.values(name, id);
|
|
780
|
+
values?.set('updatedAt', internals.now);
|
|
781
|
+
values?.set('updatedBy', actor(internals));
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
}
|