uql-orm 0.104.1 → 0.105.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 (161) hide show
  1. package/README.md +24 -10
  2. package/dist/browser/querier/httpQuerier.d.ts +3 -3
  3. package/dist/browser/type/clientQuerier.d.ts +1 -1
  4. package/dist/browser/uql-browser.min.js +2 -2
  5. package/dist/browser/uql-browser.min.js.map +9 -9
  6. package/dist/cockroachdb/cockroachDialect.d.ts +2 -2
  7. package/dist/dialect/abstractDialect.d.ts +3 -3
  8. package/dist/dialect/abstractSqlDialect.d.ts +39 -37
  9. package/dist/dialect/abstractSqlDialect.js +35 -32
  10. package/dist/dialect/aliases.d.ts +2 -0
  11. package/dist/dialect/aliases.js +2 -0
  12. package/dist/dialect/jsonSql.js +2 -2
  13. package/dist/dialect/mergeSqlDialect.d.ts +2 -2
  14. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -7
  15. package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
  16. package/dist/dialect/operators.js +2 -4
  17. package/dist/dialect/queryJoins.d.ts +4 -2
  18. package/dist/dialect/vectorSqlDialect.d.ts +1 -1
  19. package/dist/dialect/vectorSqlDialect.js +1 -1
  20. package/dist/entity/column.d.ts +3 -0
  21. package/dist/entity/column.js +3 -0
  22. package/dist/entity/columnOptionsBuilder.d.ts +54 -0
  23. package/dist/entity/columnOptionsBuilder.js +108 -0
  24. package/dist/entity/decorator/bag.d.ts +5 -5
  25. package/dist/entity/decorator/entity.d.ts +3 -20
  26. package/dist/entity/decorator/entity.js +3 -37
  27. package/dist/entity/decorator/members.d.ts +46 -76
  28. package/dist/entity/decorator/members.js +18 -7
  29. package/dist/entity/index.d.ts +2 -1
  30. package/dist/entity/index.js +2 -1
  31. package/dist/entity/metadata/definition.d.ts +15 -26
  32. package/dist/entity/metadata/definition.js +344 -148
  33. package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
  34. package/dist/entity/metadata/schemaFixture/animal.js +7 -0
  35. package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
  36. package/dist/entity/metadata/schemaFixture/author.js +25 -0
  37. package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
  38. package/dist/entity/metadata/schemaFixture/book.js +23 -0
  39. package/dist/http/contract.d.ts +2 -2
  40. package/dist/http/handler.d.ts +2 -2
  41. package/dist/http/query.js +12 -13
  42. package/dist/index.d.ts +2 -2
  43. package/dist/index.js +2 -1
  44. package/dist/mariadb/mariaDialect.d.ts +2 -2
  45. package/dist/mariadb/mariaDialect.js +1 -1
  46. package/dist/mariadb/mariadbQuerier.js +1 -3
  47. package/dist/migrate/builder/columnBuilder.d.ts +20 -68
  48. package/dist/migrate/builder/columnBuilder.js +104 -110
  49. package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
  50. package/dist/migrate/builder/migrationBuilder.js +7 -6
  51. package/dist/migrate/builder/tableBuilder.d.ts +3 -55
  52. package/dist/migrate/builder/tableBuilder.js +88 -204
  53. package/dist/migrate/builder/types.d.ts +52 -151
  54. package/dist/migrate/builder/types.js +0 -6
  55. package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
  56. package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
  57. package/dist/migrate/codegen/entityTypes.d.ts +2 -2
  58. package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
  59. package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
  60. package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
  61. package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
  62. package/dist/migrate/ddl/defaultSql.js +7 -6
  63. package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
  64. package/dist/migrate/ddl/indexCapabilities.js +26 -13
  65. package/dist/migrate/ddl/indexDdl.d.ts +13 -13
  66. package/dist/migrate/ddl/indexDdl.js +33 -30
  67. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
  68. package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
  69. package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
  70. package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
  71. package/dist/migrate/drift/driftDetector.js +2 -2
  72. package/dist/migrate/generator/definitionToNode.d.ts +8 -2
  73. package/dist/migrate/generator/definitionToNode.js +4 -5
  74. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
  75. package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
  76. package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
  77. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
  78. package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
  79. package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
  80. package/dist/migrate/introspection/postgresIntrospector.js +3 -4
  81. package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
  82. package/dist/migrate/introspection/tableSchemaAST.js +5 -1
  83. package/dist/migrate/migrator.d.ts +2 -2
  84. package/dist/migrate/schemaChange.d.ts +3 -3
  85. package/dist/migrate/schemaChange.js +3 -2
  86. package/dist/migrate/schemaGenerator.d.ts +5 -5
  87. package/dist/migrate/schemaGenerator.js +1 -1
  88. package/dist/migrate/storage/databaseStorage.js +4 -4
  89. package/dist/mongodb/mongoDialect.d.ts +41 -44
  90. package/dist/mongodb/mongoDialect.js +118 -32
  91. package/dist/mongodb/mongoIntrospector.d.ts +3 -1
  92. package/dist/mongodb/mongoIntrospector.js +11 -5
  93. package/dist/mongodb/mongoSchemaGenerator.d.ts +4 -4
  94. package/dist/mongodb/mongoSchemaGenerator.js +35 -27
  95. package/dist/mongodb/mongodbQuerier.d.ts +1 -11
  96. package/dist/mongodb/mongodbQuerier.js +9 -43
  97. package/dist/mssql/mssqlDialect.d.ts +4 -4
  98. package/dist/postgres/postgresDialect.d.ts +2 -2
  99. package/dist/querier/abstractQuerier.d.ts +0 -1
  100. package/dist/querier/abstractQuerier.js +1 -20
  101. package/dist/querier/abstractSqlQuerier.d.ts +1 -1
  102. package/dist/querier/keyset.js +3 -3
  103. package/dist/schema/declaredColumn.d.ts +11 -0
  104. package/dist/schema/declaredColumn.js +21 -0
  105. package/dist/schema/indexColumns.d.ts +0 -3
  106. package/dist/schema/indexColumns.js +11 -7
  107. package/dist/schema/indexDifferences.d.ts +10 -5
  108. package/dist/schema/indexDifferences.js +42 -28
  109. package/dist/schema/schemaASTBuilder.d.ts +4 -4
  110. package/dist/schema/schemaASTBuilder.js +28 -36
  111. package/dist/schema/schemaASTDiffer.js +8 -4
  112. package/dist/schema/sqlExpression.d.ts +21 -17
  113. package/dist/schema/sqlExpression.js +11 -23
  114. package/dist/type/column.d.ts +328 -0
  115. package/dist/type/column.js +2 -0
  116. package/dist/type/config.d.ts +3 -3
  117. package/dist/type/dialect.d.ts +15 -14
  118. package/dist/type/dialect.js +1 -0
  119. package/dist/type/entity.d.ts +292 -281
  120. package/dist/type/entity.js +6 -1
  121. package/dist/type/index.d.ts +2 -0
  122. package/dist/type/index.js +2 -0
  123. package/dist/type/migration.d.ts +11 -11
  124. package/dist/type/querier.d.ts +2 -2
  125. package/dist/type/query.d.ts +44 -40
  126. package/dist/type/query.js +2 -3
  127. package/dist/type/queryAggregate.d.ts +22 -12
  128. package/dist/type/querySql.d.ts +22 -6
  129. package/dist/type/querySql.js +27 -9
  130. package/dist/type/schemaEntity.d.ts +194 -0
  131. package/dist/type/schemaEntity.js +1 -0
  132. package/dist/type/utility.d.ts +4 -7
  133. package/dist/type/vector.d.ts +1 -1
  134. package/dist/util/ddlExpression.util.d.ts +12 -13
  135. package/dist/util/ddlExpression.util.js +12 -21
  136. package/dist/util/dialect.util.d.ts +11 -5
  137. package/dist/util/dialect.util.js +31 -37
  138. package/dist/util/field.util.d.ts +10 -9
  139. package/dist/util/field.util.js +14 -10
  140. package/dist/util/fieldOption.util.d.ts +11 -95
  141. package/dist/util/fieldOption.util.js +49 -16
  142. package/dist/util/hook.util.d.ts +3 -15
  143. package/dist/util/hook.util.js +3 -16
  144. package/dist/util/index.d.ts +1 -0
  145. package/dist/util/index.js +1 -0
  146. package/dist/util/indexEntry.util.d.ts +45 -0
  147. package/dist/util/indexEntry.util.js +138 -0
  148. package/dist/util/relationQuery.util.d.ts +0 -1
  149. package/dist/util/relationQuery.util.js +0 -5
  150. package/dist/util/sql.d.ts +13 -10
  151. package/dist/util/sql.js +34 -16
  152. package/dist/util/sql.util.d.ts +4 -5
  153. package/dist/util/sql.util.js +7 -16
  154. package/dist/util/string.util.d.ts +2 -0
  155. package/dist/util/string.util.js +4 -0
  156. package/dist/util/triggerWrite.d.ts +5 -5
  157. package/dist/util/uqlError.d.ts +1 -1
  158. package/dist/util/uqlError.js +1 -1
  159. package/package.json +1 -1
  160. package/skills/uql-orm/SKILL.md +76 -25
  161. package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
