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,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);
@@ -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)));
@@ -1,8 +1,9 @@
1
+ import { QueryRaw, type SqlValueName } from '../type/index.js';
1
2
  /**
2
- * The kind of a {@link SqlExpression}. Kinds are symbolic: `formatDefaultValue` renders each in the
3
- * dialect's spelling at DDL time, while `raw` carries its own SQL.
3
+ * The kind of a {@link SqlExpression}: a value uql exports by name, which `formatDefaultValue` spells for the
4
+ * engine at DDL time, or `raw`, carrying its own SQL.
4
5
  */
5
- export type SqlExpressionKind = 'now' | 'currentDate' | 'currentTime' | 'uuid' | 'uuidv7' | 'onUpdateNow' | 'raw';
6
+ export type SqlExpressionKind = SqlValueName | 'raw';
6
7
  /**
7
8
  * A column default that is SQL rather than a literal, whether an entity or a migration declares it or
8
9
  * introspection reads it back. It is a class, not a plain object, so a JSON default cannot pass for one.
@@ -18,5 +19,10 @@ export declare class SqlExpression {
18
19
  /** Its SQL, or its kind, as diffs and drift reports show it. */
19
20
  toString(): string;
20
21
  }
22
+ /**
23
+ * A default in schema form: a value uql exports (`currentTimestamp`) becomes its kind, so each engine spells it
24
+ * for the column it fills; other `raw` becomes the SQL `compile` renders, parenthesized; a literal is kept.
25
+ */
26
+ export declare function schemaDefault(value: unknown, compile: (sql: QueryRaw) => string): unknown;
21
27
  /** A default as text for an exact comparison: objects (SQL included) as JSON, numbers as their digits. */
22
28
  export declare function writtenDefault(value: unknown): string;
@@ -1,3 +1,5 @@
1
+ import { QueryRaw, SQL_VALUE_NAMES } from '../type/index.js';
2
+ import { SQL_VALUES } from '../util/raw.js';
1
3
  /**
2
4
  * A column default that is SQL rather than a literal, whether an entity or a migration declares it or
3
5
  * introspection reads it back. It is a class, not a plain object, so a JSON default cannot pass for one.
@@ -22,6 +24,18 @@ export class SqlExpression {
22
24
  return this.sql ?? this.kind;
23
25
  }
24
26
  }
27
+ const NAME_OF = new Map(SQL_VALUE_NAMES.map((name) => [SQL_VALUES[name], name]));
28
+ /**
29
+ * A default in schema form: a value uql exports (`currentTimestamp`) becomes its kind, so each engine spells it
30
+ * for the column it fills; other `raw` becomes the SQL `compile` renders, parenthesized; a literal is kept.
31
+ */
32
+ export function schemaDefault(value, compile) {
33
+ const name = NAME_OF.get(value);
34
+ if (name) {
35
+ return new SqlExpression(name);
36
+ }
37
+ return value instanceof QueryRaw ? SqlExpression.parenthesized(compile(value)) : value;
38
+ }
25
39
  /** A default as text for an exact comparison: objects (SQL included) as JSON, numbers as their digits. */
