uql-orm 0.92.0 → 0.93.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) 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 +147 -64
  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/index.d.ts +1 -1
  22. package/dist/migrate/ddl/index.js +3 -3
  23. package/dist/migrate/ddl/mssqlTableDdl.d.ts +3 -1
  24. package/dist/migrate/ddl/mssqlTableDdl.js +4 -0
  25. package/dist/migrate/ddl/mysqlTableDdl.d.ts +1 -1
  26. package/dist/migrate/ddl/mysqlTableDdl.js +2 -2
  27. package/dist/migrate/ddl/pgTableDdl.d.ts +5 -1
  28. package/dist/migrate/ddl/pgTableDdl.js +13 -7
  29. package/dist/migrate/ddl/tableDdl.d.ts +9 -6
  30. package/dist/migrate/ddl/tableDdl.js +16 -7
  31. package/dist/migrate/ddl/tableRebuild.d.ts +2 -5
  32. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
  33. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +4 -5
  34. package/dist/migrate/introspection/mysqlIntrospector.js +4 -2
  35. package/dist/migrate/schemaChange.d.ts +2 -5
  36. package/dist/migrate/schemaGenerator.js +2 -2
  37. package/dist/migrate/storage/databaseStorage.js +2 -2
  38. package/dist/migrate/triggerSql.js +9 -2
  39. package/dist/mongo/mongoDialect.d.ts +0 -2
  40. package/dist/mongo/mongoDialect.js +18 -14
  41. package/dist/mongo/mongodbQuerier.d.ts +13 -5
  42. package/dist/mongo/mongodbQuerier.js +39 -5
  43. package/dist/mssql/mssqlDialect.d.ts +9 -4
  44. package/dist/mssql/mssqlDialect.js +18 -5
  45. package/dist/postgres/postgresDialect.d.ts +5 -2
  46. package/dist/postgres/postgresDialect.js +5 -5
  47. package/dist/querier/abstractQuerier.d.ts +5 -5
  48. package/dist/querier/abstractQuerier.js +19 -15
  49. package/dist/querier/abstractQuerierPool.js +22 -22
  50. package/dist/querier/abstractSqlQuerier.d.ts +3 -3
  51. package/dist/querier/abstractSqlQuerier.js +7 -7
  52. package/dist/schema/schemaASTBuilder.js +2 -16
  53. package/dist/schema/sqlExpression.d.ts +9 -3
  54. package/dist/schema/sqlExpression.js +14 -0
  55. package/dist/schema/types.d.ts +2 -5
  56. package/dist/sqlite/sqliteDialect.d.ts +5 -4
  57. package/dist/sqlite/sqliteDialect.js +12 -4
  58. package/dist/type/dialect.d.ts +29 -11
  59. package/dist/type/dialect.js +2 -0
  60. package/dist/type/entity.d.ts +20 -5
  61. package/dist/type/migration.d.ts +7 -8
  62. package/dist/type/query.d.ts +12 -1
  63. package/dist/type/universalQuerier.d.ts +3 -3
  64. package/dist/util/dialect.util.d.ts +1 -1
  65. package/dist/util/index.d.ts +1 -1
  66. package/dist/util/index.js +1 -1
  67. package/dist/util/raw.d.ts +13 -3
  68. package/dist/util/raw.js +29 -3
  69. package/dist/util/triggerWrite.d.ts +11 -1
  70. package/dist/util/triggerWrite.js +14 -0
  71. package/package.json +10 -10
  72. package/skills/uql-orm/SKILL.md +22 -52
  73. package/dist/migrate/builder/expressions.d.ts +0 -63
  74. package/dist/migrate/builder/expressions.js +0 -142
@@ -34,6 +34,15 @@ export const mongoDialectFeatures = {
34
34
  };
35
35
  /** What `toWireId` converts: the hex spelling of an `ObjectId`, and nothing looser. */
36
36
  const HEX_24 = /^[0-9a-f]{24}$/i;
