You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Next] [Feature] Generalized query placeholders (including support for expanding arrays into multiple placeholders) #875
@abonander and I have been discussing the benefits of providing a more Python style of SQL placeholders for parameters
In Python database connectors, it looks like this:
conn.execute("SELECT %(name)s", name="Hello")
The connector takes care of:
Using ?, $1, or @p1 depending on the database driver
Expanding arrays into ?, ?, ?, ...
Allowing named parameters where none are supported such as PostgreSQL
The really interesting part is Intellij understands that %(name)s is a SQL parameter and correctly parses that query and still provides proper code completion ( as a side note, Intellij Rust recently gained support for SQL highlighting and code completion inside of sqlx::query! ).
We are proposing that we add support for the following ( both in query! and query ):
Positional Parameter
// "SELECT ?" in MySQL// "SELECT $1" in PostgreSQL
sqlx::query!("SELECT {0}",10);
Named Parameter
// "SELECT @id" in MSSQL// "SELECT $id" in SQLite// "SELECT $1" in PostgreSQL
sqlx::query!("SELECT {id}", id=10);
Inline Parameter (only macros)
// "SELECT @id" in MSSQL// "SELECT $id" in SQLite// "SELECT $1" in PostgreSQLlet id = 10;
sqlx::query!("SELECT {id}");
Array Parameter
// MySQL = "SELECT * FROM foo WHERE id IN (?, ?, ?, ...)"// PostgreSQL = "SELECT * FROM foo WHERE id IN ($1, $2, $3, ...)"
sqlx::query!("SELECT * FROM foo WHERE id IN ({ids+})", ids=[1,2,3]);
{ids+} or {ids*} becomes a comma-delimited list of parameters
{ids+} for a 0 length array becomes NULL
{ids*} for a 0 length array becomes `` (nothing)
I was on the fence about doing something like this but we can teach Intellij to recognize {...} as a SQL parameter which would let Intellij continue to parse and provide completion in our SQL queries.
Thoughts?
Reacted by Elina, Jeffrey Lin, Austin Bonander, philippeitis, Raphaël Thériault, Dustin Bensing, Nikolay Arhipov, 明昌, Maxime Gauduin, Robin Appelman and 107 more
Reacted by Rakshith Ravi, Jonathan de Jong, Diego Stratta, Phillip Samuel K., Luca Palmieri, Serhii Potapov, Dustin Bensing, Virgiel, Ltrlg, Andrew Wheeler(Genusis) and 25 more
I think that 90% of my uses of this are going to be {(foo.bar)} or {(foo.bar.baz)}. But since it's backwards-compatible to allow this without the extra parentheses later on, it seems fine to start without that.
The IN ({ids*}) syntax would be a god send for Sqlite in particular.
I wonder if it would be possible to add a minimal extensions of this syntax for INSERT as well?
I'd like to insert all the fields of a struct succinctly - as a nice ergonomic for developers who want to prototyping quickly and leave choosing specific fields as a later optimization.
Perhaps if there was a way to generate 'static str or const column names via a macro they could be expanded into the query at compile time?
#[derive(sqlx::Columns)]structFoo{a:i32,b:i32,c:i32}let foo = Foo{a:1,b:2,c:3};let values = foo.column_values();// INSERT INTO foos (a, b, c) VALUES (?, ? ,?)
sqlx::query!("INSERT INTO foos ({Foo::COLUMNS*}) VALUES (values*)");
@D1plo1d I would probably prefer something a little less implicit like the following: #591
That would work okay with this proposal, although if you use the ...foo syntax we'll have to disable the ability to implicitly bind variables from the scope for that query (since we can't know whether to generate code to get a given bind parameter from foo or from the surrounding scope).
However, we can't implicitly expand the column list from the fields of foo while maintaining the guarantees of query!() as there's no way to get the fields of Foo in a proc macro without some hacky side-channel communication between #[derive(sqlx::Columns)] and sqlx::query!() (which I realize is the pot calling the kettle black in this situation but I'd prefer to limit the hackiness where possible).
Is there any update to when this might be implemented, or alternatively what blockers currently exist for implementation?
I have a use-case of passing a vec of arguments for a WHERE x IN (?) clause with SQLite and cannot use the listed postgres workaround due to the database type, this feature would be incredibly helpful towards that goal.
Reacted by Isaac de Andrade, Brandon Thomas, Dave, Maxim Matyunin, Josef, Jess, Tommaso A, Jeff Parsons, d4h0, madadam and 32 more
Reacted by Brandon Thomas, Jonathan Moore, vszakd, Steve Marin and Brent George
Not being able to use WHERE ... IN (?) in SQLite makes it really hard to batch WHERE operations (for example in a data loader). With Postgres it works fine because of ANY($1).
let a = 1;structB{b:i32}let b = B{b:2};let c = "A";let d = vec![3,4,5];let query = sea_query::raw_query!(PostgresQueryBuilder,r#"SELECT ("size_w" + {a}) * {b.b} FROM "glyph" WHERE "image" LIKE {c} AND "id" IN ({..d})"#);assert_eq!(
query.sql,r#"SELECT ("size_w" + $1) * $2 FROM "glyph" WHERE "image" LIKE $3 AND "id" IN ($4, $5, $6)"#);assert_eq!(
query.values,Values(vec![1.into(),2.into(),"A".into(),3.into(),4.into(),5.into()]));
Reacted by Paul Hansen, ForgQi, Filip "botafi" Botai, Vlad Stepanov, Luca Barbato, Jacob-32587 and Ross Sullivan
Having many positional parameters in a query with no way to name them is not only unsafe, it is dangerous.
(So why haven't the Postgres authors implemented this in the latest version of the wire protocol to save hundreds of client libraries from re-inventing the wheel?)
Granted: sqlx is one of the few libraries in any language that supports compile-time query checking, and the difficulty of implemention of this feature cannot be overstated.
I don't know the primary drivers for this project, but have the authors of this library ever experienced the following (albeit oversimplified) kind of frustration?
This feature request is 5 years old. Seems like a "lifetime" to me in this ecosystem.
What will it take? The community needs safe, named parameters! Is this something contributors can collaborate on? Granted, LLMs are still primitive, stupid, often wrong, and frustrating to work with, but I've successfully used them in a couple of forks of major crates (thiserror -> wherror, tracing_subscriber -> better_tracing) to implement seemingly difficult features that the authors could not or would not implement, and that were beyond my ability given time constraints to figure out.
It's not wrong to try throwing a couple of LLMs on the codebase and getting suggestions on how to implement something like this, if that's the hurdle.
Imagine how much time this feature would save in production codebases. It would certainly make up the development time many times over. SQL was invented in the 1980s, when parameter names would take up too much memory! It's almost 2026, we have the tools and the power to achieve this! And since format_args! can successfully take named parameters, why not the sqlx macros?
Can't sqlx::query! and friends just rewrite the names to numbers internally based on their order in the query or something?
Reacted by Pascal Poredda
Reacted by Jonas Platte, Luca Barbato, Alexander van Saase, quasi-coherent, Mike Burns and Lynn
I wanted a few features in SQLx that don't exist yet: named parameters, array expansion for IN clauses, dynamic sections, and more. Since SQLx focuses on being a low-level driver interface with compile-time query checking as its backbone, I built a macro on top of it to fill these gaps.
I've been using it internally in my project and recently released it as a standalone crate:
I based my implementation on a similar syntax, but use a smart cycling strategy that generates at most N SQL variants (where N is the largest match arm count), avoiding exponential blowup. This means every individual case is validated, though not all combinations are. For virtually all real-world use cases this works fine.
At runtime, the macro uses a dynamic sqlx QueryBuilder that executes exactly the code you provide, so there's no limitation on what logic you can express.
A dynamic section looks like:
sql_forge!(User,"SELECT * FROM users {#join_org} {#filter_org}",(
#(join_org, filter_org) = match include_org {true => (" JOIN organisations o ON o.id = users.org_id ",(" AND o.active = :active ",(:active = true),),),false => ("",""),}))
For the empty-array case, I don't try to transform the SQL itself (e.g. turning WHERE field IN (...) into WHERE 1 = 0 or NULL), as that's error-prone. WHERE field NOT IN (...) with an empty array should become WHERE 1 = 1, using a generic NULL for empty arrays would probably behave in an unexpected way here, and handling each case would end up being a can of worms, solving one error, but creating 2 more. Instead, callers handle it early in the function when appropriate, or use a dynamic section:
let users:Vec<User> = sql_forge!(User,"SELECT id, name FROM users WHERE {#filter}",(
#filter = match ids.is_empty(){true => "1 = 0",false => ("id IN (:ids[])",(:ids = ids ),),})).fetch_all(&pool).await?;
The macro also supports multiple result groups and batch INSERTs with compile-time validation and less boilerplate.
I'd be happy to open a PR to integrate this into SQLx as a new macro if the maintainers are interested, so users could get these features without an external crate (after all, this uses sqlx under the hood). I built it because I genuinely wanted compile-time validation for cases that SQLx can't handle directly (yet).
Either way, the crate is available for anyone who wants to use it now. The last released version was tested and is working with the most recent sqlx version (0.9.0).
Activity
jplatte commentedon Dec 4, 2020
Big thumbs up from me 👍
If the inline form could also permit
{foo.bar}, that would be amazing!mehcode commentedon Dec 4, 2020
We should probably follow the syntax recommendation here if we want to allow expressions: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html#alternative-solution---interpolation
This also lets our Kleene operator work with these complex expressions:
jplatte commentedon Dec 4, 2020
I think that 90% of my uses of this are going to be
{(foo.bar)}or{(foo.bar.baz)}. But since it's backwards-compatible to allow this without the extra parentheses later on, it seems fine to start without that.D1plo1d commentedon Feb 8, 2021
The
IN ({ids*})syntax would be a god send for Sqlite in particular.I wonder if it would be possible to add a minimal extensions of this syntax for
INSERTas well?I'd like to insert all the fields of a struct succinctly - as a nice ergonomic for developers who want to prototyping quickly and leave choosing specific fields as a later optimization.
Perhaps if there was a way to generate
'static strorconstcolumn names via a macro they could be expanded into the query at compile time?abonander commentedon May 3, 2021
@D1plo1d I would probably prefer something a little less implicit like the following: #591
That would work okay with this proposal, although if you use the
...foosyntax we'll have to disable the ability to implicitly bind variables from the scope for that query (since we can't know whether to generate code to get a given bind parameter fromfooor from the surrounding scope).However, we can't implicitly expand the column list from the fields of
foowhile maintaining the guarantees ofquery!()as there's no way to get the fields ofFooin a proc macro without some hacky side-channel communication between#[derive(sqlx::Columns)]andsqlx::query!()(which I realize is the pot calling the kettle black in this situation but I'd prefer to limit the hackiness where possible).cbondurant commentedon Dec 12, 2022
Is there any update to when this might be implemented, or alternatively what blockers currently exist for implementation?
I have a use-case of passing a vec of arguments for a
WHERE x IN (?)clause with SQLite and cannot use the listed postgres workaround due to the database type, this feature would be incredibly helpful towards that goal.blagowtf commentedon Jul 13, 2023
I would love this as I'm currently writing a lot of code to manually trick indices for postgres. Having this done by name instead would be amazing
marvin-j97 commentedon Nov 28, 2023
Not being able to use
WHERE ... IN (?)in SQLite makes it really hard to batchWHEREoperations (for example in a data loader). With Postgres it works fine because ofANY($1).andrewgazelka commentedon May 22, 2025
Would funding this issue improve time to completion?
tyt2y3 commentedon Aug 14, 2025
Hi everyone, I've made a macro in SeaQuery - took some ideas from this discussion thread.
Would love your feedback, here is a write-up!
https://www.sea-ql.org/blog/2025-08-15-sea-query-raw-sql/
lu-zero commentedon Aug 25, 2025
@tyt2y3 if the proc_macro tightly bound to the sea-query internals or would be feasible to lift the mapping logic into the sqlx macros?
tyt2y3 commentedon Aug 25, 2025
the macro itself is not tightly coupled with sea-query, but the test cases are. so it requires some effort to port and maintain it separately.
tgrushka commentedon Oct 29, 2025
Having many positional parameters in a query with no way to name them is not only unsafe, it is dangerous.
(So why haven't the Postgres authors implemented this in the latest version of the wire protocol to save hundreds of client libraries from re-inventing the wheel?)
Granted: sqlx is one of the few libraries in any language that supports compile-time query checking, and the difficulty of implemention of this feature cannot be overstated.
I don't know the primary drivers for this project, but have the authors of this library ever experienced the following (albeit oversimplified) kind of frustration?
This feature request is 5 years old. Seems like a "lifetime" to me in this ecosystem.
What will it take? The community needs safe, named parameters! Is this something contributors can collaborate on? Granted, LLMs are still primitive, stupid, often wrong, and frustrating to work with, but I've successfully used them in a couple of forks of major crates (
thiserror->wherror,tracing_subscriber->better_tracing) to implement seemingly difficult features that the authors could not or would not implement, and that were beyond my ability given time constraints to figure out.It's not wrong to try throwing a couple of LLMs on the codebase and getting suggestions on how to implement something like this, if that's the hurdle.
Imagine how much time this feature would save in production codebases. It would certainly make up the development time many times over. SQL was invented in the 1980s, when parameter names would take up too much memory! It's almost 2026, we have the tools and the power to achieve this! And since
format_args!can successfully take named parameters, why not thesqlxmacros?Can't
sqlx::query!and friends just rewrite the names to numbers internally based on their order in the query or something?lucasbasquerotto commentedon May 29, 2026
I wanted a few features in SQLx that don't exist yet: named parameters, array expansion for IN clauses, dynamic sections, and more. Since SQLx focuses on being a low-level driver interface with compile-time query checking as its backbone, I built a macro on top of it to fill these gaps.
I've been using it internally in my project and recently released it as a standalone crate:
https://crates.io/crates/sql-forge
For example, to expand arrays into multiple placeholders (what this issue is about), I use:
I also wanted dynamic sections with compile-time safety. I found https://crates.io/crates/sqlx-conditional-queries, but for real-world projects it has a serious issue: the number of generated queries grows exponentially with the cartesian product of conditions.
I based my implementation on a similar syntax, but use a smart cycling strategy that generates at most N SQL variants (where N is the largest match arm count), avoiding exponential blowup. This means every individual case is validated, though not all combinations are. For virtually all real-world use cases this works fine.
At runtime, the macro uses a dynamic sqlx
QueryBuilderthat executes exactly the code you provide, so there's no limitation on what logic you can express.A dynamic section looks like:
For the empty-array case, I don't try to transform the SQL itself (e.g. turning
WHERE field IN (...)intoWHERE 1 = 0orNULL), as that's error-prone.WHERE field NOT IN (...)with an empty array should becomeWHERE 1 = 1, using a generic NULL for empty arrays would probably behave in an unexpected way here, and handling each case would end up being a can of worms, solving one error, but creating 2 more. Instead, callers handle it early in the function when appropriate, or use a dynamic section:The macro also supports multiple result groups and batch INSERTs with compile-time validation and less boilerplate.
I'd be happy to open a PR to integrate this into SQLx as a new macro if the maintainers are interested, so users could get these features without an external crate (after all, this uses sqlx under the hood). I built it because I genuinely wanted compile-time validation for cases that SQLx can't handle directly (yet).
Either way, the crate is available for anyone who wants to use it now. The last released version was tested and is working with the most recent sqlx version (0.9.0).