@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.
Files changed (69) hide show
  1. package/CLAUDE.md +1 -0
  2. package/README.md +48 -0
  3. package/package.json +5 -5
  4. package/src/aggregate.ts +1 -1
  5. package/src/all-truncated.ts +33 -0
  6. package/src/append-only.ts +8 -1
  7. package/src/bulk-write.ts +3 -0
  8. package/src/counter-observed.ts +199 -0
  9. package/src/database.ts +4 -2
  10. package/src/declared-index-keys.ts +65 -0
  11. package/src/declared-index.ts +6 -1
  12. package/src/define-driver.ts +24 -2
  13. package/src/describe.ts +6 -0
  14. package/src/driver-counters.ts +21 -0
  15. package/src/driver-repo-reads.ts +71 -5
  16. package/src/driver-repo-writes.ts +23 -1
  17. package/src/driver-versioned-write.ts +99 -0
  18. package/src/entity-error.ts +4 -0
  19. package/src/entity-indexes.ts +118 -0
  20. package/src/entity.ts +20 -49
  21. package/src/history-purge.ts +15 -0
  22. package/src/index-def.ts +35 -0
  23. package/src/index-identity.ts +5 -0
  24. package/src/index-init.ts +13 -1
  25. package/src/index-name.ts +25 -6
  26. package/src/index.ts +13 -0
  27. package/src/latest-by-sql.ts +93 -0
  28. package/src/latest-by.ts +249 -0
  29. package/src/lock-key.ts +56 -3
  30. package/src/lock-unsupported.ts +5 -2
  31. package/src/measures.ts +157 -0
  32. package/src/memory-aggregates.ts +9 -16
  33. package/src/memory-latest-by.ts +34 -0
  34. package/src/memory-lock.ts +15 -1
  35. package/src/memory-match.ts +2 -0
  36. package/src/memory-measures.ts +75 -0
  37. package/src/memory-observed.ts +3 -1
  38. package/src/memory-repo.ts +17 -1
  39. package/src/memory-update.ts +7 -1
  40. package/src/pg-aggregates.ts +9 -3
  41. package/src/pg-bulk-repo.ts +1 -1
  42. package/src/pg-driver.ts +13 -1
  43. package/src/pg-latest-by.ts +57 -0
  44. package/src/pg-lock.ts +24 -4
  45. package/src/pg-measures.ts +64 -0
  46. package/src/pg-sql-aggregate.ts +9 -3
  47. package/src/pg-sql-measures.ts +102 -0
  48. package/src/pg-sql.ts +37 -6
  49. package/src/pg-update-many-sql.ts +44 -1
  50. package/src/pg-write-sql.ts +32 -4
  51. package/src/preload-ceiling.ts +73 -7
  52. package/src/preload.ts +17 -1
  53. package/src/query.ts +14 -1
  54. package/src/read-aggregates.ts +87 -3
  55. package/src/registry.ts +29 -0
  56. package/src/repo.ts +34 -1
  57. package/src/row-observer.ts +29 -4
  58. package/src/sealed-repo.ts +30 -2
  59. package/src/search-repo.ts +20 -2
  60. package/src/table-locks.ts +16 -1
  61. package/src/tenant-index.ts +84 -9
  62. package/src/text-contains.ts +53 -0
  63. package/src/types.ts +2 -22
  64. package/src/unique-constraints.ts +3 -1
  65. package/src/update-many-send.ts +32 -1
  66. package/src/update-many.ts +6 -1
  67. package/src/version-lock-errors.ts +42 -0
  68. package/src/version-lock.ts +177 -0
  69. package/src/write-where.ts +3 -0
@@ -8,15 +8,24 @@ import { countsFrom, groupColumnOf } from './count-by';
8
8
  import { cursorFor, seekFrom } from './cursor';
9
9
  import { projectRow } from './driver-rows';
10
10
  import type { DriverScope } from './driver-scope';
11
+ import { planMeasures, screenMeasureFilter } from './measures';
11
12
  import { assertPageBytes } from './page-bytes';
12
13
  import { idPlan, readPlan, singleKeyOf } from './plan';
13
14
  import type { Repo } from './repo';
14
15
  import { rowKey } from './row-key';
16
+ import type { Predicate } from './tenancy';
15
17
  import { seriesPlanOf } from './time-bucket';
16
18
 
17
19
  export type DriverReads<Row> = Pick<
18
20
  Repo<Row>,
