turbine-orm 0.14.0 → 0.16.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 (42) hide show
  1. package/dist/adapters/cockroachdb.js +1 -1
  2. package/dist/adapters/index.d.ts +7 -4
  3. package/dist/adapters/index.js +1 -1
  4. package/dist/adapters/yugabytedb.js +1 -1
  5. package/dist/cjs/adapters/cockroachdb.js +1 -1
  6. package/dist/cjs/adapters/index.js +1 -1
  7. package/dist/cjs/adapters/yugabytedb.js +1 -1
  8. package/dist/cjs/cli/index.js +64 -0
  9. package/dist/cjs/cli/observe-ui.js +182 -0
  10. package/dist/cjs/cli/observe.js +242 -0
  11. package/dist/cjs/cli/studio.js +45 -7
  12. package/dist/cjs/client.js +102 -1
  13. package/dist/cjs/errors.js +44 -1
  14. package/dist/cjs/generate.js +86 -0
  15. package/dist/cjs/index.js +10 -1
  16. package/dist/cjs/nested-write.js +557 -0
  17. package/dist/cjs/observe.js +145 -0
  18. package/dist/cjs/query/builder.js +271 -23
  19. package/dist/cli/index.d.ts +1 -0
  20. package/dist/cli/index.js +64 -0
  21. package/dist/cli/observe-ui.d.ts +2 -0
  22. package/dist/cli/observe-ui.js +180 -0
  23. package/dist/cli/observe.d.ts +20 -0
  24. package/dist/cli/observe.js +237 -0
  25. package/dist/cli/studio.d.ts +10 -2
  26. package/dist/cli/studio.js +45 -7
  27. package/dist/client.d.ts +32 -2
  28. package/dist/client.js +102 -2
  29. package/dist/errors.d.ts +23 -0
  30. package/dist/errors.js +41 -0
  31. package/dist/generate.js +86 -0
  32. package/dist/index.d.ts +5 -3
  33. package/dist/index.js +4 -2
  34. package/dist/nested-write.d.ts +95 -0
  35. package/dist/nested-write.js +551 -0
  36. package/dist/observe.d.ts +36 -0
  37. package/dist/observe.js +141 -0
  38. package/dist/query/builder.d.ts +45 -12
  39. package/dist/query/builder.js +239 -24
  40. package/dist/query/index.d.ts +2 -2
  41. package/dist/query/types.d.ts +76 -8
  42. package/package.json +2 -2
