uql-orm 0.92.0 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/browser/uql-browser.min.js.map +2 -2
  2. package/dist/cockroachdb/cockroachDialect.js +1 -1
  3. package/dist/dialect/abstractSqlDialect.d.ts +45 -10
  4. package/dist/dialect/abstractSqlDialect.js +139 -63
  5. package/dist/dialect/mergeSqlDialect.d.ts +11 -2
  6. package/dist/dialect/mergeSqlDialect.js +28 -12
  7. package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
  8. package/dist/dialect/mysqlLikeSqlDialect.js +34 -21
  9. package/dist/dialect/pgLikeSqlDialect.d.ts +5 -1
  10. package/dist/dialect/pgLikeSqlDialect.js +8 -1
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +2 -2
  13. package/dist/maria/mariaDialect.d.ts +3 -1
  14. package/dist/maria/mariaDialect.js +3 -1
  15. package/dist/migrate/builder/index.d.ts +0 -1
  16. package/dist/migrate/builder/index.js +0 -1
  17. package/dist/migrate/builder/tableBuilder.js +2 -2
  18. package/dist/migrate/codegen/fieldOptionsSource.js +4 -11
  19. package/dist/migrate/ddl/defaultSql.d.ts +31 -0
  20. package/dist/migrate/ddl/defaultSql.js +109 -0
  21. package/dist/migrate/ddl/pgTableDdl.js +1 -1
  22. package/dist/migrate/ddl/tableDdl.js +1 -1
  23. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
  24. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +4 -5
  25. package/dist/migrate/introspection/mysqlIntrospector.js +4 -2
  26. package/dist/migrate/schemaGenerator.js +1 -1
  27. package/dist/migrate/storage/databaseStorage.js +2 -2
  28. package/dist/migrate/triggerSql.js +9 -2
  29. package/dist/mongo/mongodbQuerier.d.ts +13 -5
  30. package/dist/mongo/mongodbQuerier.js +39 -5
  31. package/dist/mssql/mssqlDialect.d.ts +9 -4
  32. package/dist/mssql/mssqlDialect.js +18 -5
  33. package/dist/postgres/postgresDialect.d.ts +5 -2
  34. package/dist/postgres/postgresDialect.js +5 -5
  35. package/dist/querier/abstractQuerier.d.ts +5 -5
  36. package/dist/querier/abstractQuerier.js +19 -15
  37. package/dist/querier/abstractSqlQuerier.d.ts +3 -3
  38. package/dist/querier/abstractSqlQuerier.js +7 -7
  39. package/dist/schema/schemaASTBuilder.js +2 -16
  40. package/dist/schema/sqlExpression.d.ts +9 -3
  41. package/dist/schema/sqlExpression.js +14 -0
  42. package/dist/sqlite/sqliteDialect.d.ts +5 -4
  43. package/dist/sqlite/sqliteDialect.js +12 -4
  44. package/dist/type/dialect.d.ts +29 -11
  45. package/dist/type/dialect.js +2 -0
  46. package/dist/type/entity.d.ts +15 -0
  47. package/dist/type/query.d.ts +12 -1
  48. package/dist/type/universalQuerier.d.ts +3 -3
  49. package/dist/util/index.d.ts +1 -1
  50. package/dist/util/index.js +1 -1
  51. package/dist/util/raw.d.ts +13 -3
  52. package/dist/util/raw.js +29 -3
  53. package/dist/util/triggerWrite.d.ts +11 -1
  54. package/dist/util/triggerWrite.js +14 -0
  55. package/package.json +1 -1
  56. package/skills/uql-orm/SKILL.md +3 -2
  57. package/dist/migrate/builder/expressions.d.ts +0 -63
  58. package/dist/migrate/builder/expressions.js +0 -142
@@ -1,5 +1,4 @@
1
1
  export * from './columnBuilder.js';
2
- export * from './expressions.js';
3
2
  export * from './migrationBuilder.js';
4
3
  export * from './tableBuilder.js';
5
4
  export * from './types.js';
@@ -5,9 +5,9 @@
5
5
  */
6
6
  import { DEFAULT_FOREIGN_KEY_ACTION } from '../../schema/types.js';
7
7
  import { DATE_PRECISION } from '../../util/date.js';
8
+ import { currentTimestamp } from '../../util/raw.js';
8
9
  import { columnForeignKey, columnIndex, indexDefinition } from '../generator/definitionToNode.js';
9
10
  import { ColumnBuilder } from './columnBuilder.js';
10
- import { expr } from './expressions.js';
11
11
  /** Normalizes `table.index` options, where a bare string is the index name. */
