uql-orm 0.102.0 → 0.102.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/browser/uql-browser.min.js +2 -2
  2. package/dist/browser/uql-browser.min.js.map +3 -3
  3. package/dist/dialect/abstractDialect.js +2 -1
  4. package/dist/dialect/abstractSqlDialect.d.ts +49 -27
  5. package/dist/dialect/abstractSqlDialect.js +83 -42
  6. package/dist/dialect/aliases.d.ts +10 -0
  7. package/dist/dialect/aliases.js +26 -16
  8. package/dist/dialect/jsonSql.d.ts +14 -7
  9. package/dist/dialect/jsonSql.js +16 -10
  10. package/dist/dialect/mysqlLikeSqlDialect.d.ts +5 -8
  11. package/dist/dialect/mysqlLikeSqlDialect.js +14 -12
  12. package/dist/dialect/pgLikeSqlDialect.d.ts +21 -13
  13. package/dist/dialect/pgLikeSqlDialect.js +41 -30
  14. package/dist/dialect/queryJoins.d.ts +1 -1
  15. package/dist/mariadb/mariaDialect.d.ts +2 -2
  16. package/dist/mariadb/mariaDialect.js +2 -2
  17. package/dist/mongodb/mongoDialect.d.ts +10 -13
  18. package/dist/mongodb/mongoDialect.js +139 -96
  19. package/dist/mssql/mssqlDialect.d.ts +22 -10
  20. package/dist/mssql/mssqlDialect.js +54 -35
  21. package/dist/mysql/mysqlDialect.js +1 -1
  22. package/dist/querier/abstractQuerier.js +1 -2
  23. package/dist/querier/cursorStream.js +1 -2
  24. package/dist/sqlite/localSqliteQuerierPool.js +8 -2
  25. package/dist/sqlite/sqliteDialect.d.ts +4 -4
  26. package/dist/sqlite/sqliteDialect.js +10 -8
  27. package/dist/turso/tursoLocalDialect.d.ts +3 -1
  28. package/dist/turso/tursoLocalDialect.js +9 -0
  29. package/dist/type/entity.d.ts +34 -12
  30. package/dist/type/utility.d.ts +2 -0
  31. package/dist/util/dialect.util.d.ts +29 -2
  32. package/dist/util/dialect.util.js +154 -4
  33. package/dist/util/field.util.d.ts +2 -0
  34. package/dist/util/field.util.js +5 -0
  35. package/dist/util/object.util.d.ts +3 -1
  36. package/dist/util/object.util.js +4 -0
  37. package/package.json +7 -7
  38. package/skills/uql-orm/SKILL.md +3 -3
@@ -6,62 +6,72 @@
6
6
  */
7
7
  export const OWNED_PREFIX = '_uql';
8
8
  /** The column a paged read carries its own unpaged total in, from `COUNT(*) OVER ()`. */
9
- export const TOTAL_ALIAS = '_uql_total';
9
+ export const TOTAL_ALIAS = `${OWNED_PREFIX}_total`;
10
10
  /**
11
11
  * The derived table a statement wraps the rows it counts or aggregates in: a page, a `$distinct` set, or
12
12
  * rows computing an inlined field an aggregate names. MySQL requires the alias.
13
13
  */
14
- export const ROWS_ALIAS = '_uql_rows';
14
+ export const ROWS_ALIAS = `${OWNED_PREFIX}_rows`;
15
15
  /** The derived table a capped relation aggregate reads: the page is taken first, then aggregated over. */
16
- export const AGGREGATE_PAGE_ALIAS = '_uql_page';
16
+ export const AGGREGATE_PAGE_ALIAS = `${OWNED_PREFIX}_page`;
17
17
  /**
18
18
  * The one value a statement that aggregates answers under: a `COUNT(*)` or an estimate, the column a
19
19
  * capped page carries out for the aggregate wrapping it, and the field a MongoDB `$group` or `$count`
20
20
  * leaves its result in. One name, since both ends of each are written and read here.
21
21
  */
22
- export const AGGREGATE_VALUE_ALIAS = '_uql_value';
22
+ export const AGGREGATE_VALUE_ALIAS = `${OWNED_PREFIX}_value`;
23
23
  /** Beside each MongoDB `$sum`, how many values it read: `$sum` answers 0 over none, where SQL answers null. */
24
- export const SUM_COUNT_ALIAS = '_uql_count';
24
+ export const SUM_COUNT_ALIAS = `${OWNED_PREFIX}_count`;
25
25
  /** The row a Postgres relation aggregates whole: a LATERAL projection of the columns it answers under. */
26
- export const RELATION_ROW_ALIAS = '_uql_row';
26
+ export const RELATION_ROW_ALIAS = `${OWNED_PREFIX}_row`;
27
27
  /** The alias an exploded JSON array element is read through, `_uql_elem_2` and on where one nests in another. */
28
- export const JSON_ELEM_ALIAS = '_uql_elem';
28
+ export const JSON_ELEM_ALIAS = `${OWNED_PREFIX}_elem`;
29
29
  /** The alias a `$pull` reads its surviving elements through, kept distinct from {@link JSON_ELEM_ALIAS}. */