26
40
  export function writtenDefault(value) {
27
41
  return typeof value === 'object' ? JSON.stringify(value) : String(value);
@@ -1,6 +1,6 @@
1
1
  import { AbstractSqlDialect, type DerivedRelation, type RelationRows } from '../dialect/abstractSqlDialect.js';
2
2
  import { type JsonAccessMode, type JsonSlot } from '../dialect/jsonSql.js';
3
- import { type EntityMeta, type FieldOptions, type Query, type QueryContext, type QueryTextSearchOptions, type QueryWhere, type SqlDialectFeatures, type VectorDistance, type VectorMetric } from '../type/index.js';
3
+ import { type EntityMeta, type FieldOptions, type Query, type QueryContext, type QueryTextSearchOptions, type QueryWhere, type SqlDialectFeatures, type SqlValues, type VectorDistance, type VectorMetric } from '../type/index.js';
4
4
  /** What SQLite and the engines derived from it have. */
5
5
  export declare const SQLITE_FEATURES: SqlDialectFeatures;
6
6
  export declare class SqliteDialect extends AbstractSqlDialect {
@@ -12,10 +12,11 @@ export declare class SqliteDialect extends AbstractSqlDialect {
12
12
  readonly isolationLevelStrategy = "none";
13
13
  readonly booleanLiteral = "integer";
14
14
  /**
15
- * Writes the same text as a bound `Date`. `CURRENT_TIMESTAMP` writes whole seconds with no fraction, so the
16
- * two would not compare correctly. The parentheses also let SQLite take it as a column default.
15
+ * The clock and today in the same text as a bound `Date`, where `CURRENT_TIMESTAMP` writes whole seconds and
16
+ * `CURRENT_DATE` no time, so neither would compare correctly. The parentheses let SQLite take each as a default.
17
17
  */
18
- readonly currentTimestamp = "(strftime('%Y-%m-%d %H:%M:%f', 'now'))";
18
+ readonly sqlValues: SqlValues;
19
+ protected refusal(message: string): string;
19
20
  /** SQLite's own cap on a function call before 3.48, which libSQL and `bun:sqlite`'s build still have. */
20
21
  readonly maxFunctionArgs: number;
21
22
  /**
@@ -1,4 +1,4 @@
1
- import { AbstractSqlDialect, } from '../dialect/abstractSqlDialect.js';
1
+ import { ANSI_SQL_VALUES, AbstractSqlDialect, } from '../dialect/abstractSqlDialect.js';
2
2
  import { BYTES_PREFIX } from '../dialect/hydrateColumn.js';
3
3
  import { chainedCall, groupsPerCall, jsonSetCall, jsonPath, jsonArraySlotArgs, jsonSlotArgs, } from '../dialect/jsonSql.js';
4
4
  import { QueryRaw, } from '../type/index.js';
@@ -46,6 +46,7 @@ export const SQLITE_FEATURES = {
46
46
  layout: 'timingFirst',
47
47
  scope: 'schema',
48
48
  before: true,
49
+ deferrable: false,
49
50
  },
50
51
  };
51
52
  export class SqliteDialect extends AbstractSqlDialect {
@@ -57,10 +58,17 @@ export class SqliteDialect extends AbstractSqlDialect {
57
58
  isolationLevelStrategy = 'none';
58
59
  booleanLiteral = 'integer';
59
60
  /**
60
- * Writes the same text as a bound `Date`. `CURRENT_TIMESTAMP` writes whole seconds with no fraction, so the
61
- * two would not compare correctly. The parentheses also let SQLite take it as a column default.
61
+ * The clock and today in the same text as a bound `Date`, where `CURRENT_TIMESTAMP` writes whole seconds and
62
+ * `CURRENT_DATE` no time, so neither would compare correctly. The parentheses let SQLite take each as a default.
62
63
  */
63
- currentTimestamp = "(strftime('%Y-%m-%d %H:%M:%f', 'now'))";
64
+ sqlValues = {
65
+ ...ANSI_SQL_VALUES,
66
+ currentTimestamp: "(strftime('%Y-%m-%d %H:%M:%f', 'now'))",
67
+ currentDate: "(strftime('%Y-%m-%d 00:00:00.000', 'now'))",
68
+ };
69
+ refusal(message) {
70
+ return `SELECT RAISE(ABORT, ${message});`;
71
+ }
64
72
  /** SQLite's own cap on a function call before 3.48, which libSQL and `bun:sqlite`'s build still have. */
65
73
  maxFunctionArgs = 127;
66
74
  /**
@@ -1,10 +1,15 @@
1
1
  import type { EntityMeta, EntityPredicate, UpdatePayload } from './entity.js';
2
- import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery } from './query.js';
2
+ import type { Query, QueryConflictPaths, QueryPage, QueryRenderOptions, QuerySearch, RelationQuery, UpsertOptions } from './query.js';
3
3
  import type { QueryAggMap, QueryAggregate, QueryAggregateOp, QueryGroupMap } from './queryAggregate.js';
4
4
  import type { QueryRawRenderOptions } from './queryRaw.js';
5
5
  import type { QueryWhere } from './queryWhere.js';
6
6
  import type { Type } from './utility.js';
7
7
  import type { QueryVectorQuery } from './vector.js';
8
+ /** The values the database computes that uql exports by name: `currentTimestamp`, `uuid`, ... */
9
+ export declare const SQL_VALUE_NAMES: readonly ['currentTimestamp', 'currentDate', 'currentTime', 'uuid', 'uuidv7'];
10
+ export type SqlValueName = (typeof SQL_VALUE_NAMES)[number];
11
+ /** An engine's SQL for each {@link SqlValueName}, `undefined` where it has none. */
12
+ export type SqlValues = Readonly<Record<SqlValueName, string | undefined>>;
8
13
  /**
9
14
  * comparison options.
10
15
  */
@@ -233,6 +238,8 @@ export interface TriggerFeatures {
233
238
  * so a `before*` event is refused there rather than silently made to mean something else.
234
239
  */
235
240
  readonly before: boolean;
241
+ /** Whether it can be deferred to commit, as a Postgres constraint trigger is; nowhere else can. */
242
+ readonly deferrable: boolean;
236
243
  }
237
244
  /**
238
245
  * The rows a set-based trigger's writes read: the tables `from` names, `inserted` and the like, narrowed
@@ -245,22 +252,32 @@ export type TriggerRows = {
245
252
  /** Where DDL's SQL sits: the row a trigger's predicate reads, as its prefix, and a set-based body's rows. */
246
253
  export type DdlRenderOptions = Pick<QueryComparisonOptions, 'escapedPrefix' | 'operand'> & Pick<QueryRawRenderOptions, 'rows'>;
247
254
  /**
248
- * A write a trigger's body runs, as `insertInto`, `updateTable` and `deleteFrom` state it. Held untyped
249
- * here, past those helpers' typing, since the dialect renders it by the entity's metadata alone.
255
+ * A write a trigger's body runs, as `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse` state
256
+ * it. Held untyped here, past those helpers' typing, since the dialect renders it by the entity's metadata alone.
250
257
  */
251
258
  export type TriggerWrite = {
252
- readonly entity: Type<object>;
253
- } & ({
254
259
  readonly kind: 'insert';
260
+ readonly entity: Type<object>;
261
+ readonly row: Readonly<Record<string, unknown>>;
262
+ } | {
263
+ readonly kind: 'upsert';
264
+ readonly entity: Type<object>;
265
+ readonly conflictPaths: Readonly<Record<string, unknown>>;
255
266
  readonly row: Readonly<Record<string, unknown>>;
267
+ readonly update?: Readonly<Record<string, unknown>>;
256
268
  } | {
257
269
  readonly kind: 'update';
270
+ readonly entity: Type<object>;
258
271
  readonly set: Readonly<Record<string, unknown>>;
259
272
  readonly where: EntityPredicate<object>;
260
273
  } | {
261
274
  readonly kind: 'delete';
275
+ readonly entity: Type<object>;
262
276
  readonly where: EntityPredicate<object>;
263
- });
277
+ } | {
278
+ readonly kind: 'refuse';
279
+ readonly message: string;
280
+ };
264
281
  /**
265
282
  * What a SQL statement is rendered through, as a `raw` callback and a query context see it:
266
283
  * `AbstractSqlDialect` is the one implementation.
@@ -283,10 +300,11 @@ export interface SqlQueryDialect {
283
300
  /** What the engine can do. */
284
301
  readonly features: SqlDialectFeatures;
285
302
  /**
286
- * SQL for the database's current time the way uql stores a timestamp: UTC, to the millisecond, in the same
287
- * form as a bound `Date`. A bare `CURRENT_TIMESTAMP` falls short of this on SQLite, MySQL and SQL Server.
303
+ * Each {@link SqlValueName}'s SQL on this engine, `undefined` where it has none. `currentTimestamp` is UTC to
304
+ * the millisecond in the form of a bound `Date`, which a bare `CURRENT_TIMESTAMP` is not on SQLite, MySQL
305
+ * or SQL Server.
288
306
  */
289
- readonly currentTimestamp: string;
307
+ readonly sqlValues: SqlValues;
290
308
  /** A read; with `totalAlias`, every row also carries the unpaged match count under that alias. */
291
309
  find<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: QueryRenderOptions, totalAlias?: string): void;
292
310
  /** A count of the records matching the filter, or of those a page of it takes. */
@@ -295,8 +313,8 @@ export interface SqlQueryDialect {
295
313
  insert<E>(ctx: QueryContext, entity: Type<E>, payload: E | E[], opts?: QueryRenderOptions): void;
296
314
  /** An update of the records the query matches. */
297
315
  update<E>(ctx: QueryContext, entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryRenderOptions): void;
298
- /** An upsert of one record or many by their conflict paths. */
299
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[]): void;
316
+ /** An upsert of one record or many by their conflict paths, taking the options `upsertMany` takes. */
317
+ upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], opts?: UpsertOptions<E>): void;
300
318
  /** A write in a trigger's body; `rows` are what a set-based engine's body reads, narrowed to the ones it fires for. */
