@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/src/instant.ts
CHANGED
|
@@ -131,6 +131,20 @@ const isoInstantMicros = (text: string): bigint | undefined => {
|
|
|
131
131
|
return local - offset * MICROS_PER_MINUTE;
|
|
132
132
|
};
|
|
133
133
|
|
|
134
|
+
/** The first and last milliseconds `toISOString()` writes with a four-digit year, 0001 to 9999. */
|
|
135
|
+
const FIRST_INSTANT_MS = -62_135_596_800_000;
|
|
136
|
+
const LAST_INSTANT_MS = 253_402_300_799_999;
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Whether a `Date` crosses to Postgres. It is bound as its ISO text, and outside years 0001–9999
|
|
140
|
+
* that text is one the server refuses (`22008` for year 0000, `22007`/`22009` for a signed year)
|
|
141
|
+
* while memory stored and compared the value: a row only one driver could hold.
|
|
142
|
+
*/
|
|
143
|
+
export const instantCrosses = (value: Date): boolean => {
|
|
144
|
+
const ms = value.getTime();
|
|
145
|
+
return ms >= FIRST_INSTANT_MS && ms <= LAST_INSTANT_MS;
|
|
146
|
+
};
|
|
147
|
+
|
|
134
148
|
/**
|
|
135
149
|
* The microsecond epoch of whatever a sort key or an operand is holding: a decoded row's `Date`
|
|
136
150
|
* (milliseconds, so the last three digits are zero), a value already counted in microseconds, the
|
package/src/jit-preload.ts
CHANGED
|
@@ -201,8 +201,9 @@ const fill = async <Row>(
|
|
|
201
201
|
try {
|
|
202
202
|
answers = await readByIds(read, chunk);
|
|
203
203
|
} catch (error) {
|
|
204
|
-
// The statement failed, so it fails for everyone it was
|
|
205
|
-
//
|
|
204
|
+
// The statement failed for a reason that is the statement's, so it fails for everyone it was
|
|
205
|
+
// widened to cover. A refused VALUE is not that: `readByIds` isolates the id that carried it
|
|
206
|
+
// (`batch-read.ts`), so the rest are answered as their own statement would have been.
|
|
206
207
|
for (const id of chunk) settlers.get(keyOf(read.key.kind, id))?.({ error });
|
|
207
208
|
continue;
|
|
208
209
|
}
|
package/src/memory-journal.ts
CHANGED
|
@@ -44,6 +44,14 @@ export const enrolMemoryScope = (scope: Tx, tx: Tx | undefined): void => {
|
|
|
44
44
|
if (parent !== undefined) scopes.set(scope, parent);
|
|
45
45
|
};
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Whether a memory `tx` may still take a write — its root has neither committed nor rolled back. A
|
|
49
|
+
* `Tx` the memory transactor never handed out has no root here, so it answers `true`, the same pass
|
|
50
|
+
* `refuseIfMemoryTxClosed` gives it. Off the barrel: `@ultimat3/entity/internal/memory-tx`.
|
|
51
|
+
*/
|
|
52
|
+
export const memoryTxOpen = (tx: Tx): boolean =>
|
|
53
|
+
(scopes.get(tx)?.outcome.value ?? 'open') === 'open';
|
|
54
|
+
|
|
47
55
|
/** The root a memory `tx` belongs to — what a lock is held to — or `tx` itself for any other. */
|
|
48
56
|
export const memoryRoot = (tx: Tx): Tx => scopes.get(tx)?.root ?? tx;
|
|
49
57
|
|
package/src/memory-repo.ts
CHANGED
|
@@ -391,12 +391,13 @@ export const memoryRepo = <Row>(
|
|
|
391
391
|
if (hasJsOnlyInvariant(entity.$invariants)) assertedBound(found.length, 'updateWhere');
|
|
392
392
|
// The WHOLE batch is judged before any row of it lands — the same statement Postgres sends,
|
|
393
393
|
// which refuses as one. A row this batch refuses used to leave the rows before it stored:
|
|
394
|
-
// the write was a loop, and the loop stopped half way through.
|
|
395
|
-
// statement back; here nothing was written yet, so nothing has to be undone.
|
|
394
|
+
// the write was a loop, and the loop stopped half way through.
|
|
396
395
|
const merged = judgeUpdate(entity, found, patch, untouched(found), storeKey);
|
|
397
396
|
for (const row of merged) judgeReferences(row);
|
|
398
|
-
|
|
399
|
-
|
|
397
|
+
// Judged whole, yet each row still meets the rows stored as it lands: one refused undoes the
|
|
398
|
+
// rows before it, as `deleteWhere`'s loop does and as Postgres rolls its statement back.
|
|
399
|
+
const written = undoingBatch(options?.tx, (tx) =>
|
|
400
|
+
merged.map((row, at) => write(row, { ...options, tx }, 'updateWhere', storeKey(found[at]))),
|
|
400
401
|
);
|
|
401
402
|
if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
|
|
402
403
|
return found.length;
|
|
@@ -422,8 +423,10 @@ export const memoryRepo = <Row>(
|
|
|
422
423
|
});
|
|
423
424
|
const merged = judgeUpdateMany(entity, plan, found, untouched(found), storeKey);
|
|
424
425
|
for (const row of merged) judgeReferences(row);
|
|
425
|
-
|
|
426
|
-
|
|
426
|
+
// A batch whose END state is unique can still meet a stored value part way — `c` takes `b`'s
|
|
427
|
+
// slug before `b` lets it go — and Postgres refuses that statement whole: so is this loop.
|
|
428
|
+
const written = undoingBatch(options?.tx, (tx) =>
|
|
429
|
+
merged.map((row, at) => write(row, { ...options, tx }, 'updateMany', storeKey(found[at]))),
|
|
427
430
|
);
|
|
428
431
|
if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
|
|
429
432
|
return written.length;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// `@ultimat3/entity/internal/memory-tx` — whether a memory transaction's root is still open, for
|
|
2
|
+
// `@ultimat3/action`'s settle scope. INTERNAL and a leaf on purpose: the barrel is an app's, and
|
|
3
|
+
// `/adapter` (the driver kit) put ten modules into every role's serve graph; this costs one.
|
|
4
|
+
|
|
5
|
+
export { memoryTxOpen } from './memory-journal';
|
|
@@ -110,7 +110,13 @@ const BACKREFERENCE = [
|
|
|
110
110
|
const GROUP_OPENINGS = ['(?:', '(?=', '(?!', '(?<=', '(?<!'] as const;
|
|
111
111
|
|
|
112
112
|
/** `{n}` `{n,}` `{n,m}`, the three forms both engines read the same way. */
|
|
113
|
-
const QUANTIFIER = /^\{\d+(
|
|
113
|
+
const QUANTIFIER = /^\{(\d+)(?:,(\d*))?\}/;
|
|
114
|
+
|
|
115
|
+
/** ARE's `DUPMAX`: a larger bound is `invalid repetition count(s)` on the server, fine in JS. */
|
|
116
|
+
const MAX_REPEAT = 255;
|
|
117
|
+
|
|
118
|
+
/** `*` `+` `?` `{`: what JavaScript lets repeat a lookahead (Annex B) and ARE refuses outright. */
|
|
119
|
+
const QUANTIFIER_STARTS = new Set(['*', '+', '?', '{']);
|
|
114
120
|
|
|
115
121
|
/**
|
|
116
122
|
* `\uwxyz` is EXACTLY four hex digits in ARE and exactly four in JavaScript without the `u` flag —
|
|
@@ -138,6 +144,17 @@ function escapeAt(source: string, at: number): Step {
|
|
|
138
144
|
const divergent = DIVERGENT_ESCAPES.get(next);
|
|
139
145
|
if (divergent !== undefined) return refuse(`\\${next}`, at, divergent[0], divergent[1]);
|
|
140
146
|
if (next === 'u') {
|
|
147
|
+
const digits = source.slice(at + 2, at + 6);
|
|
148
|
+
// A SURROGATE is how Bun writes an astral literal (`/😀/` is `\uD83D\uDE00`): one character to
|
|
149
|
+
// JavaScript, two lone code points to Postgres, so the CHECK refuses every row the app accepts.
|
|
150
|
+
if (HEX4.test(digits) && /^[Dd][89A-Fa-f]/.test(digits)) {
|
|
151
|
+
return refuse(
|
|
152
|
+
`\\u${digits}`,
|
|
153
|
+
at,
|
|
154
|
+
'is half of a surrogate pair: JavaScript matches the pair as one astral character, Postgres reads two code points no text holds',
|
|
155
|
+
undefined,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
141
158
|
return HEX4.test(source.slice(at + 2))
|
|
142
159
|
? at + 6
|
|
143
160
|
: refuse(
|
|
@@ -186,6 +203,9 @@ function groupAt(source: string, at: number): Step {
|
|
|
186
203
|
const LEADING_BRACKET_WHY =
|
|
187
204
|
'opens a class whose first ] Postgres reads as a MEMBER and JavaScript reads as the close of an empty class';
|
|
188
205
|
|
|
206
|
+
const CHAINED_RANGE_WHY =
|
|
207
|
+
'follows a range or a class escape, which Postgres refuses as an invalid character range and JavaScript reads as a literal -';
|
|
208
|
+
|
|
189
209
|
const RANGE_WHY =
|
|
190
210
|
'is a range whose endpoints Postgres orders by the database COLLATION and JavaScript orders by code point';
|
|
191
211
|
|
|
@@ -196,9 +216,16 @@ function bracketAt(source: string, at: number): Step {
|
|
|
196
216
|
if (source[cursor] === ']') return refuse('[]', at, LEADING_BRACKET_WHY, '\\]');
|
|
197
217
|
/** The last member that could be the lower end of a range; `undefined` after one is consumed. */
|
|
198
218
|
let previous: string | undefined;
|
|
219
|
+
/** A range or a `\d`/`\D` just ended: a `-` here, unless it is last, is ARE's syntax error. */
|
|
220
|
+
let closedSet = false;
|
|
199
221
|
while (cursor < source.length) {
|
|
200
222
|
const char = source[cursor] ?? '';
|
|
201
223
|
if (char === ']') return cursor + 1;
|
|
224
|
+
const upper = source[cursor + 1];
|
|
225
|
+
if (char === '-' && closedSet && upper !== undefined && upper !== ']') {
|
|
226
|
+
return refuse(`-${upper}`, cursor, CHAINED_RANGE_WHY, '\\-');
|
|
227
|
+
}
|
|
228
|
+
closedSet = false;
|
|
202
229
|
if (char === '\u0000') return { ...NUL, at: cursor };
|
|
203
230
|
if (char === '[') {
|
|
204
231
|
const kind = source[cursor + 1] ?? '';
|
|
@@ -218,16 +245,17 @@ function bracketAt(source: string, at: number): Step {
|
|
|
218
245
|
const step = escapeAt(source, cursor);
|
|
219
246
|
if (isRefusal(step)) return step;
|
|
220
247
|
previous = undefined;
|
|
248
|
+
closedSet = source[cursor + 1] === 'd' || source[cursor + 1] === 'D';
|
|
221
249
|
cursor = step;
|
|
222
250
|
continue;
|
|
223
251
|
}
|
|
224
|
-
const upper = source[cursor + 1];
|
|
225
252
|
if (char === '-' && previous !== undefined && upper !== undefined && upper !== ']') {
|
|
226
253
|
if (upper === '\\') {
|
|
227
254
|
const step = escapeAt(source, cursor + 1);
|
|
228
255
|
if (isRefusal(step)) return step;
|
|
229
256
|
if (!isAscii(previous)) return refuse(`${previous}-\\`, cursor - 1, RANGE_WHY, undefined);
|
|
230
257
|
previous = undefined;
|
|
258
|
+
closedSet = true;
|
|
231
259
|
cursor = step;
|
|
232
260
|
continue;
|
|
233
261
|
}
|
|
@@ -235,6 +263,7 @@ function bracketAt(source: string, at: number): Step {
|
|
|
235
263
|
return refuse(`${previous}-${upper}`, cursor - 1, RANGE_WHY, undefined);
|
|
236
264
|
}
|
|
237
265
|
previous = undefined;
|
|
266
|
+
closedSet = true;
|
|
238
267
|
cursor += 2;
|
|
239
268
|
continue;
|
|
240
269
|
}
|
|
@@ -255,23 +284,45 @@ export function unportableConstruct(source: string): UnportablePattern | undefin
|
|
|
255
284
|
let at = 0;
|
|
256
285
|
/** Whether a `{n}` here would be a quantifier at all — it needs something to repeat. */
|
|
257
286
|
let repeatable = false;
|
|
287
|
+
/** Per open group, whether it is a lookaround — closing one leaves nothing ARE will repeat. */
|
|
288
|
+
const groups: boolean[] = [];
|
|
289
|
+
let afterLookaround = false;
|
|
258
290
|
while (at < source.length) {
|
|
259
291
|
const char = source[at] ?? '';
|
|
260
292
|
if (char === '\u0000') return { ...NUL, at };
|
|
293
|
+
if (afterLookaround && QUANTIFIER_STARTS.has(char)) {
|
|
294
|
+
const bound = char === '{' ? QUANTIFIER.exec(source.slice(at)) : null;
|
|
295
|
+
return refuse(
|
|
296
|
+
bound?.[0] ?? char,
|
|
297
|
+
at,
|
|
298
|
+
'repeats a lookaround, which JavaScript allows under Annex B and Postgres refuses as an invalid quantifier operand',
|
|
299
|
+
undefined,
|
|
300
|
+
);
|
|
301
|
+
}
|
|
261
302
|
let step: Step = at + 1;
|
|
262
303
|
if (char === '\\') step = escapeAt(source, at);
|
|
263
304
|
else if (char === '[') step = bracketAt(source, at);
|
|
264
|
-
else if (char === '(')
|
|
265
|
-
|
|
305
|
+
else if (char === '(') {
|
|
306
|
+
step = groupAt(source, at);
|
|
307
|
+
groups.push(source[at + 1] === '?' && source[at + 2] !== ':');
|
|
308
|
+
} else if (char === '{') {
|
|
266
309
|
// `/^{2}$/` compiles in JavaScript under Annex B and is `invalid regular expression` on the
|
|
267
310
|
// server, so the migration is the thing that fails. Refusing here moves it to the line that
|
|
268
311
|
// wrote it — and a `{` with nothing before it is that same error, which is why the quantifier
|
|
269
312
|
// has to be judged in position and not by its own shape.
|
|
270
313
|
const quantifier = repeatable ? QUANTIFIER.exec(source.slice(at)) : null;
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
314
|
+
const bounds = quantifier === null ? [] : [quantifier[1], quantifier[2]];
|
|
315
|
+
const tooLarge = bounds.some((bound) => bound !== undefined && Number(bound) > MAX_REPEAT);
|
|
316
|
+
if (quantifier === null)
|
|
317
|
+
step = refuse('{', at, 'opens no quantifier Postgres can read', '\\{');
|
|
318
|
+
else if (tooLarge) {
|
|
319
|
+
step = refuse(
|
|
320
|
+
quantifier[0],
|
|
321
|
+
at,
|
|
322
|
+
`repeats more than ${MAX_REPEAT} times, which Postgres refuses as an invalid repetition count`,
|
|
323
|
+
undefined,
|
|
324
|
+
);
|
|
325
|
+
} else step = at + quantifier[0].length;
|
|
275
326
|
} else if (char === '.') {
|
|
276
327
|
// `'a\nb' ~ 'a.b'` is TRUE and `/a.b/.test('a\nb')` is false: ARE's `.` matches a newline.
|
|
277
328
|
step = refuse('.', at, 'matches a newline in Postgres and never in JavaScript', '[^\\n\\r]');
|
|
@@ -280,6 +331,7 @@ export function unportableConstruct(source: string): UnportablePattern | undefin
|
|
|
280
331
|
// `^`, `$`, `|` and an opening `(` leave nothing to repeat; everything else does, including a
|
|
281
332
|
// `)` that closed a group and a `]` that closed a class.
|
|
282
333
|
repeatable = char !== '^' && char !== '$' && char !== '|' && char !== '(';
|
|
334
|
+
afterLookaround = char === ')' && groups.pop() === true;
|
|
283
335
|
at = step;
|
|
284
336
|
}
|
|
285
337
|
return undefined;
|
package/src/pg-driver.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
withStatementAttribution,
|
|
18
18
|
} from '@ultimat3/db';
|
|
19
19
|
import { appendOnlyRepo } from './append-only';
|
|
20
|
+
import { asInvariantRefusal } from './check-refusal';
|
|
20
21
|
import { entityNow } from './clock';
|
|
21
22
|
import { coalesceFindById } from './coalesce';
|
|
22
23
|
import { cursorFor, seekFrom } from './cursor';
|
|
@@ -191,12 +192,17 @@ export const postgresRepo = <Row>(
|
|
|
191
192
|
* before the statement, not after), and where a keyed request's write names itself in the WAL
|
|
192
193
|
* (`write-tag.ts`). The one funnel for an autocommit repository write, so it is also where a scope
|
|
193
194
|
* whose caller was already answered stops: the pool does not refuse, and must not (`runOn`).
|
|
195
|
+
* A CHECK refusing the row is the entity's invariant answering, as `insert` answers it.
|
|
194
196
|
*/
|
|
195
197
|
const writing = async <T>(send: () => Promise<T>): Promise<T> => {
|
|
196
198
|
refuseAbandoned();
|
|
197
199
|
forgetPreloaded();
|
|
198
200
|
await stampHistoryActor(entity, config.client !== undefined);
|
|
199
|
-
|
|
201
|
+
try {
|
|
202
|
+
return await taggedWrite(config.client !== undefined, send);
|
|
203
|
+
} catch (error) {
|
|
204
|
+
throw asInvariantRefusal(entity as EntityCore<unknown>, error);
|
|
205
|
+
}
|
|
200
206
|
};
|
|
201
207
|
|
|
202
208
|
/**
|
package/src/pg-sql-aggregate.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// which compiles the row reads they share their predicates with — `conditions()` is imported, never
|
|
4
4
|
// restated, so an aggregate counts exactly the rows the matching read would return.
|
|
5
5
|
|
|
6
|
-
import { identifier, type SqlFragment, sql } from '@ultimat3/db';
|
|
6
|
+
import { identifier, raw, type SqlFragment, sql } from '@ultimat3/db';
|
|
7
7
|
import type { AggregateFn } from './aggregate';
|
|
8
8
|
import { AVG_SCALE } from './aggregate';
|
|
9
9
|
import { kindOf } from './cursor';
|
|
@@ -57,10 +57,32 @@ export const countByStatement = <Row>(
|
|
|
57
57
|
* - `agg_count` — how many non-null values went in, which is what tells `null` ("no rows") from a
|
|
58
58
|
* legitimate zero, and what `avg` divides by.
|
|
59
59
|
*
|
|
60
|
-
* `avg` is `
|
|
61
|
-
*
|
|
60
|
+
* `avg` is `averageSql` rather than the server's own scale, because the in-memory driver has to
|
|
61
|
+
* reach the same digits and "whatever numeric division gives you" is not a rule two
|
|
62
62
|
* implementations can share.
|
|
63
63
|
*/
|
|
64
|
+
/** `10^AVG_SCALE` and its inverse, as literals: the scale is a compile-time constant. */
|
|
65
|
+
const AVG_UNITS = raw(`1${'0'.repeat(AVG_SCALE)}`);
|
|
66
|
+
const AVG_UNIT = raw(`0.${'0'.repeat(AVG_SCALE - 1)}1`);
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The mean at `AVG_SCALE`, rounded ONCE, half away from zero — `averageDecimalText`'s arithmetic
|
|
70
|
+
* (`aggregate.ts`) written in SQL: `floor((2·|sum|·10^6 + count) / (2·count))`, sign restored, and
|
|
71
|
+
* scaled back by a MULTIPLICATION, which `numeric` does exactly.
|
|
72
|
+
*
|
|
73
|
+
* Not `round(avg(col), 6)`: a `numeric` quotient is computed to about sixteen SIGNIFICANT digits,
|
|
74
|
+
* so nineteen-digit `bigint`s left `avg` no fraction at all and it answered `…001.000000` for a
|
|
75
|
+
* mean of `…000.5`. Forcing a wider division scale only moves the defect — a quotient rounded at
|
|
76
|
+
* seven places and again at six rounds `.4545454…` up. `div` never rounds, so there is one rounding
|
|
77
|
+
* and it is this expression's. An empty set divides by NULL and answers NULL, as `avg` did.
|
|
78
|
+
*/
|
|
79
|
+
export const averageSql = (target: SqlFragment, filter: SqlFragment = sql``): SqlFragment => {
|
|
80
|
+
// `::numeric`: `sum(integer)` is an `int8`, and doubling it a million times over is past one.
|
|
81
|
+
const sum = sql`(sum(${target})${filter})::numeric`;
|
|
82
|
+
const count = sql`nullif(count(${target})${filter}, 0)`;
|
|
83
|
+
return sql`(sign(${sum}) * div(2 * abs(${sum}) * ${AVG_UNITS} + ${count}, 2 * ${count}) * ${AVG_UNIT})`;
|
|
84
|
+
};
|
|
85
|
+
|
|
64
86
|
export const aggregateStatement = <Row>(
|
|
65
87
|
entity: EntityCore<Row>,
|
|
66
88
|
plan: QueryPlan,
|
|
@@ -74,7 +96,7 @@ export const aggregateStatement = <Row>(
|
|
|
74
96
|
fn === 'sum'
|
|
75
97
|
? sql`sum(${target})`
|
|
76
98
|
: fn === 'avg'
|
|
77
|
-
?
|
|
99
|
+
? averageSql(target)
|
|
78
100
|
: // An instant crosses as EPOCH MILLISECONDS, never as the session's own text: `::text`
|
|
79
101
|
// prints in the session's zone, and `new Date` on that answered NaN for an offset with
|
|
80
102
|
// seconds (a pre-1937 LMT) and 1999 for year 0099. Not `at time zone 'UTC'` either —
|
package/src/pg-sql-in.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Single responsibility: compile an `in` list to SQL — the `in ($1, …)` it always was, or one array
|
|
2
|
+
// parameter once the list is long enough to spend the statement's bind budget on its own.
|
|
3
|
+
|
|
4
|
+
import { join, type SqlFragment, sql } from '@ultimat3/db';
|
|
5
|
+
import { arrayLiteral } from './pg-row';
|
|
6
|
+
import { bindsAsArray } from './predicate-operand';
|
|
7
|
+
import type { ColumnKind } from './types';
|
|
8
|
+
|
|
9
|
+
/** Nothing matches. `in ()` is a syntax error in Postgres, so an empty set needs a constant. */
|
|
10
|
+
export const NEVER = sql`1 = 0`;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `in` reads a LIST or nothing. A scalar used to be wrapped into a one-element list, which matched
|
|
14
|
+
* a row here that `memoryRepo`'s `matches` refuses outright — 0 rows in memory, 1 in Postgres, from
|
|
15
|
+
* a call `andWhere(column, op, value: unknown)` compiles. One answer, and it is the one
|
|
16
|
+
* `@ultimat3/query`'s `filterClause` already gives: no rows.
|
|
17
|
+
*
|
|
18
|
+
* A NULL bound as a parameter is `col = null`, which is UNKNOWN and therefore excludes the very row
|
|
19
|
+
* the caller listed — while memory's `sameValue(null, null)` includes it. Postgres has no `in` that
|
|
20
|
+
* compares a null as a value, so the list is partitioned and the nulls are asked for as `is null`:
|
|
21
|
+
* the `(… in (…) or … is null)` pair `eq` and `neq` already emit.
|
|
22
|
+
*
|
|
23
|
+
* A list past `IN_LIST_AS_ARRAY_FROM` is `= any($1)`: one parameter, the array literal, typed by
|
|
24
|
+
* the column it is compared to. Bound one by one, 65,536 values are `08P01` — or a dropped
|
|
25
|
+
* connection (measured on `Bun.SQL`: `X_DB_UNAVAILABLE`) — for a list memory answers. The planner
|
|
26
|
+
* reads both spellings as the same `ScalarArrayOpExpr`, so the index serves either.
|
|
27
|
+
*/
|
|
28
|
+
export const inListSql = (
|
|
29
|
+
column: SqlFragment,
|
|
30
|
+
kind: ColumnKind | undefined,
|
|
31
|
+
value: unknown,
|
|
32
|
+
): SqlFragment => {
|
|
33
|
+
if (!Array.isArray(value)) return NEVER;
|
|
34
|
+
const present = value.filter((each) => each !== null && each !== undefined);
|
|
35
|
+
const list =
|
|
36
|
+
present.length === 0
|
|
37
|
+
? undefined
|
|
38
|
+
: bindsAsArray(kind, present.length)
|
|
39
|
+
? sql`${column} = any(${arrayLiteral(present)})`
|
|
40
|
+
: sql`${column} in (${join(present.map((each) => sql`${each}`))})`;
|
|
41
|
+
const nulls = present.length === value.length ? undefined : sql`${column} is null`;
|
|
42
|
+
if (list === undefined) return nulls ?? NEVER;
|
|
43
|
+
return nulls === undefined ? list : sql`(${list} or ${nulls})`;
|
|
44
|
+
};
|
package/src/pg-sql-measures.ts
CHANGED
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
// `pg-sql-aggregate.ts`; the predicates are `pg-sql.ts`'s, imported, never restated.
|
|
4
4
|
|
|
5
5
|
import { identifier, join, type SqlFragment, sql } from '@ultimat3/db';
|
|
6
|
-
import { AVG_SCALE } from './aggregate';
|
|
7
6
|
import { moneyColumns } from './column';
|
|
8
7
|
import { kindOf } from './cursor';
|
|
9
8
|
import type { EntityCore } from './entity';
|
|
10
9
|
import type { PlannedMeasure } from './measures';
|
|
11
10
|
import { columnRef, conditions, predicatesSql, type ReadShape } from './pg-sql';
|
|
11
|
+
import { averageSql } from './pg-sql-aggregate';
|
|
12
12
|
import type { Predicate, QueryPlan } from './tenancy';
|
|
13
13
|
|
|
14
14
|
/** Output names are positional and fixed (`m0`, `u0`, …): a measure's name never reaches SQL. */
|
|
@@ -43,7 +43,7 @@ const measureSql = <Row>(
|
|
|
43
43
|
case 'sum':
|
|
44
44
|
return sql`sum(${target})${filter}`;
|
|
45
45
|
case 'avg':
|
|
46
|
-
return
|
|
46
|
+
return averageSql(target, filter);
|
|
47
47
|
default: {
|
|
48
48
|
const extreme =
|
|
49
49
|
measure.fn === 'min' ? sql`min(${target})${filter}` : sql`max(${target})${filter}`;
|
package/src/pg-sql.ts
CHANGED
|
@@ -12,17 +12,15 @@ import { searchUndeclared } from './feature-errors';
|
|
|
12
12
|
import { microsToIso, seekAlias } from './instant';
|
|
13
13
|
import { operatorUnknown } from './operator';
|
|
14
14
|
import { allColumns, arrayLiteral, columnsOf, physicalName } from './pg-row';
|
|
15
|
+
import { inListSql, NEVER } from './pg-sql-in';
|
|
15
16
|
import { orMembers, predicateNodeInvalid, viaValue } from './predicate-node';
|
|
16
|
-
import { operandFor } from './predicate-operand';
|
|
17
|
+
import { equalsNoValue, operandFor } from './predicate-operand';
|
|
17
18
|
import { viaTarget } from './predicate-screen';
|
|
18
19
|
import type { Predicate, QueryPlan, SortKey } from './tenancy';
|
|
19
20
|
import { isTextContains, textContainsSql } from './text-contains';
|
|
20
21
|
import type { ColumnKind } from './types';
|
|
21
22
|
import { isScopedVia } from './via-scope';
|
|
22
23
|
|
|
23
|
-
/** Nothing matches. `in ()` is a syntax error in Postgres, so an empty set needs a constant. */
|
|
24
|
-
const NEVER = sql`1 = 0`;
|
|
25
|
-
|
|
26
24
|
export interface ReadShape {
|
|
27
25
|
/** Soft-deleted rows are hidden unless the caller asked for them. */
|
|
28
26
|
readonly includeDeleted: boolean;
|
|
@@ -93,27 +91,13 @@ const predicateSql = <Row>(entity: EntityCore<Row>, asked: Predicate): SqlFragme
|
|
|
93
91
|
case 'eq':
|
|
94
92
|
return value === null ? sql`${column} is null` : sql`${column} = ${value}`;
|
|
95
93
|
case 'neq':
|
|
94
|
+
// Text that is no uuid is distinct from every row, the NULL ones included — memory's answer;
|
|
95
|
+
// bound, it was `22P02` (`predicate-operand.ts`).
|
|
96
|
+
if (equalsNoValue(kindOf(entity, predicate.column), value)) return sql`true`;
|
|
96
97
|
// `is distinct from` so a null on either side compares as a value, not as unknown.
|
|
97
98
|
return sql`${column} is distinct from ${value}`;
|
|
98
|
-
case 'in':
|
|
99
|
-
|
|
100
|
-
// matched a row here that `memoryRepo`'s `matches` refuses outright — 0 rows in memory, 1 in
|
|
101
|
-
// Postgres, from a call `andWhere(column, op, value: unknown)` compiles. One answer, and it
|
|
102
|
-
// is the one `@ultimat3/query`'s `filterClause` already gives: no rows.
|
|
103
|
-
if (!Array.isArray(value)) return NEVER;
|
|
104
|
-
// A NULL bound as a parameter is `col = null`, which is UNKNOWN and therefore excludes the
|
|
105
|
-
// very row the caller listed — while memory's `sameValue(null, null)` includes it. Postgres
|
|
106
|
-
// has no `in` that compares a null as a value, so the list is partitioned and the nulls are
|
|
107
|
-
// asked for as `is null`: the `(… in (…) or … is null)` pair `eq` and `neq` already emit.
|
|
108
|
-
const present = value.filter((each) => each !== null && each !== undefined);
|
|
109
|
-
const list =
|
|
110
|
-
present.length === 0
|
|
111
|
-
? undefined
|
|
112
|
-
: sql`${column} in (${join(present.map((e) => sql`${e}`))})`;
|
|
113
|
-
const nulls = present.length === value.length ? undefined : sql`${column} is null`;
|
|
114
|
-
if (list === undefined) return nulls ?? NEVER;
|
|
115
|
-
return nulls === undefined ? list : sql`(${list} or ${nulls})`;
|
|
116
|
-
}
|
|
99
|
+
case 'in':
|
|
100
|
+
return inListSql(column, kindOf(entity, predicate.column), value);
|
|
117
101
|
case 'gt':
|
|
118
102
|
return sql`${column} > ${value}`;
|
|
119
103
|
case 'gte':
|
package/src/predicate-operand.ts
CHANGED
|
@@ -9,21 +9,68 @@ import { got } from './column-values';
|
|
|
9
9
|
import { kindOf } from './cursor';
|
|
10
10
|
import type { EntityCore } from './entity';
|
|
11
11
|
import { EntityError } from './errors';
|
|
12
|
-
import { instantMicros } from './instant';
|
|
12
|
+
import { instantCrosses, instantMicros } from './instant';
|
|
13
13
|
import { isNullish as isNull } from './is-null';
|
|
14
14
|
import type { Predicate } from './tenancy';
|
|
15
15
|
import type { ColumnKind } from './types';
|
|
16
|
+
import { canonicalUuid } from './uuid-text';
|
|
16
17
|
|
|
17
18
|
/** The operators whose operand is compared to the column's value as a value of its kind. */
|
|
18
19
|
const COMPARING: ReadonlySet<string> = new Set(['eq', 'neq', 'in', 'gt', 'gte', 'lt', 'lte']);
|
|
19
20
|
|
|
20
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Postgres has no `like` for these: `integer ~~ unknown`, `uuid ~~ unknown`, `boolean ~~ unknown`
|
|
23
|
+
* are each "operator does not exist" (`42883`), where memory matched the value's text. `bytea` is
|
|
24
|
+
* NOT here: the server has a `bytea ~~ bytea`, so that call answers today and stays answered.
|
|
25
|
+
*/
|
|
26
|
+
const NO_LIKE_KINDS: ReadonlySet<ColumnKind | undefined> = new Set<ColumnKind | undefined>([
|
|
27
|
+
'integer',
|
|
28
|
+
'bigint',
|
|
29
|
+
'numeric',
|
|
30
|
+
'uuid',
|
|
31
|
+
'boolean',
|
|
32
|
+
'timestamptz',
|
|
33
|
+
'date',
|
|
34
|
+
'jsonb',
|
|
35
|
+
'array',
|
|
36
|
+
]);
|
|
37
|
+
|
|
21
38
|
const NUMERIC_KINDS: ReadonlySet<ColumnKind | undefined> = new Set<ColumnKind | undefined>([
|
|
22
39
|
'integer',
|
|
23
40
|
'bigint',
|
|
24
41
|
'numeric',
|
|
25
42
|
]);
|
|
26
43
|
|
|
44
|
+
/** Postgres binds at most this many parameters in one statement (`bulk-write.ts` holds the same). */
|
|
45
|
+
const MAX_BINDS = 65_535;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* An `in` list longer than this crosses as ONE array parameter (`pg-sql-in.ts`). Half the bind
|
|
49
|
+
* budget: every list a statement could carry before still compiles to the `in (…)` it always did,
|
|
50
|
+
* and one past the budget — `08P01`, or a dropped connection — now answers.
|
|
51
|
+
*/
|
|
52
|
+
export const IN_LIST_AS_ARRAY_FROM = 32_768;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The kinds whose `in` list has an array form: each element's text is what the same value bound
|
|
56
|
+
* alone parses to (proved per kind, `predicate-operand.test.ts`). `bytea`, `jsonb` and an array
|
|
57
|
+
* column have no element literal (`arrayElement`, `pg-row.ts`).
|
|
58
|
+
*/
|
|
59
|
+
const ARRAY_BOUND_KINDS: ReadonlySet<ColumnKind | undefined> = new Set<ColumnKind | undefined>([
|
|
60
|
+
'uuid',
|
|
61
|
+
'text',
|
|
62
|
+
'char',
|
|
63
|
+
'boolean',
|
|
64
|
+
'integer',
|
|
65
|
+
'bigint',
|
|
66
|
+
'numeric',
|
|
67
|
+
'timestamptz',
|
|
68
|
+
'date',
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
export const bindsAsArray = (kind: ColumnKind | undefined, length: number): boolean =>
|
|
72
|
+
length >= IN_LIST_AS_ARRAY_FROM && ARRAY_BOUND_KINDS.has(kind);
|
|
73
|
+
|
|
27
74
|
/** What an `int4`/`int8` parameter parses: digits with a sign, surrounding blanks allowed. */
|
|
28
75
|
const INTEGER_TEXT = /^\s*[+-]?\d+\s*$/;
|
|
29
76
|
|
|
@@ -57,8 +104,9 @@ const instantOperand = <Row>(
|
|
|
57
104
|
predicate: Predicate,
|
|
58
105
|
value: unknown,
|
|
59
106
|
): unknown => {
|
|
60
|
-
if (value instanceof Date &&
|
|
61
|
-
|
|
107
|
+
if (value instanceof Date && instantCrosses(value)) return value;
|
|
108
|
+
// Year 0000 is no year to Postgres (`22008`), whatever the offset beside it.
|
|
109
|
+
if (typeof value === 'string' && !DIGITS.test(value) && !value.trim().startsWith('0000-')) {
|
|
62
110
|
const text = value.trim();
|
|
63
111
|
// A calendar date is its midnight; a wall time without seconds gains `:00`: the instant
|
|
64
112
|
// reader asks for both.
|
|
@@ -70,7 +118,7 @@ const instantOperand = <Row>(
|
|
|
70
118
|
throw refused(
|
|
71
119
|
entity,
|
|
72
120
|
predicate,
|
|
73
|
-
`expected an instant — a Date or ISO-8601 text — ${got(value)}`,
|
|
121
|
+
`expected an instant — a Date or ISO-8601 text, in years 0001–9999 — ${got(value)}`,
|
|
74
122
|
`.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
123
|
);
|
|
76
124
|
};
|
|
@@ -133,9 +181,42 @@ const scalarOperand = <Row>(
|
|
|
133
181
|
if (kind === 'timestamptz') return instantOperand(entity, predicate, value);
|
|
134
182
|
if (kind === 'date') return dateOperand(entity, predicate, value);
|
|
135
183
|
if (kind === 'integer' || kind === 'bigint') return integerOperand(entity, predicate, value);
|
|
184
|
+
// Every spelling Postgres parses to the same sixteen bytes is ONE operand: memory compared the
|
|
185
|
+
// text, so a braced or unhyphenated id matched there and nowhere else. Text that is no uuid is
|
|
186
|
+
// left as written — `operandFor` decides what it means for the operators that have an answer.
|
|
187
|
+
if (kind === 'uuid') return canonicalUuid(value) ?? value;
|
|
136
188
|
return value;
|
|
137
189
|
};
|
|
138
190
|
|
|
191
|
+
/**
|
|
192
|
+
* A non-null operand no value of the column's kind can EQUAL: text that is not a uuid, against a
|
|
193
|
+
* `uuid()` column. Postgres refused the parameter itself (`22P02`, a 500 for an id out of a URL)
|
|
194
|
+
* where memory answered "no such row"; both now give memory's answer. `pg-sql.ts` asks this for
|
|
195
|
+
* `neq`, the one operator the rewrite below cannot spell.
|
|
196
|
+
*/
|
|
197
|
+
export const equalsNoValue = (kind: ColumnKind | undefined, value: unknown): boolean =>
|
|
198
|
+
kind === 'uuid' && !isNull(value) && canonicalUuid(value) === undefined;
|
|
199
|
+
|
|
200
|
+
const inList = <Row>(
|
|
201
|
+
entity: EntityCore<Row>,
|
|
202
|
+
predicate: Predicate,
|
|
203
|
+
kind: ColumnKind | undefined,
|
|
204
|
+
list: readonly unknown[],
|
|
205
|
+
): readonly unknown[] => {
|
|
206
|
+
const operands = list
|
|
207
|
+
.map((each: unknown) => scalarOperand(entity, predicate, kind, each))
|
|
208
|
+
.filter((each) => !equalsNoValue(kind, each));
|
|
209
|
+
if (operands.length <= MAX_BINDS || ARRAY_BOUND_KINDS.has(kind)) return operands;
|
|
210
|
+
throw refused(
|
|
211
|
+
entity,
|
|
212
|
+
predicate,
|
|
213
|
+
`${String(operands.length)} values is more than one statement binds (${String(MAX_BINDS)}), and a ${String(kind)} column has no array form to send them as`,
|
|
214
|
+
`for (let at = 0; at < values.length; at += 10_000) await ${entity.$name}.andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, 'in', values.slice(at, at + 10_000)).all() // one statement per slice`,
|
|
215
|
+
);
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const RANGE = new Set(['gt', 'gte', 'lt', 'lte']);
|
|
219
|
+
|
|
139
220
|
/**
|
|
140
221
|
* The predicate with its operand in the one form both drivers read, or a refusal. Every operator
|
|
141
222
|
* outside the comparing set passes through untouched — containment, NULL tests and search have
|
|
@@ -143,18 +224,35 @@ const scalarOperand = <Row>(
|
|
|
143
224
|
*/
|
|
144
225
|
export const operandFor = <Row>(entity: EntityCore<Row>, predicate: Predicate): Predicate => {
|
|
145
226
|
const kind = kindOf(entity, predicate.column);
|
|
146
|
-
if (predicate.op === 'like' &&
|
|
227
|
+
if (predicate.op === 'like' && NO_LIKE_KINDS.has(kind)) {
|
|
228
|
+
const column = renderFixLiteral(predicate.column, "'<column>'");
|
|
147
229
|
throw refused(
|
|
148
230
|
entity,
|
|
149
231
|
predicate,
|
|
150
232
|
`like matches text, and this column is ${String(kind)}`,
|
|
151
|
-
|
|
233
|
+
NUMERIC_KINDS.has(kind)
|
|
234
|
+
? `.andWhere(${column}, 'gte', 100).andWhere(${column}, 'lt', 200) // a number is matched by range, never by pattern`
|
|
235
|
+
: `.andWhere(${column}, 'eq', value) // like reads a text() or char() column; a ${String(kind)} is compared as a value — eq, in, or a gte/lt range`,
|
|
152
236
|
);
|
|
153
237
|
}
|
|
154
238
|
if (!COMPARING.has(predicate.op)) return predicate;
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
239
|
+
if (predicate.op === 'in' && Array.isArray(predicate.value)) {
|
|
240
|
+
return { ...predicate, value: inList(entity, predicate, kind, predicate.value) };
|
|
241
|
+
}
|
|
242
|
+
const value = scalarOperand(entity, predicate, kind, predicate.value);
|
|
243
|
+
// `eq` against a value nothing equals is the empty list both drivers already answer no row for.
|
|
244
|
+
if (predicate.op === 'eq' && equalsNoValue(kind, value)) {
|
|
245
|
+
return { ...predicate, op: 'in', value: [] };
|
|
246
|
+
}
|
|
247
|
+
// A range has no "no row" answer to agree on: memory ordered the text, Postgres refused the
|
|
248
|
+
// parameter (`22P02`). Refused in both, as a fraction against an integer is.
|
|
249
|
+
if (RANGE.has(predicate.op) && equalsNoValue(kind, value)) {
|
|
250
|
+
throw refused(
|
|
251
|
+
entity,
|
|
252
|
+
predicate,
|
|
253
|
+
`expected a uuid for a uuid column, ${got(value)}`,
|
|
254
|
+
`if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) return [] // check the operand before .andWhere(${renderFixLiteral(predicate.column, "'<column>'")}, '${predicate.op}', value): a uuid column orders uuids only`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
159
257
|
return value === predicate.value ? predicate : { ...predicate, value };
|
|
160
258
|
};
|