uql-orm 0.104.1 → 0.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +24 -10
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +7 -7
  4. package/dist/dialect/abstractSqlDialect.d.ts +6 -4
  5. package/dist/dialect/abstractSqlDialect.js +35 -32
  6. package/dist/dialect/aliases.d.ts +2 -0
  7. package/dist/dialect/aliases.js +2 -0
  8. package/dist/dialect/jsonSql.js +2 -2
  9. package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
  10. package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
  11. package/dist/dialect/operators.js +2 -4
  12. package/dist/dialect/queryJoins.d.ts +2 -0
  13. package/dist/dialect/vectorSqlDialect.d.ts +1 -1
  14. package/dist/dialect/vectorSqlDialect.js +1 -1
  15. package/dist/entity/column.d.ts +3 -0
  16. package/dist/entity/column.js +3 -0
  17. package/dist/entity/columnOptionsBuilder.d.ts +54 -0
  18. package/dist/entity/columnOptionsBuilder.js +108 -0
  19. package/dist/entity/decorator/bag.d.ts +4 -4
  20. package/dist/entity/decorator/entity.d.ts +2 -19
  21. package/dist/entity/decorator/entity.js +3 -37
  22. package/dist/entity/decorator/members.d.ts +46 -76
  23. package/dist/entity/decorator/members.js +18 -7
  24. package/dist/entity/index.d.ts +2 -1
  25. package/dist/entity/index.js +2 -1
  26. package/dist/entity/metadata/definition.d.ts +10 -24
  27. package/dist/entity/metadata/definition.js +329 -147
  28. package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
  29. package/dist/entity/metadata/schemaFixture/animal.js +7 -0
  30. package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
  31. package/dist/entity/metadata/schemaFixture/author.js +25 -0
  32. package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
  33. package/dist/entity/metadata/schemaFixture/book.js +22 -0
  34. package/dist/http/query.js +12 -13
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +2 -1
  37. package/dist/mariadb/mariaDialect.js +1 -1
  38. package/dist/mariadb/mariadbQuerier.js +1 -3
  39. package/dist/migrate/builder/columnBuilder.d.ts +20 -68
  40. package/dist/migrate/builder/columnBuilder.js +104 -110
  41. package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
  42. package/dist/migrate/builder/migrationBuilder.js +7 -6
  43. package/dist/migrate/builder/tableBuilder.d.ts +3 -55
  44. package/dist/migrate/builder/tableBuilder.js +88 -204
  45. package/dist/migrate/builder/types.d.ts +52 -151
  46. package/dist/migrate/builder/types.js +0 -6
  47. package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
  49. package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
  50. package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
  51. package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
  52. package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
  53. package/dist/migrate/ddl/defaultSql.js +7 -6
  54. package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
  55. package/dist/migrate/ddl/indexCapabilities.js +26 -13
  56. package/dist/migrate/ddl/indexDdl.d.ts +13 -13
  57. package/dist/migrate/ddl/indexDdl.js +33 -30
  58. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
  59. package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
  60. package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
  61. package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
  62. package/dist/migrate/drift/driftDetector.js +2 -2
  63. package/dist/migrate/generator/definitionToNode.d.ts +8 -2
  64. package/dist/migrate/generator/definitionToNode.js +4 -5
  65. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
  66. package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
  67. package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
  68. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
  69. package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
  70. package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
  71. package/dist/migrate/introspection/postgresIntrospector.js +3 -4
  72. package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
  73. package/dist/migrate/introspection/tableSchemaAST.js +5 -1
  74. package/dist/migrate/schemaChange.d.ts +3 -3
  75. package/dist/migrate/schemaChange.js +3 -2
  76. package/dist/migrate/schemaGenerator.js +1 -1
  77. package/dist/migrate/storage/databaseStorage.js +4 -4
  78. package/dist/mongodb/mongoDialect.d.ts +33 -36
  79. package/dist/mongodb/mongoDialect.js +118 -32
  80. package/dist/mongodb/mongoIntrospector.d.ts +3 -1
  81. package/dist/mongodb/mongoIntrospector.js +11 -5
  82. package/dist/mongodb/mongoSchemaGenerator.js +35 -27
  83. package/dist/mongodb/mongodbQuerier.d.ts +1 -11
  84. package/dist/mongodb/mongodbQuerier.js +9 -43
  85. package/dist/querier/abstractQuerier.d.ts +0 -1
  86. package/dist/querier/abstractQuerier.js +1 -20
  87. package/dist/querier/keyset.js +3 -3
  88. package/dist/schema/declaredColumn.d.ts +11 -0
  89. package/dist/schema/declaredColumn.js +21 -0
  90. package/dist/schema/indexColumns.d.ts +0 -3
  91. package/dist/schema/indexColumns.js +11 -7
  92. package/dist/schema/indexDifferences.d.ts +10 -5
  93. package/dist/schema/indexDifferences.js +42 -28
  94. package/dist/schema/schemaASTBuilder.js +28 -36
  95. package/dist/schema/schemaASTDiffer.js +8 -4
  96. package/dist/schema/sqlExpression.d.ts +21 -17
  97. package/dist/schema/sqlExpression.js +11 -23
  98. package/dist/type/column.d.ts +328 -0
  99. package/dist/type/column.js +2 -0
  100. package/dist/type/config.d.ts +1 -1
  101. package/dist/type/dialect.d.ts +2 -1
  102. package/dist/type/dialect.js +1 -0
  103. package/dist/type/entity.d.ts +290 -279
  104. package/dist/type/entity.js +6 -1
  105. package/dist/type/index.d.ts +2 -0
  106. package/dist/type/index.js +2 -0
  107. package/dist/type/migration.d.ts +5 -5
  108. package/dist/type/query.d.ts +44 -40
  109. package/dist/type/query.js +2 -3
  110. package/dist/type/queryAggregate.d.ts +22 -12
  111. package/dist/type/querySql.d.ts +20 -4
  112. package/dist/type/querySql.js +27 -9
  113. package/dist/type/schemaEntity.d.ts +190 -0
  114. package/dist/type/schemaEntity.js +1 -0
  115. package/dist/type/utility.d.ts +0 -6
  116. package/dist/type/vector.d.ts +1 -1
  117. package/dist/util/ddlExpression.util.d.ts +12 -13
  118. package/dist/util/ddlExpression.util.js +12 -21
  119. package/dist/util/dialect.util.d.ts +11 -5
  120. package/dist/util/dialect.util.js +31 -37
  121. package/dist/util/field.util.d.ts +10 -9
  122. package/dist/util/field.util.js +14 -10
  123. package/dist/util/fieldOption.util.d.ts +11 -95
  124. package/dist/util/fieldOption.util.js +49 -16
  125. package/dist/util/hook.util.d.ts +2 -14
  126. package/dist/util/hook.util.js +3 -16
  127. package/dist/util/index.d.ts +1 -0
  128. package/dist/util/index.js +1 -0
  129. package/dist/util/indexEntry.util.d.ts +45 -0
  130. package/dist/util/indexEntry.util.js +138 -0
  131. package/dist/util/relationQuery.util.d.ts +0 -1
  132. package/dist/util/relationQuery.util.js +0 -5
  133. package/dist/util/sql.d.ts +10 -7
  134. package/dist/util/sql.js +34 -16
  135. package/dist/util/sql.util.d.ts +4 -5
  136. package/dist/util/sql.util.js +7 -16
  137. package/dist/util/string.util.d.ts +2 -0
  138. package/dist/util/string.util.js +4 -0
  139. package/dist/util/uqlError.d.ts +1 -1
  140. package/dist/util/uqlError.js +1 -1
  141. package/package.json +1 -1
  142. package/skills/uql-orm/SKILL.md +76 -25
  143. package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
