uql-orm 0.104.0 → 0.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +24 -10
  2. package/dist/browser/uql-browser.min.js +2 -2
  3. package/dist/browser/uql-browser.min.js.map +7 -7
  4. package/dist/dialect/abstractSqlDialect.d.ts +6 -4
  5. package/dist/dialect/abstractSqlDialect.js +35 -32
  6. package/dist/dialect/aliases.d.ts +2 -0
  7. package/dist/dialect/aliases.js +2 -0
  8. package/dist/dialect/jsonSql.js +2 -2
  9. package/dist/dialect/mysqlLikeSqlDialect.d.ts +1 -1
  10. package/dist/dialect/mysqlLikeSqlDialect.js +1 -1
  11. package/dist/dialect/operators.js +2 -4
  12. package/dist/dialect/queryJoins.d.ts +2 -0
  13. package/dist/dialect/vectorSqlDialect.d.ts +1 -1
  14. package/dist/dialect/vectorSqlDialect.js +1 -1
  15. package/dist/entity/column.d.ts +3 -0
  16. package/dist/entity/column.js +3 -0
  17. package/dist/entity/columnOptionsBuilder.d.ts +54 -0
  18. package/dist/entity/columnOptionsBuilder.js +108 -0
  19. package/dist/entity/decorator/bag.d.ts +4 -4
  20. package/dist/entity/decorator/entity.d.ts +2 -19
  21. package/dist/entity/decorator/entity.js +3 -37
  22. package/dist/entity/decorator/members.d.ts +46 -76
  23. package/dist/entity/decorator/members.js +18 -7
  24. package/dist/entity/index.d.ts +2 -1
  25. package/dist/entity/index.js +2 -1
  26. package/dist/entity/metadata/definition.d.ts +10 -24
  27. package/dist/entity/metadata/definition.js +329 -147
  28. package/dist/entity/metadata/schemaFixture/animal.d.ts +54 -0
  29. package/dist/entity/metadata/schemaFixture/animal.js +7 -0
  30. package/dist/entity/metadata/schemaFixture/author.d.ts +140 -0
  31. package/dist/entity/metadata/schemaFixture/author.js +25 -0
  32. package/dist/entity/metadata/schemaFixture/book.d.ts +192 -0
  33. package/dist/entity/metadata/schemaFixture/book.js +22 -0
  34. package/dist/http/query.js +12 -13
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +2 -1
  37. package/dist/mariadb/mariaDialect.js +1 -1
  38. package/dist/mariadb/mariadbQuerier.js +1 -3
  39. package/dist/migrate/builder/columnBuilder.d.ts +20 -68
  40. package/dist/migrate/builder/columnBuilder.js +104 -110
  41. package/dist/migrate/builder/migrationBuilder.d.ts +3 -3
  42. package/dist/migrate/builder/migrationBuilder.js +7 -6
  43. package/dist/migrate/builder/tableBuilder.d.ts +3 -55
  44. package/dist/migrate/builder/tableBuilder.js +88 -204
  45. package/dist/migrate/builder/types.d.ts +52 -151
  46. package/dist/migrate/builder/types.js +0 -6
  47. package/dist/migrate/codegen/entityCodeGenerator.d.ts +2 -2
  48. package/dist/migrate/codegen/entityCodeGenerator.js +24 -24
  49. package/dist/migrate/codegen/fieldOptionsSource.d.ts +3 -1
  50. package/dist/migrate/codegen/fieldOptionsSource.js +35 -34
  51. package/dist/migrate/codegen/indexEntrySource.d.ts +16 -0
  52. package/dist/migrate/codegen/{indexDecoratorSource.js → indexEntrySource.js} +54 -27
  53. package/dist/migrate/ddl/defaultSql.js +7 -6
  54. package/dist/migrate/ddl/indexCapabilities.d.ts +8 -7
  55. package/dist/migrate/ddl/indexCapabilities.js +26 -13
  56. package/dist/migrate/ddl/indexDdl.d.ts +13 -13
  57. package/dist/migrate/ddl/indexDdl.js +33 -30
  58. package/dist/migrate/ddl/mysqlIndexDdl.d.ts +6 -11
  59. package/dist/migrate/ddl/mysqlIndexDdl.js +17 -28
  60. package/dist/migrate/ddl/pgIndexDdl.d.ts +2 -2
  61. package/dist/migrate/ddl/sqliteIndexDdl.d.ts +2 -2
  62. package/dist/migrate/drift/driftDetector.js +2 -2
  63. package/dist/migrate/generator/definitionToNode.d.ts +8 -2
  64. package/dist/migrate/generator/definitionToNode.js +4 -5
  65. package/dist/migrate/introspection/abstractSqlSchemaIntrospector.js +11 -2
  66. package/dist/migrate/introspection/jsonIndexEntry.d.ts +6 -0
  67. package/dist/migrate/introspection/jsonIndexEntry.js +120 -0
  68. package/dist/migrate/introspection/mysqlIntrospector.d.ts +4 -4
  69. package/dist/migrate/introspection/mysqlIntrospector.js +25 -21
  70. package/dist/migrate/introspection/postgresIntrospector.d.ts +1 -1
  71. package/dist/migrate/introspection/postgresIntrospector.js +3 -4
  72. package/dist/migrate/introspection/sqliteIntrospector.js +24 -9
  73. package/dist/migrate/introspection/tableSchemaAST.js +5 -1
  74. package/dist/migrate/schemaChange.d.ts +3 -3
  75. package/dist/migrate/schemaChange.js +3 -2
  76. package/dist/migrate/schemaGenerator.js +1 -1
  77. package/dist/migrate/storage/databaseStorage.js +4 -4
  78. package/dist/mongodb/mongoDialect.d.ts +33 -36
  79. package/dist/mongodb/mongoDialect.js +118 -32
  80. package/dist/mongodb/mongoIntrospector.d.ts +3 -1
  81. package/dist/mongodb/mongoIntrospector.js +11 -5
  82. package/dist/mongodb/mongoSchemaGenerator.js +35 -27
  83. package/dist/mongodb/mongodbQuerier.d.ts +1 -11
  84. package/dist/mongodb/mongodbQuerier.js +9 -43
  85. package/dist/querier/abstractQuerier.d.ts +0 -1
  86. package/dist/querier/abstractQuerier.js +1 -20
  87. package/dist/querier/keyset.js +3 -3
  88. package/dist/schema/declaredColumn.d.ts +11 -0
  89. package/dist/schema/declaredColumn.js +21 -0
  90. package/dist/schema/indexColumns.d.ts +0 -3
  91. package/dist/schema/indexColumns.js +11 -7
  92. package/dist/schema/indexDifferences.d.ts +10 -5
  93. package/dist/schema/indexDifferences.js +42 -28
  94. package/dist/schema/schemaASTBuilder.js +28 -36
  95. package/dist/schema/schemaASTDiffer.js +8 -4
  96. package/dist/schema/sqlExpression.d.ts +21 -17
  97. package/dist/schema/sqlExpression.js +11 -23
  98. package/dist/type/column.d.ts +328 -0
  99. package/dist/type/column.js +2 -0
  100. package/dist/type/config.d.ts +1 -1
  101. package/dist/type/dialect.d.ts +2 -1
  102. package/dist/type/dialect.js +1 -0
  103. package/dist/type/entity.d.ts +290 -279
  104. package/dist/type/entity.js +6 -1
  105. package/dist/type/index.d.ts +2 -0
  106. package/dist/type/index.js +2 -0
  107. package/dist/type/migration.d.ts +5 -5
  108. package/dist/type/query.d.ts +45 -41
  109. package/dist/type/query.js +2 -3
  110. package/dist/type/queryAggregate.d.ts +22 -12
  111. package/dist/type/querySql.d.ts +20 -4
  112. package/dist/type/querySql.js +27 -9
  113. package/dist/type/schemaEntity.d.ts +190 -0
  114. package/dist/type/schemaEntity.js +1 -0
  115. package/dist/type/utility.d.ts +0 -6
  116. package/dist/type/vector.d.ts +1 -1
  117. package/dist/util/ddlExpression.util.d.ts +12 -13
  118. package/dist/util/ddlExpression.util.js +12 -21
  119. package/dist/util/dialect.util.d.ts +11 -5
  120. package/dist/util/dialect.util.js +31 -37
  121. package/dist/util/field.util.d.ts +10 -9
  122. package/dist/util/field.util.js +14 -10
  123. package/dist/util/fieldOption.util.d.ts +11 -95
  124. package/dist/util/fieldOption.util.js +49 -16
  125. package/dist/util/hook.util.d.ts +2 -14
  126. package/dist/util/hook.util.js +3 -16
  127. package/dist/util/index.d.ts +1 -0
  128. package/dist/util/index.js +1 -0
  129. package/dist/util/indexEntry.util.d.ts +45 -0
  130. package/dist/util/indexEntry.util.js +138 -0
  131. package/dist/util/relationQuery.util.d.ts +0 -1
  132. package/dist/util/relationQuery.util.js +0 -5
  133. package/dist/util/sql.d.ts +10 -7
  134. package/dist/util/sql.js +34 -16
  135. package/dist/util/sql.util.d.ts +4 -5
  136. package/dist/util/sql.util.js +7 -16
  137. package/dist/util/string.util.d.ts +2 -0
  138. package/dist/util/string.util.js +4 -0
  139. package/dist/util/uqlError.d.ts +1 -1
  140. package/dist/util/uqlError.js +1 -1
  141. package/package.json +1 -1
  142. package/skills/uql-orm/SKILL.md +76 -25
  143. package/dist/migrate/codegen/indexDecoratorSource.d.ts +0 -16
