uql-orm 0.108.0 → 0.109.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 (36) hide show
  1. package/README.md +2 -1
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +5 -5
  4. package/dist/dialect/abstractSqlDialect.d.ts +9 -14
  5. package/dist/dialect/abstractSqlDialect.js +17 -23
  6. package/dist/dialect/mergeSqlDialect.d.ts +2 -2
  7. package/dist/dialect/mergeSqlDialect.js +2 -2
  8. package/dist/dialect/mysqlLikeSqlDialect.d.ts +2 -2
  9. package/dist/dialect/mysqlLikeSqlDialect.js +2 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/mongodb/mongodbQuerier.d.ts +1 -1
  13. package/dist/mongodb/mongodbQuerier.js +8 -8
  14. package/dist/mssql/mssqlDialect.d.ts +2 -2
  15. package/dist/mssql/mssqlDialect.js +2 -2
  16. package/dist/querier/abstractQuerier.d.ts +32 -15
  17. package/dist/querier/abstractQuerier.js +48 -30
  18. package/dist/querier/abstractSqlQuerier.d.ts +1 -1
  19. package/dist/querier/abstractSqlQuerier.js +12 -12
  20. package/dist/type/dialect.d.ts +2 -3
  21. package/dist/type/querier.d.ts +28 -15
  22. package/dist/type/query.d.ts +18 -13
  23. package/dist/type/querySql.d.ts +4 -2
  24. package/dist/type/querySql.js +6 -2
  25. package/dist/type/universalQuerier.d.ts +12 -12
  26. package/dist/util/dialect.util.d.ts +3 -3
  27. package/dist/util/dialect.util.js +4 -3
  28. package/dist/util/index.d.ts +1 -1
  29. package/dist/util/object.util.d.ts +2 -0
  30. package/dist/util/object.util.js +4 -0
  31. package/dist/util/sql.d.ts +12 -4
  32. package/dist/util/sql.js +71 -23
  33. package/dist/util/triggerWrite.d.ts +10 -5
  34. package/dist/util/triggerWrite.js +5 -5
  35. package/package.json +1 -1
  36. package/skills/uql-orm/SKILL.md +24 -18
