uql-orm 0.101.6 → 0.102.1

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 (43) 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 +54 -24
  5. package/dist/dialect/abstractSqlDialect.js +102 -52
  6. package/dist/dialect/aliases.d.ts +8 -0
  7. package/dist/dialect/aliases.js +24 -16
  8. package/dist/dialect/jsonSql.d.ts +10 -7
  9. package/dist/dialect/jsonSql.js +7 -10
  10. package/dist/dialect/mysqlLikeSqlDialect.d.ts +6 -10
  11. package/dist/dialect/mysqlLikeSqlDialect.js +13 -13
  12. package/dist/dialect/pgLikeSqlDialect.d.ts +20 -13
  13. package/dist/dialect/pgLikeSqlDialect.js +38 -29
  14. package/dist/libsql/libsqlDialect.d.ts +5 -0
  15. package/dist/libsql/libsqlDialect.js +5 -0
  16. package/dist/mongodb/mongoDialect.d.ts +4 -12
  17. package/dist/mongodb/mongoDialect.js +70 -70
  18. package/dist/mssql/mssqlDialect.d.ts +24 -14
  19. package/dist/mssql/mssqlDialect.js +42 -32
  20. package/dist/mysql/mysqlDialect.js +1 -1
  21. package/dist/querier/abstractQuerier.d.ts +52 -17
  22. package/dist/querier/abstractQuerier.js +141 -81
  23. package/dist/querier/abstractSqlQuerier.d.ts +5 -1
  24. package/dist/querier/abstractSqlQuerier.js +16 -1
  25. package/dist/querier/cursorStream.js +1 -2
  26. package/dist/sqlite/hranaQuerier.d.ts +2 -2
  27. package/dist/sqlite/hranaQuerier.js +2 -2
  28. package/dist/sqlite/localSqliteQuerierPool.js +8 -2
  29. package/dist/sqlite/sqliteDialect.d.ts +8 -7
  30. package/dist/sqlite/sqliteDialect.js +15 -9
  31. package/dist/turso/tursoLocalDialect.d.ts +3 -1
  32. package/dist/turso/tursoLocalDialect.js +7 -0
  33. package/dist/type/dialect.d.ts +6 -0
  34. package/dist/type/entity.d.ts +18 -10
  35. package/dist/type/querier.d.ts +6 -0
  36. package/dist/util/dialect.util.d.ts +27 -0
  37. package/dist/util/dialect.util.js +120 -4
  38. package/dist/util/field.util.d.ts +2 -0
  39. package/dist/util/field.util.js +5 -0
  40. package/dist/util/object.util.d.ts +2 -0
  41. package/dist/util/object.util.js +4 -0
  42. package/package.json +7 -7
  43. package/skills/uql-orm/SKILL.md +5 -5
@@ -1,12 +1,13 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
2
  import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, RAW_ALIAS, } from '../type/index.js';
3
3
  import { utcTimestamp } from '../util/date.js';
4
- import { isExactDecimal, isInlinedExpression, jsonKey, jsonPathKeys } from '../util/field.util.js';
5
- import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
4
+ import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
5
+ import { isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, getSoftDeleteValue, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJsonUpdate, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, throwUnknownAggregateColumn, withoutSoftDeleteFilter, } from '../util/index.js';
6
+ import { isJsonScalar } from '../util/object.util.js';
6
7
  import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
7
8
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
8
9
  import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
9
- import { holdsOperator, isJsonScalar, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, } from './jsonSql.js';
10
+ import { holdsOperator, chainedCall, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, } from './jsonSql.js';
10
11
  import { betweenBounds, COMPARE_OPS, EQUALITY_OPS, GROUP_OPS, groupClauses, inOperands, isGroupOp, isOrderedOp, isVectorQuery, LIKE_OPS, namesRows, ORDERED_OPS, VECTOR_QUERY_KEY_SET, whereOperators, } from './operators.js';
11
12
  import { SqlQueryContext } from './queryContext.js';
12
13
  import { groupPathField, NO_JOINS, aggregateColumnField, resolveGroupJoins, resolveQueryJoins, relationSortTerms, resolveSortableJoin, } from './queryJoins.js';