19
- 'findById' | 'findMany' | 'count' | 'countBy' | 'aggregate' | 'approximateCount' | 'series'
21
+ | 'findById'
22
+ | 'findMany'
23
+ | 'count'
24
+ | 'countBy'
25
+ | 'aggregate'
26
+ | 'aggregates'
27
+ | 'approximateCount'
28
+ | 'series'
20
29
  >;
21
30
 
22
31
  export const driverReads = <Row>(scope: DriverScope<Row>): DriverReads<Row> => {
@@ -63,13 +72,70 @@ export const driverReads = <Row>(scope: DriverScope<Row>): DriverReads<Row> => {
63
72
  return raw.count({ plan, tx: scope.txOf(op, args) });
64
73
  },
65
74
 
66
- async countBy(column, args = {}) {
75
+ /**
76
+ * With `where`, two store calls over the one capability a store already declares: every group
77
+ * the chain matches, then the groups' counts with the filter ANDed in — a group the filter
78
+ * empties answers `0`, as `count(*) filter (where …)` does. No new store contract to forget.
79
+ */
80
+ async countBy(column, args = {}, options) {
67
81
  const op = 'countBy';
68
82
  groupColumnOf(entity, column, op);
69
83
  scope.need(op, 'aggregate:countBy');
70
- const plan = scope.storePlan(op, readPlan(entity, args, op), args.includeDeleted);
71
- const groups = await raw.countBy?.(column, { plan, tx: scope.txOf(op, args) });
72
- return countsFrom(entity, column, op, groups ?? []);
84
+ const tx = scope.txOf(op, args);
85
+ const planOf = (where: readonly Predicate[]) =>
86
+ scope.storePlan(op, readPlan(entity, { ...args, where }, op), args.includeDeleted);
87
+ const groups = await raw.countBy?.(column, { plan: planOf(args.where ?? []), tx });
88
+ const all = countsFrom(entity, column, op, groups ?? []);
89
+ const filter = options?.where;
90
+ if (filter === undefined || filter.length === 0) return all;
91
+ const where = [...(args.where ?? []), ...screenMeasureFilter(entity, filter)];
92
+ const hit = countsFrom(
93
+ entity,
94
+ column,
95
+ op,
96
+ (await raw.countBy?.(column, { plan: planOf(where), tx })) ?? [],
97
+ );
98
+ // Re-ordered by the FILTERED count, as memory's `countsFrom` pass orders its pairs.
99
+ return countsFrom(
100
+ entity,
101
+ column,
102
+ op,
103
+ [...all.keys()].map((key) => [key, hit.get(key) ?? 0] as const),
104
+ );
105
+ },
106
+
107
+ /**
108
+ * Every measure as the store call its function already is — `count` through `count`, the rest
109
+ * through `aggregate` under its own `aggregate:<fn>` capability — each with its filter ANDed
110
+ * into the plan. Several store calls, never one statement: a store has no select list.
111
+ */
112
+ async aggregates(measures, args = {}) {
113
+ const op = 'aggregates';
114
+ const planned = planMeasures(entity, measures);
115
+ const tx = scope.txOf(op, args);
116
+ const answer: Record<string, unknown> = {};
117
+ for (const measure of planned) {
118
+ const where = [
119
+ ...(args.where ?? []),
120
+ ...measure.where,
121
+ ...(measure.fn === 'count' && measure.property !== undefined
122
+ ? [{ column: measure.property, op: 'is-not-null' as const }]
123
+ : []),
124
+ ];
125
+ const plan = scope.storePlan(
126
+ op,
127
+ readPlan(entity, { ...args, where }, op),
128
+ args.includeDeleted,
129
+ );
130
+ if (measure.fn === 'count') {
131
+ answer[measure.name] = await raw.count({ plan, tx });
132
+ continue;
133
+ }
134
+ scope.need(measure.fn, `aggregate:${measure.fn}`);
135
+ answer[measure.name] =
136
+ (await raw.aggregate?.(measure.fn, measure.property ?? '', { plan, tx })) ?? null;
137
+ }
138
+ return answer;
73
139
  },
74
140
 
75
141
  async aggregate(fn, column, args = {}) {
@@ -11,6 +11,7 @@ import { copyColumns } from './copy-plan';
11
11
  import { kindOf, valueAt } from './cursor';
12
12
  import { byKeys, checkedDelete } from './driver-delete';
13
13
  import type { DriverScope } from './driver-scope';
14
+ import { versionedWrites } from './driver-versioned-write';
14
15
  import {
15
16
  assertWrittenInScope,
16
17
  sameTenantProperties,
@@ -28,6 +29,7 @@ import { writtenRowsSink } from './search-written-rows';
28
29
  import { assertRowTenant, type QueryPlan } from './tenancy';
29
30
  import type { RowPatch, RowWrite } from './types';
30
31
  import { judgeUpdateMany, updateManyPlan } from './update-many';
32
+ import { assertVersionedUpdate, versionOf } from './version-lock';
31
33
  import { updateWherePlan, writeWherePlan } from './write-where';
32
34
 
33
35
  export type DriverWrites<Row> = Pick<
@@ -110,7 +112,10 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
110
112
  entity.$columns,
111
113
  Object.fromEntries(namedColumns(patch)),
112
114
  );
113
- if (entity.$invariants.length === 0 && !movesReference) {
115
+ // A declared version lock is per row (`v = stored + 1`), which one store patch cannot say: the
116
+ // judged path below, one write per row (`driver-versioned-write.ts`).
117
+ const lock = versionOf(entity);
118
+ if (entity.$invariants.length === 0 && !movesReference && lock === null) {
114
119
  // The search mirror asked for the rows: read them first, as the judged path does. Past the
115
120
  // judged bound they are not handed over — the mirror logs the write it could not name.
116
121
  const before =
@@ -142,6 +147,22 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
142
147
  entity.$assert(merged);
143
148
  }
144
149
  await references(results);
150
+ if (lock !== null) {
151
+ const written = await versionedWrites(scope, {
152
+ op,
153
+ plan,
154
+ patch,
155
+ lock,
156
+ found,
157
+ results,
158
+ advance,
159
+ narrowed,
160
+ tx,
161
+ references,
162
+ });
163
+ if (sink !== undefined) sink(await writtenBack(op, plan, found, tx));
164
+ return written;
165
+ }
145
166
  // The narrowed values the merge produced — the same for every row — so the store holds what
146
167
  // was judged rather than a money `bigint` the row type never carries. The version is the
147
168
  // patch's instant: the store advances it per row.
@@ -204,6 +225,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
204
225
  refuseAbandoned();
205
226
  const op = 'update';
206
227
  const patch = entity.$parsePatch(given);
228
+ assertVersionedUpdate(entity, patch);
207
229
  const plan = scope.storePlan(op, idPlan(entity, id, options, op));
208
230
  assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
209
231
  if (namedColumns(patch).length > 0 && (await patched(op, plan, patch, options)) === 0) {
@@ -0,0 +1,99 @@
1
+ // Single responsibility: a `defineDriver` write of a versioned entity, one store call per row since
2
+ // `v = stored + 1` is per row. `update(id)`/`updateMany` name the version and compare-and-set on
3
+ // it; a filtered write names none and, like Postgres's `set v = v + 1`, never answers stale.
4
+
5
+ import { valueAt } from './cursor';
6
+ import type { DriverAdvance } from './driver-kit-types';
7
+ import type { DriverScope } from './driver-scope';
8
+ import { mergedRow } from './memory-update';
9
+ import { namedColumns } from './plan';
10
+ import type { Tx } from './repo';
11
+ import { rowKey } from './row-key';
12
+ import { assertRowTenant, type QueryPlan } from './tenancy';
13
+ import { entityStale } from './version-lock-errors';
14
+
15
+ /**
16
+ * How many times a filtered write re-reads one row a concurrent writer keeps moving. Each miss is
17
+ * another writer's progress; the bound only stops a store whose conditioned update never matches.
18
+ */
19
+ export const MAX_VERSION_RETRIES = 16;
20
+
21
+ export interface VersionedWrite<Row> {
22
+ readonly op: string;
23
+ readonly plan: QueryPlan;
24
+ readonly patch: object;
25
+ /** The version property (`versionOf(entity)`). */
26
+ readonly lock: string;
27
+ /** The rows the plan matched, as read, each with the row the patch made of it. */
28
+ readonly found: readonly Row[];
29
+ readonly results: readonly Row[];
30
+ readonly advance: DriverAdvance | undefined;
31
+ readonly narrowed: Readonly<Record<string, unknown>>;
32
+ readonly tx: Tx | undefined;
33
+ /** Same-tenant references of a re-merged row, judged as the batch was. */
34
+ readonly references: (rows: readonly Row[]) => Promise<void>;
35
+ }
36
+
37
+ /**
38
+ * Writes every row conditioned on the version it was READ at. A miss is `X_ENTITY_STALE` when the
39
+ * patch named the version; otherwise the row is re-read under the same plan — gone or out of the
40
+ * filter is skipped, as Postgres re-checks the WHERE on the newer row — re-merged, re-judged and
41
+ * written again at ITS version, so neither increment is lost. Answers how many rows were written.
42
+ */
43
+ export const versionedWrites = async <Row>(
44
+ scope: DriverScope<Row>,
45
+ write: VersionedWrite<Row>,
46
+ ): Promise<number> => {
47
+ const { entity, raw } = scope;
48
+ const { op, plan, patch, lock, advance, narrowed, tx } = write;
49
+ const checks = namedColumns(patch).some(([key]) => key === lock);
50
+ const keyed = (row: Row, withVersion: boolean): QueryPlan => ({
51
+ ...plan,
52
+ where: [
53
+ ...plan.where,
54
+ ...entity.$primaryKey.map((key) => ({
55
+ column: key,
56
+ op: 'eq' as const,
57
+ value: valueAt(row, key),
58
+ })),
59
+ ...(withVersion ? [{ column: lock, op: 'eq' as const, value: valueAt(row, lock) }] : []),
60
+ ],
61
+ });
62
+ // The narrowed values the merge produced, so the store holds what was judged; the version is
63
+ // one past the read row's, and a searchable version the patch's instant the store advances.
64
+ const valuesOf = (result: Row): Record<string, unknown> => {
65
+ const merged = result as Readonly<Record<string, unknown>>;
66
+ const values = Object.fromEntries(namedColumns(patch).map(([key]) => [key, merged[key]]));
67
+ values[lock] = merged[lock];
68
+ if (advance !== undefined) values[advance.property] = narrowed[advance.property];
69
+ return values;
70
+ };
71
+ const stale = (row: Row) =>
72
+ entityStale(entity.$name, lock, rowKey(entity, row), valueAt(row, lock), undefined);
73
+ let written = 0;
74
+ for (const [at, first] of write.found.entries()) {
75
+ let read = first;
76
+ let result = write.results[at] as Row;
77
+ for (let attempt = 0; ; attempt += 1) {
78
+ const count = await raw.update({ plan: keyed(read, true), tx }, valuesOf(result), advance);
79
+ if (count > 0) {
80
+ written += count;
81
+ break;
82
+ }
83
+ if (checks || attempt >= MAX_VERSION_RETRIES) throw stale(read);
84
+ const again = keyed(read, false);
85
+ const [fresh] = scope.checked(
86
+ op,
87
+ again,
88
+ await raw.select({ plan: again, after: undefined, limit: 1, tx }),
89
+ );
90
+ if (fresh === undefined) break;
91
+ read = fresh;
92
+ result = mergedRow(entity, fresh, patch);
93
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, result);
94
+ entity.$assert(result);
95
+ await write.references([result]);
96
+ }
97
+ }
98
+ return written;
99
+ };
@@ -54,6 +54,8 @@ export const ENTITY_ERROR_CODES = [
54
54
  'X_DRIVER_ROW_OUT_OF_SCOPE',
55
55
  'X_ENTITY_PARTITION_INVALID',
56
56
  'X_ENTITY_PAGE_TOO_LARGE',
57
+ 'X_ENTITY_STALE',
58
+ 'X_ENTITY_VERSION_INVALID',
57
59
  ] as const;
58
60
 
59
61
  export type EntityErrorCode = (typeof ENTITY_ERROR_CODES)[number];
@@ -105,6 +107,8 @@ export const ENTITY_ERROR_TITLES: Readonly<Record<EntityErrorCode, string>> = {
105
107
  X_ENTITY_PARTITION_INVALID:
106
108
  'entity({ partitionBy }) declares a partitioning Postgres cannot build',
107
109
  X_ENTITY_PAGE_TOO_LARGE: 'a page weighed more than the page byte bound before it was decoded',
110
+ X_ENTITY_STALE: "the row's version moved since this write read it",
111
+ X_ENTITY_VERSION_INVALID: 'a write or declaration breaks the declared version lock',
108
112
  };
109
113
 
110
114
  // Registered at module load, unconditionally, in one call. Without this the registry humanises the
@@ -0,0 +1,118 @@
1
+ // Every index one `entity()` holds — each column's own, the `indexes:` entries, the search gin, the
2
+ // tenant index — and which implicit ones another already serves. Split out of `entity.ts` at the
3
+ // 500-line ceiling: the assembly is one job, and E9's covering rule is judged here, once.
4
+
5
+ import type { IndexMethod } from '@ultimat3/db';
6
+ import { columnName, moneyColumns } from './column';
7
+ import { declaredIndexOf } from './declared-index';
8
+ import type { InvariantColumns, Resolve } from './expr';
9
+ import { distinctIndexes } from './index-identity';
10
+ import type { IndexInit } from './index-init';
11
+ import { indexName } from './index-name';
12
+ import type { Invariant } from './invariants';
13
+ import type { CoveredIndex } from './registry';
14
+ import type { SearchVector } from './search';
15
+ import {
16
+ coveredByTenantIndex,
17
+ coveredImplicitIndexes,
18
+ coverersOf,
19
+ tenantIndexOf,
20
+ } from './tenant-index';
21
+ import type { AnyColumn, ColumnMap, IndexDef } from './types';
22
+
23
+ export interface EntityIndexesInput<C extends ColumnMap, Row> {
24
+ readonly name: string;
25
+ readonly table: string;
26
+ readonly entries: readonly (readonly [string, AnyColumn])[];
27
+ readonly declared: readonly IndexInit<C>[] | undefined;
28
+ readonly resolve: Resolve;
29
+ readonly columns: InvariantColumns<C>;
30
+ readonly search: SearchVector | null;
31
+ /** The tenant column's PHYSICAL name, `null` on an untenanted table. */
32
+ readonly tenant: string | null;
33
+ /** The primary key's physical columns, in declared order. */
34
+ readonly primaryKey: readonly string[];
35
+ readonly plainView: boolean;
36
+ readonly invariants: readonly Invariant<Row>[];
37
+ }
38
+
39
+ export interface EntityIndexes {
40
+ /** Deduplicated, in declaration order, the tenant index last. */
41
+ readonly indexes: readonly IndexDef[];
42
+ /** The tenant index, when one was added — `withoutDerivedDuplicate` reads it at describe time. */
43
+ readonly tenantIndex: IndexDef | undefined;
44
+ readonly covered: readonly CoveredIndex[];
45
+ }
46
+
47
+ /** Each column's own index: `.unique()`, `.index()`, `.references()`, `.tenant()`. */
48
+ const columnIndexes = (
49
+ name: string,
50
+ table: string,
51
+ entries: readonly (readonly [string, AnyColumn])[],
52
+ tenant: string | null,
53
+ ): readonly IndexDef[] =>
54
+ entries.flatMap(([property, column]) => {
55
+ const meta = column.$meta;
56
+ if (!meta.unique && !meta.index) return [];
57
+ const physical = [
58
+ meta.kind === 'money' ? moneyColumns(property, meta).minor : columnName(property, meta),
59
+ ];
60
+ if (coveredByTenantIndex(physical[0] ?? '', tenant, meta.unique)) return [];
61
+ return [
62
+ {
63
+ name: indexName(name, table, physical, meta.unique),
64
+ columns: physical,
65
+ unique: meta.unique,
66
+ },
67
+ ];
68
+ });
69
+
70
+ export const entityIndexesOf = <C extends ColumnMap, Row>(
71
+ input: EntityIndexesInput<C, Row>,
72
+ ): EntityIndexes => {
73
+ const { name, table, search } = input;
74
+ const own = columnIndexes(name, table, input.entries, input.tenant);
75
+ const written = (input.declared ?? []).map((index) =>
76
+ declaredIndexOf(index, { name, table, resolve: input.resolve, columns: input.columns }),
77
+ );
78
+ const declared: readonly IndexDef[] = [
79
+ ...own,
80
+ ...written,
81
+ // The one index nobody declared and every search needs. Through the SAME `IndexInit` path a
82
+ // hand-written `using: 'gin'` takes — `indexName` gives it the method discriminator, so it can
83
+ // never collide with a btree an author declares on the same column.
84
+ ...(search === null
85
+ ? []
86
+ : [
87
+ {
88
+ name: indexName(name, table, [search.column], false, undefined, null, 'gin'),
89
+ columns: [search.column],
90
+ unique: false,
91
+ using: 'gin' as IndexMethod,
92
+ },
93
+ ]),
94
+ ];
95
+ const uniques = input.invariants.filter((inv) => inv.kind === 'unique');
96
+ const { primaryKey } = input;
97
+ // After every other index, so one that already starts with `(tenant, pk)` is seen.
98
+ const [tenantIndex] = tenantIndexOf({
99
+ entityName: name,
100
+ table,
101
+ tenant: input.tenant,
102
+ primaryKey,
103
+ plainView: input.plainView,
104
+ covering: coverersOf(table, primaryKey, declared, uniques),
105
+ });
106
+ // A foreign key's own index named again in `indexes` is one index, not two (`index-identity.ts`).
107
+ const indexes = distinctIndexes(
108
+ tenantIndex === undefined ? declared : [...declared, tenantIndex],
109
+ );
110
+ // Implicit: a column's own non-unique index the author did not also write in `indexes:` — one
111
+ // they wrote is theirs to keep. A unique one is a rule, never an access path to drop.
112
+ const handWritten = new Set(written.map((index) => index.name));
113
+ const implicit = own.filter((index) => !index.unique && !handWritten.has(index.name));
114
+ const covered = input.plainView
115
+ ? []
116
+ : coveredImplicitIndexes(implicit, coverersOf(table, primaryKey, indexes, uniques));
117
+ return { indexes, tenantIndex, covered };
118
+ };
package/src/entity.ts CHANGED
@@ -3,11 +3,9 @@
3
3
  // (the typed db handle, migrations, cache tags, the admin UI, the manifest) is projected from
4
4
  // this one call.
5
5
 
6
- import type { IndexMethod } from '@ultimat3/db';
7
6
  import type { Schema } from '@ultimat3/schema';
8
7
  import { assertAppendOnlyColumns } from './append-only';
9
8
  import { assertTableName, bindColumn, columnName, moneyColumns } from './column';
10
- import { declaredIndexOf } from './declared-index';
11
9
  import {
12
10
  assertNotRetired,
13
11
  assertScan,
@@ -15,15 +13,14 @@ import {
15
13
  describeEntity,
16
14
  describeReferences,
17
15
  } from './describe';
16
+ import { entityIndexesOf } from './entity-indexes';
18
17
  import { rowParsers } from './entity-parse';
19
18
  import { parseEntityPatch } from './entity-patch';
20
19
  import { invariantViolated } from './errors';
21
20
  import type { InvariantColumns, Resolve } from './expr';
22
21
  import { invariantColumns } from './expr';
23
22
  import type { HistoryEntity, HistoryInit } from './history';
24
- import { distinctIndexes } from './index-identity';
25
23
  import type { IndexInit } from './index-init';
26
- import { indexName } from './index-name';
27
24
  import type { Invariant, InvariantDef } from './invariants';
28
25
  import { assertInvariants, bindInvariant } from './invariants';
29
26
  import { describeLifecycle, lifecycleHistory } from './lifecycle';
@@ -40,8 +37,9 @@ import { sealedInView } from './sealed-errors';
40
37
  import type { SearchInit, SearchSource, SearchVector } from './search';
41
38
  import { searchVectorOf } from './search';
42
39
  import { resolveTenantColumn } from './tenancy';
43
- import { coveredByTenantIndex, tenantIndexOf, withoutDerivedDuplicate } from './tenant-index';
40
+ import { withoutDerivedDuplicate } from './tenant-index';
44
41
  import type { AnyColumn, ColumnMap, IndexDef, RowOf, WireRow } from './types';
42
+ import { versionColumnOf } from './version-lock';
45
43
  import type { EntityView } from './view';
46
44
  import { viewFor } from './view';
47
45
  import { type ViewInit, type ViewQuery, viewQueryOf } from './view-entity';
@@ -65,6 +63,11 @@ export interface EntityInit<C extends ColumnMap> {
65
63
  * `orgId`, so silence never means unscoped.
66
64
  */
67
65
  readonly tenant?: keyof C & string;
66
+ /**
67
+ * The optimistic lock: an `integer().default(0)` column every update increments, and that
68
+ * `update(id, patch)` must name at the value it read — a row moved since is `X_ENTITY_STALE`.
69
+ */
70
+ readonly version?: keyof C & string;
68
71
  /**
69
72
  * Why an entity with no tenant column, referencing a tenant-owned one, belongs to no tenant.
70
73
  * Without it `x verify`'s exercise step reports `X_ENTITY_TENANT_UNDECLARED`; blank is refused.
@@ -168,6 +171,8 @@ export interface EntityCore<Row = unknown, C extends ColumnMap = ColumnMap> {
168
171
  readonly $readOnly: string | null;
169
172
  /** Property key of the tenant column, or `null`. Presence is what turns tenancy on. */
170
173
  readonly $tenantColumn: string | null;
174
+ /** The declared optimistic-lock property (`version-lock.ts`), or `null`. */
175
+ readonly $version: string | null;
171
176
  /**
172
177
  * The generated `tsvector` this entity's `.searchable()` columns derive, or `null` when none is.
173
178
  * Presence is what makes `.search(text)` legal — both drivers read it, and neither invents one.
@@ -309,56 +314,20 @@ export const entity = <const C extends ColumnMap>(
309
314
  bindInvariant<Row>(def, resolve, partialWhere),
310
315
  );
311
316
 
312
- const declared: readonly IndexDef[] = [
313
- ...entries.flatMap(([property, column]) => {
314
- const meta = column.$meta;
315
- if (!meta.unique && !meta.index) return [];
316
- const physical = [
317
- meta.kind === 'money' ? moneyColumns(property, meta).minor : columnName(property, meta),
318
- ];
319
- if (coveredByTenantIndex(physical[0] ?? '', tenant, meta.unique)) return [];
320
- return [
321
- {
322
- name: indexName(name, table, physical, meta.unique),
323
- columns: physical,
324
- unique: meta.unique,
325
- },
326
- ];
327
- }),
328
- ...(init.indexes ?? []).map((index) =>
329
- declaredIndexOf(index, { name, table, resolve, columns: columnsExpr }),
330
- ),
331
- // The one index nobody declared and every search needs. Through the SAME `IndexInit` path a
332
- // hand-written `using: 'gin'` takes — `indexName` gives it the method discriminator, so it can
333
- // never collide with a btree an author declares on the same column.
334
- ...(search === null
335
- ? []
336
- : [
337
- {
338
- name: indexName(name, table, [search.column], false, undefined, null, 'gin'),
339
- columns: [search.column],
340
- unique: false,
341
- using: 'gin' as IndexMethod,
342
- },
343
- ]),
344
- ];
345
- // After every other index, so one that already starts with `(tenant, pk)` is seen (`tenant-index.ts`).
346
317
  const physicalKey = primaryKey.map((property) => resolve([property]));
347
- const [tenantIndex] = tenantIndexOf({
348
- entityName: name,
318
+ const { indexes, tenantIndex, covered } = entityIndexesOf({
319
+ name,
349
320
  table,
321
+ entries,
322
+ declared: init.indexes,
323
+ resolve,
324
+ columns: columnsExpr,
325
+ search,
350
326
  tenant,
351
327
  primaryKey: physicalKey,
352
328
  plainView: init.view != null && init.view.materialized !== true,
353
- covering: [
354
- ...declared.filter((index) => index.where == null && index.using === undefined),
355
- ...invariants.filter((inv) => inv.kind === 'unique' && inv.where == null),
356
- ].map((each) => each.columns),
329
+ invariants,
357
330
  });
358
- // A foreign key's own index named again in `indexes` is one index, not two (`index-identity.ts`).
359
- const indexes = distinctIndexes(
360
- tenantIndex === undefined ? declared : [...declared, tenantIndex],
361
- );
362
331
 
363
332
  const retain = retainOf(name, init.retain, entries, indexes, appendOnly);
364
333
  const partition = partitionOf(name, init.partitionBy, {
@@ -436,6 +405,7 @@ export const entity = <const C extends ColumnMap>(
436
405
  $viewQuery: viewQuery,
437
406
  $readOnly: readOnly,
438
407
  $tenantColumn: tenantColumn,
408
+ $version: versionColumnOf(name, init.columns, init.version),
439
409
  $search: search,
440
410
  $schema: schema,
441
411
  get $row(): Row {
@@ -469,6 +439,7 @@ export const entity = <const C extends ColumnMap>(
469
439
  core: core as EntityCore<unknown>,
470
440
  describe,
471
441
  references,
442
+ ...(covered.length === 0 ? {} : { coveredIndexes: covered }),
472
443
  });
473
444
  const { history, historyOf } = init;
474
445
  const lifecycle = { name, table, columns: init.columns, primaryKey, tenantColumn, appendOnly };
@@ -0,0 +1,15 @@
1
+ // Single responsibility: the in-process twin of Postgres' `x.purge`. A history table refuses every
2
+ // delete (append-only, both drivers); inside `purgingHistory(name, work)` a filtered delete of THAT
3
+ // history table only is let through — the erase a subject's GDPR job owes. Postgres still has its
4
+ // guard trigger, which reads `x.purge`; the memory driver has no trigger, so this is its guard.
5
+
6
+ import { asyncContext } from '@ultimat3/core';
7
+
8
+ const purge = asyncContext<string>('the history table a purge may delete from');
9
+
10
+ /** Run `work` with `historyEntity`'s rows deletable — by `deleteWhere` and a chain's `deleteAll`. */
11
+ export const purgingHistory = <R>(historyEntity: string, work: () => Promise<R>): Promise<R> =>
12
+ purge.run(historyEntity, work);
13
+
14
+ /** Whether a purge scope names `entityName` right now. */
15
+ export const purgeNames = (entityName: string): boolean => purge.get() === entityName;
@@ -0,0 +1,35 @@
1
+ // Single responsibility: the shape of one declared index — its key parts, method and build — as
2
+ // `entity({ indexes })` resolves it and `describe()` hands it to `@ultimat3/db`'s DDL. Split out of
3
+ // `types.ts` (the column vocabulary) at its size ceiling.
4
+
5
+ import type { IndexMethod, IndexOperatorClass } from '@ultimat3/db';
6
+
7
+ export interface IndexDef {
8
+ readonly name: string;
9
+ readonly columns: readonly string[];
10
+ readonly unique: boolean;
11
+ readonly order?: 'asc' | 'desc';
12
+ /** Partial index predicate — a soft-deleted row is excluded with this. */
13
+ readonly where?: string;
14
+ /**
15
+ * The access method. Absent is `btree`, which is Postgres' own default and what every index
16
+ * declared before this field existed is — so an entity that names none emits the statement it
17
+ * always emitted, byte for byte, and no app's sidecar regenerates. `@ultimat3/db` owns the
18
+ * closed set (`INDEX_METHODS`); redeclaring the union here would be the second declaration of
19
+ * one fact that this release exists to stop.
20
+ */
21
+ readonly using?: IndexMethod;
22
+ /**
23
+ * How it is built (`IndexInit`). Absent is the default: concurrently on a table that already
24
+ * exists. `false` is the opt-out, a plain build `x db gen` marks `-- lock-heavy: true`.
25
+ */
26
+ readonly concurrently?: boolean;
27
+ /** The ONE key is this SQL expression over PHYSICAL columns; `columns` names the columns it reads. */
28
+ readonly expression?: string;
29
+ /** A direction per key, in key order; `null` writes none. Never beside `order`. */
30
+ readonly orders?: readonly ('asc' | 'desc' | null)[];
31
+ /** INCLUDE payload columns, physical, btree only. */
32
+ readonly include?: readonly string[];
33
+ /** An operator class on every key: `gin_trgm_ops`, gin only (what `contains` needs). */
34
+ readonly operatorClass?: IndexOperatorClass;
35
+ }
@@ -16,6 +16,11 @@ const identity = (index: IndexDef): string =>
16
16
  index.order ?? '',
17
17
  index.where ?? '',
18
18
  index.using ?? '',
19
+ // The key parts (E8): `lower(email)` and `upper(email)` on one column are two indexes.
20
+ index.expression ?? '',
21
+ JSON.stringify(index.orders ?? null),
22
+ (index.include ?? []).join(','),
23
+ index.operatorClass ?? '',
19
24
  ].join('|');
20
25
 
21
26
  /**
package/src/index-init.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // What one `indexes: [...]` entry of `entity(name, { indexes })` may say. Its own file so the
2
2
  // declaration's shape is readable apart from `entity.ts`, which turns it into an `IndexDef`.
3
3
 
4
- import type { IndexMethod } from '@ultimat3/db';
4
+ import type { IndexMethod, IndexOperatorClass } from '@ultimat3/db';
5
5
  import type { Expr, InvariantColumns } from './expr';
6
6
  import type { ColumnMap } from './types';
7
7
 
@@ -41,4 +41,16 @@ export interface IndexInit<C extends ColumnMap> {
41
41
  * `x db gen` marks `-- lock-heavy: true`.
42
42
  */
43
43
  readonly concurrently?: boolean;
44
+ /**
45
+ * The ONE key is this SQL expression — `lower(email)`, `(payload->>'kind')` — written over
46
+ * PHYSICAL column names, as Postgres reads it; `on` names the columns it reads, which is what the
47
+ * covering rule and the name look at. `unique: true` with it is `unique(lower(email))`.
48
+ */
49
+ readonly expression?: string;
50
+ /** A direction per key, in key order (`null` writes none). Replaces `order`, never beside it. */
51
+ readonly orders?: readonly ('asc' | 'desc' | null)[];
52
+ /** Columns stored in the index but never keyed — an index-only scan reads them. btree only. */
53
+ readonly include?: readonly (keyof C & string)[];
54
+ /** An operator class on every key: `gin_trgm_ops` (with `using: 'gin'`), what `contains` needs. */
55
+ readonly operatorClass?: IndexOperatorClass;
44
56
  }