301
319
  triggerWrite(ctx: QueryContext, write: TriggerWrite, rows?: TriggerRows): void;
302
320
  /** A delete of the records the query matches, a soft delete where the entity has one. */
@@ -1,3 +1,5 @@
1
+ /** The values the database computes that uql exports by name: `currentTimestamp`, `uuid`, ... */
2
+ export const SQL_VALUE_NAMES = ['currentTimestamp', 'currentDate', 'currentTime', 'uuid', 'uuidv7'];
1
3
  /**
2
4
  * An index capability some engines lack, named in the words an error reports it in. Introspectors use
3
5
  * the same vocabulary for what they can read back, a separate set: MySQL emits an expression index it
@@ -771,6 +771,11 @@ type TriggerRun<E, Ev extends TriggerEvent> = TriggerBody<E, Ev> | Readonly<AtLe
771
771
  */
772
772
  export type TriggerOptions<E = unknown> = {
773
773
  [Ev in TriggerEvent]: {
774
+ /**
775
+ * The write that fires the trigger and on which side of it, `beforeUpdate` or `afterDelete`. The rows
776
+ * the body has follow from it: the incoming one on an insert, the outgoing one on a delete, both on an
777
+ * update.
778
+ */
774
779
  readonly on: Ev;
775
780
  /**
776
781
  * What to call this trigger within the entity, for a clearer identifier than its event and position.
@@ -790,6 +795,16 @@ export type TriggerOptions<E = unknown> = {
790
795
  * rendered on every engine from the one declaration, or SQL off them for what no predicate states.
791
796
  */
792
797
  readonly where?: TriggerPredicate<E, Ev> | TriggerBody<E, Ev>;
798
+ /**
799
+ * Fire at commit rather than after each statement, so a check over many rows (a ledger's entries
800
+ * summing to zero) sees the transaction's every write. Postgres only, and only after the write.
801
+ */
802
+ readonly deferred?: Ev extends `after${string}` ? boolean : never;
803
+ /**
804
+ * The body, as SQL off the rows, `(newRow, oldRow) => raw`...``: the incoming row first and the
805
+ * outgoing one second, the one `on` lacks typed `never`. One for every engine, or a map naming one
806
+ * per engine where their SQL differs.
807
+ */
793
808
  readonly run: TriggerRun<E, Ev>;
794
809
  };
795
810
  }[TriggerEvent];