@@ -1,4 +1,4 @@
1
- import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type JsonArrayUpdateOp, type JsonUpdateOp, type Query, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryExclude, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type Type, type UpdatePayload } from '../type/index.js';
1
+ import { type ColumnFamily, type SavepointCommand, type DdlRenderOptions, type EntityData, type EntityMeta, type EntityWhereMeta, type FieldKey, type FieldOptions, type IsolationLevel, type TransactionOptions, type JsonColumnType, type JsonArrayUpdateOp, type JsonUpdateOp, type Query, type QueryAggregate, type QueryBuildFn, type QueryComparisonOptions, type QueryConflictPaths, type QueryContext, type QueryContextOptions, type QueryGroupOp, type QueryHavingMap, type QueryRenderOptions, type QueryPage, type QueryPager, QuerySql, type QuerySqlFnOptions, type QuerySearch, type QuerySelectValue, type QuerySizeComparisonOps, type QueryTextSearchOptions, type QueryWhere, type QueryWhereArray, type QueryWhereFieldOp, type QueryWhereOptions, type RelationAggregateSpec, type RelationMeta, type SqlDialectName, type SqlQueryDialect, type SqlValues, type TriggerRows, type TriggerWrite, type AbstractType, type UpdatePayload } from '../type/index.js';
2
2
  import { type SortDirection } from '../util/index.js';
3
3
  import type { HydrateKind } from './hydrateColumn.js';
4
4
  import { type JsonAccessMode, type JsonContainer, type JsonKeyWrite, type JsonSlot } from './jsonSql.js';
@@ -67,7 +67,7 @@ type SelectOptions = {
67
67
  };
68
68
  /** A to-many's rows as the parent's statement reads them: an ordinary read of the related entity. */
69
69
  export type RelationRows = {
70
- readonly entity: Type<object>;
70
+ readonly entity: AbstractType<object>;
71
71
  readonly query: Query<object>;
72
72
  readonly alias: string;
73
73
  readonly joins: QueryJoins;
@@ -144,7 +144,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
144
144
  */
145
145
  protected buildFragment(ctx: QueryContext, build: QueryBuildFn): string;
146
146
  /** A `sql()` rendered in place, an operand or a projected term: bound, the driver would get the object. */
147
- protected rawFragment(ctx: QueryContext, value: QuerySql, prefix?: string, entity?: Type<unknown>): string;
147
+ protected rawFragment(ctx: QueryContext, value: QuerySql, prefix?: string, entity?: AbstractType<unknown>): string;
148
148
  /**
149
149
  * Each operand rendered on its own, keeping those that emitted SQL: an empty one leaves no dangling
150
150
  * separator, and the count of what emitted decides the parentheses.
@@ -166,12 +166,12 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
166
166
  * ` RETURNING` the fields `keys` names, after an `UPDATE` or `DELETE` this context holds, projected and read as
167
167
  * a read's are: the terms its rows answer under. Only where `features.writeReturning`.
168
168
  */
169
- returning<E>(ctx: QueryContext, entity: Type<E>, keys: readonly FieldKey<E>[]): readonly SelectTerm[];
169
+ returning<E>(ctx: QueryContext, entity: AbstractType<E>, keys: readonly FieldKey<E>[]): readonly SelectTerm[];
170
170
  /** What the returned row is read off, for an engine that names it: SQL Server's `INSERTED.`. */
171
171
  protected readonly returnedRowPrefix: string;
172
172
  /** `<id column> AS` {@link RETURNED_ID} on its own, for a statement composing a `RETURNING` list of several items. */
173
173
  protected returningIdExpression<E>(meta: EntityMeta<E>): string;
174
- search<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: ReadOptions, joins?: QueryJoins, order?: readonly SortRef[]): void;
174
+ search<E>(ctx: QueryContext, entity: AbstractType<E>, q?: Query<E>, opts?: ReadOptions, joins?: QueryJoins, order?: readonly SortRef[]): void;
175
175
  /**
176
176
  * A relation's rows ordered by the columns their sort terms were carried out in, where they are
177
177
  * paged: otherwise the aggregate reading them orders them, and sorting them first is wasted work.
@@ -183,7 +183,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
183
183
  * joined row keeps its key, every column of a composite past any subtraction: it is what tells a
184
184
  * matched row from no match.
185
185
  */
186
- selectTerms<E>(ctx: QueryContext, entity: Type<E>, select: QuerySelectValue<E> | undefined, opts?: SelectOptions, exclude?: QueryExclude<E>): SelectTerm[];
186
+ selectTerms<E>(ctx: QueryContext, entity: AbstractType<E>, select: QuerySelectValue<E> | undefined, opts?: SelectOptions): SelectTerm[];
187
187
  /** One field's column, or the expression an inlined one stands for, as the projection reads it. */
188
188
  private fieldTerm;
189
189
  /**
@@ -219,13 +219,13 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
219
219
  protected textColumns<E>(meta: EntityMeta<E>, keys: readonly string[], prefix: string | undefined): string[];
220
220
  /** Ranks by the root `$text` of `where`, which is looked up only once a `$sort` asks for it. */
221
221
  private textRanker;
