uql-orm 0.104.1 → 0.105.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +24 -10
  2. package/dist/browser/querier/httpQuerier.d.ts +3 -3
  3. package/dist/browser/type/clientQuerier.d.ts +1 -1
  4. package/dist/browser/uql-browser.min.js +2 -2
  5. package/dist/browser/uql-browser.min.js.map +9 -9
  6. package/dist/cockroachdb/cockroachDialect.d.ts +2 -2
  7. package/dist/dialect/abstractDialect.d.ts +3 -3
  8. package/dist/dialect/abstractSqlDialect.d.ts +39 -37
  9. package/dist/dialect/abstractSqlDialect.js +35 -32
  10. package/dist/dialect/aliases.d.ts +2 -0
  11. package/dist/dialect/aliases.js +2 -0
  12. package/dist/dialect/jsonSql.js +2 -2
  13. package/dist/dialect/mergeSqlDialect.d.ts +2 -2
  14. package/dist/dialect/mysqlLikeSqlDialect.d.ts +7 -7
  15. package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
  16. package/dist/dialect/operators.js +2 -4
  17. package/dist/dialect/queryJoins.d.ts +4 -2
  18. package/dist/dialect/vectorSqlDialect.d.ts +1 -1
  19. package/dist/dialect/vectorSqlDialect.js +1 -1
  20. package/dist/entity/column.d.ts +3 -0
  21. package/dist/entity/column.js +3 -0
  22. package/dist/entity/columnOptionsBuilder.d.ts +54 -0
  23. package/dist/entity/columnOptionsBuilder.js +108 -0
  24. package/dist/entity/decorator/bag.d.ts +5 -5
  25. package/dist/entity/decorator/entity.d.ts +3 -20
  26. package/dist/entity/decorator/entity.js +3 -37
  27. package/dist/entity/decorator/members.d.ts +46 -76
  28. package/dist/entity/decorator/members.js +18 -7
  29. package/dist/entity/index.d.ts +2 -1
  30. package/dist/entity/index.js +2 -1
  31. package/dist/entity/metadata/definition.d.ts +15 -26
  32. package/dist/entity/metadata/definition.js +344 -148
  33. package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
  34. package/dist/entity/metadata/schemaFixture/animal.js +7 -0
  35. package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
  36. package/dist/entity/metadata/schemaFixture/author.js +25 -0
  37. package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
  38. package/dist/entity/metadata/schemaFixture/book.js +23 -0
  39. package/dist/http/contract.d.ts +2 -2
  40. package/dist/http/handler.d.ts +2 -2
  41. package/dist/http/query.js +12 -13
  42. package/dist/index.d.ts +2 -2
  43. package/dist/index.js +2 -1
  44. package/dist/mariadb/mariaDialect.d.ts +2 -2
  45. package/dist/mariadb/mariaDialect.js +1 -1
  46. package/dist/mariadb/mariadbQuerier.js +1 -3
  47. package/dist/migrate/builder/columnBuilder.d.ts +20 -68
  48. package/dist/migrate/builder/columnBuilder.js +104 -110
  49. package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
  50. package/dist/migrate/builder/migrationBuilder.js +7 -6
  51. package/dist/migrate/builder/tableBuilder.d.ts +3 -55
  52. package/dist/migrate/builder/tableBuilder.js +88 -204
  53. package/dist/migrate/builder/types.d.ts +52 -151
  54. package/dist/migrate/builder/types.js +0 -6
  55. package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
  56. package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
  57. package/dist/migrate/codegen/entityTypes.d.ts +2 -2
  58. package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
  59. package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
  60. package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
  61. package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
  62. package/dist/migrate/ddl/defaultSql.js +7 -6
  63. package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
  64. package/dist/migrate/ddl/indexCapabilities.js +26 -13
  65. package/dist/migrate/ddl/indexDdl.d.ts +13 -13
  66. package/dist/migrate/ddl/indexDdl.js +33 -30
  67. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
  68. package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
  69. package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
  70. package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
  71. package/dist/migrate/drift/driftDetector.js +2 -2
  72. package/dist/migrate/generator/definitionToNode.d.ts +8 -2
  73. package/dist/migrate/generator/definitionToNode.js +4 -5
  74. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
  75. package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
  76. package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
  77. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
  78. package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
  79. package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
  80. package/dist/migrate/introspection/postgresIntrospector.js +3 -4
  81. package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
  82. package/dist/migrate/introspection/tableSchemaAST.js +5 -1
  83. package/dist/migrate/migrator.d.ts +2 -2
  84. package/dist/migrate/schemaChange.d.ts +3 -3
  85. package/dist/migrate/schemaChange.js +3 -2
  86. package/dist/migrate/schemaGenerator.d.ts +5 -5
  87. package/dist/migrate/schemaGenerator.js +1 -1
  88. package/dist/migrate/storage/databaseStorage.js +4 -4
  89. package/dist/mongodb/mongoDialect.d.ts +41 -44
  90. package/dist/mongodb/mongoDialect.js +118 -32
  91. package/dist/mongodb/mongoIntrospector.d.ts +3 -1
  92. package/dist/mongodb/mongoIntrospector.js +11 -5
  93. package/dist/mongodb/mongoSchemaGenerator.d.ts +4 -4
  94. package/dist/mongodb/mongoSchemaGenerator.js +35 -27
  95. package/dist/mongodb/mongodbQuerier.d.ts +1 -11
  96. package/dist/mongodb/mongodbQuerier.js +9 -43
  97. package/dist/mssql/mssqlDialect.d.ts +4 -4
  98. package/dist/postgres/postgresDialect.d.ts +2 -2
  99. package/dist/querier/abstractQuerier.d.ts +0 -1
  100. package/dist/querier/abstractQuerier.js +1 -20
  101. package/dist/querier/abstractSqlQuerier.d.ts +1 -1
  102. package/dist/querier/keyset.js +3 -3
  103. package/dist/schema/declaredColumn.d.ts +11 -0
  104. package/dist/schema/declaredColumn.js +21 -0
  105. package/dist/schema/indexColumns.d.ts +0 -3
  106. package/dist/schema/indexColumns.js +11 -7
  107. package/dist/schema/indexDifferences.d.ts +10 -5
  108. package/dist/schema/indexDifferences.js +42 -28
  109. package/dist/schema/schemaASTBuilder.d.ts +4 -4
  110. package/dist/schema/schemaASTBuilder.js +28 -36
  111. package/dist/schema/schemaASTDiffer.js +8 -4
  112. package/dist/schema/sqlExpression.d.ts +21 -17
  113. package/dist/schema/sqlExpression.js +11 -23
  114. package/dist/type/column.d.ts +328 -0
  115. package/dist/type/column.js +2 -0
  116. package/dist/type/config.d.ts +3 -3
  117. package/dist/type/dialect.d.ts +15 -14
  118. package/dist/type/dialect.js +1 -0
  119. package/dist/type/entity.d.ts +292 -281
  120. package/dist/type/entity.js +6 -1
  121. package/dist/type/index.d.ts +2 -0
  122. package/dist/type/index.js +2 -0
  123. package/dist/type/migration.d.ts +11 -11
  124. package/dist/type/querier.d.ts +2 -2
  125. package/dist/type/query.d.ts +44 -40
  126. package/dist/type/query.js +2 -3
  127. package/dist/type/queryAggregate.d.ts +22 -12
  128. package/dist/type/querySql.d.ts +22 -6
  129. package/dist/type/querySql.js +27 -9
  130. package/dist/type/schemaEntity.d.ts +194 -0
  131. package/dist/type/schemaEntity.js +1 -0
  132. package/dist/type/utility.d.ts +4 -7
  133. package/dist/type/vector.d.ts +1 -1
  134. package/dist/util/ddlExpression.util.d.ts +12 -13
  135. package/dist/util/ddlExpression.util.js +12 -21
  136. package/dist/util/dialect.util.d.ts +11 -5
  137. package/dist/util/dialect.util.js +31 -37
  138. package/dist/util/field.util.d.ts +10 -9
  139. package/dist/util/field.util.js +14 -10
  140. package/dist/util/fieldOption.util.d.ts +11 -95
  141. package/dist/util/fieldOption.util.js +49 -16
  142. package/dist/util/hook.util.d.ts +3 -15
  143. package/dist/util/hook.util.js +3 -16
  144. package/dist/util/index.d.ts +1 -0
  145. package/dist/util/index.js +1 -0
  146. package/dist/util/indexEntry.util.d.ts +45 -0
  147. package/dist/util/indexEntry.util.js +138 -0
  148. package/dist/util/relationQuery.util.d.ts +0 -1
  149. package/dist/util/relationQuery.util.js +0 -5
  150. package/dist/util/sql.d.ts +13 -10
  151. package/dist/util/sql.js +34 -16
  152. package/dist/util/sql.util.d.ts +4 -5
  153. package/dist/util/sql.util.js +7 -16
  154. package/dist/util/string.util.d.ts +2 -0
  155. package/dist/util/string.util.js +4 -0
  156. package/dist/util/triggerWrite.d.ts +5 -5
  157. package/dist/util/uqlError.d.ts +1 -1
  158. package/dist/util/uqlError.js +1 -1
  159. package/package.json +1 -1
  160. package/skills/uql-orm/SKILL.md +76 -25
  161. package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