@@ -1,4 +1,4 @@
1
- import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey, WrittenId } from './entity.js';
1
+ import type { FieldKey, FieldKeyOf, JsonFieldPaths, RelationKey, RelationTarget, ToManyRelationKey, UpdatePayload, WrittenId } from './entity.js';
2
2
  import type { QueryLock } from './queryLock.js';
3
3
  import type { QueryRaw } from './queryRaw.js';
4
4
  import type { QueryWhere } from './queryWhere.js';
@@ -447,6 +447,17 @@ Pick<E, Exclude<ProjectedKeys<E, S, V, X, P>, PopulatedToMany<E, P>> & keyof E>
447
447
  } : E;
448
448
  /** The to-many relations a query populated, which come back as lists rather than as optional ones. */
449
449
  type PopulatedToMany<E, P> = Extract<P, ToManyRelationKey<E>>;
450
+ /**
451
+ * How an upsert treats a row its conflict paths find: by default it takes the payload, less those paths. `U` is
452
+ * what a trigger's `upsertInto` narrows the update to.
453
+ */
454
+ export type UpsertOptions<E, U = UpdatePayload<E>> = {
455
+ /**
456
+ * What such a row takes instead, as an update does, `{ uses: { $inc: 1 } }` counting; `{}` leaves it as it is,
457
+ * inserting only where none is. The payload still inserts.
458
+ */
459
+ readonly update?: U;
460
+ };
450
461
  /** What upserting one row reports. `created` is only knowable for a single statement, so a batch has none. */
