turbine-orm 0.13.3 → 0.15.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.
- package/dist/adapters/cockroachdb.js +1 -1
- package/dist/adapters/index.d.ts +7 -4
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/yugabytedb.js +1 -1
- package/dist/cjs/adapters/cockroachdb.js +1 -1
- package/dist/cjs/adapters/index.js +1 -1
- package/dist/cjs/adapters/yugabytedb.js +1 -1
- package/dist/cjs/cli/studio.js +45 -7
- package/dist/cjs/client.js +48 -1
- package/dist/cjs/dialect.js +6 -4
- package/dist/cjs/errors.js +44 -1
- package/dist/cjs/generate.js +95 -1
- package/dist/cjs/index.js +10 -1
- package/dist/cjs/introspect.js +14 -4
- package/dist/cjs/nested-write.js +467 -0
- package/dist/cjs/query/builder.js +212 -16
- package/dist/cli/studio.d.ts +10 -2
- package/dist/cli/studio.js +45 -7
- package/dist/client.d.ts +23 -0
- package/dist/client.js +47 -1
- package/dist/dialect.d.ts +3 -3
- package/dist/dialect.js +6 -4
- package/dist/errors.d.ts +23 -0
- package/dist/errors.js +41 -0
- package/dist/generate.js +95 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -2
- package/dist/introspect.js +15 -5
- package/dist/nested-write.d.ts +95 -0
- package/dist/nested-write.js +461 -0
- package/dist/query/builder.d.ts +28 -12
- package/dist/query/builder.js +180 -17
- package/dist/query/index.d.ts +1 -1
- package/dist/query/types.d.ts +76 -8
- package/dist/schema.d.ts +9 -3
- package/package.json +2 -2
|
@@ -0,0 +1,467 @@
|
|
|
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, and delete on related records at
|
|
8
|
+
* 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']);
|
|
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' : ''}.`);
|
|
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
|
+
}
|
|
227
|
+
else if (rel.type === 'belongsTo') {
|
|
228
|
+
await processBelongsToCreate(ctx, rel, ops, parentRow, tableName, depth, path, relName);
|
|
229
|
+
if (ops.disconnect !== undefined) {
|
|
230
|
+
// For belongsTo disconnect, null out the FK on the parent
|
|
231
|
+
const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
|
|
232
|
+
const nullable = fks.every((fk) => {
|
|
233
|
+
const col = tableMeta.columns.find((c) => c.name === fk);
|
|
234
|
+
return col?.nullable ?? false;
|
|
235
|
+
});
|
|
236
|
+
if (!nullable) {
|
|
237
|
+
throw new errors_js_1.ValidationError(`[turbine] Cannot disconnect "${relName}": foreign key column(s) ${fks.join(', ')} are NOT NULL. Use delete instead.`);
|
|
238
|
+
}
|
|
239
|
+
const updateData = {};
|
|
240
|
+
for (const fk of fks) {
|
|
241
|
+
const field = tableMeta.reverseColumnMap[fk] ?? fk;
|
|
242
|
+
updateData[field] = null;
|
|
243
|
+
}
|
|
244
|
+
await ctx.tx.table(tableName).update({
|
|
245
|
+
where: pkWhere(tableMeta, parentRow),
|
|
246
|
+
data: updateData,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// Final read with all touched relations
|
|
252
|
+
const withClause = {};
|
|
253
|
+
for (const relName of Object.keys(relations)) {
|
|
254
|
+
withClause[relName] = true;
|
|
255
|
+
}
|
|
256
|
+
const fullRow = await ctx.tx.table(tableName).findUnique({
|
|
257
|
+
where: pkWhere(tableMeta, parentRow),
|
|
258
|
+
with: Object.keys(withClause).length > 0 ? withClause : undefined,
|
|
259
|
+
});
|
|
260
|
+
return (fullRow ?? parentRow);
|
|
261
|
+
}
|
|
262
|
+
// ---------------------------------------------------------------------------
|
|
263
|
+
// hasMany/hasOne create operations
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
async function processHasManyCreate(ctx, rel, ops, parentRow, depth, path, relName) {
|
|
266
|
+
// create
|
|
267
|
+
if (ops.create !== undefined) {
|
|
268
|
+
const items = toArray(ops.create);
|
|
269
|
+
if (items.length > 0) {
|
|
270
|
+
// Check if any items have nested relations (need per-row recursion)
|
|
271
|
+
const childTable = ctx.schema.tables[rel.to];
|
|
272
|
+
const hasNested = childTable && items.some((item) => Object.keys(item).some((k) => k in (childTable.relations ?? {})));
|
|
273
|
+
if (hasNested) {
|
|
274
|
+
// Per-row recursive create for items with nested relations
|
|
275
|
+
for (const item of items) {
|
|
276
|
+
const injected = injectForeignKey(item, rel, parentRow, ctx.schema);
|
|
277
|
+
await executeNestedCreate(ctx, rel.to, injected, depth + 1, [...path, relName]);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
// Batch via createMany (UNNEST) — fast path
|
|
282
|
+
const injected = items.map((item) => injectForeignKey(item, rel, parentRow, ctx.schema));
|
|
283
|
+
await ctx.tx.table(rel.to).createMany({ data: injected });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// connect
|
|
288
|
+
if (ops.connect !== undefined) {
|
|
289
|
+
const items = toArray(ops.connect);
|
|
290
|
+
if (items.length > 0) {
|
|
291
|
+
await batchConnect(ctx, rel, items, parentRow);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
// connectOrCreate
|
|
295
|
+
if (ops.connectOrCreate !== undefined) {
|
|
296
|
+
const items = toArray(ops.connectOrCreate);
|
|
297
|
+
for (const item of items) {
|
|
298
|
+
const op = item;
|
|
299
|
+
await connectOrCreate(ctx, rel, op, parentRow);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
// belongsTo create operations
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
async function processBelongsToCreate(ctx, rel, ops, parentRow, parentTable, depth, path, relName) {
|
|
307
|
+
const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
|
|
308
|
+
const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
|
|
309
|
+
// create — insert the related row, then update parent's FK
|
|
310
|
+
if (ops.create !== undefined) {
|
|
311
|
+
const items = toArray(ops.create);
|
|
312
|
+
if (items.length > 0) {
|
|
313
|
+
const relatedRow = (await executeNestedCreate(ctx, rel.to, items[0], depth + 1, [...path, relName]));
|
|
314
|
+
const updateData = {};
|
|
315
|
+
const relatedTable = ctx.schema.tables[rel.to];
|
|
316
|
+
for (let i = 0; i < fks.length; i++) {
|
|
317
|
+
const fkField = ctx.schema.tables[parentTable]?.reverseColumnMap[fks[i]] ?? fks[i];
|
|
318
|
+
const refField = relatedTable?.reverseColumnMap[refs[i]] ?? refs[i];
|
|
319
|
+
updateData[fkField] = relatedRow[refField];
|
|
320
|
+
}
|
|
321
|
+
const parentMeta = ctx.schema.tables[parentTable];
|
|
322
|
+
await ctx.tx.table(parentTable).update({
|
|
323
|
+
where: pkWhere(parentMeta, parentRow),
|
|
324
|
+
data: updateData,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
// connect — validate existence, update parent's FK
|
|
329
|
+
if (ops.connect !== undefined) {
|
|
330
|
+
const items = toArray(ops.connect);
|
|
331
|
+
if (items.length > 0) {
|
|
332
|
+
const target = items[0];
|
|
333
|
+
const existing = await ctx.tx.table(rel.to).findUnique({ where: target });
|
|
334
|
+
if (!existing) {
|
|
335
|
+
throw new errors_js_1.ValidationError(`[turbine] connect on "${relName}": no ${rel.to} row found matching ${JSON.stringify(target)}.`);
|
|
336
|
+
}
|
|
337
|
+
const updateData = {};
|
|
338
|
+
const relatedTable = ctx.schema.tables[rel.to];
|
|
339
|
+
for (let i = 0; i < fks.length; i++) {
|
|
340
|
+
const fkField = ctx.schema.tables[parentTable]?.reverseColumnMap[fks[i]] ?? fks[i];
|
|
341
|
+
const refField = relatedTable?.reverseColumnMap[refs[i]] ?? refs[i];
|
|
342
|
+
updateData[fkField] = existing[refField];
|
|
343
|
+
}
|
|
344
|
+
const parentMeta = ctx.schema.tables[parentTable];
|
|
345
|
+
await ctx.tx.table(parentTable).update({
|
|
346
|
+
where: pkWhere(parentMeta, parentRow),
|
|
347
|
+
data: updateData,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
// connect, connectOrCreate, disconnect, set, delete helpers
|
|
354
|
+
// ---------------------------------------------------------------------------
|
|
355
|
+
async function batchConnect(ctx, rel, items, parentRow) {
|
|
356
|
+
const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
|
|
357
|
+
const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
|
|
358
|
+
const childTable = ctx.schema.tables[rel.to];
|
|
359
|
+
if (!childTable)
|
|
360
|
+
return;
|
|
361
|
+
// Validate all targets exist
|
|
362
|
+
for (const target of items) {
|
|
363
|
+
const existing = await ctx.tx.table(rel.to).findUnique({ where: target });
|
|
364
|
+
if (!existing) {
|
|
365
|
+
throw new errors_js_1.ValidationError(`[turbine] connect: no ${rel.to} row found matching ${JSON.stringify(target)}.`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
// Build FK update data to point children at parent
|
|
369
|
+
const updateData = {};
|
|
370
|
+
for (let i = 0; i < fks.length; i++) {
|
|
371
|
+
const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
|
|
372
|
+
const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
|
|
373
|
+
updateData[fkField] = parentRow[refField];
|
|
374
|
+
}
|
|
375
|
+
// Update each matching child
|
|
376
|
+
for (const target of items) {
|
|
377
|
+
await ctx.tx.table(rel.to).update({ where: target, data: updateData });
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
async function connectOrCreate(ctx, rel, op, parentRow) {
|
|
381
|
+
const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
|
|
382
|
+
const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
|
|
383
|
+
const childTable = ctx.schema.tables[rel.to];
|
|
384
|
+
if (!childTable)
|
|
385
|
+
return;
|
|
386
|
+
// Try to find existing
|
|
387
|
+
let row = (await ctx.tx.table(rel.to).findUnique({ where: op.where }));
|
|
388
|
+
if (!row) {
|
|
389
|
+
// Create with FK injected
|
|
390
|
+
const injected = injectForeignKey(op.create, rel, parentRow, ctx.schema);
|
|
391
|
+
row = (await ctx.tx.table(rel.to).create({ data: injected }));
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
// Update FK to point to parent
|
|
395
|
+
const updateData = {};
|
|
396
|
+
for (let i = 0; i < fks.length; i++) {
|
|
397
|
+
const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
|
|
398
|
+
const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
|
|
399
|
+
updateData[fkField] = parentRow[refField];
|
|
400
|
+
}
|
|
401
|
+
await ctx.tx.table(rel.to).update({ where: op.where, data: updateData });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async function processDisconnect(ctx, rel, disconnectArg, relName) {
|
|
405
|
+
const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
|
|
406
|
+
const childTable = ctx.schema.tables[rel.to];
|
|
407
|
+
if (!childTable)
|
|
408
|
+
return;
|
|
409
|
+
// Check FK nullability
|
|
410
|
+
const nullable = fks.every((fk) => {
|
|
411
|
+
const col = childTable.columns.find((c) => c.name === fk);
|
|
412
|
+
return col?.nullable ?? false;
|
|
413
|
+
});
|
|
414
|
+
if (!nullable) {
|
|
415
|
+
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.`);
|
|
416
|
+
}
|
|
417
|
+
const items = toArray(disconnectArg);
|
|
418
|
+
const nullData = {};
|
|
419
|
+
for (const fk of fks) {
|
|
420
|
+
const field = childTable.reverseColumnMap[fk] ?? fk;
|
|
421
|
+
nullData[field] = null;
|
|
422
|
+
}
|
|
423
|
+
for (const target of items) {
|
|
424
|
+
await ctx.tx.table(rel.to).update({ where: target, data: nullData });
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
async function processSet(ctx, rel, setItems, parentRow) {
|
|
428
|
+
const fks = (0, schema_js_1.normalizeKeyColumns)(rel.foreignKey);
|
|
429
|
+
const refs = (0, schema_js_1.normalizeKeyColumns)(rel.referenceKey);
|
|
430
|
+
const childTable = ctx.schema.tables[rel.to];
|
|
431
|
+
if (!childTable)
|
|
432
|
+
return;
|
|
433
|
+
// Build parent FK match for finding current children
|
|
434
|
+
const parentWhere = {};
|
|
435
|
+
for (let i = 0; i < fks.length; i++) {
|
|
436
|
+
const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
|
|
437
|
+
const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
|
|
438
|
+
parentWhere[fkField] = parentRow[refField];
|
|
439
|
+
}
|
|
440
|
+
// Disconnect all current children
|
|
441
|
+
const nullData = {};
|
|
442
|
+
for (const fk of fks) {
|
|
443
|
+
const field = childTable.reverseColumnMap[fk] ?? fk;
|
|
444
|
+
nullData[field] = null;
|
|
445
|
+
}
|
|
446
|
+
await ctx.tx.table(rel.to).updateMany({
|
|
447
|
+
where: parentWhere,
|
|
448
|
+
data: nullData,
|
|
449
|
+
allowFullTableScan: true,
|
|
450
|
+
});
|
|
451
|
+
// Connect the specified items
|
|
452
|
+
const updateData = {};
|
|
453
|
+
for (let i = 0; i < fks.length; i++) {
|
|
454
|
+
const fkField = childTable.reverseColumnMap[fks[i]] ?? fks[i];
|
|
455
|
+
const refField = ctx.schema.tables[rel.from]?.reverseColumnMap[refs[i]] ?? refs[i];
|
|
456
|
+
updateData[fkField] = parentRow[refField];
|
|
457
|
+
}
|
|
458
|
+
for (const target of setItems) {
|
|
459
|
+
await ctx.tx.table(rel.to).update({ where: target, data: updateData });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
async function processDelete(ctx, rel, deleteArg) {
|
|
463
|
+
const items = toArray(deleteArg);
|
|
464
|
+
for (const target of items) {
|
|
465
|
+
await ctx.tx.table(rel.to).delete({ where: target });
|
|
466
|
+
}
|
|
467
|
+
}
|