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
@@ -31,7 +31,7 @@ export declare abstract class VectorSqlDialect extends AbstractDialect {
31
31
  /** Whether this engine has a vector index: the one a metric's `index` names. */
32
32
  hasVectorIndex(): boolean;
33
33
  /** The distance a vector index built for `metric`, as {@link vectorMetrics} names it for an index, measures. */
34
- indexedDistance(metric: string | undefined): VectorDistance | undefined;
34
+ distanceOfMetric(metric: string | undefined): VectorDistance | undefined;
35
35
  /** Quotes an identifier; supplied by the SQL dialect built on top of this layer. */
36
36
  abstract escapeId(val: string | undefined, forbidQualified?: boolean, addDot?: boolean): string;
37
37
  /** What a distance expression reads, for a `$sort` and a `$near` alike. */
@@ -46,7 +46,7 @@ export class VectorSqlDialect extends AbstractDialect {
46
46
  return [...this.vectorMetrics.values()].some((metric) => metric.index);
47
47
  }
48
48
  /** The distance a vector index built for `metric`, as {@link vectorMetrics} names it for an index, measures. */
49
- indexedDistance(metric) {
49
+ distanceOfMetric(metric) {
50
50
  return [...this.vectorMetrics].find(([, { index }]) => index === metric)?.[0];
51
51
  }
52
52
  /** What a distance expression reads, for a `$sort` and a `$near` alike. */
@@ -0,0 +1,3 @@
1
+ import type { ColumnFactory } from '../type/index.js';
2
+ /** Declares a column, `f.string()`, its options chained: `f.number().nullable().default(0)`. See the entities guide. */
3
+ export declare const f: ColumnFactory;
@@ -0,0 +1,3 @@
1
+ import { columns } from './columnOptionsBuilder.js';
2
+ /** Declares a column, `f.string()`, its options chained: `f.number().nullable().default(0)`. See the entities guide. */
3
+ export const f = columns;
@@ -0,0 +1,54 @@
1
+ import type { ForeignKeyAction } from '../schema/types.js';
2
+ import { COLUMN_OPTIONS, type ColumnType, type FieldOptions, type JsonShape, type OnFieldCallback, type QuerySql, type StampEvent, type Type, type VectorDistance } from '../type/index.js';
3
+ /**
4
+ * Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
5
+ * `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
6
+ */
7
+ export declare class ColumnOptionsBuilder {
8
+ readonly [COLUMN_OPTIONS]: FieldOptions;
9
+ constructor(options: FieldOptions);
10
+ with(options: FieldOptions): ColumnOptionsBuilder;
11
+ nullable(): ColumnOptionsBuilder;
12
+ id(): ColumnOptionsBuilder;
13
+ default(defaultValue: FieldOptions['defaultValue']): ColumnOptionsBuilder;
14
+ onInsert(onInsert: OnFieldCallback): ColumnOptionsBuilder;
15
+ onUpdate(onUpdate: OnFieldCallback): ColumnOptionsBuilder;
16
+ updatable(updatable: false): ColumnOptionsBuilder;
17
+ softDelete(softDelete?: OnFieldCallback): ColumnOptionsBuilder;
18
+ unique(): ColumnOptionsBuilder;
19
+ index(index?: string | false): ColumnOptionsBuilder;
20
+ name(name: string): ColumnOptionsBuilder;
21
+ comment(comment: string): ColumnOptionsBuilder;
22
+ eager(eager: false): ColumnOptionsBuilder;
23
+ columnType(columnType: ColumnType): ColumnOptionsBuilder;
24
+ columnType(columnType: QuerySql): ColumnOptionsBuilder;
25
+ references(references: () => Type<object>): ColumnOptionsBuilder;
26
+ onDelete(onDelete: ForeignKeyAction): ColumnOptionsBuilder;
27
+ narrow(): ColumnOptionsBuilder;
28
+ as(computed: QuerySql): ColumnOptionsBuilder;
29
+ stored(events?: readonly StampEvent[]): ColumnOptionsBuilder;
30
+ precision(precision: number): ColumnOptionsBuilder;
31
+ scale(scale: number): ColumnOptionsBuilder;
32
+ autoIncrement(autoIncrement?: boolean): ColumnOptionsBuilder;
33
+ length(length: number): ColumnOptionsBuilder;
34
+ dimensions(dimensions: number): ColumnOptionsBuilder;
35
+ distance(distance: VectorDistance): ColumnOptionsBuilder;
36
+ }
37
+ /** The column constructors at run time, which `f` types and the migration builder names. */
38
+ export declare const columns: {
39
+ string: () => ColumnOptionsBuilder;
40
+ text: () => ColumnOptionsBuilder;
41
+ uuid: () => ColumnOptionsBuilder;
42
+ number: () => ColumnOptionsBuilder;
43
+ bigint: () => ColumnOptionsBuilder;
44
+ decimal: (precision?: number, scale?: number) => ColumnOptionsBuilder;
45
+ boolean: () => ColumnOptionsBuilder;
46
+ date: () => ColumnOptionsBuilder;
47
+ json: (shape?: JsonShape) => ColumnOptionsBuilder;
48
+ jsonb: (shape?: JsonShape) => ColumnOptionsBuilder;
49
+ vector: (dimensions: number) => ColumnOptionsBuilder;
50
+ enum: (members: readonly string[] | readonly number[]) => ColumnOptionsBuilder;
51
+ version: (type?: NumberConstructor | BigIntConstructor) => ColumnOptionsBuilder;
52
+ column: (type: ColumnType) => ColumnOptionsBuilder;
53
+ references: (references: () => Type<object>) => ColumnOptionsBuilder;
54
+ };
@@ -0,0 +1,108 @@
1
+ import { COLUMN_OPTIONS, } from '../type/index.js';
2
+ /**
3
+ * Every family's builder at run time: the types offer each family only its own methods. Immutable, so a shared
4
+ * `const money = f.decimal(12, 2)` is reused safely, and its options are the plain ones the registry reads.
5
+ */
6
+ export class ColumnOptionsBuilder {
7
+ [COLUMN_OPTIONS];
8
+ constructor(options) {
9
+ this[COLUMN_OPTIONS] = options;
10
+ }
11
+ with(options) {
12
+ return new ColumnOptionsBuilder({ ...this[COLUMN_OPTIONS], ...options });
13
+ }
14
+ nullable() {
15
+ return this.with({ nullable: true });
16
+ }
17
+ id() {
18
+ return this.with({ isId: true });
19
+ }
20
+ default(defaultValue) {
21
+ return this.with({ defaultValue });
22
+ }
23
+ onInsert(onInsert) {
24
+ return this.with({ onInsert });
25
+ }
26
+ onUpdate(onUpdate) {
27
+ return this.with({ onUpdate });
28
+ }
29
+ updatable(updatable) {
30
+ return this.with({ updatable });
31
+ }
32
+ softDelete(softDelete) {
33
+ return this.with({ softDelete: softDelete ?? true });
34
+ }
35
+ unique() {
36
+ return this.with({ unique: true });
37
+ }
38
+ index(index) {
39
+ return this.with({ index: index ?? true });
40
+ }
41
+ name(name) {
42
+ return this.with({ name });
43
+ }
44
+ comment(comment) {
45
+ return this.with({ comment });
46
+ }
47
+ eager(eager) {
48
+ return this.with({ eager });
49
+ }
50
+ columnType(columnType) {
51
+ return this.with({ columnType });
52
+ }
53
+ references(references) {
54
+ return this.with({ references });
55
+ }
56
+ onDelete(onDelete) {
57
+ return this.with({ onDelete });
58
+ }
59
+ narrow() {
60
+ return this;
61
+ }
62
+ as(computed) {
63
+ return this.with({ computed });
64
+ }
65
+ stored(events) {
66
+ return this.with({ stored: events ?? true });
67
+ }
68
+ precision(precision) {
69
+ return this.with({ precision });
70
+ }
71
+ scale(scale) {
72
+ return this.with({ scale });
73
+ }
74
+ autoIncrement(autoIncrement = true) {
75
+ return this.with({ autoIncrement });
76
+ }
77
+ length(length) {
78
+ return this.with({ length });
79
+ }
80
+ dimensions(dimensions) {
81
+ return this.with({ dimensions });
82
+ }
83
+ distance(distance) {
84
+ return this.with({ distance });
85
+ }
86
+ }
87
+ const column = (options) => new ColumnOptionsBuilder(options);
88
+ function json(type, shape) {
89
+ return column({ type, ...(shape && { shape }) });
90
+ }
91
+ /** The column constructors at run time, which `f` types and the migration builder names. */
92
+ export const columns = {
93
+ string: () => column({ type: String }),
94
+ text: () => column({ type: 'text' }),
95
+ uuid: () => column({ type: 'uuid' }),
96
+ number: () => column({ type: Number }),
97
+ bigint: () => column({ type: BigInt }),
98
+ decimal: (precision, scale) => column({ type: 'decimal', ...(precision !== undefined && { precision }), ...(scale !== undefined && { scale }) }),
99
+ boolean: () => column({ type: Boolean }),
100
+ date: () => column({ type: Date }),
101
+ json: (shape) => json('json', shape),
102
+ jsonb: (shape) => json('jsonb', shape),
103
+ vector: (dimensions) => column({ type: 'vector', dimensions }),
104
+ enum: (members) => column({ type: typeof members[0] === 'number' ? Number : String, enum: members }),
105
+ version: (type = Number) => column({ type, version: true }),
106
+ column: (type) => column({ type }),
107
+ references: (references) => column({ references }),
108
+ };
@@ -1,12 +1,12 @@
1
- import type { FieldOptions, HookEvent, RelationRegistration, Type } from '../../type/index.js';
1
+ import type { FieldOptions, HookDeclaration, HookEvent, RelationRegistration, AbstractType } from '../../type/index.js';
2
2
  /**
3
- * What the member decorators record for one class, until `@Entity()` or `defineEntity` drains it: the
4
- * only channel from a member decorator to its class. The writable counterpart of `EntityMembers`.
3
+ * What the member decorators record for one class, until `@Entity()` or a subclass's registration drains it: the
4
+ * only channel from a member decorator to its class, and what a schema's members are registered as too.
5
5
  */
6
6
  export type MemberRegistrations = {
7
7
  readonly fields: Record<string, FieldOptions>;
8
8
  readonly relations: Record<string, RelationRegistration>;
9
- readonly hooks: Partial<Record<HookEvent, string[]>>;
9
+ readonly hooks: Partial<Record<HookEvent, HookDeclaration[]>>;
10
10
  };
11
11
  /**
12
12
  * The class's own registrations, created on first use, never read through a parent's: inheritance walks
@@ -22,4 +22,4 @@ export declare function drainRegistrations(metadata: DecoratorMetadata | undefin
22
22
  * The registrations a class made for itself, readable once it is fully defined: `@Entity()` reads
23
23
  * `context.metadata` instead, since the class gets `Symbol.metadata` after its decorators return.
24
24
  */
25
- export declare function ownRegistrations(entity: Type<unknown>): MemberRegistrations | undefined;
25
+ export declare function ownRegistrations(entity: AbstractType<unknown>): MemberRegistrations | undefined;
@@ -1,23 +1,6 @@
1
- import type { BrandsNameFields, EntityIndexColumnInput, EntityIndexOptions, EntityOptions, FilterName, FilterOptions, RefMap, TriggerOptions, Type } from '../../type/index.js';
1
+ import type { BrandsNameFields, EntityOptions, AbstractType } from '../../type/index.js';
2
2
  /**
3
3
  * Marks a class as an entity and finalizes its metadata, draining `context.metadata`: the class gets
4
- * `Symbol.metadata` only after its decorators return.
4
+ * `Symbol.metadata` only after its decorators return. `abstract: true` marks a base that is never a table.
5
5
  */
6
- export declare function Entity<E>(opts?: NoInfer<EntityOptions<E>>): (entity: Type<E> & BrandsNameFields<E>, context?: ClassDecoratorContext) => void;
7
- /**
8
- * Registers a named `$where` filter, applied to every query unless bypassed via `QueryOptions.filters`.
9
- *
10
- * @example `@Filter('active', { where: { status: 'active' }, default: false })`
11
- */
12
- export declare function Filter<E, N extends string>(name: FilterName<N>, opts: FilterOptions<E>): (entity: Type<E>) => void;
13
- /**
14
- * Declares a composite index, its columns read off the entity's refs, so `@Index((user) => [user.nope])`
15
- * does not compile and a rename reaches every column. Stacks, so several may sit above one class.
16
- * @example `@Index((user) => [user.lastName, sql`lower(${user.email})`], { unique: true })`
17
- */
18
- export declare function Index<E>(columns: (refs: RefMap<E>) => readonly EntityIndexColumnInput<E>[], options?: EntityIndexOptions<E>): (entity: Type<E>) => void;
19
- /**
20
- * Declares triggers the database runs, in the order written. Stacks, so several may sit above one class.
21
- * @example ``@Trigger({ on: 'beforeUpdate', of: (post) => [post.body], run: (newRow) => sql`...` })``
22
- */
23
- export declare function Trigger<E>(...triggers: readonly TriggerOptions<E>[]): (entity: Type<E>) => void;
6
+ export declare function Entity<E>(opts?: NoInfer<EntityOptions<E>>): (entity: AbstractType<E> & BrandsNameFields<E>, context?: ClassDecoratorContext) => void;
@@ -1,45 +1,11 @@
1
- import { applyMembers, defineEntity, defineFilter, defineIndex, defineTrigger } from '../metadata/definition.js';
1
+ import { registerEntity } from '../metadata/definition.js';
2
2
  import { drainRegistrations } from './bag.js';
3
- // The class-level decorators. Unlike the member ones they receive the class, so each is a direct call
4
- // into the registry with no bag in between.
5
3
  /**
6
4
  * Marks a class as an entity and finalizes its metadata, draining `context.metadata`: the class gets
7
- * `Symbol.metadata` only after its decorators return.
5
+ * `Symbol.metadata` only after its decorators return. `abstract: true` marks a base that is never a table.
8
6
  */
9
7
  export function Entity(opts) {
10
8
  return (entity, context) => {
11
- applyMembers(entity, drainRegistrations(context?.metadata));
12
- defineEntity(entity, opts);
13
- };
14
- }
15
- /**
16
- * Registers a named `$where` filter, applied to every query unless bypassed via `QueryOptions.filters`.
17
- *
18
- * @example `@Filter('active', { where: { status: 'active' }, default: false })`
19
- */
20
- export function Filter(name, opts) {
21
- return (entity) => {
22
- defineFilter(entity, name, opts);
23
- };
24
- }
25
- /**
26
- * Declares a composite index, its columns read off the entity's refs, so `@Index((user) => [user.nope])`
27
- * does not compile and a rename reaches every column. Stacks, so several may sit above one class.
28
- * @example `@Index((user) => [user.lastName, sql`lower(${user.email})`], { unique: true })`
29
- */
30
- export function Index(columns, options = {}) {
31
- return (entity) => {
32
- defineIndex(entity, { ...options, columns });
33
- };
34
- }
35
- /**
36
- * Declares triggers the database runs, in the order written. Stacks, so several may sit above one class.
37
- * @example ``@Trigger({ on: 'beforeUpdate', of: (post) => [post.body], run: (newRow) => sql`...` })``
38
- */
39
- export function Trigger(...triggers) {
40
- return (entity) => {
41
- for (const trigger of triggers) {
42
- defineTrigger(entity, trigger);
43
- }
9
+ registerEntity(entity, opts, drainRegistrations(context?.metadata));
44
10
  };
45
11
  }
@@ -1,5 +1,4 @@
1
- import type { AggregateValue, EntityAggregate, EntityGetter, Except, FieldOptions, FieldType, HasCompositeKey, IdValue, NamedIdKey, VersionKey, RejectKeys, RelationManyToManyOptions, RelationManyToOneOptions, RelationOneToManyOptions, RelationOneToOneOptions, TsTypeOf, Writable } from '../../type/index.js';
2
- import type { RejectIncompatible } from '../../util/index.js';
1
+ import { type Column, type ComputedRefs, type EntityGetter, type FilledOptions, type filledKey, type HookContext, type IsEqual, type Json, type JsonBrand, type NamedIdKey, type NullOf, type QuerySql, RelationAggregate, type RelationManyToManyOptions, type RelationManyToOneOptions, type RelationOneToManyOptions, type RelationOneToOneOptions, type VersionKey } from '../../type/index.js';
3
2
  /** A member decorator that also constrains the property it may be applied to, on a class `O`. */
4
3
  type MemberDecorator<V, O = unknown> = (value: undefined, context: ClassFieldDecoratorContext<O, V>) => void;
5
4
  /**
@@ -11,63 +10,45 @@ type MemberDecorator<V, O = unknown> = (value: undefined, context: ClassFieldDec
11
10
  * family - `jsonb`, whose document the property shapes, or `numeric`, either number kind - is meant to
12
11
  * be narrowed. A column insists on its `null`; an aggregate, whose value is exact, insists on all of it.
13
12
  */
14
- type AdmittingDecorator<V, M, O> = <P extends V | undefined>(value: undefined, context: ClassFieldDecoratorContext<O, P> & ([Writable<M>] extends [Writable<P>] ? unknown : {
13
+ type AdmittingDecorator<V, M, O, Filled = true, Key = false, Lock = false> = <P extends V | undefined, N extends PropertyKey>(value: undefined, context: ClassFieldDecoratorContext<O, P> & {
14
+ readonly name: N;
15
+ } & ([M] extends [P] ? unknown : {
15
16
  readonly __propertyMustAdmit: M;
16
- })) => void;
17
- /**
18
- * The property type a set of field options describes: the declared `type`, narrowed by `enum` to the
19
- * values that type admits (so `enum: [2]` stays off a `String`), or else the referenced key's own type,
20
- * which makes `@Field({ references: () => User })` on a `number` an error when `User.id` is a `uuid`.
21
- */
22
- type DeclaredValue<O> = O extends {
23
- readonly type: infer T extends FieldType;
24
- } ? O extends {
25
- readonly enum: infer E extends readonly unknown[];
26
- } ? EnumValue<Extract<E[number], TsTypeOf<T>>, TsTypeOf<T>> : TsTypeOf<T> : O extends {
27
- readonly references: EntityGetter<infer E>;
28
- } ? HasCompositeKey<E> extends true ? {
29
- readonly __compositeKeyNeedsAColumnPerKey: true;
30
- } : IdValue<E> : never;
17
+ }) & FilledIfBranded<O, N, Filled> & ([Key] extends [true] ? KeyIsNamed<O> : unknown) & ([Lock] extends [true] ? VersionIsBranded<O> : unknown)) => void;
18
+ /** A field the `filledKey` brand lets an insert leave out, which only a default can then fill. */
19
+ type FilledIfBranded<O, N, Filled> = [Filled] extends [true] ? unknown : typeof filledKey extends keyof O ? N extends O[typeof filledKey] ? {
20
+ readonly __filledKeyNeedsADefault: true;
21
+ } : unknown : unknown;
31
22
  /**
32
- * The `null` a column reads back: every one holds it unless `nullable: false` says otherwise, so the
33
- * property admits it too. A key holds none, whether `@Id` or `@Field({ isId: true })` declares it, since
34
- * it is NOT NULL on every engine, and neither does a version, which is NOT NULL DEFAULT 0.
23
+ * Declares a persisted field, the property checked against the column: `@Field(f.string()) name!: string;`, and
24
+ * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().id()`.
25
+ * @example `@Field(f.references(() => User).nullable()) userId?: number | null;`
35
26
  */
36
- type NullOf<O> = O extends {
37
- readonly nullable: false;
38
- } | {
39
- readonly isId: true;
40
- } | {
27
+ export declare function Field<This, O, V>(column: Column<O, V>): AdmittingDecorator<Narrowable<V> | NullOf<O>, NullOf<O>, This, O extends FilledOptions ? true : false, IsKey<O>, O extends {
41
28
  readonly version: true;
42
- } ? never : null;
43
- /** The enum's members, or a named complaint where they widened for lack of `as const`, which would check nothing. */
44
- type EnumValue<Members, Declared> = Declared extends Members ? {
45
- readonly __enumNeedsAsConst: true;
46
- } : Members;
29
+ } ? true : false>;
47
30
  /**
48
- * Declares a persisted field, its `type` checked against the property's.
49
- * @example `@Field({ type: String, nullable: false }) name!: string;`
50
- * @example `@Field({ references: () => User }) userId?: string | null;`
31
+ * Declares a field the database computes, read off the entity's refs: SQL as a column,
32
+ * `@Computed((user) => f.string().as(sql`upper(${user.name})`)) readonly shout?: string;`, or a relation
33
+ * aggregate, `@Computed((user) => user.posts.count()) readonly postCount?: number;`, which types itself.
51
34
  */
52
- export declare function Field<This, O extends FieldOptions<DeclaredValue<O>, This> & ({
53
- type: FieldType;
54
- } | {
55
- references: EntityGetter;
56
- }) & RejectKeys<Exclude<keyof O, keyof FieldOptions>> & RejectIncompatible<O>>(opts: O & VersionIsBranded<O, This>): AdmittingDecorator<DeclaredValue<O> | NullOf<O>, NullOf<O>, This>;
57
- /**
58
- * Declares a field a relation aggregate computes, `@Field({ computed: (user) => user.resources.count() })`.
59
- * The aggregate says what the field holds, so it takes no `type`, and only `count` and `sum` - the two a
60
- * row change turns into a delta - may be `stored`.
61
- * @example `@Field({ computed: (user) => user.resources.count() }) readonly resourceCount?: number;`
62
- */
63
- export declare function Field<This, O extends AggregateOptions<This> & RejectKeys<Exclude<keyof O, keyof FieldOptions>>>(opts: O): AdmittingDecorator<AggregateValue<O>, AggregateValue<O>, This>;
64
- /** A field the aggregate itself types, read on each query, never `stored`, and every other option as a column takes it. */
65
- type AggregateOptions<E> = Except<FieldOptions<never, E>, 'computed' | 'stored' | 'type'> & {
66
- readonly computed: EntityAggregate<E>;
67
- readonly stored?: false;
68
- };
35
+ export declare function Computed<This, C extends ComputedColumn | RelationAggregate>(expression: (refs: ComputedRefs<This>) => C): AdmittingDecorator<ComputedValue<C>, ComputedAdmits<C>, This>;
36
+ /** A column the database computes, what `as()` returns. */
37
+ type ComputedColumn = Column<{
38
+ readonly computed: QuerySql;
39
+ }>;
40
+ /** What a computed field holds: an aggregate's exact value, or a column's, `null` where it said so. */
41
+ type ComputedValue<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O, infer V> ? V | NullOf<O> : never;
42
+ /** What the property has to admit: all of an aggregate's value, which is exact, and a column's `null`. */
43
+ type ComputedAdmits<C> = C extends RelationAggregate<infer V> ? V : C extends Column<infer O> ? NullOf<O> : never;
44
+ /** A JSON column with no shape holds any document, which the property narrows: `Json<Settings>`. */
45
+ type Narrowable<V> = IsEqual<V, Json> extends true ? JsonBrand | readonly JsonBrand[] : V;
46
+ /** Whether the column is a key, which the class has to name. */
47
+ type IsKey<O> = O extends {
48
+ readonly isId: true;
49
+ } ? true : false;
69
50
  /**
70
- * A key the type level cannot name, reported on each `@Id` that leaves it unnamed. Where no `idKey`
51
+ * A key the type level cannot name, reported on each key column that leaves it unnamed. Where no `idKey`
71
52
  * brand and no conventional name applies, `IdKey` falls back to every field, and `IdValue`,
72
53
  * `EntityId` and every by-id method are then typed against a column that is not the key.
73
54
  */
@@ -79,22 +60,9 @@ type KeyIsNamed<This> = [NamedIdKey<This>] extends [never] ? {
79
60
  * time; the `versionKey` brand is what makes an update payload require it, and a lock only half
80
61
  * declared would be a guarantee nothing enforces, so the decorator asks for both.
81
62
  */
82
- type VersionIsBranded<O, This> = O extends {
83
- readonly version: true;
84
- } ? [VersionKey<This>] extends [never] ? {
63
+ type VersionIsBranded<This> = [VersionKey<This>] extends [never] ? {
85
64
  readonly __versionNeedsVersionKeyBrand: true;
86
- } : unknown : unknown;
87
- /** {@link MemberDecorator} that also constrains the class, which is where a key is named. */
88
- type IdDecorator<V> = <This>(value: undefined, context: ClassFieldDecoratorContext<This, V> & KeyIsNamed<This>) => void;
89
- /**
90
- * Declares the primary key, checked like `@Field`; a key not named `id`, `_id` or `uuid` needs the `idKey` brand.
91
- * @example `@Id({ type: 'uuid', onInsert: uuidv7 }) id!: string;`
92
- */
93
- export declare function Id<O extends FieldOptions<DeclaredValue<O>> & {
94
- type: FieldType;
95
- } & RejectKeys<Exclude<keyof O, keyof FieldOptions>> & RejectIncompatible<O> & {
96
- readonly nullable?: false;
97
- }>(opts: O): IdDecorator<DeclaredValue<O> | undefined>;
65
+ } : unknown;
98
66
  /**
99
67
  * `E` comes from the mandatory `entity` getter, so the context can insist the property really holds that
100
68
  * entity: `@ManyToOne({ entity: () => Other })` on a `Company` field stops compiling, and a to-many
@@ -108,13 +76,15 @@ export declare function OneToOne<E extends object, O>(opts: WithEntity<E, Relati
108
76
  export declare function ManyToOne<E extends object, O>(opts: WithEntity<E, RelationManyToOneOptions<E, O>>): MemberDecorator<E | undefined, O>;
109
77
  export declare function OneToMany<E extends object, O>(opts: WithEntity<E, RelationOneToManyOptions<E, O>>): MemberDecorator<readonly E[] | undefined, O>;
110
78
  export declare function ManyToMany<E extends object, O>(opts: WithEntity<E, RelationManyToManyOptions<E, O>>): MemberDecorator<readonly E[] | undefined, O>;
111
- export declare const BeforeInsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
112
- export declare const AfterInsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
113
- export declare const BeforeUpdate: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
114
- export declare const AfterUpdate: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
115
- export declare const BeforeUpsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
116
- export declare const AfterUpsert: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
117
- export declare const BeforeDelete: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
118
- export declare const AfterDelete: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
119
- export declare const AfterLoad: () => <This>(_value: unknown, context: ClassMethodDecoratorContext<This>) => void;
79
+ /** What a hook method is called with: the row as `this`, and the querier's context. */
80
+ type HookMethod<This> = (this: This, ctx: HookContext) => unknown;
81
+ export declare const BeforeInsert: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
82
+ export declare const AfterInsert: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
83
+ export declare const BeforeUpdate: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
84
+ export declare const AfterUpdate: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
85
+ export declare const BeforeUpsert: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
86
+ export declare const AfterUpsert: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
87
+ export declare const BeforeDelete: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
88
+ export declare const AfterDelete: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
89
+ export declare const AfterLoad: () => <This>(_value: HookMethod<This>, context: ClassMethodDecoratorContext<This>) => void;
120
90
  export {};
@@ -1,17 +1,28 @@
1
+ import { COLUMN_OPTIONS, RelationAggregate, } from '../../type/index.js';
2
+ import { aggregateField } from '../../util/field.util.js';
3
+ import { memberRefs } from '../../util/sql.js';
1
4
  import { relationRegistration } from '../metadata/definition.js';
2
5
  import { memberRegistrations } from './bag.js';
3
- export function Field(opts) {
6
+ /**
7
+ * Declares a persisted field, the property checked against the column: `@Field(f.string()) name!: string;`, and
8
+ * `@Field(f.string().nullable()) bio?: string | null;` for a column holding `null`. A key is `f.number().id()`.
9
+ * @example `@Field(f.references(() => User).nullable()) userId?: number | null;`
10
+ */
11
+ export function Field(column) {
4
12
  return (_value, context) => {
5
- memberRegistrations(context.metadata).fields[String(context.name)] = opts;
13
+ memberRegistrations(context.metadata).fields[String(context.name)] = column[COLUMN_OPTIONS];
6
14
  };
7
15
  }
8
16
  /**
9
- * Declares the primary key, checked like `@Field`; a key not named `id`, `_id` or `uuid` needs the `idKey` brand.
10
- * @example `@Id({ type: 'uuid', onInsert: uuidv7 }) id!: string;`
17
+ * Declares a field the database computes, read off the entity's refs: SQL as a column,
18
+ * `@Computed((user) => f.string().as(sql`upper(${user.name})`)) readonly shout?: string;`, or a relation
19
+ * aggregate, `@Computed((user) => user.posts.count()) readonly postCount?: number;`, which types itself.
11
20
  */
12
- export function Id(opts) {
21
+ export function Computed(expression) {
13
22
  return (_value, context) => {
14
- memberRegistrations(context.metadata).fields[String(context.name)] = { ...opts, isId: true };
23
+ const computed = expression(memberRefs());
24
+ memberRegistrations(context.metadata).fields[String(context.name)] =
25
+ computed instanceof RelationAggregate ? aggregateField(computed) : computed[COLUMN_OPTIONS];
15
26
  };
16
27
  }
17
28
  function relation(opts) {
@@ -38,7 +49,7 @@ function hook(event) {
38
49
  (_value, context) => {
39
50
  const { hooks } = memberRegistrations(context.metadata);
40
51
  hooks[event] ??= [];
41
- hooks[event].push(String(context.name));
52
+ hooks[event].push({ methodName: String(context.name) });
42
53
  };
43
54
  }
44
55
  export const BeforeInsert = hook('beforeInsert');
@@ -1,3 +1,4 @@
1
+ export * from './column.js';
1
2
  export * from './decorator/entity.js';
2
3
  export * from './decorator/members.js';
3
- export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, keyOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
4
+ export { defineEntity, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, keyOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
@@ -1,3 +1,4 @@
1
+ export * from './column.js';
1
2
  export * from './decorator/entity.js';
2
3
  export * from './decorator/members.js';
3
- export { defineEntity, defineField, defineFilter, defineHook, defineId, defineIndex, defineRelation, defineTrigger, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, keyOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
4
+ export { defineEntity, getEntities, getMeta, removeEntity, assertSoleId, fieldOf, idOf, keyOf, namesKey, relationOf, soleIdOf, } from './metadata/definition.js';
@@ -1,8 +1,5 @@
1
- import type { BrandsNameFields, EntityGetter, EntityIndexInput, EntityMembers, EntityMeta, EntityOptions, FieldMeta, FieldOptions, FilterName, FilterOptions, HookEvent, IdKey, KeyMap, RelationKey, RelationMeta, RelationOptions, RelationRegistration, TriggerOptions, Type, WrittenId } from '../../type/index.js';
2
- export declare function defineField<E>(entity: Type<E>, key: string, opts?: FieldOptions): EntityMeta<E>;
3
- export declare function defineId<E>(entity: Type<E>, key: string, opts: FieldOptions): EntityMeta<E>;
4
- /** `T` is the relation's target, independent of the owner `E`. */
5
- export declare function defineRelation<E, T extends object>(entity: Type<E>, key: string, opts: RelationOptions<T, E>): EntityMeta<E>;
1
+ import { type EntityGetter, type EntityMeta, type EntityOptions, type FieldMeta, type IdKey, type KeyMap, type RelationKey, type RelationMeta, type RelationOptions, type RelationRegistration, type SchemaEntityOptions, type Brands, type ColumnRow, type SchemaFields, type SchemaKey, type Type, type AbstractType, type WrittenId, type SchemaEntity } from '../../type/index.js';
2
+ import { type MemberRegistrations } from '../decorator/bag.js';
6
3
  /**
7
4
  * `opts` as the registry takes them: `mappedBy` and `references` read off their key maps down to the
8
5
  * names they give. The callbacks only read properties, so they run here, before any entity has to
@@ -14,28 +11,20 @@ export declare function relationRegistration<T extends object, O>({ mappedBy, re
14
11
  * entity names one, since a selector follows a rename and a string does not.
15
12
  */
16
13
  export declare function keyOf<E, K extends keyof E>(pick: (keys: KeyMap<E>) => K): K;
17
- export declare function defineHook<E>(entity: Type<E>, methodName: string, event: HookEvent): EntityMeta<E>;
18
14
  /**
19
- * Declares a composite index, its columns read off the entity's refs. `unique` and the authored column
20
- * sugar are normalized here, which is what lets the dialects render one shape instead of re-parsing it.
15
+ * Declares an entity by its schema and returns its class, whose row type the schema derives, so nothing is
16
+ * written twice: its columns now, then each section, `.indexes()` and so on, `.relations()` last but for
17
+ * `.filters()`. It registers on first read, with every section in, and its relations once each target exists.
21
18
  */
22
- export declare function defineIndex<E>(entity: Type<E>, index: EntityIndexInput<E>): EntityMeta<E>;
19
+ export declare function defineEntity<const F extends SchemaFields, B = object, BK = unknown, BC = unknown>(schema: SchemaEntityOptions<F, B, BK, BC> & {
20
+ readonly abstract: true;
21
+ }): SchemaEntity<B & ColumnRow<F> & Brands<F>, SchemaKey<F, BK>, BC & ColumnRow<F>, B, true>;
22
+ export declare function defineEntity<const F extends SchemaFields, B = object, BK = unknown, BC = unknown>(schema: SchemaEntityOptions<F, B, BK, BC>): SchemaEntity<B & ColumnRow<F> & Brands<F>, SchemaKey<F, BK>, BC & ColumnRow<F>, B>;
23
23
  /**
24
- * Registers a trigger, its watched columns read off the entity's refs so a rename reaches them and a
25
- * column the entity has not got does not compile. Appended, since triggers fire in the order written.
24
+ * The registration both forms share, a schema's `members` given as the decorators would register them. Built
25
+ * apart and stored once it passes, so a rejected definition leaves the registry as it was.
26
26
  */
27
- export declare function defineTrigger<E>(entity: Type<E>, trigger: TriggerOptions<E>): EntityMeta<E>;
28
- export declare function defineFilter<E, N extends string>(entity: Type<E>, name: FilterName<N>, opts: FilterOptions<E>): EntityMeta<E>;
29
- /**
30
- * Feeds fields, relations and hooks into the `define*` primitives, so the decorators and the imperative
31
- * API converge on one registration path before anything is finalized.
32
- */
33
- export declare function applyMembers<E>(entity: Type<E>, specs: EntityMembers | undefined): void;
34
- /**
35
- * Registers a class as an entity from `opts` alone, the decorator-free counterpart of `@Entity()` with
36
- * `@Field`/`@ManyToOne`/...
37
- */
38
- export declare function defineEntity<E>(entity: Type<E> & BrandsNameFields<E>, opts?: EntityOptions<E>): EntityMeta<E>;
27
+ export declare function registerEntity<E>(entity: AbstractType<E>, opts?: EntityOptions<E>, members?: Partial<MemberRegistrations>): EntityMeta<E>;
39
28
  /**
40
29
  * Refuses an entity whose primary key is not one column, naming the path that cannot express it.
41
30
  *
@@ -73,11 +62,11 @@ export declare function idOf<E>(meta: EntityMeta<E>, row: KeyedRow<E>): WrittenI
73
62
  * what pointed at it, and a decorated class does not come back (its decorators drained at first
74
63
  * registration). See the Runtime Schemas guide.
75
64
  */
76
- export declare function removeEntity<E>(entity: Type<E>): boolean;
65
+ export declare function removeEntity<E>(entity: AbstractType<E>): boolean;
77
66
  export declare function getEntities(): Type<object>[];
78
- export declare function getMeta<E>(entity: Type<E>): EntityMeta<E>;
67
+ export declare function getMeta<E>(entity: AbstractType<E>): EntityMeta<E>;
79
68
  /**
80
- * The foreign keys an entity holds: each owning to-one's columns, and each `@Field({ references })` no
69
+ * The foreign keys an entity holds: each owning to-one's columns, and each `f.references()` no
81
70
  * relation joins on, as the many-to-one it describes, once its target has registered a key. What the
82
71
  * schema build constrains and a junction joins by, settling the relations holding them first.
83
72
  */