metal-orm 1.1.10 → 1.1.16

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 (192) hide show
  1. package/README.md +758 -769
  2. package/dist/index.cjs +106 -43
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +5 -5
  5. package/dist/index.d.ts +5 -5
  6. package/dist/index.js +106 -43
  7. package/dist/index.js.map +1 -1
  8. package/package.json +100 -96
  9. package/scripts/generate-entities/render.mjs +21 -12
  10. package/scripts/generate-entities/schema.mjs +209 -195
  11. package/scripts/generate-entities/tree-detection.mjs +159 -153
  12. package/scripts/inflection/pt-br.mjs +468 -468
  13. package/scripts/run-eslint.mjs +33 -34
  14. package/scripts/show-sql-seed.sql +102 -0
  15. package/scripts/show-sql.mjs +321 -325
  16. package/src/bulk/bulk-delete-executor.ts +3 -5
  17. package/src/bulk/bulk-insert-executor.ts +7 -7
  18. package/src/bulk/bulk-update-executor.ts +2 -2
  19. package/src/bulk/bulk-upsert-executor.ts +5 -7
  20. package/src/codegen/naming-strategy.ts +54 -54
  21. package/src/codegen/typescript.ts +482 -482
  22. package/src/core/ast/adapters.ts +1 -1
  23. package/src/core/ast/builders.ts +123 -123
  24. package/src/core/ast/expression-builders.ts +745 -745
  25. package/src/core/ast/expression-nodes.ts +304 -304
  26. package/src/core/ast/expression-visitor.ts +212 -212
  27. package/src/core/ast/expression.ts +20 -20
  28. package/src/core/ast/helpers.ts +14 -14
  29. package/src/core/ast/join.ts +18 -18
  30. package/src/core/ast/query.ts +200 -200
  31. package/src/core/ddl/dialects/base-schema-dialect.ts +1 -1
  32. package/src/core/ddl/dialects/mssql-schema-dialect.ts +1 -1
  33. package/src/core/ddl/dialects/mysql-schema-dialect.ts +1 -1
  34. package/src/core/ddl/dialects/postgres-schema-dialect.ts +1 -1
  35. package/src/core/ddl/dialects/render-reference.test.ts +70 -70
  36. package/src/core/ddl/dialects/sqlite-schema-dialect.ts +1 -1
  37. package/src/core/ddl/introspect/catalogs/index.ts +5 -5
  38. package/src/core/ddl/introspect/catalogs/postgres.ts +146 -146
  39. package/src/core/ddl/introspect/context.ts +15 -15
  40. package/src/core/ddl/introspect/functions/postgres.ts +35 -35
  41. package/src/core/ddl/introspect/mysql.ts +113 -36
  42. package/src/core/ddl/introspect/registry.ts +40 -40
  43. package/src/core/ddl/introspect/run-select.ts +35 -35
  44. package/src/core/ddl/introspect/utils.ts +56 -56
  45. package/src/core/ddl/naming-strategy.ts +16 -16
  46. package/src/core/ddl/schema-dialect.ts +56 -56
  47. package/src/core/ddl/schema-diff.ts +234 -234
  48. package/src/core/ddl/schema-generator.ts +1 -1
  49. package/src/core/ddl/schema-introspect.ts +25 -25
  50. package/src/core/ddl/sql-writing.ts +171 -171
  51. package/src/core/dialect/abstract.ts +541 -541
  52. package/src/core/dialect/base/cte-compiler.ts +33 -33
  53. package/src/core/dialect/base/function-table-formatter.ts +103 -103
  54. package/src/core/dialect/base/groupby-compiler.ts +21 -21
  55. package/src/core/dialect/base/join-compiler.ts +25 -25
  56. package/src/core/dialect/base/orderby-compiler.ts +35 -35
  57. package/src/core/dialect/base/pagination-strategy.ts +32 -32
  58. package/src/core/dialect/base/returning-strategy.ts +57 -57
  59. package/src/core/dialect/base/sql-dialect.ts +294 -294
  60. package/src/core/dialect/dialect-factory.ts +91 -91
  61. package/src/core/dialect/mssql/functions.ts +120 -120
  62. package/src/core/dialect/mssql/index.ts +317 -317
  63. package/src/core/dialect/mysql/functions.ts +103 -103
  64. package/src/core/dialect/mysql/index.ts +105 -105
  65. package/src/core/dialect/postgres/functions.ts +108 -108
  66. package/src/core/dialect/postgres/index.ts +91 -91
  67. package/src/core/dialect/sqlite/functions.ts +129 -129
  68. package/src/core/dialect/sqlite/index.ts +67 -67
  69. package/src/core/driver/database-driver.ts +19 -19
  70. package/src/core/driver/mssql-driver.ts +23 -23
  71. package/src/core/driver/mysql-driver.ts +23 -23
  72. package/src/core/driver/postgres-driver.ts +23 -23
  73. package/src/core/driver/sqlite-driver.ts +23 -23
  74. package/src/core/execution/db-executor.ts +92 -92
  75. package/src/core/execution/executors/better-sqlite3-executor.ts +94 -94
  76. package/src/core/execution/executors/mssql-executor.ts +184 -184
  77. package/src/core/execution/executors/mysql-executor.ts +88 -88
  78. package/src/core/execution/executors/postgres-executor.ts +26 -26
  79. package/src/core/execution/executors/sqlite-executor.ts +42 -42
  80. package/src/core/execution/pooling/pool-types.ts +30 -30
  81. package/src/core/execution/pooling/pool.ts +275 -275
  82. package/src/core/functions/array.ts +35 -35
  83. package/src/core/functions/control-flow.ts +79 -79
  84. package/src/core/functions/datetime.ts +237 -237
  85. package/src/core/functions/json.ts +70 -70
  86. package/src/core/functions/numeric.ts +297 -297
  87. package/src/core/functions/text.ts +334 -334
  88. package/src/core/functions/types.ts +33 -33
  89. package/src/core/hydration/types.ts +51 -51
  90. package/src/core/sql/sql-operator-config.ts +39 -39
  91. package/src/core/sql/sql.ts +152 -152
  92. package/src/decorators/column-decorator.ts +87 -87
  93. package/src/decorators/decorator-metadata.ts +143 -143
  94. package/src/decorators/entity.ts +93 -93
  95. package/src/decorators/index.ts +39 -39
  96. package/src/decorators/relations.ts +231 -231
  97. package/src/decorators/transformers/built-in/string-transformers.ts +231 -231
  98. package/src/decorators/transformers/transformer-decorators.ts +134 -134
  99. package/src/decorators/transformers/transformer-executor.ts +171 -171
  100. package/src/decorators/transformers/transformer-metadata.ts +73 -73
  101. package/src/decorators/validators/built-in/br-cep-validator.ts +55 -55
  102. package/src/decorators/validators/built-in/br-cnpj-validator.ts +105 -105
  103. package/src/decorators/validators/built-in/br-cpf-validator.ts +103 -103
  104. package/src/decorators/validators/country-validator-registry.ts +64 -64
  105. package/src/decorators/validators/country-validators-decorators.ts +203 -203
  106. package/src/decorators/validators/country-validators.ts +105 -105
  107. package/src/decorators/validators/validator-metadata.ts +59 -59
  108. package/src/dto/dto-types.ts +226 -226
  109. package/src/dto/filter-types.ts +141 -141
  110. package/src/dto/index.ts +95 -95
  111. package/src/dto/openapi/generators/base.ts +29 -29
  112. package/src/dto/openapi/generators/column.ts +37 -37
  113. package/src/dto/openapi/generators/dto.ts +91 -91
  114. package/src/dto/openapi/generators/filter.ts +75 -75
  115. package/src/dto/openapi/generators/nested-dto.ts +618 -618
  116. package/src/dto/openapi/generators/pagination.ts +111 -111
  117. package/src/dto/openapi/generators/relation-filter.ts +228 -228
  118. package/src/dto/openapi/index.ts +12 -12
  119. package/src/dto/openapi/types.ts +101 -101
  120. package/src/dto/openapi/utilities.ts +95 -95
  121. package/src/dto/pagination-utils.ts +150 -150
  122. package/src/dto/transform.ts +197 -197
  123. package/src/index.ts +86 -86
  124. package/src/orm/als.ts +58 -58
  125. package/src/orm/domain-event-bus.ts +119 -119
  126. package/src/orm/entity-context.ts +86 -86
  127. package/src/orm/entity-materializer.ts +159 -159
  128. package/src/orm/entity-meta.ts +97 -97
  129. package/src/orm/entity-registry.ts +39 -39
  130. package/src/orm/entity-relation-cache.ts +39 -39
  131. package/src/orm/execute.ts +194 -194
  132. package/src/orm/execution-context.ts +18 -18
  133. package/src/orm/hydration-context.ts +26 -26
  134. package/src/orm/hydration.ts +112 -112
  135. package/src/orm/identity-map.ts +61 -61
  136. package/src/orm/interceptor-pipeline.ts +16 -16
  137. package/src/orm/lazy-batch/belongs-to-many.ts +119 -119
  138. package/src/orm/lazy-batch/belongs-to.ts +108 -108
  139. package/src/orm/lazy-batch/has-many.ts +69 -69
  140. package/src/orm/lazy-batch/has-one.ts +68 -68
  141. package/src/orm/lazy-batch/shared.ts +125 -125
  142. package/src/orm/orm-session.ts +620 -620
  143. package/src/orm/orm.ts +34 -34
  144. package/src/orm/pooled-executor-factory.ts +121 -121
  145. package/src/orm/query-logger.ts +40 -40
  146. package/src/orm/relation-change-processor.ts +420 -420
  147. package/src/orm/relations/belongs-to.ts +143 -143
  148. package/src/orm/relations/has-many.ts +204 -204
  149. package/src/orm/relations/has-one.ts +174 -174
  150. package/src/orm/relations/many-to-many.ts +288 -288
  151. package/src/orm/relations/morph-many.ts +156 -156
  152. package/src/orm/relations/morph-one.ts +151 -151
  153. package/src/orm/relations/morph-to.ts +162 -162
  154. package/src/orm/runtime-types.ts +92 -92
  155. package/src/orm/save-graph.ts +561 -561
  156. package/src/orm/transaction-runner.ts +24 -24
  157. package/src/orm/unit-of-work.ts +426 -426
  158. package/src/query/index.ts +69 -69
  159. package/src/query/target.ts +46 -46
  160. package/src/query-builder/column-selector.ts +81 -81
  161. package/src/query-builder/delete.ts +141 -141
  162. package/src/query-builder/insert-query-state.ts +149 -149
  163. package/src/query-builder/insert.ts +117 -117
  164. package/src/query-builder/query-ast-service.ts +287 -287
  165. package/src/query-builder/query-resolution.ts +78 -78
  166. package/src/query-builder/raw-column-parser.ts +38 -38
  167. package/src/query-builder/relation-filter-utils.ts +153 -153
  168. package/src/query-builder/relation-join-planner.ts +10 -10
  169. package/src/query-builder/relation-manager.ts +87 -87
  170. package/src/query-builder/relation-projection-helper.ts +102 -102
  171. package/src/query-builder/relation-types.ts +9 -9
  172. package/src/query-builder/relation-utils.ts +15 -15
  173. package/src/query-builder/select/cte-facet.ts +40 -40
  174. package/src/query-builder/select/from-facet.ts +80 -80
  175. package/src/query-builder/select/join-facet.ts +62 -62
  176. package/src/query-builder/select/predicate-facet.ts +104 -104
  177. package/src/query-builder/select/projection-facet.ts +70 -70
  178. package/src/query-builder/select/relation-facet.ts +81 -81
  179. package/src/query-builder/select/setop-facet.ts +36 -36
  180. package/src/query-builder/select-helpers.ts +1 -1
  181. package/src/query-builder/select-query-builder-deps.ts +130 -130
  182. package/src/query-builder/select-query-state.ts +207 -207
  183. package/src/query-builder/update.ts +151 -151
  184. package/src/schema/column-types.ts +322 -322
  185. package/src/schema/table-guards.ts +37 -37
  186. package/src/schema/table.ts +281 -281
  187. package/src/tree/index.ts +13 -13
  188. package/src/tree/nested-set-strategy.ts +545 -545
  189. package/src/tree/tree-decorator.ts +397 -397
  190. package/src/tree/tree-manager.ts +754 -754
  191. package/src/tree/tree-query.ts +427 -427
  192. package/src/tree/tree-types.ts +299 -299
