@ultimat3/entity 31.8.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.
Files changed (82) hide show
  1. package/CLAUDE.md +2 -1
  2. package/README.md +78 -1
  3. package/package.json +5 -5
  4. package/src/adapter.ts +2 -2
  5. package/src/aggregate.ts +1 -1
  6. package/src/all-truncated.ts +33 -0
  7. package/src/append-only-errors.ts +2 -1
  8. package/src/append-only.ts +24 -2
  9. package/src/batch-bytes.ts +34 -0
  10. package/src/bulk-write-send.ts +38 -5
  11. package/src/bulk-write.ts +3 -0
  12. package/src/copy-plan.ts +40 -0
  13. package/src/counter-observed.ts +199 -0
  14. package/src/database.ts +4 -2
  15. package/src/declared-index-keys.ts +65 -0
  16. package/src/declared-index.ts +6 -1
  17. package/src/define-driver.ts +24 -2
  18. package/src/describe.ts +6 -0
  19. package/src/driver-counters.ts +21 -0
  20. package/src/driver-repo-reads.ts +76 -9
  21. package/src/driver-repo-writes.ts +104 -6
  22. package/src/driver-versioned-write.ts +99 -0
  23. package/src/entity-error.ts +6 -0
  24. package/src/entity-indexes.ts +118 -0
  25. package/src/entity.ts +20 -49
  26. package/src/history-purge.ts +15 -0
  27. package/src/index-def.ts +35 -0
  28. package/src/index-identity.ts +5 -0
  29. package/src/index-init.ts +13 -1
  30. package/src/index-name.ts +25 -6
  31. package/src/index.ts +19 -2
  32. package/src/latest-by-sql.ts +93 -0
  33. package/src/latest-by.ts +249 -0
  34. package/src/lock-key.ts +56 -3
  35. package/src/lock-unsupported.ts +5 -2
  36. package/src/measures.ts +157 -0
  37. package/src/memory-aggregates.ts +9 -16
  38. package/src/memory-latest-by.ts +34 -0
  39. package/src/memory-lock.ts +15 -1
  40. package/src/memory-match.ts +2 -0
  41. package/src/memory-measures.ts +75 -0
  42. package/src/memory-observed.ts +7 -1
  43. package/src/memory-repo.ts +60 -6
  44. package/src/memory-update.ts +17 -4
  45. package/src/page-bytes.ts +127 -0
  46. package/src/pg-aggregates.ts +9 -3
  47. package/src/pg-bulk-repo.ts +163 -0
  48. package/src/pg-copy.ts +87 -0
  49. package/src/pg-driver.ts +31 -72
  50. package/src/pg-latest-by.ts +57 -0
  51. package/src/pg-lock.ts +24 -4
  52. package/src/pg-measures.ts +64 -0
  53. package/src/pg-sql-aggregate.ts +9 -3
  54. package/src/pg-sql-measures.ts +102 -0
  55. package/src/pg-sql.ts +37 -6
  56. package/src/pg-update-many-sql.ts +146 -0
  57. package/src/pg-values-list.ts +55 -0
  58. package/src/pg-write-sql.ts +42 -26
  59. package/src/plan.ts +1 -56
  60. package/src/preload-ceiling.ts +73 -7
  61. package/src/preload.ts +17 -1
  62. package/src/query-write.ts +169 -0
  63. package/src/query.ts +38 -48
  64. package/src/read-aggregates.ts +87 -3
  65. package/src/registry.ts +29 -0
  66. package/src/repo.ts +74 -3
  67. package/src/row-observer.ts +68 -5
  68. package/src/sealed-repo.ts +78 -9
  69. package/src/search-mirrored-repo.ts +53 -0
  70. package/src/search-repo.ts +20 -2
  71. package/src/table-locks.ts +16 -1
  72. package/src/tenant-index.ts +84 -9
  73. package/src/text-contains.ts +53 -0
  74. package/src/type-pins.ts +9 -0
  75. package/src/types.ts +2 -22
  76. package/src/unique-constraints.ts +3 -1
  77. package/src/update-many-send.ts +97 -0
  78. package/src/update-many.ts +175 -0
  79. package/src/version-lock-errors.ts +42 -0
  80. package/src/version-lock.ts +177 -0
  81. package/src/view-repo.ts +4 -0
  82. package/src/write-where.ts +164 -0