@@ -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) {
@@ -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
@@ -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
@@ -31,7 +31,7 @@ export declare abstract class VectorSqlDialect extends AbstractDialect {
31
31
  /** Whether this engine has a vector index: the one a metric's `index` names. */
32
32
  hasVectorIndex(): boolean;
33
33
  /** The distance a vector index built for `metric`, as {@link vectorMetrics} names it for an index, measures. */
34
- indexedDistance(metric: string | undefined): VectorDistance | undefined;
34
+ distanceOfMetric(metric: string | undefined): VectorDistance | undefined;
35
35
  /** Quotes an identifier; supplied by the SQL dialect built on top of this layer. */
36
36
  abstract escapeId(val: string | undefined, forbidQualified?: boolean, addDot?: boolean): string;
37
37
  /** What a distance expression reads, for a `$sort` and a `$near` alike. */
@@ -46,7 +46,7 @@ export class VectorSqlDialect extends AbstractDialect {
46
46
  return [...this.vectorMetrics.values()].some((metric) => metric.index);
47
47
  }
48
48
  /** The distance a vector index built for `metric`, as {@link vectorMetrics} names it for an index, measures. */
49
- indexedDistance(metric) {
49
+ distanceOfMetric(metric) {
50
50
  return [...this.vectorMetrics].find(([, { index }]) => index === metric)?.[0];
51
51
  }
52
52
  /** What a distance expression reads, for a `$sort` and a `$near` alike. */
@@ -0,0 +1,3 @@
1
+ import type { ColumnFactory } from '../type/index.js';
2
+ /** Declares a column, `f.string()`, its options chained: `f.number().nullable().default(0)`. See the entities guide. */
3
+ export declare const f: ColumnFactory;
@@ -0,0 +1,3 @@
1
+ import { columns } from './columnOptionsBuilder.js';
2
+ /** Declares a column, `f.string()`, its options chained: `f.number().nullable().default(0)`. See the entities guide. */
3
+ export const f = columns;
@@ -0,0 +1,54 @@
1
+ import type { ForeignKeyAction } from '../schema/types.js';
2
+ import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type JsonShape, type OnFieldCallback, type QuerySql, type StampEvent, type Type, type VectorDistance } from '../type/index.js';
3
+ /**
4
+ * Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
5
+ * `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
6
+ */
7
+ export declare class ColumnOptionsBuilder {
8
+ readonly [COLUMN_OPTIONS]: FieldOptions;
9
+ constructor(options: FieldOptions);
10
+ with(options: FieldOptions): ColumnOptionsBuilder;
11
+ nullable(): ColumnOptionsBuilder;
12
+ id(): ColumnOptionsBuilder;
13
+ default(defaultValue: FieldOptions['defaultValue']): ColumnOptionsBuilder;
14
+ onInsert(onInsert: OnFieldCallback): ColumnOptionsBuilder;
15
+ onUpdate(onUpdate: OnFieldCallback): ColumnOptionsBuilder;
16
+ updatable(updatable: false): ColumnOptionsBuilder;
17
+ softDelete(softDelete?: OnFieldCallback): ColumnOptionsBuilder;
18
+ unique(): ColumnOptionsBuilder;
19
+ index(index?: string | false): ColumnOptionsBuilder;
20
+ name(name: string): ColumnOptionsBuilder;
21
+ comment(comment: string): ColumnOptionsBuilder;
22
+ eager(eager: false): ColumnOptionsBuilder;
23
+ columnType(columnType: ColumnType): ColumnOptionsBuilder;
24
+ columnType(columnType: QuerySql): ColumnOptionsBuilder;
25
+ references(references: () => Type<object>): ColumnOptionsBuilder;
26
+ onDelete(onDelete: ForeignKeyAction): ColumnOptionsBuilder;
27
+ narrow(): ColumnOptionsBuilder;
28
+ as(computed: QuerySql): ColumnOptionsBuilder;
29
+ stored(events?: readonly StampEvent[]): ColumnOptionsBuilder;
30
+ precision(precision: number): ColumnOptionsBuilder;
31
+ scale(scale: number): ColumnOptionsBuilder;
32
+ autoIncrement(autoIncrement?: boolean): ColumnOptionsBuilder;
33
+ length(length: number): ColumnOptionsBuilder;
34
+ dimensions(dimensions: number): ColumnOptionsBuilder;
35
+ distance(distance: VectorDistance): ColumnOptionsBuilder;
36
+ }
37
+ /** The column constructors at run time, which `f` types and the migration builder names. */
38
+ export declare const columns: {
39
+ string: () => ColumnOptionsBuilder;
40
+ text: () => ColumnOptionsBuilder;
41
+ uuid: () => ColumnOptionsBuilder;
42
+ number: () => ColumnOptionsBuilder;
43
+ bigint: () => ColumnOptionsBuilder;
44
+ decimal: (precision?: number, scale?: number) => ColumnOptionsBuilder;
45
+ boolean: () => ColumnOptionsBuilder;
46
+ date: () => ColumnOptionsBuilder;
47
+ json: (shape?: JsonShape) => ColumnOptionsBuilder;
48
+ jsonb: (shape?: JsonShape) => ColumnOptionsBuilder;
49
+ vector: (dimensions: number) => ColumnOptionsBuilder;
50
+ enum: (members: readonly string[] | readonly number[]) => ColumnOptionsBuilder;
51
+ version: (type?: NumberConstructor | BigIntConstructor) => ColumnOptionsBuilder;
52
+ column: (type: ColumnType) => ColumnOptionsBuilder;
53
+ references: (references: () => Type<object>) => ColumnOptionsBuilder;
54
+ };
@@ -0,0 +1,108 @@
1
+ import { COLUMN_OPTIONS, } from '../type/index.js';
2
+ /**
3
+ * Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
4
+ * `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
5
+ */
6
+ export class ColumnOptionsBuilder {
7
+ [COLUMN_OPTIONS];
8
+ constructor(options) {
9
+ this[COLUMN_OPTIONS] = options;
10
+ }
11
+ with(options) {
12
+ return new ColumnOptionsBuilder({ ...this[COLUMN_OPTIONS], ...options });
13
+ }
14
+ nullable() {
15
+ return this.with({ nullable: true });
16
+ }
17
+ id() {
18
+ return this.with({ isId: true });
19
+ }
20
+ default(defaultValue) {
21
+ return this.with({ defaultValue });
22
+ }
23
+ onInsert(onInsert) {
24
+ return this.with({ onInsert });
25
+ }
26
+ onUpdate(onUpdate) {
27
+ return this.with({ onUpdate });
28
+ }
29
+ updatable(updatable) {
30
+ return this.with({ updatable });
31
+ }
32
+ softDelete(softDelete) {
33
+ return this.with({ softDelete: softDelete ?? true });
34
+ }
35
+ unique() {
36
+ return this.with({ unique: true });
37
+ }
38
+ index(index) {
39
+ return this.with({ index: index ?? true });
40
+ }
41
+ name(name) {
42
+ return this.with({ name });
43
+ }
44
+ comment(comment) {
45
+ return this.with({ comment });
46
+ }
47
+ eager(eager) {
48
+ return this.with({ eager });
49
+ }
50
+ columnType(columnType) {
51
+ return this.with({ columnType });
52
+ }
53
+ references(references) {
54
+ return this.with({ references });
55
+ }
56
+ onDelete(onDelete) {
57
+ return this.with({ onDelete });
58
+ }
59
+ narrow() {
60
+ return this;
61
+ }
62
+ as(computed) {
63
+ return this.with({ computed });
64
+ }
65
+ stored(events) {
66
+ return this.with({ stored: events ?? true });
67
+ }
68
+ precision(precision) {
69
+ return this.with({ precision });
70
+ }
71
+ scale(scale) {
72
+ return this.with({ scale });
73
+ }
74
+ autoIncrement(autoIncrement = true) {
75
+ return this.with({ autoIncrement });
76
+ }
77
+ length(length) {
78
+ return this.with({ length });
79
+ }
80
+ dimensions(dimensions) {
81
+ return this.with({ dimensions });
82
+ }
83
+ distance(distance) {
84
+ return this.with({ distance });
85
+ }
86
+ }
87
+ const column = (options) => new ColumnOptionsBuilder(options);
88
+ function json(type, shape) {
89
+ return column({ type, ...(shape && { shape }) });
90
+ }
91
+ /** The column constructors at run time, which `f` types and the migration builder names. */
92
+ export const columns = {
93
+ string: () => column({ type: String }),
94
+ text: () => column({ type: 'text' }),
95
+ uuid: () => column({ type: 'uuid' }),
96
+ number: () => column({ type: Number }),
97
+ bigint: () => column({ type: BigInt }),
98
+ decimal: (precision, scale) => column({ type: 'decimal', ...(precision !== undefined && { precision }), ...(scale !== undefined && { scale }) }),
99
+ boolean: () => column({ type: Boolean }),
100
+ date: () => column({ type: Date }),
101
+ json: (shape) => json('json', shape),
102
+ jsonb: (shape) => json('jsonb', shape),
103
+ vector: (dimensions) => column({ type: 'vector', dimensions }),
104
+ enum: (members) => column({ type: typeof members[0] === 'number' ? Number : String, enum: members }),
105
+ version: (type = Number) => column({ type, version: true }),
106
+ column: (type) => column({ type }),
107
+ references: (references) => column({ references }),
108
+ };
@@ -1,12 +1,12 @@
1
- import type { FieldOptions, HookEvent, RelationRegistration, Type } from '../../type/index.js';
1
+ import type { FieldOptions, HookDeclaration, HookEvent, RelationRegistration, Type } from '../../type/index.js';
2
2
  /**
3
- * What the member decorators record for one class, until `@Entity()` or `defineEntity` drains it: the
4
- * only channel from a member decorator to its class. The writable counterpart of `EntityMembers`.
3
+ * What the member decorators record for one class, until `@Entity()` or a subclass's registration drains it: the
4
+ * only channel from a member decorator to its class, and what a schema's members are registered as too.
5
5
  */
6
6
  export type MemberRegistrations = {
7
7
  readonly fields: Record<string, FieldOptions>;
8
8
  readonly relations: Record<string, RelationRegistration>;
9
- readonly hooks: Partial<Record<HookEvent, string[]>>;
9
+ readonly hooks: Partial<Record<HookEvent, HookDeclaration[]>>;
10
10
  };
11
11
  /**
12
12
  * The class's own registrations, created on first use, never read through a parent's: inheritance walks
@@ -1,23 +1,6 @@
1
- import type { BrandsNameFields, EntityIndexColumnInput, EntityIndexOptions, EntityOptions, FilterName, FilterOptions, RefMap, TriggerOptions, Type } from '../../type/index.js';
1
+ import type { BrandsNameFields, EntityOptions, Type } from '../../type/index.js';
2
2
  /**
3
3
  * Marks a class as an entity and finalizes its metadata, draining `context.metadata`: the class gets
4
- * `Symbol.metadata` only after its decorators return.
4
+ * `Symbol.metadata` only after its decorators return. `abstract: true` marks a base that is never a table.
5
5
  */
6
6
  export declare function Entity<E>(opts?: NoInfer<EntityOptions<E>>): (entity: Type<E> & BrandsNameFields<E>, context?: ClassDecoratorContext) => void;
7
- /**
8
- * Registers a named `$where` filter, applied to every query unless bypassed via `QueryOptions.filters`.
9
- *
10
- * @example `@Filter('active', { where: { status: 'active' }, default: false })`
11
- */
12
- export declare function Filter<E, N extends string>(name: FilterName<N>, opts: FilterOptions<E>): (entity: Type<E>) => void;
13
- /**
14
- * Declares a composite index, its columns read off the entity's refs, so `@Index((user) => [user.nope])`
15
- * does not compile and a rename reaches every column. Stacks, so several may sit above one class.
16
- * @example `@Index((user) => [user.lastName, sql`lower(${user.email})`], { unique: true })`
17
- */
18
- export declare function Index<E>(columns: (refs: RefMap<E>) => readonly EntityIndexColumnInput<E>[], options?: EntityIndexOptions<E>): (entity: Type<E>) => void;
19
- /**
20
- * Declares triggers the database runs, in the order written. Stacks, so several may sit above one class.
21
- * @example ``@Trigger({ on: 'beforeUpdate', of: (post) => [post.body], run: (newRow) => sql`...` })``
22
- */
23
- export declare function Trigger<E>(...triggers: readonly TriggerOptions<E>[]): (entity: Type<E>) => void;
@@ -1,45 +1,11 @@
1
- import { applyMembers, defineEntity, defineFilter, defineIndex, defineTrigger } from '../metadata/definition.js';
1
+ import { registerEntity } from '../metadata/definition.js';
2
2
  import { drainRegistrations } from './bag.js';
3
- // The class-level decorators. Unlike the member ones they receive the class, so each is a direct call
4
- // into the registry with no bag in between.
5
3
  /**
6
4
  * Marks a class as an entity and finalizes its metadata, draining `context.metadata`: the class gets
7
- * `Symbol.metadata` only after its decorators return.
5
+ * `Symbol.metadata` only after its decorators return. `abstract: true` marks a base that is never a table.
8
6
  */
9
7
  export function Entity(opts) {
10
8
  return (entity, context) => {
11
- applyMembers(entity, drainRegistrations(context?.metadata));
12
- defineEntity(entity, opts);
13
- };
14
- }
15
- /**
16
- * Registers a named `$where` filter, applied to every query unless bypassed via `QueryOptions.filters`.
17
- *
18
- * @example `@Filter('active', { where: { status: 'active' }, default: false })`
19
- */
20
- export function Filter(name, opts) {
21
- return (entity) => {
22
- defineFilter(entity, name, opts);
23
- };
24
- }
25
- /**
26
- * Declares a composite index, its columns read off the entity's refs, so `@Index((user) => [user.nope])`
27
- * does not compile and a rename reaches every column. Stacks, so several may sit above one class.
28
- * @example `@Index((user) => [user.lastName, sql`lower(${user.email})`], { unique: true })`
29
- */
30
- export function Index(columns, options = {}) {
31
- return (entity) => {
32
- defineIndex(entity, { ...options, columns });
33
- };
34
- }
35
- /**
36
- * Declares triggers the database runs, in the order written. Stacks, so several may sit above one class.
37
- * @example ``@Trigger({ on: 'beforeUpdate', of: (post) => [post.body], run: (newRow) => sql`...` })``
38
- */
39
- export function Trigger(...triggers) {
40
- return (entity) => {
41
- for (const trigger of triggers) {
42
- defineTrigger(entity, trigger);
43
- }
9
+ registerEntity(entity, opts, drainRegistrations(context?.metadata));
44
10
  };
45
11
  }