uql-orm 0.104.0 → 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 +45 -41
  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
@@ -0,0 +1,190 @@
1
+ import type { ForeignKeyAction } from '../schema/types.js';
2
+ import type { Column, ColumnOptionsOf, ColumnValueOf, FilledOptions, NullOf } from './column.js';
3
+ import type { CheckSection, FilterSection, filledKey, HookContext, HookEvent, idKey, IdValue, IndexSection, IsUnion, RefMap, RelationCardinality, RelationInverseOptions, RelationJoinOptions, RelationOwnerOptions, RelationRef, ToManyRefs, ToManyRelationKey, TriggerSection, versionKey } from './entity.js';
4
+ import type { QuerySql, RelationAggregate } from './querySql.js';
5
+ import type { Type } from './utility.js';
6
+ /**
7
+ * A schema entity's columns, each an `f` builder. A foreign key is declared in `.references()`, once every entity
8
+ * exists: one written here would read its target while that target's own type is still being inferred. A computed
9
+ * column is declared in `.computed()`, where its row is read-only.
10
+ */
11
+ export type SchemaFields = {
12
+ readonly [key: string]: Column<{
13
+ readonly references?: undefined;
14
+ readonly computed?: undefined;
15
+ } & {
16
+ readonly [key: string]: unknown;
17
+ }>;
18
+ };
19
+ /** The key a class holds: carried beside a schema's, so a cycle never reads its row; read off a decorated one's. */
20
+ export type ReferencedKey<C> = C extends {
21
+ readonly [schemaShape]?: {
22
+ readonly key: infer K;
23
+ };
24
+ } ? unknown extends K ? RowKey<C> : K : RowKey<C>;
25
+ type RowKey<C> = C extends Type<infer R> ? NonNullable<IdValue<R>> : never;
26
+ /** The keys of `F` whose column is a `C`. */
27
+ type FlagKeys<F, C> = {
28
+ [K in keyof F]-?: F[K] extends C ? K : never;
29
+ }[keyof F];
30
+ /**
31
+ * The columns as a row reads them, mapped over parameters constrained to `keyof F` so each key stays linked to
32
+ * its declaration for a rename. A nullable column may be absent on insert and reads `null`.
33
+ */
34
+ export type ColumnRow<F, Nullable extends keyof F = FlagKeys<F, Column<{
35
+ readonly nullable: true;
36
+ }>>, Present extends keyof F = Exclude<keyof F, Nullable>> = {
37
+ -readonly [K in Present]-?: ColumnValueOf<F[K]>;
38
+ } & {
39
+ -readonly [K in Nullable]?: ColumnValueOf<F[K]> | null;
40
+ };
41
+ /** The computed columns as a row reads them, never written. */
42
+ type ComputedRow<C> = {
43
+ readonly [K in keyof C]?: ColumnValueOf<C[K]> | NullOf<ColumnOptionsOf<C[K]>>;
44
+ };
45
+ /** What `.computed()` returns: columns the database computes, `f.string().as(sql`...`)`. */
46
+ type SchemaComputed = {
47
+ readonly [key: string]: Column<{
48
+ readonly computed: QuerySql;
49
+ }>;
50
+ };
51
+ /** A relation as a schema declares it: what `rel.*` returns, its target carried for the row. */
52
+ export type SchemaRelation<T = object, C extends RelationCardinality = RelationCardinality, Columns = T> = {
53
+ readonly target: Type<T>;
54
+ readonly cardinality: C;
55
+ /** Checked by the builder's signature, so held erased: the registry reads them back as any relation's options. */
56
+ readonly options?: object;
57
+ /** The target's columns, which an aggregate over the relation reads. */
58
+ readonly columns?: Columns;
59
+ };
60
+ /** Each to-many relation as an aggregate reads it, typed by its target's columns, read lazily as the relations are. */
61
+ type AggregateRefs<R> = {
62
+ readonly [K in keyof R]: R[K] extends () => {
63
+ readonly cardinality: '1m' | 'mm';
64
+ readonly columns?: infer Columns;
65
+ } ? RelationRef<Columns> : never;
66
+ };
67
+ /** The aggregates as a row reads them, each a computed column typed by the value it reads, never written. */
68
+ export type AggregateRow<A> = {
69
+ readonly [K in keyof A]?: A[K] extends () => RelationAggregate<infer V> ? V : never;
70
+ };
71
+ type RelationValue<P> = P extends () => SchemaRelation<infer T, infer C, unknown> ? C extends '1m' | 'mm' ? T[] : T : never;
72
+ /** The relations as a row reads them; exported, as a schema's emitted declaration names it. */
73
+ export type RelationRow<R> = {
74
+ -readonly [K in keyof R]?: RelationValue<R[K]>;
75
+ };
76
+ /** The brands the type level reads keys off, derived from the columns rather than written by hand. */
77
+ export type Brands<F> = {
78
+ readonly [idKey]?: FlagKeys<F, Column<{
79
+ readonly isId: true;
80
+ }>>;
81
+ readonly [versionKey]?: FlagKeys<F, Column<{
82
+ readonly version: true;
83
+ }>>;
84
+ readonly [filledKey]?: Exclude<FlagKeys<F, Column<FilledOptions>>, FlagKeys<F, Column<{
85
+ readonly isId: true;
86
+ }>>>;
87
+ };
88
+ /** The relation constructors a schema's `relations` receives, typed by the columns of the entity declaring them. */
89
+ export type RelationBuilder<O> = {
90
+ oneToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>> | RelationInverseOptions<T, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, '11'>;
91
+ manyToOne<T extends object, K = IdValue<T>, Columns = T>(target: Type<T> & SchemaShape<K, Columns>, opts: RelationOwnerOptions<T, O, SchemaJoins<T, O, K, Columns>>): SchemaRelation<T, 'm1'>;
92
+ /** With no options, it is mapped by the one many-to-one of its target pointing back. */
93
+ oneToMany<T extends object, Columns = T>(target: Type<T> & SchemaShape<unknown, Columns>, opts?: RelationInverseOptions<T, SchemaJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, SchemaJoins<T, O, unknown, Columns>>): SchemaRelation<T, '1m', Columns>;
94
+ manyToMany<T extends object, Columns = T>(target: Type<T> & SchemaShape<unknown, Columns>, opts: RelationInverseOptions<T, SchemaJoins<T, O, unknown, Columns>> | RelationJoinOptions<T, O, SchemaJoins<T, O, unknown, Columns>>): SchemaRelation<T, 'mm', Columns>;
95
+ };
96
+ /**
97
+ * A schema's joins: a foreign key and paired columns checked by type, off the target's carried key and columns;
98
+ * `mappedBy` by key alone, its kind checked on first read.
99
+ */
100
+ type SchemaJoins<T, O, K = unknown, Columns = T> = {
101
+ readonly key: KeyHolding<O, K>;
102
+ readonly pairs: readonly SchemaJoinPair<O, Columns>[];
103
+ readonly mappedBy: keyof T;
104
+ };
105
+ /** One pair of join columns, the local one holding what the target's column does. */
106
+ type SchemaJoinPair<O, Columns> = {
107
+ readonly [F in keyof Columns]-?: {
108
+ readonly local: KeyHolding<O, NonNullable<Columns[F]>>;
109
+ readonly foreign: F;
110
+ };
111
+ }[keyof Columns];
112
+ /** What the first call of a schema states: the class, its table and its columns. */
113
+ export type SchemaEntityOptions<F extends SchemaFields, B = object, BK = unknown, BC = unknown> = {
114
+ /** The class's name, which a naming strategy derives the table's from, as it does a decorated class's. */
115
+ readonly name: string;
116
+ /** The table, exactly as the database names it, where it is not derived from `name`. */
117
+ readonly table?: string;
118
+ /** The schema (a MySQL database) the table lives in; unset follows the pool's. */
119
+ readonly schema?: string;
120
+ /** A base that is never a table: the entities extending it take what it declares. */
121
+ readonly abstract?: true;
122
+ /** The entity it inherits from, which the declared class extends, so its methods and `super` work. */
123
+ readonly extends?: SchemaClass<B, BK, BC>;
124
+ readonly fields: F;
125
+ };
126
+ /** A hook a schema runs on a row; a promise it returns is awaited. */
127
+ type SchemaHook<Row> = (row: Row, ctx: HookContext) => unknown;
128
+ /**
129
+ * Each foreign key column's target, `{ authorId: () => Author }`, or with its delete action. The getter is typed as
130
+ * returning nothing: typing its target would read an entity referencing itself while it is inferred, so the key's
131
+ * kind is checked on first read.
132
+ */
133
+ type SchemaReferences<Columns> = {
134
+ readonly [K in keyof Columns]?: LazyTarget | {
135
+ readonly entity: LazyTarget;
136
+ readonly onDelete?: ForeignKeyAction;
137
+ };
138
+ };
139
+ /** The entity a foreign key points at, read once every entity exists. */
140
+ type LazyTarget = () => void;
141
+ /**
142
+ * What a schema declares after its columns, each section typed by the columns now fixed, so none is inferred
143
+ * again. `relations` comes last: what follows a relation would read its target while that target is inferred.
144
+ */
145
+ type SchemaSections<Row, Key, Columns, B> = {
146
+ /** Columns the database computes off the stored ones, `(post) => ({ slug: f.string().as(sql`...`) })`. */
147
+ computed<const C extends SchemaComputed>(computed: (refs: RefMap<Columns>) => C): SchemaEntity<Row & ComputedRow<C>, Key, Columns & ComputedRow<C>, B>;
148
+ indexes(indexes: IndexSection<Columns>): SchemaEntity<Row, Key, Columns, B>;
149
+ checks(checks: CheckSection<Columns>): SchemaEntity<Row, Key, Columns, B>;
150
+ triggers(triggers: TriggerSection<Columns>): SchemaEntity<Row, Key, Columns, B>;
151
+ filters(filters: FilterSection<Row>): SchemaEntity<Row, Key, Columns, B>;
152
+ /** Functions each lifecycle event runs on the row, in order, given the querier writing it. */
153
+ hooks(hooks: {
154
+ readonly [E in HookEvent]?: readonly SchemaHook<Row>[];
155
+ }): SchemaEntity<Row, Key, Columns, B>;
156
+ /** The foreign keys no relation joins on, each column's target: `{ authorId: () => Author }`. */
157
+ references(references: SchemaReferences<Columns>): SchemaEntity<Row, Key, Columns, B>;
158
+ /**
159
+ * The relations, each read lazily so entities pointing at each other declare in either order, and the values
160
+ * read over the to-many ones, its base's too: `(agg) => ({ postCount: () => agg.posts.count() })`.
161
+ */
162
+ relations<const R, const A = {}>(relations: (rel: RelationBuilder<Columns>) => R, aggregates?: (agg: AggregateRefs<R> & ToManyRefs<B, Exclude<ToManyRelationKey<B>, keyof R>>) => A): SchemaClass<Row & RelationRow<R> & AggregateRow<A>, Key, Columns>;
163
+ };
164
+ /** A schema entity's class while its sections may still be declared. */
165
+ export type SchemaEntity<Row, Key, Columns, B> = SchemaClass<Row, Key, Columns> & SchemaSections<Row, Key, Columns, B>;
166
+ /** The class a schema declares, to use as it is or to extend with behaviour. */
167
+ export type SchemaClass<Row, Key = unknown, Columns = unknown> = (new () => Row) & SchemaShape<Key, Columns>;
168
+ declare const schemaShape: unique symbol;
169
+ /**
170
+ * What a relation or an aggregate pointing at a schema reads of it, its key's type and its columns, carried beside
171
+ * its class rather than read off its row: the columns alone settle both while the row is still being inferred.
172
+ */
173
+ type SchemaShape<Key, Columns = unknown> = {
174
+ readonly [schemaShape]?: {
175
+ readonly key: Key;
176
+ readonly columns: Columns;
177
+ };
178
+ };
179
+ /**
180
+ * The key's type: its own column's, else the base's it inherits, `never` for a composite, which no one column can
181
+ * reference, and anything for a schema built from data, whose columns are known only at run time.
182
+ */
183
+ export type SchemaKey<F, Inherited = unknown> = string extends keyof F ? unknown : FlagKeys<F, Column<{
184
+ readonly isId: true;
185
+ }>> extends infer K extends keyof F ? [K] extends [never] ? Inherited : true extends IsUnion<K> ? never : ColumnValueOf<F[K]> : never;
186
+ /** The columns of `O` holding a `V`: a foreign key to a key of that type. */
187
+ type KeyHolding<O, V> = {
188
+ [K in keyof O]-?: NonNullable<O[K]> extends V ? K : never;
189
+ }[keyof O];
190
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -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.