Repository navigation
Description
Introduction
Dynamic queries are a pretty common usecase, for example when filtering through records.
Here are some workarounds which have been used so far:
1. checking for NULL first
SELECT * FROM table WHERE ($1::type IS NULL OR $1 = column)with this, the
WHEREclause is always present and can be checked during compile-time, but it only does something when$1isSome. Obviously, this only works in very specific cases.
2. writing the query out multiple times
I've seen people write out each permutation of the query by hand. This preserves compile-time checking, but results in a lot of repetition.
Personally, I've written declarative macros which factor out common parts, avoiding repetition. But that's not great to maintain, either.
3. ditching compile-time checking
The obvious solution is to just not use compile-time checking and go for the query functions instead of the macros.
Apart from losing the compile-time checks, this requires adding a lot ofFromRowimplementations in a codebase which would otherwise not need them.
Proposal
I propose the addition of a new macro, which automates workaround 2.
The macro would accept a much richer syntax compared to query! or query_as!, allowing the use of if and match.
A call would then expand to query!/query_as! calls for every permutation of the query, allowing all of them to be checked against the database at compile-time.
I attempted to implement this before here [example] [implementation] using macro_rules!.
While it does work, it has some heavy limitations, which often came up in the #ormx channel on discord.
A new implementation I started working uses a procedural macro and doesn't suffer from these limitations.
Here is an example of how using it currently looks like. The exact syntax is of course up for debate.
conditional_query_as!(
User,
"SELECT *"
"FROM users"
"WHERE"
"email =" ?query
"OR first_name LIKE" ?query
"OR last_name LIKE" ?query
"ORDER BY"
match order_by {
OrderBy::Name => "first_name",
OrderBy::UserId => "id"
}
match order {
Order::Ascending => "ASC",
Order::Descending => "DESC"
}
if let Some(limit) = limit {
"LIMIT" ?limit
}
).fetch_all(&db).await?;This currently expands to this:
if let Some(limit) = limit {
match order {
Order::Ascending => match order_by {
OrderBy::Name => ConditionalMap8::_1(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY first_name ASC LIMIT $4", query, query, query, limit)),
OrderBy::UserId => ConditionalMap8::_2(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY id ASC LIMIT $4", query, query, query, limit)),
},
Order::Descending => match order_by {
OrderBy::Name => ConditionalMap8::_3(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY first_name DESC LIMIT $4", query, query, query, limit)),
OrderBy::UserId => ConditionalMap8::_4(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY id DESC LIMIT $4", query, query, query, limit)),
},
}
} else {
match order {
Order::Ascending => match order_by {
OrderBy::Name => ConditionalMap8::_5(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY first_name ASC", query, query, query)),
OrderBy::UserId => ConditionalMap8::_6(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY id ASC", query, query, query)),
},
Order::Descending => match order_by {
OrderBy::Name => ConditionalMap8::_7(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY first_name DESC", query, query, query)),
OrderBy::UserId => ConditionalMap8::_8(sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1 OR first_name LIKE $2 OR last_name LIKE $3 ORDER BY id DESC", query, query, query)),
},
}
}Issues
With this approach, each generated call to query_as! must result in the same type.
Currently, this is solved by generating an enum, ConditionalMap8 in this case, which has 8 variants. Each of those variants wraps a sqlx::query::Map. Calling a function like fetch_all on ConditionalMap8 then does a match and redirects the call to the appropriate Map.
For something like conditional_query! (a conditional verison of query!), this approach is currently not possible since each call to query! returns a Map with an ad-hoc generated anonymous type. For this to work with query!, it would be necessarry that sqlx only ever generated one struct for a given set of columns such that the different calls to query! with slightly different queries would return Map with the same generated type.
@mehcode suggested a different approach - sqlx could just expose a macro to generate a struct for a given query. Then, conditional_query! could just be implemented as a wrapper around this macro and conditional_query_as!.
Activity
WIP: initial implementation of conditional_query_as! (transact-rs#1488)
abonander commentedon Oct 15, 2021
This is something that's been hotly requested for a long time. I'm interested, but I have a couple of comments:
I think this way, we at least have a chance of retaining some syntax highlighting in IDEs like CLion as we can make
{.*}get treated as a placeholder. It might not sophisticated enough to parse nested pairs of brackets though as I think it's just regex.NyxCode commentedon Oct 15, 2021
Syntax for branches and parameters
I think we need a slightly different syntax for branches (if/match).
This could either be interpreted as a branch or as just a
&strargument for the query. Maybe!match ..and!if ..for branches, idk, but there needs to be some way of differentiating them.Syntax highlighting
I'm not what the current state of this is, but with my current setup, clion does give me some rudimentary highlighting with the first approach, while none with the 2nd.
I haven't spent too much time thinking about this, but I would think seperating SQL string literals and arguments would make syntax highlighting easier, not harder.
Having branches & arguments inline in the string definetely requires special treatment by the IDE, while seperate arguments of a macro could be highlighted correctly by just properly supporting macros.
Here is what the first approach currently feels like in CLion:

And here is the 2nd:

I think I'd prefer the 1st one, but maybe that's just because Im used to it.
jplatte commentedon Oct 15, 2021
How about something like
using a special sigil like
#that's not valid in identifiers to denote that this isn't a regular bound parameter but rather an injection-prone part of the query string (and can't come from the surrounding scope like the inline parameters suggested in #875 will allow).NyxCode commentedon Oct 15, 2021
I like this a lot! Would also give nice syntax highlighting since not everything is in a big string literal
NyxCode commentedon Oct 15, 2021
@jplatte Though I'm not sure how nested branches would look like, maybe something like
?
jplatte commentedon Oct 15, 2021
EDIT: Initial idea doesn't work. Let me think more about it...
NyxCode commentedon Oct 26, 2021
I'm now at the point where I'm trying to figure out how to integrate this into
query_as!.Right now, the macro just calls
query_as!itself, so it's basically just a wrapper around that.My approach to this would just be to keep the old macro under a new name, and in calls to
query_as!, figure out ifold_query_as!orconditional_query_as!should be called.This is obviously more like a hack than a proper solution. That being said, I'm not familiar with the rest of the sqlx codebase and not sure how to properly integrate it.
I'd really appreciate if someone could take a look at what I did and how to integrate it into
query_as!.NyxCode commentedon Oct 27, 2021
EDIT: I have now made conditional_query_as! expand to
expand_query!and (hopefully) fully backwards compatible toquery_as!, which I replaced with the new proc macro. Let's see what the tests say.NyxCode commentedon Mar 2, 2022
#1491 now passes all tests, so it's backwards-compatible as far as the tests can tell.
While there is still quite some work to do regarding documentation, you can get an idea of how this works here
inline arguments
This currently supports the "basic" inline arguments of #875: Everything within
{..}will be interpreted as an argument. Every rust expression can be used here. Array parameters, as outlined in #875, are not included yet.NyxCode commentedon Mar 9, 2022
TODOs:
write more tests for the new functionality of thequery_as!macroTmLev commentedon Oct 15, 2022
Sorry for bumping, but are there any updates on this?
martijnarts commentedon Nov 18, 2022
@TmLev it's been commented on by @abonander, suggesting this won't happen: #1491 (comment)
kyrias commentedon Mar 14, 2023
Hey!
As this is no longer planned to be included in SQLx upstream we decided to implement it as a separate crate since we have a need for it. sqlx-conditional-queries (github).
vagra commentedon Jun 19, 2023
I fully support this proposal!
When I use string constants or macros to extract the first half of the query string, the compiler tells me that query_as! is not supported, but if I use query_as, it cannot check SQL statement errors at compile time. No way, I would rather copy the query statement than not have the compile-time check function.
TOO LONG my code:
tgross35 commentedon Feb 12, 2024
The argument against this seems to be the combinatorial explosion from checking all known values, which is reasonable. As an alternative, what about partially checked queries? That is, validate a portion of the query at compile time to get type information, but allow editing the query to fill in missing information.
Something like the following could be a possible API:
So, what happens is:
query_as!sees that there aredynamic!segments (syntax like{}would work too). It will delete these placeholders before sending the query to the database.Result<Vec<User>>directly, it returns a type that contains:a. The
Row -> Usermapping function/closureb. The base query string and binds, with
dynamic!segments removedc. Something with information about how to add string segments or binds.
[(&str, usize, usize); 2]withsqlx::Argumentsprobably needs to gain aninsertmethod to make this possible, or another trait added for dynamic argumentsfetch_allmakes sure that all dynamic keys were.set(even if null). The statement actually gets prepared here.The pattern would work well for cases where you don't want to change the columns, only apply refinement operations to the return dataset. This covers the main use cases -
ORDER BYsorting,WHEREfiltering,LIMIT/OFFSETtraditional pagination,WHEREcursor pagination,GROUP BYaggregation.The full dynamic query cannot be checked at compile time, but that is probably acceptable given the explosion problem mentioned above.
leebenson commentedon Jul 13, 2024
This is excellent, thank you!
Two small points: