webspresso 0.0.98 → 0.0.100

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 (88) hide show
  1. package/.agents/ADMIN.md +11 -1
  2. package/.agents/AGENTS.md +2 -2
  3. package/.agents/AUTH.md +415 -0
  4. package/.agents/CLI.md +47 -0
  5. package/.agents/ERRORS.md +59 -0
  6. package/.agents/ORM.md +178 -4
  7. package/.agents/PLUGINS.md +113 -8
  8. package/.agents/QUEUE.md +92 -0
  9. package/.agents/ROUTING.md +160 -7
  10. package/.agents/STREAMING.md +35 -0
  11. package/AGENTS.md +2 -0
  12. package/README.md +145 -93
  13. package/bin/commands/add-docker.js +467 -0
  14. package/bin/commands/deploy-check.js +339 -0
  15. package/bin/webspresso.js +4 -0
  16. package/core/auth/index.js +123 -1
  17. package/core/auth/magic-link.js +170 -0
  18. package/core/auth/manager.js +477 -3
  19. package/core/auth/middleware.js +118 -5
  20. package/core/auth/oauth.js +517 -0
  21. package/core/auth/qrcode.js +499 -0
  22. package/core/auth/session-manager.js +255 -0
  23. package/core/auth/sessions.js +351 -0
  24. package/core/auth/tokens.js +1 -0
  25. package/core/auth/totp.js +507 -0
  26. package/core/auth/user-agent.js +161 -0
  27. package/core/orm/eager-loader.js +144 -10
  28. package/core/orm/index.js +10 -1
  29. package/core/orm/model.js +55 -1
  30. package/core/orm/query-builder.js +90 -4
  31. package/core/orm/repository.js +327 -16
  32. package/core/orm/scopes.js +3 -2
  33. package/core/orm/search.js +213 -0
  34. package/core/orm/types.js +6 -1
  35. package/core/queue/cron.js +544 -0
  36. package/core/queue/index.js +8 -1
  37. package/core/queue/manager.js +100 -1
  38. package/core/queue/scheduler.js +415 -0
  39. package/core/sse/index.js +19 -0
  40. package/core/sse/stream.js +430 -0
  41. package/core/ssr/stream.js +62 -2
  42. package/index.d.ts +794 -6
  43. package/index.js +48 -0
  44. package/package.json +7 -5
  45. package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +323 -31
  46. package/plugins/admin-panel/client/parts/08-record-list.js +5 -0
  47. package/plugins/admin-panel/client/verify-spa-parts.js +2 -0
  48. package/plugins/admin-panel/field-renderers/file-upload.js +187 -104
  49. package/plugins/admin-panel/field-renderers/index.js +2 -0
  50. package/plugins/admin-panel/modules/admin-users.js +1 -1
  51. package/plugins/api-key/crypto.js +101 -0
  52. package/plugins/api-key/index.js +288 -0
  53. package/plugins/api-key/middleware.js +461 -0
  54. package/plugins/api-key/migration-template.js +48 -0
  55. package/plugins/api-key/model.js +50 -0
  56. package/plugins/api-key/scopes.js +125 -0
  57. package/plugins/audit-log/admin-component.js +487 -70
  58. package/plugins/audit-log/api-handlers.js +114 -0
  59. package/plugins/audit-log/index.js +24 -0
  60. package/plugins/content/client/inline-edit.js +2 -46
  61. package/plugins/cors.js +13 -2
  62. package/plugins/email/auth-bridge.js +66 -0
  63. package/plugins/email/bundled-templates.js +15 -0
  64. package/plugins/email/templates/auth-magic-link.mjml +13 -0
  65. package/plugins/file-manager/admin-component.js +69 -53
  66. package/plugins/file-manager/index.js +25 -8
  67. package/plugins/index.js +8 -0
  68. package/plugins/oauth/index.js +338 -0
  69. package/plugins/queue/index.js +4 -0
  70. package/plugins/webhooks/admin-component.js +608 -0
  71. package/plugins/webhooks/api-handlers.js +237 -0
  72. package/plugins/webhooks/crypto.js +144 -0
  73. package/plugins/webhooks/dispatcher.js +708 -0
  74. package/plugins/webhooks/index.js +263 -0
  75. package/plugins/webhooks/matcher.js +113 -0
  76. package/plugins/webhooks/migration-template.js +75 -0
  77. package/plugins/webhooks/models.js +98 -0
  78. package/plugins/webhooks/sender.js +176 -0
  79. package/src/api/api-loader.js +1 -0
  80. package/src/bundle/index.js +2 -1
  81. package/src/discovery/file-route-parser.js +44 -1
  82. package/src/discovery/scan-routes.js +2 -2
  83. package/src/file-router.js +310 -104
  84. package/src/helpers.js +16 -1
  85. package/src/njk-frontmatter.js +3 -0
  86. package/src/routing/cascading.js +490 -0
  87. package/src/routing/middleware-resolver.js +92 -0
  88. package/src/server.js +6 -0
@@ -1,31 +1,109 @@
1
1
  /**
2
2
  * Webspresso ORM - Eager Loader
3
- * Batch loading algorithm for relations
3
+ * Batch loading algorithm for relations (supports direct & arbitrary nested relations)
4
4
  * @module core/orm/eager-loader
5
5
  */
6
6
 
7
7
  const { resolveRelationModel, getRelationKeys } = require('./model');
8
8
  const { applyScopes, createScopeContext } = require('./scopes');
9
+ const { getJsonColumns, deserializeJsonFields } = require('./json-fields');
9
10
 
10
11
  /**
11
- * Load relations for a set of records using batch queries
12
+ * Parse relation specifications into a grouped structure: Map<topLevelRelation, string[]>
13
+ * Supports dot notation ('author.profile'), arrays (['author', 'comments.author']),
14
+ * and nested relation chains of arbitrary depth.
15
+ *
16
+ * @param {Array<string|Object>} relationNames
17
+ * @returns {Map<string, string[]>}
18
+ */
19
+ function parseRelationTree(relationNames) {
20
+ const tree = new Map();
21
+
22
+ function addPath(top, nested) {
23
+ if (!top || typeof top !== 'string') return;
24
+ const cleanTop = top.trim();
25
+ if (!cleanTop) return;
26
+
27
+ if (!tree.has(cleanTop)) {
28
+ tree.set(cleanTop, []);
29
+ }
30
+ if (nested) {
31
+ if (Array.isArray(nested)) {
32
+ for (const item of nested) {
33
+ if (item && typeof item === 'string') tree.get(cleanTop).push(item.trim());
34
+ }
35
+ } else if (typeof nested === 'string') {
36
+ const cleanNested = nested.trim();
37
+ if (cleanNested) tree.get(cleanTop).push(cleanNested);
38
+ }
39
+ }
40
+ }
41
+
42
+ function processItem(item) {
43
+ if (!item) return;
44
+
45
+ if (typeof item === 'string') {
46
+ const dotIndex = item.indexOf('.');
47
+ if (dotIndex === -1) {
48
+ addPath(item);
49
+ } else {
50
+ const top = item.slice(0, dotIndex);
51
+ const rest = item.slice(dotIndex + 1);
52
+ addPath(top, rest);
53
+ }
54
+ } else if (Array.isArray(item)) {
55
+ for (const sub of item) {
56
+ processItem(sub);
57
+ }
58
+ } else if (typeof item === 'object') {
59
+ for (const [key, value] of Object.entries(item)) {
60
+ if (value === true || value == null) {
61
+ processItem(key);
62
+ } else if (typeof value === 'string' || Array.isArray(value)) {
63
+ const dotIndex = key.indexOf('.');
64
+ if (dotIndex === -1) {
65
+ addPath(key, value);
66
+ } else {
67
+ const top = key.slice(0, dotIndex);
68
+ const rest = key.slice(dotIndex + 1);
69
+ const nestedValues = Array.isArray(value) ? value : [value];
70
+ for (const v of nestedValues) {
71
+ addPath(top, `${rest}.${v}`);
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ }
78
+
79
+ const list = Array.isArray(relationNames) ? relationNames : [relationNames];
80
+ for (const item of list) {
81
+ processItem(item);
82
+ }
83
+
84
+ return tree;
85
+ }
86
+
87
+ /**
88
+ * Load relations for a set of records using batch queries (supports nested relations)
12
89
  * @param {Object[]} records - Records to load relations for
13
- * @param {string[]} relationNames - Names of relations to load
90
+ * @param {Array<string|Object>} relationNames - Names of relations to load (e.g. ['author.profile', 'comments.author'])
14
91
  * @param {import('./types').ModelDefinition} model - Model definition
15
92
  * @param {import('knex').Knex|import('knex').Knex.Transaction} knex - Knex instance
16
93
  * @param {import('./types').ScopeContext} [scopeContext] - Scope context
17
94
  * @returns {Promise<Object[]>} Records with relations attached
18
95
  */
19
96
  async function loadRelations(records, relationNames, model, knex, scopeContext) {
20
- if (!records.length || !relationNames.length) {
97
+ if (!records || !records.length || !relationNames || !relationNames.length) {
21
98
  return records;
22
99
  }
23
100
 
24
101
  const context = scopeContext || createScopeContext();
102
+ const tree = parseRelationTree(relationNames);
25
103
 
26
- // Process each relation
27
- for (const relationName of relationNames) {
28
- const relation = model.relations[relationName];
104
+ // Process each relation grouped by top-level
105
+ for (const [relationName, nestedPaths] of tree.entries()) {
106
+ const relation = model.relations?.[relationName];
29
107
  if (!relation) {
30
108
  console.warn(`Relation "${relationName}" not found on model "${model.name}"`);
31
109
  continue;
@@ -43,6 +121,38 @@ async function loadRelations(records, relationNames, model, knex, scopeContext)
43
121
  case 'hasOne':
44
122
  await loadHasOne(records, relationName, localKey, foreignKey, relatedModel, knex, context);
45
123
  break;
124
+ default:
125
+ console.warn(`Unsupported relation type "${relation.type}" for relation "${relationName}" on model "${model.name}"`);
126
+ continue;
127
+ }
128
+
129
+ // Process nested relations if any
130
+ if (nestedPaths.length > 0) {
131
+ const childRecords = [];
132
+ const seenRefs = new Set();
133
+ const len = records.length;
134
+
135
+ for (let i = 0; i < len; i++) {
136
+ const child = records[i][relationName];
137
+ if (!child) continue;
138
+
139
+ if (Array.isArray(child)) {
140
+ for (let j = 0; j < child.length; j++) {
141
+ const item = child[j];
142
+ if (item && typeof item === 'object' && !seenRefs.has(item)) {
143
+ seenRefs.add(item);
144
+ childRecords.push(item);
145
+ }
146
+ }
147
+ } else if (typeof child === 'object' && !seenRefs.has(child)) {
148
+ seenRefs.add(child);
149
+ childRecords.push(child);
150
+ }
151
+ }
152
+
153
+ if (childRecords.length > 0) {
154
+ await loadRelations(childRecords, nestedPaths, relatedModel, knex, context);
155
+ }
46
156
  }
47
157
  }
48
158
 
@@ -116,6 +226,14 @@ async function loadBelongsTo(records, relationName, localKey, foreignKey, relate
116
226
  relatedModel
117
227
  );
118
228
 
229
+ const jsonCols = getJsonColumns(relatedModel);
230
+ if (jsonCols.size > 0) {
231
+ const rLen = relatedRecords.length;
232
+ for (let i = 0; i < rLen; i++) {
233
+ deserializeJsonFields(relatedRecords[i], jsonCols);
234
+ }
235
+ }
236
+
119
237
  const relatedMap = new Map();
120
238
  const rLen = relatedRecords.length;
121
239
  const pk = relatedModel.primaryKey;
@@ -171,6 +289,14 @@ async function loadHasMany(records, relationName, localKey, foreignKey, relatedM
171
289
  relatedModel
172
290
  );
173
291
 
292
+ const jsonCols = getJsonColumns(relatedModel);
293
+ if (jsonCols.size > 0) {
294
+ const rLen = relatedRecords.length;
295
+ for (let i = 0; i < rLen; i++) {
296
+ deserializeJsonFields(relatedRecords[i], jsonCols);
297
+ }
298
+ }
299
+
174
300
  const relatedGroups = new Map();
175
301
  const rLen = relatedRecords.length;
176
302
  for (let i = 0; i < rLen; i++) {
@@ -229,6 +355,14 @@ async function loadHasOne(records, relationName, localKey, foreignKey, relatedMo
229
355
  relatedModel
230
356
  );
231
357
 
358
+ const jsonCols = getJsonColumns(relatedModel);
359
+ if (jsonCols.size > 0) {
360
+ const rLen = relatedRecords.length;
361
+ for (let i = 0; i < rLen; i++) {
362
+ deserializeJsonFields(relatedRecords[i], jsonCols);
363
+ }
364
+ }
365
+
232
366
  const relatedMap = new Map();
233
367
  const rLen = relatedRecords.length;
234
368
  for (let i = 0; i < rLen; i++) {
@@ -247,9 +381,9 @@ async function loadHasOne(records, relationName, localKey, foreignKey, relatedMo
247
381
  }
248
382
 
249
383
  /**
250
- * Load a single relation for a single record
384
+ * Load a single relation (or nested relation path) for a single record
251
385
  * @param {Object} record - Record to load relation for
252
- * @param {string} relationName - Name of relation to load
386
+ * @param {string} relationName - Name or dot-separated path of relation to load (e.g. 'author.profile')
253
387
  * @param {import('./types').ModelDefinition} model - Model definition
254
388
  * @param {import('knex').Knex} knex - Knex instance
255
389
  * @param {import('./types').ScopeContext} [scopeContext] - Scope context
@@ -267,5 +401,5 @@ module.exports = {
267
401
  loadHasMany,
268
402
  loadHasOne,
269
403
  queryInChunks,
404
+ parseRelationTree,
270
405
  };
271
-
package/core/orm/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  const path = require('path');
8
8
  const fs = require('fs');
9
9
  const { createSchemaHelpers, extractColumnsFromSchema, getColumnMeta } = require('./schema-helpers');
10
- const { defineModel, getModel, getAllModels, hasModel, clearRegistry, resolveModelName } = require('./model');
10
+ const { defineModel, getModel, getAllModels, hasModel, clearRegistry, resolveModelName, isCascadeEnabled } = require('./model');
11
11
  const { createRepository } = require('./repository');
12
12
  const { createMigrationManager } = require('./migrations');
13
13
  const { createSeeder } = require('./seeder');
@@ -358,6 +358,7 @@ module.exports = {
358
358
  getAllModels,
359
359
  hasModel,
360
360
  clearRegistry,
361
+ isCascadeEnabled,
361
362
  // Column utilities
362
363
  extractColumnsFromSchema,
363
364
  getColumnMeta,
@@ -372,9 +373,17 @@ module.exports = {
372
373
  Hooks,
373
374
  HookCancellationError,
374
375
  createEventContext,
376
+ // Eager loading & nested relations
377
+ loadRelations: require('./eager-loader').loadRelations,
378
+ loadRelation: require('./eager-loader').loadRelation,
379
+ parseRelationTree: require('./eager-loader').parseRelationTree,
375
380
  // Query Complexity & DoS Protection
376
381
  QueryComplexityError: require('./complexity').QueryComplexityError,
377
382
  validateQueryComplexity: require('./complexity').validateQueryComplexity,
378
383
  resolveQueryLimits: require('./complexity').resolveQueryLimits,
379
384
  DEFAULT_QUERY_LIMITS: require('./complexity').DEFAULT_QUERY_LIMITS,
385
+ // Universal Full-Text Search
386
+ buildSearchClause: require('./search').buildSearchClause,
387
+ tokenizeSearchTerm: require('./search').tokenizeSearchTerm,
388
+ detectDialect: require('./search').detectDialect,
380
389
  };
package/core/orm/model.js CHANGED
@@ -33,6 +33,7 @@ function defineModel(options) {
33
33
  hidden = [],
34
34
  queryLimits = {},
35
35
  cache: cacheOption,
36
+ searchable,
36
37
  } = options;
37
38
 
38
39
  // Validate required fields
@@ -82,7 +83,21 @@ function defineModel(options) {
82
83
  );
83
84
  }
84
85
 
85
- normalizedRelations[relationName] = relation;
86
+ if (relation.cascade !== undefined && relation.cascade !== null) {
87
+ const validCascade = typeof relation.cascade === 'boolean' ||
88
+ typeof relation.cascade === 'string' ||
89
+ Array.isArray(relation.cascade) ||
90
+ (typeof relation.cascade === 'object' && relation.cascade !== null);
91
+ if (!validCascade) {
92
+ throw new Error(
93
+ `Invalid cascade option for relation "${relationName}" in model "${name}". Must be boolean, string, array, or object.`
94
+ );
95
+ }
96
+ }
97
+
98
+ normalizedRelations[relationName] = {
99
+ ...relation,
100
+ };
86
101
  }
87
102
 
88
103
  // Create model definition
@@ -131,6 +146,9 @@ function defineModel(options) {
131
146
  allowInclude: Array.isArray(rest.allowInclude) ? rest.allowInclude.filter((x) => typeof x === 'string') : null,
132
147
  },
133
148
  hidden: Array.isArray(hidden) ? hidden : [],
149
+ searchable: Array.isArray(searchable)
150
+ ? searchable
151
+ : (Array.isArray(admin.searchFields) ? admin.searchFields : null),
134
152
  queryLimits: typeof queryLimits === 'object' && queryLimits !== null ? queryLimits : {},
135
153
  hooks: {},
136
154
  cache: cacheOption,
@@ -273,6 +291,41 @@ function getRelationKeys(model, relationName) {
273
291
  };
274
292
  }
275
293
 
294
+ /**
295
+ * Check if a relation has cascade enabled for a given operation ('delete' or 'restore')
296
+ * @param {import('./types').RelationDefinition} relation - Relation definition
297
+ * @param {'delete'|'restore'} operation - Operation to check
298
+ * @returns {boolean}
299
+ */
300
+ function isCascadeEnabled(relation, operation) {
301
+ if (!relation || relation.cascade === undefined || relation.cascade === null) {
302
+ return false;
303
+ }
304
+ const { cascade } = relation;
305
+ if (cascade === true) {
306
+ return true;
307
+ }
308
+ if (cascade === false) {
309
+ return false;
310
+ }
311
+ const op = String(operation).toLowerCase();
312
+ if (typeof cascade === 'string') {
313
+ const c = cascade.toLowerCase();
314
+ return c === op || c === 'all';
315
+ }
316
+ if (Array.isArray(cascade)) {
317
+ return cascade.some(item => {
318
+ if (typeof item !== 'string') return false;
319
+ const c = item.toLowerCase();
320
+ return c === op || c === 'all';
321
+ });
322
+ }
323
+ if (typeof cascade === 'object' && cascade !== null) {
324
+ return Boolean(cascade[op]);
325
+ }
326
+ return false;
327
+ }
328
+
276
329
  module.exports = {
277
330
  defineModel,
278
331
  getModel,
@@ -283,6 +336,7 @@ module.exports = {
283
336
  resolveModelName,
284
337
  resolveRelationModel,
285
338
  getRelationKeys,
339
+ isCascadeEnabled,
286
340
  // Export registry for testing
287
341
  _registry: modelRegistry,
288
342
  };
@@ -15,6 +15,7 @@ const {
15
15
  } = require('./json-fields');
16
16
  const { getAmbientTransaction } = require('./transaction');
17
17
  const { validateQueryComplexity } = require('./complexity');
18
+ const { buildSearchClause } = require('./search');
18
19
 
19
20
  /**
20
21
  * Create a new query builder
@@ -232,6 +233,70 @@ class QueryBuilder {
232
233
  return this;
233
234
  }
234
235
 
236
+ /**
237
+ * Add a raw ORDER BY clause
238
+ * @param {string} sql - Raw SQL expression
239
+ * @param {Array} [bindings=[]] - Parameter bindings
240
+ * @returns {this}
241
+ */
242
+ orderByRaw(sql, bindings = []) {
243
+ this.state.orderBys.push({ raw: true, sql, bindings });
244
+ return this;
245
+ }
246
+
247
+ /**
248
+ * Full-Text / Keyword Search across columns
249
+ * Supports SQLite, PostgreSQL, and MySQL with dialect-aware FTS and tokenized LIKE fallback
250
+ * @param {string} term - Search query string
251
+ * @param {string|string[]} [columns] - Columns to search (defaults to model.searchable)
252
+ * @param {Object} [options] - Search options
253
+ * @param {'auto'|'fts'|'like'} [options.mode='auto'] - Search mode
254
+ * @param {string} [options.language='english'] - PostgreSQL text search language
255
+ * @param {boolean} [options.matchAllWords=true] - Require all words to match (AND)
256
+ * @param {boolean} [options.exact=false] - Match exact phrase
257
+ * @param {boolean} [options.rank=false] - Order by relevance rank (Postgres)
258
+ * @param {string} [options.ftsTable] - Separate SQLite FTS virtual table name
259
+ * @returns {this}
260
+ */
261
+ search(term, columns, options = {}) {
262
+ const activeKnex = this.getActiveKnex();
263
+ const clause = buildSearchClause({
264
+ knex: activeKnex,
265
+ model: this.model,
266
+ term,
267
+ columns,
268
+ options,
269
+ });
270
+
271
+ if (!clause) {
272
+ return this;
273
+ }
274
+
275
+ this.state.wheres.push({
276
+ raw: true,
277
+ sql: clause.sql,
278
+ bindings: clause.bindings,
279
+ boolean: clause.boolean || 'and',
280
+ });
281
+
282
+ if (clause.rankClause) {
283
+ this.orderByRaw(clause.rankClause.sql, clause.rankClause.bindings);
284
+ }
285
+
286
+ return this;
287
+ }
288
+
289
+ /**
290
+ * Add an OR Full-Text / Keyword Search clause
291
+ * @param {string} term - Search query string
292
+ * @param {string|string[]} [columns] - Columns to search
293
+ * @param {Object} [options] - Search options
294
+ * @returns {this}
295
+ */
296
+ orSearch(term, columns, options = {}) {
297
+ return this.search(term, columns, { ...options, boolean: 'or' });
298
+ }
299
+
235
300
  /**
236
301
  * Set LIMIT
237
302
  * @param {number} limit - Limit value
@@ -265,6 +330,15 @@ class QueryBuilder {
265
330
  return this;
266
331
  }
267
332
 
333
+ /**
334
+ * Add relations to eager load (alias for with)
335
+ * @param {...string} relations - Relation names or nested paths (e.g. 'author.profile')
336
+ * @returns {this}
337
+ */
338
+ include(...relations) {
339
+ return this.with(...relations);
340
+ }
341
+
268
342
  /**
269
343
  * Include soft-deleted records
270
344
  * @returns {this}
@@ -376,7 +450,11 @@ class QueryBuilder {
376
450
 
377
451
  // Apply order by
378
452
  for (const orderBy of this.state.orderBys) {
379
- qb = qb.orderBy(orderBy.column, orderBy.direction);
453
+ if (orderBy.raw) {
454
+ qb = qb.orderByRaw(orderBy.sql, orderBy.bindings);
455
+ } else {
456
+ qb = qb.orderBy(orderBy.column, orderBy.direction);
457
+ }
380
458
  }
381
459
 
382
460
  if (includeLimitOffset) {
@@ -416,7 +494,7 @@ class QueryBuilder {
416
494
 
417
495
  const withs = self.getWiths();
418
496
  if (withs.length > 0) {
419
- await loadRelations([result], ensureArray(withs), self.model, self.knex, self.scopeContext);
497
+ await loadRelations([result], ensureArray(withs), self.model, self.getActiveKnex(), self.scopeContext);
420
498
  }
421
499
 
422
500
  ModelEvents.emit(self.model.name, Hooks.AFTER_FIND, result, ctx);
@@ -482,7 +560,7 @@ class QueryBuilder {
482
560
 
483
561
  const withs = self.getWiths();
484
562
  if (withs.length > 0 && results.length > 0) {
485
- await loadRelations(results, ensureArray(withs), self.model, self.knex, self.scopeContext);
563
+ await loadRelations(results, ensureArray(withs), self.model, self.getActiveKnex(), self.scopeContext);
486
564
  }
487
565
 
488
566
  for (const record of results) {
@@ -527,6 +605,14 @@ class QueryBuilder {
527
605
  return this.list();
528
606
  }
529
607
 
608
+ /**
609
+ * Alias for list()
610
+ * @returns {Promise<Object[]>}
611
+ */
612
+ async find() {
613
+ return this.list();
614
+ }
615
+
530
616
  /**
531
617
  * Execute query and return count
532
618
  * @returns {Promise<number>}
@@ -613,7 +699,7 @@ class QueryBuilder {
613
699
 
614
700
  const withs = self.getWiths();
615
701
  if (withs.length > 0 && data.length > 0) {
616
- await loadRelations(data, ensureArray(withs), self.model, self.knex, self.scopeContext);
702
+ await loadRelations(data, ensureArray(withs), self.model, self.getActiveKnex(), self.scopeContext);
617
703
  }
618
704
 
619
705
  for (const record of data) {