uql-orm 0.107.3 → 0.108.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.
- package/dist/browser/uql-browser.min.js +2 -2
- package/dist/browser/uql-browser.min.js.map +5 -5
- package/dist/cockroachdb/cockroachDialect.d.ts +1 -4
- package/dist/cockroachdb/cockroachDialect.js +1 -5
- package/dist/dialect/abstractSqlDialect.d.ts +84 -43
- package/dist/dialect/abstractSqlDialect.js +270 -192
- package/dist/dialect/aliases.d.ts +2 -0
- package/dist/dialect/aliases.js +2 -0
- package/dist/dialect/jsonSql.d.ts +9 -7
- package/dist/dialect/jsonSql.js +16 -10
- package/dist/dialect/mergeSqlDialect.d.ts +5 -7
- package/dist/dialect/mergeSqlDialect.js +20 -19
- package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
- package/dist/dialect/mysqlLikeSqlDialect.js +34 -12
- package/dist/dialect/operators.d.ts +7 -1
- package/dist/dialect/operators.js +37 -2
- package/dist/dialect/pgLikeSqlDialect.d.ts +4 -4
- package/dist/dialect/pgLikeSqlDialect.js +8 -7
- package/dist/entity/index.d.ts +1 -1
- package/dist/entity/index.js +1 -1
- package/dist/entity/metadata/definedFixture/author.d.ts +4 -4
- package/dist/entity/metadata/definedFixture/book.d.ts +5 -5
- package/dist/entity/metadata/definition.d.ts +2 -0
- package/dist/entity/metadata/definition.js +19 -11
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mariadb/mariaDialect.d.ts +2 -2
- package/dist/mariadb/mariaDialect.js +3 -2
- package/dist/migrate/codegen/fieldOptionsSource.js +28 -7
- package/dist/migrate/ddl/defaultSql.d.ts +3 -2
- package/dist/migrate/ddl/defaultSql.js +8 -12
- package/dist/migrate/ddl/mysqlTableDdl.js +1 -1
- package/dist/migrate/ddl/tableDdl.d.ts +1 -1
- package/dist/migrate/drift/driftDetector.js +10 -3
- package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/mssqlIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/mysqlIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
- package/dist/migrate/introspection/sqliteIntrospector.d.ts +2 -2
- package/dist/migrate/migrator.js +2 -1
- package/dist/migrate/schemaChange.d.ts +0 -2
- package/dist/migrate/schemaChange.js +1 -4
- package/dist/migrate/schemaGenerator.d.ts +2 -2
- package/dist/migrate/triggerSql.js +11 -15
- package/dist/mongodb/mongoDialect.d.ts +6 -1
- package/dist/mongodb/mongoDialect.js +90 -46
- package/dist/mongodb/mongoSchemaGenerator.js +2 -2
- package/dist/mongodb/mongodbQuerier.d.ts +7 -9
- package/dist/mongodb/mongodbQuerier.js +54 -47
- package/dist/mssql/mssqlDialect.d.ts +9 -9
- package/dist/mssql/mssqlDialect.js +51 -28
- package/dist/mssql/mssqlWireTypes.d.ts +1 -4
- package/dist/mssql/mssqlWireTypes.js +19 -10
- package/dist/querier/abstractQuerier.d.ts +53 -29
- package/dist/querier/abstractQuerier.js +154 -102
- package/dist/querier/abstractSqlQuerier.d.ts +41 -10
- package/dist/querier/abstractSqlQuerier.js +145 -79
- package/dist/schema/declaredColumn.js +2 -2
- package/dist/schema/schemaASTDiffer.d.ts +3 -3
- package/dist/schema/sqlExpression.d.ts +7 -5
- package/dist/schema/sqlExpression.js +20 -16
- package/dist/schema/types.d.ts +8 -2
- package/dist/sqlite/sqliteDialect.js +1 -2
- package/dist/type/definedEntity.d.ts +5 -5
- package/dist/type/dialect.d.ts +26 -15
- package/dist/type/entity.d.ts +14 -8
- package/dist/type/query.d.ts +7 -2
- package/dist/type/queryAggregate.d.ts +4 -4
- package/dist/type/querySql.d.ts +4 -1
- package/dist/type/querySql.js +5 -1
- package/dist/type/queryWhere.d.ts +16 -11
- package/dist/type/universalQuerier.d.ts +7 -7
- package/dist/util/ddlExpression.util.d.ts +5 -0
- package/dist/util/ddlExpression.util.js +9 -2
- package/dist/util/dialect.util.d.ts +14 -6
- package/dist/util/dialect.util.js +17 -13
- package/dist/util/field.util.d.ts +12 -0
- package/dist/util/field.util.js +17 -1
- package/dist/util/fieldOption.util.js +5 -1
- package/dist/util/object.util.d.ts +4 -0
- package/dist/util/object.util.js +13 -0
- package/dist/util/query.util.d.ts +5 -3
- package/dist/util/query.util.js +7 -2
- package/dist/util/sql.d.ts +25 -7
- package/dist/util/sql.js +58 -18
- package/dist/util/triggerWrite.d.ts +7 -4
- package/dist/util/triggerWrite.js +5 -4
- package/package.json +1 -1
- package/skills/uql-orm/SKILL.md +27 -19
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { fieldOf, getMeta, relationOf } from '../entity/index.js';
|
|
2
|
-
import { generatesKey,
|
|
3
|
-
import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, renderSql, RAW_ALIAS, } from '../type/index.js';
|
|
2
|
+
import { generatesKey, ownsSoleKey, valueFieldOf } from '../entity/metadata/definition.js';
|
|
3
|
+
import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, REF_ENTITY, REF_KEY, ColumnRef, renderSql, RAW_ALIAS, } from '../type/index.js';
|
|
4
4
|
import { utcTimestamp } from '../util/date.js';
|
|
5
|
-
import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
|
|
6
|
-
import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql,
|
|
5
|
+
import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys, lacksValueOnInsert, } from '../util/field.util.js';
|
|
6
|
+
import { RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, hasTriggers, foundRowAssigned, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, columnRef, refOwner, throwUnknownAggregateColumn, } from '../util/index.js';
|
|
7
7
|
import { cachedIn, isJsonScalar } from '../util/object.util.js';
|
|
8
8
|
import { escapeAnsiSqlLiteral } from '../util/sqlLiteral.js';
|
|
9
9
|
import { kindOf, UqlUsageError } from '../util/uqlError.js';
|
|
10
10
|
import { AGGREGATE_PAGE_ALIAS, AGGREGATE_VALUE_ALIAS, ROWS_ALIAS, JSON_ELEM_ALIAS, JSON_PULL_ALIAS, relationSortColumn, } from './aliases.js';
|
|
11
|
-
import { holdsOperator, chainedCall, jsonCompareMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, unlessThen, } from './jsonSql.js';
|
|
11
|
+
import { holdsOperator, chainedCall, jsonCompareMode, literalMode, jsonTypeMode, jsonElemExists, jsonPath, jsonRemoveCall, jsonSetCall, jsonSetTarget, unlessThen, } from './jsonSql.js';
|
|
12
12
|
import { betweenBounds, EQUALITY_OPS, GROUP_OPS, groupClauses, inOperands, isGroupOp, isOrderedOp, isVectorQuery, LIKE_OPS, namesRows, ORDERED_OPS, ORDERED_SYMBOLS, sizeComparisons, VECTOR_QUERY_KEY_SET, whereOperators, } from './operators.js';
|
|
13
13
|
import { SqlQueryContext } from './queryContext.js';
|
|
14
14
|
import { groupPathField, NO_JOINS, aggregateColumnField, resolveGroupJoins, resolveQueryJoins, relationSortTerms, resolveSortableJoin, } from './queryJoins.js';
|
|
@@ -72,11 +72,19 @@ function chain(parts, op) {
|
|
|
72
72
|
* How `op` reads a JSON value: an ordered comparison as a number, an equality as its operand compares,
|
|
73
73
|
* and a pattern or a null check as text.
|
|
74
74
|
*/
|
|
75
|
-
function jsonOperatorMode(op, value) {
|
|
75
|
+
function jsonOperatorMode(op, value, scope) {
|
|
76
76
|
if (ORDERED_OPS.has(op)) {
|
|
77
77
|
return 'numeric';
|
|
78
78
|
}
|
|
79
|
-
return EQUALITY_OPS.has(op) ? jsonCompareMode(value) : 'text';
|
|
79
|
+
return EQUALITY_OPS.has(op) ? jsonCompareMode(value, (operand) => operandMode(operand, scope)) : 'text';
|
|
80
|
+
}
|
|
81
|
+
/** The mode an operand asks for: a ref by its column's declared type, as an index over the path reads it; else its own. */
|
|
82
|
+
function operandMode(operand, scope) {
|
|
83
|
+
if (!(operand instanceof ColumnRef)) {
|
|
84
|
+
return literalMode(operand);
|
|
85
|
+
}
|
|
86
|
+
const key = operand[REF_KEY];
|
|
87
|
+
return jsonTypeMode(getMeta(refOwner(operand[REF_ENTITY], key, scope)).fields[key]?.type);
|
|
80
88
|
}
|
|
81
89
|
/** `$group` aggregate operator to SQL function name, over ops `resolveAggregateOp` has already allowlisted. */
|
|
82
90
|
const AGGREGATE_FN = {
|
|
@@ -166,8 +174,8 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
166
174
|
return fragmentCtx.sql;
|
|
167
175
|
}
|
|
168
176
|
/** A `sql()` rendered in place, an operand or a projected term: bound, the driver would get the object. */
|
|
169
|
-
rawFragment(ctx, value,
|
|
170
|
-
return this.buildFragment(ctx, (fragmentCtx) => this.getRawValue(fragmentCtx, {
|
|
177
|
+
rawFragment(ctx, value, scope = {}) {
|
|
178
|
+
return this.buildFragment(ctx, (fragmentCtx) => this.getRawValue(fragmentCtx, { ...scope, value }));
|
|
171
179
|
}
|
|
172
180
|
/**
|
|
173
181
|
* Each operand rendered on its own, keeping those that emitted SQL: an empty one leaves no dangling
|
|
@@ -178,9 +186,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
178
186
|
.map((operand) => this.buildFragment(ctx, (fragmentCtx) => render(fragmentCtx, operand)))
|
|
179
187
|
.filter((part) => part !== '');
|
|
180
188
|
}
|
|
181
|
-
|
|
189
|
+
/** `value` bound, or SQL rendered where it stands, in `scope` where a field is compared with it, so a ref names its column as the field is named. */
|
|
190
|
+
addValue(ctx, value, scope) {
|
|
182
191
|
if (value instanceof QuerySql) {
|
|
183
|
-
return this.rawFragment(ctx, value);
|
|
192
|
+
return this.rawFragment(ctx, value, scope);
|
|
184
193
|
}
|
|
185
194
|
if (ctx.inlineValues) {
|
|
186
195
|
return this.escape(this.normalizeValue(value));
|
|
@@ -213,17 +222,34 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
213
222
|
return expression ? `RETURNING ${expression}` : '';
|
|
214
223
|
}
|
|
215
224
|
/**
|
|
216
|
-
*
|
|
217
|
-
*
|
|
225
|
+
* Whether a `write` of `meta`'s rows reports them as written: where the engine's `write` reports rows, and no trigger
|
|
226
|
+
* or stamp can change the row after it, on an engine whose trigger cannot assign to its row.
|
|
227
|
+
*/
|
|
228
|
+
reportsWrite(meta, write) {
|
|
229
|
+
const { reportsWrites, triggers } = this.features;
|
|
230
|
+
return reportsWrites.includes(write) && (triggers.assignsRow || !hasTriggers(meta));
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The `write` `render` appends, reporting the fields `returning` names of each row it writes, projected and read
|
|
234
|
+
* as a read's are: the terms its rows answer under, none where it names none. `render` takes what goes between the
|
|
235
|
+
* target and its rows; here nothing, as a ` RETURNING` follows the write. Refused where the engine's `write`
|
|
236
|
+
* reports no rows, which `features.reportsWrites` says.
|
|
218
237
|
*/
|
|
219
|
-
|
|
220
|
-
|
|
238
|
+
reportedWrite(ctx, entity, returning, write, render) {
|
|
239
|
+
if (returning && !this.features.reportsWrites.includes(write)) {
|
|
240
|
+
throw new UqlUsageError(`${this.engineName} reports no rows of a write's ${write}: read them back instead`);
|
|
241
|
+
}
|
|
242
|
+
render('');
|
|
243
|
+
if (!returning) {
|
|
244
|
+
return [];
|
|
245
|
+
}
|
|
246
|
+
const terms = this.selectTerms(ctx, entity, keySet(returning));
|
|
221
247
|
ctx.append(` RETURNING ${this.termsSql(terms)}`);
|
|
222
248
|
return terms;
|
|
223
249
|
}
|
|
224
250
|
/** What the returned row is read off, for an engine that names it: SQL Server's `INSERTED.`. */
|
|
225
251
|
returnedRowPrefix = '';
|
|
226
|
-
/** `<id column> AS` {@link RETURNED_ID}
|
|
252
|
+
/** `<id column> AS` {@link RETURNED_ID}, as a clause reporting an insert's id lists it. */
|
|
227
253
|
returningIdExpression(meta) {
|
|
228
254
|
const [idKey] = meta.ids;
|
|
229
255
|
return meta.ids.length === 1
|
|
@@ -270,7 +296,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
270
296
|
return [{ sql: `${this.escapeId(opts.prefix, true, true)}*`, bare: true, kinds }];
|
|
271
297
|
}
|
|
272
298
|
return keys.map((key) => key instanceof QuerySql
|
|
273
|
-
? { sql: this.rawFragment(ctx, key, opts.prefix), key: key[RAW_ALIAS] }
|
|
299
|
+
? { sql: this.rawFragment(ctx, key, { prefix: opts.prefix }), key: key[RAW_ALIAS] }
|
|
274
300
|
: this.fieldTerm(ctx, meta, key, opts));
|
|
275
301
|
}
|
|
276
302
|
/** One field's column, or the expression an inlined one stands for, as the projection reads it. */
|
|
@@ -525,23 +551,12 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
525
551
|
}
|
|
526
552
|
compare(ctx, entity, key, val, opts = {}) {
|
|
527
553
|
const meta = getMeta(entity);
|
|
528
|
-
if (val instanceof QuerySql) {
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
this.getRawValue(ctx, {
|
|
535
|
-
value: val,
|
|
536
|
-
prefix: alias,
|
|
537
|
-
escapedPrefix: this.escapeId(alias, true, true),
|
|
538
|
-
});
|
|
539
|
-
ctx.append(')');
|
|
540
|
-
return;
|
|
541
|
-
}
|
|
542
|
-
this.getComparisonKey(ctx, entity, key, opts);
|
|
543
|
-
ctx.append(' = ');
|
|
544
|
-
this.getRawValue(ctx, { ...opts, value: val });
|
|
554
|
+
if ((key === '$exists' || key === '$nexists') && val instanceof QuerySql) {
|
|
555
|
+
// The read's alias: the enclosing statement declares one, and Postgres forbids reaching past
|
|
556
|
+
// it to the qualified name it aliased.
|
|
557
|
+
const alias = opts.prefix ?? this.resolveTableAlias(meta);
|
|
558
|
+
const subquery = this.rawFragment(ctx, val, { prefix: alias });
|
|
559
|
+
ctx.append(`${key === '$exists' ? 'EXISTS' : 'NOT EXISTS'} (${subquery})`);
|
|
545
560
|
return;
|
|
546
561
|
}
|
|
547
562
|
if (key === '$text') {
|
|
@@ -553,9 +568,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
553
568
|
return;
|
|
554
569
|
}
|
|
555
570
|
// Detect JSONB dot-notation: 'column.path' where column is a registered JSON/JSONB field
|
|
556
|
-
const jsonDot = this.resolveJsonDotPath(meta, key, opts
|
|
571
|
+
const jsonDot = this.resolveJsonDotPath(meta, key, opts);
|
|
557
572
|
if (jsonDot) {
|
|
558
|
-
ctx.append(this.jsonConditions(ctx, this.jsonPathTarget(jsonDot), val));
|
|
573
|
+
ctx.append(this.jsonConditions(ctx, this.jsonPathTarget(jsonDot), val, { ...opts, entity }));
|
|
559
574
|
return;
|
|
560
575
|
}
|
|
561
576
|
if (key.includes('.')) {
|
|
@@ -621,9 +636,13 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
621
636
|
// Stated on every engine, although only SQLite and SQL Server lack `\` as their default escape.
|
|
622
637
|
return `${fold ? `LOWER(${operand})` : operand} ${matchOp} ${ph} ESCAPE ${this.escape('\\')}`;
|
|
623
638
|
}
|
|
639
|
+
/** What a column is read off: the qualifier already escaped, else the alias in scope escaped with its dot. */
|
|
640
|
+
qualifierOf(opts) {
|
|
641
|
+
return opts.escapedPrefix ?? this.escapeId(opts.prefix, true, true);
|
|
642
|
+
}
|
|
624
643
|
/** Builds `prefix.column` from an already-resolved field, through the same memo writes use. */
|
|
625
644
|
columnWithPrefix(key, field, opts) {
|
|
626
|
-
return
|
|
645
|
+
return this.qualifierOf(opts) + this.escapedColumnOf(key, field);
|
|
627
646
|
}
|
|
628
647
|
/**
|
|
629
648
|
* The SQL a field comparison reads its left-hand side from. An inlined field builds its expression
|
|
@@ -643,7 +662,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
643
662
|
inlinedOperand(ctx, meta, key, prefix) {
|
|
644
663
|
const field = meta.fields[key];
|
|
645
664
|
return field && isInlinedExpression(field)
|
|
646
|
-
? this.rawFragment(ctx, columnRef(meta.entity, key),
|
|
665
|
+
? this.rawFragment(ctx, columnRef(meta.entity, key), {
|
|
666
|
+
prefix: prefix ?? this.resolveTableAlias(meta),
|
|
667
|
+
entity: meta.entity,
|
|
668
|
+
})
|
|
647
669
|
: undefined;
|
|
648
670
|
}
|
|
649
671
|
/** {@link fieldCondition}, appended. */
|
|
@@ -659,7 +681,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
659
681
|
return this.vectorNearCondition(ctx, getMeta(entity), key, val, opts.prefix);
|
|
660
682
|
}
|
|
661
683
|
const field = this.resolveOperandField(ctx, entity, key, opts);
|
|
662
|
-
const
|
|
684
|
+
const scope = { ...opts, entity };
|
|
685
|
+
const condition = this.operatorCondition(ctx, field, op, val, (value) => this.addValue(ctx, value, scope)) ??
|
|
686
|
+
this.jsonArrayCondition(ctx, { base: field, path: '' }, op, val, scope);
|
|
663
687
|
return orRefuse(condition, `unknown operator: ${op}`);
|
|
664
688
|
}
|
|
665
689
|
/**
|
|
@@ -711,14 +735,14 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
711
735
|
}
|
|
712
736
|
}
|
|
713
737
|
/** `$all`, `$size` and `$elemMatch`, which read the JSON array at `slot`; `undefined` for the rest. */
|
|
714
|
-
jsonArrayCondition(ctx, slot, op, val) {
|
|
738
|
+
jsonArrayCondition(ctx, slot, op, val, scope) {
|
|
715
739
|
switch (op) {
|
|
716
740
|
case '$all':
|
|
717
|
-
return this.jsonAll(ctx, slot, val);
|
|
741
|
+
return this.jsonAll(ctx, slot, val, scope);
|
|
718
742
|
case '$size':
|
|
719
743
|
return this.sizeCondition(ctx, (fragmentCtx) => fragmentCtx.append(this.jsonLength(slot)), val);
|
|
720
744
|
case '$elemMatch':
|
|
721
|
-
return this.jsonElemMatch(ctx, slot, val);
|
|
745
|
+
return this.jsonElemMatch(ctx, slot, val, scope);
|
|
722
746
|
default:
|
|
723
747
|
return undefined;
|
|
724
748
|
}
|
|
@@ -728,37 +752,52 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
728
752
|
return { slot, read: (mode) => this.jsonPathExpr(slot.base, slot.path, mode) };
|
|
729
753
|
}
|
|
730
754
|
/** Every operator `target` is compared with, `AND`-joined. */
|
|
731
|
-
jsonConditions(ctx, target, val) {
|
|
732
|
-
return conjunction(whereOperators(val, 'unknown operator').map(([op, value]) => this.jsonCondition(ctx, target, op, value)));
|
|
755
|
+
jsonConditions(ctx, target, val, scope) {
|
|
756
|
+
return conjunction(whereOperators(val, 'unknown operator').map(([op, value]) => this.jsonCondition(ctx, target, op, value, scope)));
|
|
733
757
|
}
|
|
734
|
-
jsonCondition(ctx, target, op, value) {
|
|
758
|
+
jsonCondition(ctx, target, op, value, scope) {
|
|
735
759
|
if (op === '$not') {
|
|
736
|
-
return `NOT (${this.jsonConditions(ctx, target, value)})`;
|
|
760
|
+
return `NOT (${this.jsonConditions(ctx, target, value, scope)})`;
|
|
737
761
|
}
|
|
738
|
-
const array = this.jsonArrayCondition(ctx, target.slot, op, value);
|
|
762
|
+
const array = this.jsonArrayCondition(ctx, target.slot, op, value, scope);
|
|
739
763
|
if (array !== undefined) {
|
|
740
764
|
return array;
|
|
741
765
|
}
|
|
742
|
-
const mode = jsonOperatorMode(op, value);
|
|
766
|
+
const mode = jsonOperatorMode(op, value, scope);
|
|
743
767
|
const operand = target.read(mode);
|
|
744
768
|
// Only a boolean compares as a JSON value, so the set holds two at most, and MySQL documents `IN()`
|
|
745
769
|
// as unsupported on JSON values: the comparisons are spelled out.
|
|
746
770
|
if (mode === 'json' && (op === '$in' || op === '$nin')) {
|
|
747
771
|
const negate = op === '$nin';
|
|
748
|
-
const comparisons = inOperands(op, value).map((val) => `${operand} ${negate ? '<>' : '='} ${this.
|
|
772
|
+
const comparisons = inOperands(op, value).map((val) => `${operand} ${negate ? '<>' : '='} ${this.jsonOperand(ctx, val, mode, scope)}`);
|
|
749
773
|
return `(${comparisons.join(negate ? ' AND ' : ' OR ')})`;
|
|
750
774
|
}
|
|
751
|
-
const condition = this.operatorCondition(ctx, operand, op, value, (val) => this.jsonOperand(ctx, val, mode));
|
|
775
|
+
const condition = this.operatorCondition(ctx, operand, op, value, (val) => this.jsonOperand(ctx, val, mode, scope));
|
|
752
776
|
return orRefuse(condition, `unknown operator: ${op}`);
|
|
753
777
|
}
|
|
754
|
-
/**
|
|
755
|
-
|
|
778
|
+
/**
|
|
779
|
+
* An operand of a JSON comparison, read the way `mode` reads the path it is compared with. SQL in `json` mode
|
|
780
|
+
* is a boolean column's ref, which no engine casts to JSON alike, so its value picks the JSON literal.
|
|
781
|
+
*/
|
|
782
|
+
jsonOperand(ctx, value, mode, scope) {
|
|
783
|
+
if (value instanceof QuerySql) {
|
|
784
|
+
const column = this.rawFragment(ctx, value, scope);
|
|
785
|
+
if (mode !== 'json') {
|
|
786
|
+
return mode === 'text' ? this.textOperand(column) : column;
|
|
787
|
+
}
|
|
788
|
+
const arms = [true, false].map((it) => `WHEN ${this.addValue(ctx, it)} THEN ${this.jsonScalarParam(ctx, it)}`);
|
|
789
|
+
return `CASE ${column} ${arms.join(' ')} END`;
|
|
790
|
+
}
|
|
756
791
|
if (mode === 'json') {
|
|
757
792
|
return this.jsonScalarParam(ctx, value);
|
|
758
793
|
}
|
|
759
794
|
const placeholder = this.addValue(ctx, value);
|
|
760
795
|
return mode === 'numeric' ? this.numericCast(placeholder) : placeholder;
|
|
761
796
|
}
|
|
797
|
+
/** A column compared with a JSON path's text, as it compares: as it is, where the engine converts it. */
|
|
798
|
+
textOperand(column) {
|
|
799
|
+
return column;
|
|
800
|
+
}
|
|
762
801
|
/** The JSON value at `slot`, as an array operator reads it. */
|
|
763
802
|
jsonValue(slot) {
|
|
764
803
|
return slot.path ? this.jsonPathExpr(slot.base, slot.path, 'json') : slot.base;
|
|
@@ -768,15 +807,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
768
807
|
* `JSON_CONTAINS` read one: a scalar equal, an array each of its elements, an object each of its keys.
|
|
769
808
|
* Plain JSON goes to {@link jsonContains}; an operator anywhere in it is matched element by element.
|
|
770
809
|
*/
|
|
771
|
-
jsonAll(ctx, slot, values) {
|
|
772
|
-
return holdsOperator(values) ? this.jsonElemsHold(ctx, slot, values) : this.jsonContains(ctx, slot, values);
|
|
810
|
+
jsonAll(ctx, slot, values, scope) {
|
|
811
|
+
return holdsOperator(values) ? this.jsonElemsHold(ctx, slot, values, scope) : this.jsonContains(ctx, slot, values);
|
|
773
812
|
}
|
|
774
813
|
/** `$all` over plain JSON, which an engine with containment of its own spells natively, for an index to serve. */
|
|
775
814
|
jsonContains(ctx, slot, values) {
|
|
776
|
-
return this.jsonElemsHold(ctx, slot, values);
|
|
815
|
+
return this.jsonElemsHold(ctx, slot, values, {});
|
|
777
816
|
}
|
|
778
817
|
/** One `EXISTS` per value, over the elements of the array at `slot`: a scalar equal, anything else held. */
|
|
779
|
-
jsonElemsHold(ctx, slot, values) {
|
|
818
|
+
jsonElemsHold(ctx, slot, values, scope) {
|
|
780
819
|
const alias = ctx.claimAlias(JSON_ELEM_ALIAS);
|
|
781
820
|
const from = this.jsonElemFrom(slot, alias);
|
|
782
821
|
const element = {
|
|
@@ -785,7 +824,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
785
824
|
};
|
|
786
825
|
const conditions = values.map((value) => {
|
|
787
826
|
const holds = isOperatorMap(value) || Array.isArray(value)
|
|
788
|
-
? this.jsonHolds(ctx, element, value)
|
|
827
|
+
? this.jsonHolds(ctx, element, value, scope)
|
|
789
828
|
: [this.jsonElemEquals(ctx, slot, alias, value)];
|
|
790
829
|
return jsonElemExists(from, holds, this.jsonElemHint);
|
|
791
830
|
});
|
|
@@ -795,15 +834,15 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
795
834
|
* What the JSON `target` reads satisfies to hold `value`: an array each of its elements, an object each
|
|
796
835
|
* of its keys as a path, and an operator map or a scalar compared as a path is.
|
|
797
836
|
*/
|
|
798
|
-
jsonHolds(ctx, target, value) {
|
|
837
|
+
jsonHolds(ctx, target, value, scope) {
|
|
799
838
|
if (Array.isArray(value)) {
|
|
800
|
-
return [this.jsonAll(ctx, target.slot, value)];
|
|
839
|
+
return [this.jsonAll(ctx, target.slot, value, scope)];
|
|
801
840
|
}
|
|
802
841
|
if (!isJsonObject(value)) {
|
|
803
|
-
return [this.jsonConditions(ctx, target, value)];
|
|
842
|
+
return [this.jsonConditions(ctx, target, value, scope)];
|
|
804
843
|
}
|
|
805
844
|
const { base, path } = target.slot;
|
|
806
|
-
return Object.entries(value).flatMap(([key, item]) => this.jsonHolds(ctx, this.jsonPathTarget({ base, path: path ? `${path}.${key}` : key }), item));
|
|
845
|
+
return Object.entries(value).flatMap(([key, item]) => this.jsonHolds(ctx, this.jsonPathTarget({ base, path: path ? `${path}.${key}` : key }), item, scope));
|
|
807
846
|
}
|
|
808
847
|
/** An element of the array at `slot` equal to `value`, both read as JSON. */
|
|
809
848
|
jsonElemEquals(ctx, slot, alias, value) {
|
|
@@ -811,7 +850,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
811
850
|
}
|
|
812
851
|
/** The JSON array at `slot` contains at least one of `values`, each as `$all` reads it. */
|
|
813
852
|
jsonAny(ctx, slot, values) {
|
|
814
|
-
const anyOf = values.map((value) => this.
|
|
853
|
+
const anyOf = values.map((value) => this.jsonContains(ctx, slot, [value]));
|
|
815
854
|
return `(${chain(anyOf, 'OR')})`;
|
|
816
855
|
}
|
|
817
856
|
/** An element of the array at `slot` itself, read the way `mode` reads a path: its document, or its root. */
|
|
@@ -824,7 +863,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
824
863
|
* itself. An element equal to one value, or to one of several, is containment whatever the operator
|
|
825
864
|
* says, which compares by JSON type and is what an array index serves.
|
|
826
865
|
*/
|
|
827
|
-
jsonElemMatch(ctx, slot, match) {
|
|
866
|
+
jsonElemMatch(ctx, slot, match, scope) {
|
|
828
867
|
const keys = Object.keys(match);
|
|
829
868
|
if (keys.some(isOperatorKey) && !keys.every(isOperatorKey)) {
|
|
830
869
|
throw new UqlUsageError(`$elemMatch cannot mix operators with field names: ${keys.join(', ')}`);
|
|
@@ -832,12 +871,12 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
832
871
|
const single = keys.length === 1;
|
|
833
872
|
const { $eq: equal, $in: within } = match;
|
|
834
873
|
if (single && isJsonScalar(equal)) {
|
|
835
|
-
return this.jsonAll(ctx, slot, [equal]);
|
|
874
|
+
return this.jsonAll(ctx, slot, [equal], scope);
|
|
836
875
|
}
|
|
837
876
|
if (single && Array.isArray(within) && within.length > 0 && within.every(isJsonScalar)) {
|
|
838
877
|
return this.jsonAny(ctx, slot, within);
|
|
839
878
|
}
|
|
840
|
-
return this.jsonAll(ctx, slot, [match]);
|
|
879
|
+
return this.jsonAll(ctx, slot, [match], scope);
|
|
841
880
|
}
|
|
842
881
|
/** The optimizer hint a `$elemMatch` subquery opens with, where the engine plans one wrong without it. */
|
|
843
882
|
jsonElemHint = '';
|
|
@@ -851,10 +890,6 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
851
890
|
}
|
|
852
891
|
return this.jsonCast(this.addValue(ctx, JSON.stringify(value)));
|
|
853
892
|
}
|
|
854
|
-
/** {@link resolveOperandField}, appended. */
|
|
855
|
-
getComparisonKey(ctx, entity, key, opts = {}) {
|
|
856
|
-
ctx.append(this.resolveOperandField(ctx, entity, key, opts));
|
|
857
|
-
}
|
|
858
893
|
/** Appends the `ORDER BY`, reporting whether there was one - which {@link pager} needs on the
|
|
859
894
|
* engines that refuse to page an unordered statement. */
|
|
860
895
|
sort(ctx, entity, q, opts = {}) {
|
|
@@ -962,7 +997,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
962
997
|
const expr = this.inlinedOperand(ctx, meta, key, prefix) ?? this.columnWithPrefix(key, field, { prefix });
|
|
963
998
|
return [{ expr, output: false }];
|
|
964
999
|
}
|
|
965
|
-
const json = this.resolveJsonDotPath(meta, key, prefix);
|
|
1000
|
+
const json = this.resolveJsonDotPath(meta, key, { prefix });
|
|
966
1001
|
if (!json) {
|
|
967
1002
|
return [{ expr: this.escapeId(key), output: true }];
|
|
968
1003
|
}
|
|
@@ -1243,22 +1278,30 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1243
1278
|
return alias === name ? opts : { ...opts, alias };
|
|
1244
1279
|
}
|
|
1245
1280
|
/**
|
|
1246
|
-
* The clause that returns
|
|
1281
|
+
* The clause that returns an insert's ids. It is `''` on an engine whose
|
|
1247
1282
|
* statement cannot return them, and on a composite key, which has no id to ask for.
|
|
1248
1283
|
*/
|
|
1249
1284
|
insertedIdReturning(meta) {
|
|
1250
1285
|
return this.insertIdSource === 'returning' ? this.returningId(meta) : '';
|
|
1251
1286
|
}
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1287
|
+
/**
|
|
1288
|
+
* An insert of `payload` reporting each row's id, or the fields `returning` names, as its write reports
|
|
1289
|
+
* them: the terms it answers under, none for the id alone.
|
|
1290
|
+
*/
|
|
1291
|
+
insert(ctx, entity, payload, returning) {
|
|
1292
|
+
if (returning) {
|
|
1293
|
+
return this.reportedWrite(ctx, entity, returning, 'insert', (afterTarget) => this.appendInsertValues(ctx, entity, payload, afterTarget));
|
|
1294
|
+
}
|
|
1295
|
+
const idReturning = this.insertedIdReturning(getMeta(entity));
|
|
1296
|
+
if (idReturning && this.returningPosition === 'afterTarget') {
|
|
1297
|
+
this.appendInsertValues(ctx, entity, payload, idReturning);
|
|
1298
|
+
return [];
|
|
1257
1299
|
}
|
|
1258
1300
|
this.appendInsertValues(ctx, entity, payload);
|
|
1259
|
-
if (
|
|
1260
|
-
ctx.append(` ${
|
|
1301
|
+
if (idReturning) {
|
|
1302
|
+
ctx.append(` ${idReturning}`);
|
|
1261
1303
|
}
|
|
1304
|
+
return [];
|
|
1262
1305
|
}
|
|
1263
1306
|
/**
|
|
1264
1307
|
* What a text search matches and a fulltext index covers, which have to agree for the index to serve the
|
|
@@ -1344,43 +1387,60 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1344
1387
|
appendDefaultInsertValue(ctx, _field) {
|
|
1345
1388
|
ctx.append('DEFAULT');
|
|
1346
1389
|
}
|
|
1347
|
-
update(ctx, entity, q, payload, opts) {
|
|
1390
|
+
update(ctx, entity, q, payload, opts, returning) {
|
|
1348
1391
|
const meta = getMeta(entity);
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1392
|
+
return this.reportedWrite(ctx, entity, returning, 'update', (afterTarget) => {
|
|
1393
|
+
ctx.append(`UPDATE ${this.escapedTableName(meta)} SET `);
|
|
1394
|
+
this.appendAssignments(ctx, meta, this.updateEntries(meta, payload));
|
|
1395
|
+
ctx.append(afterTarget && ` ${afterTarget}`);
|
|
1396
|
+
this.search(ctx, entity, q, opts);
|
|
1397
|
+
});
|
|
1352
1398
|
}
|
|
1353
|
-
/** What an update assigns: the payload's fields, `onUpdate` fills included. */
|
|
1354
|
-
updateEntries(meta, payload) {
|
|
1355
|
-
const [filled] = fillOnFields(meta, payload, 'onUpdate');
|
|
1399
|
+
/** What an update assigns: the payload's fields, the `onUpdate` fills `scope` can write included. */
|
|
1400
|
+
updateEntries(meta, payload, scope = 'statement') {
|
|
1401
|
+
const [filled] = fillOnFields(meta, payload, 'onUpdate', scope);
|
|
1356
1402
|
return filterFieldKeys(meta, filled, 'onUpdate').map((key) => [key, filled[key]]);
|
|
1357
1403
|
}
|
|
1358
1404
|
/**
|
|
1359
1405
|
* A `SET` list, each assignment reading its column as `qualifier` names it, which an upsert sets: `MERGE`'s
|
|
1360
1406
|
* source and MySQL's new row share the table's column names.
|
|
1361
1407
|
*/
|
|
1362
|
-
appendAssignments(ctx, meta, entries, qualifier = '') {
|
|
1408
|
+
appendAssignments(ctx, meta, entries, qualifier = '', guard) {
|
|
1363
1409
|
entries.forEach(([key, value], i) => {
|
|
1364
1410
|
if (i > 0) {
|
|
1365
1411
|
ctx.append(', ');
|
|
1366
1412
|
}
|
|
1367
|
-
this.appendAssignment(ctx, meta, key, value, qualifier);
|
|
1413
|
+
this.appendAssignment(ctx, meta, key, value, qualifier, guard);
|
|
1368
1414
|
});
|
|
1369
1415
|
}
|
|
1370
1416
|
/**
|
|
1371
1417
|
* `col = value`, a JSON operator or a `$inc`/`$mul` spelled as the engine's. What reads the table, the operators
|
|
1372
|
-
* and the refs in SQL alike, reads it through `qualifier`.
|
|
1418
|
+
* and the refs in SQL alike, reads it through `qualifier`. With a `guard`, the column takes the value only where
|
|
1419
|
+
* that condition holds, and keeps its own elsewhere.
|
|
1373
1420
|
*/
|
|
1374
|
-
appendAssignment(ctx, meta, key, value, qualifier = '') {
|
|
1375
|
-
const field = meta.fields[key];
|
|
1421
|
+
appendAssignment(ctx, meta, key, value, qualifier = '', guard) {
|
|
1376
1422
|
const escapedCol = this.escapedColumnName(meta, key);
|
|
1377
|
-
|
|
1423
|
+
ctx.append(`${escapedCol} = `);
|
|
1424
|
+
if (!guard) {
|
|
1425
|
+
this.appendAssignedValue(ctx, meta, key, value, qualifier);
|
|
1426
|
+
return;
|
|
1427
|
+
}
|
|
1428
|
+
ctx.append('CASE WHEN ');
|
|
1429
|
+
guard(ctx);
|
|
1430
|
+
ctx.append(' THEN ');
|
|
1431
|
+
this.appendAssignedValue(ctx, meta, key, value, qualifier);
|
|
1432
|
+
ctx.append(` ELSE ${qualifier}${escapedCol} END`);
|
|
1433
|
+
}
|
|
1434
|
+
/** What {@link appendAssignment} sets its column to. */
|
|
1435
|
+
appendAssignedValue(ctx, meta, key, value, qualifier) {
|
|
1436
|
+
const field = meta.fields[key];
|
|
1437
|
+
const current = `${qualifier}${this.escapedColumnName(meta, key)}`;
|
|
1378
1438
|
if (isJsonUpdateOp(value)) {
|
|
1379
|
-
this.
|
|
1439
|
+
ctx.append(this.jsonUpdate(ctx, value, field, current));
|
|
1380
1440
|
}
|
|
1381
1441
|
else if (isFieldUpdateOp(value)) {
|
|
1382
1442
|
const [op, operand] = fieldUpdateOf(key, value);
|
|
1383
|
-
ctx.append(
|
|
1443
|
+
ctx.append(`COALESCE(${current}, 0) ${SQL_ARITHMETIC[op]} `);
|
|
1384
1444
|
if (operand instanceof QuerySql) {
|
|
1385
1445
|
ctx.append('(');
|
|
1386
1446
|
this.getRawValue(ctx, { value: operand, escapedPrefix: qualifier });
|
|
@@ -1391,11 +1451,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1391
1451
|
}
|
|
1392
1452
|
}
|
|
1393
1453
|
else if (value instanceof QuerySql) {
|
|
1394
|
-
ctx.append(`${escapedCol} = `);
|
|
1395
1454
|
this.getRawValue(ctx, { value, escapedPrefix: qualifier });
|
|
1396
1455
|
}
|
|
1397
1456
|
else {
|
|
1398
|
-
ctx.append(`${escapedCol} = `);
|
|
1399
1457
|
this.formatPersistableValue(ctx, field, value);
|
|
1400
1458
|
}
|
|
1401
1459
|
}
|
|
@@ -1412,29 +1470,25 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1412
1470
|
const meta = getMeta(write.entity);
|
|
1413
1471
|
const table = this.escapedTableName(meta);
|
|
1414
1472
|
if (write.kind === 'insert' || write.kind === 'upsert') {
|
|
1415
|
-
const
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1473
|
+
const [row] = fillOnFields(meta, { ...write.row }, 'onInsert', 'trigger');
|
|
1474
|
+
const unfilled = definedEntries(meta.fields)
|
|
1475
|
+
.filter(([key, field]) => row[key] === undefined && lacksValueOnInsert(field, ownsSoleKey(meta, key)))
|
|
1476
|
+
.map(([key]) => key);
|
|
1477
|
+
if (unfilled.length) {
|
|
1478
|
+
throw new UqlUsageError(`a trigger's insert into '${meta.name}' leaves out ${unfilled.map((key) => `'${key}'`).join(', ')}, ` +
|
|
1479
|
+
'required with no default and no onInsert a trigger can write, a value or SQL: name it, or give it a default');
|
|
1419
1480
|
}
|
|
1420
|
-
const entries = this.writtenEntries(meta,
|
|
1481
|
+
const entries = this.writtenEntries(meta, row);
|
|
1421
1482
|
if (write.kind === 'insert') {
|
|
1422
1483
|
this.appendTriggerInsert(ctx, meta, entries, rows);
|
|
1423
1484
|
ctx.append(';');
|
|
1424
1485
|
return;
|
|
1425
1486
|
}
|
|
1426
|
-
const {
|
|
1427
|
-
|
|
1428
|
-
const assigned = update === undefined
|
|
1429
|
-
? entries
|
|
1430
|
-
.filter(([key]) => !conflictPaths[key])
|
|
1431
|
-
.map(([key]) => [key, this.incoming(meta, key)])
|
|
1432
|
-
: hasKeys(update)
|
|
1433
|
-
? this.writtenEntries(meta, update)
|
|
1434
|
-
: [];
|
|
1487
|
+
const { q, update } = write;
|
|
1488
|
+
const assigned = this.foundRowEntries(meta, q.$conflict, write.row, update, 'trigger');
|
|
1435
1489
|
this.refuseAccumulating(meta, assigned, rows);
|
|
1436
|
-
const
|
|
1437
|
-
this.appendTriggerUpsert(ctx, meta,
|
|
1490
|
+
const found = this.foundRowUpdate(ctx, write.entity, assigned, q.$where);
|
|
1491
|
+
this.appendTriggerUpsert(ctx, meta, q.$conflict, entries, found, rows);
|
|
1438
1492
|
return;
|
|
1439
1493
|
}
|
|
1440
1494
|
assertWhere(meta, write.where);
|
|
@@ -1443,7 +1497,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1443
1497
|
throw new UqlUsageError(`a trigger's ${write.kind} over '${meta.name}' names no rows, so it would address every one`);
|
|
1444
1498
|
}
|
|
1445
1499
|
if (write.kind === 'update') {
|
|
1446
|
-
const entries = this.
|
|
1500
|
+
const entries = this.triggerUpdateEntries(meta, write.set);
|
|
1447
1501
|
this.refuseAccumulating(meta, entries, rows);
|
|
1448
1502
|
ctx.append(`UPDATE ${table} SET `);
|
|
1449
1503
|
this.appendAssignments(ctx, meta, entries);
|
|
@@ -1484,15 +1538,16 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1484
1538
|
this.formatPersistableValue(ctx, meta.fields[key], value);
|
|
1485
1539
|
});
|
|
1486
1540
|
}
|
|
1487
|
-
/** A trigger's upsert: its insert, then what a conflicting row takes, `
|
|
1488
|
-
appendTriggerUpsert(ctx, meta,
|
|
1541
|
+
/** A trigger's upsert: its insert, then what a conflicting row takes, `found`, or nothing where it assigns none. */
|
|
1542
|
+
appendTriggerUpsert(ctx, meta, conflictKeys, entries, found, rows) {
|
|
1489
1543
|
this.appendTriggerInsert(ctx, meta, entries, rows);
|
|
1490
|
-
ctx.append(`${this.onConflict(meta,
|
|
1544
|
+
ctx.append(`${this.onConflict(meta, conflictKeys, found)};`);
|
|
1491
1545
|
}
|
|
1492
|
-
/** ` ON CONFLICT (keys) DO UPDATE SET ...`, or `DO NOTHING` with nothing to assign. */
|
|
1493
|
-
onConflict(meta,
|
|
1494
|
-
const keys = this.
|
|
1495
|
-
|
|
1546
|
+
/** ` ON CONFLICT (keys) DO UPDATE SET ... WHERE ...`, or `DO NOTHING` with nothing to assign. */
|
|
1547
|
+
onConflict(meta, conflictKeys, { assignments, condition }) {
|
|
1548
|
+
const keys = this.conflictKeysSql(meta, conflictKeys);
|
|
1549
|
+
const update = `DO UPDATE SET ${assignments}${condition && ` WHERE ${condition}`}`;
|
|
1550
|
+
return ` ON CONFLICT (${keys}) ${assignments ? update : 'DO NOTHING'}`;
|
|
1496
1551
|
}
|
|
1497
1552
|
/**
|
|
1498
1553
|
* The statement failing a trigger's write with `message`, a quoted literal: SQL/PSM's `SIGNAL`, which the
|
|
@@ -1501,6 +1556,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1501
1556
|
refusal(message, _rows) {
|
|
1502
1557
|
return `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = ${message};`;
|
|
1503
1558
|
}
|
|
1559
|
+
/** What a trigger's update assigns: the values it names, and the `onUpdate` fills a trigger can write, a value or SQL. */
|
|
1560
|
+
triggerUpdateEntries(meta, values) {
|
|
1561
|
+
const [filled] = fillOnFields(meta, { ...values }, 'onUpdate', 'trigger');
|
|
1562
|
+
return this.writtenEntries(meta, filled);
|
|
1563
|
+
}
|
|
1504
1564
|
/** The values a write names, refusing one the entity has no column for. */
|
|
1505
1565
|
writtenEntries(meta, values) {
|
|
1506
1566
|
const entries = Object.entries(values).filter(([, value]) => value !== undefined);
|
|
@@ -1514,45 +1574,84 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1514
1574
|
return entries;
|
|
1515
1575
|
}
|
|
1516
1576
|
/**
|
|
1517
|
-
* `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING
|
|
1518
|
-
*
|
|
1577
|
+
* `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`, the id, or the fields `returning` names as
|
|
1578
|
+
* {@link insert} reports them. What a found row takes is read before the insert fills `onInsert` columns, which must
|
|
1579
|
+
* stay out of it, and written after the rows, in the order the statement reads its values.
|
|
1519
1580
|
*/
|
|
1520
|
-
upsert(ctx, entity,
|
|
1581
|
+
upsert(ctx, entity, q, payload, update, returning) {
|
|
1521
1582
|
const meta = getMeta(entity);
|
|
1522
|
-
const
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
if (updateCtx !== ctx) {
|
|
1528
|
-
ctx.pushValue(...updateCtx.values);
|
|
1529
|
-
}
|
|
1583
|
+
const entries = this.conflictEntries(entity, q, payload, update);
|
|
1584
|
+
return this.reportedWrite(ctx, entity, returning, 'upsert', () => {
|
|
1585
|
+
this.appendInsertValues(ctx, entity, payload);
|
|
1586
|
+
ctx.append(this.onConflict(meta, q.$conflict, this.foundRowUpdate(ctx, entity, entries, q.$where)));
|
|
1587
|
+
});
|
|
1530
1588
|
}
|
|
1531
1589
|
/**
|
|
1532
1590
|
* What an upsert of rows shaped as `row` assigns a row it finds: the values its assignments bind once per
|
|
1533
1591
|
* statement beside its rows, and whether there are any, where none is `DO NOTHING`, which skips that row.
|
|
1534
1592
|
*/
|
|
1535
|
-
upsertAssignments(entity,
|
|
1593
|
+
upsertAssignments(entity, q, row, update) {
|
|
1536
1594
|
const ctx = this.createContext();
|
|
1537
|
-
const assignments = this.
|
|
1595
|
+
const { assignments } = this.conflictUpdate(ctx, entity, q, row, update);
|
|
1538
1596
|
return { binds: ctx.values.length, assigns: assignments !== '' };
|
|
1539
1597
|
}
|
|
1540
1598
|
/**
|
|
1541
|
-
*
|
|
1542
|
-
*
|
|
1543
|
-
* for one row's generated key, a found row's too, since the upsert assigns it through `LAST_INSERT_ID`.
|
|
1599
|
+
* What a row an upsert finds takes: `update` where given, else the incoming row less the conflict keys, and what
|
|
1600
|
+
* `onUpdate` fills, under `q.$where`. An empty `update` leaves the row as it is, its fills included.
|
|
1544
1601
|
*/
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1602
|
+
conflictUpdate(ctx, entity, q, payload, update) {
|
|
1603
|
+
return this.foundRowUpdate(ctx, entity, this.conflictEntries(entity, q, payload, update), q.$where);
|
|
1604
|
+
}
|
|
1605
|
+
/** The columns a row an upsert finds takes, read off the payload before the insert fills it. */
|
|
1606
|
+
conflictEntries(entity, q, payload, update) {
|
|
1607
|
+
return this.foundRowEntries(getMeta(entity), q.$conflict, Array.isArray(payload) ? payload[0] : payload, update);
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* What a row an upsert of `row` finds takes, {@link foundRowAssigned}, with the `onUpdate` fills: by default, each
|
|
1611
|
+
* payload column as the incoming row has it, and no fill of what it matched on. In a trigger, an update as written
|
|
1612
|
+
* and the fills a trigger can write.
|
|
1613
|
+
*/
|
|
1614
|
+
foundRowEntries(meta, conflictKeys, row, update, scope = 'statement') {
|
|
1615
|
+
const assigned = foundRowAssigned(meta, conflictKeys, row, update);
|
|
1616
|
+
if (!assigned) {
|
|
1617
|
+
return [];
|
|
1549
1618
|
}
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1619
|
+
if (update) {
|
|
1620
|
+
return scope === 'trigger' ? this.triggerUpdateEntries(meta, assigned) : this.updateEntries(meta, assigned);
|
|
1621
|
+
}
|
|
1622
|
+
const matched = new Set([...meta.ids, ...getKeys(conflictKeys)]);
|
|
1623
|
+
return this.updateEntries(meta, assigned, scope).flatMap(([key, value]) => matched.has(key) ? [] : [[key, Object.hasOwn(row, key) ? this.incoming(meta, key) : value]]);
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* `entries` as a row an upsert finds takes them: its `SET` list, empty for none, and the condition it takes it
|
|
1627
|
+
* under, `where` read off that row through the table's name, empty where it always does.
|
|
1628
|
+
*/
|
|
1629
|
+
foundRowUpdate(ctx, entity, entries, where) {
|
|
1630
|
+
const assignments = this.foundRowAssignments(ctx, entity, entries);
|
|
1631
|
+
const condition = assignments && where
|
|
1632
|
+
? this.buildFragment(ctx, (fragment) => this.foundRowCondition(fragment, entity, where))
|
|
1633
|
+
: '';
|
|
1634
|
+
return { assignments, condition };
|
|
1635
|
+
}
|
|
1636
|
+
/** `entries` as the `SET` list of a row an upsert finds, each read through the table's name, under `guard` if any. */
|
|
1637
|
+
foundRowAssignments(ctx, entity, entries, guard) {
|
|
1638
|
+
const meta = getMeta(entity);
|
|
1639
|
+
const qualifier = `${this.escapedTableName(meta)}.`;
|
|
1640
|
+
return this.buildFragment(ctx, (fragment) => this.appendAssignments(fragment, meta, entries, qualifier, guard));
|
|
1641
|
+
}
|
|
1642
|
+
/** `where` as the row an upsert found holds it, its columns read through the table's name. */
|
|
1643
|
+
foundRowCondition(ctx, entity, where) {
|
|
1644
|
+
const escapedPrefix = `${this.escapedTableName(getMeta(entity))}.`;
|
|
1645
|
+
this.renderWhere(ctx, entity, where, { clause: false, escapedPrefix, operand: true });
|
|
1646
|
+
}
|
|
1647
|
+
/**
|
|
1648
|
+
* Whether an upsert of `rows` rows that assigns a found row something names its row's generated key in the header,
|
|
1649
|
+
* a found row's too, since the upsert assigns it through `LAST_INSERT_ID`: one row's only. An engine with
|
|
1650
|
+
* `RETURNING` reports its keys there instead.
|
|
1651
|
+
*/
|
|
1652
|
+
upsertReportsIds(meta, rows) {
|
|
1653
|
+
return this.insertIdSource === 'firstId' && rows === 1 && generatesKey(meta);
|
|
1553
1654
|
}
|
|
1554
|
-
/** Whether the upsert's assignments bind straight into the statement, as numbered `$n` placeholders can. */
|
|
1555
|
-
upsertUpdateBindsInPlace = false;
|
|
1556
1655
|
/** How an upsert's assignment reads `column` of the row that was being inserted. */
|
|
1557
1656
|
upsertIncoming(column) {
|
|
1558
1657
|
return `EXCLUDED.${column}`;
|
|
@@ -1562,41 +1661,26 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1562
1661
|
const column = this.escapedColumnName(meta, key);
|
|
1563
1662
|
return sql(() => this.upsertIncoming(column));
|
|
1564
1663
|
}
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
* `onUpdate` fills. An empty `update` leaves the row as it is, its fills included: nothing to assign.
|
|
1568
|
-
*/
|
|
1569
|
-
getUpsertUpdateAssignments(ctx, meta, conflictPaths, payload, update) {
|
|
1570
|
-
const entries = update
|
|
1571
|
-
? hasKeys(update)
|
|
1572
|
-
? this.updateEntries(meta, update)
|
|
1573
|
-
: []
|
|
1574
|
-
: this.conflictEntries(meta, conflictPaths, Array.isArray(payload) ? payload[0] : payload);
|
|
1575
|
-
const qualifier = `${this.escapedTableName(meta)}.`;
|
|
1576
|
-
return this.buildFragment(ctx, (fragmentCtx) => this.appendAssignments(fragmentCtx, meta, entries, qualifier));
|
|
1577
|
-
}
|
|
1578
|
-
/** What a found row takes by default: each payload column as the incoming row has it, and the `onUpdate` fills. */
|
|
1579
|
-
conflictEntries(meta, conflictPaths, row) {
|
|
1580
|
-
const always = upsertAssigned(meta, row, conflictPaths);
|
|
1581
|
-
return getKeys(always).map((key) => [key, Object.hasOwn(row, key) ? this.incoming(meta, key) : always[key]]);
|
|
1582
|
-
}
|
|
1583
|
-
getUpsertConflictPathsStr(meta, conflictPaths) {
|
|
1584
|
-
return getKeys(conflictPaths)
|
|
1664
|
+
conflictKeysSql(meta, conflictKeys) {
|
|
1665
|
+
return getKeys(conflictKeys)
|
|
1585
1666
|
.map((key) => this.escapedColumnName(meta, key))
|
|
1586
1667
|
.join(', ');
|
|
1587
1668
|
}
|
|
1588
|
-
delete(ctx, entity, q, opts = {}) {
|
|
1669
|
+
delete(ctx, entity, q, opts = {}, returning) {
|
|
1589
1670
|
const meta = getMeta(entity);
|
|
1590
1671
|
const tableName = this.escapedTableName(meta);
|
|
1591
1672
|
const { stamp, opts: read } = deletionOf(meta, opts);
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1673
|
+
return this.reportedWrite(ctx, entity, returning, stamp ? 'update' : 'delete', (afterTarget) => {
|
|
1674
|
+
if (stamp) {
|
|
1675
|
+
ctx.append(`UPDATE ${tableName} SET `);
|
|
1676
|
+
this.appendAssignment(ctx, meta, stamp.key, stamp.value());
|
|
1677
|
+
}
|
|
1678
|
+
else {
|
|
1679
|
+
ctx.append(`DELETE FROM ${tableName}`);
|
|
1680
|
+
}
|
|
1681
|
+
ctx.append(afterTarget && ` ${afterTarget}`);
|
|
1682
|
+
this.search(ctx, entity, q, read);
|
|
1683
|
+
});
|
|
1600
1684
|
}
|
|
1601
1685
|
escapeId(val, forbidQualified, addDot) {
|
|
1602
1686
|
return escapeSqlId(val, this.escapeIdChar, forbidQualified, addDot);
|
|
@@ -1720,15 +1804,14 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1720
1804
|
return `CAST(${operand} AS JSON)`;
|
|
1721
1805
|
}
|
|
1722
1806
|
/**
|
|
1723
|
-
*
|
|
1724
|
-
*
|
|
1807
|
+
* A JSON update's expression, folded to one write per path, on an empty document in place of a NULL column
|
|
1808
|
+
* where one writes a key. Each write reads `current`, the column as stored.
|
|
1725
1809
|
*/
|
|
1726
|
-
|
|
1810
|
+
jsonUpdate(ctx, value, field, current) {
|
|
1727
1811
|
const update = foldJson(value);
|
|
1728
1812
|
if ('array' in update) {
|
|
1729
1813
|
const slot = { base: current, path: '' };
|
|
1730
|
-
|
|
1731
|
-
return;
|
|
1814
|
+
return this.jsonOrStored(slot, this.jsonArrayWrite(ctx, slot, update.array));
|
|
1732
1815
|
}
|
|
1733
1816
|
const writes = update.object;
|
|
1734
1817
|
const arrays = Object.entries(writes.arrays);
|
|
@@ -1744,8 +1827,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1744
1827
|
const withSet = hasKeys(writes.set)
|
|
1745
1828
|
? this.jsonSet(ctx, this.jsonWriteKeys(withArrays, this.jsonParents(Object.keys(writes.set), current), { create: true }), writes.set)
|
|
1746
1829
|
: withArrays;
|
|
1747
|
-
|
|
1748
|
-
ctx.append(`${escapedCol} = ${expr}`);
|
|
1830
|
+
return writes.unset.length > 0 ? this.jsonUnset(ctx, withSet, writes.unset) : withSet;
|
|
1749
1831
|
}
|
|
1750
1832
|
/**
|
|
1751
1833
|
* The array at `slot` as `write` leaves it, or NULL where a value that is no array stays: its pulls, then each
|
|
@@ -1836,17 +1918,11 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1836
1918
|
return ctx.sql;
|
|
1837
1919
|
}
|
|
1838
1920
|
getRawValue(ctx, opts) {
|
|
1839
|
-
const { value, prefix = ''
|
|
1840
|
-
renderSql(value, {
|
|
1841
|
-
...opts,
|
|
1842
|
-
ctx,
|
|
1843
|
-
dialect: this,
|
|
1844
|
-
prefix,
|
|
1845
|
-
escapedPrefix: escapedPrefix ?? this.escapeId(prefix, true, true),
|
|
1846
|
-
});
|
|
1921
|
+
const { value, prefix = '' } = opts;
|
|
1922
|
+
renderSql(value, { ...opts, ctx, dialect: this, prefix, escapedPrefix: this.qualifierOf(opts) });
|
|
1847
1923
|
}
|
|
1848
1924
|
/** A `column.path` key of `meta`'s JSON field as the path it names, shared by `where` and `sort`; else `undefined`. */
|
|
1849
|
-
resolveJsonDotPath(meta, key,
|
|
1925
|
+
resolveJsonDotPath(meta, key, opts) {
|
|
1850
1926
|
const dotIndex = key.indexOf('.');
|
|
1851
1927
|
if (dotIndex <= 0) {
|
|
1852
1928
|
return undefined;
|
|
@@ -1857,8 +1933,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1857
1933
|
return undefined;
|
|
1858
1934
|
}
|
|
1859
1935
|
const colName = this.resolveColumnName(root, field);
|
|
1860
|
-
|
|
1861
|
-
|
|
1936
|
+
return {
|
|
1937
|
+
base: this.qualifierOf(opts) + this.escapeId(colName),
|
|
1938
|
+
path: jsonPathKeys(key.slice(dotIndex + 1)).join('.'),
|
|
1939
|
+
};
|
|
1862
1940
|
}
|
|
1863
1941
|
/**
|
|
1864
1942
|
* One JSON path, read the way `mode` asks for: the one place the three readings are chosen between,
|
|
@@ -1973,7 +2051,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
|
|
|
1973
2051
|
const { where: $where, page } = aggregate;
|
|
1974
2052
|
// `1` where nothing is aggregated: a tally counts the rows the page holds, whatever they carry.
|
|
1975
2053
|
const { field } = aggregate;
|
|
1976
|
-
const read = field ?
|
|
2054
|
+
const read = field ? columnRef(entity, field) : sql `1`;
|
|
1977
2055
|
const query = {
|
|
1978
2056
|
...page,
|
|
1979
2057
|
$select: [read.as(AGGREGATE_VALUE_ALIAS)],
|