@ultimat3/entity 31.9.0 → 31.10.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/CLAUDE.md +1 -0
- package/README.md +48 -0
- package/package.json +5 -5
- package/src/aggregate.ts +1 -1
- package/src/all-truncated.ts +33 -0
- package/src/append-only.ts +8 -1
- package/src/bulk-write.ts +3 -0
- package/src/counter-observed.ts +199 -0
- package/src/database.ts +4 -2
- package/src/declared-index-keys.ts +65 -0
- package/src/declared-index.ts +6 -1
- package/src/define-driver.ts +24 -2
- package/src/describe.ts +6 -0
- package/src/driver-counters.ts +21 -0
- package/src/driver-repo-reads.ts +71 -5
- package/src/driver-repo-writes.ts +23 -1
- package/src/driver-versioned-write.ts +99 -0
- package/src/entity-error.ts +4 -0
- package/src/entity-indexes.ts +118 -0
- package/src/entity.ts +20 -49
- package/src/history-purge.ts +15 -0
- package/src/index-def.ts +35 -0
- package/src/index-identity.ts +5 -0
- package/src/index-init.ts +13 -1
- package/src/index-name.ts +25 -6
- package/src/index.ts +13 -0
- package/src/latest-by-sql.ts +93 -0
- package/src/latest-by.ts +249 -0
- package/src/lock-key.ts +56 -3
- package/src/lock-unsupported.ts +5 -2
- package/src/measures.ts +157 -0
- package/src/memory-aggregates.ts +9 -16
- package/src/memory-latest-by.ts +34 -0
- package/src/memory-lock.ts +15 -1
- package/src/memory-match.ts +2 -0
- package/src/memory-measures.ts +75 -0
- package/src/memory-observed.ts +3 -1
- package/src/memory-repo.ts +17 -1
- package/src/memory-update.ts +7 -1
- package/src/pg-aggregates.ts +9 -3
- package/src/pg-bulk-repo.ts +1 -1
- package/src/pg-driver.ts +13 -1
- package/src/pg-latest-by.ts +57 -0
- package/src/pg-lock.ts +24 -4
- package/src/pg-measures.ts +64 -0
- package/src/pg-sql-aggregate.ts +9 -3
- package/src/pg-sql-measures.ts +102 -0
- package/src/pg-sql.ts +37 -6
- package/src/pg-update-many-sql.ts +44 -1
- package/src/pg-write-sql.ts +32 -4
- package/src/preload-ceiling.ts +73 -7
- package/src/preload.ts +17 -1
- package/src/query.ts +14 -1
- package/src/read-aggregates.ts +87 -3
- package/src/registry.ts +29 -0
- package/src/repo.ts +34 -1
- package/src/row-observer.ts +29 -4
- package/src/sealed-repo.ts +30 -2
- package/src/search-repo.ts +20 -2
- package/src/table-locks.ts +16 -1
- package/src/tenant-index.ts +84 -9
- package/src/text-contains.ts +53 -0
- package/src/types.ts +2 -22
- package/src/unique-constraints.ts +3 -1
- package/src/update-many-send.ts +32 -1
- package/src/update-many.ts +6 -1
- package/src/version-lock-errors.ts +42 -0
- package/src/version-lock.ts +177 -0
- package/src/write-where.ts +3 -0
package/src/pg-lock.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
// Single responsibility: `lock` and `
|
|
1
|
+
// Single responsibility: `lock`, `lockKey` and `lockKeys` on Postgres. A transaction, through the driver's own
|
|
2
2
|
// transactor, so nested in `withTransaction` it is a savepoint and the lock lives to the root COMMIT.
|
|
3
3
|
// No wait option: the bound is the role's `statement_timeout`, and a deadlock the server breaks is
|
|
4
4
|
// `X_DB_SERIALIZATION_FAILURE` through the funnel like any other statement.
|
|
5
5
|
|
|
6
|
-
import { type DbClient, type SqlFragment, sql, withStatementAttribution } from '@ultimat3/db';
|
|
6
|
+
import { type DbClient, join, type SqlFragment, sql, withStatementAttribution } from '@ultimat3/db';
|
|
7
7
|
import type { EntityCore } from './entity';
|
|
8
8
|
import { notFound } from './errors';
|
|
9
|
-
import { lockKeyInput } from './lock-key';
|
|
9
|
+
import { lockKeyInput, lockKeysInput } from './lock-key';
|
|
10
10
|
import { decodeRow, type PhysicalRow } from './pg-row';
|
|
11
11
|
import { selectStatement } from './pg-sql';
|
|
12
12
|
import { postgresTransactor } from './pg-transactor';
|
|
@@ -21,11 +21,21 @@ const lockedRow = <Row>(entity: EntityCore<Row>, plan: ReturnType<typeof idPlan>
|
|
|
21
21
|
const advisoryLock = (input: string): SqlFragment =>
|
|
22
22
|
sql`select pg_advisory_xact_lock(hashtextextended(${input}::text, 0))`;
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Every input, one round trip, in the order given: a `values` list is scanned in list order and the
|
|
26
|
+
* aggregate consumes its rows in that order, so the locks are taken in `lockKeysInput`'s sorted
|
|
27
|
+
* order — the one global order that keeps two overlapping `lockKeys` calls from deadlocking.
|
|
28
|
+
*/
|
|
29
|
+
const advisoryLocks = (inputs: readonly string[]): SqlFragment =>
|
|
30
|
+
sql`select count(pg_advisory_xact_lock(hashtextextended(k, 0))) from (values ${join(
|
|
31
|
+
inputs.map((input) => sql`(${input}::text)`),
|
|
32
|
+
)}) as held(k)`;
|
|
33
|
+
|
|
24
34
|
export const postgresLocks = <Row>(
|
|
25
35
|
entity: EntityCore<Row>,
|
|
26
36
|
pinned: DbClient | undefined,
|
|
27
37
|
client: () => DbClient,
|
|
28
|
-
): Required<Pick<Repo<Row>, 'lock' | 'lockKey'>> => ({
|
|
38
|
+
): Required<Pick<Repo<Row>, 'lock' | 'lockKey' | 'lockKeys'>> => ({
|
|
29
39
|
async lock(id, fn, options) {
|
|
30
40
|
const plan = idPlan(entity, id, options, 'lock');
|
|
31
41
|
return postgresTransactor(pinned === undefined ? {} : { client: pinned }).run(async (tx) => {
|
|
@@ -47,4 +57,14 @@ export const postgresLocks = <Row>(
|
|
|
47
57
|
return fn(tx);
|
|
48
58
|
});
|
|
49
59
|
},
|
|
60
|
+
|
|
61
|
+
async lockKeys(keys, fn, options) {
|
|
62
|
+
const inputs = lockKeysInput(entity, keys, options);
|
|
63
|
+
return postgresTransactor(pinned === undefined ? {} : { client: pinned }).run(async (tx) => {
|
|
64
|
+
await withStatementAttribution(entity.$name, 'lockKeys', () =>
|
|
65
|
+
client().query(advisoryLocks(inputs)),
|
|
66
|
+
);
|
|
67
|
+
return fn(tx);
|
|
68
|
+
});
|
|
69
|
+
},
|
|
50
70
|
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Single responsibility: the Postgres driver's `aggregates(measures)` — one statement for every
|
|
2
|
+
// measure, money's unit check included, decoded exactly as the single-column `aggregate()` decodes.
|
|
3
|
+
// The rules are `measures.ts`' and `aggregate.ts`'; this is one driver's execution of them.
|
|
4
|
+
|
|
5
|
+
import { type DbClient, withStatementAttribution } from '@ultimat3/db';
|
|
6
|
+
import { aggregateMinor, assertOneUnit, type MoneyUnit } from './aggregate';
|
|
7
|
+
import { decodeAggregate } from './aggregate-decode';
|
|
8
|
+
import type { EntityCore } from './entity';
|
|
9
|
+
import { type MeasureReads, type PlannedMeasure, planMeasures } from './measures';
|
|
10
|
+
import { measuresStatement, unitAlias, valueAlias } from './pg-sql-measures';
|
|
11
|
+
import { readPlan } from './plan';
|
|
12
|
+
|
|
13
|
+
/** `USD/6,EUR/` back into units — the encoding `pg-sql-measures.ts` writes. */
|
|
14
|
+
const unitsOf = (text: unknown): readonly MoneyUnit[] =>
|
|
15
|
+
typeof text !== 'string' || text.length === 0
|
|
16
|
+
? []
|
|
17
|
+
: text.split(',').map((one) => {
|
|
18
|
+
const [currency = '', scale = ''] = one.split('/');
|
|
19
|
+
return { currency: currency.trim(), scale: scale === '' ? null : Number(scale) };
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const decodeMeasure = <Row>(
|
|
23
|
+
entity: EntityCore<Row>,
|
|
24
|
+
measure: PlannedMeasure,
|
|
25
|
+
value: unknown,
|
|
26
|
+
units: unknown,
|
|
27
|
+
): unknown => {
|
|
28
|
+
// `count` is never null: over no rows it is 0, which is what SQL answers and what a tile shows.
|
|
29
|
+
if (measure.fn === 'count') return Number(value ?? 0);
|
|
30
|
+
if (value === null || value === undefined) return null;
|
|
31
|
+
const { fn, column, property = '' } = measure;
|
|
32
|
+
const kind = column?.$meta.kind ?? 'integer';
|
|
33
|
+
if (kind !== 'money') return decodeAggregate(fn, kind, String(value));
|
|
34
|
+
const unit = assertOneUnit(entity, fn, property, unitsOf(units));
|
|
35
|
+
if (unit === undefined) return null;
|
|
36
|
+
return {
|
|
37
|
+
minor: aggregateMinor(entity, fn, property, String(value)),
|
|
38
|
+
currency: unit.currency,
|
|
39
|
+
...(unit.scale === null ? {} : { scale: unit.scale }),
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export const postgresMeasures = <Row>(
|
|
44
|
+
entity: EntityCore<Row>,
|
|
45
|
+
client: () => DbClient,
|
|
46
|
+
): MeasureReads => ({
|
|
47
|
+
async aggregates(measures, args = {}) {
|
|
48
|
+
const op = 'aggregate';
|
|
49
|
+
const planned = planMeasures(entity, measures);
|
|
50
|
+
const plan = readPlan(entity, args, op);
|
|
51
|
+
const shape = { includeDeleted: args.includeDeleted === true };
|
|
52
|
+
const row = await withStatementAttribution(entity.$name, op, () =>
|
|
53
|
+
client().one<Readonly<Record<string, unknown>>>(
|
|
54
|
+
measuresStatement(entity, plan, shape, planned),
|
|
55
|
+
),
|
|
56
|
+
);
|
|
57
|
+
return Object.fromEntries(
|
|
58
|
+
planned.map((measure, index) => [
|
|
59
|
+
measure.name,
|
|
60
|
+
decodeMeasure(entity, measure, row?.[valueAlias(index)], row?.[unitAlias(index)]),
|
|
61
|
+
]),
|
|
62
|
+
);
|
|
63
|
+
},
|
|
64
|
+
});
|
package/src/pg-sql-aggregate.ts
CHANGED
|
@@ -8,8 +8,8 @@ import type { AggregateFn } from './aggregate';
|
|
|
8
8
|
import { AVG_SCALE } from './aggregate';
|
|
9
9
|
import { kindOf } from './cursor';
|
|
10
10
|
import type { EntityCore } from './entity';
|
|
11
|
-
import { columnRef, conditions, type ReadShape } from './pg-sql';
|
|
12
|
-
import type { QueryPlan } from './tenancy';
|
|
11
|
+
import { columnRef, conditions, predicatesSql, type ReadShape } from './pg-sql';
|
|
12
|
+
import type { Predicate, QueryPlan } from './tenancy';
|
|
13
13
|
|
|
14
14
|
/** What a grouped count comes back as. Both names are fixed, so neither can be a column's. */
|
|
15
15
|
export interface GroupRow {
|
|
@@ -33,9 +33,15 @@ export const countByStatement = <Row>(
|
|
|
33
33
|
shape: ReadShape,
|
|
34
34
|
column: string,
|
|
35
35
|
limit: number,
|
|
36
|
+
where: readonly Predicate[] = [],
|
|
36
37
|
): SqlFragment => {
|
|
37
38
|
const grouped = columnRef(entity, column);
|
|
38
|
-
|
|
39
|
+
// A filter narrows the COUNT, never the groups: a group none of its rows satisfy answers 0.
|
|
40
|
+
const counted =
|
|
41
|
+
where.length === 0
|
|
42
|
+
? sql`count(*)`
|
|
43
|
+
: sql`count(*) filter (where ${predicatesSql(entity, where)})`;
|
|
44
|
+
return sql`select ${grouped} as group_value, ${counted} as group_count from ${identifier(
|
|
39
45
|
entity.$table,
|
|
40
46
|
)} where ${conditions(entity, plan, shape)} group by ${grouped} limit ${limit}`;
|
|
41
47
|
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Single responsibility: several measures, each with its own filter, compiled to ONE statement —
|
|
2
|
+
// `count(*) filter (where …)` beside `sum(col) filter (where …)` over the chain's rows. Split from
|
|
3
|
+
// `pg-sql-aggregate.ts`; the predicates are `pg-sql.ts`'s, imported, never restated.
|
|
4
|
+
|
|
5
|
+
import { identifier, join, type SqlFragment, sql } from '@ultimat3/db';
|
|
6
|
+
import { AVG_SCALE } from './aggregate';
|
|
7
|
+
import { moneyColumns } from './column';
|
|
8
|
+
import { kindOf } from './cursor';
|
|
9
|
+
import type { EntityCore } from './entity';
|
|
10
|
+
import type { PlannedMeasure } from './measures';
|
|
11
|
+
import { columnRef, conditions, predicatesSql, type ReadShape } from './pg-sql';
|
|
12
|
+
import type { Predicate, QueryPlan } from './tenancy';
|
|
13
|
+
|
|
14
|
+
/** Output names are positional and fixed (`m0`, `u0`, …): a measure's name never reaches SQL. */
|
|
15
|
+
export const valueAlias = (index: number): string => `m${index}`;
|
|
16
|
+
export const unitAlias = (index: number): string => `u${index}`;
|
|
17
|
+
|
|
18
|
+
/** ` filter (where …)`, or nothing — an unfiltered aggregate stays the plain call. */
|
|
19
|
+
const filterOf = <Row>(
|
|
20
|
+
entity: EntityCore<Row>,
|
|
21
|
+
where: readonly Predicate[],
|
|
22
|
+
extra?: SqlFragment,
|
|
23
|
+
): SqlFragment => {
|
|
24
|
+
const parts = [
|
|
25
|
+
...(where.length === 0 ? [] : [predicatesSql(entity, where)]),
|
|
26
|
+
...(extra ? [extra] : []),
|
|
27
|
+
];
|
|
28
|
+
return parts.length === 0 ? sql`` : sql` filter (where ${join(parts, ' and ')})`;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** The aggregate over `path` with `fn`, at the precision `aggregateStatement` answers with. */
|
|
32
|
+
const measureSql = <Row>(
|
|
33
|
+
entity: EntityCore<Row>,
|
|
34
|
+
measure: PlannedMeasure,
|
|
35
|
+
path: string | undefined,
|
|
36
|
+
): SqlFragment => {
|
|
37
|
+
const filter = filterOf(entity, measure.where);
|
|
38
|
+
if (path === undefined) return sql`count(*)${filter}`;
|
|
39
|
+
const target = columnRef(entity, path);
|
|
40
|
+
switch (measure.fn) {
|
|
41
|
+
case 'count':
|
|
42
|
+
return sql`count(${target})${filter}`;
|
|
43
|
+
case 'sum':
|
|
44
|
+
return sql`sum(${target})${filter}`;
|
|
45
|
+
case 'avg':
|
|
46
|
+
return sql`round(avg(${target})${filter}, ${AVG_SCALE})`;
|
|
47
|
+
default: {
|
|
48
|
+
const extreme =
|
|
49
|
+
measure.fn === 'min' ? sql`min(${target})${filter}` : sql`max(${target})${filter}`;
|
|
50
|
+
// Epoch milliseconds, never the session's text — `aggregateStatement`'s reason, unchanged.
|
|
51
|
+
return kindOf(entity, path) === 'timestamptz'
|
|
52
|
+
? sql`(extract(epoch from ${extreme}) * 1000)`
|
|
53
|
+
: extreme;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The distinct `(currency, scale)` units a money measure covers, as `USD/` or `USD/6` joined by
|
|
60
|
+
* commas — folded into the same statement instead of `currenciesStatement`'s second one. A
|
|
61
|
+
* currency is a three-letter code and a scale an integer, so neither separator can occur in one.
|
|
62
|
+
*/
|
|
63
|
+
const unitsOf = <Row>(entity: EntityCore<Row>, measure: PlannedMeasure, property: string) => {
|
|
64
|
+
const meta = measure.column?.$meta;
|
|
65
|
+
if (meta === undefined) return sql`null`;
|
|
66
|
+
const money = moneyColumns(property, meta);
|
|
67
|
+
const currency = identifier(money.currency);
|
|
68
|
+
const scale =
|
|
69
|
+
money.scale === null ? sql`''` : sql`coalesce(${identifier(money.scale)}::text, '')`;
|
|
70
|
+
return sql`string_agg(distinct ${currency} || '/' || ${scale}, ',')${filterOf(
|
|
71
|
+
entity,
|
|
72
|
+
measure.where,
|
|
73
|
+
sql`${currency} is not null`,
|
|
74
|
+
)}`;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const isMoney = (measure: PlannedMeasure): boolean => measure.column?.$meta.kind === 'money';
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* One row: `m<i>` per measure as TEXT (decoded by the column's kind, as `aggregate()` decodes),
|
|
81
|
+
* and `u<i>` beside every money measure that sums or compares — a count of money has no unit.
|
|
82
|
+
*/
|
|
83
|
+
export const measuresStatement = <Row>(
|
|
84
|
+
entity: EntityCore<Row>,
|
|
85
|
+
plan: QueryPlan,
|
|
86
|
+
shape: ReadShape,
|
|
87
|
+
measures: readonly PlannedMeasure[],
|
|
88
|
+
): SqlFragment => {
|
|
89
|
+
const outputs = measures.flatMap((measure, index) => {
|
|
90
|
+
const property = measure.property;
|
|
91
|
+
const money = isMoney(measure);
|
|
92
|
+
const path = property === undefined ? undefined : money ? `${property}.minor` : property;
|
|
93
|
+
const value = sql`${measureSql(entity, measure, path)}::text as ${identifier(valueAlias(index))}`;
|
|
94
|
+
if (!money || measure.fn === 'count' || property === undefined) return [value];
|
|
95
|
+
return [value, sql`${unitsOf(entity, measure, property)} as ${identifier(unitAlias(index))}`];
|
|
96
|
+
});
|
|
97
|
+
return sql`select ${join(outputs)} from ${identifier(entity.$table)} where ${conditions(
|
|
98
|
+
entity,
|
|
99
|
+
plan,
|
|
100
|
+
shape,
|
|
101
|
+
)}`;
|
|
102
|
+
};
|
package/src/pg-sql.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { microsToIso, seekAlias } from './instant';
|
|
|
13
13
|
import { operatorUnknown } from './operator';
|
|
14
14
|
import { allColumns, arrayLiteral, columnsOf, physicalName } from './pg-row';
|
|
15
15
|
import type { Predicate, QueryPlan, SortKey } from './tenancy';
|
|
16
|
+
import { isTextContains, textContainsSql } from './text-contains';
|
|
16
17
|
import type { ColumnKind } from './types';
|
|
17
18
|
|
|
18
19
|
/** Nothing matches. `in ()` is a syntax error in Postgres, so an empty set needs a constant. */
|
|
@@ -122,8 +123,12 @@ const predicateSql = <Row>(entity: EntityCore<Row>, predicate: Predicate): SqlFr
|
|
|
122
123
|
// seam refuses a plain object as a parameter), an array operand as the array literal
|
|
123
124
|
// `bindValues` already builds. What is written into the statement is the operator, and the
|
|
124
125
|
// operator is chosen here from a closed set of four.
|
|
126
|
+
// On a `text()`/`char()` column `contains` is a case-insensitive substring (`text-contains.ts`),
|
|
127
|
+
// the one meaning `@>` cannot have there; on `jsonb` and arrays it stays containment.
|
|
125
128
|
case 'contains':
|
|
126
|
-
return
|
|
129
|
+
return isTextContains(kindOf(entity, predicate.column))
|
|
130
|
+
? textContainsSql(column, value)
|
|
131
|
+
: containmentSql(entity, predicate, 'contains');
|
|
127
132
|
case 'contained-by':
|
|
128
133
|
return containmentSql(entity, predicate, 'contained-by');
|
|
129
134
|
case 'overlaps':
|
|
@@ -306,6 +311,22 @@ const seekSql = <Row>(
|
|
|
306
311
|
return terms.length === 0 ? NEVER : sql`(${join(terms, ' or ')})`;
|
|
307
312
|
};
|
|
308
313
|
|
|
314
|
+
/**
|
|
315
|
+
* A list of predicates as one conjunction, `true` when there are none — a measure's own filter
|
|
316
|
+
* (`count(*) filter (where …)`) compiled by the very `predicateSql` the chain's `where` is, so a
|
|
317
|
+
* filtered aggregate and a filtered read cannot mean two things.
|
|
318
|
+
*/
|
|
319
|
+
export const predicatesSql = <Row>(
|
|
320
|
+
entity: EntityCore<Row>,
|
|
321
|
+
where: readonly Predicate[],
|
|
322
|
+
): SqlFragment =>
|
|
323
|
+
where.length === 0
|
|
324
|
+
? sql`true`
|
|
325
|
+
: join(
|
|
326
|
+
where.map((predicate) => predicateSql(entity, predicate)),
|
|
327
|
+
' and ',
|
|
328
|
+
);
|
|
329
|
+
|
|
309
330
|
export const conditions = <Row>(
|
|
310
331
|
entity: EntityCore<Row>,
|
|
311
332
|
plan: QueryPlan,
|
|
@@ -333,12 +354,22 @@ export const conditions = <Row>(
|
|
|
333
354
|
const NULLS_LAST = raw('asc nulls last');
|
|
334
355
|
const NULLS_FIRST = raw('desc nulls first');
|
|
335
356
|
|
|
336
|
-
|
|
357
|
+
/**
|
|
358
|
+
* Exported so every statement that orders rows (`latest-by-sql.ts`) writes NULL's place with these
|
|
359
|
+
* words and no copy of them. `qualifier` prefixes each column (`"L$LB"."at"`) for a statement
|
|
360
|
+
* ordering the output of a subquery.
|
|
361
|
+
*/
|
|
362
|
+
export const orderSql = <Row>(
|
|
363
|
+
entity: EntityCore<Row>,
|
|
364
|
+
orderBy: readonly SortKey[],
|
|
365
|
+
qualifier?: SqlFragment,
|
|
366
|
+
): SqlFragment =>
|
|
337
367
|
join(
|
|
338
|
-
orderBy.map(
|
|
339
|
-
(entry)
|
|
340
|
-
|
|
341
|
-
|
|
368
|
+
orderBy.map((entry) => {
|
|
369
|
+
const column = columnRef(entity, entry.column);
|
|
370
|
+
const ref = qualifier === undefined ? column : sql`${qualifier}.${column}`;
|
|
371
|
+
return sql`${ref} ${entry.direction === 'desc' ? NULLS_FIRST : NULLS_LAST}`;
|
|
372
|
+
}),
|
|
342
373
|
);
|
|
343
374
|
|
|
344
375
|
/**
|
|
@@ -16,6 +16,7 @@ import { conditions } from './pg-sql';
|
|
|
16
16
|
import { VERSION_STEP_SQL } from './pg-write-sql';
|
|
17
17
|
import { advancingVersionColumn } from './search-index-version';
|
|
18
18
|
import type { UpdateManyPlan } from './update-many';
|
|
19
|
+
import { versionOf } from './version-lock';
|
|
19
20
|
|
|
20
21
|
/**
|
|
21
22
|
* The source's column names. Upper case, which no physical column can be (`seekAlias` relies on
|
|
@@ -40,6 +41,12 @@ const versionColumn = <Row>(entity: EntityCore<Row>): string | undefined => {
|
|
|
40
41
|
return property === undefined ? undefined : physicalName(entity, property);
|
|
41
42
|
};
|
|
42
43
|
|
|
44
|
+
/** The declared lock's column, physical (`version-lock.ts`), or `undefined`. */
|
|
45
|
+
const lockColumn = <Row>(entity: EntityCore<Row>): string | undefined => {
|
|
46
|
+
const property = versionOf(entity);
|
|
47
|
+
return property === null ? undefined : physicalName(entity, property);
|
|
48
|
+
};
|
|
49
|
+
|
|
43
50
|
/** Rows per statement: what the bind budget left after the scope's own binds, over one row's width. */
|
|
44
51
|
const chunked = <T>(items: readonly T[], width: number, reserved: number): readonly T[][] => {
|
|
45
52
|
const size = Math.max(1, Math.floor((MAX_BIND_PARAMETERS - reserved) / width));
|
|
@@ -74,14 +81,23 @@ export const updateManyStatements = <Row>(
|
|
|
74
81
|
sql`${identifier(keyColumn)} as ${identifier(KEY_ALIAS)}`,
|
|
75
82
|
...columns.map((column, at) => sql`${identifier(column)} as ${identifier(aliasOf(at))}`),
|
|
76
83
|
])} from ${table} where false`;
|
|
84
|
+
// A declared lock: every row names the version it read (`updateManyPlan`), so each is matched
|
|
85
|
+
// only at that version and stored one past it — a stale row is not written, and not counted.
|
|
86
|
+
const lock = lockColumn(entity);
|
|
77
87
|
const set = join(
|
|
78
88
|
columns.map((column, at) => {
|
|
79
89
|
const next = sql`${SOURCE}.${identifier(aliasOf(at))}`;
|
|
90
|
+
if (column === lock) return sql`${identifier(column)} = ${table}.${identifier(column)} + 1`;
|
|
80
91
|
return column === version
|
|
81
92
|
? sql`${identifier(column)} = greatest(${next}, ${table}.${identifier(column)} + ${VERSION_STEP_SQL})`
|
|
82
93
|
: sql`${identifier(column)} = ${next}`;
|
|
83
94
|
}),
|
|
84
95
|
);
|
|
96
|
+
const at = lock === undefined ? -1 : columns.indexOf(lock);
|
|
97
|
+
const read =
|
|
98
|
+
at < 0 || lock === undefined
|
|
99
|
+
? sql``
|
|
100
|
+
: sql` and ${table}.${identifier(lock)} = ${SOURCE}.${identifier(aliasOf(at))}`;
|
|
85
101
|
const tail = returning ? sql` returning ${table}.*` : sql``;
|
|
86
102
|
return chunked(bound, columns.length + 1, where.values.length).map((chunk) => {
|
|
87
103
|
const legs = chunk.map(
|
|
@@ -98,6 +114,33 @@ export const updateManyStatements = <Row>(
|
|
|
98
114
|
const source = join([head, ...legs], ' union all ');
|
|
99
115
|
return sql`update ${table} set ${set} from (${source}) as ${SOURCE} where ${table}.${identifier(
|
|
100
116
|
keyColumn,
|
|
101
|
-
)} = ${SOURCE}.${identifier(KEY_ALIAS)} and ${where}${tail}`;
|
|
117
|
+
)} = ${SOURCE}.${identifier(KEY_ALIAS)} and ${where}${read}${tail}`;
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* How many of a batch's rows are live and in scope, chunked as the batch is: what a versioned
|
|
123
|
+
* `updateMany` compares its written count with, inside its transaction — present but not written
|
|
124
|
+
* is a row another write moved past the version the batch read (`X_ENTITY_STALE`).
|
|
125
|
+
*/
|
|
126
|
+
export const updateManyPresence = <Row>(
|
|
127
|
+
entity: EntityCore<Row>,
|
|
128
|
+
plan: UpdateManyPlan<Row>,
|
|
129
|
+
): readonly SqlFragment[] => {
|
|
130
|
+
const reserved = conditions(entity, plan.scope, { includeDeleted: false }).values.length;
|
|
131
|
+
return chunked(
|
|
132
|
+
plan.patches.map((each) => each.id),
|
|
133
|
+
1,
|
|
134
|
+
reserved,
|
|
135
|
+
).map((ids) => {
|
|
136
|
+
const match = {
|
|
137
|
+
...plan.scope,
|
|
138
|
+
where: [...plan.scope.where, { column: plan.key, op: 'in' as const, value: ids }],
|
|
139
|
+
};
|
|
140
|
+
return sql`select count(*)::int as ${identifier('n')} from ${identifier(entity.$table)} where ${conditions(
|
|
141
|
+
entity,
|
|
142
|
+
match,
|
|
143
|
+
{ includeDeleted: false },
|
|
144
|
+
)}`;
|
|
102
145
|
});
|
|
103
146
|
};
|
package/src/pg-write-sql.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { conditions, type ReadShape } from './pg-sql';
|
|
|
15
15
|
import { valuesList } from './pg-values-list';
|
|
16
16
|
import { advancingVersionColumn } from './search-index-version';
|
|
17
17
|
import type { QueryPlan } from './tenancy';
|
|
18
|
+
import { versionOf } from './version-lock';
|
|
18
19
|
|
|
19
20
|
/** `on conflict (…) do update set …`, or `do nothing` when there is nothing to overwrite. */
|
|
20
21
|
export interface ConflictTarget {
|
|
@@ -136,13 +137,40 @@ export const updateStatement = <Row>(
|
|
|
136
137
|
): SqlFragment => {
|
|
137
138
|
const json = jsonColumns(entity);
|
|
138
139
|
const version = advancingColumn(entity);
|
|
139
|
-
|
|
140
|
-
|
|
140
|
+
const lock = lockOf(entity, plan, values);
|
|
141
|
+
const set = [...values]
|
|
142
|
+
.filter(([column]) => column !== lock?.column)
|
|
143
|
+
.map(([column, value]) =>
|
|
141
144
|
column === version
|
|
142
145
|
? advanced(column, cell(json, column, value), identifier(column))
|
|
143
146
|
: sql`${identifier(column)} = ${cell(json, column, value)}`,
|
|
144
|
-
)
|
|
145
|
-
|
|
147
|
+
);
|
|
148
|
+
if (lock !== undefined) set.push(lock.increment);
|
|
149
|
+
return sql`update ${identifier(entity.$table)} set ${join(set)} where ${conditions(
|
|
150
|
+
entity,
|
|
151
|
+
lock?.plan ?? plan,
|
|
152
|
+
shape,
|
|
153
|
+
)}${returning ? sql` returning *` : sql``}`;
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A declared lock (`version-lock.ts`) in SQL: every UPDATE sets `"v" = "v" + 1`, and one whose
|
|
158
|
+
* values named the version is conditioned on it — `"v" = $read`, as one more predicate of the
|
|
159
|
+
* plan, so a row another write moved is simply not matched. `undefined` for an unversioned entity.
|
|
160
|
+
*/
|
|
161
|
+
const lockOf = <Row>(
|
|
162
|
+
entity: EntityCore<Row>,
|
|
163
|
+
plan: QueryPlan,
|
|
164
|
+
values: ReadonlyMap<string, unknown>,
|
|
165
|
+
): { column: string; increment: SqlFragment; plan: QueryPlan } | undefined => {
|
|
166
|
+
const property = versionOf(entity);
|
|
167
|
+
const meta = property === null ? undefined : entity.$columns[property]?.$meta;
|
|
168
|
+
if (property === null || meta === undefined) return undefined;
|
|
169
|
+
const column = columnName(property, meta);
|
|
170
|
+
const increment = sql`${identifier(column)} = ${identifier(column)} + 1`;
|
|
171
|
+
if (!values.has(column)) return { column, increment, plan };
|
|
172
|
+
const read = { column: property, op: 'eq' as const, value: values.get(column) };
|
|
173
|
+
return { column, increment, plan: { ...plan, where: [...plan.where, read] } };
|
|
146
174
|
};
|
|
147
175
|
|
|
148
176
|
/** Only reached when the entity has no soft-delete column, so there is no filter to apply. */
|
package/src/preload-ceiling.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
// Single responsibility: the bound on a preload — the ceiling a chain declares (or the default),
|
|
2
|
-
// resolved where `preload()` is called, and the refusal past it
|
|
2
|
+
// resolved where `preload()` is called, and the refusal past it — plus the per-parent bound a
|
|
3
|
+
// `hasMany` may declare (`perParent`), resolved and refused at the same place. `preload.ts` reads
|
|
4
|
+
// under both.
|
|
3
5
|
|
|
4
6
|
import { describeValue } from '@ultimat3/schema';
|
|
5
7
|
import { describeCommand, EntityError } from './errors';
|
|
6
8
|
import { MAX_PAGE_SIZE } from './plan';
|
|
7
9
|
import type { Relation } from './relations';
|
|
8
10
|
import { relationNamed } from './relations';
|
|
11
|
+
import type { SortDirection, SortKey } from './tenancy';
|
|
9
12
|
|
|
10
13
|
/**
|
|
11
14
|
* How many related rows ONE relation may attach to one page when the chain declares no ceiling of
|
|
@@ -18,10 +21,71 @@ export const MAX_PRELOADED_ROWS = MAX_PAGE_SIZE;
|
|
|
18
21
|
export interface PreloadOptions {
|
|
19
22
|
/** The ceiling for this relation on this chain. Past it the read is refused, never truncated. */
|
|
20
23
|
readonly max?: number;
|
|
24
|
+
/**
|
|
25
|
+
* A `hasMany` only: at most this many related rows per parent — "the last 3 messages of each
|
|
26
|
+
* conversation" — read for the whole page in ONE statement (`LATERAL`, `latest-by.ts`), not one
|
|
27
|
+
* `limit(n)` read per parent. Which n is `order` (a column of the related entity) in
|
|
28
|
+
* `direction` (default `desc`); unnamed, the related key descending — newest first by uuid v7.
|
|
29
|
+
*/
|
|
30
|
+
readonly perParent?: number;
|
|
31
|
+
readonly order?: string;
|
|
32
|
+
readonly direction?: SortDirection;
|
|
21
33
|
}
|
|
22
34
|
|
|
23
|
-
/**
|
|
24
|
-
export
|
|
35
|
+
/** The per-parent bound a chain declared: how many, and which ones. */
|
|
36
|
+
export interface PerParent {
|
|
37
|
+
readonly rows: number;
|
|
38
|
+
readonly order: readonly SortKey[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A relation as a chain named it: the edge, the ceiling it is read under, its per-parent bound. */
|
|
42
|
+
export type PreloadRelation = Relation & {
|
|
43
|
+
readonly max: number;
|
|
44
|
+
readonly perParent?: PerParent | undefined;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Whether a call stated anything a later call of the same relation replaces. */
|
|
48
|
+
const states = (options: PreloadOptions | undefined): boolean =>
|
|
49
|
+
options?.max !== undefined || options?.perParent !== undefined;
|
|
50
|
+
|
|
51
|
+
const perParentOf = (
|
|
52
|
+
entityName: string,
|
|
53
|
+
relation: Relation,
|
|
54
|
+
options: PreloadOptions | undefined,
|
|
55
|
+
): PerParent | undefined => {
|
|
56
|
+
const rows = options?.perParent;
|
|
57
|
+
const call = `${entityName}.preload('${relation.name}', { perParent })`;
|
|
58
|
+
const refuse = (cause: string, fix: string): EntityError =>
|
|
59
|
+
new EntityError({
|
|
60
|
+
code: 'X_INVARIANT_VIOLATED',
|
|
61
|
+
cause: `${call} — ${cause}`,
|
|
62
|
+
fix: `${describeCommand(entityName)} # ${fix}`,
|
|
63
|
+
});
|
|
64
|
+
if (rows === undefined) {
|
|
65
|
+
if (options?.order === undefined && options?.direction === undefined) return undefined;
|
|
66
|
+
throw refuse(
|
|
67
|
+
'an order without perParent names no "first n": a whole relation attaches in full',
|
|
68
|
+
`preload('${relation.name}', { perParent: <n>, order, direction }) # or drop { order, direction }: with no perParent the relation attaches in full`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
if (relation.kind !== 'hasMany') {
|
|
72
|
+
throw refuse(
|
|
73
|
+
`'${relation.name}' is a belongsTo, which attaches one row per parent already`,
|
|
74
|
+
`preload('${relation.name}') # no { perParent }: a belongsTo attaches one row per parent`,
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (!Number.isSafeInteger(rows) || rows < 1 || rows > MAX_PAGE_SIZE) {
|
|
78
|
+
throw refuse(
|
|
79
|
+
`perParent is a whole number of rows, at least 1 and at most ${MAX_PAGE_SIZE}; got ${describeValue(rows)}`,
|
|
80
|
+
`preload('${relation.name}', { perParent: 1 }) # a whole number of rows per parent, 1 to ${MAX_PAGE_SIZE}`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const order =
|
|
84
|
+
options?.order === undefined
|
|
85
|
+
? []
|
|
86
|
+
: [{ column: options.order, direction: options.direction ?? ('desc' as const) }];
|
|
87
|
+
return { rows, order };
|
|
88
|
+
};
|
|
25
89
|
|
|
26
90
|
/**
|
|
27
91
|
* The relation a `preload()` call names, resolved on the chain — an unknown name and a ceiling
|
|
@@ -41,13 +105,15 @@ export const preloadOf = (
|
|
|
41
105
|
fix: `${describeCommand(entityName)} # the entity whose chain preloads '${relation.name}': correct the { max } on that call`,
|
|
42
106
|
});
|
|
43
107
|
}
|
|
44
|
-
|
|
108
|
+
const perParent = perParentOf(entityName, relation, options);
|
|
109
|
+
return perParent === undefined ? { ...relation, max } : { ...relation, max, perParent };
|
|
45
110
|
};
|
|
46
111
|
|
|
47
112
|
/**
|
|
48
113
|
* The chain's preloads after one more `preload()` call. A relation named twice is ONE statement,
|
|
49
|
-
* and its
|
|
50
|
-
* as a second `.limit()` replaces the first; a later call that states
|
|
114
|
+
* and its bounds are one setting: a later call that STATES `max` or `perParent` replaces the
|
|
115
|
+
* earlier one whole, exactly as a second `.limit()` replaces the first; a later call that states
|
|
116
|
+
* neither leaves it. Name-only
|
|
51
117
|
* dedup kept the first and silently dropped a stricter ceiling written after it.
|
|
52
118
|
*/
|
|
53
119
|
export const preloadsWith = (
|
|
@@ -58,7 +124,7 @@ export const preloadsWith = (
|
|
|
58
124
|
): readonly PreloadRelation[] => {
|
|
59
125
|
const resolved = preloadOf(entityName, name, options);
|
|
60
126
|
if (!held.some((one) => one.name === resolved.name)) return [...held, resolved];
|
|
61
|
-
if (options
|
|
127
|
+
if (!states(options)) return held;
|
|
62
128
|
return held.map((one) => (one.name === resolved.name ? resolved : one));
|
|
63
129
|
};
|
|
64
130
|
|
package/src/preload.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { keyOf, MAX_IDS_PER_STATEMENT, statementChunks } from './batch-read';
|
|
|
11
11
|
import { valueAt } from './cursor';
|
|
12
12
|
import type { EntityCore } from './entity';
|
|
13
13
|
import { EntityError } from './errors';
|
|
14
|
+
import { latestRows } from './latest-by';
|
|
14
15
|
import { type PreloadRelation, preloadTooMany } from './preload-ceiling';
|
|
15
16
|
import type { Relation } from './relations';
|
|
16
17
|
import type { Repo } from './repo';
|
|
@@ -76,7 +77,8 @@ const tenantScope = (
|
|
|
76
77
|
* The page loop is what keeps a `hasMany` honest: a relation with more rows than one page holds
|
|
77
78
|
* costs another statement rather than silently returning the first page of them. And the ceiling
|
|
78
79
|
* is what keeps the loop finite: it asks for at most ONE row past `relation.max`, which is the
|
|
79
|
-
* row that proves the refusal, and reads nothing after it.
|
|
80
|
+
* row that proves the refusal, and reads nothing after it. A `perParent` bound is the one exception
|
|
81
|
+
* to the page loop: its rows are already bounded by keys × n, in one statement per chunk.
|
|
80
82
|
*/
|
|
81
83
|
const relatedRows = async (
|
|
82
84
|
source: string,
|
|
@@ -86,7 +88,21 @@ const relatedRows = async (
|
|
|
86
88
|
scope: readonly Predicate[],
|
|
87
89
|
): Promise<readonly unknown[]> => {
|
|
88
90
|
const rows: unknown[] = [];
|
|
91
|
+
const perParent = relation.perParent;
|
|
89
92
|
for (const chunk of statementChunks(values)) {
|
|
93
|
+
// n per parent: ONE statement per chunk however many rows each parent has (`LATERAL` on
|
|
94
|
+
// Postgres), grouped by key in the order asked — never a page loop over every child.
|
|
95
|
+
if (perParent !== undefined) {
|
|
96
|
+
const spec = {
|
|
97
|
+
group: relation.remoteKey,
|
|
98
|
+
order: perParent.order,
|
|
99
|
+
perGroup: perParent.rows,
|
|
100
|
+
keys: chunk,
|
|
101
|
+
};
|
|
102
|
+
rows.push(...(await latestRows(target.entity, target.repo, spec, { where: scope })));
|
|
103
|
+
if (rows.length > relation.max) throw preloadTooMany(source, relation);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
90
106
|
let cursor: string | null = null;
|
|
91
107
|
do {
|
|
92
108
|
const page = await target.repo.findMany({
|
package/src/query.ts
CHANGED
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
import type { Page } from '@ultimat3/core';
|
|
8
8
|
import { pageOf } from '@ultimat3/core';
|
|
9
|
+
import { reportTruncatedAll } from './all-truncated';
|
|
9
10
|
import { assertBatchable, type BatchIterator, batchIterator } from './batch';
|
|
10
11
|
import { shrinkingPages } from './batch-bytes';
|
|
11
12
|
import type { EntityCore } from './entity';
|
|
12
13
|
import { searchUndeclared } from './feature-errors';
|
|
14
|
+
import { latestByRows, type ReadLatest } from './latest-by';
|
|
13
15
|
import { checkedPredicate, type Operator } from './operator';
|
|
14
16
|
import { assertFinitePageSize, DEFAULT_PAGE_SIZE } from './plan';
|
|
15
17
|
import { preloaded, type RelatedTables } from './preload';
|
|
@@ -53,6 +55,7 @@ export type Preloaded<Name extends string> = { readonly [K in Name]: unknown };
|
|
|
53
55
|
*/
|
|
54
56
|
export interface ReadBuilder<Row, S extends SealedKeySet = NoSealedKeys>
|
|
55
57
|
extends ReadAggregates<Row, S>,
|
|
58
|
+
ReadLatest<Row, S>,
|
|
56
59
|
ChainWrites<Row> {
|
|
57
60
|
/** Equality on the columns given. `where({ orgId })` is what satisfies the tenancy guard. */
|
|
58
61
|
where(filter: RowPatch<Filterable<Row, S>>): ReadBuilder<Row, S>;
|
|
@@ -345,7 +348,13 @@ const builder = <Source, Row>(
|
|
|
345
348
|
return pageOf(await attach(result.rows), result.nextCursor);
|
|
346
349
|
},
|
|
347
350
|
|
|
348
|
-
|
|
351
|
+
// A page, never the table: when a next one existed and no `limit()` said so, dev and test hear
|
|
352
|
+
// about it (`all-truncated.ts`) — the refusal is a break and waits on `next`.
|
|
353
|
+
all: async () => {
|
|
354
|
+
const page = await repo.findMany(args());
|
|
355
|
+
reportTruncatedAll(entity.$name, page.nextCursor, state.limit !== undefined);
|
|
356
|
+
return attach(page.rows);
|
|
357
|
+
},
|
|
349
358
|
|
|
350
359
|
one: async () => {
|
|
351
360
|
const { rows } = await repo.findMany({ ...args(), limit: 1 });
|
|
@@ -355,6 +364,10 @@ const builder = <Source, Row>(
|
|
|
355
364
|
|
|
356
365
|
count: () => repo.count(args()),
|
|
357
366
|
|
|
367
|
+
// The projection and every preload apply after the per-group pick, as a page's do.
|
|
368
|
+
latestBy: async (group, options) =>
|
|
369
|
+
attach(await latestByRows(entity, repo, group, options, args())),
|
|
370
|
+
|
|
358
371
|
...chainWrites<Source, Row>(entity, repo, state),
|
|
359
372
|
|
|
360
373
|
...readAggregates(entity, repo, args),
|