uql-orm 0.107.3 → 0.108.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 (89) hide show
  1. package/dist/browser/uql-browser.min.js +2 -2
  2. package/dist/browser/uql-browser.min.js.map +5 -5
  3. package/dist/cockroachdb/cockroachDialect.d.ts +1 -4
  4. package/dist/cockroachdb/cockroachDialect.js +1 -5
  5. package/dist/dialect/abstractSqlDialect.d.ts +84 -43
  6. package/dist/dialect/abstractSqlDialect.js +270 -192
  7. package/dist/dialect/aliases.d.ts +2 -0
  8. package/dist/dialect/aliases.js +2 -0
  9. package/dist/dialect/jsonSql.d.ts +9 -7
  10. package/dist/dialect/jsonSql.js +16 -10
  11. package/dist/dialect/mergeSqlDialect.d.ts +5 -7
  12. package/dist/dialect/mergeSqlDialect.js +20 -19
  13. package/dist/dialect/mysqlLikeSqlDialect.d.ts +12 -6
  14. package/dist/dialect/mysqlLikeSqlDialect.js +34 -12
  15. package/dist/dialect/operators.d.ts +7 -1
  16. package/dist/dialect/operators.js +37 -2
  17. package/dist/dialect/pgLikeSqlDialect.d.ts +4 -4
  18. package/dist/dialect/pgLikeSqlDialect.js +8 -7
  19. package/dist/entity/index.d.ts +1 -1
  20. package/dist/entity/index.js +1 -1
  21. package/dist/entity/metadata/definedFixture/author.d.ts +4 -4
  22. package/dist/entity/metadata/definedFixture/book.d.ts +5 -5
  23. package/dist/entity/metadata/definition.d.ts +2 -0
  24. package/dist/entity/metadata/definition.js +19 -11
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/mariadb/mariaDialect.d.ts +2 -2
  28. package/dist/mariadb/mariaDialect.js +3 -2
  29. package/dist/migrate/codegen/fieldOptionsSource.js +28 -7
  30. package/dist/migrate/ddl/defaultSql.d.ts +3 -2
  31. package/dist/migrate/ddl/defaultSql.js +8 -12
  32. package/dist/migrate/ddl/mysqlTableDdl.js +1 -1
  33. package/dist/migrate/ddl/tableDdl.d.ts +1 -1
  34. package/dist/migrate/drift/driftDetector.js +10 -3
  35. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.d.ts +2 -2
  36. package/dist/migrate/introspection/mssqlIntrospector.d.ts +2 -2
  37. package/dist/migrate/introspection/mysqlIntrospector.d.ts +2 -2
  38. package/dist/migrate/introspection/postgresIntrospector.d.ts +2 -2
  39. package/dist/migrate/introspection/sqliteIntrospector.d.ts +2 -2
  40. package/dist/migrate/migrator.js +2 -1
  41. package/dist/migrate/schemaChange.d.ts +0 -2
  42. package/dist/migrate/schemaChange.js +1 -4
  43. package/dist/migrate/schemaGenerator.d.ts +2 -2
  44. package/dist/migrate/triggerSql.js +11 -15
  45. package/dist/mongodb/mongoDialect.d.ts +6 -1
  46. package/dist/mongodb/mongoDialect.js +90 -46
  47. package/dist/mongodb/mongoSchemaGenerator.js +2 -2
  48. package/dist/mongodb/mongodbQuerier.d.ts +7 -9
  49. package/dist/mongodb/mongodbQuerier.js +54 -47
  50. package/dist/mssql/mssqlDialect.d.ts +9 -9
  51. package/dist/mssql/mssqlDialect.js +51 -28
  52. package/dist/mssql/mssqlWireTypes.d.ts +1 -4
  53. package/dist/mssql/mssqlWireTypes.js +19 -10
  54. package/dist/querier/abstractQuerier.d.ts +53 -29
  55. package/dist/querier/abstractQuerier.js +154 -102
  56. package/dist/querier/abstractSqlQuerier.d.ts +41 -10
  57. package/dist/querier/abstractSqlQuerier.js +145 -79
  58. package/dist/schema/declaredColumn.js +2 -2
  59. package/dist/schema/schemaASTDiffer.d.ts +3 -3
  60. package/dist/schema/sqlExpression.d.ts +7 -5
  61. package/dist/schema/sqlExpression.js +20 -16
  62. package/dist/schema/types.d.ts +8 -2
  63. package/dist/sqlite/sqliteDialect.js +1 -2
  64. package/dist/type/definedEntity.d.ts +5 -5
  65. package/dist/type/dialect.d.ts +26 -15
  66. package/dist/type/entity.d.ts +14 -8
  67. package/dist/type/query.d.ts +7 -2
  68. package/dist/type/queryAggregate.d.ts +4 -4
  69. package/dist/type/querySql.d.ts +4 -1
  70. package/dist/type/querySql.js +5 -1
  71. package/dist/type/queryWhere.d.ts +16 -11
  72. package/dist/type/universalQuerier.d.ts +7 -7
  73. package/dist/util/ddlExpression.util.d.ts +5 -0
  74. package/dist/util/ddlExpression.util.js +9 -2
  75. package/dist/util/dialect.util.d.ts +14 -6
  76. package/dist/util/dialect.util.js +17 -13
  77. package/dist/util/field.util.d.ts +12 -0
  78. package/dist/util/field.util.js +17 -1
  79. package/dist/util/fieldOption.util.js +5 -1
  80. package/dist/util/object.util.d.ts +4 -0
  81. package/dist/util/object.util.js +13 -0
  82. package/dist/util/query.util.d.ts +5 -3
  83. package/dist/util/query.util.js +7 -2
  84. package/dist/util/sql.d.ts +25 -7
  85. package/dist/util/sql.js +58 -18
  86. package/dist/util/triggerWrite.d.ts +7 -4
  87. package/dist/util/triggerWrite.js +5 -4
  88. package/package.json +1 -1
  89. package/skills/uql-orm/SKILL.md +27 -19