222
- select<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: ReadOptions, joins?: QueryJoins, totalAlias?: string): ReadProjection;
222
+ select<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, opts?: ReadOptions, joins?: QueryJoins, totalAlias?: string): ReadProjection;
223
223
  /**
224
224
  * Everything a read's rows answer under, in order: its own fields, each joined row's fields and to-many
225
225
  * relations under its path, its own to-many relations and `$count`, and each vector distance a `$sort`
226
226
  * projects.
227
227
  */
228
- protected projection<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts: SelectOptions, joins: QueryJoins): SelectTerm[];
228
+ protected projection<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, opts: SelectOptions, joins: QueryJoins): SelectTerm[];
229
229
  /** A projection's list of terms. */
230
230
  private termsSql;
231
231
  /** A term as a projection writes it, aliased unless its SQL already answers under its key. */
@@ -260,11 +260,11 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
260
260
  /** Each joined row's columns and to-many relations under its path, which is what unflattens it. */
261
261
  protected selectJoinedRows(ctx: QueryContext, joins: QueryJoins, json: boolean | undefined, distinct: boolean): SelectTerm[];
262
262
  protected selectRelationJoins<E>(ctx: QueryContext, meta: EntityMeta<E>, rootAlias: string, joins: QueryJoins): void;
263
- where<E>(ctx: QueryContext, entity: Type<E>, where?: QueryWhere<E>, opts?: QueryWhereOptions): void;
263
+ where<E>(ctx: QueryContext, entity: AbstractType<E>, where?: QueryWhere<E>, opts?: QueryWhereOptions): void;
264
264
  /** Renders a `$where` tree without applying entity filters (used for same-scope group-operator recursion). */
265
- protected renderWhere<E>(ctx: QueryContext, entity: Type<E>, where?: QueryWhere<E>, opts?: QueryWhereOptions): void;
266
- compare<E>(ctx: QueryContext, entity: Type<E>, key: string, val: unknown, opts?: QueryComparisonOptions): void;
267
- protected compareLogicalOperator<E>(ctx: QueryContext, entity: Type<E>, key: QueryGroupOp, val: QueryWhereArray<E>, opts: QueryComparisonOptions): void;
265
+ protected renderWhere<E>(ctx: QueryContext, entity: AbstractType<E>, where?: QueryWhere<E>, opts?: QueryWhereOptions): void;
266
+ compare<E>(ctx: QueryContext, entity: AbstractType<E>, key: string, val: unknown, opts?: QueryComparisonOptions): void;
267
+ protected compareLogicalOperator<E>(ctx: QueryContext, entity: AbstractType<E>, key: QueryGroupOp, val: QueryWhereArray<E>, opts: QueryComparisonOptions): void;
268
268
  /** Memoizes {@link escapedColumnName}; see there for why it is per dialect instance. */
269
269
  private readonly escapedColumns;
270
270
  /**
@@ -285,7 +285,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
285
285
  * as text rather than appending it, so every operator gets a real operand to wrap - `LOWER(...)`,
286
286
  * `NOT (... <=> ...)` - instead of having to fall back to a form that takes none.
287
287
  */
288
- protected resolveOperandField<E>(ctx: QueryContext, entity: Type<E>, key: string, opts: QueryRenderOptions): string;
288
+ protected resolveOperandField<E>(ctx: QueryContext, entity: AbstractType<E>, key: string, opts: QueryRenderOptions): string;
289
289
  /**
290
290
  * The expression an inlined computed field stands for, or nothing when the field is a real column. Every
291
291
  * clause names it by the expression, never the output alias, which exists only when it was selected; and
@@ -293,7 +293,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
293
293
  */
294
294
  private inlinedOperand;
295
295
  /** {@link fieldCondition}, appended. */
296
- compareFieldOperator<E>(ctx: QueryContext, entity: Type<E>, key: FieldKey<E>, op: QueryWhereFieldOp, val: unknown, opts?: QueryComparisonOptions): void;
296
+ compareFieldOperator<E>(ctx: QueryContext, entity: AbstractType<E>, key: FieldKey<E>, op: QueryWhereFieldOp, val: unknown, opts?: QueryComparisonOptions): void;
297
297
  /** One operator of a field's condition. Both come from the query as data, so neither is trusted. */
298
298
  private fieldCondition;
299
299
  /**
@@ -364,10 +364,10 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
364
364
  */
365
365
  protected jsonScalarParam(ctx: QueryContext, value: unknown): string;
366
366
  /** {@link resolveOperandField}, appended. */
367
- getComparisonKey<E>(ctx: QueryContext, entity: Type<E>, key: FieldKey<E>, opts?: QueryRenderOptions): void;
367
+ getComparisonKey<E>(ctx: QueryContext, entity: AbstractType<E>, key: FieldKey<E>, opts?: QueryRenderOptions): void;
368
368
  /** Appends the `ORDER BY`, reporting whether there was one - which {@link pager} needs on the
369
369
  * engines that refuse to page an unordered statement. */
370
- sort<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: QuerySortOptions): boolean;
370
+ sort<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, opts?: QuerySortOptions): boolean;
371
371
  /**
372
372
  * The terms of an `ORDER BY`, collected before anything is appended so an unorderable key is reported
373
373
  * instead of half a clause, and because a vector distance is the primary ordering wherever it appears.
@@ -376,10 +376,12 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
376
376
  /**
377
377
  * Walks `$sort` against the metadata of the entity each level addresses, rather than flattening it
378
378
  * to dotted strings and reading every key off the root: only that way does a related column resolve
379
- * through its own `@Field({ name })`, and only that way is `tax.category` the one alias the join
379
+ * through its own `.name()`, and only that way is `tax.category` the one alias the join
380
380
  * carries instead of two quoted identifiers.
381
381
  */
382
382
  private collectSortTerms;
383
+ /** A term the SELECT list projects is ordered by its alias, not computed twice, where the alias is in reach. */
384
+ private projectedSortTerm;
383
385
  /**
384
386
  * The `ORDER BY` operands for one key: a JSON path's in each of {@link jsonSortModes}. A key that is
385
387
  * not a field of `meta` - a `sql()` projection, a `$select` alias - is an output alias, which is never
@@ -399,7 +401,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
399
401
  */
400
402
  pager(ctx: QueryContext, opts: QueryPager, _sorted?: boolean): void;
401
403
  /** The engine's own refusal first, then what a lock over a join needs, which is SQL's alone. */
402
- assertLockSupported<E>(entity: Type<E>, q: Query<E>, joins?: QueryJoins): void;
404
+ assertLockSupported<E>(entity: AbstractType<E>, q: Query<E>, joins?: QueryJoins): void;
403
405
  /**
404
406
  * The lock as a hint on the table itself, which a `'tableHint'` dialect states instead of the
405
407
  * trailing clause {@link appendLock} emits. Empty everywhere else: `rowLocks.placement` is what
@@ -411,17 +413,17 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
411
413
  * joined: Postgres refuses a bare `FOR UPDATE` over the nullable side of an outer join outright,
412
414
  * and the other engines quietly widen the lock to the joined rows.
413
415
  */
