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
@@ -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,4 +1,4 @@
1
- import type { Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
1
+ import type { Alteration, Change, ForeignKeySchema, IndexSchema, PrimaryKeySchema, StoredDefinition } from '../type/migration.js';
2
2
  import type { IndexFacet } from './indexDifferences.js';
3
3
  /**
4
4
  * Type categories universal across SQL dialects.
@@ -175,10 +175,7 @@ export type NodeChange<T, Altered = unknown> = {
175
175
  } | {
176
176
  readonly from: T;
177
177
  readonly to?: undefined;
178
- } | ({
179
- readonly from: T;
180
- readonly to: T;
181
- } & Altered);
178
+ } | (Alteration<T> & Altered);
182
179
  /** A column to create, drop or alter; an alter lists in `changed` which parts of the column differ. */
183
180
  export type ColumnDiff = NodeChange<ColumnNode, {
184
181
  readonly changed: readonly ColumnFacet[];
@@ -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
@@ -140,14 +140,14 @@ type JsonUpdateOpFor<V, T = UnwrapJson<NonNullable<V>>> = [T] extends [never] ?
140
140
  /**
141
141
  * A scalar field's update operator, as {@link JsonUpdateOp} is a JSON field's, computed in the statement:
142
142
  * `$inc` adds, `$mul` multiplies, a NULL counting as 0 on every engine. One per field, since their order
143
- * would change the result. A `bigint` steps by a `bigint`, exactly.
144
- * @example `{ stock: { $inc: -1 } }`
143
+ * would change the result. A `bigint` steps by a `bigint`, exactly, and the step may be SQL of the field's type.
144
+ * @example `{ stock: { $inc: -1 } }`, `{ total: { $inc: newRow.amount } }`
145
145
  */
146
- export type FieldUpdateOp<T extends number | bigint = number | bigint> = ExactlyOne<Record<'$inc' | '$mul', T>>;
146
+ export type FieldUpdateOp<T = number | bigint | QueryRaw> = ExactlyOne<Record<'$inc' | '$mul', T>>;
147
147
  /** The {@link FieldUpdateOp} a field takes: `never` on one it has no operator for, which is any but a number. */
148
- type FieldUpdateOpFor<V> = [NonNullable<V>] extends [number] ? FieldUpdateOp<number> : [NonNullable<V>] extends [bigint] ? FieldUpdateOp<bigint> : never;
148
+ type FieldUpdateOpFor<V, Raw> = [NonNullable<V>] extends [number] ? FieldUpdateOp<number | RawFor<Raw, number>> : [NonNullable<V>] extends [bigint] ? FieldUpdateOp<bigint | RawFor<Raw, bigint>> : never;
149
149
  /** What an update takes beyond the value: `null` to clear an optional member, `raw` SQL, and update operators. */
150
- type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V>;
150
+ type UpdateExtra<V, Raw> = (undefined extends V ? null : never) | RawFor<Raw, V> | JsonUpdateOpFor<V> | FieldUpdateOpFor<V, Raw>;
151
151
  /**
152
152
  * What a whole-record write persists: the fields and relations with their declared optionality, a
153
153
  * related row as a caller writes one, and no methods. Two mapped types, since asking each key costs a
@@ -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];
@@ -187,10 +187,7 @@ export type ColumnChange = Change<ColumnSchema> & {
187
187
  readonly isBreaking?: boolean;
188
188
  };
189
189
  /** A name changed, `from` the database's `to` the entity's. */
190
- export type Rename = {
191
- readonly from: string;
192
- readonly to: string;
193
- };
190
+ export type Rename = Alteration<string>;
194
191
  /** Renamed columns by qualified table name. */
195
192
  export type ColumnRenames = ReadonlyMap<string, readonly Rename[]>;
196
193
  /**
@@ -202,6 +199,11 @@ export interface Change<T> {
202
199
  readonly from?: T;
203
200
  readonly to?: T;
204
201
  }
202
+ /** A {@link Change} with both sides: the object altered in place. */
203
+ export type Alteration<T> = {
204
+ readonly from: T;
205
+ readonly to: T;
206
+ };
205
207
  /** A primary key, whichever side it is read from: the entities, the database, or a diff between them. */
206
208
  export interface PrimaryKeySchema {
207
209
  /** Its columns **in order**, which is what a composite is: `(a, b)` is not `(b, a)`. */
@@ -233,10 +235,7 @@ export interface SchemaDiff {
233
235
  * The table copied into a new one, which is how an engine that {@link DialectFeatures.rebuildsTables}
234
236
  * applies the changes above. Its column renames are carried by the copy.
235
237
  */
236
- readonly rebuild?: {
237
- readonly from: RebuiltTable;
238
- readonly to: RebuiltTable;
239
- };
238
+ readonly rebuild?: Alteration<RebuiltTable>;
240
239
  }
241
240
  /**
242
241
  * What every sync entry point takes: `safe` keeps it additive, `drop` lets it remove a column, and
@@ -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
@@ -82,7 +82,7 @@ export declare function isFieldUpdateOp(value: unknown): value is FieldUpdateOp;
82
82
  * The one operator a scalar field's update carries, and its operand. Naming both throws rather than
83
83
  * reading one: their order would change the result, and an untyped payload is how both arrive.
84
84
  */
85
- export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint];
85
+ export declare function fieldUpdateOf(key: string, value: FieldUpdateOp): [keyof FieldUpdateOp, number | bigint | QueryRaw];
86
86
  /** Returns a `QueryOptions.filters` value with the built-in soft-delete filter disabled (used by hard delete). */
87
87
  export declare function withoutSoftDeleteFilter(filters: QueryOptions['filters']): QueryOptions['filters'];
88
88
  /**
@@ -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));
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "homepage": "https://uql-orm.dev",
4
4
  "description": "JSON-native TypeScript ORM for Bun, Browsers, Edge, Deno, Node, Workers. Supports PostgreSQL, PGlite, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, Turso, Neon, Cloudflare D1 and MongoDB. Queries are plain JSON, typed to the leaf.",
5
5
  "license": "MIT",
6
- "version": "0.92.0",
6
+ "version": "0.93.1",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=24"
@@ -135,25 +135,25 @@
135
135
  "@electric-sql/pglite": "0.5.8",
136
136
  "@electric-sql/pglite-pgvector": "0.0.9",
137
137
  "@libsql/client": "^0.18.0",
138
- "@neondatabase/serverless": "^1.1.0",
139
- "@nestjs/common": "^12.1.1",
140
- "@nestjs/core": "^12.1.1",
141
- "@nestjs/testing": "^12.1.1",
142
- "@tursodatabase/database": "^0.7.2",
138
+ "@neondatabase/serverless": "^1.2.0",
139
+ "@nestjs/common": "^12.1.2",
140
+ "@nestjs/core": "^12.1.2",
141
+ "@nestjs/testing": "^12.1.2",
142
+ "@tursodatabase/database": "^0.8.1",
143
143
  "@tursodatabase/serverless": "^1.4.0",
144
144
  "@types/better-sqlite3": "^9.6.0",
145
145
  "@types/express": "^5.0.6",
146
146
  "@types/mssql": "^12.3.0",
147
147
  "@types/pg": "^8.23.1",
148
- "@types/ws": "^8.18.1",
148
+ "@types/ws": "^8.18.2",
149
149
  "better-sqlite3": "^13.0.3",
150
150
  "express": "^5.2.1",
151
151
  "mariadb": "^3.5.4",
152
152
  "mongodb": "^7.7.0",
153
153
  "mssql": "^12",
154
- "mysql2": "^3.24.4",
155
- "pg": "^8.23.0",
156
- "pg-query-stream": "^4.17.0",
154
+ "mysql2": "^3.24.5",
155
+ "pg": "^8.23.1",
156
+ "pg-query-stream": "^4.17.1",
157
157
  "rxjs": "^7.8.2",
158
158
  "sqlite-vec": "^0.1.9",
159
159
  "ws": "^8.22.0"