[Proposal] Stand-alone Where Clauses
See original GitHub issueI wanted to bounce a feature idea off the community here.
I think it’d be nice to have standalone where clauses that you could pass around. My proposal for the API would be:
var whereClause = knex.where({state: 'CA'});
knex.select().from('users').where(whereClause);
The purpose here would be the ability to pass where clauses into functions. So you could make a function that looks like this:
var getUsers = function(whereClause){
return knex.select().from('users').where(whereClause);
};
and then call it with:
getUsers(knex.where({state:'CA'}));
(Obviously, this would be a useless abstraction - just trying to keep the example simple)
I, personally, have a use case where this functionality would be useful. In the example above, the solution might be to just getUsers().where({state:'CA'}) but for my use case, the where clause is actually applied to a subquery.
I currently solve the problem by defining the function like so:
var getUsers = function(userSelector){
return knex.select().from('users').whereIn('username', userSelector);
};
and then executing it like so:
getUsers(knex.select('username').from('users').where({state: 'CA'})
(I realize that this solution has potential drawbacks but, for my use case, they’re not significant)
Issue Analytics
- State:
- Created 7 years ago
- Reactions:4
- Comments:8 (8 by maintainers)

Top Related StackOverflow Question
I agree. It’s a subtle difference but I do think the pull request remains a worthy improvement to the code base. As we’ve demonstrated, it’s not new functionality but it makes the API cleaner, IMO. I think the difference is most significant when building up where clauses. Here’s the before/after of that use-case:
Before:
After:
It’s not all that much less code but I would say the code is far cleaner and more readable.
For my use case, this difference is exacerbated by conditional where clauses, where I want to scope a query only under certain conditions.
#2673 could potentially be used for this if merged. Alternatively a similar solution could be added to handle builders in
.where:But there are probably lots of edge cases to consider, I’m guessing… For example that would also allow and update/insert sql builder to be used in
.wherewhich would most likely break.