@@ -72,10 +72,15 @@ export declare const COUNT_RESULT_KEY = "_count";
72
72
  export type QueryCount<E, Sql = QuerySql, R extends keyof E = ToManyRelationKey<E>> = {
73
73
  [K in R]?: BooleanLike | QueryFilter<RelationTarget<E[K]>, Sql>;
74
74
  };
75
+ /** The fields of a unique key an upsert finds a row by, `{ email: true }`, as `$select` names them. */
76
+ export type QueryConflictKeys<E> = QuerySelect<E, FieldKey<E>, true>;
75
77
  /**
76
- * query conflict paths - subset of field keys used to detect upsert conflicts.
78
+ * The rows an upsert writes: a row `$conflict`'s keys find, `{ email: true }`, takes the update where it matches
79
+ * `$where`, as `updateMany` reads one, `{ status: ['done', 'failed'] }`, and stays as it is elsewhere; the rest insert.
77
80
  */
78
- export type QueryConflictPaths<E> = QuerySelect<E, FieldKey<E>, true>;
81
+ export type QueryUpsert<E, Sql = QuerySql> = QueryFilter<E, Sql> & {
82
+ readonly $conflict: QueryConflictKeys<E>;
83
+ };
79
84
  /**
80
85
  * Options to populate a relation declared as `V`, by its cardinality.
81
86
  */
@@ -123,8 +123,8 @@ type Simplify<T> = {
123
123
  [K in keyof T]: T[K];
124
124
  } & {};
125
125
  /** An aggregate's row for the query `Q`: each grouped column with its entity type, each alias with its path's, each computed one with its aggregate's. */