@@ -1,288 +1,288 @@
1
- import { ManyToManyCollection } from '../../schema/types.js';
2
- import { EntityContext } from '../entity-context.js';
3
- import { RelationKey } from '../runtime-types.js';
4
- import { BelongsToManyRelation } from '../../schema/relation.js';
5
- import { TableDef } from '../../schema/table.js';
6
- import { findPrimaryKey } from '../../query-builder/hydration-planner.js';
7
- import { EntityMeta, getHydrationRows } from '../entity-meta.js';
8
-
9
- type Rows = Record<string, unknown>[];
10
-
11
- const toKey = (value: unknown): string => (value === null || value === undefined ? '' : String(value));
12
-
13
- const hideInternal = (obj: object, keys: string[]): void => {
14
- for (const key of keys) {
15
- Object.defineProperty(obj, key, {
16
- value: obj[key],
17
- writable: false,
18
- configurable: false,
19
- enumerable: false
20
- });
21
- }
22
- };
23
-
24
- const hideWritable = (obj: object, keys: string[]): void => {
25
- for (const key of keys) {
26
- const value = obj[key as keyof typeof obj];
27
- Object.defineProperty(obj, key, {
28
- value,
29
- writable: true,
30
- configurable: true,
31
- enumerable: false
32
- });
33
- }
34
- };
35
-
36
- const normalizePivot = (pivot: unknown): Record<string, unknown> | undefined => {
37
- if (!pivot || typeof pivot !== 'object' || Array.isArray(pivot)) return undefined;
38
- const entries = Object.entries(pivot as Record<string, unknown>)
39
- .filter(([, value]) => value !== undefined);
40
- if (!entries.length) return undefined;
41
- return Object.fromEntries(entries);
42
- };
43
-
44
- const applyPivot = (entity: Record<string, unknown>, pivot?: Record<string, unknown>): void => {
45
- if (!pivot) return;
46
- const current = entity._pivot;
47
- if (current && typeof current === 'object' && !Array.isArray(current)) {
48
- entity._pivot = { ...(current as Record<string, unknown>), ...pivot };
49
- return;
50
- }
51
- entity._pivot = { ...pivot };
52
- };
53
-
54
- /**
55
- * Default implementation of a many-to-many collection.
56
- * Manages the relationship between two entities through a pivot table.
57
- * Supports lazy loading, attaching/detaching entities, and syncing by IDs.
58
- *
59
- * @template TTarget The type of the target entities in the collection.
60
- */
61
- export class DefaultManyToManyCollection<TTarget, TPivot extends object | undefined = undefined>
62
- implements ManyToManyCollection<TTarget, TPivot> {
63
- private loaded = false;
64
- private items: TTarget[] = [];
65
-
66
- /**
67
- * @param ctx The entity context for tracking changes.
68
- * @param meta Metadata for the root entity.
69
- * @param root The root entity instance.
70
- * @param relationName The name of the relation.
71
- * @param relation Relation definition.
72
- * @param rootTable Table definition of the root entity.
73
- * @param loader Function to load the collection items.
74
- * @param createEntity Function to create entity instances from rows.
75
- * @param localKey The local key used for joining.
76
- */
77
- constructor(
78
- private readonly ctx: EntityContext,
79
- private readonly meta: EntityMeta<TableDef>,
80
- private readonly root: unknown,
81
- private readonly relationName: string,
82
- private readonly relation: BelongsToManyRelation,
83
- private readonly rootTable: TableDef,
84
- private readonly loader: () => Promise<Map<string, Rows>>,
85
- private readonly createEntity: (row: Record<string, unknown>) => TTarget,
86
- private readonly localKey: string
87
- ) {
88
- hideInternal(this, ['ctx', 'meta', 'root', 'relationName', 'relation', 'rootTable', 'loader', 'createEntity', 'localKey']);
89
- hideWritable(this, ['loaded', 'items']);
90
- this.hydrateFromCache();
91
- }
92
-
93
- /**
94
- * Loads the collection items if not already loaded.
95
- * @returns A promise that resolves to the array of target entities.
96
- */
97
- async load(): Promise<TTarget[]> {
98
- if (this.loaded) return this.items;
99
- const map = await this.loader();
100
- const key = toKey(this.root[this.localKey]);
101
- const rows = map.get(key) ?? [];
102
- this.items = rows.map(row => {
103
- const entity = this.createEntity(row);
104
- if ((row as { _pivot?: unknown })._pivot) {
105
- (entity as { _pivot?: unknown })._pivot = (row as { _pivot?: unknown })._pivot;
106
- }
107
- return entity;
108
- });
109
- this.loaded = true;
110
- return this.items;
111
- }
112
-
113
- /**
114
- * Returns the currently loaded items.
115
- * @returns Array of target entities.
116
- */
117
- getItems(): TTarget[] {
118
- return this.items;
119
- }
120
-
121
- /**
122
- * Array-compatible length for testing frameworks.
123
- */
124
- get length(): number {
125
- return this.items.length;
126
- }
127
-
128
- /**
129
- * Enables iteration over the collection like an array.
130
- */
131
- [Symbol.iterator](): Iterator<TTarget> {
132
- return this.items[Symbol.iterator]();
133
- }
134
-
135
- /**
136
- * Attaches an entity to the collection.
137
- * Registers an 'attach' change in the entity context.
138
- * @param target Entity instance or its primary key value.
139
- */
140
- attach(target: TTarget | number | string, pivot?: Partial<TPivot> | Record<string, unknown>): void {
141
- const entity = this.ensureEntity(target);
142
- const id = this.extractId(entity);
143
- const pivotPayload = this.filterPivotPayload(normalizePivot(pivot));
144
- const existing = id != null
145
- ? this.items.find(item => this.extractId(item) === id)
146
- : this.items.find(item => item === entity);
147
-
148
- if (existing) {
149
- if (pivotPayload) {
150
- applyPivot(existing as Record<string, unknown>, pivotPayload);
151
- this.ctx.registerRelationChange(
152
- this.root,
153
- this.relationKey,
154
- this.rootTable,
155
- this.relationName,
156
- this.relation,
157
- { kind: 'update', entity: existing, pivot: pivotPayload }
158
- );
159
- }
160
- return;
161
- }
162
-
163
- if (pivotPayload) {
164
- applyPivot(entity as Record<string, unknown>, pivotPayload);
165
- }
166
- this.items.push(entity);
167
- this.ctx.registerRelationChange(
168
- this.root,
169
- this.relationKey,
170
- this.rootTable,
171
- this.relationName,
172
- this.relation,
173
- { kind: 'attach', entity, pivot: pivotPayload }
174
- );
175
- }
176
-
177
- /**
178
- * Detaches an entity from the collection.
179
- * Registers a 'detach' change in the entity context.
180
- * @param target Entity instance or its primary key value.
181
- */
182
- detach(target: TTarget | number | string): void {
183
- const id = typeof target === 'number' || typeof target === 'string'
184
- ? target
185
- : this.extractId(target);
186
-
187
- if (id == null) return;
188
-
189
- const existing = this.items.find(item => this.extractId(item) === id);
190
- if (!existing) return;
191
-
192
- this.items = this.items.filter(item => this.extractId(item) !== id);
193
- this.ctx.registerRelationChange(
194
- this.root,
195
- this.relationKey,
196
- this.rootTable,
197
- this.relationName,
198
- this.relation,
199
- { kind: 'detach', entity: existing }
200
- );
201
- }
202
-
203
- /**
204
- * Syncs the collection with a list of IDs.
205
- * Attaches missing IDs and detaches IDs not in the list.
206
- * @param ids Array of primary key values to sync with.
207
- */
208
- async syncByIds(ids: (number | string)[]): Promise<void> {
209
- await this.load();
210
- const normalized = new Set(ids.map(id => toKey(id)));
211
- const currentIds = new Set(this.items.map(item => toKey(this.extractId(item))));
212
-
213
- for (const id of normalized) {
214
- if (!currentIds.has(id)) {
215
- this.attach(id);
216
- }
217
- }
218
-
219
- for (const item of [...this.items]) {
220
- const itemId = toKey(this.extractId(item));
221
- if (!normalized.has(itemId)) {
222
- this.detach(item);
223
- }
224
- }
225
- }
226
-
227
- private ensureEntity(target: TTarget | number | string): TTarget {
228
- if (typeof target === 'number' || typeof target === 'string') {
229
- const stub: Record<string, unknown> = {
230
- [this.targetKey]: target
231
- };
232
- return this.createEntity(stub);
233
- }
234
- return target;
235
- }
236
-
237
- private extractId(entity: TTarget | number | string | null | undefined): number | string | null {
238
- if (entity === null || entity === undefined) return null;
239
- if (typeof entity === 'number' || typeof entity === 'string') {
240
- return entity;
241
- }
242
- return (entity as Record<string, unknown>)[this.targetKey] as string | number | null ?? null;
243
- }
244
-
245
- private get relationKey(): RelationKey {
246
- return `${this.rootTable.name}.${this.relationName}`;
247
- }
248
-
249
- private get targetKey(): string {
250
- return this.relation.targetKey || findPrimaryKey(this.relation.target);
251
- }
252
-
253
- private filterPivotPayload(pivot?: Record<string, unknown>): Record<string, unknown> | undefined {
254
- if (!pivot) return undefined;
255
- const payload: Record<string, unknown> = {};
256
- for (const [key, value] of Object.entries(pivot)) {
257
- if (value === undefined) continue;
258
- if (!this.relation.pivotTable.columns[key]) continue;
259
- if (key === this.relation.pivotForeignKeyToRoot || key === this.relation.pivotForeignKeyToTarget) continue;
260
- payload[key] = value;
261
- }
262
- return Object.keys(payload).length ? payload : undefined;
263
- }
264
-
265
- private hydrateFromCache(): void {
266
- const keyValue = (this.root as Record<string, unknown>)[this.localKey];
267
- if (keyValue === undefined || keyValue === null) return;
268
- const rows = getHydrationRows(this.meta, this.relationName, keyValue);
269
- if (!rows?.length) return;
270
- this.items = rows.map(row => {
271
- const entity = this.createEntity(row);
272
- if ((row as { _pivot?: unknown })._pivot) {
273
- (entity as { _pivot?: unknown })._pivot = (row as { _pivot?: unknown })._pivot;
274
- }
275
- return entity;
276
- });
277
- this.loaded = true;
278
- }
279
-
280
- toJSON(): unknown[] {
281
- return this.items.map(item => {
282
- const entityWithToJSON = item as { toJSON?: () => unknown };
283
- return typeof entityWithToJSON.toJSON === 'function'
284
- ? entityWithToJSON.toJSON()
285
- : item;
286
- });
287
- }
288
- }
1
+ import { ManyToManyCollection } from '../../schema/types.js';
2
+ import { EntityContext } from '../entity-context.js';
3
+ import { RelationKey } from '../runtime-types.js';
4
+ import { BelongsToManyRelation } from '../../schema/relation.js';
5
+ import { TableDef } from '../../schema/table.js';
6
+ import { findPrimaryKey } from '../../query-builder/hydration-planner.js';
7
+ import { EntityMeta, getHydrationRows } from '../entity-meta.js';
8
+
9
+ type Rows = Record<string, unknown>[];
10
+
11
+ const toKey = (value: unknown): string => (value === null || value === undefined ? '' : String(value));
12
+
13
+ const hideInternal = (obj: object, keys: string[]): void => {
14
+ for (const key of keys) {
15
+ Object.defineProperty(obj, key, {
16
+ value: obj[key],
17
+ writable: false,
18
+ configurable: false,
19
+ enumerable: false
20
+ });
21
+ }
22
+ };
23
+
24
+ const hideWritable = (obj: object, keys: string[]): void => {
25
+ for (const key of keys) {
26
+ const value = obj[key as keyof typeof obj];
27
+ Object.defineProperty(obj, key, {
28
+ value,
29
+ writable: true,
30
+ configurable: true,
31
+ enumerable: false
32
+ });
33
+ }
34
+ };
35
+
36
+ const normalizePivot = (pivot: unknown): Record<string, unknown> | undefined => {
37
+ if (!pivot || typeof pivot !== 'object' || Array.isArray(pivot)) return undefined;
38
+ const entries = Object.entries(pivot as Record<string, unknown>)
39
+ .filter(([, value]) => value !== undefined);
40
+ if (!entries.length) return undefined;
41
+ return Object.fromEntries(entries);
42
+ };
43
+
44
+ const applyPivot = (entity: Record<string, unknown>, pivot?: Record<string, unknown>): void => {
45
+ if (!pivot) return;
46
+ const current = entity._pivot;
47
+ if (current && typeof current === 'object' && !Array.isArray(current)) {
48
+ entity._pivot = { ...(current as Record<string, unknown>), ...pivot };
49
+ return;
50
+ }
51
+ entity._pivot = { ...pivot };
52
+ };
53
+
54
+ /**
55
+ * Default implementation of a many-to-many collection.
56
+ * Manages the relationship between two entities through a pivot table.
57
+ * Supports lazy loading, attaching/detaching entities, and syncing by IDs.
58
+ *
59
+ * @template TTarget The type of the target entities in the collection.
60
+ */
61
+ export class DefaultManyToManyCollection<TTarget, TPivot extends object | undefined = undefined>
62
+ implements ManyToManyCollection<TTarget, TPivot> {
63
+ private loaded = false;
64
+ private items: TTarget[] = [];
65
+
66
+ /**
67
+ * @param ctx The entity context for tracking changes.
68
+ * @param meta Metadata for the root entity.
69
+ * @param root The root entity instance.
70
+ * @param relationName The name of the relation.
71
+ * @param relation Relation definition.
72
+ * @param rootTable Table definition of the root entity.
73
+ * @param loader Function to load the collection items.
74
+ * @param createEntity Function to create entity instances from rows.
75
+ * @param localKey The local key used for joining.
76
+ */
77
+ constructor(
78
+ private readonly ctx: EntityContext,
79
+ private readonly meta: EntityMeta<TableDef>,
80
+ private readonly root: unknown,
81
+ private readonly relationName: string,
82
+ private readonly relation: BelongsToManyRelation,
83
+ private readonly rootTable: TableDef,
84
+ private readonly loader: () => Promise<Map<string, Rows>>,
85
+ private readonly createEntity: (row: Record<string, unknown>) => TTarget,
86
+ private readonly localKey: string
87
+ ) {
88
+ hideInternal(this, ['ctx', 'meta', 'root', 'relationName', 'relation', 'rootTable', 'loader', 'createEntity', 'localKey']);
89
+ hideWritable(this, ['loaded', 'items']);
90
+ this.hydrateFromCache();
91
+ }
92
+
93
+ /**
94
+ * Loads the collection items if not already loaded.
95
+ * @returns A promise that resolves to the array of target entities.
96
+ */
97
+ async load(): Promise<TTarget[]> {
98
+ if (this.loaded) return this.items;
99
+ const map = await this.loader();
100
+ const key = toKey(this.root[this.localKey]);
101
+ const rows = map.get(key) ?? [];
102
+ this.items = rows.map(row => {
103
+ const entity = this.createEntity(row);
104
+ if ((row as { _pivot?: unknown })._pivot) {
105
+ (entity as { _pivot?: unknown })._pivot = (row as { _pivot?: unknown })._pivot;
106
+ }
107
+ return entity;
108
+ });
109
+ this.loaded = true;
110
+ return this.items;
111
+ }
112
+
113
+ /**
114
+ * Returns the currently loaded items.
115
+ * @returns Array of target entities.
116
+ */
117
+ getItems(): TTarget[] {
118
+ return this.items;
119
+ }
120
+
121
+ /**
122
+ * Array-compatible length for testing frameworks.
123
+ */
124
+ get length(): number {
125
+ return this.items.length;
126
+ }
127
+
128
+ /**
129
+ * Enables iteration over the collection like an array.
130
+ */
131
+ [Symbol.iterator](): Iterator<TTarget> {
132
+ return this.items[Symbol.iterator]();
133
+ }
134
+
135
+ /**
136
+ * Attaches an entity to the collection.
137
+ * Registers an 'attach' change in the entity context.
138
+ * @param target Entity instance or its primary key value.
139
+ */
140
+ attach(target: TTarget | number | string, pivot?: Partial<TPivot> | Record<string, unknown>): void {
141
+ const entity = this.ensureEntity(target);
142
+ const id = this.extractId(entity);
143
+ const pivotPayload = this.filterPivotPayload(normalizePivot(pivot));
144
+ const existing = id != null
145
+ ? this.items.find(item => this.extractId(item) === id)
146
+ : this.items.find(item => item === entity);
147
+
148
+ if (existing) {
149
+ if (pivotPayload) {
150
+ applyPivot(existing as Record<string, unknown>, pivotPayload);
151
+ this.ctx.registerRelationChange(
152
+ this.root,
153
+ this.relationKey,
154
+ this.rootTable,
155
+ this.relationName,
156
+ this.relation,
157
+ { kind: 'update', entity: existing, pivot: pivotPayload }
158
+ );
159
+ }
160
+ return;
161
+ }
162
+
163
+ if (pivotPayload) {
164
+ applyPivot(entity as Record<string, unknown>, pivotPayload);
165
+ }
166
+ this.items.push(entity);
167
+ this.ctx.registerRelationChange(
168
+ this.root,
169
+ this.relationKey,
170
+ this.rootTable,
171
+ this.relationName,
172
+ this.relation,
173
+ { kind: 'attach', entity, pivot: pivotPayload }
174
+ );
175
+ }
176
+
177
+ /**
178
+ * Detaches an entity from the collection.
179
+ * Registers a 'detach' change in the entity context.
180
+ * @param target Entity instance or its primary key value.
181
+ */
182
+ detach(target: TTarget | number | string): void {
183
+ const id = typeof target === 'number' || typeof target === 'string'
184
+ ? target
185
+ : this.extractId(target);
186
+
187
+ if (id == null) return;
188
+
189
+ const existing = this.items.find(item => this.extractId(item) === id);
190
+ if (!existing) return;
191
+
192
+ this.items = this.items.filter(item => this.extractId(item) !== id);
193
+ this.ctx.registerRelationChange(
194
+ this.root,
195
+ this.relationKey,
196
+ this.rootTable,
197
+ this.relationName,
198
+ this.relation,
199
+ { kind: 'detach', entity: existing }
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Syncs the collection with a list of IDs.
205
+ * Attaches missing IDs and detaches IDs not in the list.
206
+ * @param ids Array of primary key values to sync with.
207
+ */
208
+ async syncByIds(ids: (number | string)[]): Promise<void> {
209
+ await this.load();
210
+ const normalized = new Set(ids.map(id => toKey(id)));
211
+ const currentIds = new Set(this.items.map(item => toKey(this.extractId(item))));
212
+
213
+ for (const id of normalized) {
214
+ if (!currentIds.has(id)) {
215
+ this.attach(id);
216
+ }
217
+ }
218
+
219
+ for (const item of [...this.items]) {
220
+ const itemId = toKey(this.extractId(item));
221
+ if (!normalized.has(itemId)) {
222
+ this.detach(item);
223
+ }
224
+ }
225
+ }
226
+
227
+ private ensureEntity(target: TTarget | number | string): TTarget {
228
+ if (typeof target === 'number' || typeof target === 'string') {
229
+ const stub: Record<string, unknown> = {
230
+ [this.targetKey]: target
231
+ };
232
+ return this.createEntity(stub);
233
+ }
234
+ return target;
235
+ }
236
+
237
+ private extractId(entity: TTarget | number | string | null | undefined): number | string | null {
238
+ if (entity === null || entity === undefined) return null;
239
+ if (typeof entity === 'number' || typeof entity === 'string') {
240
+ return entity;
241
+ }
242
+ return (entity as Record<string, unknown>)[this.targetKey] as string | number | null ?? null;
243
+ }
244
+
245
+ private get relationKey(): RelationKey {
246
+ return `${this.rootTable.name}.${this.relationName}`;
247
+ }
248
+
249
+ private get targetKey(): string {
250
+ return this.relation.targetKey || findPrimaryKey(this.relation.target);
251
+ }
252
+
253
+ private filterPivotPayload(pivot?: Record<string, unknown>): Record<string, unknown> | undefined {
254
+ if (!pivot) return undefined;
255
+ const payload: Record<string, unknown> = {};
256
+ for (const [key, value] of Object.entries(pivot)) {
257
+ if (value === undefined) continue;
258
+ if (!this.relation.pivotTable.columns[key]) continue;
259
+ if (key === this.relation.pivotForeignKeyToRoot || key === this.relation.pivotForeignKeyToTarget) continue;
260
+ payload[key] = value;
261
+ }
262
+ return Object.keys(payload).length ? payload : undefined;
263
+ }
264
+
265
+ private hydrateFromCache(): void {
266
+ const keyValue = (this.root as Record<string, unknown>)[this.localKey];
267
+ if (keyValue === undefined || keyValue === null) return;
268
+ const rows = getHydrationRows(this.meta, this.relationName, keyValue);
269
+ if (!rows?.length) return;
270
+ this.items = rows.map(row => {
271
+ const entity = this.createEntity(row);
272
+ if ((row as { _pivot?: unknown })._pivot) {
273
+ (entity as { _pivot?: unknown })._pivot = (row as { _pivot?: unknown })._pivot;
274
+ }
275
+ return entity;
276
+ });
277
+ this.loaded = true;
278
+ }
279
+
280
+ toJSON(): unknown[] {
281
+ return this.items.map(item => {
282
+ const entityWithToJSON = item as { toJSON?: () => unknown };
283
+ return typeof entityWithToJSON.toJSON === 'function'
284
+ ? entityWithToJSON.toJSON()
285
+ : item;
286
+ });
287
+ }
288
+ }