@@ -1,9 +1,10 @@
1
1
  import type { EnumValues, ForeignKeyAction, IndexType } from '../schema/types.js';
2
2
  import type { SqlDialectName } from './dialect.js';
3
+ import type { Querier } from './querier.js';
3
4
  import type { FilterOptions, RelationQuery } from './query.js';
4
- import type { ColumnRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
5
+ import type { ColumnRef, JsonPathRef, QuerySql, SqlFor, RelationAggregate } from './querySql.js';
5
6
  import type { QueryWhere } from './queryWhere.js';
6
- import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, JsonBrand, IsMany, Json, JsonScalar, Scalar, Type, Unpacked, Writable } from './utility.js';
7
+ import type { AtLeastOne, Except, ExactlyOne, IsEqual, IsJson, JsonBrand, IsMany, Json, JsonScalar, Scalar, Type, AbstractType, Unpacked, Writable } from './utility.js';
7
8
  import type { VectorDistance, VectorIndexOptions, VectorIndexType } from './vector.js';
8
9
  /** Brands the property an entity is identified by, where it is not `id`, `_id` or `uuid`. */
9
10
  export declare const idKey: unique symbol;
@@ -22,16 +23,14 @@ type BrandNames<E, B extends EntityBrand> = E extends {
22
23
  } ? N : never;
23
24
  /**
24
25
  * A brand naming a key that is no field, which each reader would drop silently: refused where an entity
25
- * registers, `@Entity()` or `defineEntity`, by a member the class lacks that names the typo. A class with no
26
+ * registers, `@Entity()`, by a member the class lacks that names the typo. A class with no
26
27
  * members matches every optional brand, so only one declaring a brand is read.
27
28
  */
28
29
  export type BrandsNameFields<E> = {
29
30
  readonly [N in Exclude<[EntityBrand & keyof E] extends [never] ? never : BrandNames<E, EntityBrand>, FieldKey<E>> & string as `brand names '${N}', which is no field`]: never;
30
31
  };
31
- /** The filter `@Field({ softDelete })` registers, a name reserved against an entity's own filters. */
32
+ /** The filter a `softDelete()` column registers, a name reserved against an entity's own filters. */
32
33
  export declare const SOFT_DELETE_FILTER = "softDelete";
33
- /** A filter name an entity may declare: any but {@link SOFT_DELETE_FILTER}, which a refusal names. */
34
- export type FilterName<N extends string> = N extends typeof SOFT_DELETE_FILTER ? `'${N}' is reserved for the filter @Field({ softDelete }) registers` : N;
35
34
  /** The key names of an entity. */
36
35
  export type Key<E> = keyof E & string;
37
36
  /**
@@ -70,7 +69,7 @@ export type WriteRow<E, F extends keyof E = WritableKey<E>> = {
70
69
  };
71
70
  /**
72
71
  * The property an entity brands with {@link versionKey} as its optimistic lock, `never` where it
73
- * brands none. The brand is what carries `@Field({ version: true })` to the type level, since a
72
+ * brands none. The brand is what carries `f.version()` to the type level, since a
74
73
  * decorator's options never reach `E`.
75
74
  */