@@ -0,0 +1,557 @@
1
+ "use strict";
2
+ /**
3
+ * turbine-orm — Nested write engine
4
+ *
5
+ * Tree-walking create/update that resolves relation fields in `data` into
6
+ * batched SQL operations within a transaction. Supports create, connect,
7
+ * connectOrCreate, disconnect, set, delete, update, and upsert on related
8
+ * records at arbitrary depth (capped at 10).
9
+ *
10
+ * This module is imported by `query/builder.ts` when the `data` argument
11
+ * of `create()` or `update()` contains relation fields. It never imports
12
+ * `client.ts` directly — the transaction handle is passed in via
13
+ * `NestedWriteContext`.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.extractRelationFields = extractRelationFields;
17
+ exports.hasRelationFields = hasRelationFields;
18
+ exports.injectForeignKey = injectForeignKey;
19
+ exports.executeNestedCreate = executeNestedCreate;
20
+ exports.executeNestedUpdate = executeNestedUpdate;
21
+ const errors_js_1 = require("./errors.js");
22
+ const schema_js_1 = require("./schema.js");
23
+ const MAX_DEPTH = 10;
24
+ const CREATE_ONLY_OPS = new Set(['create', 'connect', 'connectOrCreate']);
25
+ const UPDATE_ONLY_OPS = new Set(['disconnect', 'set', 'delete', 'update', 'upsert']);
26
+ // ---------------------------------------------------------------------------
27
+ // Pure helpers (exported for testing)
28
+ // ---------------------------------------------------------------------------
29
+ /**
30
+ * Separates scalar data fields from relation operation fields.
31
+ *
32
+ * A key is treated as a relation field only when:
33
+ * 1. It matches a relation name in `tableMeta.relations`
34
+ * 2. Its value is a non-null, non-array, non-Date plain object
35
+ *
36
+ * Everything else goes into `scalars`.
37
+ */
38
+ function extractRelationFields(data, tableMeta) {
39
+ const scalars = {};
40
+ const relations = {};
41
+ for (const [key, value] of Object.entries(data)) {
42
+ if (key in tableMeta.relations &&
43
+ value !== null &&
44
+ typeof value === 'object' &&
45
+ !Array.isArray(value) &&
46
+ !(value instanceof Date)) {
47
+ relations[key] = value;
48
+ }
49
+ else {
50
+ scalars[key] = value;
51
+ }
52
+ }
53
+ return { scalars, relations };
54
+ }
55
+ /**
56
+ * Quick check: does `data` contain any relation fields that would trigger
57
+ * the nested write path? Used by QueryInterface to decide whether to
58
+ * delegate to the nested write engine or take the fast scalar-only path.
59
+ */
60
+ function hasRelationFields(data, tableMeta) {
61
+ for (const key of Object.keys(data)) {
62
+ if (key in tableMeta.relations) {
63
+ const val = data[key];
64
+ if (val !== null && typeof val === 'object' && !Array.isArray(val) && !(val instanceof Date)) {
65
+ return true;
66
+ }
67
+ }
68
+ }
69
+ return false;
70
+ }
71
+ /**
72
+ * Inject the parent row's PK value(s) as FK field(s) into child data.
73
+ * Handles composite keys. Returns a new object (does not mutate input).
74
+ */
75
+ function injectForeignKey(childData, relation, parentRow, schema) {
76
+ const fks = (0, schema_js_1.normalizeKeyColumns)(relation.foreignKey);
77
+ const refs = (0, schema_js_1.normalizeKeyColumns)(relation.referenceKey);
78
+ const childTable = schema.tables[relation.to];
79
+ const result = { ...childData };
80
+ for (let i = 0; i < fks.length; i++) {
81
+ const fkCol = fks[i];
82
+ const refCol = refs[i];
83
+ const refField = schema.tables[relation.from]?.reverseColumnMap[refCol] ?? refCol;
84
+ const fkField = childTable?.reverseColumnMap[fkCol] ?? fkCol;
85
+ result[fkField] = parentRow[refField];
86
+ }
87
+ return result;
88
+ }
89
+ // ---------------------------------------------------------------------------
90
+ // Internal helpers
91
+ // ---------------------------------------------------------------------------
92
+ function toArray(value) {
93
+ return Array.isArray(value) ? value : [value];
94
+ }
95
+ /**
96
+ * Validate that all operation keys in a nested write are recognized and
97
+ * allowed for the current context (create vs update).
98
+ */
99
+ function validateOps(relationName, ops, isUpdate) {
100
+ for (const opName of Object.keys(ops)) {
101
+ if (!CREATE_ONLY_OPS.has(opName) && !UPDATE_ONLY_OPS.has(opName)) {
102
+ throw new errors_js_1.ValidationError(`[turbine] Unknown nested write operation "${opName}" on relation "${relationName}". ` +
103
+ `Valid operations: create, connect, connectOrCreate${isUpdate ? ', disconnect, set, delete, update, upsert' : ''}.`);
104
+ }
105
+ if (!isUpdate && UPDATE_ONLY_OPS.has(opName)) {
106
+ throw new errors_js_1.ValidationError(`[turbine] Operation "${opName}" on relation "${relationName}" is only valid inside update(), not create().`);
107
+ }
108
+ }
109
+ }
110
+ /**
111
+ * Build a PK-based where clause from a parent row and its table metadata.
112
+ */
113
+ function pkWhere(tableMeta, row) {
114
+ const where = {};
115
+ for (const col of tableMeta.primaryKey) {
116
+ const field = tableMeta.reverseColumnMap[col] ?? col;
117
+ where[field] = row[field];
118
+ }
119
+ return where;
120
+ }
121
+ // ---------------------------------------------------------------------------
122
+ // executeNestedCreate
123
+ // ---------------------------------------------------------------------------
124
+ /**
125
+ * Tree-walking create: inserts the parent row, then processes each relation
126
+ * operation (create, connect, connectOrCreate), and finally reads back the
127
+ * full tree using `findUnique` with an auto-built `with` clause.
128
+ */
129
+ async function executeNestedCreate(ctx, tableName, data, depth = 0, path = []) {
130
+ if (depth > MAX_DEPTH) {
131
+ throw new errors_js_1.CircularRelationError(path);
132
+ }
133
+ const tableMeta = ctx.schema.tables[tableName];
134
+ if (!tableMeta) {
135
+ throw new errors_js_1.ValidationError(`[turbine] Unknown table "${tableName}".`);
136
+ }
137
+ const { scalars, relations } = extractRelationFields(data, tableMeta);
138
+ // Validate all relation operations
139
+ for (const [relName, ops] of Object.entries(relations)) {
140
+ const rel = tableMeta.relations[relName];
141
+ if (!rel) {
142
+ throw new errors_js_1.RelationError(`[turbine] Unknown relation "${relName}" on table "${tableName}". ` +
143
+ `Available relations: ${Object.keys(tableMeta.relations).join(', ') || '(none)'}.`);
144
+ }
145
+ validateOps(relName, ops, false);
146
+ }
147
+ // Insert the parent row
148
+ const parentRow = (await ctx.tx.table(tableName).create({ data: scalars }));
149
+ // Process each relation
150
+ for (const [relName, ops] of Object.entries(relations)) {
151
+ const rel = tableMeta.relations[relName];
152
+ if (rel.type === 'hasMany' || rel.type === 'hasOne') {
153
+ await processHasManyCreate(ctx, rel, ops, parentRow, depth, path, relName);
154
+ }
155
+ else if (rel.type === 'belongsTo') {
156
+ await processBelongsToCreate(ctx, rel, ops, parentRow, tableName, depth, path, relName);
157
+ }
158
+ }
159
+ // Build the `with` clause for the final read to return the full tree
160
+ const withClause = {};
161
+ for (const relName of Object.keys(relations)) {
162
+ withClause[relName] = true;
163
+ }
164
+ // Final read using existing json_agg machinery
165
+ const fullRow = await ctx.tx.table(tableName).findUnique({
166
+ where: pkWhere(tableMeta, parentRow),
167
+ with: Object.keys(withClause).length > 0 ? withClause : undefined,
168
+ });
169
+ return (fullRow ?? parentRow);
170
+ }
171
+ // ---------------------------------------------------------------------------
172
+ // executeNestedUpdate
173
+ // ---------------------------------------------------------------------------
174
+ /**
175
+ * Tree-walking update: updates the parent row with scalar data, then
176
+ * processes each relation operation (create, connect, connectOrCreate,
177
+ * disconnect, set, delete), and reads back the full tree.
178
+ */
179
+ async function executeNestedUpdate(ctx, tableName, where, data, depth = 0, path = []) {
180
+ if (depth > MAX_DEPTH) {
181
+ throw new errors_js_1.CircularRelationError(path);
182
+ }
183
+ const tableMeta = ctx.schema.tables[tableName];
184
+ if (!tableMeta) {
185
+ throw new errors_js_1.ValidationError(`[turbine] Unknown table "${tableName}".`);
186
+ }
187
+ const { scalars, relations } = extractRelationFields(data, tableMeta);
188
+ // Validate all relation operations
189
+ for (const [relName, ops] of Object.entries(relations)) {
190
+ const rel = tableMeta.relations[relName];
191
+ if (!rel) {
192
+ throw new errors_js_1.RelationError(`[turbine] Unknown relation "${relName}" on table "${tableName}". ` +
193
+ `Available relations: ${Object.keys(tableMeta.relations).join(', ') || '(none)'}.`);
194
+ }
195
+ validateOps(relName, ops, true);
196
+ }
197
+ // Update parent row with scalar data (may be empty if only relation ops)
198
+ let parentRow;
199
+ if (Object.keys(scalars).length > 0) {
200
+ parentRow = (await ctx.tx.table(tableName).update({ where, data: scalars }));
201
+ }
202
+ else {
203
+ parentRow = (await ctx.tx.table(tableName).findUnique({ where }));
204
+ if (!parentRow) {
205
+ throw new errors_js_1.ValidationError(`[turbine] update: no ${tableName} row found matching ${JSON.stringify(where)}.`);
206
+ }
207
+ }
208
+ // Process each relation
209
+ for (const [relName, ops] of Object.entries(relations)) {
210
+ const rel = tableMeta.relations[relName];
211
+ if (rel.type === 'hasMany' || rel.type === 'hasOne') {
212
+ // create, connect, connectOrCreate — same as nested create
213
+ await processHasManyCreate(ctx, rel, ops, parentRow, depth, path, relName);
214
+ // disconnect
215
+ if (ops.disconnect !== undefined) {
216
+ await processDisconnect(ctx, rel, ops.disconnect, relName);
217
+ }
218
+ // set
219
+ if (ops.set !== undefined) {
220
+ await processSet(ctx, rel, ops.set, parentRow);
221
+ }
222
+ // delete
223
+ if (ops.delete !== undefined) {
224
+ await processDelete(ctx, rel, ops.delete);
225
+ }
226
+ // update
227
+ if (ops.update !== undefined) {
228
+ await processNestedUpdate(ctx, rel, ops.update);
229
+ }
230
+ // upsert
231
+ if (ops.upsert !== undefined) {
232
+ await processNestedUpsert(ctx, rel, ops.upsert, parentRow);
233
+ }
234
+ }
235
+ else if (rel.type === 'belongsTo') {
236
+ await processBelongsToCreate(ctx, rel, ops, parentRow, tableName, depth, path, relName);
237
+ // update (belongsTo — derive where from parent FK)
238
+ if (ops.update !== undefined) {
239
+ await processBelongsToUpdate(ctx, rel, ops.update, parentRow, tableName);
240
+ }
241
+ // upsert (belongsTo)
242
+ if (ops.upsert !== undefined) {
243
+ await processBelongsToUpsert(ctx, rel, ops.upsert, parentRow, tableName);
244
+ }
245
+ if (ops.disconnect !== undefined) {
246
+ // For belongsTo disconnect, null out the FK on the parent
247
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
248
+ const nullable = fks.every((fk) => {
249
+ const col = tableMeta.columns.find((c) => c.name === fk);
250
+ return col?.nullable ?? false;
251
+ });
252
+ if (!nullable) {
253
+ throw new errors_js_1.ValidationError(`[turbine] Cannot disconnect "${relName}": foreign key column(s) ${fks.join(', ')} are NOT NULL. Use delete instead.`);
254
+ }
255
+ const updateData = {};
256
+ for (const fk of fks) {
257
+ const field = tableMeta.reverseColumnMap[fk] ?? fk;
258
+ updateData[field] = null;
259
+ }
260
+ await ctx.tx.table(tableName).update({
261
+ where: pkWhere(tableMeta, parentRow),
262
+ data: updateData,
263
+ });
264
+ }
265
+ }
266
+ }
267
+ // Final read with all touched relations
268
+ const withClause = {};
269
+ for (const relName of Object.keys(relations)) {
270
+ withClause[relName] = true;
271
+ }
272
+ const fullRow = await ctx.tx.table(tableName).findUnique({
273
+ where: pkWhere(tableMeta, parentRow),
274
+ with: Object.keys(withClause).length > 0 ? withClause : undefined,
275
+ });
276
+ return (fullRow ?? parentRow);
277
+ }
278
+ // ---------------------------------------------------------------------------
279
+ // hasMany/hasOne create operations
280
+ // ---------------------------------------------------------------------------
281
+ async function processHasManyCreate(ctx, rel, ops, parentRow, depth, path, relName) {
282
+ // create
283
+ if (ops.create !== undefined) {
284
+ const items = toArray(ops.create);
285
+ if (items.length > 0) {
286
+ // Check if any items have nested relations (need per-row recursion)
287
+ const childTable = ctx.schema.tables[rel.to];
288
+ const hasNested = childTable && items.some((item) => Object.keys(item).some((k) => k in (childTable.relations ?? {})));
289
+ if (hasNested) {
290
+ // Per-row recursive create for items with nested relations
291
+ for (const item of items) {
292
+ const injected = injectForeignKey(item, rel, parentRow, ctx.schema);
293
+ await executeNestedCreate(ctx, rel.to, injected, depth + 1, [...path, relName]);
294
+ }
295
+ }
296
+ else {
297
+ // Batch via createMany (UNNEST) — fast path
298
+ const injected = items.map((item) => injectForeignKey(item, rel, parentRow, ctx.schema));
299
+ await ctx.tx.table(rel.to).createMany({ data: injected });
300
+ }
301
+ }
302
+ }
303
+ // connect
304
+ if (ops.connect !== undefined) {
305
+ const items = toArray(ops.connect);
306
+ if (items.length > 0) {
307
+ await batchConnect(ctx, rel, items, parentRow);
308
+ }
309
+ }
310
+ // connectOrCreate
311
+ if (ops.connectOrCreate !== undefined) {
312
+ const items = toArray(ops.connectOrCreate);
313
+ for (const item of items) {
314
+ const op = item;
315
+ await connectOrCreate(ctx, rel, op, parentRow);
316
+ }
317
+ }
318
+ }
319
+ // ---------------------------------------------------------------------------
320
+ // belongsTo create operations
321
+ // ---------------------------------------------------------------------------
322
+ async function processBelongsToCreate(ctx, rel, ops, parentRow, parentTable, depth, path, relName) {
323
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
324
+ const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
325
+ // create — insert the related row, then update parent's FK
326
+ if (ops.create !== undefined) {
327
+ const items = toArray(ops.create);
328
+ if (items.length > 0) {
329
+ const relatedRow = (await executeNestedCreate(ctx, rel.to, items[0], depth + 1, [...path, relName]));
330
+ const updateData = {};
331
+ const relatedTable = ctx.schema.tables[rel.to];
332
+ for (let i = 0; i < fks.length; i++) {
333
+ const fkField = ctx.schema.tables[parentTable]?.reverseColumnMap[fks[i]] ?? fks[i];
334
+ const refField = relatedTable?.reverseColumnMap[refs[i]] ?? refs[i];
335
+ updateData[fkField] = relatedRow[refField];
336
+ }
337
+ const parentMeta = ctx.schema.tables[parentTable];
338
+ await ctx.tx.table(parentTable).update({
339
+ where: pkWhere(parentMeta, parentRow),
340
+ data: updateData,
341
+ });
342
+ }
343
+ }
344
+ // connect — validate existence, update parent's FK
345
+ if (ops.connect !== undefined) {
346
+ const items = toArray(ops.connect);
347
+ if (items.length > 0) {
348
+ const target = items[0];
349
+ const existing = await ctx.tx.table(rel.to).findUnique({ where: target });
350
+ if (!existing) {
351
+ throw new errors_js_1.ValidationError(`[turbine] connect on "${relName}": no ${rel.to} row found matching ${JSON.stringify(target)}.`);
352
+ }
353
+ const updateData = {};
354
+ const relatedTable = ctx.schema.tables[rel.to];
355
+ for (let i = 0; i < fks.length; i++) {
356
+ const fkField = ctx.schema.tables[parentTable]?.reverseColumnMap[fks[i]] ?? fks[i];
357
+ const refField = relatedTable?.reverseColumnMap[refs[i]] ?? refs[i];
358
+ updateData[fkField] = existing[refField];
359
+ }
360
+ const parentMeta = ctx.schema.tables[parentTable];
361
+ await ctx.tx.table(parentTable).update({
362
+ where: pkWhere(parentMeta, parentRow),
363
+ data: updateData,
364
+ });
365
+ }
366
+ }
367
+ }
368
+ // ---------------------------------------------------------------------------
369
+ // connect, connectOrCreate, disconnect, set, delete helpers
370
+ // ---------------------------------------------------------------------------
371
+ async function batchConnect(ctx, rel, items, parentRow) {
372
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
373
+ const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
374
+ const childTable = ctx.schema.tables[rel.to];
375
+ if (!childTable)
376
+ return;
377
+ // Validate all targets exist
378
+ for (const target of items) {
379
+ const existing = await ctx.tx.table(rel.to).findUnique({ where: target });
380
+ if (!existing) {
381
+ throw new errors_js_1.ValidationError(`[turbine] connect: no ${rel.to} row found matching ${JSON.stringify(target)}.`);
382
+ }
383
+ }
384
+ // Build FK update data to point children at parent
385
+ const updateData = {};
386
+ for (let i = 0; i < fks.length; i++) {
387
+ const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
388
+ const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
389
+ updateData[fkField] = parentRow[refField];
390
+ }
391
+ // Update each matching child
392
+ for (const target of items) {
393
+ await ctx.tx.table(rel.to).update({ where: target, data: updateData });
394
+ }
395
+ }
396
+ async function connectOrCreate(ctx, rel, op, parentRow) {
397
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
398
+ const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
399
+ const childTable = ctx.schema.tables[rel.to];
400
+ if (!childTable)
401
+ return;
402
+ // Try to find existing
403
+ let row = (await ctx.tx.table(rel.to).findUnique({ where: op.where }));
404
+ if (!row) {
405
+ // Create with FK injected
406
+ const injected = injectForeignKey(op.create, rel, parentRow, ctx.schema);
407
+ row = (await ctx.tx.table(rel.to).create({ data: injected }));
408
+ }
409
+ else {
410
+ // Update FK to point to parent
411
+ const updateData = {};
412
+ for (let i = 0; i < fks.length; i++) {
413
+ const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
414
+ const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
415
+ updateData[fkField] = parentRow[refField];
416
+ }
417
+ await ctx.tx.table(rel.to).update({ where: op.where, data: updateData });
418
+ }
419
+ }
420
+ async function processDisconnect(ctx, rel, disconnectArg, relName) {
421
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
422
+ const childTable = ctx.schema.tables[rel.to];
423
+ if (!childTable)
424
+ return;
425
+ // Check FK nullability
426
+ const nullable = fks.every((fk) => {
427
+ const col = childTable.columns.find((c) => c.name === fk);
428
+ return col?.nullable ?? false;
429
+ });
430
+ if (!nullable) {
431
+ throw new errors_js_1.ValidationError(`[turbine] Cannot disconnect "${relName}": foreign key column(s) ${fks.join(', ')} on "${rel.to}" are NOT NULL. Use delete instead.`);
432
+ }
433
+ const items = toArray(disconnectArg);
434
+ const nullData = {};
435
+ for (const fk of fks) {
436
+ const field = childTable.reverseColumnMap[fk] ?? fk;
437
+ nullData[field] = null;
438
+ }
439
+ for (const target of items) {
440
+ await ctx.tx.table(rel.to).update({ where: target, data: nullData });
441
+ }
442
+ }
443
+ async function processSet(ctx, rel, setItems, parentRow) {
444
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
445
+ const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
446
+ const childTable = ctx.schema.tables[rel.to];
447
+ if (!childTable)
448
+ return;
449
+ // Build parent FK match for finding current children
450
+ const parentWhere = {};
451
+ for (let i = 0; i < fks.length; i++) {
452
+ const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
453
+ const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
454
+ parentWhere[fkField] = parentRow[refField];
455
+ }
456
+ // Disconnect all current children
457
+ const nullData = {};
458
+ for (const fk of fks) {
459
+ const field = childTable.reverseColumnMap[fk] ?? fk;
460
+ nullData[field] = null;
461
+ }
462
+ await ctx.tx.table(rel.to).updateMany({
463
+ where: parentWhere,
464
+ data: nullData,
465
+ allowFullTableScan: true,
466
+ });
467
+ // Connect the specified items
468
+ const updateData = {};
469
+ for (let i = 0; i < fks.length; i++) {
470
+ const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
471
+ const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
472
+ updateData[fkField] = parentRow[refField];
473
+ }
474
+ for (const target of setItems) {
475
+ await ctx.tx.table(rel.to).update({ where: target, data: updateData });
476
+ }
477
+ }
478
+ // ---------------------------------------------------------------------------
479
+ // update / upsert operations (update-context only)
480
+ // ---------------------------------------------------------------------------
481
+ async function processNestedUpdate(ctx, rel, updateArg) {
482
+ const items = toArray(updateArg);
483
+ for (const item of items) {
484
+ if (!item.where || !item.data) {
485
+ throw new errors_js_1.ValidationError(`[turbine] Nested update on "${rel.name}" requires both "where" and "data" fields.`);
486
+ }
487
+ await ctx.tx.table(rel.to).update({ where: item.where, data: item.data });
488
+ }
489
+ }
490
+ async function processNestedUpsert(ctx, rel, upsertArg, parentRow) {
491
+ const items = toArray(upsertArg);
492
+ for (const item of items) {
493
+ if (!item.where || !item.create || !item.update) {
494
+ throw new errors_js_1.ValidationError(`[turbine] Nested upsert on "${rel.name}" requires "where", "create", and "update" fields.`);
495
+ }
496
+ const existing = await ctx.tx.table(rel.to).findUnique({ where: item.where });
497
+ if (existing) {
498
+ await ctx.tx.table(rel.to).update({ where: item.where, data: item.update });
499
+ }
500
+ else {
501
+ const injected = injectForeignKey(item.create, rel, parentRow, ctx.schema);
502
+ await ctx.tx.table(rel.to).create({ data: injected });
503
+ }
504
+ }
505
+ }
506
+ async function processBelongsToUpdate(ctx, rel, updateArg, parentRow, parentTable) {
507
+ const item = updateArg;
508
+ if (!item.data) {
509
+ throw new errors_js_1.ValidationError(`[turbine] Nested update on belongsTo "${rel.name}" requires a "data" field.`);
510
+ }
511
+ // Derive where from parent's FK values
512
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
513
+ const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
514
+ const parentMeta = ctx.schema.tables[parentTable];
515
+ const relatedTable = ctx.schema.tables[rel.to];
516
+ const where = {};
517
+ for (let i = 0; i < fks.length; i++) {
518
+ const fkField = parentMeta?.reverseColumnMap[fks[i]] ?? fks[i];
519
+ const refField = relatedTable?.reverseColumnMap[refs[i]] ?? refs[i];
520
+ where[refField] = parentRow[fkField];
521
+ }
522
+ await ctx.tx.table(rel.to).update({ where, data: item.data });
523
+ }
524
+ async function processBelongsToUpsert(ctx, rel, upsertArg, parentRow, parentTable) {
525
+ const item = upsertArg;
526
+ if (!item.where || !item.create || !item.update) {
527
+ throw new errors_js_1.ValidationError(`[turbine] Nested upsert on belongsTo "${rel.name}" requires "where", "create", and "update" fields.`);
528
+ }
529
+ const existing = await ctx.tx.table(rel.to).findUnique({ where: item.where });
530
+ if (existing) {
531
+ await ctx.tx.table(rel.to).update({ where: item.where, data: item.update });
532
+ }
533
+ else {
534
+ // Create the related row, then update parent's FK to point at it
535
+ const createdRow = (await ctx.tx.table(rel.to).create({ data: item.create }));
536
+ const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
537
+ const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
538
+ const parentMeta = ctx.schema.tables[parentTable];
539
+ const relatedTable = ctx.schema.tables[rel.to];
540
+ const updateData = {};
541
+ for (let i = 0; i < fks.length; i++) {
542
+ const fkField = parentMeta.reverseColumnMap[fks[i]] ?? fks[i];
543
+ const refField = relatedTable?.reverseColumnMap[refs[i]] ?? refs[i];
544
+ updateData[fkField] = createdRow[refField];
545
+ }
546
+ await ctx.tx.table(parentTable).update({
547
+ where: pkWhere(parentMeta, parentRow),
548
+ data: updateData,
549
+ });
550
+ }
551
+ }
552
+ async function processDelete(ctx, rel, deleteArg) {
553
+ const items = toArray(deleteArg);
554
+ for (const target of items) {
555
+ await ctx.tx.table(rel.to).delete({ where: target });
556
+ }
557
+ }