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,6 +1,6 @@
1
- import { RelationAggregate, SOFT_DELETE_FILTER } from '../../type/index.js';
2
- import { fieldKeys, isInlinedExpression } from '../../util/field.util.js';
3
- import { entitySql, entityWhere, fieldOptionConflict, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, memberRefs, fulltextWeights, normalizeIndexColumn, definedEntries, whereWith, } from '../../util/index.js';
1
+ import { COLUMN_OPTIONS, REF_KEY, RelationAggregate, SECTION_ENTRY, SOFT_DELETE_FILTER, } from '../../type/index.js';
2
+ import { aggregateField, defaultReadKeys, fieldKeys, isInlinedExpression } from '../../util/field.util.js';
3
+ import { fieldOptionConflict, findVectorIndex, valueTypesOf, hasKeys, holdsForeignKey, isCascadable, isToManyRelation, indexRefs, memberRefs, relationRefs, fulltextWeights, normalizeIndexColumn, definedEntries, whereWith, } from '../../util/index.js';
4
4
  import { UqlUsageError } from '../../util/uqlError.js';
5
5
  import { ownRegistrations } from '../decorator/bag.js';
6
6
  /**
@@ -16,44 +16,27 @@ function globalMap(key) {
16
16
  return holder[symbol];
17
17
  }
18
18
  const metas = globalMap('uql-orm/entity/metadata/v1');
19
- export function defineField(entity, key, opts = {}) {
20
- const meta = ensureWritableMeta(entity);
21
- const { computed, ...rest } = opts;
22
- const sql = computed === undefined ? undefined : entitySql(computed);
19
+ function addField(meta, key, opts) {
20
+ const { entity } = meta;
23
21
  // The types refuse this too; an untyped caller still reaches here.
24
- if (opts.stored && sql instanceof RelationAggregate) {
22
+ if (opts.stored && opts.computed instanceof RelationAggregate) {
25
23
  throw new UqlUsageError(`'${entity.name}.${key}' cannot be 'stored': a relation aggregate reads as a subquery, which no ` +
26
24
  "engine keeps in a generated column. Drop 'stored' to have it read on each query.");
27
25
  }
28
26
  // A stored computed column is a real column and still needs a type; only an inlined one is exempt,
29
27
  // its expression being spliced in rather than declared.
30
28
  if (!opts.type && !opts.references && !isInlinedExpression(opts)) {
31
- throw new UqlUsageError(`'${entity.name}.${key}' needs a 'type'. Declare it - '@Field({ type: String })' - or point the field ` +
32
- "at another entity with 'references', which resolves the column type from its primary key.");
29
+ throw new UqlUsageError(`'${entity.name}.${key}' needs a 'type'. Declare it - 'f.string()' - or point the field ` +
30
+ "at another entity with 'f.references()', which resolves the column type from its primary key.");
33
31
  }
34
32
  const conflict = fieldOptionConflict(opts);
35
33
  if (conflict) {
36
34
  throw new UqlUsageError(`'${entity.name}.${key}' ${conflict}.`);
37
35
  }
38
- const fieldKey = key;
39
36
  // Flagged when the author gave `references` but no `type`, so schema generation knows to resolve the
40
37
  // column from the referenced primary key (picking up its `columnType`, length and chained keys)
41
38
  // instead of treating whatever ends up in `type` as deliberate.
42
- const resolved = rest.type ? rest : { ...rest, typeFromReference: true };
43
- meta.fields[fieldKey] = {
44
- ...meta.fields[fieldKey],
45
- name: key,
46
- ...resolved,
47
- ...(sql && { computed: sql }),
48
- };
49
- return meta;
50
- }
51
- export function defineId(entity, key, opts) {
52
- return defineField(entity, key, { ...opts, isId: true });
53
- }
54
- /** `T` is the relation's target, independent of the owner `E`. */
55
- export function defineRelation(entity, key, opts) {
56
- return addRelation(entity, key, relationRegistration(opts));
39
+ columnsOf(meta).fields[key] = { name: key, ...opts, ...(!opts.type && { typeFromReference: true }) };
57
40
  }
58
41
  /**
59
42
  * `opts` as the registry takes them: `mappedBy` and `references` read off their key maps down to the
@@ -80,7 +63,8 @@ export function keyOf(pick) {
80
63
  return pick(keyMap());
81
64
  }
82
65
  const KEY_MAP = new Proxy({}, { get: (_, key) => key });
83
- function addRelation(entity, key, registration) {
66
+ function addRelation(meta, key, registration) {
67
+ const { entity } = meta;
84
68
  if (!registration.entity) {
85
69
  throw new UqlUsageError(`'${entity.name}.${key}' needs an 'entity' getter, e.g. '@ManyToOne({ entity: () => Company })'.`);
86
70
  }
@@ -88,43 +72,33 @@ function addRelation(entity, key, registration) {
88
72
  throw new UqlUsageError(`'${entity.name}.${key}' joins through a junction, whose column referencing each side is the join; ` +
89
73
  "'references' pairs the declaring entity's columns with the target's instead.");
90
74
  }
91
- const meta = ensureWritableMeta(entity);
92
75
  // Registration writes into a map declared as resolved: `getMeta` runs `fillRelations`, which settles
93
76
  // `references` or throws. Bridging the two shapes here is what lets every consumer read `RelationMeta`
94
77
  // without asserting.
95
78
  const relations = meta.relations;
96
- relations[key] = { ...relations[key], ...registration };
97
- return meta;
98
- }
99
- export function defineHook(entity, methodName, event) {
100
- const meta = ensureWritableMeta(entity);
101
- ((meta.hooks ??= {})[event] ??= []).push({ methodName });
102
- return meta;
79
+ relations[key] = registration;
103
80
  }
104
81
  /**
105
82
  * Declares a composite index, its columns read off the entity's refs. `unique` and the authored column
106
83
  * sugar are normalized here, which is what lets the dialects render one shape instead of re-parsing it.
107
84
  */