package/src/pg-copy.ts ADDED
@@ -0,0 +1,87 @@
1
+ // Single responsibility: `copyAll`'s send on Postgres — `COPY … FROM STDIN` in chunks of at most
2
+ // `MAX_ROWS_PER_COPY` when the client can stream one, the count-only insert when it cannot. The batch arrives judged
3
+ // and bound (`pg-bulk-repo.ts`); what is decided here is only which wire carries it, so the rows
4
+ // stored are the same either way.
5
+
6
+ import {
7
+ canCopyIn,
8
+ type DbClient,
9
+ identifier,
10
+ join,
11
+ type SqlFragment,
12
+ sql,
13
+ withTransaction,
14
+ } from '@ultimat3/db';
15
+ import { countChunks } from './bulk-write-send';
16
+ import type { EntityCore } from './entity';
17
+ import { allColumns } from './pg-row';
18
+
19
+ /**
20
+ * The statement a copy streams into. Identifiers only — the entity's own table and columns — and
21
+ * no value: COPY binds nothing, which `copyIn` refuses before any send.
22
+ */
23
+ export const copyStatement = <Row>(
24
+ entity: EntityCore<Row>,
25
+ columns: readonly string[],
26
+ ): SqlFragment =>
27
+ sql`copy ${identifier(entity.$table)} (${join(columns.map(identifier))}) from stdin`;
28
+
29
+ /** Each bound row as its cells in `columns`' order — lazily, so 100k rows are never a second array. */
30
+ function* cellsOf(
31
+ bound: readonly ReadonlyMap<string, unknown>[],
32
+ columns: readonly string[],
33
+ ): Generator<readonly unknown[]> {
34
+ for (const row of bound) yield columns.map((column) => row.get(column));
35
+ }
36
+
37
+ /**
38
+ * Rows per COPY statement. One statement must stay inside the role's `statement_timeout` and the
39
+ * pool's unanswered-statement sweep, which a single COPY of an unbounded batch does not: measured
40
+ * 2026-11-11 on loopback Postgres 17 at load 20+, a 50,000-row, 12-column COPY took 0.3-0.6 s.
41
+ */
42
+ export const MAX_ROWS_PER_COPY = 50_000;
43
+
44
+ /**
45
+ * Rows stored. Each chunk is one COPY; several are one transaction — a SAVEPOINT inside an open
46
+ * one — exactly as `countChunks` holds several inserts, so the batch is all or nothing. Inside a
47
+ * caller's transaction `direct` is that transaction's own client, and its pin copies.
48
+ *
49
+ * The insert is taken instead, and stores the same rows, when COPY would not mean the same thing:
50
+ * a client with no copy stream (PGlite, a fake), row security armed (`canCopyIn`: Postgres refuses
51
+ * COPY FROM under RLS), a row that does not bind every listed column (only a cell can spell
52
+ * `default`), or no column named at all (`copy t () from stdin` is a syntax error; an insert
53
+ * writes `default` in every cell).
54
+ */
55
+ export const copyRows = async <Row>(
56
+ entity: EntityCore<Row>,
57
+ bound: readonly ReadonlyMap<string, unknown>[],
58
+ columns: readonly string[],
59
+ direct: DbClient,
60
+ pinned: DbClient | undefined,
61
+ ): Promise<number> => {
62
+ if (bound.length === 0) return 0;
63
+ const complete = columns.length > 0 && bound.every((row) => columns.every((c) => row.has(c)));
64
+ if (!complete || !canCopyIn(direct)) {
65
+ // No column named is `statementColumns`' case too: every column listed, every cell `default`.
66
+ const listed = columns.length > 0 ? columns : allColumns(entity);
67
+ return countChunks(entity, bound, { columns: listed, returning: false }, direct, pinned);
68
+ }
69
+ const target = copyStatement(entity, columns);
70
+ if (bound.length <= MAX_ROWS_PER_COPY) return direct.copyIn(target, cellsOf(bound, columns));
71
+ const chunks: (readonly ReadonlyMap<string, unknown>[])[] = [];
72
+ for (let from = 0; from < bound.length; from += MAX_ROWS_PER_COPY) {
73
+ chunks.push(bound.slice(from, from + MAX_ROWS_PER_COPY));
74
+ }
75
+ return withTransaction(
76
+ async (tx) => {
77
+ let count = 0;
78
+ for (const chunk of chunks) {
79
+ count += canCopyIn(tx)
80
+ ? await tx.copyIn(target, cellsOf(chunk, columns))
81
+ : await countChunks(entity, chunk, { columns, returning: false }, tx, undefined);
82
+ }
83
+ return count;
84
+ },
85
+ pinned === undefined ? {} : { client: pinned },
86
+ );
87
+ };
package/src/pg-driver.ts CHANGED
@@ -17,11 +17,8 @@ import {
17
17
  withStatementAttribution,
18
18
  } from '@ultimat3/db';
