From e3c660b9b91630e7db46fe8341a490ed32c0df9d Mon Sep 17 00:00:00 2001 From: Maciej Holyszko <14310995+falkenhawk@users.noreply.github.com> Date: Thu, 22 Dec 2022 16:27:33 +0100 Subject: [PATCH] fix: overwriting already existing query's context in `childQueryOf` This is a fix for an edge case, where a query context could be already set in a `Model.query()` call or in a custom QueryBuilder's constructor. In our case we are defining columns with a custom `@DefaultOrderBy(columns)` decorator, they are stored to query's context after query builder is instantiated, and eventually are read in `query.onBuild()` hook to apply sorting for a query, if none other was provided to it in the meantime. But when coupled with fetching graphs, where both parent and children models have `@DefaultOrderBy` configured, child model's query context (eager query to fetch models for a relation) was being completely overwritten with parent's query context, and that, in our case, resulted in using invalid columns to be passed to `orderBy()`, resulting in a sql error. --- lib/queryBuilder/QueryBuilderOperationSupport.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/queryBuilder/QueryBuilderOperationSupport.js b/lib/queryBuilder/QueryBuilderOperationSupport.js index 4c7159bdf..090ec60be 100644 --- a/lib/queryBuilder/QueryBuilderOperationSupport.js +++ b/lib/queryBuilder/QueryBuilderOperationSupport.js @@ -153,6 +153,7 @@ class QueryBuilderOperationSupport { childQueryOf(query, { fork, isInternalQuery } = {}) { if (query) { + let currentCtx = this.context(); let ctx = query.internalContext(); if (fork) { @@ -165,6 +166,7 @@ class QueryBuilderOperationSupport { this._parentQuery = query; this.internalContext(ctx); + this.context(currentCtx); // Use the parent's knex if there was no knex in `ctx`. if (this.unsafeKnex() === null) {