451
462
  export type QueryUpsertOneResult<E> = {
452
463
  readonly id?: WrittenId<E>;
@@ -1,5 +1,5 @@
1
1
  import type { EntityId, EntityWrite, FieldKey, RelationKey, UpdateWrite, WrittenId } from './entity.js';
2
- import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, QueryUpsertManyResult } from './query.js';
2
+ import type { CursorPage, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeysetProjected, QueryOneProjected, QueryOptions, QueryPage, QueryProjected, QuerySearch, QueryUpsertOneResult, UpsertOptions, QueryUpsertManyResult } from './query.js';
3
3
  import type { QueryAggMap, QueryAggregate, QueryAggregateResult, QueryGroupMap } from './queryAggregate.js';
4
4
  import type { Type } from './utility.js';
5
5
  import type { QuerierCountedResult, QuerierRaw, QuerierResult, QuerierTransport } from './wire.js';
@@ -93,9 +93,9 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
93
93
  */
94
94
  insertMany<E extends object>(entity: Type<E>, payload: readonly EntityWrite<E>[]): Promise<(WrittenId<E> | undefined)[]>;
95
95
  /** Insert or update a record by its conflict paths; resolves to its id and whether it was created. */
96
- upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>): Promise<QueryUpsertOneResult<E>>;
96
+ upsertOne<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, opts?: UpsertOptions<E>): Promise<QueryUpsertOneResult<E>>;
97
97
  /** Insert or update records by their conflict paths; resolves to their ids in payload order. */
98
- upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[]): Promise<QueryUpsertManyResult<E>>;
98
+ upsertMany<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: readonly EntityWrite<E>[], opts?: UpsertOptions<E>): Promise<QueryUpsertManyResult<E>>;
99
99
  /**
100
100
  * insert or update a record.
101
101
  * @param entity the entity to persist on
@@ -8,7 +8,7 @@ export * from './ddlExpression.util.js';
8
8
  export * from './logger.js';
9
9
  export * from './object.util.js';
10
10
  export * from './raw.js';
11
- export { deleteFrom, insertInto, updateTable } from './triggerWrite.js';
11
+ export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './triggerWrite.js';
12
12
  export * from './rowKey.util.js';
13
13
  export * from './relationQuery.util.js';
14
14
  export * from './sql.util.js';
@@ -8,7 +8,7 @@ export * from './ddlExpression.util.js';
8
8
  export * from './logger.js';
9
9
  export * from './object.util.js';
10
10
  export * from './raw.js';
11
- export { deleteFrom, insertInto, updateTable } from './triggerWrite.js';
11
+ export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './triggerWrite.js';
12
12
  export * from './rowKey.util.js';
13
13
  export * from './relationQuery.util.js';
14
14
  export * from './sql.util.js';
@@ -1,4 +1,4 @@
1
- import { type EntitySql, type EntityWhere, type EntityWhereMeta, QueryRaw, type QueryRawFn, type ComputedRefs, type RefMap, type TriggerRowName, type Type } from '../type/index.js';
1
+ import { type EntitySql, type EntityWhere, type EntityWhereMeta, QueryRaw, type QueryRawFn, type ComputedRefs, type RefMap, type SqlValueName, type TriggerRowName, type Type } from '../type/index.js';
2
2
  /**
3
3
  * Raw SQL, where an interpolated value binds, a `refs` field renders its column, and a `raw` renders
4
4
  * in place: `raw`GREATEST(0, ${user.credits} - ${amount})``. A callback writes whatever it writes, so
@@ -12,10 +12,20 @@ export declare function raw(value: QueryRawFn): QueryRaw;
12
12
  */
