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,561 +1,561 @@
1
- import type {
2
- EntityInstance,
3
- HasManyCollection,
4
- HasOneReference,
5
- BelongsToReference,
6
- ManyToManyCollection
7
- } from '../schema/types.js';
8
- import { normalizeColumnType, type ColumnDef } from '../schema/column-types.js';
9
- import {
10
- RelationKinds,
11
- type BelongsToManyRelation,
12
- type BelongsToRelation,
13
- type HasManyRelation,
14
- type HasOneRelation,
15
- type RelationDef,
16
- type MorphOneRelation,
17
- type MorphManyRelation,
18
- type MorphToRelation
19
- } from '../schema/relation.js';
20
- import type { TableDef } from '../schema/table.js';
21
- import { findPrimaryKey } from '../query-builder/hydration-planner.js';
22
- import { createEntityFromRow } from './entity.js';
23
- import type { EntityConstructor } from './entity-metadata.js';
24
- import { getTableDefFromEntity } from '../decorators/bootstrap.js';
25
- import type { OrmSession } from './orm-session.js';
26
- import type { PrimaryKey } from './entity-context.js';
27
-
28
- /**
29
- * Options for controlling the behavior of save graph operations.
30
- */
31
- export interface SaveGraphOptions {
32
- /** Remove existing collection members that are not present in the payload */
33
- pruneMissing?: boolean;
34
- /**
35
- * Coerce JSON-friendly input values into DB-friendly primitives.
36
- * Currently:
37
- * - `json`: Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
38
- * - `json-in`: string/number -> Date (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
39
- */
40
- coerce?: 'json' | 'json-in';
41
- }
42
-
43
- /** Represents an entity object with arbitrary properties. */
44
- type AnyEntity = Record<string, unknown>;
45
-
46
- /**
47
-
48
- * Converts a value to a string key, returning an empty string for null or undefined.
49
-
50
- * @param value - The value to convert.
51
-
52
- * @returns The string representation or empty string.
53
-
54
- */
55
-
56
- const toKey = (value: unknown): string => (value === null || value === undefined ? '' : String(value));
57
-
58
- const coerceColumnValue = (
59
- table: TableDef,
60
- columnName: string,
61
- value: unknown,
62
- options: SaveGraphOptions
63
- ): unknown => {
64
- if (value === null || value === undefined) return value;
65
-
66
- const column = table.columns[columnName] as unknown as ColumnDef | undefined;
67
- if (!column) return value;
68
-
69
- const normalized = normalizeColumnType(column.type);
70
-
71
- const isDateLikeColumn =
72
- normalized === 'date' ||
73
- normalized === 'datetime' ||
74
- normalized === 'timestamp' ||
75
- normalized === 'timestamptz';
76
-
77
- if (!isDateLikeColumn) return value;
78
-
79
- if (options.coerce === 'json') {
80
- if (value instanceof Date) {
81
- return value.toISOString();
82
- }
83
- return value;
84
- }
85
-
86
- if (options.coerce === 'json-in') {
87
- if (value instanceof Date) return value;
88
- if (typeof value === 'string' || typeof value === 'number') {
89
- const date = new Date(value);
90
- if (Number.isNaN(date.getTime())) {
91
- throw new Error(`Invalid date value for column "${columnName}"`);
92
- }
93
- return date;
94
- }
95
- return value;
96
- }
97
-
98
- // Future coercions can be added here based on `normalized`.
99
- return value;
100
- };
101
-
102
- const pickColumns = (table: TableDef, payload: AnyEntity, options: SaveGraphOptions): Record<string, unknown> => {
103
- const columns: Record<string, unknown> = {};
104
- for (const key of Object.keys(table.columns)) {
105
- if (payload[key] !== undefined) {
106
- columns[key] = coerceColumnValue(table, key, payload[key], options);
107
- }
108
- }
109
- return columns;
110
- };
111
-
112
- const ensureEntity = <TTable extends TableDef>(
113
- session: OrmSession,
114
- table: TTable,
115
- payload: AnyEntity,
116
- options: SaveGraphOptions
117
- ): EntityInstance<TTable> => {
118
- const pk = findPrimaryKey(table);
119
- const row = pickColumns(table, payload, options);
120
- const pkValue = payload[pk];
121
-
122
- if (pkValue !== undefined && pkValue !== null) {
123
- const tracked = session.getEntity(table, pkValue as PrimaryKey);
124
- if (tracked) {
125
- return tracked as EntityInstance<TTable>;
126
- }
127
- // Seed the stub with PK to track a managed entity when updating.
128
- if (row[pk] === undefined) {
129
- row[pk] = pkValue;
130
- }
131
- }
132
-
133
- return createEntityFromRow(session, table, row) as EntityInstance<TTable>;
134
- };
135
-
136
- const assignColumns = (table: TableDef, entity: AnyEntity, payload: AnyEntity, options: SaveGraphOptions): void => {
137
- for (const key of Object.keys(table.columns)) {
138
- if (payload[key] !== undefined) {
139
- entity[key] = coerceColumnValue(table, key, payload[key], options);
140
- }
141
- }
142
- };
143
-
144
- const isEntityInCollection = (items: AnyEntity[], pkName: string, entity: AnyEntity): boolean => {
145
- if (items.includes(entity)) return true;
146
- const entityPk = entity[pkName];
147
- if (entityPk === undefined || entityPk === null) return false;
148
- return items.some(item => toKey(item[pkName]) === toKey(entityPk));
149
- };
150
-
151
- const findInCollectionByPk = (items: AnyEntity[], pkName: string, pkValue: unknown): AnyEntity | undefined => {
152
- if (pkValue === undefined || pkValue === null) return undefined;
153
- return items.find(item => toKey(item[pkName]) === toKey(pkValue));
154
- };
155
-
156
- const extractPivotPayload = (payload: AnyEntity): Record<string, unknown> | undefined => {
157
- const pivot = payload._pivot ?? payload.pivot;
158
- if (!pivot || typeof pivot !== 'object' || Array.isArray(pivot)) return undefined;
159
- const entries = Object.entries(pivot as Record<string, unknown>)
160
- .filter(([, value]) => value !== undefined);
161
- if (!entries.length) return undefined;
162
- return Object.fromEntries(entries);
163
- };
164
-
165
- const handleHasMany = async (
166
- session: OrmSession,
167
- root: AnyEntity,
168
- relationName: string,
169
- relation: HasManyRelation,
170
- payload: unknown,
171
- options: SaveGraphOptions
172
- ): Promise<void> => {
173
- if (!Array.isArray(payload)) return;
174
- const collection = root[relationName] as unknown as HasManyCollection<unknown>;
175
- await collection.load();
176
-
177
- const targetTable = relation.target;
178
- const targetPk = findPrimaryKey(targetTable);
179
- const existing = collection.getItems() as unknown as AnyEntity[];
180
- const seen = new Set<string>();
181
-
182
- for (const item of payload) {
183
- if (item === null || item === undefined) continue;
184
- const asObj = typeof item === 'object' ? (item as AnyEntity) : { [targetPk]: item };
185
- const pkValue = asObj[targetPk];
186
-
187
- const current =
188
- findInCollectionByPk(existing, targetPk, pkValue) ??
189
- (pkValue !== undefined && pkValue !== null ? session.getEntity(targetTable, pkValue as PrimaryKey) : undefined);
190
-
191
- const entity = current ?? ensureEntity(session, targetTable, asObj, options);
192
- assignColumns(targetTable, entity as AnyEntity, asObj, options);
193
- await applyGraphToEntity(session, targetTable, entity as AnyEntity, asObj, options);
194
-
195
- if (!isEntityInCollection(collection.getItems() as unknown as AnyEntity[], targetPk, entity as unknown as AnyEntity)) {
196
- collection.attach(entity);
197
- }
198
-
199
- if (pkValue !== undefined && pkValue !== null) {
200
- seen.add(toKey(pkValue));
201
- }
202
- }
203
-
204
- if (options.pruneMissing) {
205
- for (const item of [...collection.getItems()]) {
206
- const pkValue = item[targetPk];
207
- if (pkValue !== undefined && pkValue !== null && !seen.has(toKey(pkValue))) {
208
- collection.remove(item);
209
- }
210
- }
211
- }
212
- };
213
-
214
- const handleHasOne = async (
215
- session: OrmSession,
216
- root: AnyEntity,
217
- relationName: string,
218
- relation: HasOneRelation,
219
- payload: unknown,
220
- options: SaveGraphOptions
221
- ): Promise<void> => {
222
- const ref = root[relationName] as unknown as HasOneReference<object>;
223
- if (payload === undefined) return;
224
- if (payload === null) {
225
- ref.set(null);
226
- return;
227
- }
228
- const pk = findPrimaryKey(relation.target);
229
- if (typeof payload === 'number' || typeof payload === 'string') {
230
- const entity = ref.set({ [pk]: payload });
231
- if (entity) {
232
- await applyGraphToEntity(session, relation.target, entity as AnyEntity, { [pk]: payload as PrimaryKey }, options);
233
- }
234
- return;
235
- }
236
- const attached = ref.set(payload as AnyEntity);
237
- if (attached) {
238
- await applyGraphToEntity(session, relation.target, attached as AnyEntity, payload as AnyEntity, options);
239
- }
240
- };
241
-
242
- const handleBelongsTo = async (
243
- session: OrmSession,
244
- root: AnyEntity,
245
- relationName: string,
246
- relation: BelongsToRelation,
247
- payload: unknown,
248
- options: SaveGraphOptions
249
- ): Promise<void> => {
250
- const ref = root[relationName] as unknown as BelongsToReference<object>;
251
- if (payload === undefined) return;
252
- if (payload === null) {
253
- ref.set(null);
254
- return;
255
- }
256
- const pk = relation.localKey || findPrimaryKey(relation.target);
257
- if (typeof payload === 'number' || typeof payload === 'string') {
258
- const entity = ref.set({ [pk]: payload });
259
- if (entity) {
260
- await applyGraphToEntity(session, relation.target, entity as AnyEntity, { [pk]: payload as PrimaryKey }, options);
261
- }
262
- return;
263
- }
264
- const attached = ref.set(payload as AnyEntity);
265
- if (attached) {
266
- await applyGraphToEntity(session, relation.target, attached as AnyEntity, payload as AnyEntity, options);
267
- }
268
- };
269
-
270
- const handleBelongsToMany = async (
271
- session: OrmSession,
272
- root: AnyEntity,
273
- relationName: string,
274
- relation: BelongsToManyRelation,
275
- payload: unknown,
276
- options: SaveGraphOptions
277
- ): Promise<void> => {
278
- if (!Array.isArray(payload)) return;
279
- const collection = root[relationName] as unknown as ManyToManyCollection<unknown>;
280
- await collection.load();
281
-
282
- const targetTable = relation.target;
283
- const targetPk = relation.targetKey || findPrimaryKey(targetTable);
284
- const seen = new Set<string>();
285
-
286
- for (const item of payload) {
287
- if (item === null || item === undefined) continue;
288
- if (typeof item === 'number' || typeof item === 'string') {
289
- const id = item;
290
- collection.attach(id);
291
- seen.add(toKey(id));
292
- continue;
293
- }
294
-
295
- const asObj = item as AnyEntity;
296
- const pivotPayload = extractPivotPayload(asObj);
297
- const pkValue = asObj[targetPk];
298
- const entity = pkValue !== undefined && pkValue !== null
299
- ? session.getEntity(targetTable, pkValue as PrimaryKey) ?? ensureEntity(session, targetTable, asObj, options)
300
- : ensureEntity(session, targetTable, asObj, options);
301
-
302
- assignColumns(targetTable, entity as AnyEntity, asObj, options);
303
- await applyGraphToEntity(session, targetTable, entity as AnyEntity, asObj, options);
304
-
305
- const existsInCollection = isEntityInCollection(
306
- collection.getItems() as unknown as AnyEntity[],
307
- targetPk,
308
- entity as unknown as AnyEntity
309
- );
310
- if (!existsInCollection || pivotPayload) {
311
- collection.attach(entity, pivotPayload);
312
- }
313
-
314
- if (pkValue !== undefined && pkValue !== null) {
315
- seen.add(toKey(pkValue));
316
- }
317
- }
318
-
319
- if (options.pruneMissing) {
320
- for (const item of [...collection.getItems()] as unknown as AnyEntity[]) {
321
- const pkValue = item[targetPk];
322
- if (pkValue !== undefined && pkValue !== null && !seen.has(toKey(pkValue))) {
323
- collection.detach(item);
324
- }
325
- }
326
- }
327
- };
328
-
329
- const handleMorphOne = async (
330
- session: OrmSession,
331
- root: AnyEntity,
332
- relationName: string,
333
- relation: MorphOneRelation,
334
- payload: unknown,
335
- options: SaveGraphOptions
336
- ): Promise<void> => {
337
- const ref = root[relationName] as unknown as HasOneReference<object>;
338
- if (payload === undefined) return;
339
- if (payload === null) {
340
- ref.set(null);
341
- return;
342
- }
343
- const pk = findPrimaryKey(relation.target);
344
- if (typeof payload === 'number' || typeof payload === 'string') {
345
- const entity = ref.set({ [pk]: payload });
346
- if (entity) {
347
- await applyGraphToEntity(session, relation.target, entity as AnyEntity, { [pk]: payload as PrimaryKey }, options);
348
- }
349
- return;
350
- }
351
- const attached = ref.set(payload as AnyEntity);
352
- if (attached) {
353
- await applyGraphToEntity(session, relation.target, attached as AnyEntity, payload as AnyEntity, options);
354
- }
355
- };
356
-
357
- const handleMorphMany = async (
358
- session: OrmSession,
359
- root: AnyEntity,
360
- relationName: string,
361
- relation: MorphManyRelation,
362
- payload: unknown,
363
- options: SaveGraphOptions
364
- ): Promise<void> => {
365
- if (!Array.isArray(payload)) return;
366
- const collection = root[relationName] as unknown as HasManyCollection<unknown>;
367
- await collection.load();
368
-
369
- const targetTable = relation.target;
370
- const targetPk = findPrimaryKey(targetTable);
371
- const existing = collection.getItems() as unknown as AnyEntity[];
372
- const seen = new Set<string>();
373
-
374
- for (const item of payload) {
375
- if (item === null || item === undefined) continue;
376
- const asObj = typeof item === 'object' ? (item as AnyEntity) : { [targetPk]: item };
377
- const pkValue = asObj[targetPk];
378
-
379
- const current =
380
- findInCollectionByPk(existing, targetPk, pkValue) ??
381
- (pkValue !== undefined && pkValue !== null ? session.getEntity(targetTable, pkValue as PrimaryKey) : undefined);
382
-
383
- const entity = current ?? ensureEntity(session, targetTable, asObj, options);
384
- assignColumns(targetTable, entity as AnyEntity, asObj, options);
385
- await applyGraphToEntity(session, targetTable, entity as AnyEntity, asObj, options);
386
-
387
- if (!isEntityInCollection(collection.getItems() as unknown as AnyEntity[], targetPk, entity as unknown as AnyEntity)) {
388
- collection.attach(entity);
389
- }
390
-
391
- if (pkValue !== undefined && pkValue !== null) {
392
- seen.add(toKey(pkValue));
393
- }
394
- }
395
-
396
- if (options.pruneMissing) {
397
- for (const item of [...collection.getItems()]) {
398
- const pkValue = item[targetPk];
399
- if (pkValue !== undefined && pkValue !== null && !seen.has(toKey(pkValue))) {
400
- collection.remove(item);
401
- }
402
- }
403
- }
404
- };
405
-
406
- const handleMorphTo = async (
407
- session: OrmSession,
408
- root: AnyEntity,
409
- relationName: string,
410
- relation: MorphToRelation,
411
- payload: unknown,
412
- options: SaveGraphOptions
413
- ): Promise<void> => {
414
- const ref = root[relationName] as unknown as BelongsToReference<object>;
415
- if (payload === undefined) return;
416
- if (payload === null) {
417
- ref.set(null);
418
- return;
419
- }
420
- // MorphTo set — the wrapper handles setting typeField/idField on the root
421
- const attached = ref.set(payload as AnyEntity);
422
- if (attached) {
423
- // Try to find the right target table
424
- for (const [, targetTable] of Object.entries(relation.targets)) {
425
- const pk = relation.targetKey || findPrimaryKey(targetTable);
426
- const pkValue = (attached as AnyEntity)[pk];
427
- if (pkValue !== undefined && pkValue !== null) {
428
- await applyGraphToEntity(session, targetTable, attached as AnyEntity, payload as AnyEntity, options);
429
- break;
430
- }
431
- }
432
- }
433
- };
434
-
435
- const applyRelation = async (
436
- session: OrmSession,
437
- table: TableDef,
438
- entity: AnyEntity,
439
- relationName: string,
440
- relation: RelationDef,
441
- payload: unknown,
442
- options: SaveGraphOptions
443
- ): Promise<void> => {
444
- switch (relation.type) {
445
- case RelationKinds.HasMany:
446
- return handleHasMany(session, entity, relationName, relation, payload, options);
447
- case RelationKinds.HasOne:
448
- return handleHasOne(session, entity, relationName, relation, payload, options);
449
- case RelationKinds.BelongsTo:
450
- return handleBelongsTo(session, entity, relationName, relation, payload, options);
451
- case RelationKinds.BelongsToMany:
452
- return handleBelongsToMany(session, entity, relationName, relation, payload, options);
453
- case RelationKinds.MorphOne:
454
- return handleMorphOne(session, entity, relationName, relation as MorphOneRelation, payload, options);
455
- case RelationKinds.MorphMany:
456
- return handleMorphMany(session, entity, relationName, relation as MorphManyRelation, payload, options);
457
- case RelationKinds.MorphTo:
458
- return handleMorphTo(session, entity, relationName, relation as MorphToRelation, payload, options);
459
- }
460
- };
461
-
462
- const applyGraphToEntity = async (
463
- session: OrmSession,
464
- table: TableDef,
465
- entity: AnyEntity,
466
- payload: AnyEntity,
467
- options: SaveGraphOptions
468
- ): Promise<void> => {
469
- assignColumns(table, entity, payload, options);
470
-
471
- for (const [relationName, relation] of Object.entries(table.relations)) {
472
- if (!(relationName in payload)) continue;
473
- await applyRelation(session, table, entity, relationName, relation as RelationDef, payload[relationName], options);
474
- }
475
- };
476
-
477
- export const saveGraph = async <TTable extends TableDef>(
478
- session: OrmSession,
479
- entityClass: EntityConstructor,
480
- payload: AnyEntity,
481
- options: SaveGraphOptions = {}
482
- ): Promise<EntityInstance<TTable>> => {
483
- const table = getTableDefFromEntity(entityClass);
484
- if (!table) {
485
- throw new Error('Entity metadata has not been bootstrapped');
486
- }
487
-
488
- const root = ensureEntity<TTable>(session, table as TTable, payload, options);
489
- await applyGraphToEntity(session, table, root as AnyEntity, payload, options);
490
- return root;
491
- };
492
-
493
- /**
494
-
495
- * Internal version of saveGraph with typed return based on the constructor.
496
-
497
- * @param session - The ORM session.
498
-
499
- * @param entityClass - The entity constructor.
500
-
501
- * @param payload - The payload data for the root entity and its relations.
502
-
503
- * @param options - Options for the save operation.
504
-
505
- * @returns The root entity instance.
506
-
507
- */
508
-
509
- export const saveGraphInternal = async <TCtor extends EntityConstructor>(
510
-
511
- session: OrmSession,
512
-
513
- entityClass: TCtor,
514
-
515
- payload: AnyEntity,
516
-
517
- options: SaveGraphOptions = {}
518
-
519
- ): Promise<InstanceType<TCtor>> => {
520
-
521
- const table = getTableDefFromEntity(entityClass);
522
-
523
- if (!table) {
524
-
525
- throw new Error('Entity metadata has not been bootstrapped');
526
-
527
- }
528
-
529
- const root = ensureEntity(session, table, payload, options);
530
-
531
- await applyGraphToEntity(session, table, root as AnyEntity, payload, options);
532
-
533
- return root as unknown as InstanceType<TCtor>;
534
-
535
- };
536
-
537
- /**
538
- * Patches an existing entity by applying only the provided fields.
539
- * Requires the entity to exist (fetched by primary key).
540
- *
541
- * @param session - The ORM session.
542
- * @param entityClass - The entity constructor.
543
- * @param payload - The partial payload data for the root entity and its relations.
544
- * @param options - Options for the patch operation.
545
- * @returns The patched entity instance.
546
- */
547
- export const patchGraphInternal = async <TCtor extends EntityConstructor>(
548
- session: OrmSession,
549
- entityClass: TCtor,
550
- existing: InstanceType<TCtor>,
551
- payload: AnyEntity,
552
- options: SaveGraphOptions = {}
553
- ): Promise<InstanceType<TCtor>> => {
554
- const table = getTableDefFromEntity(entityClass);
555
- if (!table) {
556
- throw new Error('Entity metadata has not been bootstrapped');
557
- }
558
-
559
- await applyGraphToEntity(session, table, existing as AnyEntity, payload, options);
560
- return existing;
561
- };
1
+ import type {
2
+ EntityInstance,
3
+ HasManyCollection,
4
+ HasOneReference,
5
+ BelongsToReference,
6
+ ManyToManyCollection
7
+ } from '../schema/types.js';
8
+ import { normalizeColumnType, type ColumnDef } from '../schema/column-types.js';
9
+ import {
10
+ RelationKinds,
11
+ type BelongsToManyRelation,
12
+ type BelongsToRelation,
13
+ type HasManyRelation,
14
+ type HasOneRelation,
15
+ type RelationDef,
16
+ type MorphOneRelation,
17
+ type MorphManyRelation,
18
+ type MorphToRelation
19
+ } from '../schema/relation.js';
20
+ import type { TableDef } from '../schema/table.js';
21
+ import { findPrimaryKey } from '../query-builder/hydration-planner.js';
22
+ import { createEntityFromRow } from './entity.js';
23
+ import type { EntityConstructor } from './entity-metadata.js';
24
+ import { getTableDefFromEntity } from '../decorators/bootstrap.js';
25
+ import type { OrmSession } from './orm-session.js';
26
+ import type { PrimaryKey } from './entity-context.js';
27
+
28
+ /**
29
+ * Options for controlling the behavior of save graph operations.
30
+ */
31
+ export interface SaveGraphOptions {
32
+ /** Remove existing collection members that are not present in the payload */
33
+ pruneMissing?: boolean;
34
+ /**
35
+ * Coerce JSON-friendly input values into DB-friendly primitives.
36
+ * Currently:
37
+ * - `json`: Date -> ISO string (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
38
+ * - `json-in`: string/number -> Date (for DATE/DATETIME/TIMESTAMP/TIMESTAMPTZ columns)
39
+ */
40
+ coerce?: 'json' | 'json-in';
41
+ }
42
+
43
+ /** Represents an entity object with arbitrary properties. */
44
+ type AnyEntity = Record<string, unknown>;
45
+
46
+ /**
47
+
48
+ * Converts a value to a string key, returning an empty string for null or undefined.
49
+
50
+ * @param value - The value to convert.
51
+
52
+ * @returns The string representation or empty string.
53
+
54
+ */
55
+
56
+ const toKey = (value: unknown): string => (value === null || value === undefined ? '' : String(value));
57
+
58
+ const coerceColumnValue = (
59
+ table: TableDef,
60
+ columnName: string,
61
+ value: unknown,
62
+ options: SaveGraphOptions
63
+ ): unknown => {
64
+ if (value === null || value === undefined) return value;
65
+
66
+ const column = table.columns[columnName] as unknown as ColumnDef | undefined;
67
+ if (!column) return value;
68
+
69
+ const normalized = normalizeColumnType(column.type);
70
+
71
+ const isDateLikeColumn =
72
+ normalized === 'date' ||
73
+ normalized === 'datetime' ||
74
+ normalized === 'timestamp' ||
75
+ normalized === 'timestamptz';
76
+
77
+ if (!isDateLikeColumn) return value;
78
+
79
+ if (options.coerce === 'json') {
80
+ if (value instanceof Date) {
81
+ return value.toISOString();
82
+ }
83
+ return value;
84
+ }
85
+
86
+ if (options.coerce === 'json-in') {
87
+ if (value instanceof Date) return value;
88
+ if (typeof value === 'string' || typeof value === 'number') {
89
+ const date = new Date(value);
90
+ if (Number.isNaN(date.getTime())) {
91
+ throw new Error(`Invalid date value for column "${columnName}"`);
92
+ }
93
+ return date;
94
+ }
95
+ return value;
96
+ }
97
+
98
+ // Future coercions can be added here based on `normalized`.
99
+ return value;
100
+ };
101
+
102
+ const pickColumns = (table: TableDef, payload: AnyEntity, options: SaveGraphOptions): Record<string, unknown> => {
103
+ const columns: Record<string, unknown> = {};
104
+ for (const key of Object.keys(table.columns)) {
105
+ if (payload[key] !== undefined) {
106
+ columns[key] = coerceColumnValue(table, key, payload[key], options);
107
+ }
108
+ }
109
+ return columns;
110
+ };
111
+
112
+ const ensureEntity = <TTable extends TableDef>(
113
+ session: OrmSession,
114
+ table: TTable,
115
+ payload: AnyEntity,
116
+ options: SaveGraphOptions
117
+ ): EntityInstance<TTable> => {
118
+ const pk = findPrimaryKey(table);
119
+ const row = pickColumns(table, payload, options);
120
+ const pkValue = payload[pk];
121
+
122
+ if (pkValue !== undefined && pkValue !== null) {
123
+ const tracked = session.getEntity(table, pkValue as PrimaryKey);
124
+ if (tracked) {
125
+ return tracked as EntityInstance<TTable>;
126
+ }
127
+ // Seed the stub with PK to track a managed entity when updating.
128
+ if (row[pk] === undefined) {
129
+ row[pk] = pkValue;
130
+ }
131
+ }
132
+
133
+ return createEntityFromRow(session, table, row) as EntityInstance<TTable>;
134
+ };
135
+
136
+ const assignColumns = (table: TableDef, entity: AnyEntity, payload: AnyEntity, options: SaveGraphOptions): void => {
137
+ for (const key of Object.keys(table.columns)) {
138
+ if (payload[key] !== undefined) {
139
+ entity[key] = coerceColumnValue(table, key, payload[key], options);
140
+ }
141
+ }
142
+ };
143
+
144
+ const isEntityInCollection = (items: AnyEntity[], pkName: string, entity: AnyEntity): boolean => {
145
+ if (items.includes(entity)) return true;
146
+ const entityPk = entity[pkName];
147
+ if (entityPk === undefined || entityPk === null) return false;
148
+ return items.some(item => toKey(item[pkName]) === toKey(entityPk));
149
+ };
150
+
151
+ const findInCollectionByPk = (items: AnyEntity[], pkName: string, pkValue: unknown): AnyEntity | undefined => {
152
+ if (pkValue === undefined || pkValue === null) return undefined;
153
+ return items.find(item => toKey(item[pkName]) === toKey(pkValue));
154
+ };
155
+
156
+ const extractPivotPayload = (payload: AnyEntity): Record<string, unknown> | undefined => {
157
+ const pivot = payload._pivot ?? payload.pivot;
158
+ if (!pivot || typeof pivot !== 'object' || Array.isArray(pivot)) return undefined;
159
+ const entries = Object.entries(pivot as Record<string, unknown>)
160
+ .filter(([, value]) => value !== undefined);
161
+ if (!entries.length) return undefined;
162
+ return Object.fromEntries(entries);
163
+ };
164
+
165
+ const handleHasMany = async (
166
+ session: OrmSession,
167
+ root: AnyEntity,
168
+ relationName: string,
169
+ relation: HasManyRelation,
170
+ payload: unknown,
171
+ options: SaveGraphOptions
172
+ ): Promise<void> => {
173
+ if (!Array.isArray(payload)) return;
174
+ const collection = root[relationName] as unknown as HasManyCollection<unknown>;
175
+ await collection.load();
176
+
177
+ const targetTable = relation.target;
178
+ const targetPk = findPrimaryKey(targetTable);
179
+ const existing = collection.getItems() as unknown as AnyEntity[];
180
+ const seen = new Set<string>();
181
+
182
+ for (const item of payload) {
183
+ if (item === null || item === undefined) continue;
184
+ const asObj = typeof item === 'object' ? (item as AnyEntity) : { [targetPk]: item };
185
+ const pkValue = asObj[targetPk];
186
+
187
+ const current =
188
+ findInCollectionByPk(existing, targetPk, pkValue) ??
189
+ (pkValue !== undefined && pkValue !== null ? session.getEntity(targetTable, pkValue as PrimaryKey) : undefined);
190
+
191
+ const entity = current ?? ensureEntity(session, targetTable, asObj, options);
192
+ assignColumns(targetTable, entity as AnyEntity, asObj, options);
193
+ await applyGraphToEntity(session, targetTable, entity as AnyEntity, asObj, options);
194
+
195
+ if (!isEntityInCollection(collection.getItems() as unknown as AnyEntity[], targetPk, entity as unknown as AnyEntity)) {
196
+ collection.attach(entity);
197
+ }
198
+
199
+ if (pkValue !== undefined && pkValue !== null) {
200
+ seen.add(toKey(pkValue));
201
+ }
202
+ }
203
+
204
+ if (options.pruneMissing) {
205
+ for (const item of [...collection.getItems()]) {
206
+ const pkValue = item[targetPk];
207
+ if (pkValue !== undefined && pkValue !== null && !seen.has(toKey(pkValue))) {
208
+ collection.remove(item);
209
+ }
210
+ }
211
+ }
212
+ };
213
+
214
+ const handleHasOne = async (
215
+ session: OrmSession,
216
+ root: AnyEntity,
217
+ relationName: string,
218
+ relation: HasOneRelation,
219
+ payload: unknown,
220
+ options: SaveGraphOptions
221
+ ): Promise<void> => {
222
+ const ref = root[relationName] as unknown as HasOneReference<object>;
223
+ if (payload === undefined) return;
224
+ if (payload === null) {
225
+ ref.set(null);
226
+ return;
227
+ }
228
+ const pk = findPrimaryKey(relation.target);
229
+ if (typeof payload === 'number' || typeof payload === 'string') {
230
+ const entity = ref.set({ [pk]: payload });
231
+ if (entity) {
232
+ await applyGraphToEntity(session, relation.target, entity as AnyEntity, { [pk]: payload as PrimaryKey }, options);
233
+ }
234
+ return;
235
+ }
236
+ const attached = ref.set(payload as AnyEntity);
237
+ if (attached) {
238
+ await applyGraphToEntity(session, relation.target, attached as AnyEntity, payload as AnyEntity, options);
239
+ }
240
+ };
241
+
242
+ const handleBelongsTo = async (
243
+ session: OrmSession,
244
+ root: AnyEntity,
245
+ relationName: string,
246
+ relation: BelongsToRelation,
247
+ payload: unknown,
248
+ options: SaveGraphOptions
249
+ ): Promise<void> => {
250
+ const ref = root[relationName] as unknown as BelongsToReference<object>;
251
+ if (payload === undefined) return;
252
+ if (payload === null) {
253
+ ref.set(null);
254
+ return;
255
+ }
256
+ const pk = relation.localKey || findPrimaryKey(relation.target);
257
+ if (typeof payload === 'number' || typeof payload === 'string') {
258
+ const entity = ref.set({ [pk]: payload });
259
+ if (entity) {
260
+ await applyGraphToEntity(session, relation.target, entity as AnyEntity, { [pk]: payload as PrimaryKey }, options);
261
+ }
262
+ return;
263
+ }
264
+ const attached = ref.set(payload as AnyEntity);
265
+ if (attached) {
266
+ await applyGraphToEntity(session, relation.target, attached as AnyEntity, payload as AnyEntity, options);
267
+ }
268
+ };
269
+
270
+ const handleBelongsToMany = async (
271
+ session: OrmSession,
272
+ root: AnyEntity,
273
+ relationName: string,
274
+ relation: BelongsToManyRelation,
275
+ payload: unknown,
276
+ options: SaveGraphOptions
277
+ ): Promise<void> => {
278
+ if (!Array.isArray(payload)) return;
279
+ const collection = root[relationName] as unknown as ManyToManyCollection<unknown>;
280
+ await collection.load();
281
+
282
+ const targetTable = relation.target;
283
+ const targetPk = relation.targetKey || findPrimaryKey(targetTable);
284
+ const seen = new Set<string>();
285
+
286
+ for (const item of payload) {
287
+ if (item === null || item === undefined) continue;
288
+ if (typeof item === 'number' || typeof item === 'string') {
289
+ const id = item;
290
+ collection.attach(id);
291
+ seen.add(toKey(id));
292
+ continue;
293
+ }
294
+
295
+ const asObj = item as AnyEntity;
296
+ const pivotPayload = extractPivotPayload(asObj);
297
+ const pkValue = asObj[targetPk];
298
+ const entity = pkValue !== undefined && pkValue !== null
299
+ ? session.getEntity(targetTable, pkValue as PrimaryKey) ?? ensureEntity(session, targetTable, asObj, options)
300
+ : ensureEntity(session, targetTable, asObj, options);
301
+
302
+ assignColumns(targetTable, entity as AnyEntity, asObj, options);
303
+ await applyGraphToEntity(session, targetTable, entity as AnyEntity, asObj, options);
304
+
305
+ const existsInCollection = isEntityInCollection(
306
+ collection.getItems() as unknown as AnyEntity[],
307
+ targetPk,
308
+ entity as unknown as AnyEntity
309
+ );
310
+ if (!existsInCollection || pivotPayload) {
311
+ collection.attach(entity, pivotPayload);
312
+ }
313
+
314
+ if (pkValue !== undefined && pkValue !== null) {
315
+ seen.add(toKey(pkValue));
316
+ }
317
+ }
318
+
319
+ if (options.pruneMissing) {
320
+ for (const item of [...collection.getItems()] as unknown as AnyEntity[]) {
321
+ const pkValue = item[targetPk];
322
+ if (pkValue !== undefined && pkValue !== null && !seen.has(toKey(pkValue))) {
323
+ collection.detach(item);
324
+ }
325
+ }
326
+ }
327
+ };
328
+
329
+ const handleMorphOne = async (
330
+ session: OrmSession,
331
+ root: AnyEntity,
332
+ relationName: string,
333
+ relation: MorphOneRelation,
334
+ payload: unknown,
335
+ options: SaveGraphOptions
336
+ ): Promise<void> => {
337
+ const ref = root[relationName] as unknown as HasOneReference<object>;
338
+ if (payload === undefined) return;
339
+ if (payload === null) {
340
+ ref.set(null);
341
+ return;
342
+ }
343
+ const pk = findPrimaryKey(relation.target);
344
+ if (typeof payload === 'number' || typeof payload === 'string') {
345
+ const entity = ref.set({ [pk]: payload });
346
+ if (entity) {
347
+ await applyGraphToEntity(session, relation.target, entity as AnyEntity, { [pk]: payload as PrimaryKey }, options);
348
+ }
349
+ return;
350
+ }
351
+ const attached = ref.set(payload as AnyEntity);
352
+ if (attached) {
353
+ await applyGraphToEntity(session, relation.target, attached as AnyEntity, payload as AnyEntity, options);
354
+ }
355
+ };
356
+
357
+ const handleMorphMany = async (
358
+ session: OrmSession,
359
+ root: AnyEntity,
360
+ relationName: string,
361
+ relation: MorphManyRelation,
362
+ payload: unknown,
363
+ options: SaveGraphOptions
364
+ ): Promise<void> => {
365
+ if (!Array.isArray(payload)) return;
366
+ const collection = root[relationName] as unknown as HasManyCollection<unknown>;
367
+ await collection.load();
368
+
369
+ const targetTable = relation.target;
370
+ const targetPk = findPrimaryKey(targetTable);
371
+ const existing = collection.getItems() as unknown as AnyEntity[];
372
+ const seen = new Set<string>();
373
+
374
+ for (const item of payload) {
375
+ if (item === null || item === undefined) continue;
376
+ const asObj = typeof item === 'object' ? (item as AnyEntity) : { [targetPk]: item };
377
+ const pkValue = asObj[targetPk];
378
+
379
+ const current =
380
+ findInCollectionByPk(existing, targetPk, pkValue) ??
381
+ (pkValue !== undefined && pkValue !== null ? session.getEntity(targetTable, pkValue as PrimaryKey) : undefined);
382
+
383
+ const entity = current ?? ensureEntity(session, targetTable, asObj, options);
384
+ assignColumns(targetTable, entity as AnyEntity, asObj, options);
385
+ await applyGraphToEntity(session, targetTable, entity as AnyEntity, asObj, options);
386
+
387
+ if (!isEntityInCollection(collection.getItems() as unknown as AnyEntity[], targetPk, entity as unknown as AnyEntity)) {
388
+ collection.attach(entity);
389
+ }
390
+
391
+ if (pkValue !== undefined && pkValue !== null) {
392
+ seen.add(toKey(pkValue));
393
+ }
394
+ }
395
+
396
+ if (options.pruneMissing) {
397
+ for (const item of [...collection.getItems()]) {
398
+ const pkValue = item[targetPk];
399
+ if (pkValue !== undefined && pkValue !== null && !seen.has(toKey(pkValue))) {
400
+ collection.remove(item);
401
+ }
402
+ }
403
+ }
404
+ };
405
+
406
+ const handleMorphTo = async (
407
+ session: OrmSession,
408
+ root: AnyEntity,
409
+ relationName: string,
410
+ relation: MorphToRelation,
411
+ payload: unknown,
412
+ options: SaveGraphOptions
413
+ ): Promise<void> => {
414
+ const ref = root[relationName] as unknown as BelongsToReference<object>;
415
+ if (payload === undefined) return;
416
+ if (payload === null) {
417
+ ref.set(null);
418
+ return;
419
+ }
420
+ // MorphTo set — the wrapper handles setting typeField/idField on the root
421
+ const attached = ref.set(payload as AnyEntity);
422
+ if (attached) {
423
+ // Try to find the right target table
424
+ for (const [, targetTable] of Object.entries(relation.targets)) {
425
+ const pk = relation.targetKey || findPrimaryKey(targetTable);
426
+ const pkValue = (attached as AnyEntity)[pk];
427
+ if (pkValue !== undefined && pkValue !== null) {
428
+ await applyGraphToEntity(session, targetTable, attached as AnyEntity, payload as AnyEntity, options);
429
+ break;
430
+ }
431
+ }
432
+ }
433
+ };
434
+
435
+ const applyRelation = async (
436
+ session: OrmSession,
437
+ table: TableDef,
438
+ entity: AnyEntity,
439
+ relationName: string,
440
+ relation: RelationDef,
441
+ payload: unknown,
442
+ options: SaveGraphOptions
443
+ ): Promise<void> => {
444
+ switch (relation.type) {
445
+ case RelationKinds.HasMany:
446
+ return handleHasMany(session, entity, relationName, relation, payload, options);
447
+ case RelationKinds.HasOne:
448
+ return handleHasOne(session, entity, relationName, relation, payload, options);
449
+ case RelationKinds.BelongsTo:
450
+ return handleBelongsTo(session, entity, relationName, relation, payload, options);
451
+ case RelationKinds.BelongsToMany:
452
+ return handleBelongsToMany(session, entity, relationName, relation, payload, options);
453
+ case RelationKinds.MorphOne:
454
+ return handleMorphOne(session, entity, relationName, relation as MorphOneRelation, payload, options);
455
+ case RelationKinds.MorphMany:
456
+ return handleMorphMany(session, entity, relationName, relation as MorphManyRelation, payload, options);
457
+ case RelationKinds.MorphTo:
458
+ return handleMorphTo(session, entity, relationName, relation as MorphToRelation, payload, options);
459
+ }
460
+ };
461
+
462
+ const applyGraphToEntity = async (
463
+ session: OrmSession,
464
+ table: TableDef,
465
+ entity: AnyEntity,
466
+ payload: AnyEntity,
467
+ options: SaveGraphOptions
468
+ ): Promise<void> => {
469
+ assignColumns(table, entity, payload, options);
470
+
471
+ for (const [relationName, relation] of Object.entries(table.relations)) {
472
+ if (!(relationName in payload)) continue;
473
+ await applyRelation(session, table, entity, relationName, relation as RelationDef, payload[relationName], options);
474
+ }
475
+ };
476
+
477
+ export const saveGraph = async <TTable extends TableDef>(
478
+ session: OrmSession,
479
+ entityClass: EntityConstructor,
480
+ payload: AnyEntity,
481
+ options: SaveGraphOptions = {}
482
+ ): Promise<EntityInstance<TTable>> => {
483
+ const table = getTableDefFromEntity(entityClass);
484
+ if (!table) {
485
+ throw new Error('Entity metadata has not been bootstrapped');
486
+ }
487
+
488
+ const root = ensureEntity<TTable>(session, table as TTable, payload, options);
489
+ await applyGraphToEntity(session, table, root as AnyEntity, payload, options);
490
+ return root;
491
+ };
492
+
493
+ /**
494
+
495
+ * Internal version of saveGraph with typed return based on the constructor.
496
+
497
+ * @param session - The ORM session.
498
+
499
+ * @param entityClass - The entity constructor.
500
+
501
+ * @param payload - The payload data for the root entity and its relations.
502
+
503
+ * @param options - Options for the save operation.
504
+
505
+ * @returns The root entity instance.
506
+
507
+ */
508
+
509
+ export const saveGraphInternal = async <TCtor extends EntityConstructor>(
510
+
511
+ session: OrmSession,
512
+
513
+ entityClass: TCtor,
514
+
515
+ payload: AnyEntity,
516
+
517
+ options: SaveGraphOptions = {}
518
+
519
+ ): Promise<InstanceType<TCtor>> => {
520
+
521
+ const table = getTableDefFromEntity(entityClass);
522
+
523
+ if (!table) {
524
+
525
+ throw new Error('Entity metadata has not been bootstrapped');
526
+
527
+ }
528
+
529
+ const root = ensureEntity(session, table, payload, options);
530
+
531
+ await applyGraphToEntity(session, table, root as AnyEntity, payload, options);
532
+
533
+ return root as unknown as InstanceType<TCtor>;
534
+
535
+ };
536
+
537
+ /**
538
+ * Patches an existing entity by applying only the provided fields.
539
+ * Requires the entity to exist (fetched by primary key).
540
+ *
541
+ * @param session - The ORM session.
542
+ * @param entityClass - The entity constructor.
543
+ * @param payload - The partial payload data for the root entity and its relations.
544
+ * @param options - Options for the patch operation.
545
+ * @returns The patched entity instance.
546
+ */
547
+ export const patchGraphInternal = async <TCtor extends EntityConstructor>(
548
+ session: OrmSession,
549
+ entityClass: TCtor,
550
+ existing: InstanceType<TCtor>,
551
+ payload: AnyEntity,
552
+ options: SaveGraphOptions = {}
553
+ ): Promise<InstanceType<TCtor>> => {
554
+ const table = getTableDefFromEntity(entityClass);
555
+ if (!table) {
556
+ throw new Error('Entity metadata has not been bootstrapped');
557
+ }
558
+
559
+ await applyGraphToEntity(session, table, existing as AnyEntity, payload, options);
560
+ return existing;
561
+ };