30
- export const JSON_PULL_ALIAS = '_uql_pull';
30
+ export const JSON_PULL_ALIAS = `${OWNED_PREFIX}_pull`;
31
+ /** The key a JSON write aims at where it writes nothing, there being none by that name, nor any key in an array. */
32
+ export const JSON_SKIP_KEY = `${OWNED_PREFIX}_skip`;
33
+ /** What a savepoint the querier names is called, its depth appended. */
34
+ export const SAVEPOINT_PREFIX = `${OWNED_PREFIX}_sp`;
35
+ /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
36
+ export const CURSOR_ALIAS = `${OWNED_PREFIX}_cursor`;
37
+ /** The SQL Server table variable an `OUTPUT` fills. */
38
+ export const OUTPUT_TABLE = `@${OWNED_PREFIX}_output`;
31
39
  /** The field a MongoDB `$sort` by `$text` reads `textScore` from where it projects none, taken back out after. */
32
- export const TEXT_SCORE_ALIAS = '_uql_text_score';
40
+ export const TEXT_SCORE_ALIAS = `${OWNED_PREFIX}_text_score`;
33
41
  /**
34
42
  * The field a MongoDB `$sort` placing nulls orders by first: 1 where the value is null or missing, 0
35
43
  * where it is not. MongoDB takes no `NULLS FIRST`, so the placement is this flag plus the sort on it.
36
44
  * A dot becomes `_o` and an underscore `__`, so two paths such as `a.b` and `a_b` never share a flag.
37
45
  */
38
46
  export function nullsSortField(path) {
39
- return `_uql_nulls_${path.replace(/[._]/g, (char) => (char === '.' ? '_o' : '__'))}`;
47
+ return `${OWNED_PREFIX}_nulls_${path.replace(/[._]/g, (char) => (char === '.' ? '_o' : '__'))}`;
40
48
  }
41
49
  /** Prefix for the field a MongoDB relation lookup parks its result on, one per condition. */
42
- export const REL_TEMP_PREFIX = '_uql_rel_';
50
+ export const REL_TEMP_PREFIX = `${OWNED_PREFIX}_rel_`;
51
+ /** Prefix for the field a MongoDB lookup puts a relation's rows on where a stored field has the relation's name. */
52
+ export const REL_FIELD_PREFIX = `${OWNED_PREFIX}_joined_`;
43
53
  /** The field a ManyToMany lookup nests its target match under, inside the junction's own pipeline. */
44
- export const REL_NESTED_KEY = '_uql_target';
54
+ export const REL_NESTED_KEY = `${OWNED_PREFIX}_target`;
45
55
  /**
46
56
  * The alias MySQL's upsert gives the row being inserted, so its `ON DUPLICATE KEY UPDATE`
47
57
  * assignments read `_uql_new.col` instead of the deprecated `VALUES(col)`. MariaDB has no such
48
58
  * syntax and reads `VALUE(col)`.
49
59
  */
50
- export const UPSERT_NEW_ROW_ALIAS = '_uql_new';
60
+ export const UPSERT_NEW_ROW_ALIAS = `${OWNED_PREFIX}_new`;
51
61
  /** The row source a `MERGE` upsert reads its incoming values from, on SQL Server and Oracle. */
52
- export const UPSERT_SOURCE_ALIAS = '_uql_src';
62
+ export const UPSERT_SOURCE_ALIAS = `${OWNED_PREFIX}_src`;
53
63
  /**
54
64
  * Where a `$sort` by a relation's aggregate - its size, or its nearest row - parks the value until the
55
65
  * ordering has run. A function, so the `$sort` that names the field and the stage that produces it cannot
56
66
  * spell it differently - MongoDB ranks a field that is not there as all-equal, so a drift would go unnoticed.
57
67
  */
58
68
  export function sortAggregateField({ op, relation, field }) {
59
- return `_uql_sort_${op.slice(1)}_${relation}${field ? `_${field}` : ''}`;
69
+ return `${OWNED_PREFIX}_sort_${op.slice(1)}_${relation}${field ? `_${field}` : ''}`;
60
70
  }
61
71
  /**
62
72
  * The column a relation's rows carry one sort term out in, beside the columns they answer under, for
63
73
  * the aggregate reading them to order by: `_uql_sort_createdAt`.
64
74
  */
65
75
  export function relationSortColumn(path) {
66
- return `_uql_sort_${path}`;
76
+ return `${OWNED_PREFIX}_sort_${path}`;
67
77
  }
@@ -4,6 +4,14 @@ import type { FieldOptions, FieldType } from '../type/index.js';
4
4
  * accessor such as `[#]` or `[*]`.
5
5
  */
6
6
  export declare function jsonPath(path: string, suffix?: string): string;
7
+ /** `then`, or `skip` where the condition `unless` holds. */
8
+ export declare function unlessThen(unless: string | undefined, skip: string, then: string): string;
9
+ /** `path`, or a key no document has, which a write leaves alone, where the condition `unless` holds. */
10
+ export declare function skippablePath(path: string, unless: string | undefined): string;
11
+ /** A key a JSON update writes, and the value it writes there, NULL where the stored one stays. */
12
+ export type JsonKeyWrite = readonly [slot: JsonSlot, value: string];
13
+ /** The JSON values a path can be asked to hold, beside a scalar. */
14
+ export type JsonContainer = 'array' | 'object';
7
15
  /** A JSON value a condition reads: `path` of the JSON in `base`, `''` for all of it. */