13
13
  export declare function constantSql(value: QueryRaw): string | undefined;
14
14
  /**
15
- * The database's current time in UTC to the millisecond, in each engine's SQL, so uql reads the timestamp
16
- * back exactly. Use it for a stamp, an `onUpdate`, a `$where` or a `defaultValue`.
15
+ * The database's clock in UTC to the millisecond, the form uql reads a timestamp back in exactly. Use it for
16
+ * a `defaultValue`, a stamp, an `onUpdate` or a `$where`, in entities and migrations alike.
17
17
  */
18
18
  export declare const currentTimestamp: QueryRaw;
19
+ /** Today on the database's clock; on SQLite, the text a bound `Date` at midnight is. */
20
+ export declare const currentDate: QueryRaw;
21
+ /** The time of day on the database's clock. */
22
+ export declare const currentTime: QueryRaw;
23
+ /** A UUID the database generates: a version 4, or a version 1 on MySQL and MariaDB. SQLite has none. */
24
+ export declare const uuid: QueryRaw;
25
+ /** A time-ordered version 7 UUID, which indexes better as a key. Postgres 18+ and MariaDB 11.7+ only. */
26
+ export declare const uuidv7: QueryRaw;
27
+ /** Each value above by its name, the name a migration or `generate:from-db` writes it under. */
28
+ export declare const SQL_VALUES: Readonly<Record<SqlValueName, QueryRaw>>;
19
29
  /**
20
30
  * The fields of `entity` as {@link ColumnRef}s, each rendering inside `raw` as its column: named the way
21
31
  * the dialect names it, so the naming strategy and `@Field({ name })` apply, and qualified by the alias
package/dist/util/raw.js CHANGED
@@ -30,11 +30,37 @@ export function raw(value, ...rest) {
30
30
  export function constantSql(value) {
31
31
  return value[RAW_TEXT];
32
32
  }
33
+ /** A value the database computes, in each engine's SQL; one an engine has no function for throws. */
34
+ function sqlValue(name) {
35
+ return raw(({ dialect }) => {
36
+ const sql = dialect.sqlValues[name];
37
+ if (sql === undefined) {
38
+ throw new UqlUsageError(`${dialect.dialectName} has no ${name}; write it as raw SQL this engine accepts`);
39
+ }
40
+ return sql;
41
+ });
42
+ }
33
43
  /**
34
- * The database's current time in UTC to the millisecond, in each engine's SQL, so uql reads the timestamp
35
- * back exactly. Use it for a stamp, an `onUpdate`, a `$where` or a `defaultValue`.
44
+ * The database's clock in UTC to the millisecond, the form uql reads a timestamp back in exactly. Use it for
45
+ * a `defaultValue`, a stamp, an `onUpdate` or a `$where`, in entities and migrations alike.
36
46
  */