@@ -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)) {
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: () => 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,58 @@ 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()].filter((meta) => meta.ids.length && !meta.abstract).map((meta) => meta.entity);
334
465
  }
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;
466
+ /** The metadata `entity` has, a pending schema registered first, without settling anything further. */
467
+ function knownMeta(entity) {
468
+ settleSchema(entity);
469
+ return ensureMeta(entity);
343
470
  }
344
471
  function ensureMeta(entity) {
345
472
  let meta = metas.get(entity);
346
473
  if (meta) {
347
474
  return meta;
348
475
  }
349
- meta = { entity, ids: [], fields: {}, relations: {}, revision: 0 };
476
+ meta = emptyMeta(entity);
350
477
  metas.set(entity, meta);
351
478
  return meta;
352
479
  }
480
+ function emptyMeta(entity) {
481
+ return { entity, ids: [], fields: {}, relations: {} };
482
+ }
353
483
  export function getMeta(entity) {
484
+ const resolved = metas.get(entity);
485
+ if (resolved?.stage === 'resolved') {
486
+ return resolved;
487
+ }
354
488
  const meta = registeredMeta(entity);
489
+ if (meta.abstract) {
490
+ throw new UqlUsageError(`'${entity.name}' is abstract: read an entity extending it`);
491
+ }
355
492
  // Stamped once finalizing succeeds, so a read after a failure reports the same mistake again. Finalizing
356
493
  // 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
- }
494
+ fillRelations(meta);
495
+ meta.readKeys = defaultReadKeys(meta);
496
+ meta.stage = 'resolved';
361
497
  return meta;