37
+ /** `raw()` renders SQL, which MongoDB has no equivalent of: refused rather than emitted as `{}`. */
38
+ function rawRefusal(place) {
39
+ return new UqlUsageError(`raw() in ${place} is not supported on MongoDB`);
40
+ }
41
+ function assertNoRaw(value, place) {
42
+ if (value instanceof QueryRaw) {
43
+ throw rawRefusal(place);
44
+ }
45
+ }
37
46
  /** How a declared column type reads in a message: `Number`, `uuid` - not its whole source. */
38
47
  function declaredTypeName(type) {
39
48
  return typeof type === 'function' ? type.name : String(type);
@@ -170,14 +179,14 @@ export class MongoDialect extends AbstractDialect {
170
179
  filter['$text'] = { $search: $value, ...($config && { $language: textLanguage($config) }) };
171
180
  }
172
181
  else if (meta.relations[key]) {
173
- this.assertNoRaw(val);
182
+ assertNoRaw(val, '$where');
174
183
  if (!lookups) {
175
184
  throw new UqlUsageError(`filtering by relation '${key}' is not supported here on MongoDB`);
176
185
  }
177
186
  this.appendRelationLookup(filter, meta, key, val, lookups);
178
187
  }
179
188
  else {
180
- this.assertNoRaw(val);
189
+ assertNoRaw(val, '$where');
181
190
  this.assertKnownPathRoot(meta, key);
182
191
  if (aggregateOf(meta.fields[key])) {
183
192
  if (!lookups) {
@@ -219,7 +228,7 @@ export class MongoDialect extends AbstractDialect {
219
228
  const { join, negate } = GROUP_OPS[key];
220
229
  const parts = groupClauses(key, val)
221
230
  .map((filterIt) => {
222
- this.assertNoRaw(filterIt);
231
+ assertNoRaw(filterIt, '$where');
223
232
  return this.renderFilter(entity, filterIt, lookups);
224
233
  })
225
234
  .filter((part) => Object.keys(part).length > 0);
@@ -310,12 +319,6 @@ export class MongoDialect extends AbstractDialect {
310
319
  target: this.columnOf(throughMeta, targetColumn),
311
320
  };
312
321
  }
313
- /** `raw()` renders SQL, so it has no MongoDB equivalent - say so instead of emitting `{}`. */
314
- assertNoRaw(value) {
315
- if (value instanceof QueryRaw) {
316
- throw new UqlUsageError('raw() in $where is not supported on MongoDB');
317
- }
318
- }
319
322
  /**
320
323
  * A dotted key addresses an embedded path, whose root must still be a declared field - otherwise it
321
324
  * is a typo (or an injected key) that would silently match nothing, the same guard the SQL dialects
@@ -424,7 +427,7 @@ export class MongoDialect extends AbstractDialect {
424
427
  return {};
425
428
  }
426
429
  if (isSelectList(select)) {
427
- throw new UqlUsageError('raw $select is not supported on MongoDB');
430
+ throw rawRefusal('$select');
428
431
  }
429
432
  const fields = normalizeScalarFieldSelection(meta, select, exclude);
430
433
  // Projected by column, not by field key; `normalizeId` maps them back on the way out.
@@ -1004,6 +1007,7 @@ export class MongoDialect extends AbstractDialect {
1004
1007
  for (const [key, value] of Object.entries(persistable)) {
1005
1008
  if (isFieldUpdateOp(value)) {
1006
1009
  const [op, operand] = fieldUpdateOf(key, value);
1010
+ assertNoRaw(operand, 'a write');
1007
1011
  arithmetic[key] = { [MONGO_ARITHMETIC[op]]: [{ $ifNull: [`$${key}`, 0] }, { $literal: operand }] };
1008
1012
  continue;
1009
1013
  }
@@ -1100,7 +1104,9 @@ export class MongoDialect extends AbstractDialect {
1100
1104
  if (key === idKey)
1101
1105
  continue;
1102
1106
  const field = meta.fields[key];
1103
- doc[this.resolveColumnName(key, field)] = field.references ? this.toWireId(it[key]) : it[key];
1107
+ const value = it[key];
1108
+ assertNoRaw(value, 'a write');
1109
+ doc[this.resolveColumnName(key, field)] = field.references ? this.toWireId(value) : value;
1104
1110
  }
1105
1111
  return doc;
1106
1112
  });
@@ -1220,9 +1226,7 @@ export class MongoDialect extends AbstractDialect {
1220
1226
  if (isGroupOp(key)) {
1221
1227
  const { join, negate } = GROUP_OPS[key];
1222
1228
  const clauses = groupClauses(key, where[key]).map((clause) => {
1223
- if (clause instanceof QueryRaw) {
1224
- throw new UqlUsageError('raw SQL is not supported in an aggregate $where on MongoDB');
1225
- }
1229
+ assertNoRaw(clause, 'an aggregate $where');
1226
1230
  return this.whereExpression(meta, clause, named);
1227
1231
  });
1228
1232
  return negate ? { $not: [{ [join]: clauses }] } : { [join]: clauses };
@@ -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> & {
@@ -1,7 +1,7 @@
1
1
  import { assertSoleId, getMeta, idOf, namesKey, relationOf } from '../entity/index.js';
2
2
  import { namesRows } from '../dialect/operators.js';
3
3
  import { parseQueryLock } from '../type/index.js';
4
- import { cascadesOnDelete, childrenOf, clone, entityName, fillOnFields, filterFieldKeys, filterPersistableRelationKeys, forEachRequestedRelation, getKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetKeyColumns, whereAnyOf, whereEach, whereIds, whereWith, withoutSoftDeleteFilter, } from '../util/index.js';
4
+ import { cascadesOnDelete, childrenOf, clone, entityName, fillOnFields, filterFieldKeys, filterPersistableRelationKeys, forEachRequestedRelation, getKeys, hasKeys, getRelationRequestSummary, guardWrite, idOnlyQuery, keySet, isPagedQuery, isScalarId, LoggerWrapper, parentJoins, queryLoggerFor, parseRelationAtKey, parseRelationQueryValue, rowKey, runHooks, securityConditions, someKey, targetKeyColumns, whereAnyOf, whereEach, whereIds, whereWith, withoutSoftDeleteFilter, } from '../util/index.js';
5
5
  import { UqlOptimisticLockError, UqlUsageError } from '../util/uqlError.js';
6
6
  import { keysetRead } from './keyset.js';
7
7
  import { enrichError } from './queryError.js';
@@ -87,6 +87,14 @@ function assertLockableUpdate(meta, q, settles) {
87
87
  function writtenIds(meta, rows) {
88
88
  return rows.map((row) => (namesKey(meta, row) ? idOf(meta, row) : undefined));
89
89
  }
90
+ /** What `ON CONFLICT` assigns a row it finds by default: the payload, less the columns it matched on. */
91
+ function conflictAssignments(row, conflictPaths) {
92
+ const assigned = { ...row };
93
+ for (const key of getKeys(conflictPaths)) {
94
+ delete assigned[key];
95
+ }
96
+ return assigned;
97
+ }
90
98
  /**
91
99
  * Writes the key an upsert reported onto each row that named none - only the key, since an `onInsert`
92
100
  * value was never written to a row the upsert updated. A report aligns with the rows only when it
@@ -368,25 +376,25 @@ export class AbstractQuerier {
368
376
  return this.hooked(entity, 'Update', [payload], ([row]) => this.updateRows(entity, q, row, opts, undefined));
369
377
  }
370
378
  /** 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. */
371
- async upsertOne(entity, conflictPaths, payload) {
379
+ async upsertOne(entity, conflictPaths, payload, opts = {}) {
372
380
  const meta = getMeta(entity);
373
381
  assertUnversioned(meta, "'upsertOne'");
374
382
  return this.hooked(entity, 'Upsert', [payload], async (rows) => {
375
383
  const { ids, changes, created } = securityConditions(meta).length
376
- ? await this.guardedUpsert(entity, conflictPaths, rows)
377
- : await this.internalUpsertOne(entity, conflictPaths, rows[0]);
384
+ ? await this.guardedUpsert(entity, conflictPaths, rows, opts)
385
+ : await this.internalUpsertOne(entity, conflictPaths, rows[0], opts);
378
386
  adoptReportedIds(meta, rows, ids);
379
387
  const [id] = writtenIds(meta, rows);
380
388
  return { id, changes, created };
381
389
  });
382
390
  }
383
- async upsertMany(entity, conflictPaths, payload) {
391
+ async upsertMany(entity, conflictPaths, payload, opts = {}) {
384
392
  const meta = getMeta(entity);
385
393
  assertUnversioned(meta, "'upsertMany'");
386
394
  return this.hooked(entity, 'Upsert', payload, async (rows) => {
387
395
  const { ids, changes } = securityConditions(meta).length
388
- ? await this.guardedUpsert(entity, conflictPaths, rows)
389
- : await this.internalUpsertMany(entity, conflictPaths, rows);
396
+ ? await this.guardedUpsert(entity, conflictPaths, rows, opts)
397
+ : await this.internalUpsertMany(entity, conflictPaths, rows, opts);
390
398
  adoptReportedIds(meta, rows, ids);
391
399
  return { ids: writtenIds(meta, rows), changes };
392
400
  });
@@ -396,7 +404,7 @@ export class AbstractQuerier {
396
404
  * it belongs to, so the rows the conflict names are read through the filter: those found update, the
397
405
  * rest insert, where another tenant's row fails on its key. See architecture/security-filter-writes.md.
398
406
  */
399
- async guardedUpsert(entity, conflictPaths, rows) {
407
+ async guardedUpsert(entity, conflictPaths, rows, { update }) {
400
408
  guardWrite(getMeta(entity), rows, 'insert');
401
409
  if (!rows.length) {
402
410
  return { changes: 0 };
@@ -406,13 +414,9 @@ export class AbstractQuerier {
406
414
  const ids = await this.idsByConflict(entity, conflictPaths, rows);
407
415
  let changes = 0;
408
416
  for (const [index, row] of rows.entries()) {
409
- if (ids[index] !== undefined) {
410
- // What `ON CONFLICT` would assign: the row, less the columns it matched on.
411
- const payload = { ...row };
412
- for (const key of keys) {
413
- delete payload[key];
414
- }
415
- changes += await this.updateColumns(entity, { $where: whereEach(keys, (key) => row[key]) }, payload, undefined, 0);
417
+ // An empty `update` leaves a found row as it is, as `DO NOTHING` does.
418
+ if (ids[index] !== undefined && (update === undefined || hasKeys(update))) {
419
+ changes += await this.updateColumns(entity, { $where: whereEach(keys, (key) => row[key]) }, update ?? conflictAssignments(row, conflictPaths), undefined, 0);
416
420
  }
417
421
  }
418
422
  const inserts = rows.filter((_, index) => ids[index] === undefined);
@@ -86,14 +86,14 @@ export class AbstractQuerierPool {
86
86
  runScoped(context, fn) {
87
87
  return context ? withContext(context, fn) : fn();
88
88
  }
89
- findOneById = (entity, id, q, opts) => this.withQuerier((querier) => querier.findOneById(entity, id, q, opts));
90
- findOne = (entity, q, opts) => this.withQuerier((querier) => querier.findOne(entity, q, opts));
91
- findMany = (entity, q, opts) => this.withQuerier((querier) => querier.findMany(entity, q, opts));
89
+ findOneById = (...args) => this.withQuerier((querier) => querier.findOneById(...args));
90
+ findOne = (...args) => this.withQuerier((querier) => querier.findOne(...args));
91
+ findMany = (...args) => this.withQuerier((querier) => querier.findMany(...args));
92
92
  /**
93
93
  * The connection outlives the call: it is held until the iterator is drained or closed by a `break` or
94
94
  * `throw`. Abandoning the iterator leaks it until GC, so consume it in a `for await`.
95
95
  */
96
- findManyStream = (entity, q, opts) => this.streamWithQuerier((querier) => querier.findManyStream(entity, q, opts));
96
+ findManyStream = (...args) => this.streamWithQuerier((querier) => querier.findManyStream(...args));
97
97
  async *streamWithQuerier(read) {
98
98
  const env_1 = { stack: [], error: void 0, hasError: false };
99
99
  try {
@@ -110,22 +110,22 @@ export class AbstractQuerierPool {
110
110
  await result_1;
111
111
  }
112
112
  }
113
- findManyAndCount = (entity, q, opts) => this.withQuerier((querier) => querier.findManyAndCount(entity, q, opts));
114
- findManyPage = (entity, q, opts) => this.withQuerier((querier) => querier.findManyPage(entity, q, opts));
115
- count = (entity, q, opts) => this.withQuerier((querier) => querier.count(entity, q, opts));
116
- exists = (entity, q, opts) => this.withQuerier((querier) => querier.exists(entity, q, opts));
117
- aggregate = (entity, q, opts) => this.withQuerier((querier) => querier.aggregate(entity, q, opts));
118
- estimatedCount = (entity) => this.withQuerier((querier) => querier.estimatedCount(entity));
119
- insertOne = (entity, payload) => this.withQuerier((querier) => querier.insertOne(entity, payload));
120
- insertMany = (entity, payload) => this.withQuerier((querier) => querier.insertMany(entity, payload));
121
- updateOneById = (entity, id, payload, opts) => this.withQuerier((querier) => querier.updateOneById(entity, id, payload, opts));
122
- updateMany = (entity, q, payload, opts) => this.withQuerier((querier) => querier.updateMany(entity, q, payload, opts));
123
- upsertOne = (entity, conflictPaths, payload) => this.withQuerier((querier) => querier.upsertOne(entity, conflictPaths, payload));
124
- upsertMany = (entity, conflictPaths, payload) => this.withQuerier((querier) => querier.upsertMany(entity, conflictPaths, payload));
125
- saveOne = (entity, payload) => this.withQuerier((querier) => querier.saveOne(entity, payload));
126
- saveMany = (entity, payload) => this.withQuerier((querier) => querier.saveMany(entity, payload));
127
- deleteOneById = (entity, id, opts) => this.withQuerier((querier) => querier.deleteOneById(entity, id, opts));
128
- deleteMany = (entity, q, opts) => this.withQuerier((querier) => querier.deleteMany(entity, q, opts));
129
- restoreOneById = (entity, id) => this.withQuerier((querier) => querier.restoreOneById(entity, id));
130
- restoreMany = (entity, q) => this.withQuerier((querier) => querier.restoreMany(entity, q));
113
+ findManyAndCount = (...args) => this.withQuerier((querier) => querier.findManyAndCount(...args));
114
+ findManyPage = (...args) => this.withQuerier((querier) => querier.findManyPage(...args));
115
+ count = (...args) => this.withQuerier((querier) => querier.count(...args));
116
+ exists = (...args) => this.withQuerier((querier) => querier.exists(...args));
117
+ aggregate = (...args) => this.withQuerier((querier) => querier.aggregate(...args));
118
+ estimatedCount = (...args) => this.withQuerier((querier) => querier.estimatedCount(...args));
119
+ insertOne = (...args) => this.withQuerier((querier) => querier.insertOne(...args));
120
+ insertMany = (...args) => this.withQuerier((querier) => querier.insertMany(...args));
121
+ updateOneById = (...args) => this.withQuerier((querier) => querier.updateOneById(...args));
122
+ updateMany = (...args) => this.withQuerier((querier) => querier.updateMany(...args));
123
+ upsertOne = (...args) => this.withQuerier((querier) => querier.upsertOne(...args));
124
+ upsertMany = (...args) => this.withQuerier((querier) => querier.upsertMany(...args));
125
+ saveOne = (...args) => this.withQuerier((querier) => querier.saveOne(...args));
126
+ saveMany = (...args) => this.withQuerier((querier) => querier.saveMany(...args));
127
+ deleteOneById = (...args) => this.withQuerier((querier) => querier.deleteOneById(...args));
128
+ deleteMany = (...args) => this.withQuerier((querier) => querier.deleteMany(...args));
129
+ restoreOneById = (...args) => this.withQuerier((querier) => querier.restoreOneById(...args));
130
+ restoreMany = (...args) => this.withQuerier((querier) => querier.restoreMany(...args));
131
131
  }
@@ -1,5 +1,5 @@
1
1
  import type { AbstractSqlDialect } from '../dialect/index.js';
2
- import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, SqlQuerier, TransactionOptions, Type, UpdatePayload } from '../type/index.js';
2
+ import type { EntityData, ExtraOptions, Query, QueryAggMap, QueryAggregate, QueryAggregateResult, QueryConflictPaths, QueryPage, QueryGroupMap, QueryOptions, QuerySearch, QueryUpdateResult, SqlQuerier, TransactionOptions, Type, UpdatePayload, UpsertOptions } from '../type/index.js';
3
3
  import type { BuildUpdateResultPayload } from '../util/sql.util.js';
4
4
  import { AbstractQuerier } from './abstractQuerier.js';
5
5
  export declare abstract class AbstractSqlQuerier extends AbstractQuerier implements SqlQuerier {
@@ -85,8 +85,8 @@ export declare abstract class AbstractSqlQuerier extends AbstractQuerier impleme
85
85
  protected internalAggregate<E extends object, G extends QueryGroupMap<E>, A extends QueryAggMap<E>>(entity: Type<E>, q: QueryAggregate<E, G, A>, opts?: QueryOptions): Promise<QueryAggregateResult<E, G, A>[]>;
86
86
  internalInsertMany<E extends object>(entity: Type<E>, rows: EntityData<E>[]): Promise<void>;
87
87
  internalUpdateMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryOptions): Promise<number>;
88
- protected internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>): Promise<QueryUpdateResult>;
89
- protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityData<E>[]): Promise<QueryUpdateResult>;
88
+ protected internalUpsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E, opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
89
+ protected internalUpsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E[], opts: UpsertOptions<E>): Promise<QueryUpdateResult>;
90
90
  private runUpsert;
91
91
  protected internalDeleteMany<E extends object>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions): Promise<number>;
92
92
  get hasOpenTransaction(): boolean;
@@ -341,10 +341,10 @@ export class AbstractSqlQuerier extends AbstractQuerier {
341
341
  const { changes = 0 } = await this.exec((ctx) => this.dialect.update(ctx, entity, q, payload, opts));
342
342
  return changes;
343
343
  }
344
- async internalUpsertOne(entity, conflictPaths, payload) {
345
- return this.internalUpsertMany(entity, conflictPaths, [payload]);
344
+ async internalUpsertOne(entity, conflictPaths, payload, opts) {
345
+ return this.internalUpsertMany(entity, conflictPaths, [payload], opts);
346
346
  }
347
- async internalUpsertMany(entity, conflictPaths, payload) {
347
+ async internalUpsertMany(entity, conflictPaths, payload, opts) {
348
348
  if (!payload?.length) {
349
349
  return { changes: 0 };
350
350
  }
@@ -355,7 +355,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
355
355
  // `DO UPDATE SET` resolves to non-binding `EXCLUDED` references rather than inlined values.
356
356
  const statements = groupByInsertShape(meta, payload).flatMap((group) => chunkByBindBudget(meta, payload, group, this.dialect.maxBindValues));
357
357
  if (statements.length === 1) {
358
- return this.runUpsert(entity, conflictPaths, payload);
358
+ return this.runUpsert(entity, conflictPaths, payload, opts);
359
359
  }
360
360
  // An upsert's assignment list is the statement's, so rows of different shapes go in statements
361
361
  // of their own, together in a transaction (`transaction` is re-entrant).
@@ -365,7 +365,7 @@ export class AbstractSqlQuerier extends AbstractQuerier {
365
365
  // than it wrote places none.
366
366
  const ids = new Array(payload.length);
367
367
  for (const indexes of statements) {
368
- const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]));
368
+ const { changes: written = 0, ids: reported } = await this.runUpsert(entity, conflictPaths, indexes.map((index) => payload[index]), opts);
369
369
  changes += written;
370
370
  if (reported?.length === indexes.length) {
371
371
  for (let position = 0; position < indexes.length; position++) {
@@ -377,11 +377,11 @@ export class AbstractSqlQuerier extends AbstractQuerier {
377
377
  return { changes, ids };
378
378
  });
379
379
  }
380
- async runUpsert(entity, conflictPaths, payload) {
380
+ async runUpsert(entity, conflictPaths, payload, opts) {
381
381
  const meta = getMeta(entity);
382
382
  // Asked first: the statement fills an `onInsert` key into these rows whether it inserts them or not.
383
383
  const unnamed = meta.ids.length === 1 && payload.some((row) => !namesKey(meta, row));
384
- const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload));
384
+ const result = await this.exec((ctx) => this.dialect.upsert(ctx, entity, conflictPaths, payload, opts));
385
385
  const ordered = payload.length === 1 ||
386
386
  (this.dialect.insertIdSource === 'returning' && this.dialect.features.orderedUpsertReturning);
387
387
  if (ordered && result.ids?.length === payload.length) {
@@ -1,15 +1,13 @@
1
1
  import { fieldOf, foreignKeysOf, getMeta } from '../entity/metadata/definition.js';
2
- import { QueryRaw } from '../type/queryRaw.js';
3
2
  import { declaredIndexes, declaredIndexName, renderIndexColumn } from '../util/ddlExpression.util.js';
4
3
  import { fulltextWeights, textWeightSteps } from '../util/dialect.util.js';
5
4
  import { declaresNotNull, isAutoIncrement, isInlinedExpression, isSoleIdField } from '../util/field.util.js';
6
5
  import { definedEntries } from '../util/object.util.js';
7
- import { currentTimestamp } from '../util/raw.js';
8
6
  import { derivedForeignKeyName, derivedIndexName, qualifyName } from '../util/sql.util.js';
9
7
  import { UqlUsageError } from '../util/uqlError.js';
10
8
  import { resolveColumnCanonicalType } from './canonicalType.js';
11
9
  import { createTableNode, keyOfColumns, SchemaAST } from './schemaAST.js';
12
- import { SqlExpression } from './sqlExpression.js';
10
+ import { schemaDefault } from './sqlExpression.js';
13
11
  import { DEFAULT_FOREIGN_KEY_ACTION } from './types.js';
14
12
  /**
15
13
  * Build a SchemaAST from entity classes (decorated with `@Entity`, `@Field`, etc.).
@@ -71,7 +69,7 @@ function addTableFromEntity(ctx, meta) {
71
69
  name: columnName,
72
70
  type,
73
71
  nullable: !declaresNotNull(field) && !notNull.has(key),
74
- defaultValue: columnDefault(ctx, meta, field.defaultValue),
72
+ defaultValue: schemaDefault(field.defaultValue, (sql) => ctx.compileDdl(sql, meta.entity)),
75
73
  isPrimaryKey,
76
74
  isAutoIncrement: isAutoIncrement(field, isSoleKey),
77
75
  isUnique: field.unique ?? false,
@@ -88,18 +86,6 @@ function addTableFromEntity(ctx, meta) {
88
86
  table.primaryKey = keyOfColumns(columns.values());
89
87
  ctx.ast.addTable(table);
90
88
  }
91
- /**
92
- * A field's default in schema form: SQL becomes an {@link SqlExpression}, and `currentTimestamp` stays
93
- * symbolic (`now`) so each engine spells it for the column it fills.
94
- */
95
- function columnDefault(ctx, meta, value) {
96
- if (!(value instanceof QueryRaw)) {
97
- return value;
98
- }
99
- return value === currentTimestamp
100
- ? new SqlExpression('now')
101
- : SqlExpression.parenthesized(ctx.compileDdl(value, meta.entity));
102
- }
103
89
  /** The node an entity maps to, found under the key {@link SchemaAST} stores it by. */
104
90
  function tableOf(ctx, meta) {
105
91
  return ctx.ast.getTable(qualifyName(ctx.resolveTableName(meta), ctx.resolveSchema(meta)));