37
- export const currentTimestamp = raw(({ dialect }) => dialect.currentTimestamp);
47
+ export const currentTimestamp = sqlValue('currentTimestamp');
48
+ /** Today on the database's clock; on SQLite, the text a bound `Date` at midnight is. */
49
+ export const currentDate = sqlValue('currentDate');
50
+ /** The time of day on the database's clock. */
51
+ export const currentTime = sqlValue('currentTime');
52
+ /** A UUID the database generates: a version 4, or a version 1 on MySQL and MariaDB. SQLite has none. */
53
+ export const uuid = sqlValue('uuid');
54
+ /** A time-ordered version 7 UUID, which indexes better as a key. Postgres 18+ and MariaDB 11.7+ only. */
55
+ export const uuidv7 = sqlValue('uuidv7');
56
+ /** Each value above by its name, the name a migration or `generate:from-db` writes it under. */
57
+ export const SQL_VALUES = {
58
+ currentTimestamp,
59
+ currentDate,
60
+ currentTime,
61
+ uuid,
62
+ uuidv7,
63
+ };
38
64
  /**
39
65
  * The fields of `entity` as {@link ColumnRef}s, each rendering inside `raw` as its column: named the way
40
66
  * the dialect names it, so the naming strategy and `@Field({ name })` apply, and qualified by the alias
@@ -1,10 +1,15 @@
1
- import { type EntityPredicate, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type WritableKey, type WriteRow } from '../type/index.js';
1
+ import { type EntityPredicate, type QueryConflictPaths, type QueryRaw, type TriggerWrite, type Type, type UpdatePayload, type UpsertOptions, type WritableKey, type WriteRow } from '../type/index.js';
2
2
  /**
3
3
  * A row inserted by a trigger's body, into any table: `insertInto(PostAudit, { postId: newRow.id })`.
4
4
  * Each value is a literal or SQL, a row's ref most often, and every engine renders it, SQL Server's
5
5
  * set-based trigger included, where it inserts one row for each the statement touched.
6
6
  */
7
7
  export declare function insertInto<E extends object>(entity: Type<E>, row: WriteRow<E>): QueryRaw;
8
+ /**
9
+ * A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
10
+ * does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { update: { count: { $inc: 1 } } })`.
11
+ */
12
+ export declare function upsertInto<E extends object>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: WriteRow<E>, { update }?: UpsertOptions<E, UpdatePayload<E, QueryRaw, WritableKey<E>, never>>): QueryRaw;
8
13
  /** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
9
14
  export declare function updateTable<E extends object>(entity: Type<E>, q: {
10
15
  readonly $where: EntityPredicate<E>;
@@ -13,5 +18,10 @@ export declare function updateTable<E extends object>(entity: Type<E>, q: {
13
18
  export declare function deleteFrom<E extends object>(entity: Type<E>, q: {
14
19
  readonly $where: EntityPredicate<E>;
15
20
  }): QueryRaw;
21
+ /**
22
+ * Fails the write that fired the trigger, with `message` as the error: a table kept append-only refuses its
23
+ * updates and deletes, and a `where` narrows it to the rows a rule forbids.
24
+ */
25
+ export declare function refuse(message: string): QueryRaw;
16
26
  /** A write in a trigger's body, as every helper here and a stamp render one. */
17
27
  export declare function written(write: TriggerWrite): QueryRaw;
@@ -7,6 +7,13 @@ import { TriggerWriteRaw, } from '../type/index.js';
7
7
  export function insertInto(entity, row) {
8
8
  return written({ kind: 'insert', entity, row });
9
9
  }
10
+ /**
11
+ * A row inserted by a trigger's body, or what its conflict paths find taking `update` instead, as `upsertOne`
12
+ * does: `upsertInto(Tally, { postId: true }, { postId: newRow.id, count: 1 }, { update: { count: { $inc: 1 } } })`.
13
+ */
14
+ export function upsertInto(entity, conflictPaths, row, { update } = {}) {
15
+ return written({ kind: 'upsert', entity, conflictPaths, row, update });
16
+ }
10
17
  /** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
11
18
  export function updateTable(entity, q, set) {
12
19
  return written({ kind: 'update', entity, set, where: q.$where });
@@ -15,6 +22,13 @@ export function updateTable(entity, q, set) {
15
22
  export function deleteFrom(entity, q) {
16
23
  return written({ kind: 'delete', entity, where: q.$where });
17
24
  }
25
+ /**
26
+ * Fails the write that fired the trigger, with `message` as the error: a table kept append-only refuses its
27
+ * updates and deletes, and a `where` narrows it to the rows a rule forbids.
28
+ */
29
+ export function refuse(message) {
30
+ return written({ kind: 'refuse', message });
31
+ }
18
32
  /** A write in a trigger's body, as every helper here and a stamp render one. */
19
33
  export function written(write) {
20
34
  return new TriggerWriteRaw(({ ctx, dialect, rows }) => dialect.triggerWrite(ctx, write, rows));