8
16
  export type JsonSlot = {
9
17
  readonly base: string;
@@ -25,13 +33,14 @@ export declare function groupsPerCall(maxArgs: number, size: number): number;
25
33
  */
26
34
  export declare function chainedCall(fn: string, target: string, groups: readonly string[], size: number, maxArgs: number): string;
27
35
  /**
28
- * `JSON_SET(target, path, value, ...)`, which MySQL and SQLite share, nested past `maxArgs`. `pathSuffix`
29
- * appends an accessor per key (SQLite's `[#]` append). Values bind in key order through `bindValue`.
36
+ * `JSON_SET(target, path, value, ...)`, which MySQL and SQLite share, nested past `maxArgs`. Values bind in
37
+ * key order through `bindValue`.
30
38
  */
31
- export declare function jsonSetCall(bindValue: (value: unknown) => string, target: string, entries: Record<string, unknown>, maxArgs: number, pathSuffix?: string): string;
39
+ export declare function jsonSetCall(bindValue: (value: unknown) => string, target: string, entries: Record<string, unknown>, maxArgs: number): string;
32
40
  /**
33
- * The target a `$set` builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL one goes in bare,
34
- * which keeps MySQL's partial in-place JSON update, since that needs the column itself as `JSON_SET`'s input.
41
+ * The document a JSON update writing keys builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL
42
+ * one goes in bare, which keeps MySQL's partial in-place JSON update, since that needs the column itself as
43
+ * `JSON_SET`'s input.
35
44
  */
36
45
  export declare function jsonSetTarget(expr: string, field: FieldOptions | undefined, empty: string): string;
37
46
  /** `JSON_REMOVE(expr, path, ...)`, which MySQL and SQLite share, nested past `maxArgs`. */
@@ -57,5 +66,3 @@ export declare function jsonCompareMode(value: unknown): JsonAccessMode;
57
66
  export declare function jsonTypeMode(type: FieldType): JsonAccessMode;
58
67
  /** Whether `value` asks for more than JSON containment: an operator map anywhere in it. */
59
68
  export declare function holdsOperator(value: unknown): boolean;
60
- /** A value an array element is matched to by JSON containment: a string, a finite number or a boolean. */
61
- export declare function isJsonScalar(value: unknown): value is string | number | boolean;
@@ -1,6 +1,7 @@
1
1
  import { isOperatorMap } from '../util/dialect.util.js';
2
2
  import { columnFamily, jsonPathKeys } from '../util/field.util.js';
3
3
  import { isOperatorKey, someKey } from '../util/object.util.js';
4
+ import { JSON_SKIP_KEY } from './aliases.js';
4
5
  /**
5
6
  * A `'$.a.b'` JSON path literal, and `'$'` for an empty path, the document itself. `suffix` appends an
6
7
  * accessor such as `[#]` or `[*]`.
@@ -9,6 +10,14 @@ export function jsonPath(path, suffix = '') {
9
10
  const segments = path && `.${jsonPathKeys(path).join('.')}`;
10
11
  return `'$${segments}${suffix}'`;
11
12
  }
13
+ /** `then`, or `skip` where the condition `unless` holds. */
14
+ export function unlessThen(unless, skip, then) {
15
+ return unless === undefined ? then : `CASE WHEN ${unless} THEN ${skip} ELSE ${then} END`;
16
+ }
17
+ /** `path`, or a key no document has, which a write leaves alone, where the condition `unless` holds. */
18
+ export function skippablePath(path, unless) {
19
+ return unlessThen(unless, jsonPath(JSON_SKIP_KEY), path);
20
+ }
12
21
  /** `base, '$.a.b'`, how `JSON_EACH`, `OPENJSON` and the like take the value at `slot`: no path for the whole document. */
13
22
  export function jsonSlotArgs({ base, path }) {
14
23
  return path ? `${base}, ${jsonPath(path)}` : base;
@@ -38,16 +47,17 @@ export function chainedCall(fn, target, groups, size, maxArgs) {
38
47
  return call;
39
48
  }
40
49
  /**
41
- * `JSON_SET(target, path, value, ...)`, which MySQL and SQLite share, nested past `maxArgs`. `pathSuffix`
42
- * appends an accessor per key (SQLite's `[#]` append). Values bind in key order through `bindValue`.
50
+ * `JSON_SET(target, path, value, ...)`, which MySQL and SQLite share, nested past `maxArgs`. Values bind in
51
+ * key order through `bindValue`.
43
52
  */
44
- export function jsonSetCall(bindValue, target, entries, maxArgs, pathSuffix = '') {
45
- const pairs = Object.entries(entries).map(([key, value]) => `${jsonPath(key, pathSuffix)}, ${bindValue(value)}`);
53
+ export function jsonSetCall(bindValue, target, entries, maxArgs) {
54
+ const pairs = Object.entries(entries).map(([key, value]) => `${jsonPath(key)}, ${bindValue(value)}`);
46
55
  return chainedCall('JSON_SET', target, pairs, 2, maxArgs);
47
56
  }
48
57
  /**
49
- * The target a `$set` builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL one goes in bare,
50
- * which keeps MySQL's partial in-place JSON update, since that needs the column itself as `JSON_SET`'s input.
58
+ * The document a JSON update writing keys builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL
59
+ * one goes in bare, which keeps MySQL's partial in-place JSON update, since that needs the column itself as
60
+ * `JSON_SET`'s input.
51
61
  */
52
62
  export function jsonSetTarget(expr, field, empty) {
53
63
  return field?.nullable === false ? expr : `COALESCE(${expr}, ${empty})`;
@@ -94,7 +104,3 @@ export function holdsOperator(value) {
94
104
  }
95
105
  return isOperatorMap(value) && someKey(value, (key) => isOperatorKey(key) || holdsOperator(value[key]));
96
106
  }
97
- /** A value an array element is matched to by JSON containment: a string, a finite number or a boolean. */
98
- export function isJsonScalar(value) {
99
- return typeof value === 'string' || typeof value === 'boolean' || Number.isFinite(value);
100
- }
@@ -1,6 +1,6 @@
1
1
  import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type, UpdatePayload, TransactionOptions } from '../type/index.js';
2
2
  import { AbstractSqlDialect, type DerivedRelation, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
3
- import { type JsonSlot } from './jsonSql.js';
3
+ import { type JsonContainer, type JsonSlot } from './jsonSql.js';
4
4
  /** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
5
5
  export declare const MYSQL_ROW_LOCKS: RowLockFeatures;
6
6
  /** The features of MySQL, which MariaDB starts from. */
@@ -95,12 +95,8 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
95
95
  /** `DOUBLE`, never a bare `DECIMAL`, which is `DECIMAL(10,0)` and rounds `1.4` to `1`. */
96
96
  protected numericCast(expr: string): string;
97
97
  neExpr(field: string, ph: string): string;
98
- /**
99
- * `JSON_MERGE_PRESERVE` concatenates arrays and creates absent keys, so every pushed key is
100
- * handled in one call that references `expr` once - unlike `JSON_ARRAY_APPEND`, which needs a
101
- * second reference for the array source and returns NULL on MariaDB for an absent key.
102
- */
103
- protected jsonPush(ctx: QueryContext, expr: string, push: Record<string, unknown>): string;
98
+ /** A guarded one merges an array of it or of nothing, since MariaDB answers `JSON_ARRAY_APPEND` at a skipping path with NULL. */
99
+ protected jsonAppended(ctx: QueryContext, array: string, value: unknown, unless?: string): string;
104
100
  /**
105
101
  * `->` for the value and `->>` for its text, each taking the whole path (`'$.a.b'`): a bare key, as
106
102
  * Postgres chains them, is "Invalid JSON path expression" here.
@@ -110,7 +106,8 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
110
106
  protected jsonContains(ctx: QueryContext, slot: JsonSlot, values: readonly unknown[]): string;
111
107
  /** Only an array's, where `JSON_LENGTH` counts a scalar as 1 and an object by its keys. */
112
108
  protected jsonLength(slot: JsonSlot): string;
113
- protected jsonIsArray(slot: JsonSlot): string;
109
+ protected jsonIs(slot: JsonSlot, kind: JsonContainer): string;
110
+ protected jsonIsNull(slot: JsonSlot): string;
114
111
  /**
115
112
  * Each element of the array at the path as one `JSON` column, which any path then reads the way it reads
116
113
  * a column's document.
@@ -4,7 +4,7 @@ import { escapeMysqlSqlLiteral } from '../util/sqlLiteral.js';
4
4
  import { ANSI_SQL_VALUES, AbstractSqlDialect, isolationSetBefore, } from './abstractSqlDialect.js';
5
5
  import { AGGREGATE_VALUE_ALIAS } from './aliases.js';
6
6
  import { BYTES_PREFIX } from './hydrateColumn.js';
7
- import { jsonPath } from './jsonSql.js';
7
+ import { jsonPath, unlessThen } from './jsonSql.js';
8
8
  import { aggregatesRelations } from './queryJoins.js';
9
9
  /**
10
10
  * The largest `BIGINT UNSIGNED`: the row count MySQL's manual gives for "all rows from the offset on",
@@ -219,14 +219,13 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
219
219
  // MySQL/MariaDB null-safe inequality: true when values differ or one side is NULL.
220
220
  return `NOT (${field} <=> ${ph})`;
221
221
  }
222
- /**
223
- * `JSON_MERGE_PRESERVE` concatenates arrays and creates absent keys, so every pushed key is
224
- * handled in one call that references `expr` once - unlike `JSON_ARRAY_APPEND`, which needs a
225
- * second reference for the array source and returns NULL on MariaDB for an absent key.
226
- */
227
- jsonPush(ctx, expr, push) {
228
- const entries = Object.entries(push).map(([key, value]) => `'${key}', JSON_ARRAY(${this.jsonScalarParam(ctx, value)})`);
229
- return `JSON_MERGE_PRESERVE(${expr}, JSON_OBJECT(${entries.join(', ')}))`;
222
+ /** A guarded one merges an array of it or of nothing, since MariaDB answers `JSON_ARRAY_APPEND` at a skipping path with NULL. */
223
+ jsonAppended(ctx, array, value, unless) {
224
+ if (unless === undefined) {
225
+ return `JSON_ARRAY_APPEND(${array}, '$', ${this.jsonScalarParam(ctx, value)})`;
226
+ }
227
+ const added = unlessThen(unless, this.jsonEmptyArray, `JSON_ARRAY(${this.jsonScalarParam(ctx, value)})`);
228
+ return `JSON_MERGE_PRESERVE(${array}, ${added})`;
230
229
  }
231
230
  /**
232
231
  * `->` for the value and `->>` for its text, each taking the whole path (`'$.a.b'`): a bare key, as
@@ -241,10 +240,13 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
241
240
  }
242
241
  /** Only an array's, where `JSON_LENGTH` counts a scalar as 1 and an object by its keys. */
243
242
  jsonLength(slot) {
244
- return `CASE WHEN ${this.jsonIsArray(slot)} THEN JSON_LENGTH(${this.jsonValue(slot)}) END`;
243
+ return `CASE WHEN ${this.jsonIs(slot, 'array')} THEN JSON_LENGTH(${this.jsonValue(slot)}) END`;
244
+ }
245
+ jsonIs(slot, kind) {
246
+ return `JSON_TYPE(${this.jsonValue(slot)}) = '${kind.toUpperCase()}'`;
245
247
  }
246
- jsonIsArray(slot) {
247
- return `JSON_TYPE(${this.jsonValue(slot)}) = 'ARRAY'`;
248
+ jsonIsNull(slot) {
249
+ return `COALESCE(JSON_TYPE(${this.jsonValue(slot)}), 'NULL') = 'NULL'`;
248
250
  }
249
251
  /**
250
252
  * Each element of the array at the path as one `JSON` column, which any path then reads the way it reads
@@ -4,7 +4,7 @@ import { type DriverCapabilities, type EntityMeta, type FieldOptions, type JsonC
4
4
  import type { DialectOptions } from './abstractDialect.js';
5
5
  import { AbstractSqlDialect, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
6
6
  import { type HydrateKind } from './hydrateColumn.js';
7
- import { type JsonAccessMode, type JsonSlot } from './jsonSql.js';
7
+ import { type JsonAccessMode, type JsonContainer, type JsonKeyWrite, type JsonSlot } from './jsonSql.js';
8
8
  /** A Postgres-wire dialect's options: the base's, and how its driver binds a parameter. */
9
9
  export type PgLikeDialectOptions = DialectOptions & {
10
10
  readonly driverCapabilities?: Partial<DriverCapabilities>;
@@ -95,7 +95,8 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
95
95
  protected jsonLength(slot: JsonSlot): string;
96
96
  /** Each element stays `jsonb`, so it is read as any path is: `->` for the value, `->>` for its text. */
97
97
  protected jsonElemFrom(slot: JsonSlot, alias: string): string;
98
- protected jsonIsArray(slot: JsonSlot): string;
98
+ protected jsonIs(slot: JsonSlot, kind: JsonContainer): string;
99
+ protected jsonIsNull(slot: JsonSlot): string;
99
100
  /** The array at `slot`, NULL where the value there is none: the array functions fail the whole read on one. */
100
101
  private jsonArray;
101
102
  protected jsonElemDoc(alias: string): string;
@@ -121,19 +122,26 @@ export declare abstract class PgLikeSqlDialect extends AbstractSqlDialect {
121
122
  * `[1,0,2]` every other type takes is rejected as "invalid input syntax for type sparsevec".
122
123
  */
123
124
  protected appendVectorValue(ctx: QueryContext, value: readonly unknown[], field?: FieldOptions): void;
125
+ /** `WITH ORDINALITY` numbers each element, which the aggregate orders by to keep the survivors in their order. */
126
+ protected jsonKeptFrom(slot: JsonSlot): string;
127
+ protected jsonKeptAggregate(): string;
128
+ /** Each key or dotted path set as `jsonb`, which `JSONB_SET` takes and nothing else. */
129
+ protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>): string;
124
130
  /**
125
- * `create_if_missing => false` keeps an absent key (and a NULL column) untouched, and a value that is no
126
- * array is set back as it is; `WITH ORDINALITY` keeps the surviving elements in their original order.
131
+ * A value as `jsonb` inside a document: a null one JSON's, as `JSONB_SET` and a comparison need, and a `sql()`
132
+ * one read back out of an object, since `TO_JSONB` refuses an untyped literal.
127
133
  */
128
- protected jsonPullKey(ctx: QueryContext, expr: string, escapedCol: string, key: string, value: unknown): string;
129
- /**
130
- * The plain values merge as one bound object; a `sql()` one is an SQL expression rather than JSON,
131
- * so it merges through `JSONB_BUILD_OBJECT` and is evaluated in place - stringified with the rest,
132
- * it would land as `{}`.
133
- */
134
- protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>, field?: FieldOptions): string;
135
- /** The only fragment that references `expr` twice - safe here because placeholders are numbered. */
136
- protected jsonPush(ctx: QueryContext, expr: string, push: Record<string, unknown>): string;
134
+ private jsonbOf;
135
+ /** `JSONB_BUILD_ARRAY` takes any type, and a NULL as JSON's null. */
136
+ protected jsonAppended(ctx: QueryContext, array: string, value: unknown, unless?: string): string;
137
+ protected readonly jsonEmptyObject = "'{}'::jsonb";
138
+ protected readonly jsonEmptyArray = "'[]'::jsonb";
139
+ /** `JSONB_SET` takes one path, so each key wraps the last. */
140
+ protected jsonWriteKeys(expr: string, writes: readonly JsonKeyWrite[], { create }: {
141
+ create: boolean;
142
+ }): string;
143
+ /** A replace hands an absent key's NULL back, which `JSONB_SET` would answer for the whole document. */
144
+ private jsonSetKey;
137
145
  protected jsonUnset(ctx: QueryContext, expr: string, unset: readonly string[]): string;
138
146
  /** Postgres binds JSON with a numbered placeholder and an explicit cast, per driver capability. */
139
147
  protected jsonScalarParam(ctx: QueryContext, value: unknown): string;
@@ -6,7 +6,7 @@ import { escapePgSqlLiteral, PG_UTC } from '../util/sqlLiteral.js';
6
6
  import { ANSI_SQL_VALUES, AbstractSqlDialect, } from './abstractSqlDialect.js';
7
7
  import { JSON_PULL_ALIAS, RELATION_ROW_ALIAS } from './aliases.js';
8
8
  import { BYTES_PREFIX } from './hydrateColumn.js';
9
- import { jsonSetTarget } from './jsonSql.js';
9
+ import { unlessThen } from './jsonSql.js';
10
10
  import { resolveVectorCast, toSparsevecLiteral } from './vectorCast.js';
11
11
  /** Each metric's pgvector distance operator, and the infix of the operator class its index is built with. */
12
12
  export const PG_VECTOR_METRICS = new Map([
@@ -206,12 +206,15 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
206
206
  jsonElemFrom(slot, alias) {
207
207
  return `JSONB_ARRAY_ELEMENTS(${this.jsonArray(slot)}) AS ${alias}`;
208
208
  }
209
- jsonIsArray(slot) {
210
- return `JSONB_TYPEOF(${this.jsonValue(slot)}) = 'array'`;
209
+ jsonIs(slot, kind) {
210
+ return `JSONB_TYPEOF(${this.jsonValue(slot)}) = '${kind}'`;
211
+ }
212
+ jsonIsNull(slot) {
213
+ return `COALESCE(JSONB_TYPEOF(${this.jsonValue(slot)}), 'null') = 'null'`;
211
214
  }
212
215
  /** The array at `slot`, NULL where the value there is none: the array functions fail the whole read on one. */
213
216
  jsonArray(slot) {
214
- return `CASE WHEN ${this.jsonIsArray(slot)} THEN ${this.jsonValue(slot)} END`;
217
+ return `CASE WHEN ${this.jsonIs(slot, 'array')} THEN ${this.jsonValue(slot)} END`;
215
218
  }
216
219
  jsonElemDoc(alias) {
217
220
  return alias;
@@ -275,40 +278,48 @@ export class PgLikeSqlDialect extends AbstractSqlDialect {
275
278
  ctx.addValue(vectorType === 'sparsevec' ? toSparsevecLiteral(value) : `[${value.join(',')}]`);
276
279
  ctx.append(`::${vectorType}`);
277
280
  }
278
- /**
279
- * `create_if_missing => false` keeps an absent key (and a NULL column) untouched, and a value that is no
280
- * array is set back as it is; `WITH ORDINALITY` keeps the surviving elements in their original order.
281
- */
282
- jsonPullKey(ctx, expr, escapedCol, key, value) {
283
- const slot = { base: escapedCol, path: key };
284
- const kept = `SELECT JSONB_AGG(${JSON_PULL_ALIAS}.val ORDER BY ${JSON_PULL_ALIAS}.ord) FROM JSONB_ARRAY_ELEMENTS(${this.jsonValue(slot)}) WITH ORDINALITY AS ${JSON_PULL_ALIAS}(val, ord) WHERE ${JSON_PULL_ALIAS}.val <> ${this.jsonVal(ctx, value)}`;
285
- const pulled = `CASE WHEN ${this.jsonIsArray(slot)} THEN COALESCE((${kept}), '[]'::jsonb) ELSE COALESCE(${this.jsonValue(slot)}, 'null') END`;
286
- return `JSONB_SET(${expr}, '{"${key}"}', ${pulled}, false)`;
281
+ /** `WITH ORDINALITY` numbers each element, which the aggregate orders by to keep the survivors in their order. */
282
+ jsonKeptFrom(slot) {
283
+ return `JSONB_ARRAY_ELEMENTS(${this.jsonValue(slot)}) WITH ORDINALITY AS ${JSON_PULL_ALIAS}(${JSON_PULL_ALIAS}, ord)`;
284
+ }
285
+ jsonKeptAggregate() {
286
+ return `JSONB_AGG(${JSON_PULL_ALIAS} ORDER BY ${JSON_PULL_ALIAS}.ord)`;
287
+ }
288
+ /** Each key or dotted path set as `jsonb`, which `JSONB_SET` takes and nothing else. */
289
+ jsonSet(ctx, expr, set) {
290
+ return Object.entries(set).reduce((acc, [path, value]) => this.jsonSetKey(acc, path, this.jsonbOf(ctx, value)), expr);
287
291
  }
288
292
  /**
289
- * The plain values merge as one bound object; a `sql()` one is an SQL expression rather than JSON,
290
- * so it merges through `JSONB_BUILD_OBJECT` and is evaluated in place - stringified with the rest,
291
- * it would land as `{}`.
293
+ * A value as `jsonb` inside a document: a null one JSON's, as `JSONB_SET` and a comparison need, and a `sql()`
294
+ * one read back out of an object, since `TO_JSONB` refuses an untyped literal.
292
295
  */
293
- jsonSet(ctx, expr, set, field) {
294
- const entries = Object.entries(set);
295
- const merged = this.jsonVal(ctx, Object.fromEntries(entries.filter(([, value]) => !(value instanceof QuerySql))));
296
- const raws = entries.flatMap(([key, value]) => value instanceof QuerySql ? [` || JSONB_BUILD_OBJECT('${key}', ${this.rawFragment(ctx, value)})`] : []);
297
- return `${jsonSetTarget(expr, field, `'{}'::jsonb`)} || ${merged}${raws.join('')}`;
298
- }
299
- /** The only fragment that references `expr` twice - safe here because placeholders are numbered. */
300
- jsonPush(ctx, expr, push) {
301
- return Object.entries(push).reduce((acc, [key, value]) => {
302
- const ph = this.jsonVal(ctx, value);
303
- return `JSONB_SET(${acc}, '{"${key}"}', COALESCE((${acc})->'${key}', '[]'::jsonb) || JSONB_BUILD_ARRAY(${ph}))`;
304
- }, expr);
296
+ jsonbOf(ctx, value) {
297
+ if (value instanceof QuerySql) {
298
+ return `JSONB_BUILD_OBJECT('v', ${this.rawFragment(ctx, value)})->'v'`;
299
+ }
300
+ return value === null ? `'null'::jsonb` : this.jsonVal(ctx, value);
301
+ }
302
+ /** `JSONB_BUILD_ARRAY` takes any type, and a NULL as JSON's null. */
303
+ jsonAppended(ctx, array, value, unless) {
304
+ return `${array} || ${unlessThen(unless, this.jsonEmptyArray, `JSONB_BUILD_ARRAY(${this.jsonVal(ctx, value)})`)}`;
305
+ }
306
+ jsonEmptyObject = `'{}'::jsonb`;
307
+ jsonEmptyArray = `'[]'::jsonb`;
308
+ /** `JSONB_SET` takes one path, so each key wraps the last. */
309
+ jsonWriteKeys(expr, writes, { create }) {
310
+ return writes.reduce((acc, [slot, value]) => this.jsonSetKey(acc, slot.path, this.jsonOrStored(slot, value), { create }), expr);
311
+ }
312
+ /** A replace hands an absent key's NULL back, which `JSONB_SET` would answer for the whole document. */
313
+ jsonSetKey(expr, path, value, { create = true } = {}) {
314
+ const set = create ? value : `COALESCE(${value}, 'null'::jsonb), false`;
315
+ return `JSONB_SET(${expr}, '${toPgArray(jsonPathKeys(path))}', ${set})`;
305
316
  }
306
317
  jsonUnset(ctx, expr, unset) {
307
- return `(${expr}) - ${this.addValue(ctx, [...unset])}::text[]`;
318
+ return unset.reduce((acc, path) => `(${acc}) #- '${toPgArray(jsonPathKeys(path))}'`, expr);
308
319
  }
309
320
  /** Postgres binds JSON with a numbered placeholder and an explicit cast, per driver capability. */
310
321
  jsonScalarParam(ctx, value) {
311
- return this.jsonVal(ctx, value);
322
+ return this.jsonbOf(ctx, value);
312
323
  }
313
324
  /**
314
325
  * Helper to add a JSON value to context with appropriate stringification and cast.
@@ -6,7 +6,7 @@ import { type ParsedGroupEntry } from '../util/index.js';
6
6
  * `$sort` needs - which joins the same way, filters included, but adds nothing to the result.
7
7
  */
8
8
  export type QueryJoin = {
9
- /** The relation key on its parent, which is how MongoDB names the field a `$lookup` adds. */
9
+ /** The relation key on its parent. */
10
10
  readonly key: string;
11
11
  /** Dotted path from the queried entity, which is what a joined row's columns answer under. */
12
12
  readonly path: string;
@@ -1,5 +1,5 @@
1
1
  import { type RelationRows, type SelectTerm } from '../dialect/abstractSqlDialect.js';
2
- import { type JsonAccessMode } from '../dialect/jsonSql.js';
2
+ import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
3
3
  import { MysqlLikeSqlDialect } from '../dialect/mysqlLikeSqlDialect.js';
4
4
  import type { FieldOptions, Query, QueryContext, SqlDialectFeatures, SqlValues, Type, VectorDistance, VectorMetric } from '../type/index.js';
5
5
  export declare class MariaDialect extends MysqlLikeSqlDialect {
@@ -33,7 +33,7 @@ export declare class MariaDialect extends MysqlLikeSqlDialect {
33
33
  */
34
34
  protected jsonArrayOf(elem: string): string;
35
35
  /** Text-backed JSON compares as text, so `JSON_EQUALS` compares it as JSON, key order aside. */
36
- protected jsonDiffers(elem: string, operand: string): string;
36
+ protected jsonElemEquals(ctx: QueryContext, slot: JsonSlot, alias: string, value: unknown): string;
37
37
  /** `VEC_DISTANCE_COSINE`/`VEC_DISTANCE_EUCLIDEAN`, 11.7+, which the index's `DISTANCE=` names alike. */
38
38
  readonly vectorMetrics: ReadonlyMap<VectorDistance, VectorMetric>;
39
39
  /**
@@ -61,8 +61,8 @@ export class MariaDialect extends MysqlLikeSqlDialect {
61
61
  return super.jsonArrayOf(`JSON_COMPACT(${elem})`);
62
62
  }
63
63
  /** Text-backed JSON compares as text, so `JSON_EQUALS` compares it as JSON, key order aside. */
64
- jsonDiffers(elem, operand) {
65
- return `NOT JSON_EQUALS(${elem}, ${operand})`;
64
+ jsonElemEquals(ctx, slot, alias, value) {
65
+ return `JSON_EQUALS(${this.jsonElemValue(slot, alias, 'json')}, ${this.jsonScalarParam(ctx, value)})`;
66
66
  }
67
67
  /** `VEC_DISTANCE_COSINE`/`VEC_DISTANCE_EUCLIDEAN`, 11.7+, which the index's `DISTANCE=` names alike. */
68
68
  vectorMetrics = new Map([
@@ -1,4 +1,4 @@
1
- import { type Document, type Filter, type Sort, type UpdateFilter } from 'mongodb';
1
+ import { type Document, type Filter, type Sort } from 'mongodb';
2
2
  import { AbstractDialect } from '../dialect/abstractDialect.js';
3
3
  import type { DialectFeatures, EntityData, EntityMeta, Query, QueryAggMap, QueryAggregate, QueryExclude, QueryGroupMap, QueryOptions, QueryPager, QuerySelectValue, QuerySortMap, QueryVectorSearch, QueryWhere, Type } from '../type/index.js';
4
4
  import { type CallbackKey } from '../util/index.js';
@@ -113,7 +113,10 @@ export declare class MongoDialect extends AbstractDialect {
113
113
  * by ahead of the value itself.
114
114
  */
115
115
  sortPlan<E extends Document>(entity: Type<E>, { $sort: sort, $populate: populate, $where: where }: Query<E>): MongoSortPlan;
116
- /** Walks `$sort` against the metadata of the entity each level addresses, as the SQL dialects do. */
116
+ /**
117
+ * Walks `$sort` against the metadata of the entity each level addresses, as the SQL dialects do. `at` is where the
118
+ * level is: the relations walked to it (`path`, ending in a dot), and the join its rows came from, if any.
119
+ */
117
120
  private collectSort;
118
121
  /**
119
122
  * The stages a `$sort` by a relation's aggregate needs - its size, or its row nearest a vector: one
@@ -206,6 +209,8 @@ export declare class MongoDialect extends AbstractDialect {
206
209
  private joinKeys;
207
210
  /** `[column, key]` for the fields whose stored name differs from their property name, memoized per entity. */
208
211
  private renamedColumns;
212
+ /** Each relation's key, the field its rows are read from, and its entity, memoized per entity for `normalizeId`. */
213
+ private relationReads;
209
214
  private referenceKeys;
210
215
  normalizeIds<E extends Document>(meta: EntityMeta<E>, docs: Document[]): E[];
211
216
  /** `doc` is the wire shape - `_id`, stored names, `ObjectId`s - and what comes back is the code's. */
@@ -225,19 +230,11 @@ export declare class MongoDialect extends AbstractDialect {
225
230
  /** The seam out of the driver: an `ObjectId` becomes its hex string, the type the code declares. */
226
231
  fromWireId(value: unknown): unknown;
227
232
  getPersistable<E extends Document>(meta: EntityMeta<E>, payload: EntityData<E>, callbackKey: CallbackKey): Partial<E>;
228
- /** One MongoDB update document's operators, grouped by kind and keyed by dotted path. */
229
- private groupUpdateOperators;
230
- /**
231
- * Turn a persistable payload into a MongoDB update, mapping UQL's JSON operators onto their native
232
- * equivalents: `$set` becomes dotted-path assignments, `$unset`/`$push`/`$pull` map one-to-one.
233
- * Plain field values are assigned with `$set`.
234
- */
235
- getUpdateFilter<E extends Document>(persistable: Partial<E>): UpdateFilter<E> | Document[];
236
233
  /**
237
- * An update as one pipeline, since MongoDB refuses two operators on one path: each path composed as
238
- * `$pull`, `$set`, `$push`, then `$unset`, as SQL does, with values as `$literal` so `$x` stays data.
234
+ * A payload as one update pipeline, so every engine's answer holds: a `null` or missing document or array
235
+ * counts as empty, and values go in as `$literal`, so `$x` stays data.
239
236
  */
240
- private getUpdatePipeline;
237
+ getUpdateFilter<E extends Document>(persistable: Partial<E>): Document[];
241
238
  /** Refuses a key left to MongoDB that it cannot mint: only an `ObjectId`, read back as a string, so not a `Number`. */
242
239
  private assertMintableKey;
243
240
  getPersistables<E extends Document>(meta: EntityMeta<E>, payload: EntityData<E> | EntityData<E>[], callbackKey: CallbackKey): Partial<E>[];