Skip to content

Commit

Permalink
added error for relatedQueries ommiting 'for' outside subqueries (#1895)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahamed-Belkheir authored Jul 6, 2023
1 parent 03c3cf7 commit 119ece2
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/relations/RelationOwner.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,10 @@ function isQueryBuilder(item) {

function findFirstNonPartialAncestorQuery(builder) {
builder = builder.parentQuery();

if (!builder)
throw Error(
'query method `for` ommitted outside a subquery, can not figure out relation target'
);
while (builder.isPartial()) {
if (!builder.parentQuery()) {
break;
Expand Down
78 changes: 78 additions & 0 deletions tests/integration/misc/relatedQueryErrors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const { expect } = require('chai');
const { Model } = require('../../../');

module.exports = session => {
describe('model relatedQueries fail when they lack a proper target', () => {
let knex = session.knex;

class Post extends Model {
static get tableName() {
return 'posts';
}
}

class User extends Model {
static get tableName() {
return 'users';
}
static get relationMappings() {
return {
posts: {
modelClass: Post,
relation: Model.HasManyRelation,
join: {
from: 'users.id',
to: 'posts.user_id'
}
}
};
}
}

before(async () => {
const knex = session.knex;

await knex.schema.dropTableIfExists('posts');
await knex.schema.dropTableIfExists('users');

await knex.schema
.createTable('users', table => {
table.increments('id').primary();
table.string('name');
})
.createTable('posts', table => {
table.increments('id').primary();
table
.integer('user_id')
.unsigned()
.references('id')
.inTable('users');
table.string('content');
});
});

after(async () => {
await knex.schema.dropTableIfExists('posts');
await knex.schema.dropTableIfExists('users');
});

it('relatedQuery insert does not silently fail when ommiting `for` a target', async () => {
try {
await User.relatedQuery('posts', knex).insert({ content: 'my post content' });
} catch (e) {
expect(e.message).to.equal(
'query method `for` ommitted outside a subquery, can not figure out relation target'
);
}
});
it('relatedQuery where fails when `for` is ommited and is not a subquery', async () => {
try {
await User.relatedQuery('posts', knex).where({ content: 'my post content' });
} catch (e) {
expect(e.message).to.equal(
'query method `for` ommitted outside a subquery, can not figure out relation target'
);
}
});
});
};

0 comments on commit 119ece2

Please sign in to comment.