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,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiles a search domain (RFC 0005 §7.1) plus automatic scoping (`active`, companies) into WHERE fragments:
|
|
3
|
+
* field conditions ANDed, `or` / `and` / `not`, dotted relation paths (`'partner.name'`, `'order.user'`) and
|
|
4
|
+
* `{ lines: { any | none: domain } }` on x2many fields. Relations compile to sub-selects, never joins, so rows are
|
|
5
|
+
* never duplicated (RFC 0005 R8).
|
|
6
|
+
*/
|
|
7
|
+
import { sql } from '../../sql/index.js';
|
|
8
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
9
|
+
import { InvalidDomainError } from '../errors.js';
|
|
10
|
+
import { junctionTable } from './relations.js';
|
|
11
|
+
const OPERATORS = new Set([
|
|
12
|
+
'eq',
|
|
13
|
+
'ne',
|
|
14
|
+
'lt',
|
|
15
|
+
'lte',
|
|
16
|
+
'gt',
|
|
17
|
+
'gte',
|
|
18
|
+
'in',
|
|
19
|
+
'notIn',
|
|
20
|
+
'isNull',
|
|
21
|
+
'like',
|
|
22
|
+
'ilike',
|
|
23
|
+
]);
|
|
24
|
+
function bind(value) {
|
|
25
|
+
if (DecimalJs.isDecimal(value))
|
|
26
|
+
return value.toFixed();
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function column(model, key, translation) {
|
|
30
|
+
const field = model.fields[key];
|
|
31
|
+
const col = model.columns[key];
|
|
32
|
+
if (field === undefined) {
|
|
33
|
+
throw new InvalidDomainError(`'${key}' is not a field of ${model.name}.`, `Fields: ${Object.keys(model.fields).join(', ')}.`);
|
|
34
|
+
}
|
|
35
|
+
if (field.encrypted) {
|
|
36
|
+
throw new InvalidDomainError(`'${key}' of ${model.name} is encrypted and cannot be filtered or sorted on.`, 'Encrypted values are opaque to the database; filter in memory after loading, or store a searchable hash in another field.');
|
|
37
|
+
}
|
|
38
|
+
if (col === undefined) {
|
|
39
|
+
throw new InvalidDomainError(`'${key}' of ${model.name} is a ${field.kind} field and cannot be filtered on directly.`, 'Filter x2many relations with any / all / none (full domain compiler), and non-stored computes in memory.');
|
|
40
|
+
}
|
|
41
|
+
if (field.translate && translation !== undefined) {
|
|
42
|
+
// COALESCE(col->>lang, col->>source): what readers see, so filters and sorts match reads (RFC 0005 §7.4).
|
|
43
|
+
return {
|
|
44
|
+
field,
|
|
45
|
+
column: sql `COALESCE(${sql.id(col)}->>${translation.lang}, ${sql.id(col)}->>${translation.source})`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return { field, column: sql.id(col) };
|
|
49
|
+
}
|
|
50
|
+
function condition(col, op, value, key) {
|
|
51
|
+
switch (op) {
|
|
52
|
+
case 'eq':
|
|
53
|
+
return value === null ? sql `${col} IS NULL` : sql `${col} = ${bind(value)}`;
|
|
54
|
+
case 'ne':
|
|
55
|
+
return value === null ? sql `${col} IS NOT NULL` : sql `${col} IS DISTINCT FROM ${bind(value)}`;
|
|
56
|
+
case 'lt':
|
|
57
|
+
return sql `${col} < ${bind(value)}`;
|
|
58
|
+
case 'lte':
|
|
59
|
+
return sql `${col} <= ${bind(value)}`;
|
|
60
|
+
case 'gt':
|
|
61
|
+
return sql `${col} > ${bind(value)}`;
|
|
62
|
+
case 'gte':
|
|
63
|
+
return sql `${col} >= ${bind(value)}`;
|
|
64
|
+
case 'in': {
|
|
65
|
+
if (!Array.isArray(value))
|
|
66
|
+
throw new InvalidDomainError(`'${key}': in needs an array.`, "Use { in: ['draft', 'sale'] }.");
|
|
67
|
+
return value.length === 0 ? sql `FALSE` : sql `${col} = ANY(${value.map(bind)})`;
|
|
68
|
+
}
|
|
69
|
+
case 'notIn': {
|
|
70
|
+
if (!Array.isArray(value))
|
|
71
|
+
throw new InvalidDomainError(`'${key}': notIn needs an array.`, "Use { notIn: ['cancel'] }.");
|
|
72
|
+
return value.length === 0
|
|
73
|
+
? sql `TRUE`
|
|
74
|
+
: sql `(${col} IS NULL OR ${col} <> ALL(${value.map(bind)}))`;
|
|
75
|
+
}
|
|
76
|
+
case 'isNull':
|
|
77
|
+
return value === true ? sql `${col} IS NULL` : sql `${col} IS NOT NULL`;
|
|
78
|
+
case 'like':
|
|
79
|
+
return sql `${col} LIKE ${value}`;
|
|
80
|
+
case 'ilike':
|
|
81
|
+
return sql `${col} ILIKE ${value}`;
|
|
82
|
+
default:
|
|
83
|
+
throw new InvalidDomainError(`'${op}' is not a domain operator (field '${key}').`, `Use one of: ${[...OPERATORS].join(', ')}.`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function isOperators(value) {
|
|
87
|
+
return (typeof value === 'object' &&
|
|
88
|
+
value !== null &&
|
|
89
|
+
!Array.isArray(value) &&
|
|
90
|
+
!(value instanceof Date) &&
|
|
91
|
+
!DecimalJs.isDecimal(value) &&
|
|
92
|
+
Object.getPrototypeOf(value) === Object.prototype);
|
|
93
|
+
}
|
|
94
|
+
/** Compiles the user's domain into conditions (ANDed). */
|
|
95
|
+
export function compileDomain(model, where, translation, resolve, scope) {
|
|
96
|
+
const conditions = [];
|
|
97
|
+
for (const [key, value] of Object.entries(where ?? {})) {
|
|
98
|
+
if (value === undefined)
|
|
99
|
+
continue;
|
|
100
|
+
if (key === 'or' || key === 'and') {
|
|
101
|
+
if (!Array.isArray(value))
|
|
102
|
+
throw new InvalidDomainError(`'${key}' needs an array of domains.`, "Use { or: [{ state: 'draft' }, { user: 7 }] }.");
|
|
103
|
+
const parts = value.map((d) => {
|
|
104
|
+
const inner = compileDomain(model, d, translation, resolve, scope);
|
|
105
|
+
return inner.length === 0 ? sql `TRUE` : sql `(${sql.join(inner, sql ` AND `)})`;
|
|
106
|
+
});
|
|
107
|
+
if (parts.length > 0)
|
|
108
|
+
conditions.push(sql `(${sql.join(parts, key === 'or' ? sql ` OR ` : sql ` AND `)})`);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (key === 'not') {
|
|
112
|
+
const inner = compileDomain(model, value, translation, resolve, scope);
|
|
113
|
+
if (inner.length > 0)
|
|
114
|
+
conditions.push(sql `NOT (${sql.join(inner, sql ` AND `)})`);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const dot = key.indexOf('.');
|
|
118
|
+
if (dot > 0) {
|
|
119
|
+
// 'partner.name': the condition on the related model, as a sub-select.
|
|
120
|
+
conditions.push(relation(model, key.slice(0, dot), { [key.slice(dot + 1)]: value }, 'any', translation, resolve, scope));
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const relField = model.fields[key];
|
|
124
|
+
if (relField !== undefined && (relField.kind === 'one2many' || relField.kind === 'many2many')) {
|
|
125
|
+
if (!isOperators(value) || Object.keys(value).some((k) => k !== 'any' && k !== 'none'))
|
|
126
|
+
throw new InvalidDomainError(`'${key}' is a ${relField.kind}: filter it with { any: domain } or { none: domain }.`, `E.g. { ${key}: { any: { quantity: { gt: 10 } } } }.`);
|
|
127
|
+
for (const mode of ['any', 'none']) {
|
|
128
|
+
const inner = value[mode];
|
|
129
|
+
if (inner !== undefined)
|
|
130
|
+
conditions.push(relation(model, key, inner, mode, translation, resolve, scope));
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const { column: col } = column(model, key, translation);
|
|
135
|
+
if (isOperators(value)) {
|
|
136
|
+
for (const [op, operand] of Object.entries(value)) {
|
|
137
|
+
if (operand === undefined)
|
|
138
|
+
continue;
|
|
139
|
+
if (!OPERATORS.has(op)) {
|
|
140
|
+
throw new InvalidDomainError(`'${op}' is not a domain operator (field '${key}').`, `Use one of: ${[...OPERATORS].join(', ')}.`);
|
|
141
|
+
}
|
|
142
|
+
conditions.push(condition(col, op, operand, key));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
conditions.push(condition(col, 'eq', value, key));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return conditions;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* A condition through relation `key`: records related to at least one (`any`) or no (`none`) record of the target
|
|
153
|
+
* matching `inner`.
|
|
154
|
+
*/
|
|
155
|
+
function relation(model, key, inner, mode, translation, resolve, scope) {
|
|
156
|
+
const field = model.fields[key];
|
|
157
|
+
const targetName = field?.target;
|
|
158
|
+
if (field === undefined || targetName === undefined) {
|
|
159
|
+
throw new InvalidDomainError(`'${key}' is not a relation of ${model.name}, so it cannot start a path.`, `Paths go through many2one, one2many or many2many fields of ${model.name}.`);
|
|
160
|
+
}
|
|
161
|
+
if (resolve === undefined) {
|
|
162
|
+
throw new InvalidDomainError(`Relation path '${key}.…' needs the registry.`, 'This compiler call has no model resolver.');
|
|
163
|
+
}
|
|
164
|
+
const target = resolve(targetName);
|
|
165
|
+
const conditions = [
|
|
166
|
+
...compileDomain(target, inner, translation, resolve, scope),
|
|
167
|
+
...(scope?.(target) ?? []),
|
|
168
|
+
];
|
|
169
|
+
const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
|
|
170
|
+
const targets = sql `SELECT ${sql.id('id')} FROM ${sql.id(target.table)}${where}`;
|
|
171
|
+
let match;
|
|
172
|
+
if (field.kind === 'many2one') {
|
|
173
|
+
const col = sql.id(model.columns[key] ?? '');
|
|
174
|
+
return mode === 'any'
|
|
175
|
+
? sql `${col} IN (${targets})`
|
|
176
|
+
: sql `(${col} IS NULL OR ${col} NOT IN (${targets}))`;
|
|
177
|
+
}
|
|
178
|
+
if (field.kind === 'one2many') {
|
|
179
|
+
const inverse = sql.id(target.columns[field.inverseField ?? ''] ?? '');
|
|
180
|
+
const and = conditions.length === 0 ? sql.empty : sql ` AND ${sql.join(conditions, sql ` AND `)}`;
|
|
181
|
+
match = sql `SELECT ${inverse} FROM ${sql.id(target.table)} WHERE ${inverse} IS NOT NULL${and}`;
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
const j = junctionTable(model, field, target);
|
|
185
|
+
match = sql `SELECT ${sql.id(j.sourceColumn)} FROM ${sql.id(j.table)} WHERE ${sql.id(j.targetColumn)} IN (${targets})`;
|
|
186
|
+
}
|
|
187
|
+
return mode === 'any'
|
|
188
|
+
? sql `${sql.id('id')} IN (${match})`
|
|
189
|
+
: sql `${sql.id('id')} NOT IN (${match})`;
|
|
190
|
+
}
|
|
191
|
+
/** Conditions the environment adds to every search (RFC 0005 §7.4): archived records and company scope. */
|
|
192
|
+
export function scopingConditions(model, env) {
|
|
193
|
+
const conditions = [];
|
|
194
|
+
if (model.archivable && env.flags.activeTest) {
|
|
195
|
+
const active = model.columns['active'];
|
|
196
|
+
if (active !== undefined)
|
|
197
|
+
conditions.push(sql `${sql.id(active)} = TRUE`);
|
|
198
|
+
}
|
|
199
|
+
if (model.companyScoped !== undefined && env.flags.checkCompany) {
|
|
200
|
+
const company = model.columns['company'];
|
|
201
|
+
if (company !== undefined) {
|
|
202
|
+
const inCompanies = sql `${sql.id(company)} = ANY(${[...env.companyIds]})`;
|
|
203
|
+
conditions.push(model.companyScoped.required
|
|
204
|
+
? inCompanies
|
|
205
|
+
: sql `(${inCompanies} OR ${sql.id(company)} IS NULL)`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return conditions;
|
|
209
|
+
}
|
|
210
|
+
/** `ORDER BY` from `'field'`, `'field asc'`, `'field desc'` entries, with an `id` tiebreaker. */
|
|
211
|
+
export function compileOrder(model, order, translation) {
|
|
212
|
+
const terms = [];
|
|
213
|
+
const specs = order ?? model.order.map((o) => `${o.field} ${o.direction}`);
|
|
214
|
+
let hasId = false;
|
|
215
|
+
for (const spec of specs) {
|
|
216
|
+
const [key, direction = 'asc', ...rest] = spec.split(' ');
|
|
217
|
+
if (key === undefined || rest.length > 0 || (direction !== 'asc' && direction !== 'desc')) {
|
|
218
|
+
throw new InvalidDomainError(`order entry '${spec}' is malformed.`, "Use 'field', 'field asc' or 'field desc'.");
|
|
219
|
+
}
|
|
220
|
+
const { column: col } = column(model, key, translation);
|
|
221
|
+
if (key === 'id')
|
|
222
|
+
hasId = true;
|
|
223
|
+
terms.push(direction === 'desc' ? sql `${col} DESC` : sql `${col} ASC`);
|
|
224
|
+
}
|
|
225
|
+
if (!hasId)
|
|
226
|
+
terms.push(sql `${sql.id('id')} ASC`);
|
|
227
|
+
return sql.join(terms);
|
|
228
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Onchange (RFC 0009 §7.3–7.4): a draft is a virtual record in the cache (negative id). Handlers run for the changed
|
|
3
|
+
* fields, then the real compute engine computes the draft and its virtual child rows. Nothing is written; the virtual
|
|
4
|
+
* records are purged afterwards.
|
|
5
|
+
*/
|
|
6
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
7
|
+
import type { AnyModel } from '../model/model.js';
|
|
8
|
+
import { type ComputeHost } from './compute.js';
|
|
9
|
+
/** What the draft runtime needs from the recordset runtime. */
|
|
10
|
+
export interface OnchangeHost extends ComputeHost {
|
|
11
|
+
/** Stored, non-x2many keys with sibling currency / unit fields. */
|
|
12
|
+
defaults(model: AnyModel): Set<string>;
|
|
13
|
+
/** Children ids of an x2many of a real record. */
|
|
14
|
+
children(model: AnyModel, id: number, key: string): Promise<number[]>;
|
|
15
|
+
/** Plain JSON rows (as `read()` returns them) of records. */
|
|
16
|
+
read(model: AnyModel, ids: readonly number[], keys: readonly string[]): Record<string, unknown>[];
|
|
17
|
+
}
|
|
18
|
+
/** The input of `env.model(M).onchange()`. */
|
|
19
|
+
export interface OnchangeInputRaw {
|
|
20
|
+
readonly id?: number | undefined;
|
|
21
|
+
readonly values: Readonly<Record<string, unknown>>;
|
|
22
|
+
readonly changed: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
/** The output of `env.model(M).onchange()`. */
|
|
25
|
+
export interface OnchangeResultRaw {
|
|
26
|
+
/** Scalar and many2one fields whose plain value differs from the input. */
|
|
27
|
+
readonly values: Readonly<Record<string, unknown>>;
|
|
28
|
+
readonly warnings: readonly string[];
|
|
29
|
+
/** Plain rows of the virtual children created by x2many `create` commands, per field. */
|
|
30
|
+
readonly children: Readonly<Record<string, readonly Record<string, unknown>[]>>;
|
|
31
|
+
}
|
|
32
|
+
/** The draft handed to onchange handlers (untyped runtime; typed as `Draft<S, M>`). */
|
|
33
|
+
export interface DraftRaw {
|
|
34
|
+
readonly id: number | null;
|
|
35
|
+
readonly env: ScopeInternals['env'];
|
|
36
|
+
get(key: string): unknown;
|
|
37
|
+
set(key: string, value: unknown): void;
|
|
38
|
+
/** The related record of a many2one (loaded), or null. */
|
|
39
|
+
record(key: string): Promise<unknown>;
|
|
40
|
+
warn(message: string): void;
|
|
41
|
+
}
|
|
42
|
+
/** `env.model(M).onchange(input)`. */
|
|
43
|
+
export declare function runOnchange(host: OnchangeHost, model: AnyModel, input: OnchangeInputRaw): Promise<OnchangeResultRaw>;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Onchange (RFC 0009 §7.3–7.4): a draft is a virtual record in the cache (negative id). Handlers run for the changed
|
|
3
|
+
* fields, then the real compute engine computes the draft and its virtual child rows. Nothing is written; the virtual
|
|
4
|
+
* records are purged afterwards.
|
|
5
|
+
*/
|
|
6
|
+
import { computeFields } from './compute.js';
|
|
7
|
+
import { assertAccess } from './security.js';
|
|
8
|
+
import { fail, normalize } from './values.js';
|
|
9
|
+
function translationOf(host) {
|
|
10
|
+
return { lang: host.internals.env.lang, source: host.internals.sourceLang };
|
|
11
|
+
}
|
|
12
|
+
function defaultOf(field, env) {
|
|
13
|
+
return typeof field.default === 'function'
|
|
14
|
+
? field.default(env)
|
|
15
|
+
: field.default;
|
|
16
|
+
}
|
|
17
|
+
function isX2Many(field) {
|
|
18
|
+
return field.kind === 'one2many' || field.kind === 'many2many';
|
|
19
|
+
}
|
|
20
|
+
function scalarKeys(model) {
|
|
21
|
+
return Object.keys(model.fields).filter((k) => !isX2Many(model.fields[k]));
|
|
22
|
+
}
|
|
23
|
+
/** Writes one draft value into the cache: `null` is always allowed, everything else is normalized like a write. */
|
|
24
|
+
function setDraftValue(model, values, key, value, translation) {
|
|
25
|
+
const field = model.fields[key];
|
|
26
|
+
if (field === undefined || key === 'id')
|
|
27
|
+
fail(model, [key], `'${key}' is not a field.`, `Fields: ${Object.keys(model.fields).join(', ')}.`);
|
|
28
|
+
if (value === null || value === undefined) {
|
|
29
|
+
values.set(key, null);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
// A virtual parent (negative id) is a valid draft reference.
|
|
33
|
+
if (field.kind === 'many2one' && typeof value === 'number' && value < 0) {
|
|
34
|
+
values.set(key, value);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
values.set(key, normalize(model, key, field, value, (k) => values.get(k), translation));
|
|
38
|
+
}
|
|
39
|
+
/** Fills a virtual record with defaults (or a real record's values), then the given values. */
|
|
40
|
+
async function materialize(host, model, id, given, preset, children) {
|
|
41
|
+
const { internals } = host;
|
|
42
|
+
const vid = internals.nextVirtualId();
|
|
43
|
+
const values = host.values(model.name, vid, true);
|
|
44
|
+
const stored = [...host.defaults(model)].filter((k) => k !== 'id' && model.columns[k] !== undefined);
|
|
45
|
+
if (id !== undefined) {
|
|
46
|
+
await host.load(model, [id], { fields: new Set(stored), relations: new Map() });
|
|
47
|
+
const current = host.values(model.name, id);
|
|
48
|
+
for (const key of stored)
|
|
49
|
+
values.set(key, current.get(key) ?? null);
|
|
50
|
+
for (const key of Object.keys(model.fields)) {
|
|
51
|
+
if (isX2Many(model.fields[key]))
|
|
52
|
+
values.set(key, await host.children(model, id, key));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
for (const key of stored) {
|
|
57
|
+
const field = model.fields[key];
|
|
58
|
+
// Defaults are normalized like given values ('1' → Decimal), so computes on drafts see real types.
|
|
59
|
+
if (field.computed)
|
|
60
|
+
values.set(key, null);
|
|
61
|
+
else
|
|
62
|
+
setDraftValue(model, values, key, defaultOf(field, internals.env) ?? null, translationOf(host));
|
|
63
|
+
}
|
|
64
|
+
for (const key of Object.keys(model.fields)) {
|
|
65
|
+
if (isX2Many(model.fields[key]))
|
|
66
|
+
values.set(key, []);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
for (const [key, value] of Object.entries(preset))
|
|
70
|
+
setDraftValue(model, values, key, value, translationOf(host));
|
|
71
|
+
for (const [key, value] of Object.entries(given)) {
|
|
72
|
+
if (value === undefined)
|
|
73
|
+
continue;
|
|
74
|
+
const field = model.fields[key];
|
|
75
|
+
if (field !== undefined && isX2Many(field)) {
|
|
76
|
+
const commands = (value ?? {});
|
|
77
|
+
const target = internals.registry.get(field.target ?? '').model;
|
|
78
|
+
const list = [...(values.get(key) ?? [])];
|
|
79
|
+
if (Array.isArray(commands['set']))
|
|
80
|
+
list.splice(0, list.length, ...commands['set']);
|
|
81
|
+
if (Array.isArray(commands['link']))
|
|
82
|
+
for (const linked of commands['link'])
|
|
83
|
+
if (!list.includes(linked))
|
|
84
|
+
list.push(linked);
|
|
85
|
+
const created = [];
|
|
86
|
+
if (Array.isArray(commands['create'])) {
|
|
87
|
+
const inverse = field.kind === 'one2many'
|
|
88
|
+
? (field.inverseField ?? '')
|
|
89
|
+
: '';
|
|
90
|
+
for (const row of commands['create']) {
|
|
91
|
+
const cid = await materialize(host, target, undefined, row, inverse === '' ? {} : { [inverse]: vid }, new Map());
|
|
92
|
+
created.push(cid);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
list.push(...created);
|
|
96
|
+
values.set(key, list);
|
|
97
|
+
children.set(key, created);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
setDraftValue(model, values, key, value, translationOf(host));
|
|
101
|
+
}
|
|
102
|
+
return vid;
|
|
103
|
+
}
|
|
104
|
+
/** Computes every computed field of `model` for `ids`, in rank order (fields sharing a compute go together). */
|
|
105
|
+
async function computeAll(host, model, ids) {
|
|
106
|
+
const fields = host.internals.registry.compute.fields
|
|
107
|
+
.filter((f) => f.model === model.name)
|
|
108
|
+
.sort((a, b) => a.rank - b.rank);
|
|
109
|
+
const done = new Set();
|
|
110
|
+
for (const f of fields) {
|
|
111
|
+
if (done.has(f.compute))
|
|
112
|
+
continue;
|
|
113
|
+
done.add(f.compute);
|
|
114
|
+
await computeFields(host, model, ids, [f]);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** `env.model(M).onchange(input)`. */
|
|
118
|
+
export async function runOnchange(host, model, input) {
|
|
119
|
+
const { internals } = host;
|
|
120
|
+
assertAccess(internals, model, 'read');
|
|
121
|
+
const warnings = [];
|
|
122
|
+
const childIds = new Map();
|
|
123
|
+
const wasRecomputing = internals.compute.recomputing;
|
|
124
|
+
internals.compute.recomputing = true; // suspends recompute and constraint checks for nested flushes (RFC 0009 §7.4)
|
|
125
|
+
const created = [];
|
|
126
|
+
try {
|
|
127
|
+
const vid = await materialize(host, model, input.id, input.values, {}, childIds);
|
|
128
|
+
created.push({ model: model, id: vid });
|
|
129
|
+
for (const [key, ids] of childIds) {
|
|
130
|
+
const target = internals.registry.get(model.fields[key].target ?? '').model;
|
|
131
|
+
for (const id of ids)
|
|
132
|
+
created.push({ model: target, id });
|
|
133
|
+
}
|
|
134
|
+
const values = host.values(model.name, vid);
|
|
135
|
+
const keys = scalarKeys(model).filter((k) => k !== 'id');
|
|
136
|
+
// Loads nothing (every column is in the cache) but brings the currency / unit objects the reads need.
|
|
137
|
+
await host.load(model, [vid], {
|
|
138
|
+
fields: new Set(keys.filter((k) => model.columns[k] !== undefined)),
|
|
139
|
+
relations: new Map(),
|
|
140
|
+
});
|
|
141
|
+
const [beforeRow] = host.read(model, [vid], keys.filter((k) => values.has(k)));
|
|
142
|
+
// Handlers, cascading once per key.
|
|
143
|
+
const queue = [...input.changed];
|
|
144
|
+
const done = new Set();
|
|
145
|
+
const draft = {
|
|
146
|
+
id: input.id ?? null,
|
|
147
|
+
env: internals.env,
|
|
148
|
+
get: (key) => values.get(key),
|
|
149
|
+
set(key, value) {
|
|
150
|
+
setDraftValue(model, values, key, value, translationOf(host));
|
|
151
|
+
if (!done.has(key) && !queue.includes(key))
|
|
152
|
+
queue.push(key);
|
|
153
|
+
},
|
|
154
|
+
async record(key) {
|
|
155
|
+
const field = model.fields[key];
|
|
156
|
+
const target = field?.target;
|
|
157
|
+
const id = values.get(key);
|
|
158
|
+
if (field?.kind !== 'many2one' || target === undefined || typeof id !== 'number')
|
|
159
|
+
return null;
|
|
160
|
+
const set = await host.recordset(internals.registry.get(target).model, [id]).load();
|
|
161
|
+
return set.first();
|
|
162
|
+
},
|
|
163
|
+
warn: (message) => {
|
|
164
|
+
warnings.push(message);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
while (queue.length > 0) {
|
|
168
|
+
const key = queue.shift();
|
|
169
|
+
if (done.has(key))
|
|
170
|
+
continue;
|
|
171
|
+
done.add(key);
|
|
172
|
+
const fn = model.onchange[key];
|
|
173
|
+
if (fn !== undefined)
|
|
174
|
+
await fn(draft, internals.env);
|
|
175
|
+
}
|
|
176
|
+
// Computes: children first, then the draft.
|
|
177
|
+
for (const [key, ids] of childIds) {
|
|
178
|
+
if (ids.length === 0)
|
|
179
|
+
continue;
|
|
180
|
+
const target = internals.registry.get(model.fields[key].target ?? '').model;
|
|
181
|
+
await computeAll(host, target, ids);
|
|
182
|
+
}
|
|
183
|
+
await computeAll(host, model, [vid]);
|
|
184
|
+
// Everything whose plain value differs from the draft as given (handler-set and computed fields).
|
|
185
|
+
const columnsOf = (m, ks) => new Set(ks.filter((k) => m.columns[k] !== undefined));
|
|
186
|
+
await host.load(model, [vid], { fields: columnsOf(model, keys), relations: new Map() }); // currency objects set by handlers
|
|
187
|
+
const [row] = host.read(model, [vid], keys);
|
|
188
|
+
const out = {};
|
|
189
|
+
for (const key of keys) {
|
|
190
|
+
if (JSON.stringify(row?.[key] ?? null) !== JSON.stringify(beforeRow?.[key] ?? null))
|
|
191
|
+
out[key] = row?.[key];
|
|
192
|
+
}
|
|
193
|
+
const children = {};
|
|
194
|
+
for (const [key, ids] of childIds) {
|
|
195
|
+
const target = internals.registry.get(model.fields[key].target ?? '').model;
|
|
196
|
+
const childKeys = scalarKeys(target).filter((k) => k !== 'id');
|
|
197
|
+
await host.load(target, ids, { fields: columnsOf(target, childKeys), relations: new Map() });
|
|
198
|
+
children[key] = host.read(target, ids, childKeys).map(({ id: _id, ...rest }) => rest);
|
|
199
|
+
}
|
|
200
|
+
return { values: out, warnings, children };
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
internals.compute.recomputing = wasRecomputing;
|
|
204
|
+
for (const { model: m, id } of created)
|
|
205
|
+
internals.forget(m.name, id);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recordset runtime (RFC 0004): identity map per transaction, prefetch groups, batched loads, typed access, and
|
|
3
|
+
* the entry points of writes (see writes.ts) and computes (see compute.ts).
|
|
4
|
+
*/
|
|
5
|
+
import type { AuditEntry } from '../../audit/index.js';
|
|
6
|
+
import { type Translations } from '../../i18n/index.js';
|
|
7
|
+
import { type Env, type ScopeInternals } from '../env/env.js';
|
|
8
|
+
import type { AnyModel } from '../model/model.js';
|
|
9
|
+
import { type Currency } from '../money/currency.js';
|
|
10
|
+
import { type Uom } from '../money/quantity.js';
|
|
11
|
+
import type { RegisteredModel } from '../registry/registry.js';
|
|
12
|
+
import { type OnchangeInputRaw, type OnchangeResultRaw } from './onchange.js';
|
|
13
|
+
/** Field values of one record. Scalars as values, many2one as id | null, x2many as id arrays. */
|
|
14
|
+
type Values = Map<string, unknown>;
|
|
15
|
+
/** The per-transaction identity map and value-object caches (RFC 0004 §7.4). */
|
|
16
|
+
export interface RecordCache {
|
|
17
|
+
readonly records: Map<string, Map<number, Values>>;
|
|
18
|
+
readonly currencies: Map<number, Currency>;
|
|
19
|
+
readonly uoms: Map<number, Uom>;
|
|
20
|
+
}
|
|
21
|
+
/** @internal */
|
|
22
|
+
export declare function createRecordCache(): RecordCache;
|
|
23
|
+
/** Stored, non-binary, not x2many (RFC 0004 §6.1). */
|
|
24
|
+
export declare function defaultKeys(model: AnyModel): string[];
|
|
25
|
+
/** Ids shared by the records loaded together (RFC 0004 §7.3). */
|
|
26
|
+
interface Group {
|
|
27
|
+
readonly ids: readonly number[];
|
|
28
|
+
}
|
|
29
|
+
interface Pending {
|
|
30
|
+
readonly parentModel: AnyModel;
|
|
31
|
+
readonly key: string;
|
|
32
|
+
/** The parent record(s) this set belongs to. */
|
|
33
|
+
readonly own: readonly number[];
|
|
34
|
+
/** Every parent of the prefetch group: loading fetches the relation for all of them. */
|
|
35
|
+
readonly parents: readonly number[];
|
|
36
|
+
}
|
|
37
|
+
/** @internal Runtime recordset. Typed through `RecordSet` / `Rec` / `PendingSet` (types.ts). */
|
|
38
|
+
export declare class RecordSetImpl {
|
|
39
|
+
#private;
|
|
40
|
+
readonly env: Env;
|
|
41
|
+
readonly registered: RegisteredModel;
|
|
42
|
+
readonly modelName: string;
|
|
43
|
+
constructor(env: Env, registered: RegisteredModel, ids: readonly number[] | undefined, group: Group | undefined, pending: Pending | undefined);
|
|
44
|
+
get model(): AnyModel;
|
|
45
|
+
get ids(): readonly number[];
|
|
46
|
+
get length(): number;
|
|
47
|
+
isEmpty(): boolean;
|
|
48
|
+
[Symbol.iterator](): Iterator<RecordSetImpl>;
|
|
49
|
+
first(): RecordSetImpl;
|
|
50
|
+
ensureOne(): RecordSetImpl;
|
|
51
|
+
/** The record's id (singletons only). */
|
|
52
|
+
get id(): number;
|
|
53
|
+
map<T>(fn: (record: never, index: number) => T): T[];
|
|
54
|
+
filter(fn: (record: never, index: number) => boolean): RecordSetImpl;
|
|
55
|
+
mapped(key: string): unknown[];
|
|
56
|
+
load(spec?: unknown): Promise<RecordSetImpl>;
|
|
57
|
+
/** Updates the records in the cache now; flushed at the next flush point. */
|
|
58
|
+
write(values: Readonly<Record<string, unknown>>): Promise<void>;
|
|
59
|
+
/** Deletes the records now. */
|
|
60
|
+
unlink(): Promise<void>;
|
|
61
|
+
/** Ids of a pending x2many set, loading them if needed. */
|
|
62
|
+
resolveIds(): Promise<readonly number[]>;
|
|
63
|
+
read(keys: readonly string[]): Record<string, unknown>[];
|
|
64
|
+
toJSON(): readonly number[];
|
|
65
|
+
/** The full translation map of a translatable field of a singleton (`null` when empty). */
|
|
66
|
+
translations(key: string): Translations | null;
|
|
67
|
+
/** The audit rows of these records, newest first (RFC 0013 §7.4). Pending changes are flushed first. */
|
|
68
|
+
trail(options?: {
|
|
69
|
+
readonly field?: string;
|
|
70
|
+
readonly limit?: number;
|
|
71
|
+
readonly action?: AuditEntry['action'];
|
|
72
|
+
}): Promise<AuditEntry[]>;
|
|
73
|
+
/** Numbers unnumbered records of a manual sequence field (RFC 0012 §7.4). */
|
|
74
|
+
assignNumber(key: string, options?: {
|
|
75
|
+
readonly date?: string | undefined;
|
|
76
|
+
}): Promise<void>;
|
|
77
|
+
/** @internal Runs a transition of state field `key` on these records (RFC 0010 §7.2). */
|
|
78
|
+
transition(key: string, name: string): Promise<void>;
|
|
79
|
+
/** Transition names the current state allows (singleton, state loaded). Defaults to the model's state field. */
|
|
80
|
+
transitions(key?: string): string[];
|
|
81
|
+
/** @internal Assigns a computed field of a singleton from inside its compute (RFC 0008 §7.5). */
|
|
82
|
+
assign(key: string, value: unknown): void;
|
|
83
|
+
/** @internal Reads field `key` of a singleton from the cache. */
|
|
84
|
+
fieldValue(key: string): unknown;
|
|
85
|
+
}
|
|
86
|
+
/** @internal The currency value object of a `res.currency` id, loaded through the cache. */
|
|
87
|
+
export declare function currencyById(internals: ScopeInternals, id: number): Promise<Currency>;
|
|
88
|
+
/** @internal The currency id of a company (`res.company.currency`). */
|
|
89
|
+
export declare function companyCurrencyId(internals: ScopeInternals, company: number): Promise<number>;
|
|
90
|
+
/** @internal Flushes the unit of work (every model, or one): pending computes first, then the dirty records. */
|
|
91
|
+
export declare function flushAll(internals: ScopeInternals, model?: string): Promise<void>;
|
|
92
|
+
/** @internal `env.model(name)`. */
|
|
93
|
+
export declare function modelRef(env: Env, name: string): {
|
|
94
|
+
modelName: string;
|
|
95
|
+
create(rows: readonly Readonly<Record<string, unknown>>[]): Promise<RecordSetImpl>;
|
|
96
|
+
search(query?: unknown): Promise<RecordSetImpl>;
|
|
97
|
+
browse(ids: readonly number[]): RecordSetImpl;
|
|
98
|
+
onchange(input: OnchangeInputRaw): Promise<OnchangeResultRaw>;
|
|
99
|
+
copy(rows: readonly Readonly<Record<string, unknown>>[]): Promise<RecordSetImpl>;
|
|
100
|
+
};
|
|
101
|
+
export {};
|