414
- protected appendLock<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, joins?: QueryJoins, alias?: string): void;
416
+ protected appendLock<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, joins?: QueryJoins, alias?: string): void;
415
417
  /**
416
418
  * `COUNT(*)` over the filter, or over the rows a page settles. The clauses are read off `q` one by one:
417
419
  * `/http` hands it over untyped, and a smuggled `$sort` changes no count.
418
420
  */
419
- count<E>(ctx: QueryContext, entity: Type<E>, q: QueryPage<E>, opts?: QueryRenderOptions): void;
421
+ count<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryPage<E>, opts?: QueryRenderOptions): void;
420
422
  /**
421
423
  * How many rows a `$distinct` read returns: the deduplication runs after `COUNT(*)` and a window
422
424
  * alike, so the deduplicated set is counted as a derived table, never paged.
423
425
  */
424
- countDistinct<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: QueryRenderOptions): void;
426
+ countDistinct<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, opts?: QueryRenderOptions): void;
425
427
  /** `SELECT COUNT(*)` over the rows `rows` appends, as a derived table. */
426
428
  private countRows;
427
429
  /**
@@ -429,8 +431,8 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
429
431
  * keep one; the rest throw, because falling back to `COUNT(*)` would run exactly the scan the
430
432
  * caller reached for this to avoid, and only say so by taking a long time.
431
433
  */
432
- estimatedCount<E>(_ctx: QueryContext, _entity: Type<E>): void;
433
- aggregate<E>(ctx: QueryContext, entity: Type<E>, q: QueryAggregate<E>, opts?: QueryRenderOptions): readonly SelectTerm[];
434
+ estimatedCount<E>(_ctx: QueryContext, _entity: AbstractType<E>): void;
435
+ aggregate<E>(ctx: QueryContext, entity: AbstractType<E>, q: QueryAggregate<E>, opts?: QueryRenderOptions): readonly SelectTerm[];
434
436
  /**
435
437
  * What one entry reads: a grouped field, through the join its path passes, or an aggregate's argument,
436
438
  * narrowed by its own `$where` to `CASE WHEN … THEN … END`. Bare where it is a column or `'*'`.
@@ -461,12 +463,12 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
461
463
  */
462
464
  protected readonly totalOverExpr = "COUNT(*) OVER ()";
463
465
  /** A read, answering with the terms its rows answer under, which say how each reads back. */
464
- find<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: QueryRenderOptions, totalAlias?: string): readonly SelectTerm[];
466
+ find<E>(ctx: QueryContext, entity: AbstractType<E>, q?: Query<E>, opts?: QueryRenderOptions, totalAlias?: string): readonly SelectTerm[];
465
467
  /**
466
468
  * A read's whole statement. The lock is appended here rather than in `search`, which `count`,
467
469
  * `update` and `delete` share: it belongs to a SELECT alone, and every engine spells it last.
468
470
  */
469
- protected read<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts: ReadOptions, joins: QueryJoins, totalAlias?: string): ReadProjection;
471
+ protected read<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, opts: ReadOptions, joins: QueryJoins, totalAlias?: string): ReadProjection;
470
472
  /**
471
473
  * `opts` with the alias the read's table claims: its own name, which needs no alias written, unless
472
474
  * another table of the statement took it first.
@@ -477,7 +479,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
477
479
  * statement cannot return them, and on a composite key, which has no id to ask for.
478
480
  */
479
481
  protected insertedIdReturning<E>(meta: EntityMeta<E>): string;
480
- insert<E>(ctx: QueryContext, entity: Type<E>, payload: E | E[], opts?: QueryRenderOptions): void;
482
+ insert<E>(ctx: QueryContext, entity: AbstractType<E>, payload: E | E[], opts?: QueryRenderOptions): void;
481
483
  /**
482
484
  * What a text search matches and a fulltext index covers, which have to agree for the index to serve the
483
485
  * search: the columns themselves, where the engine indexes them as they are (MySQL's `MATCH (a, b)`).
@@ -491,11 +493,11 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
491
493
  * `INSERT INTO ... VALUES (...)`, or the engine's spelling of a row naming no column, and nothing more. The upsert
492
494
  * builders extend this rather than {@link insert}: their own clause has to come before the `RETURNING`.
493
495
  */