126
- export type QueryAggregateResult<E, Q> = AggregateRow<E, AggregateGroup<Q>, AggregateSelect<Q>>;
127
- type AggregateRow<E, G, A> = Simplify<Pick<E, GroupedKeys<G> & FieldKey<E>> & {
126
+ export type QueryAggregateResult<E, Q> = AggregateResultRow<E, AggregateGroup<Q>, AggregateSelect<Q>>;
127
+ type AggregateResultRow<E, G, A> = Simplify<Pick<E, GroupedKeys<G> & FieldKey<E>> & {
128
128
  -readonly [K in Exclude<NamedKeys<G>, FieldKey<E>>]: GroupRefValue<E, G[K]>;
129
129
  } & {
130
130
  -readonly [K in keyof A]: QueryAggregateFnResult<E, A[K]>;
@@ -175,12 +175,12 @@ type ClosedAggregateQuery<E, G, A> = {
175
175
  readonly [K in keyof A]: K extends keyof G ? never : QueryAggregateFn<E>;
176
176
  };
177
177
  /** Filtering after grouping, by a result column, each value typed as that column is. */
178
- readonly $having?: HavingOf<AggregateRow<E, G, A>>;
178
+ readonly $having?: HavingOf<AggregateResultRow<E, G, A>>;
179
179
  /**
180
180
  * Sort the aggregated results by a grouped column or a computed alias - an aggregate's rows are
181
181
  * its groups, so any other entity field names a value the statement never produced.
182
182
  */
183
- readonly $sort?: SortOf<AggregateRow<E, G, A>>;
183
+ readonly $sort?: SortOf<AggregateResultRow<E, G, A>>;
184
184
  } & QueryPager;
185
185
  /**
186
186
  * A `$having` over a row's columns, each value typed as its column is. Mapped over the row once it is resolved,
@@ -37,6 +37,8 @@ export declare const SQL_TEXT: unique symbol;
37
37
  export declare const SQL_VALUE_TYPE: unique symbol;
38
38
  /** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */
39
39
  export declare const REF_KEY: unique symbol;
40
+ /** The entity a {@link ColumnRef} was read off, where it names one: a definition's refs name none. */
41
+ export declare const REF_ENTITY: unique symbol;
40
42
  /** The dotted path a {@link JsonPathRef} reads down its column's document. */
41
43
  export declare const JSON_PATH: unique symbol;
42
44
  /** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */
@@ -74,7 +76,8 @@ export declare function renderSql(statement: QuerySql, opts: QuerySqlRenderOptio
74
76
  export declare class ColumnRef<K extends string = string, V = unknown> extends QuerySql {
75
77
  readonly [SQL_VALUE_TYPE]?: V;
76
78
  readonly [REF_KEY]: K;
77
- constructor(key: K, value: QuerySqlFn);
79
+ readonly [REF_ENTITY]?: AbstractType<unknown>;
80
+ constructor(key: K, value: QuerySqlFn, entity?: AbstractType<unknown>);
78
81
  }
79
82
  /**
80
83
  * A path inside a JSON column, read off an index's refs as the `$where` key it is: `user.settings.theme`
@@ -5,6 +5,8 @@ export const SQL_TEXT = Symbol('sqlText');
5
5
  export const SQL_VALUE_TYPE = Symbol('sqlValueType');
6
6
  /** The member a ref names. A symbol, as each of a ref's own keys is, so every string key is the data's. */
7
7
  export const REF_KEY = Symbol('refKey');
8
+ /** The entity a {@link ColumnRef} was read off, where it names one: a definition's refs name none. */
9
+ export const REF_ENTITY = Symbol('refEntity');
8
10
  /** The dotted path a {@link JsonPathRef} reads down its column's document. */
9
11
  export const JSON_PATH = Symbol('jsonPath');
10
12
  /** Keys the phantom a {@link JsonPathRef} carries the value at its path in. */
@@ -42,9 +44,11 @@ export function renderSql(statement, opts) {
42
44
  */
43
45
  export class ColumnRef extends QuerySql {
44
46
  [REF_KEY];
45
- constructor(key, value) {
47
+ [REF_ENTITY];
48
+ constructor(key, value, entity) {
46
49
  super(value);
47
50
  this[REF_KEY] = key;
51
+ this[REF_ENTITY] = entity;
48
52
  }
49
53
  }
50
54
  /**
@@ -101,7 +101,7 @@ export type QueryGroupOp = QueryJoinOp | QueryNegateOp;
101
101
  * Strips `null` from picked operators since array size is always numeric.
102
102
  */
103
103
  export type QuerySizeComparisonOps = {
104
- [K in QueryHavingOp | '$between']?: NonNullable<QueryWhereFieldOperatorMap<number>[K]>;
104
+ [K in QueryHavingOp | '$between']?: NonNullable<QueryWhereFieldOperatorMap<number, never>[K]>;
105
105
  };
106
106
  /**
107
107
  * Filter by distance to a vector, `{ $near: { $vector: v, $lt: 0.35 } }`: ordered bounds only, since a
@@ -110,17 +110,22 @@ export type QuerySizeComparisonOps = {
110
110
  * checks it again at run time.
111
111
  */
112
112
  export type QueryVectorNear = QueryVectorQuery & AtLeastOne<{
113
- [K in QueryOrderedOp]: NonNullable<QueryWhereFieldOperatorMap<number>[K]>;
113
+ [K in QueryOrderedOp]: NonNullable<QueryWhereFieldOperatorMap<number, never>[K]>;
114
114
  }>;
115
+ /**
116
+ * What an operator compares a field of type `T` with: a value of it, or SQL holding one, a ref to another
117
+ * column most often, `{ effectiveTo: { $gt: rate.effectiveFrom } }`. The wire's `never` keeps it a value.
118
+ */
119
+ export type QueryOperand<T, Sql = QuerySql> = ExpandScalar<T> | SqlFor<Sql, T>;
115
120
  export type QueryWhereFieldOperatorMap<T, Sql = QuerySql> = {
116
121
  /**
117
122
  * whether a value is equal to the given value.
118
123
  */
119
- $eq?: ExpandScalar<T> | null;
124
+ $eq?: QueryOperand<T, Sql> | null;
120
125
  /**
121
126
  * whether a value is not equal to the given value.
122
127
  */
123
- $ne?: ExpandScalar<T> | null;
128
+ $ne?: QueryOperand<T, Sql> | null;
124
129
  /**
125
130
  * negates the given comparison for a single field.
126
131
  * @see {@link QueryWhereRootOperator.$not} for root-level clause negation.
@@ -129,24 +134,24 @@ export type QueryWhereFieldOperatorMap<T, Sql = QuerySql> = {
129
134
  /**
130
135
  * whether a value is less than the given value.
131
136
  */
132
- $lt?: ExpandScalar<T>;
137
+ $lt?: QueryOperand<T, Sql>;
133
138
  /**
134
139
  * whether a value is less than or equal to the given value.
135
140
  */
136
- $lte?: ExpandScalar<T>;
141
+ $lte?: QueryOperand<T, Sql>;
137
142
  /**
138
143
  * whether a value is greater than the given value.
139
144
  */
140
- $gt?: ExpandScalar<T>;
145
+ $gt?: QueryOperand<T, Sql>;
141
146
  /**
142
147
  * whether a value is greater than or equal to the given value.
143
148
  */
144
- $gte?: ExpandScalar<T>;
149
+ $gte?: QueryOperand<T, Sql>;
145
150
  /**
146
151
  * whether a value is between two values (inclusive). Shorthand for $gte + $lte.
147
152
  * @example { age: { $between: [18, 65] } }
148
153
  */
149
- $between?: readonly [ExpandScalar<T>, ExpandScalar<T>];
154
+ $between?: readonly [QueryOperand<T, Sql>, QueryOperand<T, Sql>];
150
155
  /**
151
156
  * whether a string begins with the given text, taken literally (case sensitive).
152
157
  */
@@ -188,11 +193,11 @@ export type QueryWhereFieldOperatorMap<T, Sql = QuerySql> = {
188
193
  /**
189
194
  * whether a value matches any of the given values.
190
195
  */
191
- $in?: readonly ExpandScalar<T>[];
196
+ $in?: readonly QueryOperand<T, Sql>[];
192
197
  /**
193
198
  * whether a value does not match any of the given values.
194
199
  */
195
- $nin?: readonly ExpandScalar<T>[];
200
+ $nin?: readonly QueryOperand<T, Sql>[];
196
201
  /**
197
202
  * whether a value is null.
198
203
  * @example { deletedAt: { $isNull: true } }
@@ -1,5 +1,5 @@
1
1
  import type { EntityId, EntityWrite, FieldKey, UpdateWrite } from './entity.js';
2
- import type { Captured, CursorPage, Query, QueryConflictPaths, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, QueryPage, QuerySearch, WriteResults, WriteOptions } from './query.js';
2
+ import type { Captured, CursorPage, Query, QueryUpsert, QueryFilter, QueryFindResult, QueryKeyset, QueryOne, QueryOptions, QueryPage, QuerySearch, WriteResults, WriteOptions } from './query.js';
3
3
  import type { QueryAggregate, QueryAggregateResult } from './queryAggregate.js';
4
4
  import type { BooleanLike, Type } from './utility.js';
5
5
  import type { QuerierCountedResult, QuerierSql, QuerierResult, QuerierTransport } from './wire.js';
@@ -100,13 +100,13 @@ export interface UniversalQuerier extends SharedQuerier<'server', QueryOptions>
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
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']>;
102
102
  /**
103
- * Insert or update a record by its conflict paths; resolves to its id, or the row `returning` reads back. A
104
- * conflicting row takes the payload less those paths, or `update` as `updateMany` takes one: `{ uses: { $inc: 1 } }`
105
- * counts, and `{}` leaves the row as it is. Either branch writes the cascaded relations it is given.
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.
106
106
  */
107
- upsertOne<E extends object, const S extends FieldKey<E> = never, const V extends BooleanLike = true>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
108
- /** Insert or update records by their conflict paths, 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>, conflictPaths: QueryConflictPaths<E>, payload: readonly 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>(entity: Type<E>, q: QueryUpsert<E>, payload: EntityWrite<E>, update?: UpdateWrite<E>, opts?: WriteOptions<E, S, V>): Promise<WriteResults<E, S, V>['inserted']>;
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'][]>;
110
110
  /** Insert a record, or upsert one naming its key; resolves to its id, or the row `returning` reads back. */
111
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']>;
112
112
  /** Insert records, or upsert those naming their key; resolves to their ids in payload order, or the rows. */
@@ -32,3 +32,8 @@ export declare function enumCheck(table: string, { name, enum: values }: {
32
32
  readonly name: string;
33
33
  readonly enum?: EnumValues;
34
34
  }, render: (statement: QuerySql) => string): CheckSchema[];
35
+ /**
36
+ * An enum's values as every engine's constraint states them, numbers by value and text by code unit (an enum
37
+ * holds one or the other), so a constraint, and the name hashed from it, follow which values there are.
38
+ */
39
+ export declare function sortedEnum(values: EnumValues): EnumValues;
@@ -1,5 +1,5 @@
1
1
  import { indexEntryNamePart, renderIndexColumn } from './indexEntry.util.js';
2
- import { definedEntries } from './object.util.js';
2
+ import { byCodeUnit, definedEntries } from './object.util.js';
3
3
  import { sql } from './sql.js';
4
4
  import { derivedIndexName, ownedName } from './sql.util.js';
5
5
  /**
@@ -54,7 +54,7 @@ export function enumCheck(table, { name, enum: values }, render) {
54
54
  }
55
55
  const statement = sql(({ ctx, dialect }) => {
56
56
  ctx.append(`${dialect.escapeId(name)} IN (`);
57
- values.forEach((value, i) => {
57
+ sortedEnum(values).forEach((value, i) => {
58
58
  ctx.append(i ? ', ' : '');
59
59
  ctx.addValue(value);
60
60
  });
@@ -62,3 +62,10 @@ export function enumCheck(table, { name, enum: values }, render) {
62
62
  });
63
63
  return [ownedCheck(table, name, render(statement))];
64
64
  }
65
+ /**
66
+ * An enum's values as every engine's constraint states them, numbers by value and text by code unit (an enum
67
+ * holds one or the other), so a constraint, and the name hashed from it, follow which values there are.
68
+ */
69
+ export function sortedEnum(values) {
70
+ return values.toSorted(byCodeUnit);
71
+ }
@@ -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 QueryConflictPaths, 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 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>[];
@@ -30,15 +30,23 @@ type Deletion<O> = {
30
30
  * an entity with no soft-delete field, removes them, soft-deleted ones included.
31
31
  */
32
32
  export declare function deletionOf<E, O extends QueryOptions>(meta: EntityMeta<E>, opts: O): Deletion<O>;
33
- /** What an upsert of `row` assigns a row it finds: the payload and the `onUpdate` fills, less its key and what it matched on. */
34
- export declare function upsertAssigned<E>(meta: EntityMeta<E>, row: EntityData<E>, conflictPaths: QueryConflictPaths<E>): EntityData<E>;
33
+ /**
34
+ * What the row an upsert of `row` finds takes: a copy of `update`, none for `{}`, which leaves it as `DO NOTHING`
35
+ * does, and by default the payload less its key and what it matched on.
36
+ */
37
+ export declare function foundRowAssigned<E>(meta: EntityMeta<E>, conflictKeys: QueryConflictKeys<E>, row: EntityData<E>, update: UpdatePayload<E> | undefined): UpdatePayload<E> | undefined;
35
38
  /**
36
39
  * Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
37
40
  * has that key too. Elsewhere the key is the found row's, which the upsert reads back.
38
41
  */
39
- export declare function upsertKeepsOwnKey<E>(meta: EntityMeta<E>, conflictPaths: QueryConflictPaths<E>, row: E): boolean;
40
- /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
41
- export declare function fillOnFields<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, payload: R | R[], callbackKey: CallbackKey): R[];
42
+ export declare function upsertKeepsOwnKey<E>(meta: EntityMeta<E>, conflictKeys: QueryConflictKeys<E>, row: E): boolean;
43
+ /**
44
+ * Where a write runs: a statement uql sends, or a trigger's body, which runs no JavaScript, so a fill there is
45
+ * only a value or SQL; calling a callback would bake one value into the trigger.
46
+ */
47
+ export type WriteScope = 'statement' | 'trigger';
48
+ /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset, as `scope` can. */
49
+ export declare function fillOnFields<E, R extends EntityData<E> | UpdatePayload<E>>(meta: EntityMeta<E>, payload: R | R[], callbackKey: CallbackKey, scope?: WriteScope): R[];
42
50
  /** The relations a write cascades `action` to, in declaration order. */
43
51
  export declare function cascadingRelations<E>(meta: EntityMeta<E>, action: CascadeType): RelationKey<E>[];
44
52
  export declare function isCascadable(action: CascadeType, configuration?: boolean | CascadeType): boolean;
@@ -4,7 +4,7 @@ import { QuerySql, resolveAggregateOp, } from '../type/index.js';
4
4
  import { DEFAULT_VECTOR_DISTANCE, VECTOR_INDEX_TYPES } from '../type/vector.js';
5
5
  import { defaultReadKeys, fieldKeys, isDatabaseWritten, jsonKey, jsonPathKeys } from './field.util.js';
6
6
  import { withDeleted } from './filters.util.js';
7
- import { clone, entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isRecord, someKey, } from './object.util.js';
7
+ import { entityName, getKeys, omitKeys, hasKeys, isJsonScalar, isOperatorObject, isRecord, someKey, } from './object.util.js';
8
8
  import { assertNoUndefined, whereAnd } from './query.util.js';
9
9
  import { UqlSecurityError, UqlUsageError } from './uqlError.js';
10
10
  /** The keys of `payload` a write persists as columns. */
@@ -77,22 +77,25 @@ export function deletionOf(meta, opts) {
77
77
  }
78
78
  return { stamp: { key, field, value: () => softDeleteValue(field) }, opts };
79
79
  }
80
- /** What an upsert of `row` assigns a row it finds: the payload and the `onUpdate` fills, less its key and what it matched on. */
81
- export function upsertAssigned(meta, row, conflictPaths) {
82
- const [updated] = fillOnFields(meta, clone(row), 'onUpdate');
83
- const kept = [...meta.ids, ...getKeys(conflictPaths)];
84
- const assigned = filterFieldKeys(meta, updated, 'onUpdate');
85
- return omitKeys(updated, getKeys(updated).filter((key) => kept.includes(key) || !assigned.includes(key)));
80
+ /**
81
+ * What the row an upsert of `row` finds takes: a copy of `update`, none for `{}`, which leaves it as `DO NOTHING`
82
+ * does, and by default the payload less its key and what it matched on.
83
+ */
84
+ export function foundRowAssigned(meta, conflictKeys, row, update) {
85
+ if (update === undefined) {
86
+ return omitKeys(row, [...meta.ids, ...getKeys(conflictKeys)]);
87
+ }
88
+ return hasKeys(update) ? { ...update } : undefined;
86
89
  }
87
90
  /**
88
91
  * Whether an upsert of `row` lands under the key it names: it names one and matches on it, so a row it finds
89
92
  * has that key too. Elsewhere the key is the found row's, which the upsert reads back.
90
93
  */
91
- export function upsertKeepsOwnKey(meta, conflictPaths, row) {
92
- return namesKey(meta, row) && meta.ids.every((key) => Object.hasOwn(conflictPaths, key));
94
+ export function upsertKeepsOwnKey(meta, conflictKeys, row) {
95
+ return namesKey(meta, row) && meta.ids.every((key) => Object.hasOwn(conflictKeys, key));
93
96
  }
94
- /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset. */
95
- export function fillOnFields(meta, payload, callbackKey) {
97
+ /** Fills each field `callbackKey` generates on `payload` in place, where the caller left it unset, as `scope` can. */
98
+ export function fillOnFields(meta, payload, callbackKey, scope = 'statement') {
96
99
  const payloads = Array.isArray(payload) ? payload : [payload];
97
100
  const keys = filledKeys(meta, callbackKey);
98
101
  if (keys.length === 0) {
@@ -100,8 +103,9 @@ export function fillOnFields(meta, payload, callbackKey) {
100
103
  }
101
104
  for (const it of payloads) {
102
105
  for (const key of keys) {
103
- if (it[key] === undefined) {
104
- it[key] = getFieldCallbackValue(meta.fields[key][callbackKey]);
106
+ const fill = meta.fields[key][callbackKey];
107
+ if (it[key] === undefined && (scope === 'statement' || typeof fill !== 'function')) {
108
+ it[key] = getFieldCallbackValue(fill);
105
109
  }
106
110
  }
107
111
  }
@@ -48,6 +48,18 @@ export declare function isAutoIncrement(field: FieldOptions, soleKey: boolean):
48
48
  export declare function fieldFamily(field: FieldOptions): ColumnFamily | undefined;
49
49
  /** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
50
50
  export declare function declaresNotNull(field: FieldOptions): boolean;
51
+ /** Whether a row holds nothing in `column` unless written: required, with no default, and not one the engine fills. */
52
+ export declare function lacksValue(column: {
53
+ readonly nullable: boolean;
54
+ readonly defaultValue?: unknown;
55
+ readonly generatedAs?: string;
56
+ readonly isAutoIncrement: boolean;
57
+ }): boolean;
58
+ /**
59
+ * {@link lacksValue} for an insert leaving the field out, where a computed column, a stamp its trigger fills included,
60
+ * holds a value too, unlike on the rows a migration finds.
61
+ */
62
+ export declare function lacksValueOnInsert(field: FieldOptions, soleKey: boolean): boolean;
51
63
  /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
52
64
  export declare function isFieldKey<E>(meta: EntityMeta<E>, key: string): key is FieldKey<E>;
53
65
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
@@ -52,7 +52,7 @@ export function isInlinedExpression(field) {
52
52
  }
53
53
  /** Whether the entity puts anything on its table the database runs: an authored trigger, or a stamp. */
54
54
  export function hasTriggers(meta) {
55
- return Boolean(meta.triggers?.length) || definedEntries(meta.fields).some(([, field]) => stampEvents(field));
55
+ return (Boolean(meta.triggers?.length) || definedEntries(meta.fields).some(([, field]) => stampEvents(field) !== undefined));
56
56
  }
57
57
  /**
58
58
  * The events the database writes this field on, or `undefined` where it is not a stamp. A stamp is a
@@ -101,6 +101,22 @@ export function fieldFamily(field) {
101
101
  export function declaresNotNull(field) {
102
102
  return field.nullable !== true;
103
103
  }
104
+ /** Whether a row holds nothing in `column` unless written: required, with no default, and not one the engine fills. */
105
+ export function lacksValue(column) {
106
+ return !column.nullable && column.defaultValue === undefined && !column.generatedAs && !column.isAutoIncrement;
107
+ }
108
+ /**
109
+ * {@link lacksValue} for an insert leaving the field out, where a computed column, a stamp its trigger fills included,
110
+ * holds a value too, unlike on the rows a migration finds.
111
+ */
112
+ export function lacksValueOnInsert(field, soleKey) {
113
+ return (!isDatabaseWritten(field) &&
114
+ lacksValue({
115
+ nullable: !declaresNotNull(field),
116
+ defaultValue: field.defaultValue,
117
+ isAutoIncrement: isAutoIncrement(field, soleKey),
118
+ }));
119
+ }
104
120
  /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
105
121
  export function isFieldKey(meta, key) {
106
122
  return meta.fields[key] !== undefined;
@@ -1,6 +1,6 @@
1
1
  import { QuerySql, } from '../type/index.js';
2
2
  import { columnFamily, fieldFamily, isInlinedExpression } from './field.util.js';
3
- import { getKeys } from './object.util.js';
3
+ import { getKeys, jsonDocument } from './object.util.js';
4
4
  import { constantSql } from './sql.js';
5
5
  /**
6
6
  * The column families each field option means anything on, or `'*'` where it applies to every column.
@@ -117,6 +117,10 @@ export function fieldOptionConflict(opts) {
117
117
  return stray;
118
118
  }
119
119
  const family = fieldFamily(opts);
120
+ const spelled = family === 'json' && typeof opts.defaultValue === 'string' ? jsonDocument(opts.defaultValue) : undefined;
121
+ if (spelled !== undefined) {
122
+ return `cannot use 'defaultValue': a JSON column defaults to a value, \`${JSON.stringify(spelled)}\`, not to its JSON text \`'${String(opts.defaultValue)}'\``;
123
+ }
120
124
  // Walked in table order, not in the order the field happened to be written, so a field with two
121
125
  // conflicts always reports the same one. An option no rule knows is a typo, which `@Field`'s own check
122
126
  // reports where it can still be spelled right.
@@ -1,6 +1,8 @@
1
1
  import type { EntityMeta, JsonScalar } from '../type/index.js';
2
2
  /** Whether `value` is a {@link JsonScalar}, which `$addToSet` and an `=` on a JSON path compare by equality. */
3
3
  export declare function isJsonScalar(value: unknown): value is JsonScalar;
4
+ /** Orders two strings by code unit, or two numbers by value, the order every engine sorts text by, so names and JSON keys agree across them. */
5
+ export declare function byCodeUnit<T extends string | number>(a: T, b: T): number;
4
6
  export declare function clone<T>(value: T): T;
5
7
  /** `items` in consecutive lists of at most `size`, in order: one list where `size` is unbounded. */
6
8
  export declare function chunk<T>(items: readonly T[], size: number): T[][];
@@ -41,3 +43,5 @@ export declare function entityName<E>(meta: EntityMeta<E>): string;
41
43
  export declare function isScalarId(value: unknown): boolean;
42
44
  /** Whether `value` is a plain object naming columns, the one shape a `$where` takes. */
43
45
  export declare function isWhereMap(value: unknown): value is Record<string, unknown>;
46
+ /** What `text` spells as JSON, or nothing where it is no JSON at all. */
47
+ export declare function jsonDocument(text: string): unknown;
@@ -2,6 +2,10 @@
2
2
  export function isJsonScalar(value) {
3
3
  return typeof value === 'string' || typeof value === 'boolean' || Number.isFinite(value);
4
4
  }
5
+ /** Orders two strings by code unit, or two numbers by value, the order every engine sorts text by, so names and JSON keys agree across them. */
6
+ export function byCodeUnit(a, b) {
7
+ return a < b ? -1 : 1;
8
+ }
5
9
  export function clone(value) {
6
10
  if (typeof value !== 'object' || value === null) {
7
11
  return value;
@@ -107,3 +111,12 @@ export function isScalarId(value) {
107
111
  export function isWhereMap(value) {
108
112
  return !Array.isArray(value) && !isScalarId(value);
109
113
  }
114
+ /** What `text` spells as JSON, or nothing where it is no JSON at all. */
115
+ export function jsonDocument(text) {
116
+ try {
117
+ return JSON.parse(text);
118
+ }
119
+ catch {
120
+ return undefined;
121
+ }
122
+ }
@@ -1,11 +1,11 @@
1
1
  import { type KeyedRow } from '../entity/metadata/definition.js';
2
- import type { EntityId, EntityMeta, FieldKey, Query, QueryConflictPaths, QuerySearch, QuerySortDirection, QuerySortMap, QueryWhere, QueryWhereArray } from '../type/index.js';
2
+ import type { EntityData, EntityId, EntityMeta, FieldKey, Query, QueryConflictKeys, QuerySearch, QuerySortDirection, QuerySortMap, QueryUpsert, QueryWhere, QueryWhereArray } from '../type/index.js';
3
3
  /**
4
- * Maps each of `keys` to `true`, the shape of a `$select` or conflict paths. This and the builders below hold
4
+ * Maps each of `keys` to `true`, the shape of a `$select` or conflict keys. This and the builders below hold
5
5
  * the casts generic code needs to build a statement: the compiler types these maps per entity, so it does not
6
6
  * accept a key read at run time as one of their keys.
7
7
  */
8
- export declare function keySet<E>(keys: readonly FieldKey<E>[]): QueryConflictPaths<E>;
8
+ export declare function keySet<E>(keys: readonly FieldKey<E>[]): QueryConflictKeys<E>;
9
9
  /** `where` (or an empty `$where`) with `key` also set to `value`. Keys in one map combine with `AND`. */
10
10
  export declare function whereWith<E>(key: FieldKey<E>, value: unknown, where?: QueryWhere<E>): QueryWhere<E>;
11
11
  export declare function whereEach<E>(keys: readonly FieldKey<E>[], valueOf: (key: FieldKey<E>) => unknown): QueryWhere<E>;
@@ -19,6 +19,8 @@ export declare function sortOf<E>(entries: readonly (readonly [FieldKey<E>, Quer
19
19
  * the same name, such as a second `$or`.
20
20
  */
21
21
  export declare function whereAnd<E>(where: QueryWhere<E> | undefined, clauses: QueryWhereArray<E>): QueryWhere<E>;
22
+ /** The row an upsert of `row` finds by `q.$conflict`'s keys, as one matching `q.$where` too: the one it updates. */
23
+ export declare function foundRowWhere<E>(q: QueryUpsert<E>, row: EntityData<E>): QueryWhere<E>;
22
24
  /** `q` selecting only the id. A write passes it to its backend's read builder to find the rows it will act on. */
23
25
  export declare function idOnlyQuery<E>(meta: EntityMeta<E>, q: QuerySearch<E>): Query<E>;
24
26
  /**
@@ -1,8 +1,8 @@
1
1
  import { soleIdOf } from '../entity/metadata/definition.js';
2
- import { entityName, isRecord, isScalarId, isWhereMap } from './object.util.js';
2
+ import { entityName, getKeys, isRecord, isScalarId, isWhereMap } from './object.util.js';
3
3
  import { UqlUsageError } from './uqlError.js';
4
4
  /**
5
- * Maps each of `keys` to `true`, the shape of a `$select` or conflict paths. This and the builders below hold
5
+ * Maps each of `keys` to `true`, the shape of a `$select` or conflict keys. This and the builders below hold
6
6
  * the casts generic code needs to build a statement: the compiler types these maps per entity, so it does not
7
7
  * accept a key read at run time as one of their keys.
8
8
  */
@@ -37,6 +37,11 @@ export function sortOf(entries) {
37
37
  export function whereAnd(where, clauses) {
38
38
  return { ...where, $and: [...(where?.$and ?? []), ...clauses] };
39
39
  }
40
+ /** The row an upsert of `row` finds by `q.$conflict`'s keys, as one matching `q.$where` too: the one it updates. */
41
+ export function foundRowWhere(q, row) {
42
+ const found = whereEach(getKeys(q.$conflict), (key) => row[key]);
43
+ return q.$where ? whereAnd(found, [q.$where]) : found;
44
+ }
40
45
  /** `q` selecting only the id. A write passes it to its backend's read builder to find the rows it will act on. */
41
46
  export function idOnlyQuery(meta, q) {
42
47
  return { ...q, $select: keySet(meta.ids) };
@@ -34,10 +34,15 @@ export declare const uuidv7: QuerySql;
34
34
  export declare const SQL_VALUES: Readonly<Record<SqlValueName, QuerySql>>;
35
35
  /**
36
36
  * The fields of `entity` as {@link ColumnRef}s, each rendering inside `sql` as its column: named the way
37
- * the dialect names it, so the naming strategy and `.name()` apply, and qualified by the alias
38
- * in scope. Metadata is read when a ref renders, so the map serves before the fields are registered.
37
+ * 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.
39
39
  */
40
- export declare function refs<E>(entity: AbstractType<E>): RefMap<E>;
40
+ export declare function refs<E>(entity: AbstractType<E>, alias?: string): RefMap<E>;
41
+ /**
42
+ * The table `source` names, an entity or the refs read off one under their alias, `"order" "o"`, for raw SQL
43
+ * reading another table than its statement's: `sql`SELECT ${o.state} FROM ${tableOf(o)}``, `o = refs(Order, 'o')`.
44
+ */
45
+ export declare function tableOf<E>(source: AbstractType<E> | RefMap<E>): QuerySql;
41
46
  /**
42
47
  * The refs a definition's callbacks read: a check's, a computed field's, a predicate's. A member decorator
43
48
  * sees no class, so these name no entity and resolve against the one rendering them.
@@ -54,11 +59,24 @@ export declare function indexRefs<E>(): IndexRefMap<E>;
54
59
  * {@link refs} are, so each names its own column wherever it renders, a write to another table included.
55
60
  * Columns only: a relation's aggregate is a subquery, and a trigger fires on one row, not over a table.
56
61
  */
57
- export declare function rowRefs<E>(entity: AbstractType<E>, qualifier: TriggerRowName): RefMap<E>;
62
+ export declare function rowRefs<E>(entity: AbstractType<E>, row: TriggerRowName): RefMap<E>;
63
+ /** What a ref reads its column off instead of the alias in scope: a trigger's row, `NEW` or `OLD`, or a table's alias. */
64
+ type Qualifier = {
65
+ readonly row: TriggerRowName;
66
+ readonly alias?: never;
67
+ } | {
68
+ readonly alias: string;
69
+ readonly row?: never;
70
+ };
58
71
  /**
59
- * One field as SQL, against its own entity or, read off a definition, the entity rendering it. A
60
- * `qualifier` names the row it reads from, `NEW` or `OLD`, instead of the alias in scope.
72
+ * One field as SQL, against its own entity or, read off a definition, the entity rendering it, read off the
73
+ * alias in scope unless a `qualifier` names another.
61
74
  */
62
- export declare function columnRef(entity: AbstractType<unknown> | undefined, key: string, qualifier?: string): ColumnRef;
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. */
77
+ export declare function refOwner(entity: AbstractType<unknown> | undefined, key: string, scope: {
78
+ readonly entity?: AbstractType<unknown>;
79
+ }): AbstractType<unknown>;
63
80
  /** @deprecated Renamed to {@link sql}, the tag editors recognise for SQL highlighting. */
64
81
  export declare const raw: typeof sql;
82
+ export {};