@ultimat3/entity 31.48.0 → 31.50.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 +5 -0
- package/README.md +11 -4
- package/package.json +6 -5
- package/src/aggregate.ts +4 -3
- package/src/batch-read.ts +62 -4
- package/src/bulk-write.ts +1 -19
- package/src/check-refusal.ts +38 -0
- package/src/coalesce.ts +3 -2
- package/src/columns.ts +5 -2
- package/src/cross-tenant.ts +2 -1
- package/src/entity-patch.ts +3 -0
- package/src/errors.ts +34 -8
- package/src/expr-connectives.ts +117 -0
- package/src/expr.ts +3 -27
- package/src/index.ts +2 -0
- package/src/instant-range.ts +38 -0
- package/src/instant.ts +14 -0
- package/src/jit-preload.ts +3 -2
- package/src/memory-journal.ts +8 -0
- package/src/memory-repo.ts +9 -6
- package/src/memory-tx-entry.ts +5 -0
- package/src/pattern-portability.ts +60 -8
- package/src/pg-driver.ts +7 -1
- package/src/pg-sql-aggregate.ts +26 -4
- package/src/pg-sql-in.ts +44 -0
- package/src/pg-sql-measures.ts +2 -2
- package/src/pg-sql.ts +7 -23
- package/src/predicate-operand.ts +109 -11
- package/src/row-observer.ts +71 -4
- package/src/search-repo.ts +36 -16
- package/src/seed.ts +15 -2
- package/src/uuid-text.ts +22 -0
package/CLAUDE.md
CHANGED
|
@@ -34,6 +34,11 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
|
|
|
34
34
|
- **A numeric key has one spelling** (`keyOf`): batches, conflict targets and memory's uniques. **A null test on a whole money property reads `<p>.minor`; any other predicate on it, or an unknown operator, is refused at plan time (`predicate-screen.ts`).** Why: `docs/history/entity.md` (31.0.0).
|
|
35
35
|
- **A PREDICATE's meaning is decided by the column's KIND** (`memory-match.ts`; `compareByKind` /
|
|
36
36
|
`sameValueOfKind` exported for query); ONE numeric comparison, `numericOrder`; `LIKE` never a regex. †
|
|
37
|
+
- **An operand Postgres would refuse is decided in `operandFor`, never bound** (`As of 2026-11`): text
|
|
38
|
+
that is no uuid equals no row (`equalsNoValue`, `uuid-text.ts`); `like` is text/char/bytea only; an
|
|
39
|
+
instant crosses in years 0001–9999 (writes too, `instant-range.ts` — never on read); an `in` list
|
|
40
|
+
≥ `IN_LIST_AS_ARRAY_FROM` is one array bind (`pg-sql-in.ts`). `readByIds` isolates a class-22 id.
|
|
41
|
+
- **`avg` is `averageSql`** — `averageDecimalText`'s integer arithmetic; never `round(avg())`.
|
|
37
42
|
- **The Postgres driver is proved against a real Postgres** (`pg-driver.live.test.ts`, skipped without
|
|
38
43
|
`TEST_DATABASE_URL`). A new operator, kind or write path is not done until it round-trips.
|
|
39
44
|
- **A repository call rejects, never throws synchronously** (`tableFor`'s writes are `async`).
|
package/README.md
CHANGED
|
@@ -331,7 +331,10 @@ is `kind: 'check'` and emits `slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'`. The **same s
|
|
|
331
331
|
places — nothing is translated — so a construct the two engines read differently is REFUSED where it
|
|
332
332
|
is written, with the portable spelling in the `fix` where one exists (`\w` -> `[A-Za-z0-9_]`, `.` ->
|
|
333
333
|
`[^\n\r]`) and the app-only predicate where none does (`\b` is a word boundary to `.test()` and a
|
|
334
|
-
BACKSPACE to Postgres). `i` becomes `~*`; every other flag is refused.
|
|
334
|
+
BACKSPACE to Postgres). `i` becomes `~*`; every other flag is refused. Also refused, because
|
|
335
|
+
Postgres rejects the CHECK or answers it differently: an astral character (Bun writes `/😀/` as a
|
|
336
|
+
surrogate pair `\uD83D\uDE00`), a repetition bound past 255 (`{256}`), a `-` straight after a range
|
|
337
|
+
or `\d` inside a class unless it is last (`[a-z-9]`), and a quantified lookahead (`(?=a)*`).
|
|
335
338
|
|
|
336
339
|
`isNull()` / `isNotNull()` are the only pair in the vocabulary TOTAL over NULL — `IS NULL` answers
|
|
337
340
|
true or false for every input, and the app side reads an ABSENT key and a stored `null` as one value.
|
|
@@ -519,7 +522,7 @@ visibility, never its page.
|
|
|
519
522
|
|---|---|
|
|
520
523
|
| Never a float | `sum`/`avg` answer decimal **text** whatever the column was (the sum of a million `integer` rows is not an `integer`, and `Number()` past 2^53 loses digits); money answers `MoneyValue` in integer minor units; `min`/`max` answer the row's own type |
|
|
521
524
|
| Empty set | `null` in every function, which is what SQL answers — a `0` would claim rows were seen. `count()` is `0`, and that is the distinction |
|
|
522
|
-
| `avg` | one fixed scale (6 digits), rounded half away from zero from the exact rational, so both drivers land on one number |
|
|
525
|
+
| `avg` | one fixed scale (6 digits), rounded half away from zero from the exact rational, so both drivers land on one number — at any magnitude: Postgres' own `avg(bigint)` keeps about sixteen significant digits, so the statement does the integer arithmetic itself (`averageSql`, `As of 2026-11`) |
|
|
523
526
|
| Refused | `min`/`max` on `text` (ordering is the database's collation there and JS code-unit order here); `avg` over money (every answer would be a silent rounding of a fraction of a minor unit — `sum()` and `count()` instead, dividing where the rounding is a decision); an amount covering more than one currency **or scale**; a money total past ±2^53 minor units |
|
|
524
527
|
| `approximateCount()` | `reltuples` out of `pg_class`, constant time, because `count(*)` walks every visible row and no index can make it cheaper. The whole **table** — a filtered chain, every tenant-scoped entity and every soft-deleting one (`reltuples` counts the deleted rows) are `X_APPROXIMATE_COUNT_FILTERED`, and `null` means the table has never been analysed |
|
|
525
528
|
|
|
@@ -540,9 +543,13 @@ An operand is read by the column's kind, once for both drivers (`predicate-opera
|
|
|
540
543
|
| `timestamp()` | a `Date` or ISO text with `Z`/an offset | compared as that instant |
|
|
541
544
|
| `timestamp()` | zoneless ISO text (`'2026-01-01'`, `'2026-01-01T10:00'`) | read as UTC in both drivers, never the server's `TimeZone` |
|
|
542
545
|
| `timestamp()` | a number | `X_INVARIANT_VIOLATED` — epoch milliseconds are no instant Postgres parses |
|
|
546
|
+
| `timestamp()` | a `Date` outside years 0001–9999, or text in year `0000` | `X_INVARIANT_VIOLATED` — Postgres reads an instant as ISO text with a four-digit year. A write is refused the same way, at its entry; a row the server already holds outside the range still reads (`As of 2026-11`) |
|
|
543
547
|
| `date()` | a `Date` | its UTC calendar date (`plainDateUtc`), as `$parse` writes one |
|
|
544
548
|
| `integer()` / `bigint()` | a fraction (`1.5`, `'1.5'`, `'1e1'`) | `X_INVARIANT_VIOLATED` — round it to the bound you mean |
|
|
545
|
-
| `
|
|
549
|
+
| every kind but `text()` / `char()` / `bytes()` | any `like` | `X_INVARIANT_VIOLATED` — a pattern matches text; a number is matched by range, a `uuid`, `boolean`, instant, date, `jsonb` or array by value (`As of 2026-11`) |
|
|
550
|
+
| `uuid()` | any spelling Postgres parses — upper case, no hyphens, `{braces}` | the one value it names, in `eq`/`neq`/`in`, `findById` and a batched lookup |
|
|
551
|
+
| `uuid()` | text that is no uuid, under `eq`/`neq`/`in` | a value no row equals: `eq`/`in` match nothing, `neq` every row; `findById` is `null`, `update`/`delete` are `X_NOT_FOUND` — never `22P02`. It is not bound, so the statement reads `1 = 0` (`As of 2026-11`) |
|
|
552
|
+
| any | an `in` list of 32,768 values or more | one array parameter (`= any($1)`) on Postgres, so a list past the 65,535-bind limit answers. `bytes()`, `json()` and `arrayOf()` have no array form: past 65,535 values they are `X_INVARIANT_VIOLATED` in both drivers (`As of 2026-11`) |
|
|
546
553
|
| `arrayOf()` | a list, under `eq`/`neq`/`in` | element by element, in order (`array_eq`) |
|
|
547
554
|
|
|
548
555
|
## A predicate tree: `andWhereNode`
|
|
@@ -767,7 +774,7 @@ export const find = async (orgId: string, q: string) => {
|
|
|
767
774
|
|
|
768
775
|
| Rule | Detail |
|
|
769
776
|
|---|---|
|
|
770
|
-
| `.search(term)` asks the installed index | built-in: the `matches` predicate in the statement (today's SQL). Any other: ids first — 10,000 (`MAX_PAGE_SIZE`) or more hits are refused with `X_INVARIANT_VIOLATED`, never truncated — then the chain reads those rows with its own tenancy, soft delete, order and cursor |
|
|
777
|
+
| `.search(term)` asks the installed index | built-in: the `matches` predicate in the statement (today's SQL). Any other: ids first — 10,000 (`MAX_PAGE_SIZE`) or more hits are refused with `X_INVARIANT_VIOLATED`, never truncated — then the chain reads those rows with its own tenancy, soft delete, order and cursor. The index is asked per tenant: the chain's `eq` on the tenant column, else the actor's org — and inside `crossTenant()` each tenant of an `andWhere('<tenant>', 'in', [...])`, never the actor's alone; a `crossTenant` search naming neither is refused (`X_INVARIANT_VIOLATED`) |
|
|
771
778
|
| a document has a **version** | the row's `onUpdateNow()` instant, epoch ms. A searchable entity indexed by anything declares one — `updatedAt: timestamp().defaultNow().onUpdateNow()` — or `searchDocumentOf` and `reindex()` refuse (`X_INVARIANT_VIOLATED`) |
|
|
772
779
|
| the version is STRICTLY increasing per row | a write of a searchable entity — a soft delete included — stores its version no earlier than the stored one + 1 ms: Postgres `greatest($now, updated_at + interval '1 millisecond')` in the `update` and the upsert's `on conflict` set; the memory driver in its merge (`advanceVersion`); a `defineDriver` store in ITS write, atomically per row — `DriverRepo.update`'s `advance` argument, and `advanceVersion(entity, stored, merged, (p) => plan.set.includes(p))` in its own `upsert` (`entityDriverConformance` refuses a store that skips either). So two writes inside one millisecond are two versions, and the index keeps the second. The column may run ahead of the clock by a millisecond per same-ms write. Other entities' `onUpdateNow()` columns are the clock's reading, unchanged |
|
|
773
780
|
| keep only newer | an index applies a document only when its version is newer than what it holds for that id: a document, or the tombstone `remove(scope, ids, version)` leaves (a delete's: past the row's last version and no earlier than its instant). Equal = replay. EXCEPT a `committed` document — the write path's, `index(docs, { committed: true })` — which replaces a tombstone whatever its version: a key deleted and written again is live at once, inside one millisecond too. `reindex`'s reads are not `committed`, so a stale read never brings a deleted row back |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/entity",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.50.0",
|
|
4
4
|
"description": "A table + its domain type + invariants the database also enforces",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"exports": {
|
|
27
27
|
".": "./src/index.ts",
|
|
28
28
|
"./adapter": "./src/adapter.ts",
|
|
29
|
+
"./internal/memory-tx": "./src/memory-tx-entry.ts",
|
|
29
30
|
"./record": "./src/record.ts"
|
|
30
31
|
},
|
|
31
32
|
"files": [
|
|
@@ -44,9 +45,9 @@
|
|
|
44
45
|
"test": "bun test"
|
|
45
46
|
},
|
|
46
47
|
"dependencies": {
|
|
47
|
-
"@ultimat3/core": "31.
|
|
48
|
-
"@ultimat3/db": "31.
|
|
49
|
-
"@ultimat3/schema": "31.
|
|
50
|
-
"@ultimat3/time": "31.
|
|
48
|
+
"@ultimat3/core": "31.50.0",
|
|
49
|
+
"@ultimat3/db": "31.50.0",
|
|
50
|
+
"@ultimat3/schema": "31.50.0",
|
|
51
|
+
"@ultimat3/time": "31.50.0"
|
|
51
52
|
}
|
|
52
53
|
}
|
package/src/aggregate.ts
CHANGED
|
@@ -159,9 +159,10 @@ export const sumDecimalText = (values: readonly string[]): string | null => {
|
|
|
159
159
|
};
|
|
160
160
|
|
|
161
161
|
/**
|
|
162
|
-
* `sum / count`, rounded half away from zero at `AVG_SCALE
|
|
163
|
-
*
|
|
164
|
-
*
|
|
162
|
+
* `sum / count`, rounded half away from zero at `AVG_SCALE`. The statement spells the same integer
|
|
163
|
+
* arithmetic (`averageSql`, `pg-sql-aggregate.ts`) rather than taking the server's own scale: two
|
|
164
|
+
* drivers rounding at different places answer two numbers, and `avg(bigint)` past sixteen digits
|
|
165
|
+
* rounds at none.
|
|
165
166
|
*/
|
|
166
167
|
export const averageDecimalText = (total: string | null, count: number): string | null => {
|
|
167
168
|
if (total === null || count === 0) return null;
|
package/src/batch-read.ts
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
// answers them. The microtask coalescer and the sibling-aware preload both read ids through here,
|
|
4
4
|
// so the two can never disagree about when a shared statement is legal.
|
|
5
5
|
|
|
6
|
-
import type
|
|
6
|
+
import { type DbClient, sqlState } from '@ultimat3/db';
|
|
7
7
|
import type { EntityCore } from './entity';
|
|
8
8
|
import { canonicalDecimal, canonicalInteger } from './numeric-compare';
|
|
9
9
|
import { decodeRow, type PhysicalRow } from './pg-row';
|
|
10
10
|
import { type ReadShape, selectStatement } from './pg-sql';
|
|
11
11
|
import type { QueryPlan } from './tenancy';
|
|
12
|
+
import { canonicalUuid } from './uuid-text';
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
15
|
* Postgres binds at most 65535 parameters, so a batch wider than this becomes several statements
|
|
@@ -36,14 +37,15 @@ export type Answer = { readonly row: unknown } | { readonly error: unknown };
|
|
|
36
37
|
* The string both sides of a batch are filed under — the requested id, and the key of a row that
|
|
37
38
|
* came back. Postgres compares a `uuid` as a value and prints it lower-cased, so an id handed in
|
|
38
39
|
* upper case matches the row *there* and would miss it here, which would make an answer depend on
|
|
39
|
-
* whether some other lookup shared the microtask
|
|
40
|
+
* whether some other lookup shared the microtask; braces and missing hyphens are the same value
|
|
41
|
+
* there too (`uuid-text.ts`). An integer or `numeric` is compared by value too:
|
|
40
42
|
* `'007'` matched the row and missed its answer here, filed under `'7'`. One the column could not
|
|
41
43
|
* hold stays as written, so the statement still carries it and Postgres answers its own refusal.
|
|
42
44
|
* Every other kind compares by its bytes, and lower-casing a text key would merge two rows
|
|
43
45
|
* Postgres keeps apart.
|
|
44
46
|
*/
|
|
45
47
|
export const keyOf = (kind: string, value: unknown): string => {
|
|
46
|
-
if (kind === 'uuid') return String(value).toLowerCase();
|
|
48
|
+
if (kind === 'uuid') return canonicalUuid(value) ?? String(value).toLowerCase();
|
|
47
49
|
if (kind === 'integer' || kind === 'bigint') return canonicalInteger(value) ?? String(value);
|
|
48
50
|
if (kind === 'numeric') return canonicalDecimal(value) ?? String(value);
|
|
49
51
|
if (kind === 'timestamptz') return canonicalInstant(value) ?? String(value);
|
|
@@ -117,7 +119,7 @@ export interface PointRead<Row> {
|
|
|
117
119
|
}
|
|
118
120
|
|
|
119
121
|
/** The one statement, filed by key — the same builder, the same scope, `in` instead of `=`. */
|
|
120
|
-
|
|
122
|
+
const readStatement = async <Row>(
|
|
121
123
|
read: PointRead<Row>,
|
|
122
124
|
ids: readonly unknown[],
|
|
123
125
|
): Promise<ReadonlyMap<string, Answer>> => {
|
|
@@ -144,6 +146,62 @@ export const readByIds = async <Row>(
|
|
|
144
146
|
return answers;
|
|
145
147
|
};
|
|
146
148
|
|
|
149
|
+
/** `in_failed_transaction`: a statement sent after the first refusal aborted the transaction. */
|
|
150
|
+
const IN_FAILED_TRANSACTION = '25P02';
|
|
151
|
+
|
|
152
|
+
/** SQLSTATE class 22, data exception: the server refused a VALUE, not the statement's shape. */
|
|
153
|
+
const isDataError = (error: unknown): boolean => sqlState(error)?.startsWith('22') === true;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* `readStatement`, with a value the server refuses failing only the id that carried it. One key
|
|
157
|
+
* the column cannot hold (`'abc'` against a `bigint`) is a class 22 refusal of the WHOLE statement,
|
|
158
|
+
* so every lookup widened into it was failed by an id it never asked for — rows the single
|
|
159
|
+
* statement each would have sent answers. The ids are re-sent in halves until the refused one
|
|
160
|
+
* stands alone: about `2k·log2(n)` statements for `k` bad ids, never one per id.
|
|
161
|
+
*
|
|
162
|
+
* Anything else — a dropped connection, a timeout, a stale schema — is the statement's own failure
|
|
163
|
+
* and is rethrown for every caller, as before; a half that fails that way answers its ids with its
|
|
164
|
+
* own failure. Only a half sent into a transaction the first refusal aborted (`25P02`) gets the
|
|
165
|
+
* FIRST refusal, the one the unsplit statement gave them.
|
|
166
|
+
*/
|
|
167
|
+
export const readByIds = async <Row>(
|
|
168
|
+
read: PointRead<Row>,
|
|
169
|
+
ids: readonly unknown[],
|
|
170
|
+
): Promise<ReadonlyMap<string, Answer>> => {
|
|
171
|
+
try {
|
|
172
|
+
return await readStatement(read, ids);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (!isDataError(error) || ids.length < 2) throw error;
|
|
175
|
+
const answers = new Map<string, Answer>();
|
|
176
|
+
await isolate(read, ids, error, answers);
|
|
177
|
+
return answers;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/** `ids` is known to fail together with `refusal`: halve, and file what each half answers. */
|
|
182
|
+
const isolate = async <Row>(
|
|
183
|
+
read: PointRead<Row>,
|
|
184
|
+
ids: readonly unknown[],
|
|
185
|
+
refusal: unknown,
|
|
186
|
+
answers: Map<string, Answer>,
|
|
187
|
+
): Promise<void> => {
|
|
188
|
+
const middle = Math.ceil(ids.length / 2);
|
|
189
|
+
for (const half of [ids.slice(0, middle), ids.slice(middle)]) {
|
|
190
|
+
try {
|
|
191
|
+
for (const [key, answer] of await readStatement(read, half)) answers.set(key, answer);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (isDataError(error) && half.length > 1) {
|
|
194
|
+
await isolate(read, half, error, answers);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
// Only a transaction the first refusal ABORTED inherits it; a half's own failure (a pool
|
|
198
|
+
// timeout, a failover's 57P01) is that half's answer, never "invalid input syntax".
|
|
199
|
+
const own = sqlState(error) === IN_FAILED_TRANSACTION ? refusal : error;
|
|
200
|
+
for (const id of half) answers.set(keyOf(read.key.kind, id), { error: own });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
147
205
|
/** One statement's worth at a time — a batch too wide for the bind count is several, never one. */
|
|
148
206
|
export const statementChunks = <T>(values: readonly T[]): readonly (readonly T[])[] => {
|
|
149
207
|
const chunks: T[][] = [];
|
package/src/bulk-write.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { keyOf } from './batch-read';
|
|
|
9
9
|
import { columnFor } from './column';
|
|
10
10
|
import { valueAt } from './cursor';
|
|
11
11
|
import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
|
|
12
|
-
import { EntityError, invariantViolated } from './errors';
|
|
12
|
+
import { crossTenantUpsert, EntityError, invariantViolated } from './errors';
|
|
13
13
|
import { allColumns, columnsOf } from './pg-row';
|
|
14
14
|
import type { RowPatch } from './types';
|
|
15
15
|
import { uniqueConstraints } from './unique-constraints';
|
|
@@ -134,24 +134,6 @@ const unevenBatch = (entityName: string, position: number, missing: string): Ent
|
|
|
134
134
|
fix: `${entityName}.upsertAll(rows.map((row) => ({ ...row, ${missing}: <value> })), args) # every row of an updating batch names the same columns`,
|
|
135
135
|
});
|
|
136
136
|
|
|
137
|
-
/**
|
|
138
|
-
* A cross-tenant upsert is not a batching mistake, it is a write into another tenant's row, so it
|
|
139
|
-
* gets tenancy's own code. `X_TENANCY_UNSCOPED`'s own factory sends the reader to the request
|
|
140
|
-
* context the tenant is derived from, which is not what repairs this: an upsert builds no read
|
|
141
|
-
* plan, so nothing derives anything onto it — the scope has to be part of the constraint the
|
|
142
|
-
* collision is judged against, or the row that comes back was never in scope to begin with.
|
|
143
|
-
*/
|
|
144
|
-
const crossTenantUpsert = (
|
|
145
|
-
entityName: string,
|
|
146
|
-
tenant: string,
|
|
147
|
-
on: readonly string[],
|
|
148
|
-
): EntityError =>
|
|
149
|
-
new EntityError({
|
|
150
|
-
code: 'X_TENANCY_UNSCOPED',
|
|
151
|
-
cause: `${entityName}.upsertAll() resolves a collision on (${on.join(', ')}), which does not include the tenant column "${tenant}" — a row stored by another tenant would match and be overwritten`,
|
|
152
|
-
fix: `${entityName}.upsertAll(rows, { onConflict: ['${tenant}', '${on.join("', '")}'] }) # or onMatch: 'nothing', which writes nothing to a row it does not own`,
|
|
153
|
-
});
|
|
154
|
-
|
|
155
137
|
/**
|
|
156
138
|
* Every conflict target Postgres could infer an index for: the primary key, and every non-partial
|
|
157
139
|
* unique the entity declares by either spelling (`unique-constraints.ts`).
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Single responsibility: a CHECK the server enforced on an entity's own invariant answers as that
|
|
2
|
+
// invariant. `insert` judges the whole row before the statement; a patch (`update`, `updateWhere`)
|
|
3
|
+
// only becomes a row on the server, so there the CHECK is the first judge and its `23514` is the
|
|
4
|
+
// same refusal — `X_INVARIANT_VIOLATED`, a 422, never `X_DB_STATEMENT_FAILED`, a 500.
|
|
5
|
+
|
|
6
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
7
|
+
import { namesConstraint, sqlState } from '@ultimat3/db';
|
|
8
|
+
import type { EntityCore } from './entity';
|
|
9
|
+
import { invariantViolated } from './errors';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `check_violation`. Not a row of `@ultimat3/db`'s `SQLSTATE`: that table is the states the db
|
|
13
|
+
* layer classifies into its own codes, and this one it leaves to the entity that declared the CHECK.
|
|
14
|
+
*/
|
|
15
|
+
const CHECK_VIOLATION = '23514';
|
|
16
|
+
|
|
17
|
+
/** A table name without its schema: the server reports the relation's own name. */
|
|
18
|
+
const bareTable = (table: string): string => table.slice(table.lastIndexOf('.') + 1);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The invariant refusal `error` stands for, or `error` itself. Only a check this entity declares
|
|
22
|
+
* is rewritten: a hand-written constraint the declaration does not know stays the server's
|
|
23
|
+
* verdict, because no rule here can name what it means. And only on the entity's own table: a
|
|
24
|
+
* constraint name is unique per table, so a trigger's write to another table whose CHECK shares
|
|
25
|
+
* a rule's name is that table's failure, not this rule's. A driver that names no table is judged
|
|
26
|
+
* by the constraint alone, as before.
|
|
27
|
+
*/
|
|
28
|
+
export const asInvariantRefusal = (entity: EntityCore<unknown>, error: unknown): unknown => {
|
|
29
|
+
if (sqlState(error) !== CHECK_VIOLATION || !isUltimateError(error)) return error;
|
|
30
|
+
const constraint = error.meta?.['constraint'];
|
|
31
|
+
if (typeof constraint !== 'string') return error;
|
|
32
|
+
const table = error.meta?.['table'];
|
|
33
|
+
if (typeof table === 'string' && table !== bareTable(entity.$table)) return error;
|
|
34
|
+
const rule = entity.$invariants.find(
|
|
35
|
+
(inv) => inv.kind === 'check' && namesConstraint(entity.$table, inv, constraint),
|
|
36
|
+
);
|
|
37
|
+
return rule === undefined ? error : invariantViolated(entity.$name, rule.name, rule.message);
|
|
38
|
+
};
|
package/src/coalesce.ts
CHANGED
|
@@ -107,8 +107,9 @@ const flush = async (batch: Batch): Promise<void> => {
|
|
|
107
107
|
else entry.settle(answer.row);
|
|
108
108
|
}
|
|
109
109
|
} catch (error) {
|
|
110
|
-
// The statement failed
|
|
111
|
-
//
|
|
110
|
+
// The statement failed for a reason that is the statement's — a refused VALUE never
|
|
111
|
+
// reaches here: `readByIds` re-sends around it and files that failure under its own id
|
|
112
|
+
// (`batch-read.ts`). Every entry was returned to a caller, so none goes unhandled.
|
|
112
113
|
for (const entry of chunk) entry.fail(error);
|
|
113
114
|
}
|
|
114
115
|
}
|
package/src/columns.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
makeTimestamp,
|
|
21
21
|
} from './column';
|
|
22
22
|
import { got, oneOf, refuseNul } from './column-values';
|
|
23
|
+
import { assertInstantsCross } from './instant-range';
|
|
23
24
|
import { refuseColumn } from './refuse';
|
|
24
25
|
import type {
|
|
25
26
|
Column,
|
|
@@ -443,8 +444,10 @@ const narrowUuid = <Row>(columns: ColumnMap, row: Row): Row => {
|
|
|
443
444
|
* nowhere. The `as` is the one assertion this file is for — every money property is a `MoneyValue`
|
|
444
445
|
* once `narrowMoney` has returned, and `parseMinor` threw for anything that could not become one.
|
|
445
446
|
*/
|
|
446
|
-
export const narrowRow = <Row>(columns: ColumnMap, values: RowWrite<Row>): Row =>
|
|
447
|
-
|
|
447
|
+
export const narrowRow = <Row>(columns: ColumnMap, values: RowWrite<Row>): Row => {
|
|
448
|
+
assertInstantsCross(columns, values);
|
|
449
|
+
return narrowUuid(columns, narrowMoney(columns, values)) as Row;
|
|
450
|
+
};
|
|
448
451
|
|
|
449
452
|
/**
|
|
450
453
|
* The CHECK that stops a psql session writing a currency the app would refuse — the app's own
|
package/src/cross-tenant.ts
CHANGED
|
@@ -62,7 +62,8 @@ export function crossTenant<T>(reason: string, fn: () => T): T {
|
|
|
62
62
|
|
|
63
63
|
/**
|
|
64
64
|
* The innermost enclosing reason, or `undefined` outside every scope — which is every query in an
|
|
65
|
-
* app that never calls `crossTenant`. Read by the tenant guard, and by
|
|
65
|
+
* app that never calls `crossTenant`. Read by the tenant guard, and by `search-repo.ts`, which must
|
|
66
|
+
* know the chain spans tenants before it asks an external index for one.
|
|
66
67
|
*/
|
|
67
68
|
export const crossTenantReason = (): string | undefined => storage.get();
|
|
68
69
|
|
package/src/entity-patch.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// would rewrite every column it did not name.
|
|
4
4
|
|
|
5
5
|
import { invariantViolated } from './errors';
|
|
6
|
+
import { assertInstantsCross } from './instant-range';
|
|
6
7
|
import { holdsJsonNull } from './json-null';
|
|
7
8
|
import { copyRow } from './sealed';
|
|
8
9
|
import type { AnyColumn } from './types';
|
|
@@ -40,5 +41,7 @@ export const parseEntityPatch = <Patch>(
|
|
|
40
41
|
configurable: true,
|
|
41
42
|
});
|
|
42
43
|
}
|
|
44
|
+
// A patch is a write: an instant Postgres would refuse is refused here, for both drivers.
|
|
45
|
+
assertInstantsCross(columns, parsed);
|
|
43
46
|
return parsed as Patch;
|
|
44
47
|
};
|
package/src/errors.ts
CHANGED
|
@@ -61,17 +61,43 @@ export const tenancyUnscoped = (
|
|
|
61
61
|
entityName: string,
|
|
62
62
|
operation: string,
|
|
63
63
|
actorOrg?: string,
|
|
64
|
+
): EntityError =>
|
|
65
|
+
// Two constructions, never one with a ternary in its `fix:`. `x errors explain` quotes the first
|
|
66
|
+
// throw site whose fix is ONE literal, and a ternary is none: it skipped this factory and
|
|
67
|
+
// answered a read's question with the upsert's fix below. The no-context branch is first because
|
|
68
|
+
// it is the code's general cause — its registered title, "a tenant-scoped query has no org
|
|
69
|
+
// predicate" — and both other fixes are narrower than that.
|
|
70
|
+
actorOrg === undefined
|
|
71
|
+
? new EntityError({
|
|
72
|
+
code: 'X_TENANCY_UNSCOPED',
|
|
73
|
+
cause: `${entityName}.${operation}() was built without an org predicate but the entity has an orgId column, and no request context carried an actor to take the tenant from`,
|
|
74
|
+
fix: `runWithContext(ctxOf({ actor: userActor({ id, orgId }) }), fn) // the actor's org scopes the plan — or name the tenant: ${entityName}.${operation}({ orgId }), which orgScoped(plan, orgId) is the plan-level form of`,
|
|
75
|
+
})
|
|
76
|
+
: new EntityError({
|
|
77
|
+
code: 'X_TENANCY_UNSCOPED',
|
|
78
|
+
cause: `${entityName}.${operation}() was checked against a plan with no org predicate, though the acting actor's tenant is ${renderValue(actorOrg)} — a plan is verified here, never rewritten, so the tenant had to be on it already`,
|
|
79
|
+
fix: `scopedPlan('${entityName}', tenantColumn, '${operation}', plan) // applies the actor's tenant — or add the predicate first: orgScoped(plan, ${asLiteral(actorOrg, "'<org>'")})`,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A cross-tenant upsert is not a batching mistake, it is a write into another tenant's row, so it
|
|
84
|
+
* gets tenancy's own code. `tenancyUnscoped` sends the reader to the request context the tenant is
|
|
85
|
+
* derived from, which is not what repairs this: an upsert builds no read plan, so nothing derives
|
|
86
|
+
* anything onto it — the scope has to be part of the constraint the collision is judged against,
|
|
87
|
+
* or the row that comes back was never in scope to begin with.
|
|
88
|
+
*
|
|
89
|
+
* Declared HERE, below the general factory, and not beside its one caller in `bulk-write.ts`:
|
|
90
|
+
* that file sorts first, so its fix was the one `x errors explain X_TENANCY_UNSCOPED` printed.
|
|
91
|
+
*/
|
|
92
|
+
export const crossTenantUpsert = (
|
|
93
|
+
entityName: string,
|
|
94
|
+
tenant: string,
|
|
95
|
+
on: readonly string[],
|
|
64
96
|
): EntityError =>
|
|
65
97
|
new EntityError({
|
|
66
98
|
code: 'X_TENANCY_UNSCOPED',
|
|
67
|
-
cause:
|
|
68
|
-
|
|
69
|
-
? `${entityName}.${operation}() was built without an org predicate but the entity has an orgId column, and no request context carried an actor to take the tenant from`
|
|
70
|
-
: `${entityName}.${operation}() was checked against a plan with no org predicate, though the acting actor's tenant is ${renderValue(actorOrg)} — a plan is verified here, never rewritten, so the tenant had to be on it already`,
|
|
71
|
-
fix:
|
|
72
|
-
actorOrg === undefined
|
|
73
|
-
? `runWithContext(ctxOf({ actor: userActor({ id, orgId }) }), fn) // the actor's org scopes the plan — or name the tenant: ${entityName}.${operation}({ orgId }), which orgScoped(plan, orgId) is the plan-level form of`
|
|
74
|
-
: `scopedPlan('${entityName}', tenantColumn, '${operation}', plan) // applies the actor's tenant — or add the predicate first: orgScoped(plan, ${asLiteral(actorOrg, "'<org>'")})`,
|
|
99
|
+
cause: `${entityName}.upsertAll() resolves a collision on (${on.join(', ')}), which does not include the tenant column "${tenant}" — a row stored by another tenant would match and be overwritten`,
|
|
100
|
+
fix: `${entityName}.upsertAll(rows, { onConflict: ['${tenant}', '${on.join("', '")}'] }) # or onMatch: 'nothing', which writes nothing to a row it does not own`,
|
|
75
101
|
});
|
|
76
102
|
|
|
77
103
|
/**
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Single responsibility: the connectives over invariant expressions — `allOf` (and), `anyOf` (or),
|
|
2
|
+
// and the operand rules `iff` shares with them. One declaration still compiles to both enforcement
|
|
3
|
+
// points: a three-valued verdict the app runs and the SQL predicate a CHECK or a partial index
|
|
4
|
+
// carries, so "both null" and "at most one set" are one rule, never a hand-written index.
|
|
5
|
+
|
|
6
|
+
import type { Expr } from './expr';
|
|
7
|
+
import { check, type Verdict, verdictOf } from './expr-verdict';
|
|
8
|
+
import { refuseInvariant } from './refuse';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Every operand of a combinator is a predicate: a `unique` is an `Expr` whose SQL is a COLUMN LIST,
|
|
12
|
+
* so combining one is refused where it was written, naming the rule the author meant to declare.
|
|
13
|
+
*/
|
|
14
|
+
export const assertPredicates = (combinator: string, sides: readonly Expr[]): void => {
|
|
15
|
+
for (const side of sides) {
|
|
16
|
+
if (side.kind !== 'unique') continue;
|
|
17
|
+
// The columns it names, so the pasted line is the rule the author already meant to declare —
|
|
18
|
+
// never a `<name>` for them to fill in, which is the placeholder `refuse.test.ts` refuses.
|
|
19
|
+
//
|
|
20
|
+
// `JSON.stringify` and never `'${column}'`: a column path is a VALUE reaching TypeScript
|
|
21
|
+
// SOURCE, which is this file's own hazard one layer up. `columns: { "o'brien": text() }` is a
|
|
22
|
+
// legal declaration and `unique()` is reached untyped besides, so a quote ends the literal and
|
|
23
|
+
// the fix stops parsing; a backslash is the half doubling the quote would still have missed.
|
|
24
|
+
// `errors.ts`'s `asLiteral` is the same rule for the same reason.
|
|
25
|
+
const columns = side.paths.map((path) => path.join('.'));
|
|
26
|
+
const list = columns.map((column) => JSON.stringify(column)).join(', ');
|
|
27
|
+
const name = JSON.stringify(`${columns.join('_')}_unique`);
|
|
28
|
+
refuseInvariant(
|
|
29
|
+
combinator,
|
|
30
|
+
`${side.message} is a unique constraint, whose SQL is a column list and not a predicate`,
|
|
31
|
+
`invariant(${name}, c.unique([${list}])) # uniqueness is its own invariant; ${combinator} takes predicates, e.g. iff(c.status.eq('published'), c.publishedAt.isNotNull())`,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The paths every operand reads, each once, in the order they were first named. */
|
|
37
|
+
export const operandPaths = (sides: readonly Expr[]): readonly (readonly string[])[] => {
|
|
38
|
+
const seen = new Set<string>();
|
|
39
|
+
const paths: (readonly string[])[] = [];
|
|
40
|
+
for (const path of sides.flatMap((side) => side.paths)) {
|
|
41
|
+
// The whole segment list, never `join('.')`: a property literally named `amount.minor` and the
|
|
42
|
+
// `minor` part of a money `amount` are two columns, and the dot would make them one.
|
|
43
|
+
const key = JSON.stringify(path);
|
|
44
|
+
if (seen.has(key)) continue;
|
|
45
|
+
seen.add(key);
|
|
46
|
+
paths.push(path);
|
|
47
|
+
}
|
|
48
|
+
return paths;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Two or more operands, or a combinator that combines nothing: `allOf(x)` is `x`, and writing it
|
|
53
|
+
* says the author meant a second condition they left out.
|
|
54
|
+
*/
|
|
55
|
+
const assertOperands = (combinator: string, sides: readonly Expr[]): void => {
|
|
56
|
+
if (sides.length >= 2) return;
|
|
57
|
+
// The fix names only what the author already wrote: their one operand's own columns, never a
|
|
58
|
+
// column this generator would be inventing for an entity it cannot see.
|
|
59
|
+
const column = sides[0]?.paths[0]?.join('.');
|
|
60
|
+
refuseInvariant(
|
|
61
|
+
combinator,
|
|
62
|
+
`takes two or more predicates, got ${sides.length}`,
|
|
63
|
+
column === undefined
|
|
64
|
+
? `${combinator}(first, second) # two predicates over this entity's columns, or none: drop the ${combinator}() call`
|
|
65
|
+
: `unwrap ${combinator}(…) and pass its one predicate on ${JSON.stringify(column)} directly # or add the second condition beside it inside ${combinator}(…)`,
|
|
66
|
+
);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* One connective over its operands: SQL as each operand parenthesised and joined by `keyword`, and
|
|
71
|
+
* the verdict in SQL's three values. One app-only operand makes the WHOLE rule app-only — emitting
|
|
72
|
+
* the rest would enforce a rule the author never wrote, and a partial index refuses it by name.
|
|
73
|
+
*/
|
|
74
|
+
const connective = (
|
|
75
|
+
combinator: string,
|
|
76
|
+
keyword: 'and' | 'or',
|
|
77
|
+
joiner: string,
|
|
78
|
+
sides: readonly Expr[],
|
|
79
|
+
verdict: (answers: readonly (boolean | null)[]) => boolean | null,
|
|
80
|
+
): Expr => {
|
|
81
|
+
assertOperands(combinator, sides);
|
|
82
|
+
assertPredicates(combinator, sides);
|
|
83
|
+
const verdicts: readonly Verdict[] = sides.map(verdictOf);
|
|
84
|
+
return check(
|
|
85
|
+
operandPaths(sides),
|
|
86
|
+
sides.map((side) => side.message).join(joiner),
|
|
87
|
+
(resolve) => {
|
|
88
|
+
const parts = sides.map((side) => side.toSql(resolve));
|
|
89
|
+
return parts.some((part) => part === null)
|
|
90
|
+
? null
|
|
91
|
+
: parts.map((part) => `(${part})`).join(` ${keyword} `);
|
|
92
|
+
},
|
|
93
|
+
(row) => verdict(verdicts.map((judge) => judge(row))),
|
|
94
|
+
);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Every operand holds: `allOf(c.a.isNull(), c.b.isNull())` — "both unset", rendered
|
|
99
|
+
* `(a is null) and (b is null)`. Three-valued as SQL's `and`: false when any operand is false,
|
|
100
|
+
* else unknown when any is unknown (which a CHECK passes), else true. For a rule, two invariants
|
|
101
|
+
* are the same conjunction; this is for where one predicate must say it — an index `where`, or
|
|
102
|
+
* inside `anyOf`/`iff`.
|
|
103
|
+
*/
|
|
104
|
+
export const allOf = (...sides: readonly Expr[]): Expr =>
|
|
105
|
+
connective('allOf', 'and', ', and ', sides, (answers) =>
|
|
106
|
+
answers.includes(false) ? false : answers.includes(null) ? null : true,
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* At least one operand holds: `anyOf(c.a.isNull(), c.b.isNull())` — "at most one of the two set",
|
|
111
|
+
* rendered `(a is null) or (b is null)`. Three-valued as SQL's `or`: true when any operand is
|
|
112
|
+
* true, else unknown when any is unknown, else false.
|
|
113
|
+
*/
|
|
114
|
+
export const anyOf = (...sides: readonly Expr[]): Expr =>
|
|
115
|
+
connective('anyOf', 'or', ', or ', sides, (answers) =>
|
|
116
|
+
answers.includes(true) ? true : answers.includes(null) ? null : false,
|
|
117
|
+
);
|
package/src/expr.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import { literal as sqlLiteral } from '@ultimat3/db';
|
|
16
16
|
import { invariantViolated } from './errors';
|
|
17
|
+
import { assertPredicates, operandPaths } from './expr-connectives';
|
|
17
18
|
import { check, unknownOnNull, verdictOf } from './expr-verdict';
|
|
18
19
|
import { isNullish } from './is-null';
|
|
19
20
|
import { DECIMAL_TEXT, numericOrder } from './numeric-compare';
|
|
@@ -398,33 +399,8 @@ const satisfies = (predicate: RowPredicate, columns: readonly string[]): Expr =>
|
|
|
398
399
|
* `isNull()`/`isNotNull()` are total, which is what makes a rule built from them decide a NULL.
|
|
399
400
|
*/
|
|
400
401
|
export const iff = (left: Expr, right: Expr): Expr => {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
// The columns it names, so the pasted line is the rule the author already meant to declare —
|
|
404
|
-
// never a `<name>` for them to fill in, which is the placeholder `refuse.test.ts` refuses.
|
|
405
|
-
//
|
|
406
|
-
// `JSON.stringify` and never `'${column}'`: a column path is a VALUE reaching TypeScript
|
|
407
|
-
// SOURCE, which is this file's own hazard one layer up. `columns: { "o'brien": text() }` is a
|
|
408
|
-
// legal declaration and `unique()` is reached untyped besides, so a quote ends the literal and
|
|
409
|
-
// the fix stops parsing; a backslash is the half doubling the quote would still have missed.
|
|
410
|
-
// `errors.ts`'s `asLiteral` is the same rule for the same reason.
|
|
411
|
-
const columns = side.paths.map((path) => path.join('.'));
|
|
412
|
-
const list = columns.map((column) => JSON.stringify(column)).join(', ');
|
|
413
|
-
const name = JSON.stringify(`${columns.join('_')}_unique`);
|
|
414
|
-
refuseInvariant(
|
|
415
|
-
'iff',
|
|
416
|
-
`${side.message} is a unique constraint, whose SQL is a column list and not a predicate`,
|
|
417
|
-
`invariant(${name}, c.unique([${list}])) # uniqueness is its own invariant; iff takes two predicates, e.g. iff(c.status.eq('published'), c.publishedAt.isNotNull())`,
|
|
418
|
-
);
|
|
419
|
-
}
|
|
420
|
-
const seen = new Set<string>();
|
|
421
|
-
const paths: (readonly string[])[] = [];
|
|
422
|
-
for (const path of [...left.paths, ...right.paths]) {
|
|
423
|
-
const key = path.join('.');
|
|
424
|
-
if (seen.has(key)) continue;
|
|
425
|
-
seen.add(key);
|
|
426
|
-
paths.push(path);
|
|
427
|
-
}
|
|
402
|
+
assertPredicates('iff', [left, right]);
|
|
403
|
+
const paths = operandPaths([left, right]);
|
|
428
404
|
return check(
|
|
429
405
|
paths,
|
|
430
406
|
`${left.message} exactly when ${right.message}`,
|
package/src/index.ts
CHANGED
|
@@ -72,6 +72,7 @@ export {
|
|
|
72
72
|
} from './errors';
|
|
73
73
|
export type { ColumnExpr, Expr, InvariantColumns, Resolve } from './expr';
|
|
74
74
|
export { iff } from './expr';
|
|
75
|
+
export { allOf, anyOf } from './expr-connectives';
|
|
75
76
|
/** The two DECLARED capabilities' refusals — a third-party driver raises the same ones. */
|
|
76
77
|
export type { HistoryColumns, HistoryEntity, HistoryInit } from './history';
|
|
77
78
|
export type { HistoryRecord, HistoryVersion } from './history-order';
|
|
@@ -86,6 +87,7 @@ export { MAX_LATEST_GROUPS } from './latest-by';
|
|
|
86
87
|
export { MAX_LOCK_KEYS } from './lock-key';
|
|
87
88
|
export type { CountByOptions, Measure, MeasureFn, MeasureMap } from './measures';
|
|
88
89
|
export { MAX_MEASURES } from './measures';
|
|
90
|
+
// Whether a memory transaction has ended: `@ultimat3/action`'s settle scope asks it, never a probe.
|
|
89
91
|
export { memoryJournal } from './memory-journal';
|
|
90
92
|
// How Postgres compares two values of one column, decided by the column's declared KIND. Exported
|
|
91
93
|
// because `@ultimat3/query`'s matcher and in-memory source ask the same question — and a second
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Single responsibility: refuse, at a WRITE's entry, a `timestamp()` value Postgres cannot be
|
|
2
|
+
// handed. Never on read: an instant the server already holds — a sentinel a psql session wrote past
|
|
3
|
+
// year 9999 — still decodes, exactly as it did.
|
|
4
|
+
|
|
5
|
+
import { got } from './column-values';
|
|
6
|
+
import { instantCrosses } from './instant';
|
|
7
|
+
import { refuseColumn } from './refuse';
|
|
8
|
+
import type { AnyColumn } from './types';
|
|
9
|
+
|
|
10
|
+
const outOfRange = (value: unknown): boolean => value instanceof Date && !instantCrosses(value);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A `Date` is bound as its ISO text, and outside years 0001–9999 the server refuses that text
|
|
14
|
+
* (`22008`, `22007`, `22009`) while memory stored the row: one only a single driver could hold.
|
|
15
|
+
* Refused by both, before either — the same place a malformed `uuid` is (`narrowUuid`). Only a
|
|
16
|
+
* `Date` is judged: a repository write is asserted, not parsed, and `timestamp()`'s own parser has
|
|
17
|
+
* made every other spelling a `Date` before a row reaches here.
|
|
18
|
+
*/
|
|
19
|
+
export const assertInstantsCross = (
|
|
20
|
+
columns: Readonly<Record<string, AnyColumn>>,
|
|
21
|
+
row: unknown,
|
|
22
|
+
): void => {
|
|
23
|
+
if (typeof row !== 'object' || row === null) return;
|
|
24
|
+
const record = row as Readonly<Record<string, unknown>>;
|
|
25
|
+
for (const [property, column] of Object.entries(columns)) {
|
|
26
|
+
const kind =
|
|
27
|
+
column.$meta.kind === 'array' ? column.$meta.element?.$meta.kind : column.$meta.kind;
|
|
28
|
+
if (kind !== 'timestamptz') continue;
|
|
29
|
+
const value = record[property];
|
|
30
|
+
const refusedValue = Array.isArray(value) ? value.find(outOfRange) : value;
|
|
31
|
+
if (!outOfRange(refusedValue)) continue;
|
|
32
|
+
refuseColumn(
|
|
33
|
+
'format',
|
|
34
|
+
`${property}: expected an instant in years 0001–9999, ${got(refusedValue)}`,
|
|
35
|
+
"new Date('2026-03-14T09:00:00Z') // timestamp() crosses to Postgres as ISO text with a four-digit year; store null on a .nullable() column for 'never', not a far-off sentinel",
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
};
|