108
- export function defineIndex(entity, index) {
109
- const meta = ensureWritableMeta(entity);
110
- const refs = memberRefs();
111
- const columns = index.columns(refs).map(normalizeIndexColumn);
112
- fulltextWeights({ type: index.type, entries: columns });
85
+ function addIndex(meta, { columns, include, where, [SECTION_ENTRY]: _entry, ...index }) {
86
+ const entries = columns.map(normalizeIndexColumn);
87
+ fulltextWeights({ type: index.type, entries });
113
88
  (meta.indexes ??= []).push({
114
89
  ...index,
115
90
  unique: index.unique ?? false,
116
- where: index.where && entityWhere(index.where),
117
- columns,
118
- include: index.include?.(refs).map((ref) => ref.key),
91
+ where,
92
+ entries,
93
+ include: include?.map((ref) => ref[REF_KEY]),
119
94
  });
120
- return meta;
121
95
  }
122
96
  /**
123
97
  * Registers a trigger, its watched columns read off the entity's refs so a rename reaches them and a
124
98
  * column the entity has not got does not compile. Appended, since triggers fire in the order written.
125
99
  */
126
- export function defineTrigger(entity, trigger) {
127
- const meta = ensureWritableMeta(entity);
100
+ function addTrigger(meta, { [SECTION_ENTRY]: _entry, ...trigger }) {
101
+ const { entity } = meta;
128
102
  // The type already refuses an empty map; this is the same answer for plain JavaScript.
129
103
  if (typeof trigger.run !== 'function' && !hasKeys(trigger.run)) {
130
104
  throw new UqlUsageError(`'${entity.name}' has a trigger whose body names at least one engine to run on`);
@@ -132,13 +106,12 @@ export function defineTrigger(entity, trigger) {
132
106
  if (trigger.name && meta.triggers?.some((it) => it.name === trigger.name)) {
133
107
  throw new UqlUsageError(`'${entity.name}' already has a trigger named '${trigger.name}'`);
134
108
  }
135
- (meta.triggers ??= []).push({ ...trigger, of: trigger.of?.(memberRefs()).map((ref) => ref.key) });
136
- return meta;
109
+ (meta.triggers ??= []).push({ ...trigger, of: trigger.of?.map((ref) => ref[REF_KEY]) });
137
110
  }
138
- export function defineFilter(entity, name, opts) {
139
- const meta = ensureWritableMeta(entity);
111
+ function addFilter(meta, name, opts) {
112
+ const { entity } = meta;
140
113
  if (name === SOFT_DELETE_FILTER) {
141
- throw new UqlUsageError(`'${entity.name}' filter name '${SOFT_DELETE_FILTER}' is reserved; it is auto-registered from @Field({ softDelete })`);
114
+ throw new UqlUsageError(`'${entity.name}' filter name '${SOFT_DELETE_FILTER}' is reserved; a 'softDelete()' column registers it`);
142
115
  }
143
116
  // Widened for a caller the types did not reach, which is the only one this can refuse.
144
117
  const { security, onMissing } = opts;
@@ -146,88 +119,242 @@ export function defineFilter(entity, name, opts) {
146
119
  throw new UqlUsageError(`'${entity.name}' security filter '${name}' cannot use onMissing: 'skip' (it must fail closed)`);
147
120
  }
148
121
  (meta.filters ??= {})[name] = opts;
149
- return meta;
122
+ }
123
+ /** Registers the fields, relations and hooks decorators or a schema declared, before anything is finalized. */
124
+ function applyMembers(meta, members) {
125
+ for (const [key, spec] of definedEntries(members?.fields ?? {})) {
126
+ addField(meta, key, spec);
127
+ }
128
+ for (const [key, spec] of definedEntries(members?.relations ?? {})) {
129
+ addRelation(meta, key, spec);
130
+ }
131
+ for (const [event, hooks] of definedEntries(members?.hooks ?? {})) {
132
+ const runs = hooks.map((hook) => resolvedHook(meta.entity, event, hook));
133
+ ((meta.hooks ??= {})[event] ??= []).push(...runs);
134
+ }
135
+ }
136
+ /** A hook method, run with the row as `this`, read off `entity` so an entity overriding it runs its own. */
137
+ function methodHook(entity, event, methodName) {
138
+ // A prototype is typed `any`, so what is read off it is typed here, where it enters.
139
+ const prototype = entity.prototype;
140
+ const method = prototype[methodName];
141
+ if (typeof method !== 'function') {
142
+ throw new UqlUsageError(`'${entity.name}' runs '${methodName}' on ${event}, but has no such method`);
143
+ }
144
+ return { methodName, run: (row, ctx) => method.call(row, ctx) };
150
145
  }
151
146
  /**
152
- * Feeds fields, relations and hooks into the `define*` primitives, so the decorators and the imperative
153
- * API converge on one registration path before anything is finalized.
147
+ * A hook naming a method, by any name, `''` included, is read off `entity` again as {@link methodHook} does, so an
148
+ * entity overriding it runs its own; a hook given as a function is kept as it is.
154
149
  */
155
- export function applyMembers(entity, specs) {
156
- for (const [key, spec] of definedEntries(specs?.fields ?? {})) {
157
- if (spec.isId) {
158
- defineId(entity, key, spec);
150
+ function resolvedHook(entity, event, hook) {
151
+ if (!('run' in hook)) {
152
+ return methodHook(entity, event, hook.methodName);
153
+ }
154
+ return 'methodName' in hook && hook.methodName !== undefined ? methodHook(entity, event, hook.methodName) : hook;
155
+ }
156
+ const declaredSchemas = new WeakMap();
157
+ export function defineEntity(schema) {
158
+ const base = schema.extends ?? Object;
159
+ // Its rows are read by key alone, which is what the registry types an erased schema's columns by.
160
+ const entity = {
161
+ [schema.name]: class extends base {
162
+ },
163
+ }[schema.name];
164
+ metas.set(entity, { ...emptyMeta(entity), stage: 'declared' });
165
+ declaredSchemas.set(entity, { schema, sections: {} });
166
+ for (const section of Object.keys(SECTIONS)) {
167
+ Object.defineProperty(entity, section, {
168
+ value(...declared) {
169
+ declareSection(this, section, declared);
170
+ return this;
171
+ },
172
+ });
173
+ }
174
+ return entity;
175
+ }
176
+ /** The sections a schema declares as methods. `aggregates` is no section: `relations` takes it as an argument. */
177
+ const SECTIONS = {
178
+ computed: true,
179
+ indexes: true,
180
+ checks: true,
181
+ triggers: true,
182
+ filters: true,
183
+ hooks: true,
184
+ references: true,
185
+ relations: true,
186
+ };
187
+ /** Records one section of a pending schema, refusing a second of it and one declared after the entity was read. */
188
+ function declareSection(entity, section, declared) {
189
+ const pending = pendingSchema(entity);
190
+ if (!pending) {
191
+ throw new UqlUsageError(`'${entity.name}' was read already: declare its ${section} before its first use`);
192
+ }
193
+ if (section in pending.sections) {
194
+ throw new UqlUsageError(`'${entity.name}' declares its ${section} twice: declare them in one call`);
195
+ }
196
+ const [first, aggregates] = declared;
197
+ Object.assign(pending.sections, { [section]: first }, section === 'relations' && aggregates && { aggregates });
198
+ }
199
+ /** What `entity` declared as a schema, while it is not registered yet. */
200
+ function pendingSchema(entity) {
201
+ return metas.get(entity)?.stage === 'declared' ? declaredSchemas.get(entity) : undefined;
202
+ }
203
+ /** Registers a pending schema, its base's first; a failure leaves it pending, so a later read reports it again. */
204
+ function settleSchema(entity) {
205
+ const pending = pendingSchema(entity);
206
+ if (!pending) {
207
+ return;
208
+ }
209
+ const { schema, sections } = pending;
210
+ const fields = {
211
+ ...columnOptions(schema.fields),
212
+ ...referencedFields(schema.name, schema.fields, sections.references),
213
+ };
214
+ for (const added of [computedFields(sections.computed), aggregateFields(schema.name, sections.aggregates)]) {
215
+ const taken = Object.keys(added).find((key) => key in fields);
216
+ if (taken) {
217
+ throw new UqlUsageError(`'${schema.name}.${taken}' is declared twice: name each member once`);
159
218
  }
160
- else {
161
- defineField(entity, key, spec);
219
+ Object.assign(fields, added);
220
+ }
221
+ registerEntity(entity, {
222
+ name: schema.table,
223
+ schema: schema.schema,
224
+ abstract: schema.abstract,
225
+ indexes: sections.indexes,
226
+ checks: sections.checks,
227
+ triggers: sections.triggers,
228
+ filters: sections.filters,
229
+ }, {
230
+ fields,
231
+ hooks: Object.fromEntries(definedEntries(sections.hooks ?? {}).map(([event, runs]) => [event, runs.map((run) => ({ run }))])),
232
+ });
233
+ }
234
+ /** Each foreign key `.references()` names, written onto its column as `@Field`'s `references()` would. */
235
+ function referencedFields(name, fields, references) {
236
+ return Object.fromEntries(Object.entries(references ?? {}).map(([key, target]) => {
237
+ const column = fields[key]?.[COLUMN_OPTIONS];
238
+ if (!column) {
239
+ throw new UqlUsageError(`'.references()' names '${name}.${key}', which is no column of its 'fields'`);
162
240
  }
163
- }
164
- for (const [key, spec] of definedEntries(specs?.relations ?? {})) {
165
- addRelation(entity, key, spec);
166
- }
167
- for (const [event, methodNames] of definedEntries(specs?.hooks ?? {})) {
168
- for (const methodName of methodNames) {
169
- defineHook(entity, methodName, event);
241
+ const { entity, ...action } = typeof target === 'function' ? { entity: target } : target;
242
+ return [key, { ...column, ...action, references: () => entityOf(entity(), key) }];
243
+ }));
244
+ }
245
+ /** The entity a getter returned, refused where it returned anything else. */
246
+ function entityOf(target, key) {
247
+ if (!metas.has(target) || !isTable(target)) {
248
+ throw new UqlUsageError(`'.references()' points '${key}' at something that is not an entity`);
249
+ }
250
+ return target;
251
+ }
252
+ /** An index as a section's `index(columns, options)` writes it, a bare string its name. */
253
+ function indexEntry(columns, options) {
254
+ const stated = typeof options === 'string' ? { name: options } : options;
255
+ return { ...stated, columns, [SECTION_ENTRY]: 'index' };
256
+ }
257
+ function checkEntry(where, name) {
258
+ return { where, ...(name !== undefined && { name }), [SECTION_ENTRY]: 'check' };
259
+ }
260
+ function triggerEntry(trigger) {
261
+ return { ...trigger, [SECTION_ENTRY]: 'trigger' };
262
+ }
263
+ /** The options each builder of `columns` wrote. */
264
+ function columnOptions(columns) {
265
+ return Object.fromEntries(Object.entries(columns).map(([key, column]) => [key, column[COLUMN_OPTIONS]]));
266
+ }
267
+ /** A schema's computed columns, read off its refs. */
268
+ function computedFields(computed) {
269
+ return columnOptions(computed?.(memberRefs()) ?? {});
270
+ }
271
+ /** A schema's aggregates as the computed fields they read as, through the refs a decorated `@Computed` reads. */
272
+ function aggregateFields(name, aggregates) {
273
+ return Object.fromEntries(Object.entries(aggregates?.(relationRefs()) ?? {}).map(([key, read]) => {
274
+ const aggregate = typeof read === 'function' ? read() : undefined;
275
+ // The types refuse anything else; an untyped caller still reaches here.
276
+ if (!(aggregate instanceof RelationAggregate)) {
277
+ throw new UqlUsageError(`'${name}.${key}' aggregates no relation: write it as \`() => agg.<relation>.count()\``);
170
278
  }
279
+ return [key, aggregateField(aggregate)];
280
+ }));
281
+ }
282
+ const RELATION_BUILDER = {
283
+ oneToOne: (target, options) => ({ target, cardinality: '11', options }),
284
+ manyToOne: (target, options) => ({ target, cardinality: 'm1', options }),
285
+ oneToMany: (target, options) => ({ target, cardinality: '1m', options }),
286
+ manyToMany: (target, options) => ({ target, cardinality: 'mm', options }),
287
+ };
288
+ /**
289
+ * Settles an entity's relations, once: its schema's, read now that each target exists, beside those its decorators
290
+ * registered, then a copy of each its base settled that it does not declare itself. The one place either form
291
+ * inherits a relation. Marked after, so a read after a failure reports the same mistake again.
292
+ */
293
+ function settleRelations(meta) {
294
+ if (meta.stage === 'settled' || meta.stage === 'resolved') {
295
+ return;
171
296
  }
297
+ const parent = parentOf(meta.entity);
298
+ const inherited = parent && metas.has(parent) ? registeredMeta(parent).relations : {};
299
+ const declared = declaredSchemas.get(meta.entity)?.sections.relations;
300
+ for (const [key, read] of Object.entries(declared?.(RELATION_BUILDER) ?? {})) {
301
+ const { target, cardinality, options } = read();
302
+ addRelation(meta, key, relationRegistration({ ...options, cardinality, entity: () => tableOf(target) }));
303
+ }
304
+ // A copy per entity: resolving a relation writes the columns it joins on into it, and those are the resolving
305
+ // entity's, so one shared object would leave every later entity without them.
306
+ meta.relations = {
307
+ ...Object.fromEntries(definedEntries(inherited).map(([key, relation]) => [key, { ...relation }])),
308
+ ...meta.relations,
309
+ };
310
+ meta.stage = 'settled';
172
311
  }
173
312
  /**
174
- * Registers a class as an entity from `opts` alone, the decorator-free counterpart of `@Entity()` with
175
- * `@Field`/`@ManyToOne`/...
313
+ * The registration both forms share, a schema's `members` given as the decorators would register them. Built
314
+ * apart and stored once it passes, so a rejected definition leaves the registry as it was.
176
315
  */
177
- export function defineEntity(entity, opts = {}) {
178
- // Ahead of any registration, so a rejected definition leaves nothing half-written in the registry.
316
+ export function registerEntity(entity, opts = {}, members) {
179
317
  // A dotted name reads like a schema and is not one: it escapes as a single identifier, so the
180
318
  // statement builds and then fails at the database. `schema` is the way to say it.
181
- if (opts.name?.includes('.')) {
182
- const [schema, ...rest] = opts.name.split('.');
183
- throw new UqlUsageError(`'${entity.name}' has a dotted name '${opts.name}'. Name the schema separately as ` +
319
+ const table = opts.name ?? entity.name;
320
+ if (table.includes('.')) {
321
+ const [schema, ...rest] = table.split('.');
322
+ throw new UqlUsageError(`'${entity.name}' has a dotted name '${table}'. Name the schema separately as ` +
184
323
  `{ schema: '${schema}', name: '${rest.join('.')}' }.`);
185
324
  }
186
- const meta = ensureWritableMeta(entity);
187
- // Covers `defineEntity(Decorated)` called on a class whose members carry decorators. `@Entity()`
188
- // drains `context.metadata` itself, because TypeScript only attaches `Symbol.metadata` to the class
189
- // after class decorators return; draining empties the bag, so whichever runs second is a no-op.
190
- applyMembers(entity, ownRegistrations(entity));
191
- const keys = keyMap();
192
- applyMembers(entity, {
193
- fields: opts.fields,
194
- relations: Object.fromEntries(definedEntries(opts.relations ?? {}).map(([key, spec]) => [key, relationRegistration(spec)])),
195
- hooks: Object.fromEntries(definedEntries(opts.hooks ?? {}).map(([event, methods]) => [event, methods(keys)])),
196
- });
325
+ const meta = emptyMeta(entity);
326
+ applyMembers(meta, members);
197
327
  // Unnamed checks are named by the generator, as unnamed indexes are.
198
- for (const check of opts.checks ?? []) {
199
- (meta.checks ??= []).push({ name: check.name, where: entityWhere(check.where) });
328
+ for (const check of opts.checks?.(memberRefs(), checkEntry) ?? []) {
329
+ (meta.checks ??= []).push({ name: check.name, where: check.where });
200
330
  }
201
- for (const index of opts.indexes ?? []) {
202
- defineIndex(entity, index);
331
+ for (const index of opts.indexes?.(indexRefs(), indexEntry) ?? []) {
332
+ addIndex(meta, index);
203
333
  }
204
- for (const trigger of opts.triggers ?? []) {
205
- defineTrigger(entity, trigger);
334
+ for (const trigger of opts.triggers?.(memberRefs(), triggerEntry) ?? []) {
335
+ addTrigger(meta, trigger);
206
336
  }
207
337
  for (const [name, filter] of definedEntries(opts.filters ?? {})) {
208
- defineFilter(entity, name, filter);
209
- }
210
- // A later call composes onto the entity, so a name is only ever set, and `derivedName` records that
211
- // the class name stood in, which is what a naming strategy derives from.
212
- if (opts.name !== undefined) {
213
- meta.name = opts.name;
214
- meta.derivedName = false;
338
+ addFilter(meta, name, filter);
215
339
  }
216
- else if (meta.name === undefined) {
217
- meta.name = entity.name;
218
- meta.derivedName = true;
219
- }
220
- meta.schema = opts.schema ?? meta.schema;
221
- // The class's real chain first: where a class both extends a base and names one, the one it extends
222
- // is the nearer, and nearer wins every merge.
340
+ // `derivedName` records that the class name stood in, which is what a naming strategy derives from.
341
+ meta.name = table;
342
+ meta.derivedName = opts.name === undefined;
343
+ meta.schema = opts.schema;
344
+ meta.abstract = opts.abstract;
223
345
  inheritFrom(meta, parentOf(entity));
224
- inheritFrom(meta, opts.extends);
225
346
  if (!hasKeys(meta.fields)) {
226
347
  throw new UqlUsageError(`'${entity.name}' must have fields`);
227
348
  }
349
+ for (const [key, field] of definedEntries(meta.fields)) {
350
+ const ranked = field.distance && findVectorIndex(meta, key)?.distance;
351
+ if (ranked && ranked !== field.distance) {
352
+ throw new UqlUsageError(`'${entity.name}.${key}' measures by '${field.distance}', but its vector index ranks by '${ranked}': name one metric`);
353
+ }
354
+ }
228
355
  // Derive soft-delete from the (inheritance-merged) fields, so own and inherited markers are handled
229
356
  // uniformly. Exactly one field may be marked; it auto-registers the built-in `softDelete` read
230
- // filter (a reserved name - see defineFilter - so it never clobbers a user filter).
357
+ // filter (a reserved name - see addFilter - so it never clobbers a user filter).
231
358
  const softDeleteKeys = fieldKeys(meta, ({ softDelete }) => softDelete !== undefined && softDelete !== false);
232
359
  if (softDeleteKeys.length > 1) {
233
360
  throw new UqlUsageError(`'${entity.name}' must have at most one field with 'softDelete'`);
@@ -246,13 +373,14 @@ export function defineEntity(entity, opts = {}) {
246
373
  // Implied rather than stated: the DDL default covers a row written around the ORM, and `onInsert`
247
374
  // covers MongoDB, which has no DDL to default. Both, so every backend starts a row at the same 0.
248
375
  const field = meta.fields[meta.version];
249
- meta.fields[meta.version] = { ...field, nullable: false, defaultValue: 0, onInsert: 0 };
376
+ meta.fields[meta.version] = { ...field, defaultValue: 0, onInsert: 0 };
250
377
  }
251
378
  const ids = getIdKeys(meta);
252
- if (!ids.length) {
253
- throw new UqlUsageError(`'${entity.name}' must have at least one id field (use @Id, defineId, or defineEntity({ fields: { ..., isId: true } }))`);
379
+ if (!ids.length && !meta.abstract) {
380
+ throw new UqlUsageError(`'${entity.name}' must have at least one id field (declare one with 'id()', as in 'f.number().id()')`);
254
381
  }
255
382
  meta.ids = ids;
383
+ metas.set(entity, meta);
256
384
  return meta;
257
385
  }
258
386
  /**
@@ -268,7 +396,7 @@ export function assertSoleId(meta, what) {
268
396
  }
269
397
  throw new UqlUsageError(ids.length
270
398
  ? `'${meta.entity.name}' has a composite primary key (${ids.join(', ')}), which ${what} does not support.`
271
- : // An entity registered with `@Field` but no `@Entity` never ran the check in `defineEntity`.
399
+ : // An entity registered with `@Field` but no `@Entity` never ran the check registration makes.
272
400
  `'${meta.entity.name}' has no primary key, which ${what} needs.`);
273
401
  }
274
402
  /** The entity's one primary key, for a path that cannot express a composite. See {@link assertSoleId}. */
@@ -299,7 +427,7 @@ export function valueFieldOf(field, seen) {
299
427
  return field;
300
428
  }
301
429
  seen = (seen ?? new Set()).add(field.references);
302
- const target = getMeta(field.references());
430
+ const target = registeredMeta(field.references());
303
431
  return valueFieldOf(fieldOf(target, soleIdOf(target, 'a foreign key')), seen);
304
432
  }
305
433
  /** The relation `key` names, for a caller that took `key` from the metadata itself. */
@@ -330,48 +458,72 @@ export function removeEntity(entity) {
330
458
  return metas.delete(entity);
331
459
  }
332
460
  export function getEntities() {
333
- return [...metas.values()].filter((meta) => meta.ids.length).map((meta) => meta.entity);
461
+ for (const entity of metas.keys()) {
462
+ settleSchema(entity);
463
+ }
464
+ return [...metas.values()]
465
+ .filter((meta) => meta.ids.length)
466
+ .map((meta) => meta.entity)
467
+ .filter(isTable);
334
468
  }
335
- /**
336
- * The metadata of `entity`, marked as changed. Every `define*` goes through this, and nothing outside
337
- * this file writes to a meta, so it is the one place a derived cache can be told it has gone stale.
338
- */
339
- function ensureWritableMeta(entity) {
340
- const meta = ensureMeta(entity);
341
- meta.revision++;
342
- return meta;
469
+ /** The class a schema relation targets, refused where it is abstract: a relation needs a table to join. */
470
+ function tableOf(target) {
471
+ if (!isTable(target)) {
472
+ throw new UqlUsageError(`'${target.name}' is abstract: a relation needs a table to join`);
473
+ }
474
+ return target;
475
+ }
476
+ /** Whether `entity` is a table: not marked abstract, so a query or write can take it. */
477
+ function isTable(entity) {
478
+ return !metas.get(entity)?.abstract;
479
+ }
480
+ /** The metadata `entity` has, a pending schema registered first, without settling anything further. */
481
+ function knownMeta(entity) {
482
+ settleSchema(entity);
483
+ return ensureMeta(entity);
343
484
  }
344
485
  function ensureMeta(entity) {
345
486
  let meta = metas.get(entity);
346
487
  if (meta) {
347
488
  return meta;
348
489
  }
349
- meta = { entity, ids: [], fields: {}, relations: {}, revision: 0 };
490
+ meta = emptyMeta(entity);
350
491
  metas.set(entity, meta);
351
492
  return meta;
352
493
  }
494
+ function emptyMeta(entity) {
495
+ return { entity, ids: [], fields: {}, relations: {} };
496
+ }
353
497
  export function getMeta(entity) {
498
+ const resolved = metas.get(entity);
499
+ if (resolved?.stage === 'resolved') {
500
+ return resolved;
501
+ }
354
502
  const meta = registeredMeta(entity);
503
+ if (meta.abstract) {
504
+ throw new UqlUsageError(`'${entity.name}' is abstract: read an entity extending it`);
505
+ }
355
506
  // Stamped once finalizing succeeds, so a read after a failure reports the same mistake again. Finalizing
356
507
  // reads other entities without resolving them, so no entity is ever read half resolved.
357
- if (meta.processedAt !== meta.revision) {
358
- fillRelations(meta);
359
- meta.processedAt = meta.revision;
360
- }
508
+ fillRelations(meta);
509
+ meta.readKeys = defaultReadKeys(meta);
510
+ meta.stage = 'resolved';
361
511
  return meta;
362
512
  }
363
513
  /** The metadata `entity` registered, however much of it is resolved. */
364
514
  function registeredMeta(entity) {
515
+ settleSchema(entity);
365
516
  const meta = metas.get(entity);
366
517
  if (!meta) {
367
518
  throw new UqlUsageError(`'${entity.name}' is not an entity`);
368
519
  }
520
+ settleRelations(meta);
369
521
  return meta;
370
522
  }
371
523
  function fillRelations(meta) {
372
524
  for (const [relKey, relation] of definedEntries(meta.relations)) {
373
525
  const at = `'${meta.entity.name}.${relKey}'`;
374
- const references = settledReferences(at, meta, relKey, relation);
526
+ const references = settledReferences(at, meta, relation);
375
527
  if (!references.length) {
376
528
  throw new UqlUsageError(`${at} has no columns to join on.`);
377
529
  }
@@ -392,10 +544,10 @@ function fillRelations(meta) {
392
544
  * needs it. Never resolving an entity is what keeps it from recursing, and the one column a to-one names is
393
545
  * paired with its target's key only here, since registration can run before the target has one.
394
546
  */
395
- function settledReferences(at, meta, relKey, relOpts) {
547
+ function settledReferences(at, meta, relOpts) {
396
548
  const { references, mappedBy, through } = relOpts;
397
549
  if (typeof references === 'string') {
398
- const target = ensureMeta(relOpts.entity());
550
+ const target = knownMeta(relOpts.entity());
399
551
  if (mappedBy || isToManyRelation(relOpts) || target.ids.length > 1) {
400
552
  throw new UqlUsageError(`${at} names one column, '${references}', which only a to-one holding a foreign key to a one-column key ` +
401
553
  'can: pair the columns, [{ local, foreign }].');
@@ -409,12 +561,45 @@ function settledReferences(at, meta, relKey, relOpts) {
409
561
  return fillInverseSide(at, meta, relOpts, mappedBy);
410
562
  if (through)
411
563
  return fillThrough(at, meta, relOpts, through);
564
+ const inferred = inferredJoin(at, meta, relOpts);
565
+ if (inferred) {
566
+ Object.assign(relOpts, inferred);
567
+ return settledReferences(at, meta, relOpts);
568
+ }
412
569
  throw new UqlUsageError(isToManyRelation(relOpts)
413
570
  ? `${at} is a to-many relation with no way to join: it needs 'mappedBy' (the member on the other side), ` +
414
571
  "'through' (a junction entity), or 'references' (the columns)."
415
572
  : `${at} needs 'references', the foreign key column it joins by, or 'mappedBy', the member on the other ` +
416
573
  'side holding it.');
417
574
  }
575
+ /**
576
+ * The join a relation naming none can only mean: a many-to-one's one field referencing its target, a one-to-many's
577
+ * one many-to-one on the target pointing back. Nothing where there is none; refused where there are several.
578
+ */
579
+ function inferredJoin(at, meta, relOpts) {
580
+ const target = relOpts.entity();
581
+ if (relOpts.cardinality === 'm1') {
582
+ const columns = fieldKeys(meta, (field) => !!field.references && isA(target, field.references()));
583
+ const references = onlyCandidate(at, columns, 'join by', `a foreign key to '${target.name}'`, 'references');
584
+ return references === undefined ? undefined : { references };
585
+ }
586
+ if (relOpts.cardinality === '1m') {
587
+ const back = definedEntries(registeredMeta(target).relations)
588
+ .filter(([, relation]) => relation.cardinality === 'm1' && isA(meta.entity, relation.entity()))
589
+ .map(([key]) => key);
590
+ const mappedBy = onlyCandidate(at, back, 'be mapped by', `a relation to '${meta.entity.name}'`, 'mappedBy');
591
+ return mappedBy === undefined ? undefined : { mappedBy };
592
+ }
593
+ return undefined;
594
+ }
595
+ /** The one candidate, nothing for none, and a refusal naming each where there are several. */
596
+ function onlyCandidate(at, candidates, verb, each, option) {
597
+ if (candidates.length > 1) {
598
+ const named = candidates.map((key) => `'${key}'`);
599
+ throw new UqlUsageError(`${at} could ${verb} ${named.slice(0, -1).join(', ')} or ${named.at(-1)}, each ${each}: name one with '${option}'.`);
600
+ }
601
+ return candidates[0];
602
+ }
418
603
  /**
419
604
  * Each key of this entity, then each of the target, paired with the junction's one column referencing it.
420
605
  * Both groups live on the junction whatever the cardinality, as `deleteRelations` and every dialect read
@@ -424,7 +609,7 @@ function fillThrough(at, meta, relOpts, through) {
424
609
  const junction = registeredMeta(through());
425
610
  relOpts.references = [
426
611
  ...junctionReferences(at, junction, meta),
427
- ...junctionReferences(at, junction, ensureMeta(relOpts.entity())),
612
+ ...junctionReferences(at, junction, knownMeta(relOpts.entity())),
428
613
  ];
429
614
  return relOpts.references;
430
615
  }
@@ -452,7 +637,7 @@ function fillInverseSide(at, meta, relOpts, mappedBy) {
452
637
  if (!isA(meta.entity, ownerTarget)) {
453
638
  throw new UqlUsageError(`${at} is mapped by ${other}, a relation to '${ownerTarget.name}', not to '${meta.entity.name}'.`);
454
639
  }
455
- const ownerReferences = settledReferences(other, relMeta, mappedBy, owner);
640
+ const ownerReferences = settledReferences(other, relMeta, owner);
456
641
  // Two different flips: a junction's pairs are the owner's group followed by ours, so the two groups
457
642
  // swap - `toReversed` would also reverse each group, pairing a composite's columns crosswise. A
458
643
  // plain foreign key is one pair per key whose ends swap.
@@ -498,7 +683,7 @@ function isA(entity, base) {
498
683
  return entity === base || entity.prototype instanceof base;
499
684
  }
500
685
  /**
501
- * The foreign keys an entity holds: each owning to-one's columns, and each `@Field({ references })` no
686
+ * The foreign keys an entity holds: each owning to-one's columns, and each `f.references()` no
502
687
  * relation joins on, as the many-to-one it describes, once its target has registered a key. What the
503
688
  * schema build constrains and a junction joins by, settling the relations holding them first.
504
689
  */
@@ -506,15 +691,16 @@ export function foreignKeysOf(meta) {
506
691
  const owning = definedEntries(meta.relations)
507
692
  .filter(([, relation]) => holdsForeignKey(relation))
508
693
  .map(([relKey, relation]) => {
509
- settledReferences(`'${meta.entity.name}.${relKey}'`, meta, relKey, relation);
694
+ settledReferences(`'${meta.entity.name}.${relKey}'`, meta, relation);
510
695
  return relation;
511
696
  });
512
697
  const joined = new Set(owning.flatMap(({ references }) => references.map(({ local }) => local)));
513
698
  const columns = definedEntries(meta.fields).flatMap(([key, field]) => {
514
- if (!field.references || joined.has(key))
699
+ if (!field.references)
515
700
  return [];
516
- const target = ensureMeta(field.references());
517
- if (!target.ids.length)
701
+ const target = knownMeta(field.references());
702
+ assertHoldsKey(`'${meta.entity.name}.${key}'`, field, target);
703
+ if (joined.has(key) || !target.ids.length)
518
704
  return [];
519
705
  if (target.ids.length > 1) {
520
706
  throw new UqlUsageError(`'${meta.entity.name}.${key}' cannot reference '${target.entity.name}', whose primary key is composite ` +
@@ -525,16 +711,31 @@ export function foreignKeysOf(meta) {
525
711
  });
526
712
  return [...owning, ...columns];
527
713
  }
714
+ /** The kinds a column of `type` holds as a join compares them, as `ValueKind` does: a bigint is a number, which BIGINT widens. */
715
+ function joinedKinds(type) {
716
+ const types = valueTypesOf(type);
717
+ return types && [...new Set(types.map((kind) => (kind === 'bigint' ? 'number' : kind)))];
718
+ }
719
+ /** Refuses a foreign key whose `type` holds another kind of value than the key it references, which no join matches. */
720
+ function assertHoldsKey(at, field, target) {
721
+ if (field.typeFromReference || target.ids.length !== 1)
722
+ return;
723
+ const held = joinedKinds(field.type);
724
+ const needed = joinedKinds(valueFieldOf(fieldOf(target, target.ids[0])).type);
725
+ if (held && needed && !needed.every((kind) => held.includes(kind))) {
726
+ throw new UqlUsageError(`${at} holds a ${held.join(' or ')}, but the key of '${target.entity.name}' it references is a ${needed.join(' or ')}`);
727
+ }
728
+ }
528
729
  /** Each key of `side`, paired with the one column of `junction` referencing it: a rename of either follows. */
529
730
  function junctionReferences(at, junction, side) {
530
- const pairs = foreignKeysOf(junction).flatMap(({ entity, references }) => entity() === side.entity ? references : []);
731
+ const pairs = foreignKeysOf(junction).flatMap(({ entity, references }) => Object.is(entity(), side.entity) ? references : []);
531
732
  return side.ids.map((key) => {
532
733
  const [pair, ...others] = pairs.filter(({ foreign }) => foreign === key);
533
734
  const referenced = `'${side.entity.name}.${key}'`;
534
735
  if (!pair) {
535
736
  const declare = side.ids.length > 1
536
737
  ? `a column per key, paired in a '@ManyToOne' to '${side.entity.name}'`
537
- : `'@Field({ references: () => ${side.entity.name} })'`;
738
+ : `'f.references(() => ${side.entity.name})'`;
538
739
  throw new UqlUsageError(`${at} joins through '${junction.entity.name}', which has no column referencing ${referenced}: declare ${declare}.`);
539
740
  }
540
741
  if (others.length) {
@@ -556,8 +757,8 @@ function getIdKeys(meta) {
556
757
  function inheritFrom(meta, ancestor) {
557
758
  for (let parent = ancestor; parent && parent !== Object; parent = parentOf(parent)) {
558
759
  const base = parent;
559
- applyMembers(base, ownRegistrations(base));
560
- extendMeta(meta, ensureMeta(base));
760
+ applyMembers(ensureMeta(base), ownRegistrations(base));
761
+ extendMeta(meta, knownMeta(base));
561
762
  }
562
763
  }
563
764
  /** The class `entity` extends, `Object` where it extends nothing. */
@@ -574,20 +775,15 @@ function extendMeta(target, source) {
574
775
  }
575
776
  }
576
777
  target.fields = { ...sourceFields, ...target.fields };
577
- // A copy of each relation per entity: resolving one writes the columns it joins on into it, and those
578
- // columns are the resolving entity's, so one shared object left every later entity without them.
579
- target.relations = {
580
- ...Object.fromEntries(definedEntries(source.relations).map(([key, relation]) => [key, { ...relation }])),
581
- ...target.relations,
582
- };
583
778
  // Inherit user-defined filters from the parent (child overrides by name). The built-in soft-delete
584
- // filter + `meta.softDelete` are (re)derived from the merged fields in `defineEntity`.
779
+ // filter + `meta.softDelete` are (re)derived from the merged fields at registration.
585
780
  if (source.filters) {
586
781
  target.filters = { ...source.filters, ...target.filters };
587
782
  }
588
783
  // A base's hooks fire first, as its triggers do: they are the entries written before the child's own.
589
784
  for (const [event, sourceList] of definedEntries(source.hooks ?? {})) {
590
- (target.hooks ??= {})[event] = inheritedEntries(sourceList, target.hooks?.[event], (hook) => hook.methodName);
785
+ const rebound = sourceList.map((hook) => resolvedHook(target.entity, event, hook));
786
+ (target.hooks ??= {})[event] = inheritedEntries(rebound, target.hooks?.[event], (hook) => hook.methodName);
591
787
  }
592
788
  target.indexes = inheritedEntries(source.indexes, target.indexes, (index) => index.name);
593
789
  target.checks = inheritedEntries(source.checks, target.checks, (check) => check.name);