362
498
  }
363
499
  /** The metadata `entity` registered, however much of it is resolved. */
364
500
  function registeredMeta(entity) {
501
+ settleSchema(entity);
365
502
  const meta = metas.get(entity);
366
503
  if (!meta) {
367
504
  throw new UqlUsageError(`'${entity.name}' is not an entity`);
368
505
  }
506
+ settleRelations(meta);
369
507
  return meta;
370
508
  }
371
509
  function fillRelations(meta) {
372
510
  for (const [relKey, relation] of definedEntries(meta.relations)) {
373
511
  const at = `'${meta.entity.name}.${relKey}'`;
374
- const references = settledReferences(at, meta, relKey, relation);
512
+ const references = settledReferences(at, meta, relation);
375
513
  if (!references.length) {
376
514
  throw new UqlUsageError(`${at} has no columns to join on.`);
377
515
  }
@@ -392,10 +530,10 @@ function fillRelations(meta) {
392
530
  * needs it. Never resolving an entity is what keeps it from recursing, and the one column a to-one names is
393
531
  * paired with its target's key only here, since registration can run before the target has one.
394
532
  */
395
- function settledReferences(at, meta, relKey, relOpts) {
533
+ function settledReferences(at, meta, relOpts) {
396
534
  const { references, mappedBy, through } = relOpts;
397
535
  if (typeof references === 'string') {
398
- const target = ensureMeta(relOpts.entity());
536
+ const target = knownMeta(relOpts.entity());
399
537
  if (mappedBy || isToManyRelation(relOpts) || target.ids.length > 1) {
400
538
  throw new UqlUsageError(`${at} names one column, '${references}', which only a to-one holding a foreign key to a one-column key ` +
401
539
  'can: pair the columns, [{ local, foreign }].');
@@ -409,12 +547,45 @@ function settledReferences(at, meta, relKey, relOpts) {
409
547
  return fillInverseSide(at, meta, relOpts, mappedBy);
410
548
  if (through)
411
549
  return fillThrough(at, meta, relOpts, through);
550
+ const inferred = inferredJoin(at, meta, relOpts);
551
+ if (inferred) {
552
+ Object.assign(relOpts, inferred);
553
+ return settledReferences(at, meta, relOpts);
554
+ }
412
555
  throw new UqlUsageError(isToManyRelation(relOpts)
413
556
  ? `${at} is a to-many relation with no way to join: it needs 'mappedBy' (the member on the other side), ` +
414
557
  "'through' (a junction entity), or 'references' (the columns)."
415
558
  : `${at} needs 'references', the foreign key column it joins by, or 'mappedBy', the member on the other ` +
416
559
  'side holding it.');
417
560
  }
561
+ /**
562
+ * The join a relation naming none can only mean: a many-to-one's one field referencing its target, a one-to-many's
563
+ * one many-to-one on the target pointing back. Nothing where there is none; refused where there are several.
564
+ */
565
+ function inferredJoin(at, meta, relOpts) {
566
+ const target = relOpts.entity();
567
+ if (relOpts.cardinality === 'm1') {
568
+ const columns = fieldKeys(meta, (field) => !!field.references && isA(target, field.references()));
569
+ const references = onlyCandidate(at, columns, 'join by', `a foreign key to '${target.name}'`, 'references');
570
+ return references === undefined ? undefined : { references };
571
+ }
572
+ if (relOpts.cardinality === '1m') {
573
+ const back = definedEntries(registeredMeta(target).relations)
574
+ .filter(([, relation]) => relation.cardinality === 'm1' && isA(meta.entity, relation.entity()))
575
+ .map(([key]) => key);
576
+ const mappedBy = onlyCandidate(at, back, 'be mapped by', `a relation to '${meta.entity.name}'`, 'mappedBy');
577
+ return mappedBy === undefined ? undefined : { mappedBy };
578
+ }
579
+ return undefined;
580
+ }
581
+ /** The one candidate, nothing for none, and a refusal naming each where there are several. */
582
+ function onlyCandidate(at, candidates, verb, each, option) {
583
+ if (candidates.length > 1) {
584
+ const named = candidates.map((key) => `'${key}'`);
585
+ throw new UqlUsageError(`${at} could ${verb} ${named.slice(0, -1).join(', ')} or ${named.at(-1)}, each ${each}: name one with '${option}'.`);
586
+ }
587
+ return candidates[0];
588
+ }
418
589
  /**
419
590
  * Each key of this entity, then each of the target, paired with the junction's one column referencing it.
420
591
  * Both groups live on the junction whatever the cardinality, as `deleteRelations` and every dialect read
@@ -424,7 +595,7 @@ function fillThrough(at, meta, relOpts, through) {
424
595
  const junction = registeredMeta(through());
425
596
  relOpts.references = [
426
597
  ...junctionReferences(at, junction, meta),
427
- ...junctionReferences(at, junction, ensureMeta(relOpts.entity())),
598
+ ...junctionReferences(at, junction, knownMeta(relOpts.entity())),
428
599
  ];
429
600
  return relOpts.references;
430
601
  }
@@ -452,7 +623,7 @@ function fillInverseSide(at, meta, relOpts, mappedBy) {
452
623
  if (!isA(meta.entity, ownerTarget)) {
453
624
  throw new UqlUsageError(`${at} is mapped by ${other}, a relation to '${ownerTarget.name}', not to '${meta.entity.name}'.`);
454
625
  }
455
- const ownerReferences = settledReferences(other, relMeta, mappedBy, owner);
626
+ const ownerReferences = settledReferences(other, relMeta, owner);
456
627
  // Two different flips: a junction's pairs are the owner's group followed by ours, so the two groups
457
628
  // swap - `toReversed` would also reverse each group, pairing a composite's columns crosswise. A
458
629
  // plain foreign key is one pair per key whose ends swap.
@@ -498,7 +669,7 @@ function isA(entity, base) {
498
669
  return entity === base || entity.prototype instanceof base;
499
670
  }
500
671
  /**
501
- * The foreign keys an entity holds: each owning to-one's columns, and each `@Field({ references })` no
672
+ * The foreign keys an entity holds: each owning to-one's columns, and each `f.references()` no
502
673
  * relation joins on, as the many-to-one it describes, once its target has registered a key. What the
503
674
  * schema build constrains and a junction joins by, settling the relations holding them first.
504
675
  */
@@ -506,15 +677,16 @@ export function foreignKeysOf(meta) {
506
677
  const owning = definedEntries(meta.relations)
507
678
  .filter(([, relation]) => holdsForeignKey(relation))
508
679
  .map(([relKey, relation]) => {
509
- settledReferences(`'${meta.entity.name}.${relKey}'`, meta, relKey, relation);
680
+ settledReferences(`'${meta.entity.name}.${relKey}'`, meta, relation);
510
681
  return relation;
511
682
  });
512
683
  const joined = new Set(owning.flatMap(({ references }) => references.map(({ local }) => local)));
513
684
  const columns = definedEntries(meta.fields).flatMap(([key, field]) => {
514
- if (!field.references || joined.has(key))
685
+ if (!field.references)
515
686
  return [];
516
- const target = ensureMeta(field.references());
517
- if (!target.ids.length)
687
+ const target = knownMeta(field.references());
688
+ assertHoldsKey(`'${meta.entity.name}.${key}'`, field, target);
689
+ if (joined.has(key) || !target.ids.length)
518
690
  return [];
519
691
  if (target.ids.length > 1) {
520
692
  throw new UqlUsageError(`'${meta.entity.name}.${key}' cannot reference '${target.entity.name}', whose primary key is composite ` +
@@ -525,6 +697,21 @@ export function foreignKeysOf(meta) {
525
697
  });
526
698
  return [...owning, ...columns];
527
699
  }
700
+ /** The kinds a column of `type` holds as a join compares them, as `ValueKind` does: a bigint is a number, which BIGINT widens. */
701
+ function joinedKinds(type) {
702
+ const types = valueTypesOf(type);
703
+ return types && [...new Set(types.map((kind) => (kind === 'bigint' ? 'number' : kind)))];
704
+ }
705
+ /** Refuses a foreign key whose `type` holds another kind of value than the key it references, which no join matches. */
706
+ function assertHoldsKey(at, field, target) {
707
+ if (field.typeFromReference || target.ids.length !== 1)
708
+ return;
709
+ const held = joinedKinds(field.type);
710
+ const needed = joinedKinds(valueFieldOf(fieldOf(target, target.ids[0])).type);
711
+ if (held && needed && !needed.every((kind) => held.includes(kind))) {
712
+ throw new UqlUsageError(`${at} holds a ${held.join(' or ')}, but the key of '${target.entity.name}' it references is a ${needed.join(' or ')}`);
713
+ }
714
+ }
528
715
  /** Each key of `side`, paired with the one column of `junction` referencing it: a rename of either follows. */
529
716
  function junctionReferences(at, junction, side) {
530
717
  const pairs = foreignKeysOf(junction).flatMap(({ entity, references }) => entity() === side.entity ? references : []);
@@ -534,7 +721,7 @@ function junctionReferences(at, junction, side) {
534
721
  if (!pair) {
535
722
  const declare = side.ids.length > 1
536
723
  ? `a column per key, paired in a '@ManyToOne' to '${side.entity.name}'`
537
- : `'@Field({ references: () => ${side.entity.name} })'`;
724
+ : `'f.references(() => ${side.entity.name})'`;
538
725
  throw new UqlUsageError(`${at} joins through '${junction.entity.name}', which has no column referencing ${referenced}: declare ${declare}.`);
539
726
  }
540
727
  if (others.length) {
@@ -556,8 +743,8 @@ function getIdKeys(meta) {
556
743
  function inheritFrom(meta, ancestor) {
557
744
  for (let parent = ancestor; parent && parent !== Object; parent = parentOf(parent)) {
558
745
  const base = parent;
559
- applyMembers(base, ownRegistrations(base));
560
- extendMeta(meta, ensureMeta(base));
746
+ applyMembers(ensureMeta(base), ownRegistrations(base));
747
+ extendMeta(meta, knownMeta(base));
561
748
  }
562
749
  }
563
750
  /** The class `entity` extends, `Object` where it extends nothing. */
@@ -574,20 +761,15 @@ function extendMeta(target, source) {
574
761
  }
575
762
  }
576
763
  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
764
  // 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`.
765
+ // filter + `meta.softDelete` are (re)derived from the merged fields at registration.
585
766
  if (source.filters) {
586
767
  target.filters = { ...source.filters, ...target.filters };
587
768
  }
588
769
  // A base's hooks fire first, as its triggers do: they are the entries written before the child's own.
589
770
  for (const [event, sourceList] of definedEntries(source.hooks ?? {})) {
590
- (target.hooks ??= {})[event] = inheritedEntries(sourceList, target.hooks?.[event], (hook) => hook.methodName);
771
+ const rebound = sourceList.map((hook) => resolvedHook(target.entity, event, hook));
772
+ (target.hooks ??= {})[event] = inheritedEntries(rebound, target.hooks?.[event], (hook) => hook.methodName);
591
773
  }
592
774
  target.indexes = inheritedEntries(source.indexes, target.indexes, (index) => index.name);
593
775
  target.checks = inheritedEntries(source.checks, target.checks, (check) => check.name);