76
75
  export type VersionKey<E> = E extends {
@@ -99,7 +98,7 @@ type UnwrapJson<T> = IsJson<T> extends true ? (IsEqual<T, Json> extends true ? u
99
98
  type JsonPayload<V, T = NonNullable<V>> = IsJson<T> extends true ? UnwrapJson<T> : UnwrapJson<NonNullable<Unpacked<T>>>;
100
99
  /** Whether `V` is what a JSON column holds. */
101
100
  type IsJsonColumn<V> = [JsonPayload<V>] extends [never] ? false : true;
102
- /** The JSON columns of `E`, which an index can address. */
101
+ /** The JSON columns of `E`. */
103
102
  type JsonColumnKey<E> = {
104
103
  readonly [K in keyof E]-?: IsJsonColumn<E[K]> extends true ? K : never;
105
104
  }[Key<E>];
@@ -232,7 +231,7 @@ type IdMap<E> = Partial<Pick<E, IdKey<E>>>;
232
231
  */
233
232
  export type EntityId<E> = IdValue<E> | IdMap<E>;
234
233
  /** Whether `T` is a union of more than one member, which for a key means the entity's is composite. */
235
- type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
234
+ export type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
236
235
  /**
237
236
  * The id a write reports: the value for a single key, the map for a composite. {@link EntityId} where
238
237
  * the entity names no key, since a composite cannot then be told from a single one.
@@ -259,63 +258,65 @@ type TimeColumnType = 'time';
259
258
  /** A numeric column holding an exact decimal, read as its text: a JS number would round it. */
260
259
  type DecimalColumnType = 'decimal' | 'numeric';
261
260
  export type JsonColumnType = ColumnTypeOf<'json'>;
261
+ /**
262
+ * A JSON column's payload described as data, in a field's vocabulary: a value's type (`String`), an object of
263
+ * shapes, a key ending in `?` for an optional member, and `[shape]` for an array of it.
264
+ * @example `{ theme: String, 'nickname?': String, tags: [String], billing: { plan: String } }`
265
+ */
266
+ export type JsonShape = JsonLeaf | readonly [JsonShape] | {
267
+ readonly [key: string]: JsonShape;
268
+ };
269
+ /** The values a JSON document holds at a leaf. */
270
+ type JsonLeaf = StringConstructor | NumberConstructor | BooleanConstructor;
271
+ /** The payload a {@link JsonShape} describes. */
272
+ export type ShapeValue<S> = S extends readonly [infer E] ? ShapeValue<E>[] : S extends JsonLeaf ? TsTypeOf<S> : [Extract<keyof S, `${string}?`>] extends [never] ? {
273
+ -readonly [K in keyof S]: ShapeValue<S[K]>;
274
+ } : {
275
+ -readonly [K in keyof S as K extends `${string}?` ? never : K]: ShapeValue<S[K]>;
276
+ } & {
277
+ -readonly [K in keyof S as K extends `${infer N}?` ? N : never]?: ShapeValue<S[K]>;
278
+ };
262
279
  export type BlobColumnType = ColumnTypeOf<'blob'>;
263
280
  export type BooleanColumnType = ColumnTypeOf<'boolean'>;
264
281
  export type VectorColumnType = ColumnTypeOf<'vector'>;
265
282
  /** SQL column types supported by uql migrations. */
266
283
  export type ColumnType = ColumnTypeOf<ColumnFamily>;
267
- type ColumnTypeFamily<T> = {
268
- [F in ColumnFamily]: T extends ColumnTypeOf<F> ? F : never;
269
- }[ColumnFamily];
270
- /** The family a declared `type` puts a column in, or every family where it names none. */
271
- export type FamilyOf<T> = T extends ColumnType ? ColumnTypeFamily<T> : T extends NumberConstructor | BigIntConstructor ? 'numeric' : T extends StringConstructor ? 'string' : T extends DateConstructor ? 'date' : T extends BooleanConstructor ? 'boolean' : ColumnFamily;
272
284
  /** What a field declares its `type` as: a constructor, or a column type. */
273
285
  export type FieldType = StringConstructor | NumberConstructor | BooleanConstructor | DateConstructor | BigIntConstructor | ColumnType;
274
- /**
275
- * The {@link FieldType}s legal for a field declared as `V`, so `type: String` on a `number` does not
276
- * compile. JSON is matched on its brand, which a `Json<string>` shares with `string`, and arrays before
277
- * scalars, so a vector is not read as a `number`.
278
- */
279
- export type TypeFor<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonColumnType : T extends readonly number[] ? VectorColumnType : T extends string ? StringConstructor | StringColumnType | TimeColumnType | DecimalColumnType : T extends number ? NumberConstructor | Exclude<NumericColumnType, DecimalColumnType> : T extends bigint ? BigIntConstructor | NumericColumnType : T extends boolean ? BooleanConstructor | BooleanColumnType : T extends Date ? DateConstructor | Exclude<DateColumnType, TimeColumnType> : T extends Uint8Array ? BlobColumnType : FieldType;
280
286
  /** A field as the registry holds it: what was authored, plus what registration worked out, which no decorator can write. */
281
- export type FieldMeta<V = TsTypeOf<FieldType>> = Except<FieldOptions<V>, 'computed'> & {
282
- /** {@link FieldOptions.computed}, a callback resolved to the SQL it returns. */
283
- readonly computed?: QuerySql;
287
+ export type FieldMeta<V = unknown> = FieldOptions<V> & {
284
288
  /** Whether the column type comes from the referenced key, where the field gave `references` but no `type`. */
285
289
  readonly typeFromReference?: boolean;
286
290
  };
287
291
  /** A field's options, checked against `V`, the value the column holds: every scalar where the field is unknown. */
288
- export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
292
+ export type FieldOptions<V = unknown> = {
289
293
  readonly name?: string;
290
294
  readonly isId?: true;
291
295
  readonly type?: FieldType;
292
- /** A vector column's dimensions: `@Field({ type: 'vector', dimensions: 1536 })`. */
296
+ /** A vector column's dimensions: `f.vector(1536)`. */
293
297
  readonly dimensions?: number;
294
298
  /**
295
299
  * The metric a vector search on this field uses unless it names its own `$distance`; by default its
296
- * vector index's metric, else `'cosine'`.
300
+ * vector index's metric, else `'cosine'`. Where both name one, they must agree.
297
301
  */
298
302
  readonly distance?: VectorDistance;
299
303
  /** The entity this column is a foreign key to. */
300
304
  readonly references?: EntityGetter;
301
305
  /**
302
- * The foreign key's delete action, `@Field({ references: () => Company, onDelete: 'CASCADE' })`. A
306
+ * The foreign key's delete action, `f.references(() => Company).onDelete('CASCADE')`. A
303
307
  * relation over the column wins, and is where the update action goes: `onUpdate` here is a value callback.
304
308
  */
305
309
  readonly onDelete?: ForeignKeyAction;
306
- /**
307
- * The values the column accepts, `enum: ['draft', 'paid'] as const`: a `CHECK (col IN (...))` on every
308
- * SQL engine, and the property's type through the decorator, which is why they have to be `as const`.
309
- */
310
+ /** The values the column accepts, `f.enum(['draft', 'paid'])`: a `CHECK (col IN (...))` on every SQL engine. */
310
311
  readonly enum?: EnumValues;
312
+ /** A JSON column's payload, which a schema entity's row reads it as: `shape: { theme: String, tags: [String] }`. */
313
+ readonly shape?: JsonShape;
311
314
  /**
312
- * An expression the database computes, never written: spliced into each read, or with `stored` a
313
- * generated column, `computed: (user) => sql`${user.first} || ' ' || ${user.last}``.
314
- *
315
- * A relation aggregate is the other form, `computed: (user) => user.resources.count()`, read as the
316
- * subquery a `$count` reads. Both resolve to SQL at registration, so everything downstream sees one.
315
+ * An expression the database computes, never written: spliced into each read, or with `stored` a generated
316
+ * column, `.as(sql`${user.first} || ' ' || ${user.last}`)`. A relation aggregate, `user.resources.count()`,
317
+ * is the other form, read as the subquery a `$count` reads.
317
318
  */
318
- readonly computed?: ComputedSql<E>;
319
+ readonly computed?: QuerySql;
319
320
  /**
320
321
  * Where {@link FieldOptions.computed} lives instead of being spliced into each read. `true` makes it a
321
322
  * generated column, which takes only an immutable expression; a list of events makes it a stamp a trigger
@@ -338,8 +339,8 @@ export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
338
339
  */
339
340
  readonly version?: true;
340
341
  /**
341
- * The SQL type, where it differs from the one `type` implies: `type: String, columnType: 'decimal'`.
342
- * An engine's own type is a `sql` constant, `columnType: sql`tsvector``, rendered verbatim and
342
+ * The SQL type, where it differs from the one `type` implies: `f.string().columnType('char')`.
343
+ * An engine's own type is a `sql` constant, `.columnType(sql`tsvector`)`, rendered verbatim and
343
344
  * never translated, so a column declaring one is yours to keep portable.
344
345
  */
345
346
  readonly columnType?: ColumnType | QuerySql;
@@ -349,7 +350,8 @@ export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
349
350
  readonly precision?: number;
350
351
  /** A decimal column's scale. */
351
352
  readonly scale?: number;
352
- readonly nullable?: boolean;
353
+ /** Whether the column holds NULL: NOT NULL unless `true`, as `nullable()` writes it. */
354
+ readonly nullable?: true;
353
355
  readonly unique?: boolean;
354
356
  /** The column's DDL default: a literal, or SQL the database evaluates per inserted row (`currentTimestamp`, `sql`). */
355
357
  readonly defaultValue?: DdlDefault<V> | QuerySql;
@@ -363,70 +365,19 @@ export type FieldOptions<V = TsTypeOf<FieldType>, E = unknown> = {
363
365
  /** The column's comment in the database. */
364
366
  readonly comment?: string;
365
367
  };
366
- export type OnFieldCallback<V = TsTypeOf<FieldType>> = V | QuerySql | (() => V | QuerySql);
368
+ export type OnFieldCallback<V = unknown> = V | QuerySql | (() => V | QuerySql);
367
369
  /**
368
370
  * What a column may default to: its value, or on a JSON column the document it stores, `[]`, or its SQL text,
369
371
  * `'{}'`. The erased `FieldOptions` takes them all, so every field's options stay assignable to it.
370
372
  */
371
- type DdlDefault<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonDdlDefault : [TsTypeOf<FieldType>] extends [T] ? JsonDdlDefault | T : T;
373
+ export type DdlDefault<V, T = NonNullable<V>> = IsJsonColumn<T> extends true ? JsonDdlDefault : [TsTypeOf<FieldType>] extends [T] ? JsonDdlDefault | T : T;
372
374
  /** What a JSON column, and the field-less `FieldOptions`, may default to: a document, a list included, or its text. */
373
375
  type JsonDdlDefault = Scalar | Record<string, unknown> | readonly unknown[];
374
- /**
375
- * The TypeScript type a declared `type` implies, the inverse of {@link TypeFor}: a decorator checks the
376
- * property against it, `defineEntity` the other way round. `entityOptions.test-d.ts` keeps them agreeing.
377
- */
376
+ /** The TypeScript type a declared `type` implies: a decorator checks the property against it, a schema derives it. */
378
377
  export type TsTypeOf<T> = T extends StringConstructor ? string : T extends NumberConstructor ? number : T extends BigIntConstructor ? bigint : T extends BooleanConstructor ? boolean : T extends DateConstructor ? Date : T extends StringColumnType | TimeColumnType | DecimalColumnType ? string : T extends NumericColumnType ? number | bigint : T extends BooleanColumnType ? boolean : T extends DateColumnType ? Date : T extends JsonColumnType ? JsonBrand | readonly JsonBrand[] : T extends BlobColumnType ? Uint8Array : T extends VectorColumnType ? readonly number[] : unknown;
379
- /**
380
- * {@link FieldOptions} for a field declared as `V`, `type` checked by {@link TypeFor}. A foreign key may
381
- * omit it, taking the referenced key's column type instead.
382
- */
383
- export type FieldOptionsFor<V, E = unknown> = (FieldOptions<NonNullable<V>, E> & {
384
- readonly type: TypeFor<V>;
385
- readonly isId: true;
386
- }) | (FieldOptions<NonNullable<V>, E> & {
387
- readonly type: TypeFor<V>;
388
- } & DeclaresNotNull<V>) | (FieldOptions<NonNullable<V>, E> & {
389
- readonly references: EntityGetter;
390
- readonly type?: TypeFor<V>;
391
- } & DeclaresNotNull<V>) | AggregateOptionsFor<V, E>;
392
- /**
393
- * A column holds `null` unless `nullable: false` says otherwise, and a read hydrates one, so a property
394
- * that does not admit it says so here. The decorators state the same rule the other way round, against
395
- * the property they are applied to; a key needs neither, being NOT NULL on every engine.
396
- */
397
- type DeclaresNotNull<V> = null extends V ? unknown : {
398
- readonly nullable: false;
399
- };
400
- /**
401
- * A field a relation aggregate computes: the aggregate types it, so it declares no `type`, and it is
402
- * read on each query, never `stored`.
403
- */
404
- type AggregateOptionsFor<V, E> = Except<FieldOptions<NonNullable<V>, E>, 'computed' | 'stored' | 'type'> & {
405
- readonly computed: AggregateReading<E, V>;
406
- readonly stored?: false;
407
- };
408
- /** An aggregate reading what the property holds, bivariant the way {@link EntitySql} is. */
409
- type AggregateReading<E, V> = {
410
- agg(refs: ComputedRefs<E>): RelationAggregate<null extends V ? NonNullable<V> | null : NonNullable<V>>;
411
- }['agg'];
412
378
  /** The entity a relation points at: `Company` for `company?: Company` and `companies?: Company[]` alike. */
413
379
  export type RelationTarget<V> = Extract<Unpacked<V>, object>;
414
- /**
415
- * {@link RelationOptions} for a relation declared as `V`, keyed on the `cardinality` its shape allows: a
416
- * key rather than a conditional, which is what types a `mappedBy` callback inside `defineEntity`.
417
- */
418
- export type RelationOptionsFor<V, O = unknown> = {
419
- readonly cardinality: IsMany<V> extends true ? '1m' | 'mm' : '11' | 'm1';
420
- } & (({
421
- readonly cardinality: '11';
422
- } & RelationOneToOneOptions<RelationTarget<V>, O>) | ({
423
- readonly cardinality: 'm1';
424
- } & RelationManyToOneOptions<RelationTarget<V>, O>) | ({
425
- readonly cardinality: '1m';
426
- } & RelationOneToManyOptions<RelationTarget<V>, O>) | ({
427
- readonly cardinality: 'mm';
428
- } & RelationManyToManyOptions<RelationTarget<V>, O>));
429
- /** The method names of an entity, which a hook registration names. */
380
+ /** The method names of an entity, which no query reads as a field or a relation. */
430
381
  export type MethodKey<E> = {
431
382
  readonly [K in keyof E]-?: NonNullable<E[K]> extends (...args: never[]) => unknown ? K : never;
432
383
  }[Key<E>];
@@ -440,16 +391,9 @@ export type CascadeType = 'persist' | 'delete';
440
391
  * `E` is the relation's target and `O` the entity declaring it, whose fields `references` names on its
441
392
  * `local` side; the relation decorators infer `O` from the class they sit on.
442
393
  */
443
- export type RelationOptions<E, O = unknown> = {
394
+ export type RelationOptions<E, O = unknown> = RelationCascade & RelationActions & {
444
395
  entity: EntityGetter<E>;
445
396
  cardinality: RelationCardinality;
446
- readonly cascade?: boolean | CascadeType;
447
- /**
448
- * The foreign key's delete action, the database's alternative to `cascade`, read on the owning side;
449
- * unset, the column's own `@Field({ onDelete })` applies.
450
- */
451
- readonly onDelete?: ForeignKeyAction;
452
- readonly onUpdate?: ForeignKeyAction;
453
397
  /** The inverse side: the member of the target holding the foreign key or the owning relation, `(post) => post.author`. */
454
398
  mappedBy?: (keys: KeyMap<E>) => RelationKey<E> | ForeignKey<E, O>;
455
399
  /** The junction entity of a many-to-many, holding a foreign key to each side. */
@@ -460,6 +404,15 @@ export type RelationOptions<E, O = unknown> = {
460
404
  */
461
405
  references?: (local: KeyMap<O>, foreign: KeyMap<E>) => ForeignKey<O, E> | readonly RelationReference<O, E>[];
462
406
  };
407
+ /** Whether writes reach the related rows in the same transaction; its own type, so an option set takes it without instantiating `RelationOptions`. */
408
+ type RelationCascade = {
409
+ readonly cascade?: boolean | CascadeType;
410
+ };
411
+ /** The foreign key's actions, read on the owning side; unset, the column's own `onDelete` applies. */
412
+ type RelationActions = {
413
+ readonly onDelete?: ForeignKeyAction;
414
+ readonly onUpdate?: ForeignKeyAction;
415
+ };
463
416
  /** The one column of `O` that can be a foreign key to `E`: a field holding `E`'s key, which has to be a single one. */
464
417
  type ForeignKey<O, E> = HasCompositeKey<E> extends true ? never : FieldKeyHolding<O, IdValue<E>>;
465
418
  /** One pair of join columns, each a field read off its entity's key map, the local one holding the foreign's value. */
@@ -477,8 +430,6 @@ export type FieldKeyOf<E, T> = {
477
430
  type FieldKeyHolding<O, V> = {
478
431
  readonly [K in keyof O]-?: [NonNullable<V>] extends [NonNullable<O[K]>] ? K : never;
479
432
  }[FieldKey<O>];
480
- /** {@link RelationOptions.references} as pairs alone, for a to-many, which holds no foreign key of its own to name. */
481
- type RelationReferencePairs<E, O> = (local: KeyMap<O>, foreign: KeyMap<E>) => readonly RelationReference<O, E>[];
482
433
  /** A relation once `getMeta` resolved it: `references` settled into pairs and `mappedBy` a name. */
483
434
  export type RelationMeta = Omit<RelationRegistration, 'references'> & {
484
435
  references: RelationReferences;
@@ -491,22 +442,53 @@ export type RelationRegistration = Omit<RelationOptions<object>, 'mappedBy' | 'r
491
442
  mappedBy?: string;
492
443
  references?: RelationReferences | string;
493
444
  };
494
- /** How a to-many owner reaches its children: a junction entity or the join columns, never both. */
495
- type RelationOwnerJoin<E, O> = (Required<Pick<RelationOptions<E, O>, 'through'>> & {
496
- readonly references?: never;
497
- }) | {
498
- readonly references: RelationReferencePairs<E, O>;
499
- readonly through?: never;
445
+ /**
446
+ * What a relation's join callbacks answer, `E` its target and `O` the entity declaring it: one foreign key, pairs of
447
+ * columns, or the target's member mapping it. Each form states its own: a decorated class checks each member's
448
+ * kind, a schema reads keys alone, since its target's types are still being inferred.
449
+ */
450
+ export type RelationJoins = {
451
+ readonly key: unknown;
452
+ readonly pairs: unknown;
453
+ readonly mappedBy: unknown;
454
+ };
455
+ /** A decorated class's joins, each member checked by kind. */
456
+ type DecoratedJoins<E, O> = {
457
+ readonly key: ForeignKey<O, E>;
458
+ readonly pairs: readonly RelationReference<O, E>[];
459
+ readonly mappedBy: RelationKey<E> | ForeignKey<E, O>;
500
460
  };
501
461
  /**
502
- * The side holding the foreign key, which `references` names and the actions attach to. It cascades
503
- * `'persist'` only: its target may be other rows' too, so a delete cascades from the side owning the rows.
462
+ * The side holding the foreign key, which the actions attach to. It cascades `'persist'` only: its target may
463
+ * be other rows' too, so a delete cascades from the side owning the rows.
504
464
  */
505
- type RelationOptionsOwner<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'onDelete' | 'onUpdate'> & Required<Pick<RelationOptions<E, O>, 'references'>> & {
465
+ type RelationOwnerSide = RelationActions & {
506
466
  readonly cascade?: 'persist';
467
+ readonly mappedBy?: never;
468
+ readonly through?: never;
469
+ };
470
+ /** The join columns: a to-one's foreign key, `(post) => post.authorId`, or pairs where no key fits. */
471
+ type RelationColumns<E, O, J extends RelationJoins> = (local: KeyMap<O>, foreign: KeyMap<E>) => J['key'] | J['pairs'];
472
+ /** The owning side of a to-one, naming its foreign key. */
473
+ export type RelationOwnerOptions<E, O, J extends RelationJoins> = RelationOwnerSide & {
474
+ readonly references: RelationColumns<E, O, J>;
507
475
  };
508
- type RelationOptionsInverseSide<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'cascade'> & Required<Pick<RelationOptions<E, O>, 'mappedBy'>>;
509
- type RelationOptionsThroughOwner<E, O> = Pick<RelationOptions<E, O>, 'entity' | 'cascade'> & RelationOwnerJoin<E, O>;
476
+ /** The inverse side, mapped by the target's member holding the foreign key or the owning relation. */
477
+ export type RelationInverseOptions<E, J extends RelationJoins> = RelationCascade & {
478
+ readonly mappedBy: (keys: KeyMap<E>) => J['mappedBy'];
479
+ readonly references?: never;
480
+ readonly through?: never;
481
+ };
482
+ /** How a to-many owner reaches its rows: a junction entity or the join columns, never both. */
483
+ export type RelationJoinOptions<E, O, J extends RelationJoins> = RelationCascade & {
484
+ readonly mappedBy?: never;
485
+ } & ({
486
+ readonly through: EntityGetter;
487
+ readonly references?: never;
488
+ } | {
489
+ readonly references: (local: KeyMap<O>, foreign: KeyMap<E>) => J['pairs'];
490
+ readonly through?: never;
491
+ });
510
492
  /** The key names of `E` as values, so a definition reads a member off it, `(post) => post.author`, and follows a rename. */
511
493
  export type KeyMap<E> = {
512
494
  readonly [K in keyof E]-?: K;
@@ -515,17 +497,14 @@ export type KeyMap<E> = {
515
497
  export type RefMap<E, F extends keyof E = FieldKey<E>> = {
516
498
  readonly [K in F]-?: ColumnRef<K & string, E[K]>;
517
499
  };
518
- /** SQL a definition writes: `sql`, or a callback reading the fields off its refs, bivariant so the registry can hold it. */
519
- export type EntitySql<E> = QuerySql | {
520
- sql(refs: RefMap<E>): QuerySql;
521
- }['sql'];
522
500
  /** One field of `C`, read off its refs: `(item) => item.amount`. */
523
501
  type PickRef<C, K extends keyof C> = (refs: RefMap<C>) => ColumnRef<K & string>;
524
502
  /**
525
503
  * A relation as a `computed` field reads it, its aggregates typed against the related entity. Each
526
504
  * reads as a subquery; all but `count` and `sum` are `null` where the relation holds no row.
505
+ * Declared invariant: measuring `C`'s variance walks every query type it reaches.
527
506
  */
528
- export type RelationRef<C> = {
507
+ export type RelationRef<in out C> = {
529
508
  count(q?: AggregatePage<C>): RelationAggregate<number>;
530
509
  sum<K extends FieldKeyOf<C, number | bigint>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]>>;
531
510
  min<K extends FieldKey<C>>(pick: PickRef<C, K>, q?: AggregateRows<C>): RelationAggregate<NonNullable<C[K]> | null>;
@@ -553,24 +532,11 @@ export type AggregateTopRows<C> = AggregateFilter<C> & Required<Pick<RelationQue
553
532
  /** Every related row, filtered or not, or the top ones an order picks. */
554
533
  export type AggregateRows<C> = AggregateFilter<C> | AggregateTopRows<C>;
555
534
  /** What a `computed` callback reads: the entity's fields as columns, its to-many relations as aggregates. */
556
- export type ComputedRefs<E, F extends keyof E = FieldKey<E>, R extends keyof E = ToManyRelationKey<E>> = RefMap<E, F> & {
535
+ export type ComputedRefs<E, F extends keyof E = FieldKey<E>> = RefMap<E, F> & ToManyRefs<E>;
536
+ /** Each to-many relation of `E` as an aggregate reads it. */
537
+ export type ToManyRefs<E, R extends keyof E = ToManyRelationKey<E>> = {
557
538
  readonly [K in R]-?: RelationRef<RelationTarget<E[K]>>;
558
539
  };
559
- /** A relation aggregate a definition writes, bivariant the way {@link EntitySql} is. */
560
- export type EntityAggregate<E> = {
561
- agg(refs: ComputedRefs<E>): RelationAggregate;
562
- }['agg'];
563
- /**
564
- * SQL a `computed` field writes. One callback shape for every arm, aggregate or not: overload
565
- * resolution picks a contextual parameter type per arm only while they agree on one.
566
- */
567
- export type ComputedSql<E> = QuerySql | {
568
- sql(refs: ComputedRefs<E>): QuerySql;
569
- }['sql'];
570
- /** The value a field's options declare it holds, where an aggregate is what declares it. */
571
- export type AggregateValue<O> = O extends {
572
- readonly computed: (...args: never[]) => RelationAggregate<infer V>;
573
- } ? V : never;
574
540
  /** A predicate DDL can hold: the entity's own fields, without a relation, `$text` or a sub-query. */
575
541
  export type EntityPredicate<E> = QueryWhere<E> & {
576
542
  readonly [K in RelationKey<E>]?: never;
@@ -579,25 +545,49 @@ export type EntityPredicate<E> = QueryWhere<E> & {
579
545
  readonly $exists?: never;
580
546
  readonly $nexists?: never;
581
547
  };
582
- /** A definition's predicate: an {@link EntityPredicate}, or {@link EntitySql} for what one cannot say. */
583
- export type EntityWhere<E> = EntityPredicate<E> | EntitySql<E>;
584
- /** A definition's predicate as metadata keeps it, a callback resolved to its SQL, for the schema build to compile. */
548
+ /** A definition's predicate: an {@link EntityPredicate}, or `sql` for what one cannot say. */
585
549
  export type EntityWhereMeta<E> = EntityPredicate<E> | QuerySql;
586
550
  export type RelationReferences = {
587
551
  readonly local: string;
588
552
  readonly foreign: string;
589
553
  }[];
590
554
  export type RelationCardinality = '11' | 'm1' | '1m' | 'mm';
591
- export type RelationOneToOneOptions<E, O = unknown> = RelationOptionsOwner<E, O> | RelationOptionsInverseSide<E, O>;
592
- export type RelationOneToManyOptions<E, O = unknown> = RelationOptionsInverseSide<E, O> | RelationOptionsThroughOwner<E, O>;
593
- export type RelationManyToOneOptions<E, O = unknown> = RelationOptionsOwner<E, O>;
594
- export type RelationManyToManyOptions<E, O = unknown> = RelationOptionsThroughOwner<E, O> | RelationOptionsInverseSide<E, O>;
555
+ export type RelationOneToOneOptions<E, O = unknown> = RelationOwnerOptions<E, O, DecoratedJoins<E, O>> | RelationInverseOptions<E, DecoratedJoins<E, O>>;
556
+ /** A to-many naming no join: mapped by the one relation of its target pointing back, found on first read. */
557
+ type RelationMappedBack<E> = RelationCascade & {
558
+ readonly mappedBy?: never;
559
+ readonly through?: never;
560
+ readonly references?: never;
561
+ };
562
+ export type RelationOneToManyOptions<E, O = unknown> = RelationInverseOptions<E, DecoratedJoins<E, O>> | RelationJoinOptions<E, O, DecoratedJoins<E, O>> | RelationMappedBack<E>;
563
+ /** A to-one holding the foreign key; with no `references`, it joins by the one field referencing its target. */
564
+ export type RelationManyToOneOptions<E, O = unknown> = RelationOwnerSide & Partial<Pick<RelationOwnerOptions<E, O, DecoratedJoins<E, O>>, 'references'>>;
565
+ export type RelationManyToManyOptions<E, O = unknown> = RelationJoinOptions<E, O, DecoratedJoins<E, O>> | RelationInverseOptions<E, DecoratedJoins<E, O>>;
595
566
  /** The lifecycle events. An upsert has its own pair: which branch a row takes is the database's to decide. */
596
567
  export type HookEvent = 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeUpsert' | 'afterUpsert' | 'beforeDelete' | 'afterDelete' | 'afterLoad';
597
- /** A registered hook: the entity's method to call. */
598
- export type HookRegistration = {
568
+ /** A hook as declared: the entity's method a decorator names, or the function a schema runs on the row. */
569
+ export type HookDeclaration = {
599
570
  readonly methodName: string;
571
+ } | {
572
+ readonly run: HookFunction;
573
+ };
574
+ /** A registered hook, run on the row; a method's name kept so an entity overriding it replaces its base's. */
575
+ export type HookRegistration = {
576
+ readonly run: HookFunction;
577
+ readonly methodName?: string;
578
+ };
579
+ /**
580
+ * What a lifecycle hook is handed: the querier, to write in the same transaction, and `onCommit`, for what
581
+ * must wait until that transaction commits.
582
+ */
583
+ export type HookContext = {
584
+ readonly querier: Querier;
585
+ readonly onCommit: Querier['onCommit'];
600
586
  };
587
+ /** A schema entity's hook, bivariant in its row, so one typed by its row registers. */
588
+ export type HookFunction = {
589
+ run(row: object, ctx: HookContext): unknown;
590
+ }['run'];
601
591
  /**
602
592
  * An index type with what it needs: a vector index has to name its metric, since engines default to a
603
593
  * different one than the queries use; an Atlas `vectorSearch` index may, else takes its field's, else
@@ -620,35 +610,8 @@ export type IndexTypeOptions = {
620
610
  distance?: never;
621
611
  config?: never;
622
612
  };
623
- /** One index entry as the migration builder takes it: a column name, `sql`, or an object when it needs more. */
624
- export type IndexColumnInput = string | QuerySql | EntityIndexColumn;
625
- /**
626
- * One entry of an entity's index, read off its refs: a column, `sql`, or an object when it needs more.
627
- * @example `@Index((post) => [post.tenantId, { column: post.createdAt, order: 'desc' }, sql`lower(${post.email})`])`
628
- */
629
- export type EntityIndexColumnInput<E> = QuerySql | IndexColumnOptions | IndexJsonColumnOptions<E>;
630
- /** A JSON entry, its `path` checked against its own column's payload: a misspelled one builds an index nothing uses. */
631
- type IndexJsonColumnOptions<E> = {
632
- [K in JsonColumnKey<E>]: IndexColumnPlainModifiers & {
633
- readonly column: ColumnRef<K & string>;
634
- } & ({
635
- readonly jsonPath: WithCheckedPath<IndexJsonPath, E, K>;
636
- readonly jsonArray?: never;
637
- } | {
638
- readonly jsonArray: WithCheckedPath<IndexJsonArray, E, K>;
639
- readonly jsonPath?: never;
640
- });
641
- }[JsonColumnKey<E>];
642
- /** A JSON modifier with its `path` narrowed to the column's payload, everything else taken from `T` as declared. */
643
- type WithCheckedPath<T extends {
644
- path?: string;
645
- }, E, K extends Key<E>> = Except<T, 'path' & keyof T> & {
646
- [P in keyof Pick<T, Extract<keyof T, 'path'>>]: DeepJsonKeys<JsonPayload<E[K]>>;
647
- };
648
- /** What an index entry carries besides its column, shared by the authored and the normalized entry. */
649
- export type IndexColumnModifiers = {
650
- /** Index only the first `n` characters, which the MySQL family requires on a `TEXT` or `BLOB` column. */
651
- readonly length?: number;
613
+ /** What an index entry carries besides what it indexes, at every layer. */
614
+ export type IndexEntryModifiers = {
652
615
  /** Stored sort order, which lets `ORDER BY ... DESC` pagination use the index. */
653
616
  readonly order?: 'asc' | 'desc';
654
617
  /** Where NULLs sort. Postgres only. */
@@ -660,61 +623,113 @@ export type IndexColumnModifiers = {
660
623
  * a whole number from 1 to 99999, the range MongoDB weighs by.
661
624
  */
662
625
  readonly weight?: number;
663
- /** Index a path inside a JSON column. See {@link IndexJsonPath}. */
664
- readonly jsonPath?: IndexJsonPath;
665
- /** Index every element of a JSON array. See {@link IndexJsonArray}. */
666
- readonly jsonArray?: IndexJsonArray;
667
- };
668
- /**
669
- * An index over a path inside a JSON column, spelled as the `$where` on it compiles, which is how the
670
- * planner matches the two. `type` is how the queries compare it.
671
- * @example `@Index((user) => [{ column: user.kind, jsonPath: { path: 'rating', type: Number } }])`
672
- */
673
- export type IndexJsonPath = {
674
- /** The path inside the column, spelled as a `$where` key spells it: `'theme.color'`. */
675
- readonly path: string;
676
- /** How the value is read, matching what the queries over it compare against. */
677
- readonly type: FieldType;
678
- /** Length of a string value, which MySQL keys as `CHAR(n)` and so requires. */
679
- readonly length?: number;
680
626
  };
627
+ /** How an index reads a JSON path: the type its queries compare it as, or `[type]` for each element of an array. */
628
+ export type IndexValueType = FieldType | readonly [FieldType];
681
629
  /**
682
- * MySQL's multi-valued index, one key per element of the JSON array at `path`, which `$all` and an
683
- * `$elemMatch` on one value or several use; refused on any other engine.
684
- * @example `@Index((user) => [{ column: user.tags, jsonArray: { type: String, length: 64 } }])`
630
+ * One index entry: a column as stored, a `path` inside the JSON column `json` read as `type` (text by default,
631
+ * the whole document where it names no path), or an expression. `Sql` is the expression's form, `QuerySql`
632
+ * until the schema renders it to text.
685
633
  */
686
- export type IndexJsonArray = {
687
- /** The array's path inside the column, spelled as a `$where` key spells it; omit for the column. */
634
+ export type IndexEntry<Sql = QuerySql> = IndexEntryModifiers & ((ColumnLengths & {
635
+ readonly column: string;
636
+ readonly json?: never;
637
+ readonly path?: never;
638
+ readonly type?: never;
639
+ readonly expression?: never;
640
+ }) | (JsonLengths & {
641
+ readonly json: string;
688
642
  readonly path?: string;
689
- /** The element type, matching what the queries over the array compare against. */
690
- readonly type: FieldType;
691
- /** Length of a string or binary element, which MySQL's `CHAR(n) ARRAY` cast requires. */
692
- readonly length?: number;
693
- };
694
- /** The modifiers that do not name a JSON path, and so need no entity to be checked against. */
695
- type IndexColumnPlainModifiers = Except<IndexColumnModifiers, 'jsonPath' | 'jsonArray'>;
696
- /** An entity's entry with plain modifiers, never a JSON one, whose path would then go unchecked. */
697
- type IndexColumnOptions = IndexColumnPlainModifiers & {
698
- /** A column read off the refs, or `sql` for an expression. */
643
+ readonly type?: IndexValueType;
644
+ readonly column?: never;
645
+ readonly expression?: never;
646
+ }) | (NoLengths & {
647
+ readonly expression: Sql;
648
+ readonly column?: never;
649
+ readonly json?: never;
650
+ readonly path?: never;
651
+ readonly type?: never;
652
+ }));
653
+ /** The key length a column entry takes. */
654
+ type ColumnLengths = {
655
+ /** A prefix of the column as the key, which the MySQL family requires on a `TEXT` or `BLOB` one. */
656
+ readonly prefixLength?: number;
657
+ readonly charLength?: never;
658
+ };
659
+ /** An entry keyed by its value whole: an expression, or a JSON number or boolean. */
660
+ type NoLengths = {
661
+ readonly prefixLength?: never;
662
+ readonly charLength?: never;
663
+ };
664
+ /** The key length a JSON path entry takes. */
665
+ type JsonLengths = {
666
+ /** The `CHAR(n)` MySQL keys a string path, or each string element, as. */
667
+ readonly charLength?: number;
668
+ readonly prefixLength?: never;
669
+ };
670
+ /** One index entry as the migration builder takes it: a column name, `sql`, or an entry when it needs more. */
671
+ export type IndexColumnInput = string | QuerySql | IndexEntry;
672
+ declare const untypedJson: unique symbol;
673
+ /** The value under a path of a bare {@link Json} column, which any path reads into, as text unless told otherwise. */
674
+ type UntypedJson = {
675
+ readonly [untypedJson]: true;
676
+ };
677
+ /** Any path into an untyped payload, to any depth. */
678
+ interface UntypedJsonPaths {
679
+ readonly [key: string]: JsonPathRef<UntypedJson> & UntypedJsonPaths;
680
+ }
681
+ /** The paths below one holding `V`: each key of an object, any key of an untyped payload, none past a value. */
682
+ type JsonPathMembers<V> = unknown extends V ? UntypedJsonPaths : V extends readonly unknown[] ? unknown : V extends object ? {
683
+ readonly [K in Exclude<keyof V, RefOwnKey>]-?: JsonPathRef<NonNullable<V[K]>> & JsonPathMembers<NonNullable<V[K]>>;
684
+ } : unknown;
685
+ /** The keys a path cannot be read through: a ref's own, and `Object`'s, which every ref has. */
686
+ type RefOwnKey = Extract<keyof ColumnRef, string> | keyof typeof Object.prototype;
687
+ /** A field as an index reads it: its column, and a JSON one's paths too. */
688
+ type IndexRef<K extends string, V> = IsJsonColumn<V> extends true ? ColumnRef<K, V> & JsonPathRef<UntypedLeaf<JsonPayload<V>>> & JsonPathMembers<JsonPayload<V>> : ColumnRef<K, V>;
689
+ type UntypedLeaf<P> = unknown extends P ? UntypedJson : P;
690
+ /** An index's refs: the entity's fields, each JSON one read into along its document's paths. */
691
+ export type IndexRefMap<E, F extends keyof E = FieldKey<E>> = {
692
+ readonly [K in F]-?: IndexRef<K & string, E[K]>;
693
+ };
694
+ /** The types a JSON value of `V` can be compared as, which an index on it reads it as. */
695
+ type JsonReadAs<V> = V extends string ? StringConstructor | StringColumnType : V extends number ? NumberConstructor | NumericColumnType : V extends boolean ? BooleanConstructor | BooleanColumnType : never;
696
+ /**
697
+ * What an object entry indexes: a column or `sql` as it is, or a JSON path read as its queries compare it.
698
+ * A path holding text may say nothing; any other states its `type`, `[type]` for an array's elements.
699
+ */
700
+ type IndexEntryTarget = (ColumnLengths & {
699
701
  readonly column: QuerySql;
700
- readonly jsonPath?: never;
701
- readonly jsonArray?: never;
702
- };
703
- /** One index entry, normalized, as every dialect and generator reads it. */
704
- export type IndexColumnSchema = IndexColumnModifiers & {
705
- /** A column name, or raw SQL when {@link expression} is set. */
706
- readonly column: string;
707
- /** Whether {@link column} is an expression to emit as-is rather than an identifier to quote. */
708
- readonly expression?: boolean;
709
- };
710
- /** One index entry as metadata keeps it: a member, or an expression rendered when the schema is built. */
711
- export type EntityIndexColumn = IndexColumnModifiers & {
712
- readonly column: string | QuerySql;
713
- };
702
+ readonly type?: never;
703
+ }) | (JsonLengths & {
704
+ readonly column: JsonPathRef<string>;
705
+ readonly type?: JsonReadAs<string>;
706
+ }) | (NoLengths & {
707
+ readonly column: JsonPathRef<number>;
708
+ readonly type: JsonReadAs<number>;
709
+ }) | (NoLengths & {
710
+ readonly column: JsonPathRef<boolean>;
711
+ readonly type: JsonReadAs<boolean>;
712
+ }) | (JsonLengths & {
713
+ readonly column: JsonPathRef<readonly string[]>;
714
+ readonly type: readonly [JsonReadAs<string>];
715
+ }) | (NoLengths & {
716
+ readonly column: JsonPathRef<readonly number[]>;
717
+ readonly type: readonly [JsonReadAs<number>];
718
+ }) | (JsonLengths & {
719
+ readonly column: JsonPathRef<UntypedJson>;
720
+ readonly type?: IndexValueType;
721
+ });
722
+ /**
723
+ * One entry of an entity's index, read off its refs: a column, a path inside a JSON one, `sql`, or an object
724
+ * when it needs more.
725
+ * @example `{ columns: (post) => [post.tenantId, { column: post.createdAt, order: 'desc' }, sql`lower(${post.email})`] }`
726
+ * @example `{ columns: (user) => [user.settings.theme, { column: user.settings.rating, type: Number }] }`
727
+ */
728
+ export type EntityIndexColumnInput = QuerySql | JsonPathRef<string> | JsonPathRef<UntypedJson> | (IndexEntryModifiers & IndexEntryTarget);
714
729
  /** An index as metadata keeps it. */
715
730
  export type EntityIndexMeta<E = object> = {
716
- /** The indexed columns, in order. */
717
- columns: readonly EntityIndexColumn[];
731
+ /** The indexed entries, in order. */
732
+ entries: readonly IndexEntry[];
718
733
  /** Custom index name */
719
734
  name?: string;
720
735
  /** Whether index is unique; omit or `false` for a non-unique index (default). */
@@ -725,17 +740,19 @@ export type EntityIndexMeta<E = object> = {
725
740
  include?: readonly string[];
726
741
  } & VectorIndexOptions & IndexTypeOptions;
727
742
  export type EntityMeta<E> = {
728
- readonly entity: Type<E>;
743
+ readonly entity: AbstractType<E>;
729
744
  /** The table, which is the class's own name where the entity named none - see {@link derivedName}. */
730
745
  name?: string;
731
746
  /** Whether {@link name} came from the class rather than from the author, so a naming strategy applies. */
732
747
  derivedName?: boolean;
748
+ /** A base that is never a table, only extended. */
749
+ abstract?: true;
733
750
  /** Set only when the entity named one; unset defers to the pool where it is used. See `AbstractDialect.resolveSchema`. */
734
751
  schema?: string;
735
752
  /** Every column of the primary key, in declaration order. */
736
753
  ids: readonly IdKey<E>[];
737
754
  softDelete?: FieldKey<E>;
738
- /** The optimistic lock's column, from `@Field({ version: true })`. */
755
+ /** The optimistic lock's column, from `f.version()`. */
739
756
  version?: FieldKey<E>;
740
757
  /** Named, default-on `$where` filters applied to every query unless bypassed. */
741
758
  filters?: Record<string, FilterOptions<E>>;
@@ -749,7 +766,7 @@ export type EntityMeta<E> = {
749
766
  } & {
750
767
  [key: string]: RelationMeta | undefined;
751
768
  };
752
- /** Composite indexes defined via @Index decorator */
769
+ /** The indexes `@Entity({ indexes })` or a schema's `indexes` declare. */
753
770
  indexes?: EntityIndexMeta<E>[];
754
771
  /** `CHECK` constraints, compiled when the schema is built. */
755
772
  checks?: EntityCheckMeta<E>[];
@@ -757,10 +774,14 @@ export type EntityMeta<E> = {
757
774
  hooks?: Partial<Record<HookEvent, HookRegistration[]>>;
758
775
  /** Triggers the database runs, compiled when the schema is built. */
759
776
  triggers?: EntityTriggerMeta<E>[];
760
- /** Bumped by every `define*` call, so what is derived from the metadata can tell it changed. */
761
- revision: number;
762
- /** The revision `getMeta` last finalized, which is what makes finalizing idempotent and re-entrant. */
763
- processedAt?: number;
777
+ /**
778
+ * How far the registry finalized it: `'declared'` while a schema takes sections and is not registered, unset
779
+ * once registered, `'settled'` once its schemas' relations, its bases' included, are in, and `'resolved'`
780
+ * once `getMeta` joined them too, which makes each step idempotent and re-entrant.
781
+ */
782
+ stage?: 'declared' | 'settled' | 'resolved';
783
+ /** The fields a read answers with where it names none, set once resolved: see `defaultReadKeys`. */
784
+ readKeys?: readonly FieldKey<E>[];
764
785
  };
765
786
  /** When the database writes a stamp: as the row is inserted, as it is updated, or both. */
766
787
  export type StampEvent = 'insert' | 'update';
@@ -825,7 +846,7 @@ export type TriggerOptions<E = unknown> = {
825
846
  * goes a `WHEN` comparing each with `IS DISTINCT FROM`, which is the point of the pair: `UPDATE OF`
826
847
  * fires on a column that was merely assigned, and the comparison narrows that to one that moved.
827
848
  */
828
- readonly of?: Ev extends TriggerUpdateEvent ? (refs: RefMap<E>) => readonly ColumnRef<string>[] : never;
849
+ readonly of?: Ev extends TriggerUpdateEvent ? readonly ColumnRef<FieldKey<E>>[] : never;
829
850
  /**
830
851
  * A further condition, as the `WHEN` the engine evaluates before entering the body, over the rows the
831
852
  * body reads: a predicate on each, `{ $old: { status: 'draft' }, $new: { status: 'published' } }`,
@@ -855,89 +876,79 @@ export type EntityTriggerMeta<E = object> = Except<TriggerOptions<E>, 'of' | 'wh
855
876
  readonly run: TriggerMetaBody<E> | Readonly<Partial<Record<SqlDialectName, TriggerMetaBody<E>>>>;
856
877
  };
857
878
  /**
858
- * A body as the renderer calls it, with both rows whatever the event. Bivariant, as {@link EntitySql} is,
879
+ * A body as the renderer calls it, with both rows whatever the event. Bivariant,
859
880
  * so a body typing the row its event lacks as `never` is still held here.
860
881
  */
861
882
  export type TriggerMetaBody<E> = {
862
883
  run(newRow: RefMap<E>, oldRow: RefMap<E>): QuerySql;
863
884
  }['run'];
864
- /**
865
- * A table's `CHECK`, `{ where: { balance: { $gte: 0 } } }`, or SQL off the refs,
866
- * `{ where: (wallet) => sql`${wallet.spent} <= ${wallet.balance}` }`.
867
- */
885
+ /** A table's `CHECK`: a predicate, `{ balance: { $gte: 0 } }`, or SQL off the refs, `sql`${wallet.spent} >= 0``. */
868
886
  export type CheckOptions<E = unknown> = {
869
887
  /** Derived from the table and the constraint's position when absent. */
870
888
  readonly name?: string;
871
- readonly where: EntityWhere<E>;
889
+ readonly where: EntityPredicate<E> | QuerySql;
890
+ };
891
+ /**
892
+ * Marks what a section's helper returned, so a section takes only what TypeScript checked: it checks a literal
893
+ * passed to a function, and never one a callback returns, where `{ uniqe: true }` would pass silently.
894
+ */
895
+ export declare const SECTION_ENTRY: unique symbol;
896
+ /** One entry of a section, as its helper made it. */
897
+ export type SectionEntry<T, S extends string> = T & {
898
+ readonly [SECTION_ENTRY]: S;
899
+ };
900
+ /**
901
+ * An entity's indexes over its refs, the columns first and the options or the name after, as the migration
902
+ * builder's `index()` takes them: `(post, index) => [index([post.slug], { unique: true })]`.
903
+ */
904
+ export type IndexSection<E> = (refs: IndexRefMap<E>, index: (columns: readonly EntityIndexColumnInput[], options?: string | EntityIndexOptions<E>) => SectionEntry<EntityIndexInput<E>, 'index'>) => readonly SectionEntry<EntityIndexInput<E>, 'index'>[];
905
+ /** An entity's `CHECK`s over its refs, `(wallet, check) => [check(sql`${wallet.spent} >= 0`)]`, a name after. */
906
+ export type CheckSection<E> = (refs: RefMap<E>, check: (where: CheckOptions<E>['where'], name?: string) => SectionEntry<CheckOptions<E>, 'check'>) => readonly SectionEntry<CheckOptions<E>, 'check'>[];
907
+ /** An entity's triggers over its refs, `(post, trigger) => [trigger({ on: 'beforeUpdate', of: [post.body], run })]`. */
908
+ export type TriggerSection<E> = (refs: RefMap<E>, trigger: (trigger: TriggerOptions<E>) => SectionEntry<TriggerOptions<E>, 'trigger'>) => readonly SectionEntry<TriggerOptions<E>, 'trigger'>[];
909
+ /** An entity's named, default-on `$where` filters; a `softDelete()` column registers its own. */
910
+ export type FilterSection<E> = Readonly<Record<string, FilterOptions<E>>> & {
911
+ readonly [SOFT_DELETE_FILTER]?: never;
872
912
  };
873
913
  /** A `CHECK` as entity metadata keeps it, its callback resolved. */
874
914
  export type EntityCheckMeta<E = object> = {
875
915
  readonly name?: string;
876
916
  readonly where: EntityWhereMeta<E>;
877
917
  };
878
- /** An entity's members as the registry takes them, keyed by name: what decorators and `defineEntity` both reduce to. */
879
- export type EntityMembers = {
880
- readonly fields?: Readonly<Record<string, FieldOptions | undefined>>;
881
- readonly relations?: Readonly<Record<string, RelationRegistration | undefined>>;
882
- readonly hooks?: Readonly<Partial<Record<HookEvent, readonly string[]>>>;
883
- };
884
- /** An entity's fields as `defineEntity` takes them, keyed like every entity map (see `QuerySelect`). */
885
- type EntityFieldOptions<E, F extends keyof E = FieldKey<E>> = {
886
- readonly [K in F]?: FieldOptionsFor<E[K], E>;
887
- };
888
- /** An entity's relations as `defineEntity` takes them, keyed over every member: only that types a `mappedBy` callback. */
889
- type EntityRelationOptions<E> = {
890
- readonly [K in keyof E]?: RelationOptionsFor<E[K], E>;
891
- };
892
- /** An entity's options, `@Entity()` or `defineEntity`; the members too where no decorator declares them. */
918
+ /** A decorated entity's options, `@Entity()`. */
893
919
  export type EntityOptions<E = unknown> = {
894
920
  readonly name?: string;
895
- /** A base to inherit members from, for a class that cannot extend it; its real base, if any, wins. See the Inheritance guide. */
896
- readonly extends?: string extends keyof E ? Type<object> : Type<Partial<E>>;
921
+ /** A base that is never a table: the entities extending it take what it declares. */
922
+ readonly abstract?: true;
897
923
  /** The schema (a MySQL database) the table lives in; unset follows the pool's. */
898
924
  readonly schema?: string;
899
- /** Named, default-on `$where` filters (soft-delete is auto-registered from `@Field({ softDelete })`). */
900
- readonly filters?: Record<string, FilterOptions<E>> & {
901
- readonly [SOFT_DELETE_FILTER]?: never;
902
- };
903
- /** Scalar fields; use `isId: true` on exactly one field for the primary key. */
904
- readonly fields?: EntityFieldOptions<E>;
905
- readonly relations?: EntityRelationOptions<E>;
906
- readonly indexes?: readonly EntityIndexInput<E>[];
925
+ readonly filters?: FilterSection<E>;
926
+ readonly indexes?: IndexSection<E>;
907
927
  /** Table-level `CHECK` constraints. See {@link CheckOptions}. */
908
- readonly checks?: readonly CheckOptions<E>[];
909
- /** Each lifecycle event and the methods it runs, read off the key map: `{ beforeInsert: (post) => [post.stamp] }`. */
910
- readonly hooks?: Partial<Record<HookEvent, (keys: KeyMap<E>) => readonly MethodKey<E>[]>>;
928
+ readonly checks?: CheckSection<E>;
911
929
  /** Triggers the database runs, in the order written. See {@link TriggerOptions}. */
912
- readonly triggers?: readonly TriggerOptions<E>[];
930
+ readonly triggers?: TriggerSection<E>;
913
931
  };
914
932
  /**
915
933
  * Everything an index carries beyond its columns, as the migration builder's `table.index(...)` takes it,
916
- * and through {@link EntityIndexOptions} `@Index` and `defineEntity`. `Except` (not plain `Omit`) keeps
934
+ * and through {@link EntityIndexOptions} an entity's `indexes`. `Except` (not plain `Omit`) keeps
917
935
  * `type`/`distance` a discriminated pair: omitting `distance` on a vector index type is a compile error.
918
936
  */
919
- export type IndexOptions = Except<EntityIndexMeta, 'columns' | 'where'> & {
937
+ export type IndexOptions = Except<EntityIndexMeta, 'entries' | 'where'> & {
920
938
  /** Partial-index predicate, as `sql` with no interpolation: the migration builder has no entity to compile one against. */
921
939
  readonly where?: QuerySql;
922
940
  };
923
- /**
924
- * {@link IndexOptions} on an entity, whose stored columns are read off its refs, `(post) => [post.slug]`,
925
- * so they are checked against it and follow a rename. The migration builder names raw columns instead.
926
- */
941
+ /** {@link IndexOptions} on an entity, `include` and `where` read off the section's refs as its columns are. */
927
942
  export type EntityIndexOptions<E> = Except<IndexOptions, 'include' | 'where'> & {
928
- readonly include?: (refs: RefMap<E>) => readonly ColumnRef<FieldKey<E>>[];
943
+ readonly include?: readonly ColumnRef<FieldKey<E>>[];
929
944
  /**
930
945
  * Partial-index predicate, written as the predicate the query passes: a planner matches the two by
931
- * shape, so a hand-written `sql` that means the same thing leaves the index unused. See {@link EntityWhere}.
946
+ * shape, so a hand-written `sql` that means the same thing leaves the index unused.
932
947
  */
933
- readonly where?: EntityWhere<E>;
948
+ readonly where?: EntityPredicate<E> | QuerySql;
934
949
  };
935
- /**
936
- * An index as authored on an entity, before `defineIndex` reads its columns off the refs. Only the
937
- * member lists are callbacks: TypeScript never checks a callback's returned literal for excess properties,
938
- * so the options stay a literal of their own, where `uniqe: true` is a compile error.
939
- */
950
+ /** An index as registration reads it: its columns, read off the refs, and its options. */
940
951
  export type EntityIndexInput<E> = EntityIndexOptions<E> & {
941
- readonly columns: (refs: RefMap<E>) => readonly EntityIndexColumnInput<E>[];
952
+ readonly columns: readonly EntityIndexColumnInput[];
942
953
  };
943
954
  export {};