19
19
  import { appendOnlyRepo } from './append-only';
20
- import { conflictKeys, insertColumns, statementColumns, upsertPlan } from './bulk-write';
21
- import { writeChunks } from './bulk-write-send';
22
20
  import { entityNow } from './clock';
23
21
  import { coalesceFindById } from './coalesce';
24
- import { narrowRow } from './columns';
25
22
  import { cursorFor, seekFrom } from './cursor';
26
23
  import type { Driver } from './database';
27
24
  import { noteDriverStore } from './driver-registry';
@@ -31,22 +28,26 @@ import { stampHistoryActor } from './history-actor';
31
28
  import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
32
29
  import { forgetPreloaded, tagSiblings } from './jit-preload';
33
30
  import { judgedWrite } from './judged-write';
31
+ import { assertPageBytes } from './page-bytes';
34
32
  import { postgresAggregates } from './pg-aggregates';
33
+ import { postgresBulkWrites } from './pg-bulk-repo';
34
+ import { postgresLatestBy } from './pg-latest-by';
35
35
  import { postgresLocks } from './pg-lock';
36
36
  import { bindValues, decodeRow, type PhysicalRow, physicalName, sortPrecision } from './pg-row';
37
37
  import { countStatement, type ReadShape, selectStatement } from './pg-sql';
38
38
  import { postgresTransactor } from './pg-transactor';
39
- import { type ConflictTarget, deleteStatement, updateStatement } from './pg-write-sql';
40
- import { deletePlan, idPlan, readPlan, updatePlan } from './plan';
41
- import type { FindManyArgs, Repo, UpsertArgs } from './repo';
39
+ import { deleteStatement, updateStatement } from './pg-write-sql';
40
+ import { idPlan, readPlan } from './plan';
41
+ import type { FindManyArgs, Repo } from './repo';
42
42
  import { rowKey } from './row-key';
43
43
  import { sealedRepo } from './sealed-repo';
44
44
  import { deletionStamp } from './search-index-version';
45
45
  import { writtenRowsSink } from './search-written-rows';
46
46
  import type { QueryPlan } from './tenancy';
47
47
  import { assertRowTenant } from './tenancy';
48
- import type { RowWrite } from './types';
48
+ import { assertVersionedUpdate, staleOrNotFound, versionOf } from './version-lock';
49
49
  import { taggedWrite } from './write-tag';
50
+ import { updateWherePlan, writeWherePlan } from './write-where';
50
51
 