12
12
  function namedOptions(options) {
13
13
  return typeof options === 'string' ? { name: options } : (options ?? {});
@@ -148,7 +148,7 @@ export class TableBuilder {
148
148
  return this.timestampNow('updatedAt');
149
149
  }
150
150
  timestampNow(name) {
151
- return this.timestamptz(name, { defaultValue: expr.now() });
151
+ return this.timestamptz(name, { defaultValue: currentTimestamp });
152
152
  }
153
153
  timestamps() {
154
154
  this.createdAt();
@@ -2,7 +2,6 @@ import { canonicalToColumnType, isVectorCategory } from '../../schema/canonicalT
2
2
  import { SqlExpression } from '../../schema/sqlExpression.js';
3
3
  import { DATE_PRECISION } from '../../util/date.js';
4
4
  import { isAutoIncrement } from '../../util/field.util.js';
5
- import { UqlUsageError } from '../../util/uqlError.js';
6
5
  import { quoted, rawTag } from './sourceLiteral.js';
7
6
  /** What each field of a {@link ColumnNode} contributes to `@Field({ ... })`, in emit order; `satisfies` makes a new field answer. */
8
7
  const OPTION_SOURCE = {
@@ -70,15 +69,9 @@ function defaultValueSource(value) {
70
69
  return typeof value === 'string' ? quoted(value) : JSON.stringify(value);
71
70
  }
72
71
  /**
73
- * A SQL default as an entity declares it, with the name to import for it: `currentTimestamp` for the
74
- * current timestamp, and `raw` for any other SQL, as introspection reads it back.
72
+ * A SQL default as an entity declares it, with the name to import for it: the value uql exports by its own
73
+ * name (`currentTimestamp`), and `raw` for any other SQL, as introspection reads it back.
75
74
  */
76
- function sqlDefaultSource(value) {
77
- if (value.kind === 'now') {
78
- return { name: 'currentTimestamp', source: 'currentTimestamp' };
79
- }
80
- if (value.sql === undefined) {
81
- throw new UqlUsageError(`an entity declares a SQL default as raw or currentTimestamp, and '${value.kind}' is neither`);
82
- }
83
- return { name: 'raw', source: rawTag(value.sql) };
75
+ function sqlDefaultSource({ kind, sql }) {
76
+ return sql === undefined ? { name: kind, source: kind } : { name: 'raw', source: rawTag(sql) };
84
77
  }
@@ -0,0 +1,31 @@
1
+ import type { AbstractSqlDialect } from '../../dialect/index.js';
2
+ import { SqlExpression } from '../../schema/sqlExpression.js';
3
+ import { type SqlDialectName } from '../../type/index.js';
4
+ /** How one engine renders a DDL default. A new per-dialect rule is a field here, not a second table. */
5
+ export type DialectDefaults = {
6
+ /** Column types whose `DEFAULT` this engine takes only as a parenthesized expression. */
7
+ readonly wrapTypes?: RegExp;
8
+ /** Column types whose clock default must repeat their precision, captured by the pattern. */
9
+ readonly preciseTypes?: RegExp;
10
+ };
11
+ /**
12
+ * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query bundle - the
13
+ * same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`.
14
+ */
15
+ export declare const DIALECT_DEFAULTS: Readonly<Record<SqlDialectName, DialectDefaults>>;
16
+ /**
17
+ * The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
18
+ * else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
19
+ * the result needs wrapping, which MySQL demands on its large types whatever the value.
20
+ */
21
+ export declare function formatDefaultValue(value: unknown, dialect: AbstractSqlDialect, columnType?: string): string;
22
+ /**
23
+ * Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
24
+ * and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
25
+ */
26
+ export declare function sameDefault(desired: unknown, current: unknown, dialect: AbstractSqlDialect): boolean;
27
+ /**
28
+ * Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
29
+ * compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
30
+ */
31
+ export declare function knownDefault(expression: SqlExpression, dialect: AbstractSqlDialect): SqlExpression;
@@ -0,0 +1,109 @@
1
+ import { SqlExpression, schemaDefault, writtenDefault } from '../../schema/sqlExpression.js';
2
+ import { SQL_VALUE_NAMES } from '../../type/index.js';
3
+ import { UqlUsageError } from '../../util/uqlError.js';
4
+ /** A default in schema form, its SQL compiled with no entity to read: a migration's names no field. */
5
+ const ddlDefault = (value, dialect) => schemaDefault(value, (sql) => dialect.compileDdl(sql));
6
+ /** MySQL 8.0.13+ rejects `DEFAULT 'x'` on these but accepts `DEFAULT ('x')`, whatever the value. */
7
+ const MYSQL_LARGE_TYPES = /^\s*(TINY|MEDIUM|LONG)?(TEXT|BLOB)|^\s*(JSON|GEOMETRY)\b/i;
8
+ /** A `DATETIME(3)` or `TIMESTAMP(3)`, whose fractional-second precision is captured. */
9
+ const MYSQL_PRECISE_TYPES = /^\s*(?:DATETIME|TIMESTAMP)\((\d)\)/i;
10
+ const MYSQL_DEFAULTS = { wrapTypes: MYSQL_LARGE_TYPES, preciseTypes: MYSQL_PRECISE_TYPES };
11
+ /**
12
+ * Looked up by name rather than carried on the dialect, which keeps DDL data out of the query bundle - the
13
+ * same split that keeps `ENGINE_TYPES` in `schema/canonicalType.ts`.
14
+ */
15
+ export const DIALECT_DEFAULTS = {
16
+ postgres: {},
17
+ cockroachdb: {},
18
+ mysql: MYSQL_DEFAULTS,
19
+ mariadb: MYSQL_DEFAULTS,
20
+ sqlite: {},
21
+ mssql: {},
22
+ };
23
+ /**
24
+ * The one place a DDL default becomes SQL: an expression through the dialect's own spelling, anything
25
+ * else as a literal, so `true` is `1` where booleans are integers. `columnType` decides only whether
26
+ * the result needs wrapping, which MySQL demands on its large types whatever the value.
27
+ */
28
+ export function formatDefaultValue(value, dialect, columnType) {
29
+ const sql = defaultLiteral(ddlDefault(value, dialect), dialect, columnType);
30
+ const { wrapTypes } = DIALECT_DEFAULTS[dialect.dialectName];
31
+ return columnType !== undefined && wrapTypes?.test(columnType) ? `(${sql})` : sql;
32
+ }
33
+ /**
34
+ * Whether a stored default matches the declared one. A literal never matches SQL, even SQL that spells it,
35
+ * and two SQL defaults match when the dialect renders them alike once {@link reprinted} normalizes them.
36
+ */
37
+ export function sameDefault(desired, current, dialect) {
38
+ // Both spellings of "no default" are the same fact, and engines disagree on which they report:
39
+ // MariaDB says `null` where MySQL says nothing at all. Reading them as different values asked to
40
+ // `MODIFY` every nullable column, on every sync, forever.
41
+ if (desired == null || current == null)
42
+ return desired == null && current == null;
43
+ const [want, have] = [ddlDefault(desired, dialect), ddlDefault(current, dialect)];
44
+ if (SqlExpression.isExpression(want) || SqlExpression.isExpression(have)) {
45
+ return (SqlExpression.isExpression(want) &&
46
+ SqlExpression.isExpression(have) &&
47
+ reprinted(formatDefaultValue(want, dialect)) === reprinted(formatDefaultValue(have, dialect)));
48
+ }
49
+ // Compared as text, since a catalogue may report a number either as a number or as its text.
50
+ return writtenDefault(want) === writtenDefault(have);
51
+ }
52
+ /**
53
+ * Reads SQL a catalogue reports as the value uql exports that renders alike, so a declared `currentTimestamp`
54
+ * compares equal and `generate:from-db` writes it by name; any other SQL is kept as it is.
55
+ */
56
+ export function knownDefault(expression, dialect) {
57
+ const name = SQL_VALUE_NAMES.find((kind) => dialect.sqlValues[kind] !== undefined && sameDefault(new SqlExpression(kind), expression, dialect));
58
+ return name ? new SqlExpression(name) : expression;
59
+ }
60
+ /**
61
+ * Normalizes what engines reprint differently in SQL: it lowercases, collapses spacing, and strips wrapping
62
+ * parentheses (SQLite and MySQL drop them, SQL Server adds them) and the empty argument list of
63
+ * CockroachDB's `current_timestamp()`.
64
+ */
65
+ function reprinted(sql) {
66
+ let text = sql
67
+ .toLowerCase()
68
+ .replace(/\s*([(),])\s*/g, '$1')
69
+ .replace(/\s+/g, ' ')
70
+ .trim();
71
+ while (/^\(.*\)$/s.test(text)) {
72
+ text = text.slice(1, -1);
73
+ }
74
+ return text.replace(/\(\)$/, '');
75
+ }
76
+ /**
77
+ * Quoting is the dialect's `escape`, so a backslash in a default is escaped the way the engine reads
78
+ * it - MySQL takes `'a\b'` as a backspace where Postgres takes it literally. Only the cases `escape`
79
+ * cannot serve stay here: a boolean is `1` where booleans are integers, and a plain object or array
80
+ * is JSON rather than the throw and the IN-list `escape` gives them.
81
+ */
82
+ function defaultLiteral(value, dialect, columnType) {
83
+ if (value === undefined || value === null) {
84
+ return 'NULL';
85
+ }
86
+ if (SqlExpression.isExpression(value)) {
87
+ return expressionSql(value, dialect, columnType);
88
+ }
89
+ if (typeof value === 'boolean') {
90
+ return dialect.booleanLiteral === 'native' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0';
91
+ }
92
+ return dialect.escape(typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : value);
93
+ }
94
+ /** A raw expression's own SQL, else the engine's spelling of the value it names. */
95
+ function expressionSql({ kind, sql }, dialect, columnType) {
96
+ if (sql !== undefined) {
97
+ return sql;
98
+ }
99
+ const { preciseTypes } = DIALECT_DEFAULTS[dialect.dialectName];
100
+ if (kind === 'currentTimestamp' && preciseTypes) {
101
+ const precision = columnType === undefined ? undefined : preciseTypes.exec(columnType)?.[1];
102
+ return precision ? `CURRENT_TIMESTAMP(${precision})` : 'CURRENT_TIMESTAMP';
103
+ }
104
+ const spelled = kind === 'raw' ? undefined : dialect.sqlValues[kind];
105
+ if (spelled === undefined) {
106
+ throw new UqlUsageError(`${dialect.dialectName} has no ${kind}; write it as raw SQL this engine accepts`);
107
+ }
108
+ return spelled;
109
+ }
@@ -1,4 +1,4 @@
1
- import { sameDefault } from '../builder/expressions.js';
1
+ import { sameDefault } from './defaultSql.js';
2
2
  import { TableDdl } from './tableDdl.js';
3
3
  /** Table DDL for the Postgres family, which alters each part of a column in a separate clause. */
4
4
  export class PgTableDdl extends TableDdl {
@@ -1,5 +1,5 @@
1
1
  import { UqlUsageError } from '../../util/uqlError.js';
2
- import { formatDefaultValue } from '../builder/expressions.js';
2
+ import { formatDefaultValue } from './defaultSql.js';
3
3
  /**
4
4
  * A column's type with the size it was read back with, unless its spelling already carries one:
5
5
  * introspection reports `VARCHAR` and `255` apart, where a type from an entity is already whole.
@@ -119,8 +119,8 @@ export declare abstract class AbstractSqlSchemaIntrospector extends BaseSqlIntro
119
119
  /** Parses a default as the catalogue reports it: to its literal value, or through {@link sqlDefault} if SQL. */
120
120
  protected abstract parseDefaultValue(defaultValue: string | null): unknown;
121
121
  /**
122
- * A SQL default, wrapped in parentheses. The current timestamp uql declares reads back as `expr.now()`, so
123
- * it compares equal on every engine and `generate:from-db` writes it as `currentTimestamp`.
122
+ * A SQL default, wrapped in parentheses, or the value uql exports that it spells (`currentTimestamp`), so it
123
+ * compares equal on every engine and `generate:from-db` writes it by name.
124
124
  */
125
125
  protected sqlDefault(sql: string): SqlExpression;
126
126
  }
@@ -3,7 +3,7 @@ import { FOREIGN_KEY_ACTIONS } from '../../schema/types.js';
3
3
  import { isSqlQuerier } from '../../type/index.js';
4
4
  import { isOwnedName } from '../../util/sql.util.js';
5
5
  import { UqlUsageError } from '../../util/uqlError.js';
6
- import { expr, sameDefault } from '../builder/expressions.js';
6
+ import { knownDefault } from '../ddl/defaultSql.js';
7
7
  import { BaseSqlIntrospector } from './baseSqlIntrospector.js';
8
8
  /** A SQL introspector: an engine states its catalogue queries (`get*Query`) and how their rows map (`map*Result`). */
9
9
  export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
@@ -175,12 +175,11 @@ export class AbstractSqlSchemaIntrospector extends BaseSqlIntrospector {
175
175
  return name === undefined || name === null ? undefined : String(name);
176
176
  }
177
177
  /**
178
- * A SQL default, wrapped in parentheses. The current timestamp uql declares reads back as `expr.now()`, so
179
- * it compares equal on every engine and `generate:from-db` writes it as `currentTimestamp`.
178
+ * A SQL default, wrapped in parentheses, or the value uql exports that it spells (`currentTimestamp`), so it
179
+ * compares equal on every engine and `generate:from-db` writes it by name.
180
180
  */
181
181
  sqlDefault(sql) {
182
- const expression = SqlExpression.parenthesized(sql);
183
- return sameDefault(expr.now(), expression, this.dialect) ? expr.now() : expression;
182
+ return knownDefault(SqlExpression.parenthesized(sql), this.dialect);
184
183
  }
185
184
  }
186
185
  /** A {@link TableRowReader} over one querier: the same statement is only ever sent once. */
@@ -1,5 +1,5 @@
1
+ import { SqlExpression } from '../../schema/sqlExpression.js';
1
2
  import { unescapeMysqlString } from '../../util/sqlLiteral.js';
2
- import { expr } from '../builder/expressions.js';
3
3
  import { AbstractSqlSchemaIntrospector, } from './abstractSqlSchemaIntrospector.js';
4
4
  /**
5
5
  * MySQL/MariaDB schema introspector.
@@ -155,7 +155,9 @@ export class MysqlSchemaIntrospector extends AbstractSqlSchemaIntrospector {
155
155
  const sql = introduced ? undefined : this.sqlText(defaultValue, extra);
156
156
  if (sql !== undefined) {
157
157
  // Any precision here repeats the column's own, which the column type already states.
158
- return /^CURRENT_TIMESTAMP(?:\(\d?\))?$/i.test(sql) ? expr.now() : this.sqlDefault(sql);
158
+ return /^CURRENT_TIMESTAMP(?:\(\d?\))?$/i.test(sql)
159
+ ? new SqlExpression('currentTimestamp')
160
+ : this.sqlDefault(sql);
159
161
  }
160
162
  const literal = introduced ? unescapeMysqlString(introduced[1]) : defaultValue;
161
163
  const quoted = /^'(.*)'$/s.exec(literal);
@@ -7,8 +7,8 @@ import { DEFAULT_FOREIGN_KEY_ACTION, } from '../schema/types.js';
7
7
  import { qualifyName } from '../util/index.js';
8
8
  import { derivedCheckName, derivedForeignKeyName, derivedPrimaryKeyName, isOwnedName } from '../util/sql.util.js';
9
9
  import { UqlUsageError } from '../util/uqlError.js';
10
- import { formatDefaultValue, sameDefault } from './builder/expressions.js';
11
10
  import { splitSqlStatements } from './builder/splitSqlStatements.js';
11
+ import { formatDefaultValue, sameDefault } from './ddl/defaultSql.js';
12
12
  import { indexDdlFor, tableDdlFor } from './ddl/index.js';
13
13
  import { sizedType } from './ddl/tableDdl.js';
14
14
  import { rebuildTable } from './ddl/tableRebuild.js';
@@ -1,5 +1,5 @@
1
+ import { currentTimestamp } from '../../util/raw.js';
1
2
  import { withSqlQuerierForMigrations } from '../acquireQuerierForMigrations.js';
2
- import { expr } from '../builder/expressions.js';
3
3
  import { TableBuilder } from '../builder/tableBuilder.js';
4
4
  import { SqlSchemaGenerator } from '../schemaGenerator.js';
5
5
  /** Where executed migrations are recorded when the config does not name a table. */
@@ -32,7 +32,7 @@ export class DatabaseMigrationStorage {
32
32
  async createTableIfNotExists(querier) {
33
33
  const table = new TableBuilder(this.tableName);
34
34
  table.string('name', { length: 255, primaryKey: true });
35
- table.timestamptz('executed_at', { defaultValue: expr.now() });
35
+ table.timestamptz('executed_at', { defaultValue: currentTimestamp });
36
36
  const generator = new SqlSchemaGenerator(querier.dialect);
37
37
  for (const sql of generator.generateCreateTableFromDefinition(table.build(), { ifNotExists: true })) {
38
38
  await querier.run(sql);
@@ -50,6 +50,9 @@ function triggerStatements(dialect, meta, trigger, name) {
50
50
  const features = dialect.features.triggers;
51
51
  const [timing, operation] = EVENT_PARTS[trigger.on];
52
52
  const before = timing === 'BEFORE';
53
+ if (trigger.deferred && !features.deferrable) {
54
+ throw new UqlUsageError(`${dialect.dialectName} cannot defer a trigger to commit, which ${meta.entity.name} asks for; only Postgres can`);
55
+ }
53
56
  const { fires } = features;
54
57
  const perStatement = fires === 'eachStatement';
55
58
  const names = rowNames(dialect);
@@ -76,9 +79,13 @@ function triggerStatements(dialect, meta, trigger, name) {
76
79
  const each = perStatement ? '' : '\nFOR EACH ROW';
77
80
  const whenClause = filter && byWhen ? `\nWHEN (${filter})` : '';
78
81
  const event = `${timing} ${operation}${of}`;
82
+ // Deferred, it is a constraint trigger, which is what Postgres lets wait for the commit.
83
+ const [kind, deferral] = trigger.deferred
84
+ ? ['CONSTRAINT TRIGGER', '\nDEFERRABLE INITIALLY DEFERRED']
85
+ : ['TRIGGER', ''];
79
86
  const header = features.layout === 'tableFirst'
80
- ? `CREATE TRIGGER ${id}\nON ${table} ${event}${each}${whenClause}\nAS`
81
- : `CREATE TRIGGER ${id}\n${event} ON ${table}${each}${whenClause}`;
87
+ ? `CREATE ${kind} ${id}\nON ${table} ${event}${each}${whenClause}\nAS`
88
+ : `CREATE ${kind} ${id}\n${event} ON ${table}${deferral}${each}${whenClause}`;
82
89
  if (features.body !== 'function') {
83
90
  return [`${header}\nBEGIN\n${opened}\nEND`];
84
91
  }
@@ -1,6 +1,6 @@
1
1
  import type { Document, MongoClient } from 'mongodb';
2
2
  import { AbstractQuerier } from '../querier/index.js';
3
- import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
3
+ import type { EntityData, ExtraOptions, PrimaryKey, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, TransactionOptions, Type, UpdatePayload, UpsertOptions } from '../type/index.js';
4
4
  import type { MongoDialect } from './mongoDialect.js';
5
5
  import type { MongoQuerier } from './mongoQuerier.js';
6
6
  export declare class MongodbQuerier extends AbstractQuerier implements MongoQuerier {
@@ -53,17 +53,25 @@ export declare class MongodbQuerier extends AbstractQuerier implements MongoQuer
53
53
  */
54
54
  private upsertUpdate;
55
55
  private buildConflictFilter;
56
- protected internalUpsertOne<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>): Promise<{
56
+ /**
57
+ * An upsert whose conflicting document takes `update`, which no single call pairs with inserting the payload:
58
+ * `$setOnInsert` and `$inc` on one field conflict. So the row inserts if absent, and a document it found,
59
+ * a concurrent one included, then takes `update`.
60
+ */
61
+ private upsertWithUpdate;
62
+ /** The id and whether it was created, read off the document a `findOneAndUpdate` upsert wrote. */
63
+ private upserted;
64
+ protected internalUpsertOne<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, { update }: UpsertOptions<E>): Promise<{
57
65
  ids: (PrimaryKey | undefined)[];
58
66
  changes: number;
59
67
  created: boolean;
60
68
  }>;
61
- protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<{
69
+ protected internalUpsertMany<E extends Document>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], { update }: UpsertOptions<E>): Promise<{
70
+ ids: (PrimaryKey | undefined)[];
62
71
  changes: number;
63
- ids?: undefined;
64
72
  } | {
65
73
  changes: number;
66
- ids: (PrimaryKey | undefined)[];
74
+ ids?: undefined;
67
75
  }>;
68
76
  protected internalDeleteMany<E extends Document>(entity: Type<E>, qm: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
69
77
  get hasOpenTransaction(): boolean;
@@ -226,8 +226,34 @@ export class MongodbQuerier extends AbstractQuerier {
226
226
  buildConflictFilter(entity, conflictPaths, item) {
227
227
  return this.dialect.where(entity, whereEach(getKeys(conflictPaths), (key) => item[key]));
228
228
  }
229
- async internalUpsertOne(entity, conflictPaths, payload) {
229
+ /**
230
+ * An upsert whose conflicting document takes `update`, which no single call pairs with inserting the payload:
231
+ * `$setOnInsert` and `$inc` on one field conflict. So the row inserts if absent, and a document it found,
232
+ * a concurrent one included, then takes `update`.
233
+ */
234
+ async upsertWithUpdate(entity, conflictPaths, row, update) {
235
+ const persistable = this.dialect.getPersistable(getMeta(entity), clone(row), 'onInsert');
236
+ const res = await this.execute((session) => this.collection(entity).findOneAndUpdate(this.buildConflictFilter(entity, conflictPaths, row), { $setOnInsert: persistable }, { upsert: true, returnDocument: 'after', includeResultMetadata: true, session }));
237
+ const { id, created } = this.upserted(res);
238
+ // An empty `update` leaves a found document as it is, as `DO NOTHING` does.
239
+ const updates = !created && hasKeys(update);
240
+ if (updates) {
241
+ await this.internalUpdateMany(entity, { $where: whereEach(getKeys(conflictPaths), (key) => row[key]) }, update);
242
+ }
243
+ return { id, created, changes: created || updates ? 1 : 0 };
244
+ }
245
+ /** The id and whether it was created, read off the document a `findOneAndUpdate` upsert wrote. */
246
+ upserted(res) {
247
+ const id = this.dialect.fromWireId(res.value?._id);
248
+ // `updatedExisting` is false when a new document was inserted (upserted).
249
+ return { id, created: res.lastErrorObject?.['updatedExisting'] === false };
250
+ }
251
+ async internalUpsertOne(entity, conflictPaths, payload, { update }) {
230
252
  refuseTriggers(entity);
253
+ if (update) {
254
+ const { id, created, changes } = await this.upsertWithUpdate(entity, conflictPaths, payload, update);
255
+ return { ids: [id], changes, created };
256
+ }
231
257
  return this.timed('upsertOne', undefined, async () => {
232
258
  payload = clone(payload);
233
259
  const meta = getMeta(entity);
@@ -241,14 +267,22 @@ export class MongodbQuerier extends AbstractQuerier {
241
267
  session,
242
268
  }));
243
269
  // Read off the document as written, which carries its `_id` on either branch.
244
- const id = this.dialect.fromWireId(res?.value?._id);
245
- // `updatedExisting` is false when a new document was inserted (upserted).
246
- const created = res?.lastErrorObject?.['updatedExisting'] === false;
270
+ const { id, created } = this.upserted(res);
247
271
  return { ids: [id], changes: id === undefined ? 0 : 1, created };
248
272
  });
249
273
  }
250
- async internalUpsertMany(entity, conflictPaths, payload) {
274
+ async internalUpsertMany(entity, conflictPaths, payload, { update }) {
251
275
  refuseTriggers(entity);
276
+ if (update) {
277
+ const ids = [];
278
+ let changes = 0;
279
+ for (const row of payload) {
280
+ const written = await this.upsertWithUpdate(entity, conflictPaths, row, update);
281
+ ids.push(written.id);
282
+ changes += written.changes;
283
+ }
284
+ return { ids, changes };
285
+ }
252
286
  return this.timed('upsertMany', undefined, async () => {
253
287
  if (!payload?.length) {
254
288
  return { changes: 0 };
@@ -1,7 +1,7 @@
1
1
  import { type RelationRows } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
3
3
  import { MergeSqlDialect } from '../dialect/mergeSqlDialect.js';
4
- import type { EntityMeta, FieldOptions, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryPager, SqlDialectFeatures, Type, VectorDistance, VectorMetric } from '../type/index.js';
4
+ import type { EntityMeta, FieldOptions, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryPager, SqlDialectFeatures, SqlValues, TriggerRows, Type, UpsertOptions, VectorDistance, VectorMetric } from '../type/index.js';
5
5
  /** Microsoft SQL Server 2017 and up. Identifiers are `"`-quoted, the ANSI spelling `tedious` enables. */
6
6
  export declare class MsSqlDialect extends MergeSqlDialect {
7
7
  #private;
@@ -17,8 +17,13 @@ export declare class MsSqlDialect extends MergeSqlDialect {
17
17
  */
18
18
  readonly isolationLevelStrategy = "set-before";
19
19
  readonly booleanLiteral = "integer";
20
- /** UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. */
21
- readonly currentTimestamp = "SYSUTCDATETIME()";
20
+ /**
21
+ * The clock in UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. No v7: `NEWSEQUENTIALID()` is
22
+ * an ordered v4 with no readable timestamp, so it is refused rather than served as one.
23
+ */
24
+ readonly sqlValues: SqlValues;
25
+ /** Only where the statement touched a row the trigger selects, since it fires once per statement, even for none. */
26
+ protected refusal(message: string, rows?: TriggerRows): string;
22
27
  /** [The hard server limit](https://github.com/yiisoft/yii2/issues/10371), not a driver preference. */
23
28
  readonly maxBindValues = 2100;
24
29
  /** `OUTPUT` has no trailing form: it sits between the column list and `VALUES`. */
@@ -68,7 +73,7 @@ export declare class MsSqlDialect extends MergeSqlDialect {
68
73
  * carrying a trigger, and through a table it works whether one is there or not.
69
74
  */
70
75
  returningId<E>(meta: EntityMeta<E>): string;
71
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
76
+ upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], opts?: UpsertOptions<E>): void;
72
77
  /**
73
78
  * A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
74
79
  * `OUTPUT` fills, typed as the id column is, and the read handing that back, uncounted so the batch
@@ -1,4 +1,4 @@
1
- import { relationTermKey } from '../dialect/abstractSqlDialect.js';
1
+ import { ANSI_SQL_VALUES, fromRows, relationTermKey, } from '../dialect/abstractSqlDialect.js';
2
2
  import { AGGREGATE_VALUE_ALIAS, JSON_PULL_ALIAS } from '../dialect/aliases.js';
3
3
  import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
4
4
  import { jsonArraySlotArgs, jsonPath, jsonSlotArgs } from '../dialect/jsonSql.js';
@@ -47,6 +47,7 @@ const MSSQL_FEATURES = {
47
47
  layout: 'tableFirst',
48
48
  scope: 'schema',
49
49
  before: false,
50
+ deferrable: false,
50
51
  },
51
52
  };
52
53
  /** The `type` `OPENJSON` reports for the JSON scalar an element is compared with; anything else binds as a string. */
@@ -84,8 +85,20 @@ export class MsSqlDialect extends MergeSqlDialect {
84
85
  */
85
86
  isolationLevelStrategy = 'set-before';
86
87
  booleanLiteral = 'integer';
87
- /** UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. */
88
- currentTimestamp = 'SYSUTCDATETIME()';
88
+ /**
89
+ * The clock in UTC, since `CURRENT_TIMESTAMP` is local time in the server's zone. No v7: `NEWSEQUENTIALID()` is
90
+ * an ordered v4 with no readable timestamp, so it is refused rather than served as one.
91
+ */
92
+ sqlValues = {
93
+ ...ANSI_SQL_VALUES,
94
+ currentTimestamp: 'SYSUTCDATETIME()',
95
+ uuid: 'NEWID()',
96
+ };
97
+ /** Only where the statement touched a row the trigger selects, since it fires once per statement, even for none. */
98
+ refusal(message, rows) {
99
+ const touched = rows ? `IF EXISTS (SELECT 1${fromRows(rows)}) ` : '';
100
+ return `${touched}THROW 50000, ${message}, 1;`;
101
+ }
89
102
  /** [The hard server limit](https://github.com/yiisoft/yii2/issues/10371), not a driver preference. */
90
103
  maxBindValues = 2100;
91
104
  /** `OUTPUT` has no trailing form: it sits between the column list and `VALUES`. */
@@ -167,8 +180,8 @@ export class MsSqlDialect extends MergeSqlDialect {
167
180
  const expression = this.returningIdExpression(meta);
168
181
  return expression ? this.mergeReturning(expression) : '';
169
182
  }
170
- upsert(ctx, entity, conflictPaths, payload) {
171
- this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload));
183
+ upsert(ctx, entity, conflictPaths, payload, opts) {
184
+ this.writeRows(ctx, getMeta(entity), payload, () => super.upsert(ctx, entity, conflictPaths, payload, opts));
172
185
  }
173
186
  /**
174
187
  * A statement writing rows, `write`, wrapped in what SQL Server needs around one. The table variable its
@@ -1,12 +1,15 @@
1
1
  import { PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
2
- import type { QueryConflictPaths, QueryContext, SqlDialectFeatures, SqlDialectName, Type } from '../type/index.js';
2
+ import type { QueryContext, SqlDialectFeatures, SqlDialectName, SqlValues, Type } from '../type/index.js';
3
3
  /** PostgreSQL, under every driver: `pg`, Neon, PGlite, `bun:sql`. Adds pgvector and the `xmax` upsert `created`. */
4
4
  export declare class PostgresDialect extends PgLikeSqlDialect {
5
5
  readonly dialectName: SqlDialectName;
6
6
  readonly vectorExtension: string | undefined;
7
7
  /** pgvector is the only engine with `halfvec` and `sparsevec`. */
8
8
  readonly features: SqlDialectFeatures;
9
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
9
+ /** `uuidv7()` is Postgres 18+; an older server refuses it itself. */
10
+ readonly sqlValues: SqlValues;
11
+ /** The xmax system column is 0 for a newly inserted row and non-zero for an updated one (MVCC). */
12
+ protected readonly upsertCreatedReturning: string;
10
13
  /**
11
14
  * `to_regclass` rather than a `::regclass` cast: it answers `NULL` for a table that does not exist
12
15
  * (mid-migration, say) where the cast throws. `GREATEST` because a table nothing has analyzed yet
@@ -1,5 +1,5 @@
1
1
  import { AGGREGATE_VALUE_ALIAS, UPSERT_CREATED_ALIAS } from '../dialect/aliases.js';
2
- import { PG_FEATURES, PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
2
+ import { PG_FEATURES, PG_SQL_VALUES, PgLikeSqlDialect } from '../dialect/pgLikeSqlDialect.js';
3
3
  import { getMeta } from '../entity/index.js';
4
4
  /** PostgreSQL, under every driver: `pg`, Neon, PGlite, `bun:sql`. Adds pgvector and the `xmax` upsert `created`. */
5
5
  export class PostgresDialect extends PgLikeSqlDialect {
@@ -7,10 +7,10 @@ export class PostgresDialect extends PgLikeSqlDialect {
7
7
  vectorExtension = 'vector';
8
8
  /** pgvector is the only engine with `halfvec` and `sparsevec`. */
9
9
  features = { ...PG_FEATURES, narrowVectorTypes: true };
10
- upsert(ctx, entity, conflictPaths, payload) {
11
- // The xmax system column is 0 for a newly inserted row and non-zero for an updated one (MVCC).
12
- super.upsert(ctx, entity, conflictPaths, payload, `(xmax = 0) AS ${this.escapeId(UPSERT_CREATED_ALIAS)}`);
13
- }
10
+ /** `uuidv7()` is Postgres 18+; an older server refuses it itself. */
11
+ sqlValues = { ...PG_SQL_VALUES, uuidv7: 'uuidv7()' };
12
+ /** The xmax system column is 0 for a newly inserted row and non-zero for an updated one (MVCC). */
13
+ upsertCreatedReturning = `(xmax = 0) AS ${this.escapeId(UPSERT_CREATED_ALIAS)}`;
14
14
  /**
15
15
  * `to_regclass` rather than a `::regclass` cast: it answers `NULL` for a table that does not exist
16
16
  * (mid-migration, say) where the cast throws. `GREATEST` because a table nothing has analyzed yet
@@ -1,5 +1,5 @@
1
1
  import type { AbstractDialect } from '../dialect/abstractDialect.js';
2
- import type { CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, QueryUpdateResult, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdatePayload, UpdateWrite, WrittenId } from '../type/index.js';
2
+ import type { CursorPage, EntityData, EntityId, EntityWrite, ExtraOptions, FieldKey, Querier, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryFilter, QueryFindResult, QueryGroupMap, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, PrimaryKey, QueryUpdateResult, QueryUpsertOneResult, QueryUpsertManyResult, RelationKey, TransactionOptions, Type, UpdatePayload, UpdateWrite, UpsertOptions, WrittenId } from '../type/index.js';
3
3
  import { LoggerWrapper } from '../util/index.js';
4
4
  /** Base class for all database queriers. */
5
5
  export declare abstract class AbstractQuerier implements Querier {
@@ -127,16 +127,16 @@ export declare abstract class AbstractQuerier implements Querier {
127
127
  */
128
128
  private unversionedUpdate;
129
129
  /** Fires `beforeUpsert`/`afterUpsert`: which branch a row takes is the database's to decide, so neither the insert's nor the update's pair fits. */
130
- upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>): Promise<QueryUpsertOneResult<E>>;
131
- upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[]): Promise<QueryUpsertManyResult<E>>;
130
+ upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, opts?: UpsertOptions<E>): Promise<QueryUpsertOneResult<E>>;
131
+ upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], opts?: UpsertOptions<E>): Promise<QueryUpsertManyResult<E>>;
132
132
  /**
133
133
  * An upsert on an entity a `security` filter guards. `ON CONFLICT` updates the conflicting row whoever
134
134
  * it belongs to, so the rows the conflict names are read through the filter: those found update, the
135
135
  * rest insert, where another tenant's row fails on its key. See architecture/security-filter-writes.md.
136
136
  */
137
137
  private guardedUpsert;
138
- protected abstract internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>): Promise<QueryUpdateResult>;
139
- protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<QueryUpdateResult>;
138
+ protected abstract internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
139
+ protected abstract internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
140
140
  deleteOneById<E extends object>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions): Promise<number>;
141
141
  /** Delete records matching the query, the entity passed first or as `$entity`; soft-deletes unless `opts.hardDelete`. */
142
142
  deleteMany<E extends object>(q: QuerySearch<E> & {