494
- protected appendInsertValues<E>(ctx: QueryContext, entity: Type<E>, payload: E | E[],
496
+ protected appendInsertValues<E>(ctx: QueryContext, entity: AbstractType<E>, payload: E | E[],
495
497
  /** Spliced between the target and its rows; see {@link returningPosition}. */
496
498
  afterTarget?: string): void;
497
499
  /** The columns an insert writes and the rows it writes, resolved once, and shared with a `MERGE`'s row source. */
498
- protected insertShape<E>(entity: Type<E>, payload: E | E[]): InsertShape<E>;
500
+ protected insertShape<E>(entity: AbstractType<E>, payload: E | E[]): InsertShape<E>;
499
501
  /** `(a, b), (c, d)` - the row constructor an INSERT and a MERGE source both write. */
500
502
  protected appendValueRows<E>(ctx: QueryContext, { payloads, keys, fields, kinds }: InsertShape<E>): void;
501
503
  /**
@@ -504,7 +506,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
504
506
  * it does not support the `DEFAULT` keyword inside `VALUES`.
505
507
  */
506
508
  protected appendDefaultInsertValue(ctx: QueryContext, _field: FieldOptions | undefined): void;
507
- update<E>(ctx: QueryContext, entity: Type<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryRenderOptions): void;
509
+ update<E>(ctx: QueryContext, entity: AbstractType<E>, q: QuerySearch<E>, payload: UpdatePayload<E>, opts?: QueryRenderOptions): void;
508
510
  /** What an update assigns: the payload's fields, `onUpdate` fills included. */
509
511
  private updateEntries;
510
512
  /**
@@ -544,12 +546,12 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
544
546
  * `INSERT ... ON CONFLICT ... DO UPDATE/NOTHING RETURNING`. The assignments are built before the insert
545
547
  * fills `onInsert` columns, which must stay out of them, and their values bound after it, where a `?` reads them.
546
548
  */
547
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
549
+ upsert<E>(ctx: QueryContext, entity: AbstractType<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
548
550
  /**
549
551
  * What an upsert of rows shaped as `row` assigns a row it finds: the values its assignments bind once per
550
552
  * statement beside its rows, and whether there are any, where none is `DO NOTHING`, which skips that row.
551
553
  */
552
- upsertAssignments<E>(entity: Type<E>, conflictPaths: QueryConflictPaths<E>, row: E, update?: UpdatePayload<E>): {
554
+ upsertAssignments<E>(entity: AbstractType<E>, conflictPaths: QueryConflictPaths<E>, row: E, update?: UpdatePayload<E>): {
553
555
  readonly binds: number;
554
556
  readonly assigns: boolean;
555
557
  };
@@ -573,7 +575,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
573
575
  /** What a found row takes by default: each payload column as the incoming row has it, and the `onUpdate` fills. */
574
576
  private conflictEntries;
575
577
  protected getUpsertConflictPathsStr<E>(meta: EntityMeta<E>, conflictPaths: QueryConflictPaths<E>): string;
576
- delete<E>(ctx: QueryContext, entity: Type<E>, q: QuerySearch<E>, opts?: QueryRenderOptions): void;
578
+ delete<E>(ctx: QueryContext, entity: AbstractType<E>, q: QuerySearch<E>, opts?: QueryRenderOptions): void;
577
579
  escapeId(val: string | undefined, forbidQualified?: boolean, addDot?: boolean): string;
578
580
  /**
579
581
  * A name behind its schema, each part escaped on its own rather than as one dotted string taken
@@ -672,7 +674,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
672
674
  * predicate with no entity filter applied; a migration's is `sql` reading none.
673
675
  */
674
676
  compileDdl(sql: QuerySql): string;
675
- compileDdl<E>(sql: EntityWhereMeta<E>, entity: Type<E>, opts?: DdlRenderOptions): string;
677
+ compileDdl<E>(sql: EntityWhereMeta<E>, entity: AbstractType<E>, opts?: DdlRenderOptions): string;
676
678
  getRawValue(ctx: QueryContext, opts: QuerySqlFnOptions & {
677
679
  value: QuerySql;
678
680
  }): void;
@@ -687,7 +689,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
687
689
  /** A path of the JSON in `escapedColumn`, `''` for the document itself, as its JSON value or its text. */
688
690
  protected abstract jsonPathReading(escapedColumn: string, path: string, mode: 'json' | 'text'): string;
689
691
  /**
690
- * A field key's mapped column (`@Field({ name })`), escaped, memoized per dialect instance: field
692
+ * A field key's mapped column (`.name()`), escaped, memoized per dialect instance: field
691
693
  * metadata is shared between dialects while this result is not, since `escapeIdChar` and the naming
692
694
  * strategy differ. Weakly keyed so a transient entity's metadata stays collectable.
693
695
  */
@@ -712,7 +714,7 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
712
714
  * A relation aggregate as the correlated subquery a `computed` field reads, the same one `$count`
713
715
  * emits: `(user) => user.resources.count()` renders here, wherever the field is named.
714
716
  */
715
- appendRelationAggregate<E>(ctx: QueryContext, entity: Type<E>, aggregate: RelationAggregateSpec, prefix: string): void;
717
+ appendRelationAggregate<E>(ctx: QueryContext, entity: AbstractType<E>, aggregate: RelationAggregateSpec, prefix: string): void;
716
718
  /**
717
719
  * The page a capped aggregate reads: an ordinary read of the related entity under its own alias,
718
720
  * narrowed to the parent's rows, carrying out the one column the aggregate runs over. Its `$sort`,
@@ -786,9 +788,9 @@ export declare abstract class AbstractSqlDialect extends VectorSqlDialect implem
786
788
  /** `'key', column, ...`: the arguments of a JSON object call over `pairs`. */
787
789
  protected jsonObjectArgs(pairs: DerivedRelation['pairs']): string;
788
790
  /** Filter by relation: a parent matches when {@link appendRelationSubquery} finds one target row. */
789
- protected compareRelation<E>(ctx: QueryContext, entity: Type<E>, relKey: string, val: QueryWhere<object>, rel: RelationMeta, opts: QueryComparisonOptions): void;
791
+ protected compareRelation<E>(ctx: QueryContext, entity: AbstractType<E>, relKey: string, val: QueryWhere<object>, rel: RelationMeta, opts: QueryComparisonOptions): void;
790
792
  /** Filter by relation size: the same subquery, counting instead of testing for existence. */
791
- protected compareRelationSize<E>(ctx: QueryContext, entity: Type<E>, relKey: string, sizeVal: number | QuerySizeComparisonOps, rel: RelationMeta, opts: QueryComparisonOptions): void;
793
+ protected compareRelationSize<E>(ctx: QueryContext, entity: AbstractType<E>, relKey: string, sizeVal: number | QuerySizeComparisonOps, rel: RelationMeta, opts: QueryComparisonOptions): void;
792
794
  /**
793
795
  * `<expr> <op> <value>` for each bound, `AND`-joined. `expr` is spelled once per bound because it is an
794
796
  * expression, not a column: a `WHERE` has no output alias to refer back to. A count for `$size`, a
@@ -1,6 +1,6 @@
1
1
  import { fieldOf, getMeta, relationOf } from '../entity/index.js';
2
2
  import { soleId, valueFieldOf } from '../entity/metadata/definition.js';
3
- import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, RAW_ALIAS, } from '../type/index.js';
3
+ import { COUNT_RESULT_KEY, parseQueryLock, QuerySql, renderSql, RAW_ALIAS, } from '../type/index.js';
4
4
  import { utcTimestamp } from '../util/date.js';
5
5
  import { ancestorPaths, isExactDecimal, isInlinedExpression, jsonPathKeys } from '../util/field.util.js';
6
6
  import { isAutoIncrement, RETURNED_ID, isSelectList, assertNonNegativeInteger, assertNoUndefined, assertWhere, definedEntries, escapeSqlId, fillOnFields, filterFieldKeys, getInsertFieldKeys, getKeys, getRelationRequestSummary, deletionOf, hasKeys, idOnlyQuery, keySet, whereAnd, columnFamily, fieldFamily, countedRelations, fieldUpdateOf, fulltextIndexOver, fulltextWeights, isFieldUpdateOp, isJsonObject, isJsonUpdateOp, foldJson, writesKeys, isOperatorMap, isOperatorKey, isVectorSearch, normalizeScalarFieldSelection, parentJoins, rankedTextSearch, targetJoins, textSearchFields, textSortOf, textWeightSteps, parseGroupMap, parseRelationAtKey, parseRelationSize, parseSortDirection, populatesRelations, aggregateOf, sql, refs, columnRef, throwUnknownAggregateColumn, upsertAssigned, } from '../util/index.js';
@@ -21,13 +21,13 @@ export function relationTermKey({ sql, key }) {
21
21
  return orRefuse(key, `a raw $select in a populated relation needs an alias, the key its value lands under: ${sql}`);
22
22
  }
23
23
  /**
24
- * What a projection reads: its raw expressions, or its fields past any `$exclude`, and every field where
25
- * none is left of a row crossing JSON, which answers only under keys.
24
+ * What a projection reads: its raw expressions, or the fields its map selects, and every field where none is
25
+ * left of a row crossing JSON, which answers only under keys.
26
26
  */
27
- function projectedKeys(meta, select, exclude, json) {
27
+ function projectedKeys(meta, select, json) {
28
28
  const selected = isSelectList(select)
29
29
  ? select.map(selectRaw)
30
- : normalizeScalarFieldSelection(meta, select, exclude);
30
+ : normalizeScalarFieldSelection(meta, select);
31
31
  return selected.length || !json ? selected : normalizeScalarFieldSelection(meta);
32
32
  }
33
33
  /** An item of a `$select` list, which only `sql()` fills: anything else arrived from an untyped client. */
@@ -257,9 +257,9 @@ export class AbstractSqlDialect extends VectorSqlDialect {
257
257
  * joined row keeps its key, every column of a composite past any subtraction: it is what tells a
258
258
  * matched row from no match.
259
259
  */
260
- selectTerms(ctx, entity, select, opts = {}, exclude) {
260
+ selectTerms(ctx, entity, select, opts = {}) {
261
261
  const meta = getMeta(entity);
262
- const selected = projectedKeys(meta, select, exclude, opts.json);
262
+ const selected = projectedKeys(meta, select, opts.json);
263
263
  const missingIds = opts.joined ? meta.ids.filter((key) => !selected.includes(key)) : [];
264
264
  const keys = missingIds.length ? [...missingIds, ...selected] : selected;
265
265
  if (!keys.length) {
@@ -318,7 +318,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
318
318
  appendTextRank(ctx, meta, search, prefix) {
319
319
  const keys = textSearchFields(meta, search);
320
320
  const index = fulltextIndexOver(meta, keys);
321
- const weights = index && fulltextWeights({ type: index.type, entries: index.columns });
321
+ const weights = index && fulltextWeights(index);
322
322
  if (!weights) {
323
323
  this.appendTextScore(ctx, meta, search, keys, prefix);
324
324
  return;
@@ -376,7 +376,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
376
376
  const parent = opts.prefix ?? this.resolveTableAlias(meta);
377
377
  const distinct = !!q.$distinct;
378
378
  return [
379
- ...this.selectTerms(ctx, entity, q.$select, opts, q.$exclude),
379
+ ...this.selectTerms(ctx, entity, q.$select, opts),
380
380
  ...this.selectJoinedRows(ctx, joins, opts.json, distinct),
381
381
  ...this.selectToManyRelations(ctx, meta, q.$populate, parent, distinct),
382
382
  ...this.selectRelationCounts(ctx, meta, q.$count, parent),
@@ -393,15 +393,14 @@ export class AbstractSqlDialect extends VectorSqlDialect {
393
393
  }
394
394
  /** What a `$sort` projects, each under the name it asked for: a vector's distance, the `$text` relevance. */
395
395
  selectSortProjections(ctx, meta, q, prefix) {
396
- const distances = Object.entries(q.$sort ?? {}).flatMap(([key, value]) => isVectorSearch(value) && value.$project
396
+ const score = textSortOf(q.$sort)?.project;
397
+ return Object.entries(q.$sort ?? {}).flatMap(([key, value]) => isVectorSearch(value) && value.$project !== undefined
397
398
  ? [
398
399
  this.sortProjection(ctx, meta, value.$project, (fragmentCtx) => this.appendVectorDistance(fragmentCtx, meta, key, value, prefix)),
399
400
  ]
400
- : []);
401
- const score = textSortOf(q.$sort)?.project;
402
- return score
403
- ? [...distances, this.sortProjection(ctx, meta, score, this.textRanker(meta, q.$where, prefix))]
404
- : distances;
401
+ : key === '$text' && score !== undefined
402
+ ? [this.sortProjection(ctx, meta, score, this.textRanker(meta, q.$where, prefix))]
403
+ : []);
405
404
  }
406
405
  sortProjection(ctx, meta, alias, build) {
407
406
  this.assertProjectable(meta, alias);
@@ -461,7 +460,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
461
460
  continue;
462
461
  const opts = { prefix: join.alias, json, joined: true };
463
462
  const row = [
464
- ...this.selectTerms(ctx, join.entity, join.query.$select, opts, join.query.$exclude),
463
+ ...this.selectTerms(ctx, join.entity, join.query.$select, opts),
465
464
  ...this.selectToManyRelations(ctx, join.meta, join.query.$populate, join.alias, distinct),
466
465
  ];
467
466
  const [idKey] = join.meta.ids;
@@ -882,7 +881,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
882
881
  /**
883
882
  * Walks `$sort` against the metadata of the entity each level addresses, rather than flattening it
884
883
  * to dotted strings and reading every key off the root: only that way does a related column resolve
885
- * through its own `@Field({ name })`, and only that way is `tax.category` the one alias the join
884
+ * through its own `.name()`, and only that way is `tax.category` the one alias the join
886
885
  * carries instead of two quoted identifiers.
887
886
  */
888
887
  collectSortTerms(ctx, meta, sort, opts, vectors, columns, path = '',
@@ -895,10 +894,12 @@ export class AbstractSqlDialect extends VectorSqlDialect {
895
894
  if (path) {
896
895
  throw new UqlUsageError(`$sort by $text is only supported on the queried entity, not on relation '${path}'`);
897
896
  }
898
- // Where projected in the SELECT list, ordered by that alias rather than scored twice.
899
897
  const { order, project } = textSortOf(sort);
900
- const expr = project ? this.escapeId(project) : this.buildFragment(ctx, opts.rankText);
901
- columns.push({ key, expr, ...parseSortDirection(order), output: project !== undefined });
898
+ columns.push({
899
+ key,
900
+ ...this.projectedSortTerm(ctx, project, opts, opts.rankText),
901
+ ...parseSortDirection(order),
902
+ });
902
903
  continue;
903
904
  }
904
905
  if (relation) {
@@ -931,14 +932,10 @@ export class AbstractSqlDialect extends VectorSqlDialect {
931
932
  continue;
932
933
  }
933
934
  if (isVectorSearch(value)) {
934
- // Already projected in the SELECT list: order by that alias rather than recomputing it.
935
- vectors.push(value.$project
936
- ? { key: keyPath, expr: this.escapeId(value.$project), output: true }
937
- : {
938
- key: keyPath,
939
- expr: this.buildFragment(ctx, (fragmentCtx) => this.appendVectorDistance(fragmentCtx, meta, key, value, prefix)),
940
- output: false,
941
- });
935
+ vectors.push({
936
+ key: keyPath,
937
+ ...this.projectedSortTerm(ctx, value.$project, opts, (fragmentCtx) => this.appendVectorDistance(fragmentCtx, meta, key, value, prefix)),
938
+ });
942
939
  continue;
943
940
  }
944
941
  const order = parseSortDirection(value);
@@ -948,6 +945,12 @@ export class AbstractSqlDialect extends VectorSqlDialect {
948
945
  });
949
946
  }
950
947
  }
948
+ /** A term the SELECT list projects is ordered by its alias, not computed twice, where the alias is in reach. */
949
+ projectedSortTerm(ctx, project, opts, compute) {
950
+ return project !== undefined && !opts.unaliased
951
+ ? { expr: this.escapeId(project), output: true }
952
+ : { expr: this.buildFragment(ctx, compute), output: false };
953
+ }
951
954
  /**
952
955
  * The `ORDER BY` operands for one key: a JSON path's in each of {@link jsonSortModes}. A key that is
953
956
  * not a field of `meta` - a `sql()` projection, a `$select` alias - is an output alias, which is never
@@ -1818,7 +1821,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1818
1821
  compileDdl(sql, entity, { rows, escapedPrefix, operand } = {}) {
1819
1822
  const ctx = this.createContext({ inlineValues: true });
1820
1823
  if (sql instanceof QuerySql) {
1821
- sql.render({ ctx, dialect: this, prefix: '', escapedPrefix: escapedPrefix ?? '', entity, rows });
1824
+ renderSql(sql, { ctx, dialect: this, prefix: '', escapedPrefix: escapedPrefix ?? '', entity, rows });
1822
1825
  }
1823
1826
  else if (entity) {
1824
1827
  assertNoUndefined(sql, `a predicate over '${entity.name}'`);
@@ -1834,7 +1837,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1834
1837
  }
1835
1838
  getRawValue(ctx, opts) {
1836
1839
  const { value, prefix = '', escapedPrefix } = opts;
1837
- value.render({
1840
+ renderSql(value, {
1838
1841
  ...opts,
1839
1842
  ctx,
1840
1843
  dialect: this,
@@ -1868,7 +1871,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
1868
1871
  : this.jsonPathReading(escapedColumn, path, mode);
1869
1872
  }
1870
1873
  /**
1871
- * A field key's mapped column (`@Field({ name })`), escaped, memoized per dialect instance: field
1874
+ * A field key's mapped column (`.name()`), escaped, memoized per dialect instance: field
1872
1875
  * metadata is shared between dialects while this result is not, since `escapeIdChar` and the naming
1873
1876
  * strategy differ. Weakly keyed so a transient entity's metadata stays collectable.
1874
1877
  */
@@ -2044,7 +2047,7 @@ export class AbstractSqlDialect extends VectorSqlDialect {
2044
2047
  if (!query.$distinct || !query.$sort) {
2045
2048
  return;
2046
2049
  }
2047
- const selected = projectedKeys(meta, query.$select, query.$exclude, true);
2050
+ const selected = projectedKeys(meta, query.$select, true);
2048
2051
  for (const key of getKeys(query.$sort)) {
2049
2052
  if (!selected.includes(key)) {
2050
2053
  throw new UqlUsageError(`cannot $sort the $distinct relation '${relKey}' by '${key}', which it does not select`);
@@ -37,6 +37,8 @@ export declare const CURSOR_ALIAS = "_uql_cursor";
37
37
  export declare const OUTPUT_TABLE = "@_uql_output";
38
38
  /** The field a MongoDB `$sort` by `$text` reads `textScore` from where it projects none, taken back out after. */
39
39
  export declare const TEXT_SCORE_ALIAS = "_uql_text_score";
40
+ /** A relation's row's distance from the vector its `$sort` ranks by, where it projects none. */
41
+ export declare const NEAREST_DISTANCE_ALIAS = "_uql_nearest";
40
42
  /**
41
43
  * The field a MongoDB `$sort` placing nulls orders by first: 1 where the value is null or missing, 0
42
44
  * where it is not. MongoDB takes no `NULLS FIRST`, so the placement is this flag plus the sort on it.
@@ -38,6 +38,8 @@ export const CURSOR_ALIAS = `${OWNED_PREFIX}_cursor`;
38
38
  export const OUTPUT_TABLE = `@${OWNED_PREFIX}_output`;
39
39
  /** The field a MongoDB `$sort` by `$text` reads `textScore` from where it projects none, taken back out after. */
40
40
  export const TEXT_SCORE_ALIAS = `${OWNED_PREFIX}_text_score`;
41
+ /** A relation's row's distance from the vector its `$sort` ranks by, where it projects none. */
42
+ export const NEAREST_DISTANCE_ALIAS = `${OWNED_PREFIX}_nearest`;
41
43
  /**
42
44
  * The field a MongoDB `$sort` placing nulls orders by first: 1 where the value is null or missing, 0
43
45
  * where it is not. MongoDB takes no `NULLS FIRST`, so the placement is this flag plus the sort on it.
@@ -1,5 +1,5 @@
1
1
  import { isOperatorMap } from '../util/dialect.util.js';
2
- import { columnFamily, jsonPathKeys } from '../util/field.util.js';
2
+ import { columnFamily, declaresNotNull, jsonPathKeys } from '../util/field.util.js';
3
3
  import { isOperatorKey, someKey } from '../util/object.util.js';
4
4
  import { JSON_SKIP_KEY } from './aliases.js';
5
5
  /**
@@ -60,7 +60,7 @@ export function jsonSetCall(bindValue, target, entries, maxArgs) {
60
60
  * `JSON_SET`'s input.
61
61
  */
62
62
  export function jsonSetTarget(expr, field, empty) {
63
- return field?.nullable === false ? expr : `COALESCE(${expr}, ${empty})`;
63
+ return field && declaresNotNull(field) ? expr : `COALESCE(${expr}, ${empty})`;
64
64
  }
65
65
  /** `JSON_REMOVE(expr, path, ...)`, which MySQL and SQLite share, nested past `maxArgs`. */
66
66
  export function jsonRemoveCall(expr, keys, maxArgs) {
@@ -1,4 +1,4 @@
1
- import type { EntityMeta, QueryConflictPaths, QueryContext, QueryPager, TriggerRows, Type, UpdatePayload } from '../type/index.js';
1
+ import type { EntityMeta, QueryConflictPaths, QueryContext, QueryPager, TriggerRows, AbstractType, UpdatePayload } from '../type/index.js';
2
2
  import { AbstractSqlDialect } from './abstractSqlDialect.js';
3
3
  /** What SQL Server and Oracle share: paging and upsert spelled as the standard does. */
4
4
  export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
@@ -12,7 +12,7 @@ export declare abstract class MergeSqlDialect extends AbstractSqlDialect {
12
12
  * assignments bind their values before the rows, though they follow them in the SQL; this works only because
13
13
  * SQL Server numbers each placeholder (`@p1`).
14
14
  */
15
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
15
+ upsert<E>(ctx: QueryContext, entity: AbstractType<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
16
16
  /** A trigger's upsert as a `MERGE` of the rows it was handed, `SELECT`ed off them as its source. */
17
17
  protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, conflictPaths: QueryConflictPaths<E>, entries: readonly [string, unknown][], assignments: string, rows?: TriggerRows): void;
18
18
  /**
@@ -1,4 +1,4 @@
1
- import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, Type, UpdatePayload, TransactionOptions } from '../type/index.js';
1
+ import type { EntityMeta, InsertIdSource, Query, QueryConflictPaths, QueryContext, QueryOptions, QueryTextSearchOptions, RowLockFeatures, SqlDialectFeatures, SqlDialectName, SqlValues, AbstractType, UpdatePayload, TransactionOptions } from '../type/index.js';
2
2
  import { AbstractSqlDialect, type DerivedRelation, type RelationRows, type SelectTerm } from './abstractSqlDialect.js';
3
3
  import { type JsonContainer, type JsonSlot } from './jsonSql.js';
4
4
  /** Declared apart so MariaDB, which has no `FOR UPDATE OF`, can restate that one part of it. */
@@ -17,7 +17,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
17
17
  * anything has been analyzed. `DATABASE()` where the entity names no schema, so the estimate comes
18
18
  * from the connection's own database rather than a same-named table in another one.
19
19
  */
20
- estimatedCount<E>(ctx: QueryContext, entity: Type<E>): void;
20
+ estimatedCount<E>(ctx: QueryContext, entity: AbstractType<E>): void;
21
21
  protected readonly unboundedLimit: string;
22
22
  /** Case-sensitive, as on every other engine, where the column's collation would fold it. */
23
23
  protected regexCondition(operand: string, placeholder: string): string;
@@ -30,7 +30,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
30
30
  readonly sqlValues: SqlValues;
31
31
  readonly insertIdSource: InsertIdSource;
32
32
  /** `INSERT ... ON DUPLICATE KEY UPDATE`, the assignments bound after the insert, where a `?` reads them. */
33
- upsert<E>(ctx: QueryContext, entity: Type<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
33
+ upsert<E>(ctx: QueryContext, entity: AbstractType<E>, conflictPaths: QueryConflictPaths<E>, payload: E | E[], update?: UpdatePayload<E>): void;
34
34
  protected appendTriggerUpsert<E>(ctx: QueryContext, meta: EntityMeta<E>, _conflictPaths: QueryConflictPaths<E>, entries: readonly [string, unknown][], assignments: string): void;
35
35
  /**
36
36
  * `insert` on a duplicate key: `ON DUPLICATE KEY UPDATE` with the new row named, or `INSERT IGNORE` where there
@@ -54,15 +54,15 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
54
54
  */
55
55
  protected appendRelationArray(ctx: QueryContext, rows: RelationRows): readonly SelectTerm[];
56
56
  /** A read's statement, with the settings it needs applied to it alone. */
57
- find<E>(ctx: QueryContext, entity: Type<E>, q?: Query<E>, opts?: QueryOptions, totalAlias?: string): readonly SelectTerm[];
57
+ find<E>(ctx: QueryContext, entity: AbstractType<E>, q?: Query<E>, opts?: QueryOptions, totalAlias?: string): readonly SelectTerm[];
58
58
  /** A `$distinct` read's count, which reads the relations the read does. */
59
- countDistinct<E>(ctx: QueryContext, entity: Type<E>, q: Query<E>, opts?: QueryOptions): void;
59
+ countDistinct<E>(ctx: QueryContext, entity: AbstractType<E>, q: Query<E>, opts?: QueryOptions): void;
60
60
  private settled;
61
61
  /**
62
62
  * `name=value` for each variable a read's statement sets for itself alone. `GROUP_CONCAT`, and
63
63
  * MariaDB's `JSON_ARRAYAGG` built on it, cut a relation's array at `group_concat_max_len`.
64
64
  */
65
- protected statementSettings<E>(entity: Type<E>, q: Query<E>): string[];
65
+ protected statementSettings<E>(entity: AbstractType<E>, q: Query<E>): string[];
66
66
  /** `sql` with `settings` scoped to it, in this engine's spelling. */
67
67
  protected abstract applySettings(sql: string, settings: readonly string[]): string;
68
68
  /** `JSON_OBJECT` of each key and its value. */
@@ -84,7 +84,7 @@ export declare abstract class MysqlLikeSqlDialect extends AbstractSqlDialect {
84
84
  /**
85
85
  * `MATCH(cols) AGAINST(?)`, which needs a `FULLTEXT` index over exactly those columns: without one
86
86
  * the server answers "Can't find FULLTEXT index matching the column list". Declare it with
87
- * `@Index((post) => [...], { type: 'fulltext' })`.
87
+ * `{ columns: (post) => [...], type: 'fulltext' }` in `indexes`.
88
88
  */
89
89
  protected appendTextSearch<E>(ctx: QueryContext, meta: EntityMeta<E>, search: QueryTextSearchOptions<E>, prefix: string | undefined): void;
90
90
  /**
@@ -202,7 +202,7 @@ export class MysqlLikeSqlDialect extends AbstractSqlDialect {
202
202
  /**
203
203
  * `MATCH(cols) AGAINST(?)`, which needs a `FULLTEXT` index over exactly those columns: without one
204
204
  * the server answers "Can't find FULLTEXT index matching the column list". Declare it with
205
- * `@Index((post) => [...], { type: 'fulltext' })`.
205
+ * `{ columns: (post) => [...], type: 'fulltext' }` in `indexes`.
206
206
  */
207
207
  appendTextSearch(ctx, meta, search, prefix) {
208
208
  this.appendTextScore(ctx, meta, search, textSearchFields(meta, search), prefix);
@@ -1,6 +1,7 @@
1
1
  import { QuerySql, VECTOR_QUERY_KEYS, } from '../type/index.js';
2
2
  import { isOperatorMap } from '../util/dialect.util.js';
3
3
  import { getKeys, hasKeys, isWhereMap, someKey } from '../util/object.util.js';
4
+ import { escapeRegExp } from '../util/string.util.js';
4
5
  import { kindOf, UqlUsageError } from '../util/uqlError.js';
5
6
  /**
6
7
  * How each grouping operator renders: the operator joining its clauses, and whether the group is
@@ -169,7 +170,7 @@ export function likePattern(pattern) {
169
170
  * The end anchor is `\z`, since `$` also matches before a trailing newline.
170
171
  */
171
172
  export function likeRegex(pattern) {
172
- const tokens = likeTokens(pattern).map(({ char, escaped }) => (escaped ? undefined : LIKE_WILDCARDS[char]) ?? escapeRegex(char));
173
+ const tokens = likeTokens(pattern).map(({ char, escaped }) => (escaped ? undefined : LIKE_WILDCARDS[char]) ?? escapeRegExp(char));
173
174
  const open = tokens[0] === LIKE_WILDCARDS['%'];
174
175
  const closed = tokens.at(-1) !== LIKE_WILDCARDS['%'];
175
176
  const body = tokens.slice(open ? 1 : 0, closed ? undefined : -1).join('');
@@ -184,9 +185,6 @@ function likeTokens(pattern) {
184
185
  }
185
186
  /** Each `$like` wildcard as the regex matching it, across lines as SQL does. */
186
187
  const LIKE_WILDCARDS = { '%': String.raw `[\s\S]*`, _: String.raw `[\s\S]` };
187
- function escapeRegex(char) {
188
- return char.replace(/[\\^$.*+?()[\]{}|]/, '\\$&');
189
- }
190
188
  /**
191
189
  * Every `$like`-family operator: the pattern it wraps its value in, and whether it ignores case.
192
190
  * Each case-sensitive operator is paired here with the `$i` twin that shares its pattern, so the
@@ -1,4 +1,4 @@
1
- import type { EntityMeta, FieldMeta, Query, QueryGroupMap, QuerySortMap, QueryWhere, RelationAggregateSpec, RelationMeta, RelationQuery, Type } from '../type/index.js';
1
+ import type { EntityMeta, FieldMeta, Query, QueryGroupMap, QuerySortMap, QueryWhere, RelationAggregateSpec, RelationMeta, RelationQuery, AbstractType } from '../type/index.js';
2
2
  import { type ParsedGroupEntry } from '../util/index.js';
3
3
  /**
4
4
  * One relation a statement joins, keyed by the alias its columns are addressed by (`tax`,
@@ -12,7 +12,7 @@ export type QueryJoin = {
12
12
  readonly path: string;
13
13
  /** The alias the statement reads it through: its path, unless another table of the statement took it. */
14
14
  readonly alias: string;
15
- readonly entity: Type<object>;
15
+ readonly entity: AbstractType<object>;
16
16
  readonly meta: EntityMeta<object>;
17
17
  readonly relation: RelationMeta;
18
18
  readonly query: RelationQuery;
@@ -33,6 +33,8 @@ export type QuerySortOptions = {
33
33
  /** Alias the queried entity's own columns are qualified by, when the statement qualifies them. */
34
34
  readonly prefix?: string;
35
35
  readonly joins?: QueryJoins;
36
+ /** Where the select list's aliases are out of reach, inside an aggregate: a projected term is computed again. */
37
+ readonly unaliased?: boolean;
36
38
  };
37
39
  /**
38
40
  * What the statement joins, from `$populate` and from a `$sort` by a to-one relation's field, so the