51
52
  export interface PostgresDriverOptions {
52
53
  /**
@@ -112,11 +113,6 @@ export const postgresRepo = <Row>(
112
113
  /** The cursor's id — `row-key.ts`, the spelling the memory driver stores a row under. */
113
114
  const idOf = (row: Row): string => rowKey(entity, row);
114
115
 
115
- /** Where a batch stops being wide — before `writeRows` or `upsertPlan` read a row. `narrowRow`
116
- * says why the position matters, and `memoryRepo` narrows at the same one. */
117
- const narrowed = (batch: readonly RowWrite<Row>[]): readonly Row[] =>
118
- batch.map((row) => narrowRow<Row>(entity.$columns, row));
119
-
120
116
  /**
121
117
  * A soft delete's SET list: the stamp, plus a searchable entity's version — advanced past the
122
118
  * stored one in the statement (`pg-write-sql.ts`), so a deletion is a newer version too.
@@ -238,39 +234,6 @@ export const postgresRepo = <Row>(
238
234
  ? judgedRows(op, plan, softDeletion(), shapeOf({}))
239
235
  : counted(op, plan, removalShape(), (returning) => removal(plan, returning));
240
236
 
241
- /**
242
- * The one insert path, for one row or ten thousand: the batch's own column list, split into as
243
- * many statements as Postgres's bind count allows, and the rows the server stored. `insert(row)`
244
- * comes through here too, so there is no second builder for the two to drift apart in. All or
245
- * nothing however many statements it takes (`bulk-write-send.ts`).
246
- */
247
- const writeRows = async (
248
- op: string,
249
- batch: readonly Row[],
250
- conflict: ConflictTarget | undefined,
251
- ): Promise<readonly Row[]> => {
252
- if (batch.length === 0) return [];
253
- // The whole batch is judged before any statement exists, tenant and invariants together, in
254
- // the same loop and for the same reason: Postgres refuses one statement as one, so a row this
255
- // actor may not write must stop the rows beside it too. `memoryRepo`'s `write` runs the same
256
- // pair — an insert builds no read plan, so this is the only place the tenant is checked.
257
- for (const row of batch) {
258
- assertRowTenant(entity.$name, entity.$tenantColumn, op, row);
259
- entity.$assert(row);
260
- }
261
- const bound = batch.map((row) => bindValues(entity, row));
262
- const shape = {
263
- columns: statementColumns(entity, batch),
264
- ...(conflict === undefined ? {} : { conflict }),
265
- };
266
- // Attributed here rather than in each of the three callers: a batch wide enough to split is
267
- // several statements sent inside this call, and every one of them belongs to the call that
268
- // asked for it — `insert`, `insertAll` or `upsertAll`, which is why the op is a parameter.
269
- return attributed(op, () =>
270
- writing(() => writeChunks(entity, bound, shape, client(), config.client)),
271
- );
272
- };
273
-
274
237
  const repo: Repo<Row> = {
275
238
  async findById(id, options) {
276
239
  const op = 'findById';
@@ -299,7 +262,10 @@ export const postgresRepo = <Row>(
299
262
  selectStatement(entity, plan, shapeOf(args, seekFrom(entity, plan)), plan.limit + 1),
300
263
  ),
301
264
  );
265
+ // Weighed raw, before a row is decoded — the PAGE, not the look-ahead row past it, or the
266
+ // `limit(n)` the refusal names would itself be refused.
302
267
  const page = found.slice(0, plan.limit);
268
+ assertPageBytes(entity, op, page);
303
269
  const rows = page.map((row) => decodeRow(entity, row));
304
270
  // What the page leaves behind: its foreign key values, so the first `findById` for any one
305
271
  // of them resolves the key for the whole page. A `for … of` loop over these rows costs one
@@ -323,35 +289,21 @@ export const postgresRepo = <Row>(
323
289
  );
324
290
  },
325
291
 
326
- async insert(values) {
327
- const row = narrowRow<Row>(entity.$columns, values);
328
- const [written] = await writeRows('insert', [row], undefined);
329
- // `returning *` is the row Postgres actually stored, defaults included. The fallback is the
330
- // NARROWED row: handing the caller's back would answer with a `bigint` minor unit.
331
- return written ?? row;
332
- },
333
-
334
- async insertAll(batch) {
335
- return writeRows('insertAll', narrowed(batch), undefined);
336
- },
337
-
338
- async upsertAll(batch, args: UpsertArgs<Row>) {
339
- const rows = narrowed(batch);
340
- const { onConflict, onMatch = 'update', overwrites } = args;
341
- const plan = upsertPlan(entity, rows, onConflict, onMatch, overwrites);
342
- // Refused here, not by the server: a batch that repeats a conflict target is `21000` in
343
- // Postgres and a silent overwrite in memory, and the two drivers have to mean one thing.
344
- conflictKeys(entity, plan, rows);
345
- return writeRows('upsertAll', rows, {
346
- columns: insertColumns(entity, plan.on),
347
- set: insertColumns(entity, plan.set),
348
- });
349
- },
292
+ ...postgresBulkWrites({
293
+ entity,
294
+ client,
295
+ pinned: config.client,
296
+ attributed,
297
+ writing,
298
+ }),
350
299
 
351
300
  async update(id, given, options) {
352
301
  // Here and in `memory-repo.ts`, the one door: a value `insert` refuses, a fragment included.
353
302
  const patch = entity.$parsePatch(given);
354
303
  const op = 'update';
304
+ // A declared version lock: the patch carries the version it read (`version-lock.ts`), and
305
+ // `updateStatement` conditions on it and increments it.
306
+ assertVersionedUpdate(entity, patch);
355
307
  const plan = idPlan(entity, id, options, op);
356
308
  // The plan bounds WHICH row is written; the patch decides what it becomes, and a patch
357
309
  // naming another tenant would hand this row away — a leak out of the actor's tenant that no
@@ -371,7 +323,13 @@ export const postgresRepo = <Row>(
371
323
  // the statement inside a transaction the refusal rolls back.
372
324
  return judged(async (send) => {
373
325
  const written = await attributed(op, () => writing(() => send.one<PhysicalRow>(statement)));
374
- if (written === null) throw notFound(entity.$name, id);
326
+ if (written === null) {
327
+ // No row matched: absent, another tenant's, or (versioned) moved past the read version.
328
+ if (versionOf(entity) === null) throw notFound(entity.$name, id);
329
+ throw await staleOrNotFound(entity, id, patch, () =>
330
+ attributed(op, () => one(idPlan(entity, id, options, op), options ?? {})),
331
+ );
332
+ }
375
333
  const after = decodeRow(entity, written);
376
334
  entity.$assert(after);
377
335
  return after;
@@ -397,14 +355,14 @@ export const postgresRepo = <Row>(
397
355
  async deleteWhere(filter, options) {
398
356
  const op = 'deleteWhere';
399
357
  // The plan is built before the write is announced: a refused filter never happened.
400
- const plan = deletePlan(entity, filter, options, op);
358
+ const plan = writeWherePlan(entity, filter, options, op);
401
359
  return removed(op, plan);
402
360
  },
403
361
 
404
362
  async updateWhere(filter, given, options) {
405
363
  const patch = entity.$parsePatch(given);
406
364
  const op = 'updateWhere';
407
- const plan = updatePlan(entity, filter, patch, options, op);
365
+ const plan = updateWherePlan(entity, filter, patch, options, op);
408
366
  // The same move, filtered: one statement can hand away every row it matches.
409
367
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
410
368
  const values = bindValues(entity, patch);
@@ -436,6 +394,7 @@ export const postgresRepo = <Row>(
436
394
  },
437
395
 
438
396
  ...postgresAggregates(entity, client),
397
+ ...postgresLatestBy(entity, client),
439
398
  ...postgresLocks(entity, config.client, client),
440
399
  };
441
400
  // The one sealing seam, shared with `memoryRepo()`: sealed on the way in, opened on the way out.
@@ -0,0 +1,57 @@
1
+ // Single responsibility: the Postgres driver's `latestBy` — one statement per call (per 500 keys
2
+ // for a preload's parents), weighed and decoded as a page is. What the statement means is
3
+ // `latest-by.ts`'s; how it is spelled is `latest-by-sql.ts`'s. `pg-driver.ts` spreads this in.
4
+
5
+ import { type DbClient, withStatementAttribution } from '@ultimat3/db';
6
+ import { statementChunks } from './batch-read';
7
+ import type { EntityCore } from './entity';
8
+ import { assertGroupBound, type LatestBySpec, latestPlanOf, MAX_LATEST_GROUPS } from './latest-by';
9
+ import { distinctOnStatement, lateralStatement } from './latest-by-sql';
10
+ import { assertPageBytes } from './page-bytes';
11
+ import { decodeRow, type PhysicalRow } from './pg-row';
12
+ import type { FindManyArgs } from './repo';
13
+
14
+ export interface LatestByRead<Row> {
15
+ latestBy(spec: LatestBySpec, args?: FindManyArgs): Promise<readonly Row[]>;
16
+ }
17
+
18
+ export const postgresLatestBy = <Row>(
19
+ entity: EntityCore<Row>,
20
+ client: () => DbClient,
21
+ ): LatestByRead<Row> => ({
22
+ async latestBy(spec, args = {}) {
23
+ const op = 'latestBy';
24
+ const shape = { includeDeleted: args.includeDeleted === true };
25
+ const send = (statement: ReturnType<typeof distinctOnStatement>) =>
26
+ withStatementAttribution(entity.$name, op, () => client().query<PhysicalRow>(statement));
27
+ const keys = spec.keys;
28
+ let found: readonly PhysicalRow[];
29
+ if (keys === undefined) {
30
+ const plan = latestPlanOf(entity, spec, args, op);
31
+ found = await send(distinctOnStatement(entity, plan, shape, MAX_LATEST_GROUPS + 1));
32
+ // One group per row here, so the row count IS the group count.
33
+ assertGroupBound(entity, spec, found.length);
34
+ } else {
35
+ // Null is no parent (`preload.ts` drops it); an empty list sends nothing.
36
+ const present = keys.filter((key) => key !== null && key !== undefined);
37
+ // Judged even with nothing to send, so a refusal does not depend on the page being empty.
38
+ if (present.length === 0) {
39
+ latestPlanOf(entity, spec, args, op);
40
+ return [];
41
+ }
42
+ // Planned per chunk: the plan's `in` carries the chunk's keys, never the whole list.
43
+ const plans = statementChunks(present).map((chunk) => ({
44
+ chunk,
45
+ plan: latestPlanOf(entity, { ...spec, keys: chunk }, args, op),
46
+ }));
47
+ const pages: PhysicalRow[] = [];
48
+ for (const { chunk, plan } of plans) {
49
+ pages.push(...(await send(lateralStatement(entity, plan, shape, chunk, spec.perGroup))));
50
+ }
51
+ found = pages;
52
+ }
53
+ // Weighed raw, before a row is decoded, as `findMany` weighs its page.
54
+ assertPageBytes(entity, op, found);
55
+ return found.map((row) => decodeRow(entity, row));
56
+ },
57
+ });
package/src/pg-lock.ts CHANGED
@@ -1,12 +1,12 @@
1
- // Single responsibility: `lock` and `lockKey` on Postgres. A transaction, through the driver's own
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
+ });
@@ -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
- return sql`select ${grouped} as group_value, count(*) as group_count from ${identifier(
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 containmentSql(entity, predicate, 'contains');
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
- const orderSql = <Row>(entity: EntityCore<Row>, orderBy: readonly SortKey[]): SqlFragment =>
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
- sql`${columnRef(entity, entry.column)} ${entry.direction === 'desc' ? NULLS_FIRST : NULLS_LAST}`,
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
  /**