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,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `env.model(M).aggregate()` (feedback #13): grouped totals for reports, compiled to one `GROUP BY` statement with the
|
|
3
|
+
* same guarantees as `search`: read ACL, field groups on every grouped, measured and filtered field, record rules,
|
|
4
|
+
* archived / company scoping, relation paths with the targets' rules. Monetary measures are grouped by their currency
|
|
5
|
+
* as well, so a total is never a sum of two currencies.
|
|
6
|
+
*/
|
|
7
|
+
import { compile, sql } from '../../sql/index.js';
|
|
8
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
9
|
+
import { InvalidDomainError } from '../errors.js';
|
|
10
|
+
import { Money } from '../money/money.js';
|
|
11
|
+
import { compileDomain, scopingConditions } from './domain.js';
|
|
12
|
+
import { assertAccess, assertDomainFields, assertFields, ruleConditions } from './security.js';
|
|
13
|
+
const GRANULARITIES = new Set(['day', 'week', 'month', 'quarter', 'year']);
|
|
14
|
+
const GROUPABLE = new Set([
|
|
15
|
+
'char',
|
|
16
|
+
'selection',
|
|
17
|
+
'state',
|
|
18
|
+
'boolean',
|
|
19
|
+
'integer',
|
|
20
|
+
'date',
|
|
21
|
+
'datetime',
|
|
22
|
+
'many2one',
|
|
23
|
+
]);
|
|
24
|
+
const NUMERIC = new Set(['integer', 'float', 'decimal', 'monetary']);
|
|
25
|
+
const OPS = ['sum', 'avg', 'min', 'max'];
|
|
26
|
+
/** The grouping sets of a query (indexes into its groups), or `undefined` for a plain GROUP BY. */
|
|
27
|
+
function groupingSetsOf(query, groups) {
|
|
28
|
+
const modes = [
|
|
29
|
+
query.groupingSets !== undefined,
|
|
30
|
+
query.rollup === true,
|
|
31
|
+
query.cube === true,
|
|
32
|
+
].filter(Boolean);
|
|
33
|
+
if (modes.length === 0)
|
|
34
|
+
return undefined;
|
|
35
|
+
if (modes.length > 1)
|
|
36
|
+
invalid('Give one of groupingSets, rollup and cube.', 'They are alternative ways to ask for subtotals.');
|
|
37
|
+
const all = groups.map((_, i) => i);
|
|
38
|
+
if (query.rollup === true)
|
|
39
|
+
return all.map((_, n) => all.slice(0, all.length - n)).concat([[]]);
|
|
40
|
+
if (query.cube === true) {
|
|
41
|
+
if (groups.length > 6)
|
|
42
|
+
invalid(`cube over ${groups.length} groups makes ${2 ** groups.length} groupings.`, 'Use at most 6 groups, or explicit groupingSets.');
|
|
43
|
+
return Array.from({ length: 2 ** groups.length }, (_, mask) => all.filter((i) => (mask & (1 << i)) !== 0)).sort((a, b) => b.length - a.length);
|
|
44
|
+
}
|
|
45
|
+
const sets = (query.groupingSets ?? []).map((set) => set.map((name) => {
|
|
46
|
+
const index = groups.findIndex((g) => g.name === name);
|
|
47
|
+
if (index < 0)
|
|
48
|
+
invalid(`The grouping set [${set.join(', ')}] names '${name}', which is not in groupBy.`, 'Each set is a subset of groupBy.');
|
|
49
|
+
return index;
|
|
50
|
+
}));
|
|
51
|
+
if (sets.length === 0)
|
|
52
|
+
invalid('groupingSets is empty.', 'Give at least one set; [] is the grand total.');
|
|
53
|
+
return sets;
|
|
54
|
+
}
|
|
55
|
+
function invalid(problem, hint) {
|
|
56
|
+
throw new InvalidDomainError(problem, hint);
|
|
57
|
+
}
|
|
58
|
+
function groupOf(host, model, name) {
|
|
59
|
+
const [key = '', granularity, extra] = name.split(':');
|
|
60
|
+
const field = model.fields[key];
|
|
61
|
+
if (field === undefined ||
|
|
62
|
+
extra !== undefined ||
|
|
63
|
+
!GROUPABLE.has(field.kind) ||
|
|
64
|
+
model.columns[key] === undefined)
|
|
65
|
+
invalid(`'${name}' cannot group ${model.name}.`, 'Group by a stored char, selection, state, boolean, integer, date, datetime or many2one field; dates take a granularity, e.g. dateOrder:month.');
|
|
66
|
+
if (field.translate || field.companyDependent)
|
|
67
|
+
invalid(`'${key}' is translated or company-dependent; grouping by it is not supported.`, 'Group by an untranslated field.');
|
|
68
|
+
const column = sql.id(model.columns[key] ?? '');
|
|
69
|
+
if (granularity !== undefined) {
|
|
70
|
+
if (!GRANULARITIES.has(granularity) || (field.kind !== 'date' && field.kind !== 'datetime'))
|
|
71
|
+
invalid(`'${name}': only date and datetime fields take a granularity, one of day, week, month, quarter, year.`, 'Write e.g. dateOrder:month.');
|
|
72
|
+
// Datetimes are bucketed in the environment's time zone: "October" is the user's October.
|
|
73
|
+
const local = field.kind === 'datetime' ? sql `(${column} AT TIME ZONE ${host.internals.env.tz})` : column;
|
|
74
|
+
// A date, not text: the driver reads dates as 'YYYY-MM-DD' strings, and this costs nothing per row.
|
|
75
|
+
return { name, key, field, expr: sql `date_trunc(${granularity}, ${local})::date` };
|
|
76
|
+
}
|
|
77
|
+
if (field.kind === 'datetime')
|
|
78
|
+
invalid(`'${key}' is a datetime: give a granularity.`, `Write e.g. ${key}:day or ${key}:month.`);
|
|
79
|
+
return { name, key, field, expr: column };
|
|
80
|
+
}
|
|
81
|
+
function measureOf(model, name, spec) {
|
|
82
|
+
if (spec === 'count')
|
|
83
|
+
return { name, op: 'count', key: undefined, field: undefined, expr: sql `count(*)` };
|
|
84
|
+
const entries = typeof spec === 'object' && spec !== null ? Object.entries(spec) : [];
|
|
85
|
+
const [op, key] = (entries[0] ?? []);
|
|
86
|
+
if (entries.length !== 1 || !OPS.includes(op) || typeof key !== 'string')
|
|
87
|
+
invalid(`Measure '${name}' must be 'count' or one of { sum | avg | min | max: field }.`, "Write e.g. measures: { orders: 'count', total: { sum: 'amountTotal' } }.");
|
|
88
|
+
const field = model.fields[key];
|
|
89
|
+
if (field === undefined || !NUMERIC.has(field.kind) || model.columns[key] === undefined)
|
|
90
|
+
invalid(`Measure '${name}': '${key}' is not a stored numeric field of ${model.name}.`, 'Measure an integer, float, decimal or monetary field.');
|
|
91
|
+
const column = sql.id(model.columns[key] ?? '');
|
|
92
|
+
const expr = op === 'sum'
|
|
93
|
+
? sql `coalesce(sum(${column}), 0)`
|
|
94
|
+
: op === 'avg'
|
|
95
|
+
? sql `avg(${column})`
|
|
96
|
+
: op === 'min'
|
|
97
|
+
? sql `min(${column})`
|
|
98
|
+
: sql `max(${column})`;
|
|
99
|
+
return { name, op: op, key, field, expr };
|
|
100
|
+
}
|
|
101
|
+
/** The aggregate of a measure over `ref` (the column, or its alias in a grouping-sets subquery). */
|
|
102
|
+
function aggregateOf(measure, ref) {
|
|
103
|
+
switch (measure.op) {
|
|
104
|
+
case 'count':
|
|
105
|
+
return sql `count(*)`;
|
|
106
|
+
case 'sum':
|
|
107
|
+
return sql `coalesce(sum(${ref}), 0)`;
|
|
108
|
+
case 'avg':
|
|
109
|
+
return sql `avg(${ref})`;
|
|
110
|
+
case 'min':
|
|
111
|
+
return sql `min(${ref})`;
|
|
112
|
+
case 'max':
|
|
113
|
+
return sql `max(${ref})`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function convert(measure, raw, currency) {
|
|
117
|
+
if (measure.op === 'count')
|
|
118
|
+
return Number(raw);
|
|
119
|
+
if (raw === null || raw === undefined)
|
|
120
|
+
return null;
|
|
121
|
+
const kind = measure.field?.kind;
|
|
122
|
+
if (kind === 'integer' || kind === 'float') {
|
|
123
|
+
if (measure.op === 'avg')
|
|
124
|
+
return new DecimalJs(String(raw));
|
|
125
|
+
return Number(raw);
|
|
126
|
+
}
|
|
127
|
+
const amount = new DecimalJs(String(raw));
|
|
128
|
+
if (kind === 'monetary')
|
|
129
|
+
return currency === undefined ? null : Money.of(amount, currency);
|
|
130
|
+
return amount;
|
|
131
|
+
}
|
|
132
|
+
/** Runs an aggregate query. @throws {AccessError} @throws {InvalidDomainError} */
|
|
133
|
+
export async function runAggregate(host, model, query) {
|
|
134
|
+
const { internals } = host;
|
|
135
|
+
assertAccess(internals, model, 'read');
|
|
136
|
+
assertDomainFields(internals, model, query.where);
|
|
137
|
+
const groups = (query.groupBy ?? []).map((name) => groupOf(host, model, name));
|
|
138
|
+
const measures = Object.entries(query.measures).map(([name, spec]) => measureOf(model, name, spec));
|
|
139
|
+
if (measures.length === 0)
|
|
140
|
+
invalid('aggregate() needs at least one measure.', "Add e.g. measures: { count: 'count' }.");
|
|
141
|
+
const names = new Set();
|
|
142
|
+
for (const n of [...groups.map((g) => g.name), ...measures.map((m) => m.name)]) {
|
|
143
|
+
if (names.has(n))
|
|
144
|
+
invalid(`'${n}' is both a group and a measure.`, 'Rename the measure.');
|
|
145
|
+
names.add(n);
|
|
146
|
+
}
|
|
147
|
+
assertFields(internals, model, [...groups.map((g) => g.key), ...measures.flatMap((m) => (m.key === undefined ? [] : [m.key]))], 'read');
|
|
148
|
+
// Each monetary measure is also grouped by its currency field (never a sum across currencies).
|
|
149
|
+
const currencyKeys = [
|
|
150
|
+
...new Set(measures.flatMap((m) => m.field?.kind === 'monetary'
|
|
151
|
+
? [m.field.currencyField]
|
|
152
|
+
: [])),
|
|
153
|
+
];
|
|
154
|
+
for (const key of currencyKeys) {
|
|
155
|
+
if (model.columns[key] === undefined)
|
|
156
|
+
invalid(`The currency field '${key}' of ${model.name} is not stored, so monetary totals cannot be grouped by it.`, 'Store the currency field (store: true on a related currency).');
|
|
157
|
+
}
|
|
158
|
+
await internals.flush(); // the totals must see pending writes, including the targets of relation paths
|
|
159
|
+
const sets = groupingSetsOf(query, groups);
|
|
160
|
+
const conditions = [
|
|
161
|
+
...compileDomain(model, query.where, host.translation, (n) => internals.registry.get(n).model, (target) => ruleConditions(internals, target, 'read')),
|
|
162
|
+
...scopingConditions(model, internals.env),
|
|
163
|
+
...ruleConditions(internals, model, 'read'),
|
|
164
|
+
];
|
|
165
|
+
const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
|
|
166
|
+
const from = host.translation.from?.(model) ?? sql.id(model.table);
|
|
167
|
+
const limit = query.limit === undefined ? sql.empty : sql ` LIMIT ${query.limit}`;
|
|
168
|
+
let statement;
|
|
169
|
+
if (sets === undefined) {
|
|
170
|
+
const select = [
|
|
171
|
+
...groups.map((g, i) => sql `${g.expr} AS ${sql.id(`g${i}`)}`),
|
|
172
|
+
...currencyKeys.map((k, i) => sql `${sql.id(model.columns[k] ?? '')} AS ${sql.id(`c${i}`)}`),
|
|
173
|
+
...measures.map((m, i) => sql `${m.expr} AS ${sql.id(`m${i}`)}`),
|
|
174
|
+
];
|
|
175
|
+
const grouping = [
|
|
176
|
+
...groups.map((_, i) => sql.id(`g${i}`)),
|
|
177
|
+
...currencyKeys.map((_, i) => sql.id(`c${i}`)),
|
|
178
|
+
];
|
|
179
|
+
const groupBy = grouping.length === 0 ? sql.empty : sql ` GROUP BY ${sql.join(grouping)}`;
|
|
180
|
+
const order = orderOf(query.order, groups, measures, grouping);
|
|
181
|
+
statement = sql `SELECT ${sql.join(select)} FROM ${from}${where}${groupBy}${order}${limit}`;
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
// Grouping sets: an inner query computes each group expression and measure input once (bind parameters such as
|
|
185
|
+
// the granularity or time zone would otherwise make two copies of an expression differ), the outer one groups
|
|
186
|
+
// by their names. The currency stays in every set: a subtotal is never a sum of two currencies.
|
|
187
|
+
const inner = [
|
|
188
|
+
sql `1 AS ${sql.id('one')}`,
|
|
189
|
+
...groups.map((g, i) => sql `${g.expr} AS ${sql.id(`g${i}`)}`),
|
|
190
|
+
...currencyKeys.map((k, i) => sql `${sql.id(model.columns[k] ?? '')} AS ${sql.id(`c${i}`)}`),
|
|
191
|
+
...measures.flatMap((m, i) => m.key === undefined
|
|
192
|
+
? []
|
|
193
|
+
: [sql `${sql.id(model.columns[m.key] ?? '')} AS ${sql.id(`v${i}`)}`]),
|
|
194
|
+
];
|
|
195
|
+
const currencies = currencyKeys.map((_, i) => sql.id(`c${i}`));
|
|
196
|
+
const select = [
|
|
197
|
+
...groups.map((_, i) => sql `${sql.id(`g${i}`)}`),
|
|
198
|
+
...currencies,
|
|
199
|
+
...measures.map((m, i) => sql `${aggregateOf(m, sql.id(`v${i}`))} AS ${sql.id(`m${i}`)}`),
|
|
200
|
+
groups.length === 0
|
|
201
|
+
? sql `0 AS ${sql.id('gl')}`
|
|
202
|
+
: sql `GROUPING(${sql.join(groups.map((_, i) => sql.id(`g${i}`)))}) AS ${sql.id('gl')}`,
|
|
203
|
+
];
|
|
204
|
+
const groupingSets = sql `GROUPING SETS (${sql.join(sets.map((set) => sql `(${sql.join([...set.map((i) => sql.id(`g${i}`)), ...currencies])})`))})`;
|
|
205
|
+
// Leaves first, then each subtotal level, then the grand total.
|
|
206
|
+
const order = orderOf(query.order, groups, measures, [...groups.map((_, i) => sql.id(`g${i}`)), ...currencies], sql `${sql.id('gl')} ASC`);
|
|
207
|
+
statement = sql `SELECT ${sql.join(select)} FROM (SELECT ${sql.join(inner)} FROM ${from}${where}) AS ${sql.id('t')} GROUP BY ${groupingSets}${order}${limit}`;
|
|
208
|
+
}
|
|
209
|
+
const rows = await internals.query(compile(statement));
|
|
210
|
+
const out = [];
|
|
211
|
+
for (const row of rows) {
|
|
212
|
+
const result = {};
|
|
213
|
+
if (sets !== undefined) {
|
|
214
|
+
// GROUPING() sets bit (n - 1 - i) when group i is aggregated away in this row.
|
|
215
|
+
const mask = groups.length === 0 ? 0 : Number(row['gl']);
|
|
216
|
+
result['$groups'] = groups
|
|
217
|
+
.filter((_, i) => (mask & (1 << (groups.length - 1 - i))) === 0)
|
|
218
|
+
.map((g) => g.name);
|
|
219
|
+
}
|
|
220
|
+
groups.forEach((g, i) => {
|
|
221
|
+
const value = row[`g${i}`];
|
|
222
|
+
result[g.name] =
|
|
223
|
+
value === null || value === undefined
|
|
224
|
+
? null
|
|
225
|
+
: g.field.kind === 'many2one' || g.field.kind === 'integer'
|
|
226
|
+
? Number(value)
|
|
227
|
+
: value;
|
|
228
|
+
});
|
|
229
|
+
for (const [i, m] of measures.entries()) {
|
|
230
|
+
let currency;
|
|
231
|
+
if (m.field?.kind === 'monetary') {
|
|
232
|
+
const ci = currencyKeys.indexOf(m.field.currencyField);
|
|
233
|
+
const id = row[`c${ci}`];
|
|
234
|
+
currency = id === null || id === undefined ? undefined : await host.currency(Number(id));
|
|
235
|
+
}
|
|
236
|
+
result[m.name] = convert(m, row[`m${i}`], currency);
|
|
237
|
+
}
|
|
238
|
+
out.push(result);
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
function orderOf(order, groups, measures, grouping, first) {
|
|
243
|
+
const lead = first === undefined ? [] : [first];
|
|
244
|
+
if (order === undefined || order.length === 0)
|
|
245
|
+
return grouping.length === 0 && lead.length === 0
|
|
246
|
+
? sql.empty
|
|
247
|
+
: sql ` ORDER BY ${sql.join([...lead, ...grouping.map((g) => sql `${g} ASC NULLS LAST`)])}`;
|
|
248
|
+
const terms = order.map((term) => {
|
|
249
|
+
const [name = '', direction = 'asc', extra] = term.trim().split(/\s+/);
|
|
250
|
+
const gi = groups.findIndex((g) => g.name === name);
|
|
251
|
+
const mi = measures.findIndex((m) => m.name === name);
|
|
252
|
+
if ((gi < 0 && mi < 0) || extra !== undefined || (direction !== 'asc' && direction !== 'desc'))
|
|
253
|
+
invalid(`Cannot order the aggregate by '${term}'.`, "Order by a group or a measure name, optionally followed by 'asc' or 'desc'.");
|
|
254
|
+
const alias = sql.id(gi >= 0 ? `g${gi}` : `m${mi}`);
|
|
255
|
+
return direction === 'desc' ? sql `${alias} DESC NULLS LAST` : sql `${alias} ASC NULLS LAST`;
|
|
256
|
+
});
|
|
257
|
+
return sql ` ORDER BY ${sql.join([...lead, ...terms])}`;
|
|
258
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collecting the audit trail (RFC 0013 §7.2–7.3): rows of tracked changes are gathered per transaction attempt,
|
|
3
|
+
* coalesced per (record, field) and written at flush points in one statement, in the same transaction as the data.
|
|
4
|
+
*/
|
|
5
|
+
import { type AuditEntry, type AuditRowInput, type TrailFilter } from '../../audit/index.js';
|
|
6
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
7
|
+
import type { AnyModel } from '../model/model.js';
|
|
8
|
+
/** True when the model's `tracking` list or the field's `tracking` option names the field. */
|
|
9
|
+
export declare function isTracked(model: AnyModel, key: string): boolean;
|
|
10
|
+
/** Tracked field keys of a model (with the sibling currency / unit fields needed to render money). */
|
|
11
|
+
export declare function trackedKeys(model: AnyModel): Set<string>;
|
|
12
|
+
/** The JSON form of a cached value, as `read()` would return it (RFC 0013 §7.3). */
|
|
13
|
+
export declare function auditValue(internals: ScopeInternals, model: AnyModel, key: string, raw: unknown, siblings: (key: string) => unknown): unknown;
|
|
14
|
+
/** Records a change of a tracked field (no-op for untracked fields or with `flags.tracking` off). */
|
|
15
|
+
export declare function trackChange(internals: ScopeInternals, model: AnyModel, id: number, key: string, prev: unknown, next: unknown, siblings: (key: string) => unknown): void;
|
|
16
|
+
/** Records a creation or deletion with a snapshot of the tracked fields. */
|
|
17
|
+
export declare function trackSnapshot(internals: ScopeInternals, model: AnyModel, id: number, action: 'create' | 'unlink', values: ReadonlyMap<string, unknown>): void;
|
|
18
|
+
/** Records a superuser scope (RFC 0003 §7.6). */
|
|
19
|
+
export declare function trackSuperuser(internals: ScopeInternals, reason: string): void;
|
|
20
|
+
/** Records a scoped elevation (`env.withGrants`, elevated methods): which grants, and why (RFC 0014 §7.9). */
|
|
21
|
+
export declare function trackElevation(internals: ScopeInternals, grants: readonly string[], reason: string): void;
|
|
22
|
+
/** Records a runtime security change (RFC 0014 §7.10). */
|
|
23
|
+
export declare function trackSecurityChange(internals: ScopeInternals, change: object): void;
|
|
24
|
+
/** Coalesces `write` rows per (model, record, field): the first old, the last new; unchanged values are dropped. */
|
|
25
|
+
export declare function coalesceAudit(rows: readonly AuditRowInput[]): AuditRowInput[];
|
|
26
|
+
/** Writes the pending rows of `model` (or every row) in one statement. */
|
|
27
|
+
export declare function flushAudit(internals: ScopeInternals, model?: string): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* `records.trail()`: the rows of these records, newest first, after a flush. Field security applies: rows of fields
|
|
30
|
+
* the scope may not read are left out, and such fields are removed from create / delete snapshots. `limit` counts
|
|
31
|
+
* the rows returned (more are read when some are left out), so a page shorter than `limit` is the last one.
|
|
32
|
+
*/
|
|
33
|
+
export declare function trailOf(internals: ScopeInternals, model: AnyModel, ids: readonly number[], filter: Omit<TrailFilter, 'model' | 'recordIds'>): Promise<AuditEntry[]>;
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collecting the audit trail (RFC 0013 §7.2–7.3): rows of tracked changes are gathered per transaction attempt,
|
|
3
|
+
* coalesced per (record, field) and written at flush points in one statement, in the same transaction as the data.
|
|
4
|
+
*/
|
|
5
|
+
import { AUDIT_TABLE, auditTableStatements, insertAuditStatement, readTrail, } from '../../audit/index.js';
|
|
6
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
7
|
+
import { Money } from '../money/money.js';
|
|
8
|
+
import { canField } from './security.js';
|
|
9
|
+
const ensured = new WeakSet();
|
|
10
|
+
async function ensureTable(driver) {
|
|
11
|
+
if (ensured.has(driver))
|
|
12
|
+
return;
|
|
13
|
+
// Created by migrations in production (the application role may not own the schema); on first use otherwise.
|
|
14
|
+
const [row] = await driver.query({
|
|
15
|
+
text: `SELECT to_regclass('${AUDIT_TABLE}') IS NOT NULL AS present`,
|
|
16
|
+
params: [],
|
|
17
|
+
});
|
|
18
|
+
if (row?.present !== true)
|
|
19
|
+
for (const statement of auditTableStatements())
|
|
20
|
+
await driver.query(statement);
|
|
21
|
+
ensured.add(driver);
|
|
22
|
+
}
|
|
23
|
+
/** True when the model's `tracking` list or the field's `tracking` option names the field. */
|
|
24
|
+
export function isTracked(model, key) {
|
|
25
|
+
const field = model.fields[key];
|
|
26
|
+
if (field === undefined || field.kind === 'one2many' || field.kind === 'many2many')
|
|
27
|
+
return false;
|
|
28
|
+
return field.tracking || model.tracking.includes(key);
|
|
29
|
+
}
|
|
30
|
+
/** Tracked field keys of a model (with the sibling currency / unit fields needed to render money). */
|
|
31
|
+
export function trackedKeys(model) {
|
|
32
|
+
const keys = new Set();
|
|
33
|
+
for (const key of Object.keys(model.fields)) {
|
|
34
|
+
if (!isTracked(model, key))
|
|
35
|
+
continue;
|
|
36
|
+
keys.add(key);
|
|
37
|
+
const field = model.fields[key];
|
|
38
|
+
if (field?.currencyField !== undefined)
|
|
39
|
+
keys.add(field.currencyField);
|
|
40
|
+
if (field?.uomField !== undefined)
|
|
41
|
+
keys.add(field.uomField);
|
|
42
|
+
}
|
|
43
|
+
return keys;
|
|
44
|
+
}
|
|
45
|
+
/** The JSON form of a cached value, as `read()` would return it (RFC 0013 §7.3). */
|
|
46
|
+
export function auditValue(internals, model, key, raw, siblings) {
|
|
47
|
+
if (raw === undefined || raw === null)
|
|
48
|
+
return null;
|
|
49
|
+
if (model.fields[key]?.encrypted)
|
|
50
|
+
return '[encrypted]';
|
|
51
|
+
const field = model.fields[key];
|
|
52
|
+
if (field?.kind === 'monetary' && DecimalJs.isDecimal(raw)) {
|
|
53
|
+
const currencyId = siblings(field.currencyField ?? '');
|
|
54
|
+
const currency = typeof currencyId === 'number' ? internals.cache.currencies.get(currencyId) : undefined;
|
|
55
|
+
if (currency !== undefined)
|
|
56
|
+
return Money.of(raw, currency).toJSON(); // rounded like read()
|
|
57
|
+
return { amount: raw.toFixed(), currency: null };
|
|
58
|
+
}
|
|
59
|
+
if (field?.kind === 'quantity' && DecimalJs.isDecimal(raw)) {
|
|
60
|
+
const uomId = siblings(field.uomField ?? '');
|
|
61
|
+
const uom = typeof uomId === 'number' ? internals.cache.uoms.get(uomId) : undefined;
|
|
62
|
+
return { value: raw.toFixed(), uom: uom?.name ?? null };
|
|
63
|
+
}
|
|
64
|
+
if (DecimalJs.isDecimal(raw))
|
|
65
|
+
return raw.toFixed();
|
|
66
|
+
if (raw instanceof Date)
|
|
67
|
+
return raw.toISOString();
|
|
68
|
+
if (typeof raw === 'bigint')
|
|
69
|
+
return raw.toString();
|
|
70
|
+
return raw;
|
|
71
|
+
}
|
|
72
|
+
function base(internals) {
|
|
73
|
+
const { env } = internals;
|
|
74
|
+
return {
|
|
75
|
+
at: env.now(),
|
|
76
|
+
tx: internals.tx,
|
|
77
|
+
uid: env.uid,
|
|
78
|
+
companyId: env.companyId,
|
|
79
|
+
su: env.su,
|
|
80
|
+
reason: env.reason ?? null,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** Records a change of a tracked field (no-op for untracked fields or with `flags.tracking` off). */
|
|
84
|
+
export function trackChange(internals, model, id, key, prev, next, siblings) {
|
|
85
|
+
if (!internals.env.flags.tracking || !isTracked(model, key) || id < 0)
|
|
86
|
+
return;
|
|
87
|
+
internals.auditRows.push({
|
|
88
|
+
...base(internals),
|
|
89
|
+
action: 'write',
|
|
90
|
+
model: model.name,
|
|
91
|
+
recordId: id,
|
|
92
|
+
field: key,
|
|
93
|
+
old: auditValue(internals, model, key, prev, siblings),
|
|
94
|
+
new: auditValue(internals, model, key, next, siblings),
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** Records a creation or deletion with a snapshot of the tracked fields. */
|
|
98
|
+
export function trackSnapshot(internals, model, id, action, values) {
|
|
99
|
+
if (!internals.env.flags.tracking || id < 0)
|
|
100
|
+
return;
|
|
101
|
+
const snapshot = {};
|
|
102
|
+
let any = false;
|
|
103
|
+
for (const key of Object.keys(model.fields)) {
|
|
104
|
+
if (!isTracked(model, key))
|
|
105
|
+
continue;
|
|
106
|
+
any = true;
|
|
107
|
+
snapshot[key] = values.has(key)
|
|
108
|
+
? auditValue(internals, model, key, values.get(key), (k) => values.get(k))
|
|
109
|
+
: null;
|
|
110
|
+
}
|
|
111
|
+
if (!any)
|
|
112
|
+
return;
|
|
113
|
+
internals.auditRows.push({
|
|
114
|
+
...base(internals),
|
|
115
|
+
action,
|
|
116
|
+
model: model.name,
|
|
117
|
+
recordId: id,
|
|
118
|
+
field: null,
|
|
119
|
+
old: action === 'unlink' ? snapshot : null,
|
|
120
|
+
new: action === 'create' ? snapshot : null,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/** Records a superuser scope (RFC 0003 §7.6). */
|
|
124
|
+
export function trackSuperuser(internals, reason) {
|
|
125
|
+
if (!internals.env.flags.tracking)
|
|
126
|
+
return;
|
|
127
|
+
internals.auditRows.push({
|
|
128
|
+
...base(internals),
|
|
129
|
+
su: true,
|
|
130
|
+
reason,
|
|
131
|
+
action: 'su',
|
|
132
|
+
model: null,
|
|
133
|
+
recordId: null,
|
|
134
|
+
field: null,
|
|
135
|
+
old: null,
|
|
136
|
+
new: null,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/** Records a scoped elevation (`env.withGrants`, elevated methods): which grants, and why (RFC 0014 §7.9). */
|
|
140
|
+
export function trackElevation(internals, grants, reason) {
|
|
141
|
+
if (!internals.env.flags.tracking)
|
|
142
|
+
return;
|
|
143
|
+
internals.auditRows.push({
|
|
144
|
+
...base(internals),
|
|
145
|
+
su: false,
|
|
146
|
+
reason,
|
|
147
|
+
action: 'elevate',
|
|
148
|
+
model: null,
|
|
149
|
+
recordId: null,
|
|
150
|
+
field: null,
|
|
151
|
+
old: null,
|
|
152
|
+
new: [...grants],
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** Records a runtime security change (RFC 0014 §7.10). */
|
|
156
|
+
export function trackSecurityChange(internals, change) {
|
|
157
|
+
if (!internals.env.flags.tracking)
|
|
158
|
+
return;
|
|
159
|
+
internals.auditRows.push({
|
|
160
|
+
...base(internals),
|
|
161
|
+
su: internals.env.su,
|
|
162
|
+
reason: null,
|
|
163
|
+
action: 'security',
|
|
164
|
+
model: null,
|
|
165
|
+
recordId: null,
|
|
166
|
+
field: null,
|
|
167
|
+
old: null,
|
|
168
|
+
new: change,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
function same(a, b) {
|
|
172
|
+
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
173
|
+
}
|
|
174
|
+
/** Coalesces `write` rows per (model, record, field): the first old, the last new; unchanged values are dropped. */
|
|
175
|
+
export function coalesceAudit(rows) {
|
|
176
|
+
const out = [];
|
|
177
|
+
const writes = new Map();
|
|
178
|
+
const creates = new Map();
|
|
179
|
+
for (const row of rows) {
|
|
180
|
+
if (row.action !== 'write') {
|
|
181
|
+
if (row.action === 'create')
|
|
182
|
+
creates.set(`${row.model}|${row.recordId}`, out.length);
|
|
183
|
+
out.push(row);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
// A value first computed or numbered in the transaction that created the record belongs to its creation.
|
|
187
|
+
const created = creates.get(`${row.model}|${row.recordId}`);
|
|
188
|
+
if (created !== undefined && row.field !== null && (row.old ?? null) === null) {
|
|
189
|
+
const createRow = out[created];
|
|
190
|
+
const snapshot = { ...createRow.new };
|
|
191
|
+
if ((snapshot[row.field] ?? null) === null) {
|
|
192
|
+
snapshot[row.field] = row.new;
|
|
193
|
+
out[created] = { ...createRow, new: snapshot };
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const key = `${row.model}|${row.recordId}|${row.field}`;
|
|
198
|
+
const at = writes.get(key);
|
|
199
|
+
if (at === undefined) {
|
|
200
|
+
writes.set(key, out.length);
|
|
201
|
+
out.push(row);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
const first = out[at];
|
|
205
|
+
out[at] = {
|
|
206
|
+
...first,
|
|
207
|
+
new: row.new,
|
|
208
|
+
uid: row.uid,
|
|
209
|
+
su: first.su || row.su,
|
|
210
|
+
reason: first.reason ?? row.reason,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return out.filter((row) => row.action !== 'write' || !same(row.old, row.new));
|
|
215
|
+
}
|
|
216
|
+
/** Writes the pending rows of `model` (or every row) in one statement. */
|
|
217
|
+
export async function flushAudit(internals, model) {
|
|
218
|
+
const rows = internals.auditRows;
|
|
219
|
+
if (rows.length === 0)
|
|
220
|
+
return;
|
|
221
|
+
const take = model === undefined ? rows.splice(0) : [];
|
|
222
|
+
if (model !== undefined) {
|
|
223
|
+
for (let i = rows.length - 1; i >= 0; i--) {
|
|
224
|
+
if (rows[i]?.model === model)
|
|
225
|
+
take.unshift(...rows.splice(i, 1));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const coalesced = coalesceAudit(take);
|
|
229
|
+
if (coalesced.length === 0)
|
|
230
|
+
return;
|
|
231
|
+
await ensureTable(internals.driver);
|
|
232
|
+
await internals.query(insertAuditStatement(coalesced));
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* `records.trail()`: the rows of these records, newest first, after a flush. Field security applies: rows of fields
|
|
236
|
+
* the scope may not read are left out, and such fields are removed from create / delete snapshots. `limit` counts
|
|
237
|
+
* the rows returned (more are read when some are left out), so a page shorter than `limit` is the last one.
|
|
238
|
+
*/
|
|
239
|
+
export async function trailOf(internals, model, ids, filter) {
|
|
240
|
+
await internals.flush();
|
|
241
|
+
const limit = filter.limit ?? 100;
|
|
242
|
+
const readable = (key) => canField(internals, model, key, 'read');
|
|
243
|
+
const strip = (snapshot) => snapshot !== null && typeof snapshot === 'object' && !Array.isArray(snapshot)
|
|
244
|
+
? Object.fromEntries(Object.entries(snapshot).filter(([key]) => readable(key)))
|
|
245
|
+
: snapshot;
|
|
246
|
+
const out = [];
|
|
247
|
+
let before = filter.before;
|
|
248
|
+
for (;;) {
|
|
249
|
+
const rows = await readTrail({ query: (q) => internals.query(q) }, { ...filter, model: model.name, recordIds: ids, limit, before });
|
|
250
|
+
for (const row of rows) {
|
|
251
|
+
if (row.field === null)
|
|
252
|
+
out.push({ ...row, old: strip(row.old), new: strip(row.new) });
|
|
253
|
+
else if (readable(row.field))
|
|
254
|
+
out.push(row);
|
|
255
|
+
if (out.length === limit)
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
if (rows.length < limit)
|
|
259
|
+
return out;
|
|
260
|
+
before = rows[rows.length - 1]?.id;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The compute engine at runtime (RFC 0008): trigger invalidation through the cache, resolution of triggers into the
|
|
3
|
+
* affected records (database + cache), batched recompute in rank order before flushes, computation of non-stored
|
|
4
|
+
* fields on load, and the assignment protocol inside computes.
|
|
5
|
+
*/
|
|
6
|
+
import type { ComputedField } from '../compute/graph.js';
|
|
7
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
8
|
+
import { type AnyModel } from '../model/model.js';
|
|
9
|
+
/** A load spec as the loader understands it (same shape as its normalized specs). */
|
|
10
|
+
export interface ComputeSpec {
|
|
11
|
+
readonly fields: ReadonlySet<string>;
|
|
12
|
+
readonly relations: ReadonlyMap<string, ComputeSpec>;
|
|
13
|
+
}
|
|
14
|
+
/** What the engine needs from the recordset runtime (passed in to avoid a module cycle). */
|
|
15
|
+
export interface ComputeHost {
|
|
16
|
+
readonly internals: ScopeInternals;
|
|
17
|
+
load(model: AnyModel, ids: readonly number[], spec: ComputeSpec): Promise<void>;
|
|
18
|
+
/** Loads the `Currency` / `Uom` objects the monetary / quantity `fields` of the records refer to. */
|
|
19
|
+
valueObjects(model: AnyModel, ids: readonly number[], fields: ReadonlySet<string>): Promise<void>;
|
|
20
|
+
values(model: string, id: number, create?: boolean): Map<string, unknown> | undefined;
|
|
21
|
+
/** A recordset of `ids` (one prefetch group) to pass to compute functions. */
|
|
22
|
+
recordset(model: AnyModel, ids: readonly number[]): unknown;
|
|
23
|
+
}
|
|
24
|
+
/** Drops the cached values of the dependents of `(model, key)` that are in the cache (RFC 0008 §7.2). Cache only. */
|
|
25
|
+
export declare function invalidateCached(internals: ScopeInternals, model: string, key: string, ids: readonly number[]): void;
|
|
26
|
+
/** The load spec covering the `depends` of `fields` (RFC 0004 §7.5), plus the sibling currency / unit fields. */
|
|
27
|
+
export declare function dependsSpec(internals: ScopeInternals, model: AnyModel, fields: readonly ComputedField[]): ComputeSpec;
|
|
28
|
+
/** Assigns a computed value from inside its compute (the record accessors' setter). */
|
|
29
|
+
export declare function assignComputed(host: ComputeHost, model: AnyModel, id: number, key: string, value: unknown): void;
|
|
30
|
+
/**
|
|
31
|
+
* Computes `fields` of `model` for `ids`: loads their `depends` for the whole batch, runs each compute once, then
|
|
32
|
+
* checks required fields. Fields sharing a compute are computed together.
|
|
33
|
+
*/
|
|
34
|
+
export declare function computeFields(host: ComputeHost, model: AnyModel, ids: readonly number[], fields: readonly ComputedField[]): Promise<void>;
|
|
35
|
+
/** Recomputes every stored computed field with pending triggers, in rank order, until nothing is pending (RFC 0008 §7.3). */
|
|
36
|
+
export declare function recompute(host: ComputeHost): Promise<void>;
|