@ultimat3/entity 31.43.0 → 31.45.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/README.md CHANGED
@@ -486,6 +486,18 @@ never an empty result. The `fix` names the operator meant: `>`→`gt`, `>=`→`g
486
486
  `<=`→`lte`, `=`→`eq`, `!=`/`<>`→`neq`. `isOperator(value)` is the same test, for an op read off
487
487
  the wire.
488
488
 
489
+ An operand is read by the column's kind, once for both drivers (`predicate-operand.ts`):
490
+
491
+ | Column | Operand | Both drivers |
492
+ |---|---|---|
493
+ | `timestamp()` | a `Date` or ISO text with `Z`/an offset | compared as that instant |
494
+ | `timestamp()` | zoneless ISO text (`'2026-01-01'`, `'2026-01-01T10:00'`) | read as UTC in both drivers, never the server's `TimeZone` |
495
+ | `timestamp()` | a number | `X_INVARIANT_VIOLATED` — epoch milliseconds are no instant Postgres parses |
496
+ | `date()` | a `Date` | its UTC calendar date (`plainDateUtc`), as `$parse` writes one |
497
+ | `integer()` / `bigint()` | a fraction (`1.5`, `'1.5'`, `'1e1'`) | `X_INVARIANT_VIOLATED` — round it to the bound you mean |
498
+ | `integer()` / `bigint()` / `decimal()` | any `like` | `X_INVARIANT_VIOLATED` — a number is matched by range |
499
+ | `arrayOf()` | a list, under `eq`/`neq`/`in` | element by element, in order (`array_eq`) |
500
+
489
501
  ## A predicate tree: `andWhereNode`
490
502
 
491
503
  `andWhereNode(node)` (`As of 2026-11`) adds one predicate TREE to a chain, AND-ed with the rest —
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.43.0",
3
+ "version": "31.45.0",
4
4
  "description": "A table + its domain type + invariants the database also enforces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -44,9 +44,9 @@
44
44
  "test": "bun test"
45
45
  },
46
46
  "dependencies": {
47
- "@ultimat3/core": "31.43.0",
48
- "@ultimat3/db": "31.43.0",
49
- "@ultimat3/schema": "31.43.0",
50
- "@ultimat3/time": "31.43.0"
47
+ "@ultimat3/core": "31.45.0",
48
+ "@ultimat3/db": "31.45.0",
49
+ "@ultimat3/schema": "31.45.0",
50
+ "@ultimat3/time": "31.45.0"
51
51
  }
52
52
  }
@@ -20,6 +20,7 @@ import { likeMatches } from './like';
20
20
  import { DECIMAL_TEXT, numericOrder } from './numeric-compare';
21
21
  import { operatorUnknown } from './operator';
22
22
  import { orMembers, predicateNodeInvalid } from './predicate-node';
23
+ import { operandFor } from './predicate-operand';
23
24
  import type { Predicate } from './tenancy';
24
25
  import { isTextContains, textContainsMatches } from './text-contains';
25
26
  import type { ColumnKind } from './types';
@@ -133,28 +134,51 @@ export const sameValueOfKind = (
133
134
  return left === right;
134
135
  };
135
136
 
137
+ /**
138
+ * `col = array[…]` on an `arrayOf()` column: the same length and every element equal IN ORDER, each
139
+ * pair by the element's own kind — Postgres' `array_eq`. `===` compared two array references and
140
+ * matched no row where the database matched one. Unlike `@>`'s element test, a NULL element equals
141
+ * a NULL element here: `array_eq` treats them as equal, `=` inside containment does not.
142
+ */
143
+ const sameArrayOfKind = (
144
+ elementKind: ColumnKind | undefined,
145
+ given: unknown,
146
+ operand: unknown,
147
+ ): boolean =>
148
+ Array.isArray(given) &&
149
+ Array.isArray(operand) &&
150
+ given.length === operand.length &&
151
+ given.every((each: unknown, at) =>
152
+ isNull(each) || isNull(operand[at])
153
+ ? isNull(each) && isNull(operand[at])
154
+ : sameValueOfKind(elementKind, each, operand[at]),
155
+ );
156
+
136
157
  /** One predicate against one stored row, in the meaning the Postgres driver compiles it to. */
137
158
  export const matchesPredicate = <Row>(
138
159
  entity: EntityCore<Row>,
139
160
  row: unknown,
140
- predicate: Predicate,
161
+ asked: Predicate,
141
162
  ): boolean => {
142
163
  // BEFORE anything is read off the row. A full-text match has no in-memory meaning — see
143
164
  // `searchInMemory` — and `valueAt(row, '$search')` would answer `undefined`, which every
144
165
  // comparison below reads as NULL and silently turns into "no rows".
145
- if (predicate.op === 'matches') throw searchInMemory(entity.$name);
166
+ if (asked.op === 'matches') throw searchInMemory(entity.$name);
146
167
  // A group holds when any member does; no member is no row, as Postgres' `1 = 0` answers.
147
- if (predicate.op === 'or') {
148
- return orMembers(predicate).some((member) => matchesPredicate(entity, row, member));
168
+ if (asked.op === 'or') {
169
+ return orMembers(asked).some((member) => matchesPredicate(entity, row, member));
149
170
  }
150
- if (predicate.op === 'and') {
151
- return orMembers(predicate).every((member) => matchesPredicate(entity, row, member));
171
+ if (asked.op === 'and') {
172
+ return orMembers(asked).every((member) => matchesPredicate(entity, row, member));
152
173
  }
153
174
  // A hop needs the target's rows, which one row does not carry: the memory driver resolves it to
154
175
  // an `in` list first (`memory-via.ts`), and a store held in process cannot answer one at all.
155
- if (predicate.op === 'via') {
176
+ if (asked.op === 'via') {
156
177
  throw predicateNodeInvalid(entity.$name, 'a via hop cannot be judged row by row in process');
157
178
  }
179
+ // The operand in the one form `pg-sql.ts` binds too, or the refusal it raises
180
+ // (`predicate-operand.ts`): a zoneless instant, a fraction against an integer column.
181
+ const predicate = operandFor(entity, asked);
158
182
  // The column's declared kind, resolved once — `price.minor` included, which is the path a money
159
183
  // predicate and a money sort key both name.
160
184
  const kind = kindOf(entity, predicate.column);
@@ -175,8 +199,13 @@ export const matchesPredicate = <Row>(
175
199
  * A `money()` column holding NULL reaches this every time, with no hand-built row at all —
176
200
  * `valueAt(row, 'price.minor')` has nothing to read.
177
201
  */
202
+ const elementKind = held?.$meta.element?.$meta.kind;
178
203
  const equals = (candidate: unknown): boolean =>
179
- !rowIsNull && !isNull(candidate) && sameValueOfKind(kind, actual, candidate);
204
+ !rowIsNull &&
205
+ !isNull(candidate) &&
206
+ (kind === 'array'
207
+ ? sameArrayOfKind(elementKind, actual, candidate)
208
+ : sameValueOfKind(kind, actual, candidate));
180
209
  // `col > NULL` is UNKNOWN in SQL and UNKNOWN is not a match, so a NULL on EITHER side matches no
181
210
  // row here either — `predicateSql` emits a bare `"col" > $1` and Postgres returns nothing. Without
182
211
  // this the fall-through compared `String(null)` as the text `"null"`, which sorts after `"5"` and
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 { orMembers, predicateNodeInvalid, viaValue } from './predicate-node';
16
+ import { operandFor } from './predicate-operand';
16
17
  import { viaTarget } from './predicate-screen';
17
18
  import type { Predicate, QueryPlan, SortKey } from './tenancy';
18
19
  import { isTextContains, textContainsSql } from './text-contains';
@@ -76,13 +77,16 @@ const nullTestPath = <Row>(entity: EntityCore<Row>, predicate: Predicate): strin
76
77
  : predicate.column;
77
78
  };
78
79
 
79
- const predicateSql = <Row>(entity: EntityCore<Row>, predicate: Predicate): SqlFragment => {
80
+ const predicateSql = <Row>(entity: EntityCore<Row>, asked: Predicate): SqlFragment => {
80
81
  // BEFORE the column is resolved: a `matches` predicate names `SEARCH_PROPERTY`, and an `or` group
81
82
  // `OR_PROPERTY` — neither is a column, and neither must ever be looked up as one.
82
- if (predicate.op === 'matches') return searchSql(entity, predicate);
83
- if (predicate.op === 'or') return orSql(entity, predicate);
84
- if (predicate.op === 'and') return andSql(entity, predicate);
85
- if (predicate.op === 'via') return viaSql(entity, predicate);
83
+ if (asked.op === 'matches') return searchSql(entity, asked);
84
+ if (asked.op === 'or') return orSql(entity, asked);
85
+ if (asked.op === 'and') return andSql(entity, asked);
86
+ if (asked.op === 'via') return viaSql(entity, asked);
87
+ // The operand memory compares (`predicate-operand.ts`), or the same refusal: a fraction bound to
88
+ // an `int4` parameter was a 500 here and rows there.
89
+ const predicate = operandFor(entity, asked);
86
90
  const column = columnRef(entity, nullTestPath(entity, predicate));
87
91
  const value = predicate.value;
88
92
  switch (predicate.op) {
@@ -0,0 +1,160 @@
1
+ // Single responsibility: a comparison operand, normalised or refused by the column's DECLARED KIND,
2
+ // ONCE for both drivers. `memory-match.ts` and `pg-sql.ts` each call `operandFor` before they read
3
+ // the operand, so an operand whose meaning would depend on the driver never reaches either of them:
4
+ // it is spelled one way, or it is refused with the same code in both.
5
+
6
+ import { renderFixLiteral } from '@ultimat3/core';
7
+ import { plainDateUtc } from '@ultimat3/time';
8
+ import { got } from './column-values';
9
+ import { kindOf } from './cursor';
10
+ import type { EntityCore } from './entity';
11
+ import { EntityError } from './errors';
12
+ import { instantMicros } from './instant';
13
+ import { isNullish as isNull } from './is-null';
14
+ import type { Predicate } from './tenancy';
15
+ import type { ColumnKind } from './types';
16
+
17
+ /** The operators whose operand is compared to the column's value as a value of its kind. */
18
+ const COMPARING: ReadonlySet<string> = new Set(['eq', 'neq', 'in', 'gt', 'gte', 'lt', 'lte']);
19
+
20
+ /** Postgres has no `like` for these: `integer ~~ unknown` is "operator does not exist". */
21
+ const NUMERIC_KINDS: ReadonlySet<ColumnKind | undefined> = new Set<ColumnKind | undefined>([
22
+ 'integer',
23
+ 'bigint',
24
+ 'numeric',
25
+ ]);
26
+
27
+ /** What an `int4`/`int8` parameter parses: digits with a sign, surrounding blanks allowed. */
28
+ const INTEGER_TEXT = /^\s*[+-]?\d+\s*$/;
29
+
30
+ /** A digit string is a cursor's MICROSECOND count to `instantMicros`, and no instant to Postgres. */
31
+ const DIGITS = /^\s*-?\d+\s*$/;
32
+
33
+ const refused = <Row>(
34
+ entity: EntityCore<Row>,
35
+ predicate: Predicate,
36
+ detail: string,
37
+ fix: string,
38
+ ): EntityError =>
39
+ new EntityError({
40
+ code: 'X_INVARIANT_VIOLATED',
41
+ cause: `${entity.$name}.${predicate.column} ${predicate.op}: ${detail}`,
42
+ fix,
43
+ });
44
+
45
+ /** ISO text with no zone: a calendar date, or a date and a wall time. */
46
+ const ZONELESS = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?$/;
47
+
48
+ /**
49
+ * An instant operand is a `Date` or ISO text, read in ONE zone by both drivers. Zoneless text
50
+ * (`'2026-01-01'`, `'2026-01-01T10:00'`) is read as UTC and handed on with its `Z`, so Postgres
51
+ * never reads it in a session `TimeZone` this process cannot know, and memory compares instants,
52
+ * never a `Date`'s text against the operand's (which matched every row). A number is refused: epoch
53
+ * milliseconds bind as digits, which Postgres parses as no instant.
54
+ */
55
+ const instantOperand = <Row>(
56
+ entity: EntityCore<Row>,
57
+ predicate: Predicate,
58
+ value: unknown,
59
+ ): unknown => {
60
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value;
61
+ if (typeof value === 'string' && !DIGITS.test(value)) {
62
+ const text = value.trim();
63
+ // A calendar date is its midnight; a wall time without seconds gains `:00`: the instant
64
+ // reader asks for both.
65
+ const zoned = ZONELESS.test(text)
66
+ ? `${text.replace(' ', 'T')}${text.length === 10 ? 'T00:00:00' : text.length === 16 ? ':00' : ''}Z`
67
+ : value;
68
+ if (instantMicros(zoned) !== undefined) return zoned;
69
+ }
70
+ throw refused(
71
+ entity,
72
+ predicate,
73
+ `expected an instant — a Date or ISO-8601 text — ${got(value)}`,
74
+ `.andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, '${predicate.op}', new Date('2026-01-01T00:00:00Z')) // ISO text without a zone is read as UTC; a calendar date is a date() column`,
75
+ );
76
+ };
77
+
78
+ /**
79
+ * A `Date` against a `date()` column is the calendar date it holds in UTC — `plainDateUtc`, the
80
+ * conversion the column's own `$parse` makes on write. Memory compared the `Date` to the stored
81
+ * `YYYY-MM-DD` as text; Postgres casts it. One spelling, so both compare the same two dates.
82
+ */
83
+ const dateOperand = <Row>(
84
+ entity: EntityCore<Row>,
85
+ predicate: Predicate,
86
+ value: unknown,
87
+ ): unknown => {
88
+ if (!(value instanceof Date)) return value;
89
+ if (!Number.isNaN(value.getTime())) return plainDateUtc(value);
90
+ throw refused(
91
+ entity,
92
+ predicate,
93
+ `expected a calendar date, ${got(value)}`,
94
+ `.andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, '${predicate.op}', '2026-08-22') // a YYYY-MM-DD string or a valid Date`,
95
+ );
96
+ };
97
+
98
+ /**
99
+ * An `integer()`/`bigint()` operand is not a fraction. Postgres binds it as the column's type and
100
+ * fails `1.5` (`X_DB_STATEMENT_FAILED`, a 500) where memory answered rows; refusing here is the one
101
+ * answer both can give, and the caller is the one who knows whether `1.5` meant `1` or `2`.
102
+ */
103
+ const integerOperand = <Row>(
104
+ entity: EntityCore<Row>,
105
+ predicate: Predicate,
106
+ value: unknown,
107
+ ): unknown => {
108
+ // A NUMBER the text spells (`'1.5'`, `'1e1'`) is the same fraction; text that is no number at
109
+ // all is left as written, so Postgres answers its own refusal (`keyOf`'s rule, `batch-read.ts`).
110
+ const fraction =
111
+ typeof value === 'number'
112
+ ? !Number.isInteger(value)
113
+ : typeof value === 'string' &&
114
+ !INTEGER_TEXT.test(value) &&
115
+ value.trim() !== '' &&
116
+ Number.isFinite(Number(value));
117
+ if (!fraction) return value;
118
+ throw refused(
119
+ entity,
120
+ predicate,
121
+ `expected a whole number for an integer column, ${got(value)}`,
122
+ `.andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, '${predicate.op}', Math.ceil(value)) // or Math.floor — pick the bound the fraction meant; the column holds whole numbers`,
123
+ );
124
+ };
125
+
126
+ const scalarOperand = <Row>(
127
+ entity: EntityCore<Row>,
128
+ predicate: Predicate,
129
+ kind: ColumnKind | undefined,
130
+ value: unknown,
131
+ ): unknown => {
132
+ if (isNull(value)) return value;
133
+ if (kind === 'timestamptz') return instantOperand(entity, predicate, value);
134
+ if (kind === 'date') return dateOperand(entity, predicate, value);
135
+ if (kind === 'integer' || kind === 'bigint') return integerOperand(entity, predicate, value);
136
+ return value;
137
+ };
138
+
139
+ /**
140
+ * The predicate with its operand in the one form both drivers read, or a refusal. Every operator
141
+ * outside the comparing set passes through untouched — containment, NULL tests and search have
142
+ * their own rules (`containment.ts`, `is-null.ts`, `search.ts`).
143
+ */
144
+ export const operandFor = <Row>(entity: EntityCore<Row>, predicate: Predicate): Predicate => {
145
+ const kind = kindOf(entity, predicate.column);
146
+ if (predicate.op === 'like' && NUMERIC_KINDS.has(kind)) {
147
+ throw refused(
148
+ entity,
149
+ predicate,
150
+ `like matches text, and this column is ${String(kind)}`,
151
+ `.andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, 'gte', 100).andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, 'lt', 200) // a number is matched by range, never by pattern`,
152
+ );
153
+ }
154
+ if (!COMPARING.has(predicate.op)) return predicate;
155
+ const value =
156
+ predicate.op === 'in' && Array.isArray(predicate.value)
157
+ ? predicate.value.map((each: unknown) => scalarOperand(entity, predicate, kind, each))
158
+ : scalarOperand(entity, predicate, kind, predicate.value);
159
+ return value === predicate.value ? predicate : { ...predicate, value };
160
+ };