@@ -121,7 +122,6 @@ export class AbstractSqlDialect extends VectorSqlDialect {
121
122
  createSchemaSql(schema) {
122
123
  return `CREATE SCHEMA IF NOT EXISTS ${this.escapeId(schema, true)}`;
123
124
  }
124
- isolationLevelStrategy = 'inline';
125
125
  booleanLiteral = 'native';
126
126
  sqlValues = ANSI_SQL_VALUES;
127
127
  /** The most rows one `INSERT ... VALUES` takes, which a narrow row can reach before the bind budget. */
@@ -135,17 +135,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
135
135
  * update, is spread over nested calls. No cap binds unless a dialect declares one.
136
136
  */
137
137
  maxFunctionArgs = Infinity;
138
- getBeginTransactionStatements(isolationLevel) {
139
- const level = isolationLevel?.toUpperCase();
140
- const strategy = this.isolationLevelStrategy;
141
- if (!level || strategy === 'none') {
142
- return [this.beginTransactionCommand];
143
- }
144
- if (strategy === 'inline') {
145
- return [`${this.beginTransactionCommand} ISOLATION LEVEL ${level}`];
146
- }
147
- // 'setBefore' - MySQL/MariaDB pattern
148
- return [`SET TRANSACTION ISOLATION LEVEL ${level}`, this.beginTransactionCommand];
138
+ /** The statements opening a transaction, its modes inline in the `BEGIN` as the Postgres family takes them. */
139
+ getBeginTransactionStatements({ isolationLevel, readOnly } = {}) {
140
+ const modes = [isolationLevel && `ISOLATION LEVEL ${isolationLevel.toUpperCase()}`, readOnly && 'READ ONLY'];
141
+ const inline = modes.filter((mode) => typeof mode === 'string');
142
+ return [inline.length ? `${this.beginTransactionCommand} ${inline.join(', ')}` : this.beginTransactionCommand];
149
143
  }
150
144
  createContext(options = {}) {
151
145
  return new SqlQueryContext(this, [], undefined, options.inlineValues);
@@ -217,6 +211,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
217
211
  const expression = this.returningIdExpression(meta);
218
212
  return expression ? `RETURNING ${expression}` : '';
219
213
  }
214
+ /**
215
+ * ` RETURNING` the fields `keys` names, after an `UPDATE` or `DELETE` this context holds, projected and read as
216
+ * a read's are: the terms its rows answer under. Only where `features.writeReturning`.
217
+ */
218
+ returning(ctx, entity, keys) {
219
+ const terms = this.selectTerms(ctx, entity, keySet(keys));
220
+ ctx.append(` RETURNING ${this.termsSql(terms)}`);
221
+ return terms;
222
+ }
220
223
  /** What the returned row is read off, for an engine that names it: SQL Server's `INSERTED.`. */
221
224
  returnedRowPrefix = '';
222
225
  /** `<id column> AS id` on its own, for a statement composing a `RETURNING` list of several items. */
@@ -360,7 +363,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
360
363
  }
361
364
  ctx.append(q.$distinct ? 'SELECT DISTINCT ' : 'SELECT ');
362
365
  ctx.append(this.selectModifier(q));
363
- ctx.append(columns.map((term) => this.termSql(term)).join(', '));
366
+ ctx.append(this.termsSql(columns));
364
367
  ctx.append(` FROM ${ref}${this.lockHint(q)}`);
365
368
  this.selectRelationJoins(ctx, meta, alias, joins);
366
369
  return { terms, order: carried?.order };
@@ -382,6 +385,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
382
385
  ...this.selectSortProjections(ctx, meta, q, opts.prefix),
383
386
  ];
384
387
  }
388
+ /** A projection's list of terms. */
389
+ termsSql(terms) {
390
+ return terms.map((term) => this.termSql(term)).join(', ');
391
+ }
385
392
  /** A term as a projection writes it, aliased unless its SQL already answers under its key. */
386
393
  termSql({ sql, key, bare }) {
387
394
  return bare || key === undefined ? sql : `${sql} ${this.escapeId(key, true)}`;
@@ -1684,59 +1691,98 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1684
1691
  return `CAST(${operand} AS JSON)`;
1685
1692
  }
