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
@@ -68,12 +68,6 @@ export type Writable<T> = {
68
68
  export type Except<T, K extends keyof T> = {
69
69
  [P in keyof T as P extends K ? never : P]: T[P];
70
70
  };
71
- /**
72
- * Each key of `K` mapped to `never`, so an intersection with it makes naming one a compile error;
73
- * `unknown`, inert, when there are none. A captured type parameter needs it: TypeScript skips the
74
- * excess-property check on one.
75
- */
76
- export type RejectKeys<K> = [K] extends [never] ? unknown : Record<K & string, never>;
77
71
  /**
78
72
  * Exactly one key of `T` with its value; every other key is forbidden (`never`). `Pick`, not `Record`,
79
73
  * so the chosen key stays linked to `T`'s own property and renames follow it through.
@@ -41,7 +41,7 @@ export type VectorMetric = {
41
41
  /** The error every dialect throws for a metric it lacks. */
42
42
  export declare function unsupportedVectorMetric(engine: EngineName, distance: VectorDistance, indexName?: string): UqlUsageError;
43
43
  /**
44
- * Vector-specific tuning options shared by `@Index` decorator, entity metadata, and migration schema.
44
+ * Vector-specific tuning options shared by an entity's `indexes`, its metadata, and the migration schema.
45
45
  */
46
46
  export type VectorIndexOptions = {
47
47
  /** Distance metric for vector indexes - maps to operator class. */
@@ -1,25 +1,24 @@
1
1
  import type { CheckSchema, EnumValues } from '../schema/types.js';
2
- import { type EntityIndexColumn, type EntityIndexMeta, type EntityMeta, type IndexColumnInput, type IndexColumnSchema, QuerySql } from '../type/index.js';
2
+ import type { EntityIndexMeta, EntityMeta, IndexEntry, QuerySql } from '../type/index.js';
3
3
  /**
4
- * Reduces an authored index entry to the form metadata keeps, so a column, an expression and an options
5
- * object reach the schema as one: a column read off the refs as its key, any other `sql` as it is.
6
- */
7
- export declare function normalizeIndexColumn(entry: IndexColumnInput): EntityIndexColumn;
8
- /**
9
- * Every index an entity declares: each `@Field({ index })` or `@Field({ unique })` as the one-column
10
- * `@Index` it is, then its `@Index`es. A unique column is a unique index, the one spelling of uniqueness
4
+ * Every index an entity declares: each `index()` or `unique()` column as the one-column
5
+ * index it is, then its `indexes`. A unique column is a unique index, the one spelling of uniqueness
11
6
  * every engine can add and drop.
12
7
  */
13
8
  export declare function declaredIndexes<E>(meta: EntityMeta<E>): EntityIndexMeta<E>[];
14
- /** An index entry as the schema holds it, its expression rendered to text by `render`. */
15
- export declare function renderIndexColumn(entry: EntityIndexColumn, render: (statement: QuerySql) => string): IndexColumnSchema;
16
- /** What an unnamed index's name is built from: each entry's column, or `expr<n>` for an expression, which has none. */
17
- export declare function indexNameParts(entries: readonly EntityIndexColumn[]): string[];
9
+ /**
10
+ * An index's rendered predicate and the name it is created by, settled together: `render` gets the name without the
11
+ * predicate's hash to label its errors, then the name takes the hash of what it rendered.
12
+ */
13
+ export declare function namedIndex(name: string | undefined, table: string, entries: readonly IndexEntry<unknown>[], render: (label: string) => string | undefined, unique?: boolean): {
14
+ readonly name: string;
15
+ readonly where: string | undefined;
16
+ };
18
17
  /**
19
18
  * The name an index is created and read by: its own, else one derived from its table, entries, uniqueness and
20
19
  * rendered predicate. A caller renders the predicate first, since an unnamed partial index's name carries its hash.
21
20
  */
22
- export declare function declaredIndexName(name: string | undefined, table: string, entries: readonly EntityIndexColumn[], { unique, where }?: {
21
+ export declare function declaredIndexName(name: string | undefined, table: string, entries: readonly IndexEntry<unknown>[], { unique, where }?: {
23
22
  readonly unique?: boolean;
24
23
  readonly where?: string;
25
24
  }): string;
@@ -1,25 +1,17 @@
1
- import { ColumnRef, QuerySql, } from '../type/index.js';
1
+ import { indexEntryNamePart } from './indexEntry.util.js';
2
2
  import { definedEntries } from './object.util.js';
3
3
  import { sql } from './sql.js';
4
4
  import { derivedIndexName, ownedName } from './sql.util.js';
5
5
  /**
6
- * Reduces an authored index entry to the form metadata keeps, so a column, an expression and an options
7
- * object reach the schema as one: a column read off the refs as its key, any other `sql` as it is.
8
- */
9
- export function normalizeIndexColumn(entry) {
10
- const { column, ...modifiers } = typeof entry === 'string' || entry instanceof QuerySql ? { column: entry } : entry;
11
- return { ...modifiers, column: column instanceof ColumnRef ? column.key : column };
12
- }
13
- /**
14
- * Every index an entity declares: each `@Field({ index })` or `@Field({ unique })` as the one-column
15
- * `@Index` it is, then its `@Index`es. A unique column is a unique index, the one spelling of uniqueness
6
+ * Every index an entity declares: each `index()` or `unique()` column as the one-column
7
+ * index it is, then its `indexes`. A unique column is a unique index, the one spelling of uniqueness
16
8
  * every engine can add and drop.
17
9
  */
18
10
  export function declaredIndexes(meta) {
19
11
  const fieldIndexes = definedEntries(meta.fields).flatMap(([key, field]) => field.index || field.unique
20
12
  ? [
21
13
  {
22
- columns: [{ column: key }],
14
+ entries: [{ column: key }],
23
15
  name: typeof field.index === 'string' ? field.index : undefined,
24
16
  unique: field.unique,
25
17
  },
@@ -27,21 +19,20 @@ export function declaredIndexes(meta) {
27
19
  : []);
28
20
  return [...fieldIndexes, ...(meta.indexes ?? [])];
29
21
  }
30
- /** An index entry as the schema holds it, its expression rendered to text by `render`. */
31
- export function renderIndexColumn(entry, render) {
32
- const { column } = entry;
33
- return column instanceof QuerySql ? { ...entry, column: render(column), expression: true } : { ...entry, column };
34
- }
35
- /** What an unnamed index's name is built from: each entry's column, or `expr<n>` for an expression, which has none. */
36
- export function indexNameParts(entries) {
37
- return entries.map((entry, at) => (typeof entry.column === 'string' ? entry.column : `expr${at}`));
22
+ /**
23
+ * An index's rendered predicate and the name it is created by, settled together: `render` gets the name without the
24
+ * predicate's hash to label its errors, then the name takes the hash of what it rendered.
25
+ */
26
+ export function namedIndex(name, table, entries, render, unique) {
27
+ const where = render(declaredIndexName(name, table, entries, { unique }));
28
+ return { name: declaredIndexName(name, table, entries, { unique, where }), where };
38
29
  }
39
30
  /**
40
31
  * The name an index is created and read by: its own, else one derived from its table, entries, uniqueness and
41
32
  * rendered predicate. A caller renders the predicate first, since an unnamed partial index's name carries its hash.
42
33
  */
43
34
  export function declaredIndexName(name, table, entries, { unique = false, where } = {}) {
44
- return name ?? derivedIndexName(table, indexNameParts(entries), unique, where);
35
+ return name ?? derivedIndexName(table, entries.map(indexEntryNamePart), unique, where);
45
36
  }
46
37
  /**
47
38
  * A check as uql installs it: named for its table and `label`, the author's name or `ck`, then a hash
@@ -1,5 +1,5 @@
1
1
  import type { IndexType } from '../schema/types.js';
2
- import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictPaths, type QueryExclude, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
2
+ import { type AggregateCall, type CascadeType, type EntityData, type EntityIndexMeta, type EntityMeta, type FieldKey, type FieldOptions, type FieldUpdateOp, type JsonArrayUpdateOp, type JsonUpdateOp, type OnFieldCallback, type QueryAggMap, type QueryConflictPaths, type QueryGroupMap, type QueryOptions, QuerySql, type QuerySearch, type QuerySelect, type QuerySelectValue, type QuerySortDirection, type QuerySizeComparisonOps, type QuerySortMap, type QueryTextSearchOptions, type QueryVectorQuery, type QueryVectorSearch, type QueryWhere, type RelationKey, type UpdatePayload, type VectorDistance } from '../type/index.js';
3
3
  export type CallbackKey = keyof Pick<FieldOptions, 'onInsert' | 'onUpdate'>;
4
4
  /** The keys of `payload` a write persists as columns. */
5
5
  export declare function filterFieldKeys<E>(meta: EntityMeta<E>, payload: EntityData<E> | UpdatePayload<E>, callbackKey: CallbackKey): FieldKey<E>[];
@@ -14,7 +14,7 @@ export declare function insertShapeOf<E>(meta: EntityMeta<E>, record: EntityData
14
14
  * whether or not it was filled yet. A record missing one writes its default.
15
15
  */
16
16
  export declare function getInsertFieldKeys<E>(meta: EntityMeta<E>, payloads: EntityData<E>[]): FieldKey<E>[];
17
- export declare function getFieldCallbackValue(val: OnFieldCallback): string | number | bigint | boolean | Date | import("../type/utility.js").JsonBrand | QuerySql | readonly number[] | readonly import("../type/utility.js").JsonBrand[] | Uint8Array<ArrayBufferLike>;
17
+ export declare function getFieldCallbackValue(val: OnFieldCallback): any;
18
18
  /** A delete as {@link deletionOf} plans it. */
19
19
  type Deletion<O> = {
20
20
  readonly stamp?: {
@@ -51,7 +51,11 @@ export declare function isCascadable(action: CascadeType, configuration?: boolea
51
51
  export declare function isPagedQuery<E>(q: QuerySearch<E>): boolean;
52
52
  /** Whether `select` is the list form `sql()` fills, narrowing both ways, which `Array.isArray` does not for a `readonly` array. */
53
53
  export declare function isSelectList<E>(select: QuerySelectValue<E> | undefined): select is readonly QuerySql[];
54
- export declare function normalizeScalarFieldSelection<E>(meta: EntityMeta<E>, select?: QuerySelect<E>, exclude?: QueryExclude<E>): FieldKey<E>[];
54
+ /**
55
+ * The fields a `$select` map reads: its positive entries alone where it has one, else every field it leaves in,
56
+ * a falsy entry leaving its field out.
57
+ */
58
+ export declare function normalizeScalarFieldSelection<E>(meta: EntityMeta<E>, select?: QuerySelect<E>): readonly FieldKey<E>[];
55
59
  /** Type guard: checks whether a sort value is a vector similarity search. */
56
60
  export declare function isVectorSearch(value: unknown): value is QueryVectorSearch;
57
61
  /**
@@ -72,9 +76,11 @@ export declare function vectorCandidates(q: {
72
76
  * "which kind", which decide the name Atlas is queried by and the setting Postgres is tuned with.
73
77
  */
74
78
  export declare function findVectorIndex<E>(meta: EntityMeta<E>, key: string): EntityIndexMeta<E> | undefined;
79
+ /** The metric `key`'s vector index ranks by: its own, else its field's, else cosine. */
80
+ export declare function indexedDistance<E>(meta: EntityMeta<E>, key: string, index: EntityIndexMeta<E> | undefined): VectorDistance;
75
81
  /**
76
- * The metric a distance to `key` measures by: the search's own, else the field's, else its index's, which
77
- * serves no other, else cosine. The one fallback every engine resolves, so none can rank by another.
82
+ * The metric a distance to `key` measures by: the search's own, else what its index ranks by. The one
83
+ * fallback every engine resolves, so none can rank by another.
78
84
  */
79
85
  export declare function vectorDistanceOf<E>(meta: EntityMeta<E>, key: string, search: QueryVectorQuery): VectorDistance;
80
86
  /**
@@ -134,43 +134,33 @@ export function isPagedQuery(q) {
134
134
  export function isSelectList(select) {
135
135
  return Array.isArray(select);
136
136
  }
137
- export function normalizeScalarFieldSelection(meta, select, exclude) {
138
- // A positive `$select` (the common case) wins outright and returns
139
- // before `$exclude` is ever scanned.
140
- const positiveFields = [];
141
- let excludedFields;
142
- if (select) {
143
- for (const key of getKeys(select)) {
144
- if (!(key in meta.fields))
145
- continue;
146
- if (select[key]) {
147
- positiveFields.push(key);
148
- }
149
- else {
150
- excludedFields ??= new Set();
151
- excludedFields.add(key);
152
- }
137
+ /**
138
+ * The fields a `$select` map reads: its positive entries alone where it has one, else every field it leaves in,
139
+ * a falsy entry leaving its field out.
140
+ */
141
+ export function normalizeScalarFieldSelection(meta, select) {
142
+ const positive = [];
143
+ let excluded;
144
+ for (const key of getKeys(select)) {
145
+ if (!(key in meta.fields)) {
146
+ continue;
153
147
  }
154
- if (positiveFields.length) {
155
- return positiveFields;
148
+ if (select?.[key]) {
149
+ positive.push(key);
156
150
  }
157
- }
158
- // No positive selection: every field minus the ones excluded by a falsy `$select` entry or a
159
- // truthy `$exclude` entry.
160
- if (exclude) {
161
- for (const key of getKeys(exclude)) {
162
- if (exclude[key] && key in meta.fields) {
163
- excludedFields ??= new Set();
164
- excludedFields.add(key);
165
- }
151
+ else {
152
+ excluded ??= new Set();
153
+ excluded.add(key);
166
154
  }
167
155
  }
156
+ if (positive.length) {
157
+ return positive;
158
+ }
168
159
  const allFields = defaultReadKeys(meta);
169
- if (!excludedFields) {
160
+ if (!excluded) {
170
161
  return allFields;
171
162
  }
172
- const excluded = excludedFields;
173
- return allFields.filter((it) => !excluded.has(it));
163
+ return allFields.filter((key) => !excluded.has(key));
174
164
  }
175
165
  /** Type guard: checks whether a sort value is a vector similarity search. */
176
166
  export function isVectorSearch(value) {
@@ -212,12 +202,16 @@ const VECTOR_INDEX_MATCH = new Set([...VECTOR_INDEX_TYPES, 'vectorSearch']);
212
202
  export function findVectorIndex(meta, key) {
213
203
  return meta.indexes?.find((index) => index.type !== undefined && VECTOR_INDEX_MATCH.has(index.type) && indexCoversColumn(index, key));
214
204
  }
205
+ /** The metric `key`'s vector index ranks by: its own, else its field's, else cosine. */
206
+ export function indexedDistance(meta, key, index) {
207
+ return index?.distance ?? meta.fields[key]?.distance ?? DEFAULT_VECTOR_DISTANCE;
208
+ }
215
209
  /**
216
- * The metric a distance to `key` measures by: the search's own, else the field's, else its index's, which
217
- * serves no other, else cosine. The one fallback every engine resolves, so none can rank by another.
210
+ * The metric a distance to `key` measures by: the search's own, else what its index ranks by. The one
211
+ * fallback every engine resolves, so none can rank by another.
218
212
  */
219
213
  export function vectorDistanceOf(meta, key, search) {
220
- return (search.$distance ?? meta.fields[key]?.distance ?? findVectorIndex(meta, key)?.distance ?? DEFAULT_VECTOR_DISTANCE);
214
+ return search.$distance ?? indexedDistance(meta, key, findVectorIndex(meta, key));
221
215
  }
222
216
  /**
223
217
  * Whether a `$where` filters by vector distance anywhere in its tree, `$and`/`$or`/`$not` included.
@@ -233,7 +227,7 @@ export function hasVectorNear(where) {
233
227
  return Object.entries(where).some(([key, value]) => key === '$near' || hasVectorNear(value));
234
228
  }
235
229
  function indexCoversColumn(index, key) {
236
- return index.columns.some((entry) => entry.column === key);
230
+ return index.entries.some((entry) => entry.column === key);
237
231
  }
238
232
  /** `satisfies` ties this to {@link JsonUpdateOp}, so renaming an operator breaks it at compile time. */
239
233
  const JSON_UPDATE_OPS = [
@@ -656,8 +650,8 @@ export function textWeightSteps(weights) {
656
650
  /** The fulltext index over exactly `fields`, in order, which a search of them is served by. */
657
651
  export function fulltextIndexOver(meta, fields) {
658
652
  return meta.indexes?.find((index) => index.type === 'fulltext' &&
659
- index.columns.length === fields.length &&
660
- index.columns.every((entry, at) => entry.column === fields[at]));
653
+ index.entries.length === fields.length &&
654
+ index.entries.every((entry, at) => entry.column === fields[at]));
661
655
  }
662
656
  /** How a `$sort` orders by `$text`: its direction, and the name it answers the relevance under, if any. */
663
657
  export function textSortOf(sort) {
@@ -689,7 +683,7 @@ export function textSearchFields(meta, search) {
689
683
  }
690
684
  const fulltext = (meta.indexes ?? []).filter((index) => index.type === 'fulltext');
691
685
  if (fulltext.length === 1) {
692
- return fulltext[0].columns.flatMap((entry) => (typeof entry.column === 'string' ? [entry.column] : []));
686
+ return fulltext[0].entries.flatMap((entry) => entry.column ?? []);
693
687
  }
694
688
  const name = entityName(meta);
695
689
  const declared = fulltext.length
@@ -1,4 +1,4 @@
1
- import { type ColumnFamily, type EntityMeta, type FieldKey, type FieldMeta, type FieldOptions, type StampEvent, type RelationAggregateSpec } from '../type/index.js';
1
+ import { type ColumnFamily, type EntityMeta, type FieldKey, type FieldMeta, type FieldOptions, type StampEvent, RelationAggregate, type RelationAggregateSpec } from '../type/index.js';
2
2
  /** The family of a logical field type, or `undefined` where it names none. */
3
3
  export declare function columnFamily(type: unknown): ColumnFamily | undefined;
4
4
  /**
@@ -31,6 +31,8 @@ export declare function stampEvents(field: FieldOptions): readonly StampEvent[]
31
31
  * subquery on SQL, a lookup on MongoDB - so both read the same declaration rather than parsing SQL.
32
32
  */
33
33
  export declare function aggregateOf(field: FieldOptions | undefined): RelationAggregateSpec | undefined;
34
+ /** An aggregate as a computed field holds it: `null` where the relation holds no row, but for a count or a sum. */
35
+ export declare function aggregateField(aggregate: RelationAggregate): FieldOptions;
34
36
  /**
35
37
  * Whether the database supplies this field's value, so no insert or update may write it: a stored
36
38
  * computed column *is* a real column, read like one, but writing to it is an error on every engine.
@@ -46,21 +48,20 @@ export declare function isSoleIdField<E>(meta: EntityMeta<E>, field: FieldOption
46
48
  export declare function isAutoIncrement(field: FieldOptions, isPrimaryKey: boolean): boolean;
47
49
  /** The column family of a field, from its `columnType` if set, else from its `type`. */
48
50
  export declare function fieldFamily(field: FieldOptions): ColumnFamily | undefined;
49
- /**
50
- * Whether the column is NOT NULL: the field declares `nullable: false` or is a key. A key counts whatever its
51
- * property says: `id?: number` is optional because the database assigns it, not because it can be null.
52
- */
51
+ /** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
53
52
  export declare function declaresNotNull(field: FieldOptions): boolean;
54
53
  /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
55
54
  export declare function isFieldKey<E>(meta: EntityMeta<E>, key: string): key is FieldKey<E>;
56
55
  /** The fields `meta` declares whose options `pick` accepts, in declaration order, each as the entity's own key. */
57
56
  export declare function fieldKeys<E>(meta: EntityMeta<E>, pick: (field: FieldMeta) => unknown): FieldKey<E>[];
58
57
  /**
59
- * The fields a read answers with where it names none. A relation aggregate is left out unless it asks
60
- * for `eager: true`: it reads the related rows, which is what a relation does, and a relation is loaded
61
- * only when a query asks for it. Naming one in `$select` reads it, whatever the default.
58
+ * The fields a read answers with where it names none, kept on the entity once it is resolved. A relation
59
+ * aggregate is left out unless it asks for `eager: true`: it reads the related rows, which is what a relation
60
+ * does, and a relation is loaded only when a query asks for it. Naming one in `$select` reads it, whatever the default.
62
61
  */
63
- export declare function defaultReadKeys<E>(meta: EntityMeta<E>): FieldKey<E>[];
62
+ export declare function defaultReadKeys<E>(meta: EntityMeta<E>): readonly FieldKey<E>[];
63
+ /** A JSON key a path may name, unanchored, for a pattern that reads one inside a name. */
64
+ export declare const JSON_KEY_PATTERN = "[\\p{L}_][\\p{L}\\p{N}_]*";
64
65
  /**
65
66
  * A JSON document key, refused unless it is an identifier: the one shape every engine's path reads
66
67
  * unquoted, so a key never needs escaping into SQL and never reads as path syntax.
@@ -71,6 +71,11 @@ export function aggregateOf(field) {
71
71
  const computed = field?.computed;
72
72
  return computed instanceof RelationAggregate ? computed.spec : undefined;
73
73
  }
74
+ /** An aggregate as a computed field holds it: `null` where the relation holds no row, but for a count or a sum. */
75
+ export function aggregateField(aggregate) {
76
+ const { op } = aggregate.spec;
77
+ return { computed: aggregate, ...(op !== '$count' && op !== '$sum' && { nullable: true }) };
78
+ }
74
79
  /**
75
80
  * Whether the database supplies this field's value, so no insert or update may write it: a stored
76
81
  * computed column *is* a real column, read like one, but writing to it is an error on every engine.
@@ -96,12 +101,9 @@ export function isAutoIncrement(field, isPrimaryKey) {
96
101
  export function fieldFamily(field) {
97
102
  return columnFamily(field.columnType ?? field.type);
98
103
  }
99
- /**
100
- * Whether the column is NOT NULL: the field declares `nullable: false` or is a key. A key counts whatever its
101
- * property says: `id?: number` is optional because the database assigns it, not because it can be null.
102
- */
104
+ /** Whether the column is NOT NULL: every column is, a key included, unless it declares `nullable()`. */
103
105
  export function declaresNotNull(field) {
104
- return field.isId === true || field.nullable === false;
106
+ return field.nullable !== true;
105
107
  }
106
108
  /** Whether `key` is a field of `meta`, as opposed to a relation, a JSON path or an unknown key. */
107
109
  export function isFieldKey(meta, key) {
@@ -116,14 +118,16 @@ export function fieldKeys(meta, pick) {
116
118
  });
117
119
  }
118
120
  /**
119
- * The fields a read answers with where it names none. A relation aggregate is left out unless it asks
120
- * for `eager: true`: it reads the related rows, which is what a relation does, and a relation is loaded
121
- * only when a query asks for it. Naming one in `$select` reads it, whatever the default.
121
+ * The fields a read answers with where it names none, kept on the entity once it is resolved. A relation
122
+ * aggregate is left out unless it asks for `eager: true`: it reads the related rows, which is what a relation
123
+ * does, and a relation is loaded only when a query asks for it. Naming one in `$select` reads it, whatever the default.
122
124
  */
123
125
  export function defaultReadKeys(meta) {
124
- return fieldKeys(meta, (field) => field.eager ?? !aggregateOf(field));
126
+ return meta.readKeys ?? fieldKeys(meta, (field) => field.eager ?? !aggregateOf(field));
125
127
  }
126
- const JSON_KEY = /^[\p{L}_][\p{L}\p{N}_]*$/u;
128
+ /** A JSON key a path may name, unanchored, for a pattern that reads one inside a name. */
129
+ export const JSON_KEY_PATTERN = '[\\p{L}_][\\p{L}\\p{N}_]*';
130
+ const JSON_KEY = new RegExp(`^${JSON_KEY_PATTERN}$`, 'u');
127
131
  /**
128
132
  * A JSON document key, refused unless it is an identifier: the one shape every engine's path reads
129
133
  * unquoted, so a key never needs escaping into SQL and never reads as path syntax.
@@ -1,104 +1,20 @@
1
- import { type ColumnFamily, type FamilyOf, type FieldOptions, QuerySql, type StampEvent } from '../type/index.js';
2
- /**
3
- * The column families each field option means anything on, or `'*'` where it applies to every column.
4
- * Exhaustive over {@link FieldOptions}, so a new option cannot be added without placing it - the
5
- * discipline `INDEX_FEATURE_LABELS` uses for index features.
6
- */
7
- declare const FIELD_OPTION_FAMILY: {
8
- readonly name: '*';
9
- readonly isId: '*';
10
- readonly type: '*';
11
- readonly dimensions: 'vector';
12
- readonly distance: 'vector';
13
- readonly references: '*';
14
- readonly onDelete: '*';
15
- readonly enum: '*';
16
- readonly computed: '*';
17
- readonly stored: '*';
18
- readonly updatable: '*';
19
- readonly eager: '*';
20
- readonly onInsert: '*';
21
- readonly onUpdate: '*';
22
- readonly softDelete: '*';
23
- readonly version: 'numeric';
24
- readonly columnType: '*';
25
- readonly length: 'string';
26
- readonly precision: readonly ["numeric", "date"];
27
- readonly scale: 'numeric';
28
- readonly nullable: '*';
29
- readonly unique: '*';
30
- readonly defaultValue: '*';
31
- readonly autoIncrement: 'numeric';
32
- readonly index: '*';
33
- readonly comment: '*';
34
- };
35
- /**
36
- * The only options an inlined computed field reaches: it is skipped in DDL and dropped from every insert and
37
- * update, so the whole persistence half of the options above is dead on one. Stated as what survives
38
- * rather than on each option that dies, because it is one fact rather than nineteen - and because an
39
- * option added without a thought then lands on the safe side of it.
40
- */
41
- declare const INLINE_READS: readonly ["type", "computed", "stored", "enum", "eager", "distance"];
42
- type InlineRead = (typeof INLINE_READS)[number];
43
- /**
44
- * What a column the *database* writes cannot use. A stored computed column is a real column - it has
45
- * DDL, an index, a comment, a name - so only the write half is dead on one: the engine fills it, and
46
- * `GENERATED ALWAYS AS` and `DEFAULT` are mutually exclusive on every engine that has both.
47
- */
48
- declare const GENERATED_WRITES: readonly ["updatable", "onInsert", "onUpdate", "softDelete", "defaultValue", "autoIncrement", "version"];
49
- type GeneratedWrite = (typeof GENERATED_WRITES)[number];
50
- /**
51
- * What an optimistic lock cannot use: the querier writes the column on every update and matches the
52
- * value the payload carried, so anything else deciding it would be fighting that, and the three that
53
- * would make it another kind of column entirely. Its `nullable: false` and `DEFAULT 0` are implied.
54
- */
55
- declare const VERSION_WRITES: readonly ["updatable", "onInsert", "onUpdate", "softDelete", "defaultValue", "autoIncrement", "computed", "stored", "isId"];
56
- type VersionWrite = (typeof VERSION_WRITES)[number];
1
+ import { type FieldOptions } from '../type/index.js';
2
+ /** Every option that decides what a column holds, or whether it is written at all. */
3
+ export declare const VALUE_DECIDERS: readonly ["updatable", "onInsert", "onUpdate", "softDelete", "defaultValue", "autoIncrement"];
57
4
  /**
58
5
  * What bounds a type: stated separately where uql spells the type, and part of the text where the
59
6
  * engine's own is written out, which renders verbatim and leaves these unread.
60
7
  */
61
- declare const TYPE_BOUNDS: readonly ["length", "precision", "scale", "dimensions"];
62
- type TypeBound = (typeof TYPE_BOUNDS)[number];
8
+ export declare const TYPE_BOUNDS: readonly ["length", "precision", "scale", "dimensions"];
63
9
  /**
64
10
  * The first option `opts` cannot use, phrased as the tail of `'Entity.field' ...`, or `undefined`
65
- * where every option applies. The runtime half of the decorators' check, so the imperative API and
66
- * plain JavaScript reach the same answer.
11
+ * where every option applies. The runtime half of the decorators' check, so plain JavaScript reaches
12
+ * the same answer.
67
13
  */
68
14
  export declare function fieldOptionConflict(opts: FieldOptions): string | undefined;
69
- /** The family the options put the column in; every family where they name no type to put it in. */
70
- type OptionsFamily<O> = O extends {
71
- readonly columnType: infer C;
72
- } ? FamilyOf<C> : O extends {
73
- readonly type: infer T;
74
- } ? FamilyOf<T> : ColumnFamily;
75
- /** What the field's own values leave unread, matching {@link deadOn} line for line. */
76
- type DeadOptions<O> = (O extends {
77
- readonly stored: true | readonly StampEvent[];
78
- } ? GeneratedWrite : O extends {
79
- readonly computed: QuerySql;
80
- } ? Exclude<keyof FieldOptions, InlineRead> : never) | (O extends {
81
- readonly isId: true;
82
- readonly nullable: true;
83
- } ? 'nullable' : never) | (O extends {
84
- readonly updatable: false;
85
- } ? 'onUpdate' : never) | (O extends {
86
- readonly columnType: QuerySql;
87
- } ? TypeBound : never) | (O extends {
88
- readonly version: true;
89
- } ? VersionWrite : never) | (O extends {
90
- readonly version: true;
91
- readonly nullable: true;
92
- } ? 'nullable' : never);
93
- type Given<O> = Extract<keyof O, keyof FieldOptions>;
94
- /** The families option `K` applies to, `'*'` for every one. */
95
- type OptionFamilies<K extends keyof FieldOptions> = (typeof FIELD_OPTION_FAMILY)[K] extends readonly (infer F)[] ? F : (typeof FIELD_OPTION_FAMILY)[K];
96
- type Offending<O> = {
97
- [K in Given<O>]: [Extract<OptionFamilies<K>, OptionsFamily<O> | '*'>] extends [never] ? K : K extends DeadOptions<O> ? K : never;
98
- }[Given<O>];
99
- /**
100
- * Every option `O` states but cannot use, mapped to `never`, so one that would be ignored does not compile.
101
- * `@Id` states `{ nullable?: false }` itself, since `O` has to stay naked to be inferred.
102
- */
103
- export type RejectIncompatible<O> = [Offending<O>] extends [never] ? unknown : Record<Offending<O> & string, never>;
15
+ /** What `typeof` answers on a value of `T`, where a column's values are checked: a date, a document or bytes are not. */
16
+ type ValueTypeOf<T> = T extends string ? 'string' : T extends number ? 'number' : T extends bigint ? 'bigint' : T extends boolean ? 'boolean' : never;
17
+ type ValueType = ValueTypeOf<string | number | bigint | boolean>;
18
+ /** What `typeof` a value answers on a column of `type`, as `TsTypeOf` types it; nothing where none is checked. */
19
+ export declare function valueTypesOf(type: FieldOptions['type']): readonly ValueType[] | undefined;
104
20
  export {};
@@ -1,5 +1,5 @@
1
- import { QuerySql } from '../type/index.js';
2
- import { fieldFamily, isInlinedExpression } from './field.util.js';
1
+ import { QuerySql, } from '../type/index.js';
2
+ import { columnFamily, fieldFamily, isInlinedExpression } from './field.util.js';
3
3
  import { getKeys } from './object.util.js';
4
4
  import { constantSql } from './sql.js';
5
5
  /**
@@ -16,6 +16,7 @@ const FIELD_OPTION_FAMILY = {
16
16
  references: '*',
17
17
  onDelete: '*',
18
18
  enum: '*',
19
+ shape: 'json',
19
20
  computed: '*',
20
21
  stored: '*',
21
22
  updatable: '*',
@@ -49,9 +50,10 @@ const INLINE_READS = [
49
50
  'enum',
50
51
  'eager',
51
52
  'distance',
53
+ 'nullable',
52
54
  ];
53
55
  /** Every option that decides what a column holds, or whether it is written at all. */
54
- const VALUE_DECIDERS = [
56
+ export const VALUE_DECIDERS = [
55
57
  'updatable',
56
58
  'onInsert',
57
59
  'onUpdate',
@@ -68,43 +70,41 @@ const GENERATED_WRITES = [...VALUE_DECIDERS, 'version'];
68
70
  /**
69
71
  * What an optimistic lock cannot use: the querier writes the column on every update and matches the
70
72
  * value the payload carried, so anything else deciding it would be fighting that, and the three that
71
- * would make it another kind of column entirely. Its `nullable: false` and `DEFAULT 0` are implied.
73
+ * would make it another kind of column entirely. Its `DEFAULT 0` is implied.
72
74
  */
73
75
  const VERSION_WRITES = [...VALUE_DECIDERS, 'computed', 'stored', 'isId'];
74
76
  /**
75
77
  * What bounds a type: stated separately where uql spells the type, and part of the text where the
76
78
  * engine's own is written out, which renders verbatim and leaves these unread.
77
79
  */
78
- const TYPE_BOUNDS = ['length', 'precision', 'scale', 'dimensions'];
79
- /**
80
- * Whether `key` is the `nullable: true` a NOT NULL column contradicts. `nullable: false` says what
81
- * such a column already is, and rejecting an accurate statement teaches an author to distrust the check.
82
- */
83
- function contradictsNotNull(opts, key) {
84
- return key === 'nullable' && opts.nullable === true;
85
- }
80
+ export const TYPE_BOUNDS = [
81
+ 'length',
82
+ 'precision',
83
+ 'scale',
84
+ 'dimensions',
85
+ ];
86
86
  /** Whatever leaves `key` unread, named for the message, or `undefined` where the field reads it. */
87
87
  function deadOn(opts, key) {
88
88
  if (isInlinedExpression(opts) && !INLINE_READS.some((read) => read === key))
89
89
  return 'an inlined computed field';
90
90
  if (opts.stored && GENERATED_WRITES.some((write) => write === key))
91
91
  return 'a column the database writes';
92
- if (opts.isId === true && contradictsNotNull(opts, key))
92
+ if (opts.isId === true && key === 'nullable')
93
93
  return 'a primary key';
94
94
  if (opts.updatable === false && key === 'onUpdate')
95
95
  return "a field declared 'updatable: false'";
96
96
  if (opts.columnType instanceof QuerySql && TYPE_BOUNDS.some((bound) => bound === key)) {
97
97
  return 'a column type written out as SQL, which carries its own bounds';
98
98
  }
99
- if (opts.version === true && (VERSION_WRITES.some((write) => write === key) || contradictsNotNull(opts, key))) {
99
+ if (opts.version === true && (VERSION_WRITES.some((write) => write === key) || key === 'nullable')) {
100
100
  return 'a version field';
101
101
  }
102
102
  return undefined;
103
103
  }
104
104
  /**
105
105
  * The first option `opts` cannot use, phrased as the tail of `'Entity.field' ...`, or `undefined`
106
- * where every option applies. The runtime half of the decorators' check, so the imperative API and
107
- * plain JavaScript reach the same answer.
106
+ * where every option applies. The runtime half of the decorators' check, so plain JavaScript reaches
107
+ * the same answer.
108
108
  */
109
109
  export function fieldOptionConflict(opts) {
110
110
  // Caught here rather than where the type is resolved, which is a migration on most engines and a
@@ -112,6 +112,10 @@ export function fieldOptionConflict(opts) {
112
112
  if (opts.columnType instanceof QuerySql && constantSql(opts.columnType) === undefined) {
113
113
  return "cannot use 'columnType': a `sql` one names a constant type, so it can bind no value and read no column";
114
114
  }
115
+ const stray = enumStray(opts);
116
+ if (stray) {
117
+ return stray;
118
+ }
115
119
  const family = fieldFamily(opts);
116
120
  // Walked in table order, not in the order the field happened to be written, so a field with two
117
121
  // conflicts always reports the same one. An option no rule knows is a typo, which `@Field`'s own check
@@ -130,3 +134,32 @@ export function fieldOptionConflict(opts) {
130
134
  }
131
135
  return undefined;
132
136
  }
137
+ /** The values each family holds. A family left out is not checked. */
138
+ const VALUE_TYPES_OF_FAMILY = {
139
+ string: { string: true },
140
+ numeric: { number: true, bigint: true },
141
+ boolean: { boolean: true },
142
+ };
143
+ /** Where a type's family does not decide its values: a constructor holds one kind, and `time` and an exact decimal read as text. */
144
+ const VALUE_TYPES_OF_TYPE = new Map([
145
+ [Number, { number: true }],
146
+ [BigInt, { bigint: true }],
147
+ ['time', { string: true }],
148
+ ['decimal', { string: true }],
149
+ ['numeric', { string: true }],
150
+ ]);
151
+ /** What `typeof` a value answers on a column of `type`, as `TsTypeOf` types it; nothing where none is checked. */
152
+ export function valueTypesOf(type) {
153
+ const family = columnFamily(type);
154
+ const held = VALUE_TYPES_OF_TYPE.get(type) ?? (family && VALUE_TYPES_OF_FAMILY[family]);
155
+ return held && getKeys(held);
156
+ }
157
+ /** An `enum` member its `type` cannot hold, which the row would still type as that member. */
158
+ function enumStray(opts) {
159
+ const types = valueTypesOf(opts.type);
160
+ const stray = types && opts.enum?.find((member) => !types.some((type) => type === typeof member));
161
+ if (!types || stray === undefined)
162
+ return undefined;
163
+ const shown = typeof stray === 'string' ? `'${stray}'` : String(stray);
164
+ return `cannot use 'enum': its member ${shown} is no ${types.join(' or ')}, which its type holds`;
165
+ }