@@ -44,11 +44,15 @@ export function renderSql(statement, opts) {
44
44
  */
45
45
  export class ColumnRef extends QuerySql {
46
46
  [REF_KEY];
47
- [REF_ENTITY];
47
+ #entity;
48
+ /** `entity` is read when the ref is, so an entity declared after the ref resolves. */
48
49
  constructor(key, value, entity) {
49
50
  super(value);
50
51
  this[REF_KEY] = key;
51
- this[REF_ENTITY] = entity;
52
+ this.#entity = entity;
53
+ }
54
+ get [REF_ENTITY]() {
55
+ return this.#entity?.();
52
56
  }
53
57
  }
54
58
  /**
@@ -84,33 +84,33 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
84
84
  */
85
85
  findManyStream: EntityRead<'many', 'stream', 'server', QueryOptions>;
86
86
  /** Insert a record and resolve to its id, or the row `returning` reads back. See {@link UniversalQuerier.insertMany}. */
87
- insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
87
+ insertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted']>;
88
88
  /**
89
89
  * Insert records in as few statements as the bind limit allows, resolving to their ids in payload order, or
90
90
  * the rows `returning` reads back. Ids are exact everywhere but MySQL, which infers them from its header and
91
91
  * reports `undefined` rather than a guess for a generated key that is not `AUTO_INCREMENT`.
92
92
  */
93
- insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted'][]>;
93
+ insertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted'][]>;
94
94
  /** Update the record with the given primary key; resolves to the number of affected rows, or the row `returning` reads back. */
95
- updateOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affected']>;
95
+ updateOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, id: EntityId<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['affected']>;
96
96
  /** Update the records matching the query; resolves to the number of affected rows, or the rows `returning` reads back. */
97
- updateMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affectedMany']>;
97
+ updateMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QuerySearch<E>, payload: UpdateWrite<E>, opts?: QueryOptions & WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['affectedMany']>;
98
98
  /** Delete, or soft-delete, the record with the given key; resolves to the number of affected rows, or the row as it was. */
99
- deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affected']>;
99
+ deleteOneById<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, id: EntityId<E>, opts?: QueryOptions & WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['affected']>;
100
100
  /** Delete, or soft-delete, the records matching the query; resolves to the number of affected rows, or the rows as they were. */
101
- deleteMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['affectedMany']>;
101
+ deleteMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QuerySearch<E>, opts?: QueryOptions & WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['affectedMany']>;
102
102
  /**
103
103
  * Insert or update a record by `q.$conflict`'s keys; resolves to its id, or the row `returning` reads back. A
104
- * conflicting row matching `q.$where` takes the payload less those keys, or `update` as `updateMany` takes one:
105
- * `{ uses: { $inc: 1 } }` counts, and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
104
+ * conflicting row matching `q.$where` takes the payload less those keys, or `q.$update` as `updateMany` takes an
105
+ * update: `{ uses: { $inc: 1 } }` counts, and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
106
106
  */
107
- upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QueryUpsert<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
107
+ upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QueryUpsert<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted']>;
108
108
  /** Insert or update records by `q.$conflict`'s keys, as `upsertOne` does; resolves to their ids in payload order, or the rows. */
109
- upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, q: QueryUpsert<E>, payload: readonly EntityWrite<E>[], update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted'][]>;
109
+ upsertMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, q: QueryUpsert<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted'][]>;
110
110
  /** Insert a record, or upsert one naming its key; resolves to its id, or the row `returning` reads back. */
111
- saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
111
+ saveOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: EntityWrite<E>, opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted']>;
112
112
  /** Insert records, or upsert those naming their key; resolves to their ids in payload order, or the rows. */
113
- saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted'][]>;
113
+ saveMany<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true, const W extends boolean = false>(entity: Type<E>, payload: readonly EntityWrite<E>[], opts?: WriteOptions<E, S, V, W>): Promise<WriteResults<E, S, V, W>['inserted'][]>;
114
114
  /**
115
115
  * Restore soft-deleted records (sets the soft-delete field back to `null`). Throws if the
116
116
  * entity has no soft-delete field.
@@ -1,5 +1,5 @@
1
1
  import type { IndexType } from '../schema/types.js';
2
- import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
2
+ import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictKeys, type QueryUpsert, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
3
3
  export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
4
4
  /** The keys of `payload` a write persists as columns. */
5
5
  export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
@@ -31,10 +31,10 @@ type Deletion<O> = {
31
31
  */
32
32
  export declare function deletionOf<E, O extends QueryOptions>(meta: EntityMeta<E>, opts: O): Deletion<O>;
33
33
  /**
34
- * What the row an upsert of `row` finds takes: a copy of `update`, none for `{}`, which leaves it as `DO NOTHING`
34
+ * What the row an upsert of `row` finds takes: a copy of `q.$update`, none for `{}`, which leaves it as `DO NOTHING`
35
35
  * does, and by default the payload less its key and what it matched on.
36
36
  */
37
- export declare function foundRowAssigned<E>(meta: EntityMeta<E>, conflictKeys: QueryConflictKeys<E>, row: EntityData<E>, update: UpdatePayload<E> | undefined): UpdatePayload<E> | undefined;
37
+ export declare function foundRowAssigned<E>(meta: EntityMeta<E>, q: QueryUpsert<E>, row: EntityData<E>): UpdatePayload<E> | undefined;
38
38
  /**
39
39
  * Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
40
40
  * has that key too. Elsewhere the key is the found row's, which the upsert reads back.
@@ -78,12 +78,13 @@ export function deletionOf(meta, opts) {
78
78
  return { stamp: { key, field, value: () => softDeleteValue(field) }, opts };
79
79
  }
80
80
  /**
81
- * What the row an upsert of `row` finds takes: a copy of `update`, none for `{}`, which leaves it as `DO NOTHING`
81
+ * What the row an upsert of `row` finds takes: a copy of `q.$update`, none for `{}`, which leaves it as `DO NOTHING`
82
82
  * does, and by default the payload less its key and what it matched on.
83
83
  */
84
- export function foundRowAssigned(meta, conflictKeys, row, update) {
84
+ export function foundRowAssigned(meta, q, row) {
85
+ const update = q.$update;
85
86
  if (update === undefined) {
86
- return omitKeys(row, [...meta.ids, ...getKeys(conflictKeys)]);
87
+ return omitKeys(row, [...meta.ids, ...getKeys(q.$conflict)]);
87
88
  }
88
89
  return hasKeys(update) ? { ...update } : undefined;
89
90
  }
@@ -9,7 +9,7 @@ export * from './indexEntry.util.js';
9
9
  export * from './logger.js';
10
10
  export * from './object.util.js';
11
11
  export * from './sql.js';
12
- export { deleteFrom, insertInto, refuse, updateTable, upsertInto } from './triggerWrite.js';
12
+ export { deleteFrom, insertInto, refuse, type TriggerUpsert, updateTable, upsertInto } from './triggerWrite.js';
13
13
  export * from './rowKey.util.js';
14
14
  export * from './relationQuery.util.js';
15
15
  export * from './sql.util.js';
@@ -7,6 +7,8 @@ export declare function clone<T>(value: T): T;
7
7
  /** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */
8
8
  export declare function chunk<T>(items: readonly T[], size: number): T[][];
9
9
  /** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */
10
+ /** Whether `value` is a class, which an arrow, with no `prototype`, is not. */
11
+ export declare function isClass(value: unknown): boolean;
10
12
  export declare function hasKeys<T>(obj: T): obj is NonNullable<T>;
11
13
  /**
12
14
  * Whether any enumerable key of `obj` satisfies `pred`, short-circuiting on the first match
@@ -27,6 +27,10 @@ export function chunk(items, size) {
27
27
  return chunks;
28
28
  }
29
29
  /** Whether `obj` has at least one enumerable key. Narrows away `undefined`/`null` for callers. */
30
+ /** Whether `value` is a class, which an arrow, with no `prototype`, is not. */
31
+ export function isClass(value) {
32
+ return typeof value === 'function' && value.prototype !== undefined;
33
+ }
30
34
  export function hasKeys(obj) {
31
35
  if (typeof obj !== 'object' || obj === null)
32
36
  return false;
@@ -7,6 +7,7 @@ import { ColumnRef, type IndexRefMap, QuerySql, type QuerySqlFn, type ComputedRe
7
7
  export declare function sql(strings: TemplateStringsArray, ...values: readonly SqlArg[]): QuerySql;
8
8
  export declare namespace sql {
9
9
  var join: (parts: readonly QuerySql[], separator?: string) => QuerySql;
10
+ var id: (name: string) => QuerySql;
10
11
  var text: (statement: string) => QuerySql;
11
12
  }
12
13
  export declare function sql(value: QuerySqlFn): QuerySql;
@@ -32,17 +33,25 @@ export declare const uuid: QuerySql;
32
33
  export declare const uuidv7: QuerySql;
33
34
  /** Each value above by its name, the name a migration or `generate:from-db` writes it under. */
34
35
  export declare const SQL_VALUES: Readonly<Record<SqlValueName, QuerySql>>;
36
+ /** An entity, or an arrow returning one, for an entity declared after the code reading it: `() => Order`. */
37
+ export type EntitySource<E> = AbstractType<E> | (() => AbstractType<E>);
35
38
  /**
36
39
  * The fields of `entity` as {@link ColumnRef}s, each rendering inside `sql` as its column: named the way
37
40
  * the dialect names it, so the naming strategy and `.name()` apply, and qualified by `alias`, or else by the
38
- * alias in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
41
+ * alias in scope. The entity and its metadata are read when a ref renders, so `refs(() => Order)` serves code
42
+ * running before `Order` is declared, a computed field's SQL included.
39
43
  */
40
- export declare function refs<E>(entity: AbstractType<E>, alias?: string): RefMap<E>;
44
+ export declare function refs<E>(entity: EntitySource<E>, alias?: string): RefMap<E>;
41
45
  /**
42
46
  * The table `source` names, an entity or the refs read off one under their alias, `"order" "o"`, for raw SQL
43
47
  * reading another table than its statement's: `sql`SELECT ${o.state} FROM ${tableOf(o)}``, `o = refs(Order, 'o')`.
44
48
  */
45
49
  export declare function tableOf<E>(source: AbstractType<E> | RefMap<E>): QuerySql;
50
+ /**
51
+ * The name `source`'s columns are qualified by, `"o"`, for raw SQL reading the whole row (`pdb.score(${aliasOf(o)})`)
52
+ * or naming a derived table after it (`) ${aliasOf(o)} ON TRUE`): its alias, else the alias in scope, else its table.
53
+ */
54
+ export declare function aliasOf<E>(source: AbstractType<E> | RefMap<E>): QuerySql;
46
55
  /**
47
56
  * The refs a definition's callbacks read: a check's, a computed field's, a predicate's. A member decorator
48
57
  * sees no class, so these name no entity and resolve against the one rendering them.
@@ -72,8 +81,7 @@ type Qualifier = {
72
81
  * One field as SQL, against its own entity or, read off a definition, the entity rendering it, read off the
73
82
  * alias in scope unless a `qualifier` names another.
74
83
  */
75
- export declare function columnRef(entity: AbstractType<unknown> | undefined, key: string, qualifier?: Qualifier): ColumnRef;
76
- /** The entity a ref of `key` reads its column of: its own, or, read off a definition, the entity in scope. */
84
+ export declare function columnRef(entity: EntitySource<unknown> | undefined, key: string, qualifier?: Qualifier): ColumnRef;
77
85
  export declare function refOwner(entity: AbstractType<unknown> | undefined, key: string, scope: {
78
86
  readonly entity?: AbstractType<unknown>;
79
87
  }): AbstractType<unknown>;
package/dist/util/sql.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getMeta } from '../entity/metadata/definition.js';
2
2
  import { ColumnRef, JSON_PATH, JsonPathRef, QuerySql, REF_KEY, renderSql, SQL_TEXT, RelationAggregate, TriggerWriteSql, } from '../type/index.js';
3
3
  import { aggregateOf, isInlinedExpression } from './field.util.js';
4
- import { entityName, hasKeys } from './object.util.js';
4
+ import { entityName, hasKeys, isClass } from './object.util.js';
5
5
  import { UqlUsageError } from './uqlError.js';
6
6
  export function sql(source, ...values) {
7
7
  if (!isTemplateStrings(source)) {
@@ -40,6 +40,13 @@ sql.join = function join(parts, separator = ', ') {
40
40
  });
41
41
  });
42
42
  };
43
+ /**
44
+ * A name the statement makes up, quoted as one identifier the way the dialect quotes one: a function's output, a
45
+ * derived column, read twice from one constant, `AS ${reason} ... GROUP BY ${reason}`. An entity's names come off refs.
46
+ */
47
+ sql.id = function id(name) {
48
+ return new QuerySql(({ dialect }) => dialect.escapeId(name, true));
49
+ };
43
50
  /** SQL held in a string, run as written, binding nothing: for trusted text only, never built from user input. */
44
51
  sql.text = function text(statement) {
45
52
  return new QuerySql(() => statement, { text: statement });
@@ -86,43 +93,78 @@ export const SQL_VALUES = {
86
93
  uuid,
87
94
  uuidv7,
88
95
  };
96
+ function isThunk(source) {
97
+ return !isClass(source);
98
+ }
99
+ /** `source` as what reads its entity when called. */
100
+ function resolverOf(source) {
101
+ return isThunk(source) ? source : () => source;
102
+ }
89
103
  /**
90
104
  * The fields of `entity` as {@link ColumnRef}s, each rendering inside `sql` as its column: named the way
91
105
  * the dialect names it, so the naming strategy and `.name()` apply, and qualified by `alias`, or else by the
92
- * alias in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
106
+ * alias in scope. The entity and its metadata are read when a ref renders, so `refs(() => Order)` serves code
107
+ * running before `Order` is declared, a computed field's SQL included.
93
108
  */
94
109
  export function refs(entity, alias) {
95
110
  const qualifier = alias === undefined ? undefined : { alias };
96
- return refMap((key) => columnRef(entity, key, qualifier), () => tableSql(entity, alias));
111
+ const resolve = resolverOf(entity);
112
+ return refMap((key) => columnRef(resolve, key, qualifier), {
113
+ table: () => tableSql(resolve, alias),
114
+ alias: () => aliasSql(resolve, alias),
115
+ });
97
116
  }
98
117
  /**
99
118
  * The table `source` names, an entity or the refs read off one under their alias, `"order" "o"`, for raw SQL
100
119
  * reading another table than its statement's: `sql`SELECT ${o.state} FROM ${tableOf(o)}``, `o = refs(Order, 'o')`.
101
120
  */
102
121
  export function tableOf(source) {
103
- if (typeof source === 'function') {
104
- return tableSql(source);
105
- }
106
- const table = Reflect.get(source, TABLE);
107
- if (!(table instanceof QuerySql)) {
108
- throw new UqlUsageError(`tableOf takes an entity or the refs() read off one, not a definition's refs`);
122
+ return ownSql(source, TABLE, 'tableOf');
123
+ }
124
+ /**
125
+ * The name `source`'s columns are qualified by, `"o"`, for raw SQL reading the whole row (`pdb.score(${aliasOf(o)})`)
126
+ * or naming a derived table after it (`) ${aliasOf(o)} ON TRUE`): its alias, else the alias in scope, else its table.
127
+ */
128
+ export function aliasOf(source) {
129
+ return ownSql(source, ALIAS, 'aliasOf');
130
+ }
131
+ /** What `source`'s refs keep under `key`, an entity's read as its unaliased refs; a definition's refs keep none. */
132
+ function ownSql(source, key, caller) {
133
+ const own = Reflect.get(typeof source === 'function' ? refs(source) : source, key);
134
+ if (!(own instanceof QuerySql)) {
135
+ throw new UqlUsageError(`${caller} takes an entity or the refs() read off one, not a definition's refs`);
109
136
  }
110
- return table;
137
+ return own;
111
138
  }
112
- /** `entity`'s table as its statements name it, under `alias` where one is given. */
113
- function tableSql(entity, alias) {
139
+ /** The table of the entity `resolve` reads, as its statements name it, under `alias` where one is given. */
140
+ function tableSql(resolve, alias) {
114
141
  return sql(({ ctx, dialect }) => {
115
- ctx.append(dialect.tableRef(getMeta(entity), alias).ref);
142
+ ctx.append(dialect.tableRef(getMeta(resolve()), alias).ref);
143
+ });
144
+ }
145
+ /** The name the columns of the entity `resolve` reads are qualified by: `alias`, else the alias in scope where it is that entity's, else its table. */
146
+ function aliasSql(resolve, alias) {
147
+ if (alias !== undefined) {
148
+ return sql.id(alias);
149
+ }
150
+ return sql((opts) => {
151
+ const owner = resolve();
152
+ assertRendersIn(owner, opts);
153
+ return opts.dialect.escapeId(opts.prefix || opts.dialect.tableRef(getMeta(owner)).alias, true);
116
154
  });
117
155
  }
118
- /** Where a refs map keeps the table it reads, for {@link tableOf}: a symbol, so no field can shadow it. */
156
+ /** Where a refs map keeps its table and its alias, for {@link tableOf} and {@link aliasOf}: symbols, so no field can shadow them. */
119
157
  const TABLE = Symbol('table');
158
+ const ALIAS = Symbol('alias');
120
159
  /**
121
160
  * A map answering each string key with `ref(key)`, typed as the caller's map, whose keys say what it holds, and
122
- * {@link TABLE} with what renders the table where it reads one. No other symbol, so nothing probing it sees more.
161
+ * {@link TABLE} and {@link ALIAS} with what renders its table and its alias where it reads one. No other symbol, so
162
+ * nothing probing it sees more.
123
163
  */
124
- function refMap(ref, table) {
125
- return new Proxy({}, { get: (_, key) => (key === TABLE ? table?.() : typeof key === 'string' ? ref(key) : undefined) });
164
+ function refMap(ref, own) {
165
+ return new Proxy({}, {
166
+ get: (_, key) => key === TABLE ? own?.table() : key === ALIAS ? own?.alias() : typeof key === 'string' ? ref(key) : undefined,
167
+ });
126
168
  }
127
169
  /**
128
170
  * The refs a definition's callbacks read: a check's, a computed field's, a predicate's. A member decorator
@@ -196,17 +238,23 @@ export function rowRefs(entity, row) {
196
238
  * alias in scope unless a `qualifier` names another.
197
239
  */
198
240
  export function columnRef(entity, key, qualifier) {
241
+ const resolve = entity && resolverOf(entity);
199
242
  return new ColumnRef(key, (opts) => {
200
- const owner = refOwner(entity, key, opts);
201
- const scope = opts.entity;
202
- if (!qualifier && scope && scope !== owner && !(scope.prototype instanceof owner)) {
203
- throw new UqlUsageError(`a ref of '${owner.name}' cannot render against '${scope.name}', the table in scope: ` +
204
- `read it off its own alias, refs(${owner.name}, 'alias')`);
243
+ const owner = refOwner(resolve?.(), key, opts);
244
+ if (!qualifier) {
245
+ assertRendersIn(owner, opts);
205
246
  }
206
247
  renderColumn(getMeta(owner), key, { ...opts, entity: owner }, qualifier);
207
- }, entity);
248
+ }, resolve);
208
249
  }
209
250
  /** The entity a ref of `key` reads its column of: its own, or, read off a definition, the entity in scope. */
251
+ /** Refuses a ref of `owner` read off the alias in scope where that alias is another entity's. */
252
+ function assertRendersIn(owner, { entity: scope }) {
253
+ if (scope && scope !== owner && !(scope.prototype instanceof owner)) {
254
+ throw new UqlUsageError(`a ref of '${owner.name}' cannot render against '${scope.name}', the table in scope: ` +
255
+ `read it off its own alias, refs(${owner.name}, 'alias')`);
256
+ }
257
+ }
210
258
  export function refOwner(entity, key, scope) {
211
259
  const owner = entity ?? scope.entity;
212
260
  if (!owner) {
@@ -6,13 +6,18 @@ import { type EntityPredicate, type QueryUpsert, type QuerySql, type TriggerWrit
6
6
  */
7
7
  export declare function insertInto<E extends object>(entity: AbstractType<E>, row: WriteRow<E>): QuerySql;
8
8
  /**
9
- * A row inserted by a trigger's body, or what `q.$conflict` finds taking `update` instead where it matches
10
- * `q.$where`, as `upsertOne` does: `upsertInto(Tally, { $conflict: { postId: true } }, { postId: newRow.id, count: 1 },
11
- * { count: { $inc: 1 } })`.
9
+ * An upsert's query as a trigger's body writes it: its `$update` sets columns only, no relation, and its `$where`
10
+ * reads the found row's own columns, with no relation to filter by.
12
11
  */
13
- export declare function upsertInto<E extends object>(entity: AbstractType<E>, q: QueryUpsert<E> & {
12
+ export type TriggerUpsert<E> = QueryUpsert<E, QuerySql, UpdatePayload<E, QuerySql, WritableKey<E>, never>> & {
14
13
  readonly $where?: EntityPredicate<E>;
15
- }, row: WriteRow<E>, update?: UpdatePayload<E, QuerySql, WritableKey<E>, never>): QuerySql;
14
+ };
15
+ /**
16
+ * A row inserted by a trigger's body, or what `q.$conflict` finds taking `q.$update` instead where it matches
17
+ * `q.$where`, as `upsertOne` does: `upsertInto(Tally, { $conflict: { postId: true }, $update: { count: { $inc: 1 } } },
18
+ * { postId: newRow.id, count: 1 })`.
19
+ */
20
+ export declare function upsertInto<E extends object>(entity: AbstractType<E>, q: TriggerUpsert<E>, row: WriteRow<E>): QuerySql;
16
21
  /** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
17
22
  export declare function updateTable<E extends object>(entity: AbstractType<E>, q: {
18
23
  readonly $where: EntityPredicate<E>;
@@ -8,12 +8,12 @@ export function insertInto(entity, row) {
8
8
  return written({ kind: 'insert', entity, row });
9
9
  }
10
10
  /**
11
- * A row inserted by a trigger's body, or what `q.$conflict` finds taking `update` instead where it matches
12
- * `q.$where`, as `upsertOne` does: `upsertInto(Tally, { $conflict: { postId: true } }, { postId: newRow.id, count: 1 },
13
- * { count: { $inc: 1 } })`.
11
+ * A row inserted by a trigger's body, or what `q.$conflict` finds taking `q.$update` instead where it matches
12
+ * `q.$where`, as `upsertOne` does: `upsertInto(Tally, { $conflict: { postId: true }, $update: { count: { $inc: 1 } } },
13
+ * { postId: newRow.id, count: 1 })`.
14
14
  */
15
- export function upsertInto(entity, q, row, update) {
16
- return written({ kind: 'upsert', entity, q, row, update });
15
+ export function upsertInto(entity, q, row) {
16
+ return written({ kind: 'upsert', entity, q, row });
17
17
  }
18
18
  /** The rows `q.$where` names updated by a trigger's body: `updateTable(Post, { $where: { id: newRow.postId } }, set)`. */
19
19
  export function updateTable(entity, q, set) {
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, 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.108.0",
6
+ "version": "0.109.0",
7
7
  "type": "module",
8
8
  "engines": {
9
9
  "node": ">=22.18"
@@ -3,9 +3,10 @@ name: uql-orm
3
3
  description: >
4
4
  Write code with UQL (the uql-orm package), the TypeScript ORM whose queries are plain JSON objects,
5
5
  on PostgreSQL, MySQL, MariaDB, SQLite, CockroachDB, SQL Server, MongoDB, Turso, Neon, D1 and PGlite.
6
- Use when a project imports uql-orm, or when defining entities, triggers or filters (soft delete, multi-tenancy),
7
- querying, populating relations, writing transactions, raw SQL or migrations with it. UQL is not Prisma, Drizzle, TypeORM or MikroORM:
8
- their APIs do not carry over.
6
+ Use when a project imports uql-orm, or when defining entities (@Entity, defineEntity), triggers or filters
7
+ (soft delete, multi-tenancy), querying ($where, $populate, findMany, aggregate), writing (insertMany, upsertOne,
8
+ updateMany, returning), transactions, raw SQL (sql, refs) or migrations (uql-migrate) with it. UQL is not Prisma,
9
+ Drizzle, TypeORM or MikroORM: their APIs do not carry over.
9
10
  ---
10
11
 
11
12
  # UQL
@@ -44,7 +45,7 @@ The pool's first argument is the driver's own config; set an acquire timeout the
44
45
  Two forms, mixable per entity, producing the same queries and types:
45
46
 
46
47
  - **Decorators**: a named class type, and column-level foreign keys (`f.references`), so entities may reference each other in any order. Slightly stricter: a property may be typed narrower than its column (a branded id), and `mappedBy` must name a relation or foreign key at compile time. Each field is written twice (builder and property), and it needs the TC39 decorator transform.
47
- - **`defineEntity`**: the row type is derived, nothing written twice; no transform, so it fits projects on legacy decorators (NestJS, Angular), and it can be built at run time. Cheaper to type-check. Relations come last, and the row type needs a `type X = InstanceType<typeof X>` alias. A shared set of fields spreads into `fields`.
48
+ - **`defineEntity`**: the row type is derived, nothing written twice; no transform, so it fits projects on legacy decorators (NestJS, Angular), and it can be built at run time. Cheaper to type-check. A shared set of fields spreads into `fields`.
48
49
 
49
50
  `uql-codemod` cannot convert one form into the other. Details: https://uql-orm.dev/entities/define-entity.md
50
51
 
@@ -86,10 +87,10 @@ export class Post {
86
87
  }
87
88
  ```
88
89
 
89
- - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal(precision?, scale?)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other type, and `f.references(() => Target)` for a foreign key typed as the target's key. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's.
90
+ - A column is a builder: `f.string()`, `f.text()`, `f.uuid()`, `f.number()`, `f.bigint()`, `f.decimal(precision?, scale?)`, `f.boolean()`, `f.date()`, `f.json(schema?)`, `f.jsonb(schema?)`, `f.vector(dimensions)`, `f.enum(values)`, `f.version()`, `f.column(type)` for any other SQL type uql names (`f.column('smallint')`, `f.column('date')` for a day with no time, `f.column('timestamptz')`), typed by its family, and `f.references(() => Target)` for a foreign key typed as the target's key. A type uql does not name is ``.columnType(sql`citext`)``. Only the methods a column's type takes exist: `.length()` is a string's, `.precision()` a number's or a date's. A builder is immutable, so `const money = f.decimal(12, 2)` is shared across fields, each chaining its own `.nullable()`.
90
91
  - A column is NOT NULL unless `.nullable()`. Declare a NOT NULL property `!` (`email!: string`), and `?` what an insert may omit: nullable columns (`title?: string | null`), `.eager(false)` and computed fields, relations, and the single-column key and version uql fills. A NOT NULL field a default fills (`.default()`, `.onInsert()`) stays `!` and is listed in the class's `[filledKey]?: 'stock' | 'createdAt'`: inserts may omit it, reads always have it.
91
92
  - `.default()` takes a value of the field's type, or SQL the database evaluates per row: `currentTimestamp`, `currentDate`, `currentTime`, `uuid` (not SQLite), `uuidv7` (Postgres 18+, MariaDB 11.7+), or ``sql`...` ``. A plain string is always text, `'CURRENT_TIMESTAMP'` included. A JSON column defaults to a value, `.default({})` or `.default(0)`, never its JSON text (`'{}'`, `'0'` are refused); any other string there is a JSON string.
92
- - `Date` is an instant, stored in UTC to the millisecond on every engine. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
93
+ - `Date` is an instant, stored in UTC to the millisecond. `f.decimal()` is exact text (`price?: string | null`); `f.number().precision(10).scale(2)` opts into a rounding JS number.
93
94
  - A JSON column's property is `Json<T>`: `settings?: Json<{ theme?: string }> | null`. A plain object type reads as a relation, which `$where`, `$sort` and the update operators refuse.
94
95
  - `mappedBy` and `references` may be left out where only one member fits. `@ManyToMany({ entity: () => Tag, through: () => PostTag })` names the junction entity. `cascade: true` writes related rows with their row, in one transaction on SQL and, on MongoDB, inside one the caller opens; an update replaces a to-many's rows.
95
96
  - A class inherits its base's fields, relations, hooks, filters, indexes, checks and triggers. A base of fields alone needs no `@Entity()`; one declaring entity options but no table is `@Entity({ abstract: true, ... }) abstract class`, which cannot be queried.
@@ -97,7 +98,7 @@ export class Post {
97
98
  - Computed fields are `readonly`: ``@Computed((u) => f.string().as(sql`${u.first} || ' ' || ${u.last}`))``, `.stored()` for a generated column, or a relation aggregate, `@Computed((user) => user.posts.count())`.
98
99
  - Indexes, checks, filters and triggers are `@Entity` options, each entry made by the helper the callback is handed. A partial index's predicate is a query: `indexes: (post, index) => [index([post.authorId], { where: { archived: { $ne: true } } })]`. A JSON path is indexed off the column's ref, `index([user.settings.theme])`: https://uql-orm.dev/entities/indexes.md
99
100
  - Triggers run in the database: `triggers: (post, trigger) => [trigger({ on: 'afterUpdate', of: [post.status], run })]`, where `run` returns a body built from `insertInto`, `upsertInto`, `updateTable`, `deleteFrom` and `refuse(message)`. They skip entity filters and run no JavaScript: an insert fills an `.onInsert()` value or SQL, but an `insertInto` names every required column a callback fills (`.onInsert(() => crypto.randomUUID())`) where no database default does. MongoDB has none: https://uql-orm.dev/entities/triggers.md
100
- - Hooks are methods with `this` bound to the payload: `@BeforeInsert()`, `@AfterInsert()`, and the same pairs for update, upsert and delete, plus `@AfterLoad()`. Changes to `this` in a before-hook are written. `upsert*` runs only the upsert pair, and `save*` the upsert pair for a row carrying its key. Each receives `{ querier, onCommit }`: send mail from `onCommit`, never straight from an after-hook.
101
+ - Hooks are methods with `this` bound to the payload: `@BeforeInsert()`, `@AfterInsert()`, and the same pairs for update, upsert and delete, plus `@AfterLoad()`. Changes to `this` in a before-hook are written. `upsert*` runs only the upsert pair, and `save*` the upsert pair for a row carrying its key. Each receives `{ querier, onCommit }`.
101
102
  - **MongoDB:** a `f.number()` key left to the database is refused, since MongoDB only generates ObjectIds. Declare it a string, or give it an `.onInsert()` generator.
102
103
 
103
104
  ### defineEntity
@@ -141,7 +142,7 @@ export const Book = defineEntity({
141
142
  - `defineEntity` takes `name` (the table derives from it), `table`, `schema`, `extends`, `abstract` and `fields`. Every other option is a section chained after it, each called at most once: `computed`, `indexes`, `checks`, `triggers`, `filters`, `hooks`, then `relations` last; only a `filters` reading through relations follows it.
142
143
  - A relation is a thunk, so entities pointing at each other can sit in any order and file. A foreign key is a plain field that a `manyToOne` names as `references`, checked against the target's key type. `relations`' second callback declares aggregate fields: aggregates over a to-many, or expressions mixing them with columns.
143
144
  - A JSON column's payload is any Standard Schema (Zod, Valibot, ArkType), typed by its output. uql never runs it, so a write is not validated.
144
- - A hook is a function of the row and `{ querier, onCommit }`. Behaviour is a plain function of the row (`label(author: Author)`): a row reads back as a plain object, so a method would never be there.
145
+ - A hook is a function of the row and the same second argument. Behaviour is a plain function of the row (`label(author: Author)`): a row reads back as a plain object, so a method would never be there.
145
146
 
146
147
  ### Filters, soft delete and tenants
147
148
 
@@ -174,7 +175,7 @@ await withContext({ tenantId: 42 }, () => pool.findMany(Invoice, {}));
174
175
 
175
176
  - A filter is on unless `default: false`. A `$where` naming its field wins over it. Per call, the options argument takes `{ filters: false }`, `{ filters: { softDelete: false } }` or `{ filters: { active: true } }`.
176
177
  - `.softDelete()` on one field turns a delete into a stamp (`new Date()`, or the value or callback given), and registers a `softDelete` filter hiding stamped rows. `withDeleted()` as the options reads both; `restoreOneById` and `restoreMany` undo it; `{ hardDelete: true }` removes rows for good. A restore does not cascade.
177
- - A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`. Its keys are typed by augmenting `UqlContext`, as above.
178
+ - A `where` may be a function of the context `withContext(ctx, fn)` sets, which follows `await`, `Promise.all` and transactions but not emitters, timers or queues: wrap those callbacks with `captureContext()`.
178
179
  - `security: true` makes a filter always apply, ignore bypasses, AND-merge with any `$where`, and throw `UqlSecurityError` when `where` returns `undefined`. It scopes writes too, so new rows need no tenant set by hand. For a trusted cross-tenant job, give `where` a branch returning `{}` (`ctx?.system ? {} : ...`) and run it under `withContext({ system: true }, fn)`: https://uql-orm.dev/multi-tenancy.md
179
180
 
180
181
  ## Queries
@@ -193,39 +194,39 @@ const users = await pool.findMany(User, {
193
194
  });
194
195
  ```
195
196
 
196
- - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first, or the query's `$entity`. Signatures: https://uql-orm.dev/querying/methods.md
197
+ - Methods: `findMany`, `findOne`, `findOneById`, `findManyAndCount`, `findManyPage`, `findManyStream`, `count`, `exists`, `aggregate`, `insertOne`, `insertMany`, `updateOneById`, `updateMany`, `saveOne`, `saveMany`, `upsertOne`, `upsertMany`, `deleteOneById`, `deleteMany`. Each takes the entity class first; on a querier, each taking a query also takes it as the query's `$entity`, so the whole call is JSON. Signatures: https://uql-orm.dev/querying/methods.md
197
198
  - Query keys: `$select`, `$where`, `$populate`, `$count`, `$distinct`, `$sort`, `$skip`, `$limit`, `$lock`. `$select: { password: false }` reads every field but `password`. `$count: { posts: true }` counts a to-many under `_count` without loading it.
198
199
  - Results are narrowed to what the query selected and populated, at every depth. Reading an unselected field is a compile error. Name a shape with `QueryFindResult<User, 'id' | 'email'>`, or `QueryFindResult<User, typeof query>` for a query declared `as const satisfies Query<User>`. A function forwarding a query keeps the narrowing typed `<E extends object, const Q extends Query<E>>(entity: Type<E>, q: Captured<Query<E>, Q>): Promise<QueryFindResult<E, Q>[]>`.
199
200
  - `$populate` loads relations in the same statement. Nothing is lazy: an unpopulated relation is absent. A populated to-many is always a list. A to-one is optional unless `$required: true`, which keeps only the parents that have one.
200
- - `$sort` takes `'asc'`/`1`, `'desc'`/`-1`, or `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`, which behave the same on every engine.
201
+ - `$sort` takes `'asc'`/`1`, `'desc'`/`-1`, or `'ascNullsLast'`, `'ascNullsFirst'`, `'descNullsFirst'`, `'descNullsLast'`.
201
202
  - `findManyPage(User, { $sort: { createdAt: -1, id: 1 }, $limit: 20, $after })` pages by cursor, so page 1,000 costs what page 1 does, and returns `{ items, startCursor, endCursor, hasNextPage, hasPrevPage }`. `$sort` must end in the key or a unique NOT NULL field; no `$skip`.
202
203
  - `$lock: true` locks the rows a read returns, inside an open transaction; `{ $wait: 'skip' | 'nowait' }` says what to do about a row someone else holds. The SQLite family and MongoDB refuse it.
203
204
 
204
205
  ### `$where`
205
206
 
206
- - `$where` takes a value for equality, a list as an implicit `$in`, or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$between`, `$in`, `$nin`, `$isNull`, `$isNotNull`, `$not`. Combine with `$and`, `$or`, `$not`, `$nor`. A field takes only the operators its type allows.
207
+ - `$where` takes a value for equality, a list as an implicit `$in`, or an operator map: `$eq`, `$ne`, `$lt`, `$lte`, `$gt`, `$gte`, `$between`, `$in`, `$nin`, `$isNull`, `$isNotNull`. Combine with `$and`, `$or`, `$not`, `$nor`. A field takes only the operators its type allows.
207
208
  - Text: `$like`, `$startsWith`, `$endsWith`, `$includes`, each with a case-insensitive `i` form (`$ilike`, `$istartsWith`, ...). `$like` reads `%`, `_` and `\` the same on every engine; the other three take their text literally. `$regex` is case-sensitive unless the pattern opens with `(?i)`.
208
209
  - Arrays and JSON: `$all: ['a', 'b']`, `$size: 3` or `{ $gte: 2 }`, `$elemMatch: { city: 'NYC', zip: { $startsWith: '10' } }`. A JSON path filters like a field: `{ 'settings.billing.plan': 'pro' }`.
209
210
  - A relation key keeps the parents with a matching related row, as an `EXISTS`, never duplicating them: `{ posts: { title: { $iincludes: 'orm' } } }`, or by count: `{ posts: { $size: { $gte: 5 } } }`. For a subquery no relation covers, `$exists` / `$nexists` take a `sql` fragment.
210
211
  - Full-text: `$where: { $text: { $value: 'wireless keyboard' } }` searches the entity's fulltext index; `$sort: { $text: 'desc' }` ranks by relevance.
211
212
  - Vectors: `$sort: { embedding: { $vector: v } }` with a `$limit` returns the nearest; `$where: { embedding: { $near: { $vector: v, $lt: 0.35 } } }` keeps only close rows; `$candidates` tunes ANN recall.
213
+ - An operator compares a field with another column of the row wherever it takes a value: `const rate = refs(Rate); pool.findMany(Rate, { $where: { effectiveTo: { $gt: rate.effectiveFrom } } })`. A check's refs work the same. A JSON path compared with a ref reads as that column's type. A ref of another entity than the one queried is refused: in raw SQL, read it off its own alias, `refs(Other, 'o')`.
212
214
  - An `undefined` anywhere in `$where` throws. Leave the key out to skip the filter (`...(email && { email })`), or name `null`.
213
215
  - On SQL, `$ne`, `$nin`, `$not` and `$nor` drop NULL rows, where MongoDB keeps them. To keep them, name NULL: `{ $or: [{ col: { $ne: 'a' } }, { col: null }] }`.
214
216
 
215
217
  ### Writes
216
218
 
217
- - Without options, inserts and upserts resolve to ids, updates and deletes to a count. A last argument `{ returning: { id: true } }` resolves to those rows instead.
218
- - `upsertOne(Entity, { $conflict: { email: true }, $where? }, row, update?)`: a conflicting row matching `$where` takes `update` (an update payload), else the payload but keeping its own key; one not matching stays as it is. `upsertInto` in a trigger takes the same query. On MySQL and MariaDB, a `$where` may read only one column the update sets.
219
+ - Without options, inserts and upserts resolve to ids, updates and deletes to a count. A last argument `{ returning: { id: true } }` resolves to those rows instead, `{ returning: true }` to every field a read returns.
220
+ - `upsertOne(Entity, { $conflict: { email: true }, $where?, $update? }, row)`: a conflicting row matching `$where` takes `$update` (an update payload; `{}` keeps it as it is), else the payload but keeping its own key; one not matching stays as it is. SQL in `$update` reads the found row through `refs(Entity)`, no alias: ``{ uses: sql`${query.uses} + 1` }`` with `const query = refs(SearchQuery)`. `upsertInto` in a trigger takes the same query. On MySQL and MariaDB, a `$where` may read only one column the update sets.
219
221
  - `updateMany` and `deleteMany` that name no rows (no `$where` holding a value, no `$limit`) throw. Pass `{ unfiltered: true }` to mean the whole table.
220
222
  - Update operators: `{ stock: { $inc: -1 } }` or `$mul`, with NULL counted as 0. A guard in `$where` (`stock: { $gte: 1 }`) makes a decrement race-safe. JSON fields take `$pull`, `$set`, `$push`, `$addToSet`, then `$unset`, applied in that order; `$set` and `$unset` take dotted paths and create parents: `settings: { $set: { 'billing.plan': 'pro' } }`.
221
223
 
222
224
  ### Raw SQL and errors
223
225
 
224
226
  - ``pool.all`SELECT ... WHERE id = ${id}` `` for a `SELECT`, ``pool.run`...` `` for a write. Interpolated values bind: a scalar, `null` or a list, never `undefined` or a plain object. `sql` builds a fragment, `sql.join(fragments, ' AND ')` joins them, and `sql.text(s)` runs trusted SQL held in a string: never user input.
225
- - An operator compares a field with another column through its ref, wherever it takes a value: `{ effectiveTo: { $gt: rate.effectiveFrom } }` off `refs(Rate)` or a check's refs, `$between`, `$in` and `$ne` alike, on every engine, MongoDB included. A JSON path compared with one reads as that column's type. A ref names a column of the entity in scope: one of another entity is refused, and reads off its own alias, `refs(Other, 'o')`.
226
227
  - A condition no operator expresses is a `sql` fragment beside the others, naming columns through `refs()`, never by string: ``const item = refs(Item); $where: { $and: [{ companyId: 1 }, sql`${item.price} * ${item.stock} > ${10000}`] }``. SQL databases only.
227
- - SQL reading another table names it with `tableOf`, its columns off refs read under an alias, so a rename reaches them: ``const o = refs(Order, 'o'); sql`(SELECT ${o.state} FROM ${tableOf(o)} WHERE ${o.checkoutId} = ${checkout.id} LIMIT 1)` ``. Two aliases read one table twice.
228
- - `queryErrorKind(err)` names a failure the same on every engine: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code.
228
+ - SQL reading another table names it with `tableOf`, its columns off refs read under an alias, so a rename reaches them: ``const o = refs(Order, 'o'); sql`(SELECT ${o.state} FROM ${tableOf(o)} WHERE ${o.checkoutId} = ${checkout.id} LIMIT 1)` ``. Two aliases read one table twice. For an entity declared later, a computed field's SQL included, pass an arrow: `refs(() => Order, 'o')`, `tableOf(refs(() => Order))`. `aliasOf(o)` renders the alias alone, for SQL reading the whole row (`pdb.score(${aliasOf(o)})`) or naming a derived table (`) ${aliasOf(o)} ON TRUE`). A name the statement makes up, read twice, is `sql.id('reason')`.
229
+ - `queryErrorKind(err)` names a failure: `uniqueViolation`, `foreignKeyViolation`, `notNullViolation`, `checkViolation`, `optimisticLock`, `retryable`, `usage`, `security`. Catch by kind, not by driver code.
229
230
 
230
231
  ## Aggregates
231
232
 
@@ -260,7 +261,7 @@ await pool.transaction(async (querier) => {
260
261
  ```
261
262
 
262
263
  - The callback commits when it returns and rolls back when it throws. Inside it, `pool` calls run on its querier. A nested `transaction()` is a savepoint; MongoDB refuses it.
263
- - `querier.onCommit(fn)` runs `fn` after the outermost commit, never on rollback: use it for mail and queued jobs.
264
+ - `querier.onCommit(fn)` runs `fn` after the outermost commit, never on rollback.
264
265
  - A transaction opened in one place and ended in another uses `beginTransaction`, `commitTransaction` and `rollbackTransaction`. A querier from `pool.getQuerier()` is yours to release: bind it with `await using`.
265
266
  - A `findManyStream` holds its querier until the loop ends, refusing other statements meanwhile: run them after the loop, or on another connection.
266
267
 
@@ -276,6 +277,11 @@ await pool.transaction(async (querier) => {
276
277
 
277
278
  Upgrading uql itself: `npx uql-codemod --dry-run`, then `npx uql-codemod`, which rewrites what it can and reports the rest. Breaking changes: https://uql-orm.dev/upgrade-guide.md
278
279
 
280
+ ## Before you finish
281
+
282
+ - Mail, webhooks and queued jobs run from `onCommit`, never from an after-hook or mid-transaction.
283
+ - Several writes that must land together run in one `pool.transaction(...)`; on MongoDB, so does an upsert with an `$update` or `$where`, and an `updateMany` or `deleteMany` that cascades or runs hooks.
284
+
279
285
  ## Where to read more
280
286
 
281
287
  - Operators and per-dialect SQL: https://uql-orm.dev/querying/comparison-operators.md