1686
1693
  /**
1687
- * `"col" = <expr>` for a JSON update, each operator wrapping the last: `$pull`, `$set`, `$push`, `$unset`.
1688
- * `$pull` reads the column and every later one its expression once, so no value binds twice.
1694
+ * `"col" = <expr>` for a JSON update, folded to one write per path, on an empty document in place of a NULL
1695
+ * column where one writes a key. Each write reads `current`, the column as stored.
1689
1696
  */
1690
1697
  formatJsonUpdate(ctx, escapedCol, value, field, current = escapedCol) {
1691
- const { $pull, $set, $push, $unset } = value;
1692
- [...getKeys($pull), ...getKeys($set), ...getKeys($push), ...($unset ?? [])].forEach(jsonKey);
1693
- let expr = current;
1694
- if (hasKeys($pull)) {
1695
- expr = this.jsonPull(ctx, expr, current, $pull);
1696
- }
1697
- if (hasKeys($set)) {
1698
- expr = this.jsonSet(ctx, expr, $set, field);
1699
- }
1700
- if (hasKeys($push)) {
1701
- expr = this.jsonPush(ctx, expr, $push);
1702
- }
1703
- if ($unset?.length) {
1704
- expr = this.jsonUnset(ctx, expr, $unset);
1705
- }
1698
+ const writes = foldJsonUpdate(value);
1699
+ const arrays = Object.entries(writes.arrays);
1700
+ const keyWrites = (appending) => arrays
1701
+ .filter(([, write]) => write.appends.length > 0 === appending)
1702
+ .map(([key, write]) => {
1703
+ const slot = { base: current, path: key };
1704
+ return [slot, this.jsonArrayWrite(ctx, slot, write)];
1705
+ });
1706
+ // Pulls alone first, through a write creating no key: each built before the next, as positional values bind.
1707
+ const pulled = this.jsonWriteKeys(writesKeys(writes) ? jsonSetTarget(current, field, this.jsonEmptyObject) : current, keyWrites(false), { create: false });
1708
+ const withArrays = this.jsonWriteKeys(pulled, keyWrites(true), { create: true });
1709
+ const withSet = hasKeys(writes.set)
1710
+ ? this.jsonSet(ctx, this.jsonWriteKeys(withArrays, this.jsonParents(Object.keys(writes.set), current), { create: true }), writes.set)
1711
+ : withArrays;
1712
+ const expr = writes.unset.length > 0 ? this.jsonUnset(ctx, withSet, writes.unset) : withSet;
1706
1713
  ctx.append(`${escapedCol} = ${expr}`);
1707
1714
  }
1708
1715
  /**
1709
- * Remove every element equal to the given value, per array key. Each key wraps the expression
1710
- * built so far, so dialects only supply {@link jsonPullKey} - and because every key reads
1711
- * `escapedCol` rather than the accumulated expression, values bind once, in key order.
1716
+ * The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its pull, then each
1717
+ * append, onto `[]` in place of a missing or null array. With a `unique` append, a second branch writes the array
1718
+ * without it where the stored one holds its item; each branch is built in the order it binds.
1712
1719
  */
1713
- jsonPull(ctx, expr, escapedCol, pull) {
1714
- return Object.entries(pull).reduce((acc, [key, value]) => this.jsonPullKey(ctx, acc, escapedCol, key, value), expr);
1720
+ jsonArrayWrite(ctx, slot, { pull, appends }) {
1721
+ const isArray = this.jsonIs(slot, 'array');
1722
+ const kept = () => (pull ? this.jsonPulled(ctx, slot, pull.item) : this.jsonValue(slot));
1723
+ if (appends.length === 0) {
1724
+ return `CASE WHEN ${isArray} THEN ${kept()} END`;
1725
+ }
1726
+ const isNull = this.jsonIsNull(slot);
1727
+ const appended = (included) => included.reduce((array, { item }) => this.jsonAppended(ctx, array, item), `CASE WHEN ${isNull} THEN ${this.jsonEmptyArray} ELSE ${kept()} END`);
1728
+ const unique = appends.find((append) => append.unique);
1729
+ if (!unique) {
1730
+ return `CASE WHEN ${isNull} OR ${isArray} THEN ${appended(appends)} END`;
1731
+ }
1732
+ const lacks = `${isNull} OR ${isArray} AND NOT ${this.jsonContains(ctx, slot, [unique.item])}`;
1733
+ const withUnique = `WHEN ${lacks} THEN ${appended(appends)}`;
1734
+ const others = appends.filter((append) => append !== unique);
1735
+ const without = pull || others.length > 0 ? ` WHEN ${isArray} THEN ${appended(others)}` : '';
1736
+ return `CASE ${withUnique}${without} END`;
1715
1737
  }
1716
1738
  /**
1717
- * Wrap `expr` so the array at `key` no longer contains `value`: the array rebuilt from the elements that
1718
- * differ from it, and any other value put back as it is. `JSON_REPLACE` leaves an absent key, and a NULL
1719
- * column, untouched.
1739
+ * `expr` with each key written, through as few `JSON_SET` calls, or `JSON_REPLACE` where a missing key stays
1740
+ * missing, as `maxFunctionArgs` allows: every value reads the column as stored, so none needs another's result.
1720
1741
  */
1721
- jsonPullKey(ctx, expr, escapedCol, key, value) {
1722
- const slot = { base: escapedCol, path: key };
1742
+ jsonWriteKeys(expr, writes, { create }) {
1743
+ const pairs = writes.map(([slot, value]) => `${jsonPath(slot.path)}, ${this.jsonOrStored(slot, value)}`);
1744
+ return chainedCall(create ? 'JSON_SET' : 'JSON_REPLACE', expr, pairs, 2, this.maxFunctionArgs);
1745
+ }
1746
+ /** `value`, or the one stored at `slot` where it is NULL. */
1747
+ jsonOrStored(slot, value) {
1748
+ return `COALESCE(${value}, ${this.jsonValue(slot)})`;
1749
+ }
1750
+ /** The array at `slot` without the elements equal to `item`, an empty one where it keeps none. */
1751
+ jsonPulled(ctx, slot, item) {
1752
+ return `COALESCE((${this.jsonKept(ctx, slot, item)}), ${this.jsonEmptyArray})`;
1753
+ }
1754
+ /** The surviving elements of `slot` as one array, or NULL where there are none: `jsonPulled` supplies the empty one. */
1755
+ jsonKept(ctx, slot, item) {
1723
1756
  const elem = this.jsonElemValue(slot, JSON_PULL_ALIAS, 'json');
1724
- const differs = this.jsonDiffers(elem, this.jsonScalarParam(ctx, value));
1725
- const kept = `SELECT ${this.jsonArrayOf(elem)} FROM ${this.jsonElemFrom(slot, JSON_PULL_ALIAS)} WHERE ${differs}`;
1726
- const pulled = `CASE WHEN ${this.jsonIsArray(slot)} THEN (${kept}) ELSE ${this.jsonValue(slot)} END`;
1727
- return `JSON_REPLACE(${expr}, ${jsonPath(key)}, ${pulled})`;
1757
+ const differs = this.jsonDiffers(elem, this.jsonScalarParam(ctx, item));
1758
+ return `SELECT ${this.jsonArrayOf(elem)} FROM ${this.jsonElemFrom(slot, JSON_PULL_ALIAS)} WHERE ${differs}`;
1728
1759
  }
1729
- /** The elements a `$pull` keeps, back in one array, and an empty one where it keeps none. */
1760
+ /** The elements a `$pull` keeps, aggregated into one array. */
1730
1761
  jsonArrayOf(elem) {
1731
- return `COALESCE(JSON_ARRAYAGG(${elem}), JSON_ARRAY())`;
1762
+ return `JSON_ARRAYAGG(${elem})`;
1732
1763
  }
1733
1764
  /** Whether an element is not the pulled value, both read as JSON. */
1734
1765
  jsonDiffers(elem, operand) {
1735
1766
  return `${elem} <> ${operand}`;
1736
1767
  }
1737
- /** Shallow assignment of top-level keys, matching PostgreSQL's `jsonb || jsonb`, through `JSON_SET`. */
1738
- jsonSet(ctx, expr, set, field) {
1739
- return jsonSetCall((value) => this.jsonScalarParam(ctx, value), jsonSetTarget(expr, field, `'{}'`), set, this.maxFunctionArgs);
1768
+ /** Each key or dotted path assigned, its parents already there, through `JSON_SET`. */
1769
+ jsonSet(ctx, expr, set) {
1770
+ return jsonSetCall((value) => this.jsonScalarParam(ctx, value), expr, set, this.maxFunctionArgs);
1771
+ }
1772
+ /** A JSON object with no keys, as a key write takes it. */
1773
+ jsonEmptyObject = 'JSON_OBJECT()';
1774
+ /** A JSON array with no elements, as a key write takes it. */
1775
+ jsonEmptyArray = 'JSON_ARRAY()';
1776
+ /**
1777
+ * A write at every parent of `paths`, outermost first, so a dotted `$set` has somewhere to write: an empty object
1778
+ * in place of anything that is no object, a missing value included, and NULL, the stored one kept, where it is.
1779
+ */
1780
+ jsonParents(paths, current) {
1781
+ const parents = new Set(paths.flatMap(ancestorPaths));
1782
+ return [...parents].map((path) => {
1783
+ const slot = { base: current, path };
1784
+ return [slot, `CASE WHEN ${this.jsonIs(slot, 'object')} THEN NULL ELSE ${this.jsonEmptyObject} END`];
1785
+ });
1740
1786
  }
1741
1787
  /** Remove object keys, through `JSON_REMOVE`. */
1742
1788
  jsonUnset(_ctx, expr, unset) {
@@ -2131,3 +2177,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2131
2177
  return `${operand} ${negate ? 'NOT IN' : 'IN'} (${phs})`;
2132
2178
  }
2133
2179
  }
2180
+ /** `begin` after the statement setting the level, as T-SQL and the MySQL family take it, having no inline form. */
2181
+ export function isolationSetBefore(isolationLevel, begin) {
2182
+ return isolationLevel ? [`SET TRANSACTION ISOLATION LEVEL ${isolationLevel.toUpperCase()}`, begin] : [begin];
2183
+ }
@@ -27,6 +27,14 @@ export declare const RELATION_ROW_ALIAS = "_uql_row";
27
27
  export declare const JSON_ELEM_ALIAS = "_uql_elem";
28
28
  /** The alias a `$pull` reads its surviving elements through, kept distinct from {@link JSON_ELEM_ALIAS}. */
29
29
  export declare const JSON_PULL_ALIAS = "_uql_pull";
30
+ /** The key a SQL Server JSON write aims at where it writes nothing, there being none by that name. */
31
+ export declare const JSON_SKIP_KEY = "_uql_skip";
32
+ /** What a savepoint the querier names is called, its depth appended. */
33
+ export declare const SAVEPOINT_PREFIX = "_uql_sp";
34
+ /** The cursor a stream declares. Suffixed per call, so two streams on one connection cannot collide. */
35
+ export declare const CURSOR_ALIAS = "_uql_cursor";
36
+ /** The SQL Server table variable an `OUTPUT` fills. */
37
+ export declare const OUTPUT_TABLE = "@_uql_output";
30
38
  /** The field a MongoDB `$sort` by `$text` reads `textScore` from where it projects none, taken back out after. */
31
39
  export declare const TEXT_SCORE_ALIAS = "_uql_text_score";
32
40
  /**
@@ -6,62 +6,70 @@
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 SQL Server JSON write aims at where it writes nothing, there being none by that name. */
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_`;
43
51
  /** The field a ManyToMany lookup nests its target match under, inside the junction's own pipeline. */
44
- export const REL_NESTED_KEY = '_uql_target';
52
+ export const REL_NESTED_KEY = `${OWNED_PREFIX}_target`;
45
53
  /**
46
54
  * The alias MySQL's upsert gives the row being inserted, so its `ON DUPLICATE KEY UPDATE`
47
55
  * assignments read `_uql_new.col` instead of the deprecated `VALUES(col)`. MariaDB has no such
48
56
  * syntax and reads `VALUE(col)`.
49
57
  */
50
- export const UPSERT_NEW_ROW_ALIAS = '_uql_new';
58
+ export const UPSERT_NEW_ROW_ALIAS = `${OWNED_PREFIX}_new`;
51
59
  /** The row source a `MERGE` upsert reads its incoming values from, on SQL Server and Oracle. */
52
- export const UPSERT_SOURCE_ALIAS = '_uql_src';
60
+ export const UPSERT_SOURCE_ALIAS = `${OWNED_PREFIX}_src`;
53
61
  /**
54
62
  * Where a `$sort` by a relation's aggregate - its size, or its nearest row - parks the value until the
55
63
  * ordering has run. A function, so the `$sort` that names the field and the stage that produces it cannot
56
64
  * spell it differently - MongoDB ranks a field that is not there as all-equal, so a drift would go unnoticed.
57
65
  */
58
66
  export function sortAggregateField({ op, relation, field }) {
59
- return `_uql_sort_${op.slice(1)}_${relation}${field ? `_${field}` : ''}`;
67
+ return `${OWNED_PREFIX}_sort_${op.slice(1)}_${relation}${field ? `_${field}` : ''}`;
60
68
  }
61
69
  /**
62
70
  * The column a relation's rows carry one sort term out in, beside the columns they answer under, for
63
71
  * the aggregate reading them to order by: `_uql_sort_createdAt`.
64
72
  */
65
73
  export function relationSortColumn(path) {
66
- return `_uql_sort_${path}`;
74
+ return `${OWNED_PREFIX}_sort_${path}`;
67
75
  }
@@ -4,6 +4,10 @@ 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
+ /** A key a JSON update writes, and the value it writes there, NULL where the stored one stays. */
8
+ export type JsonKeyWrite = readonly [slot: JsonSlot, value: string];
9
+ /** The JSON values a path can be asked to hold, beside a scalar. */
10
+ export type JsonContainer = 'array' | 'object';
7
11
  /** A JSON value a condition reads: `path` of the JSON in `base`, `''` for all of it. */
8
12
  export type JsonSlot = {
9
13
  readonly base: string;
@@ -25,13 +29,14 @@ export declare function groupsPerCall(maxArgs: number, size: number): number;
25
29
  */
26
30
  export declare function chainedCall(fn: string, target: string, groups: readonly string[], size: number, maxArgs: number): string;
27
31
  /**
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`.
32
+ * `JSON_SET(target, path, value, ...)`, which MySQL and SQLite share, nested past `maxArgs`. Values bind in
33
+ * key order through `bindValue`.
30
34
  */
31
- export declare function jsonSetCall(bindValue: (value: unknown) => string, target: string, entries: Record<string, unknown>, maxArgs: number, pathSuffix?: string): string;
35
+ export declare function jsonSetCall(bindValue: (value: unknown) => string, target: string, entries: Record<string, unknown>, maxArgs: number): string;
32
36
  /**
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.
37
+ * The document a JSON update writing keys builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL
38
+ * one goes in bare, which keeps MySQL's partial in-place JSON update, since that needs the column itself as
39
+ * `JSON_SET`'s input.
35
40
  */
36
41
  export declare function jsonSetTarget(expr: string, field: FieldOptions | undefined, empty: string): string;
37
42
  /** `JSON_REMOVE(expr, path, ...)`, which MySQL and SQLite share, nested past `maxArgs`. */
@@ -57,5 +62,3 @@ export declare function jsonCompareMode(value: unknown): JsonAccessMode;
57
62
  export declare function jsonTypeMode(type: FieldType): JsonAccessMode;
58
63
  /** Whether `value` asks for more than JSON containment: an operator map anywhere in it. */
59
64
  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;
@@ -38,16 +38,17 @@ export function chainedCall(fn, target, groups, size, maxArgs) {
38
38
  return call;
39
39
  }
40
40
  /**
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`.
41
+ * `JSON_SET(target, path, value, ...)`, which MySQL and SQLite share, nested past `maxArgs`. Values bind in
42
+ * key order through `bindValue`.
43
43
  */
44
- export function jsonSetCall(bindValue, target, entries, maxArgs, pathSuffix = '') {
45
- const pairs = Object.entries(entries).map(([key, value]) => `${jsonPath(key, pathSuffix)}, ${bindValue(value)}`);
44
+ export function jsonSetCall(bindValue, target, entries, maxArgs) {
45
+ const pairs = Object.entries(entries).map(([key, value]) => `${jsonPath(key)}, ${bindValue(value)}`);
46
46
  return chainedCall('JSON_SET', target, pairs, 2, maxArgs);
47
47
  }
48
48
  /**
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.
49
+ * The document a JSON update writing keys builds on. A nullable column gets a `COALESCE` fallback; a NOT NULL
50
+ * one goes in bare, which keeps MySQL's partial in-place JSON update, since that needs the column itself as
51
+ * `JSON_SET`'s input.
51
52
  */
52
53
  export function jsonSetTarget(expr, field, empty) {
53
54
  return field?.nullable === false ? expr : `COALESCE(${expr}, ${empty})`;
@@ -94,7 +95,3 @@ export function holdsOperator(value) {
94
95
  }
95
96
  return isOperatorMap(value) && someKey(value, (key) => isOperatorKey(key) || holdsOperator(value[key]));
96
97
  }
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
- import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type, UpdatePayload } from '../type/index.js';
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. */
@@ -25,7 +25,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
25
25
  readonly autoIncrementSuffix = "AUTO_INCREMENT";
26
26
  readonly escapeIdChar = "`";
27
27
  readonly beginTransactionCommand = "START TRANSACTION";
28
- readonly isolationLevelStrategy = "setBefore";
28
+ getBeginTransactionStatements({ isolationLevel, readOnly }?: TransactionOptions): string[];
29
29
  readonly booleanLiteral = "integer";
30
30
  readonly sqlValues: SqlValues;
31
31
  readonly insertIdSource: InsertIdSource;
@@ -95,12 +95,7 @@ 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
+ protected jsonAppended(ctx: QueryContext, array: string, value: unknown): string;
104
99
  /**
105
100
  * `->` for the value and `->>` for its text, each taking the whole path (`'$.a.b'`): a bare key, as
106
101
  * Postgres chains them, is "Invalid JSON path expression" here.
@@ -110,7 +105,8 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
110
105
  protected jsonContains(ctx: QueryContext, slot: JsonSlot, values: readonly unknown[]): string;
111
106
  /** Only an array's, where `JSON_LENGTH` counts a scalar as 1 and an object by its keys. */
112
107
  protected jsonLength(slot: JsonSlot): string;
113
- protected jsonIsArray(slot: JsonSlot): string;
108
+ protected jsonIs(slot: JsonSlot, kind: JsonContainer): string;
109
+ protected jsonIsNull(slot: JsonSlot): string;
114
110
  /**
115
111
  * Each element of the array at the path as one `JSON` column, which any path then reads the way it reads
116
112
  * a column's document.
@@ -1,7 +1,7 @@
1
1
  import { getMeta } from '../entity/index.js';
2
2
  import { textSearchFields } from '../util/index.js';
3
3
  import { escapeMysqlSqlLiteral } from '../util/sqlLiteral.js';
4
- import { ANSI_SQL_VALUES, AbstractSqlDialect, } from './abstractSqlDialect.js';
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
7
  import { jsonPath } from './jsonSql.js';
@@ -29,6 +29,7 @@ export const MYSQL_FEATURES = {
29
29
  serverSideCursors: false,
30
30
  correlatedWrites: true,
31
31
  rowLocks: MYSQL_ROW_LOCKS,
32
+ writeReturning: false,
32
33
  nullsSortLowest: true,
33
34
  nullsOrdering: 'expression',
34
35
  textScoreIndexes: true,
@@ -90,7 +91,9 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
90
91
  autoIncrementSuffix = 'AUTO_INCREMENT';
91
92
  escapeIdChar = '`';
92
93
  beginTransactionCommand = 'START TRANSACTION';
93
- isolationLevelStrategy = 'setBefore';
94
+ getBeginTransactionStatements({ isolationLevel, readOnly } = {}) {
95
+ return isolationSetBefore(isolationLevel, `${this.beginTransactionCommand}${readOnly ? ' READ ONLY' : ''}`);
96
+ }
94
97
  booleanLiteral = 'integer';
95
98
  sqlValues = MYSQL_SQL_VALUES;
96
99
  // No `RETURNING` support, so multi-row insert IDs are inferred from the header - see the
@@ -216,14 +219,8 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
216
219
  // MySQL/MariaDB null-safe inequality: true when values differ or one side is NULL.
217
220
  return `NOT (${field} <=> ${ph})`;
218
221
  }
219
- /**
220
- * `JSON_MERGE_PRESERVE` concatenates arrays and creates absent keys, so every pushed key is
221
- * handled in one call that references `expr` once - unlike `JSON_ARRAY_APPEND`, which needs a
222
- * second reference for the array source and returns NULL on MariaDB for an absent key.
223
- */
224
- jsonPush(ctx, expr, push) {
225
- const entries = Object.entries(push).map(([key, value]) => `'${key}', JSON_ARRAY(${this.jsonScalarParam(ctx, value)})`);
226
- return `JSON_MERGE_PRESERVE(${expr}, JSON_OBJECT(${entries.join(', ')}))`;
222
+ jsonAppended(ctx, array, value) {
223
+ return `JSON_ARRAY_APPEND(${array}, '$', ${this.jsonScalarParam(ctx, value)})`;
227
224
  }
228
225
  /**
229
226
  * `->` for the value and `->>` for its text, each taking the whole path (`'$.a.b'`): a bare key, as
@@ -238,10 +235,13 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
238
235
  }
239
236
  /** Only an array's, where `JSON_LENGTH` counts a scalar as 1 and an object by its keys. */
240
237
  jsonLength(slot) {
241
- return `CASE WHEN ${this.jsonIsArray(slot)} THEN JSON_LENGTH(${this.jsonValue(slot)}) END`;
238
+ return `CASE WHEN ${this.jsonIs(slot, 'array')} THEN JSON_LENGTH(${this.jsonValue(slot)}) END`;
239
+ }
240
+ jsonIs(slot, kind) {
241
+ return `JSON_TYPE(${this.jsonValue(slot)}) = '${kind.toUpperCase()}'`;
242
242
  }
243
- jsonIsArray(slot) {
244
- return `JSON_TYPE(${this.jsonValue(slot)}) = 'ARRAY'`;
243
+ jsonIsNull(slot) {
244
+ return `COALESCE(JSON_TYPE(${this.jsonValue(slot)}), 'NULL') = 'NULL'`;
245
245
  }
246
246
  /**
247
247
  * 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,25 @@ 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` keeps the surviving elements in their original order. */
126
+ protected jsonKept(ctx: QueryContext, slot: JsonSlot, item: unknown): string;
127
+ /** Each key or dotted path set as `jsonb`, which `JSONB_SET` takes and nothing else. */
128
+ protected jsonSet(ctx: QueryContext, expr: string, set: Record<string, unknown>): string;
124
129
  /**
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.
130
+ * A value as `jsonb` inside a document: a null one JSON's, as `JSONB_SET` and a comparison need, and a `sql()`
131
+ * one read back out of an object, since `TO_JSONB` refuses an untyped literal.
127
132
  */
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;
133
+ private jsonbOf;
134
+ /** `JSONB_BUILD_ARRAY` takes any type, and a NULL as JSON's null. */
135
+ protected jsonAppended(ctx: QueryContext, array: string, value: unknown): string;
136
+ protected readonly jsonEmptyObject = "'{}'::jsonb";
137
+ protected readonly jsonEmptyArray = "'[]'::jsonb";
138
+ /** `JSONB_SET` takes one path, so each key wraps the last. */
139
+ protected jsonWriteKeys(expr: string, writes: readonly JsonKeyWrite[], { create }: {
140
+ create: boolean;
141
+ }): string;
142
+ /** A replace hands an absent key's NULL back, which `JSONB_SET` would answer for the whole document. */
143
+ private jsonSetKey;
137
144
  protected jsonUnset(ctx: QueryContext, expr: string, unset: readonly string[]): string;
138
145
  /** Postgres binds JSON with a numbered placeholder and an explicit cast, per driver capability. */
139
146
  protected jsonScalarParam(ctx: QueryContext, value: unknown): string;