Skip to content

Commit 93a926b

Browse files
committed
feat: add named binding parameters support
This implements the long-requested named binding parameters feature (closes transact-rs#199). Users can now write queries like: // Shorthand syntax (variable name matches parameter name) query!("SELECT * FROM users WHERE id = :id AND name = :name", id, name) // Explicit syntax query!("SELECT * FROM users WHERE id = :id", id = user_id) // Mixed query!("SELECT * FROM users WHERE id = :id AND name = :name", id, name = get_name()) Supported named parameter formats in SQL: - :name (colon prefix - common in Oracle, SQLite) - ?name (question mark prefix - custom) - @name (at prefix - SQL Server style) Key implementation details: - SQL parser correctly skips string literals, comments, and PostgreSQL cast operators (::) - Duplicate parameters in SQL reuse the same positional placeholder for PostgreSQL ($N) while MySQL/SQLite use separate ? placeholders - Named arguments validated against SQL parameters at compile time - Arguments automatically reordered to match SQL parameter order The implementation is fully backwards compatible - existing positional parameter usage continues to work unchanged.
1 parent 452da1a commit 93a926b

5 files changed

Lines changed: 834 additions & 13 deletions

File tree

‎sqlx-macros-core/src/query/input.rs‎

Lines changed: 179 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,67 @@ use proc_macro2::{Ident, Span};
44
use syn::parse::{Parse, ParseStream};
55
use syn::punctuated::Punctuated;
66
use syn::{Expr, LitBool, LitStr, Token};
7-
use syn::{ExprArray, Type};
7+
use syn::Type;
8+
9+
use super::named_params::{self, NamedArg, ParsedSql};
10+
11+
/// Represents either positional or named arguments.
12+
#[derive(Clone)]
13+
pub enum MacroArgs {
14+
/// Positional arguments in order.
15+
Positional(Vec<Expr>),
16+
/// Named arguments with name = value pairs.
17+
Named(Vec<NamedArg>),
18+
}
19+
20+
impl Default for MacroArgs {
21+
fn default() -> Self {
22+
MacroArgs::Positional(Vec::new())
23+
}
24+
}
25+
26+
impl MacroArgs {
27+
pub fn is_empty(&self) -> bool {
28+
match self {
29+
MacroArgs::Positional(v) => v.is_empty(),
30+
MacroArgs::Named(v) => v.is_empty(),
31+
}
32+
}
33+
34+
pub fn len(&self) -> usize {
35+
match self {
36+
MacroArgs::Positional(v) => v.len(),
37+
MacroArgs::Named(v) => v.len(),
38+
}
39+
}
40+
}
841

942
/// Macro input shared by `query!()` and `query_file!()`
1043
pub struct QueryMacroInput {
1144
pub(super) sql: String,
1245

46+
/// The SQL string after rewriting named parameters to positional.
47+
pub(super) rewritten_sql: Option<String>,
48+
49+
/// Parsed named parameters from the SQL.
50+
pub(super) parsed_sql: Option<ParsedSql>,
51+
1352
pub(super) src_span: Span,
1453

1554
pub(super) record_type: RecordType,
1655

56+
/// Arguments - either positional or named.
57+
pub(super) args: MacroArgs,
58+
59+
/// Positional argument expressions (after reordering if named).
1760
pub(super) arg_exprs: Vec<Expr>,
1861

1962
pub(super) checked: bool,
2063

2164
pub(super) file_path: Option<String>,
65+
66+
/// Whether this database uses $N notation (PostgreSQL) or ? notation (MySQL/SQLite).
67+
pub(super) use_dollar_notation: bool,
2268
}
2369

2470
enum QuerySrc {
@@ -35,7 +81,7 @@ pub enum RecordType {
3581
impl Parse for QueryMacroInput {
3682
fn parse(input: ParseStream) -> syn::Result<Self> {
3783
let mut query_src: Option<(QuerySrc, Span)> = None;
38-
let mut args: Option<Vec<Expr>> = None;
84+
let mut args: Option<MacroArgs> = None;
3985
let mut record_type = RecordType::Generated;
4086
let mut checked = true;
4187

@@ -61,8 +107,7 @@ impl Parse for QueryMacroInput {
61107
let lit_str = input.parse::<LitStr>()?;
62108
query_src = Some((QuerySrc::File(lit_str.value()), lit_str.span()));
63109
} else if key == "args" {
64-
let exprs = input.parse::<ExprArray>()?;
65-
args = Some(exprs.elems.into_iter().collect())
110+
args = Some(parse_args_array(input)?);
66111
} else if key == "record" {
67112
if !matches!(record_type, RecordType::Generated) {
68113
return Err(input.error("colliding `scalar` or `record` key"));
@@ -93,21 +138,149 @@ impl Parse for QueryMacroInput {
93138
let (src, src_span) =
94139
query_src.ok_or_else(|| input.error("expected `source` or `source_file` key"))?;
95140

96-
let arg_exprs = args.unwrap_or_default();
141+
let macro_args = args.unwrap_or_default();
97142

98143
let file_path = src.file_path(src_span)?;
144+
let sql = src.resolve(src_span)?;
145+
146+
// Parse SQL for named parameters
147+
let parsed_sql = named_params::parse_named_params(&sql);
148+
149+
// If SQL has named parameters, process them
150+
let (arg_exprs, rewritten_sql, parsed_sql_opt) = if parsed_sql.has_named_params() {
151+
match &macro_args {
152+
MacroArgs::Named(named_args) => {
153+
// Validate that all SQL params have args and vice versa
154+
named_params::validate_named_args(&parsed_sql, named_args)
155+
.map_err(|e| syn::Error::new(src_span, e))?;
156+
157+
// Reorder args to match SQL parameter order
158+
let exprs = named_params::reorder_args_by_sql_order(&parsed_sql, named_args)
159+
.map_err(|e| syn::Error::new(src_span, e))?;
160+
161+
// SQL will be rewritten when we know the database type
162+
(exprs, None, Some(parsed_sql))
163+
}
164+
MacroArgs::Positional(exprs) if exprs.is_empty() => {
165+
// No args provided but SQL has named params - error
166+
return Err(syn::Error::new(
167+
src_span,
168+
format!(
169+
"SQL contains named parameters ({}) but no named arguments provided. \
170+
Use `args = [name = value, ...]` syntax.",
171+
parsed_sql.unique_names.join(", ")
172+
),
173+
));
174+
}
175+
MacroArgs::Positional(_) => {
176+
// Positional args with named params in SQL - error
177+
return Err(syn::Error::new(
178+
src_span,
179+
"cannot use positional arguments with named parameters in SQL; \
180+
use `args = [name = value, ...]` syntax instead",
181+
));
182+
}
183+
}
184+
} else {
185+
// No named params in SQL
186+
match &macro_args {
187+
MacroArgs::Positional(exprs) => (exprs.clone(), None, None),
188+
MacroArgs::Named(named_args) if named_args.is_empty() => {
189+
(Vec::new(), None, None)
190+
}
191+
MacroArgs::Named(_) => {
192+
return Err(syn::Error::new(
193+
src_span,
194+
"named arguments provided but SQL contains no named parameters; \
195+
use `:name`, `?name`, or `@name` syntax in SQL",
196+
));
197+
}
198+
}
199+
};
99200

100201
Ok(QueryMacroInput {
101-
sql: src.resolve(src_span)?,
202+
sql,
203+
rewritten_sql,
204+
parsed_sql: parsed_sql_opt,
102205
src_span,
103206
record_type,
207+
args: macro_args,
104208
arg_exprs,
105209
checked,
106210
file_path,
211+
use_dollar_notation: false, // Will be set by the database-specific expansion
107212
})
108213
}
109214
}
110215

216+
/// Parse the args array, which can contain either:
217+
/// - Positional: `[expr1, expr2, ...]`
218+
/// - Named: `[name1 = expr1, name2 = expr2, ...]`
219+
/// - Shorthand named: `[name1, name2]` (equivalent to `[name1 = name1, name2 = name2]`)
220+
/// - Mixed: `[name1, name2 = expr2]`
221+
fn parse_args_array(input: ParseStream) -> syn::Result<MacroArgs> {
222+
let content;
223+
syn::bracketed!(content in input);
224+
225+
if content.is_empty() {
226+
return Ok(MacroArgs::Positional(Vec::new()));
227+
}
228+
229+
// Peek to determine if we have named or positional args
230+
// Named args look like: `ident = expr` or just `ident` (shorthand)
231+
// We detect named mode if the first token is an ident followed by `=` or `,` or end
232+
let is_named = {
233+
let fork = content.fork();
234+
if fork.parse::<Ident>().is_ok() {
235+
// It's named if followed by `=` (explicit) or `,`/end (shorthand)
236+
fork.peek(Token![=]) || fork.peek(Token![,]) || fork.is_empty()
237+
} else {
238+
false
239+
}
240+
};
241+
242+
if is_named {
243+
let mut named_args = Vec::new();
244+
while !content.is_empty() {
245+
let name: Ident = content.parse()?;
246+
247+
let expr = if content.peek(Token![=]) {
248+
// Explicit: `name = expr`
249+
let _: Token![=] = content.parse()?;
250+
content.parse()?
251+
} else {
252+
// Shorthand: `name` means `name = name`
253+
Expr::Path(syn::ExprPath {
254+
attrs: Vec::new(),
255+
qself: None,
256+
path: name.clone().into(),
257+
})
258+
};
259+
260+
named_args.push(NamedArg {
261+
name: name.to_string(),
262+
expr,
263+
});
264+
265+
if !content.is_empty() {
266+
let _: Token![,] = content.parse()?;
267+
}
268+
}
269+
Ok(MacroArgs::Named(named_args))
270+
} else {
271+
let exprs = Punctuated::<Expr, Token![,]>::parse_terminated(&content)?;
272+
Ok(MacroArgs::Positional(exprs.into_iter().collect()))
273+
}
274+
}
275+
276+
impl QueryMacroInput {
277+
/// Returns the effective SQL string to use for the query.
278+
/// If named parameters were rewritten, returns the rewritten SQL; otherwise the original.
279+
pub fn effective_sql(&self) -> &str {
280+
self.rewritten_sql.as_deref().unwrap_or(&self.sql)
281+
}
282+
}
283+
111284
impl QuerySrc {
112285
/// If the query source is a file, read it to a string. Otherwise return the query string.
113286
fn resolve(self, source_span: Span) -> syn::Result<String> {

‎sqlx-macros-core/src/query/mod.rs‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ mod cache;
2222
mod data;
2323
mod input;
2424
mod metadata;
25+
pub mod named_params;
2526
mod output;
2627

2728
#[derive(Copy, Clone)]
@@ -185,13 +186,31 @@ struct Warnings {
185186

186187
fn expand_with_data<DB: DatabaseExt>(
187188
config: &Config,
188-
input: QueryMacroInput,
189+
mut input: QueryMacroInput,
189190
data: QueryData<DB>,
190191
save_dir: Option<&Path>,
191192
) -> crate::Result<TokenStream>
192193
where
193194
Describe<DB>: DescribeExt,
194195
{
196+
// Determine if this database uses $N notation (PostgreSQL) or ? notation (MySQL/SQLite)
197+
let use_dollar_notation = DB::NAME == "PostgreSQL";
198+
input.use_dollar_notation = use_dollar_notation;
199+
200+
// Rewrite SQL if we have named parameters
201+
let effective_sql = if let Some(ref parsed_sql) = input.parsed_sql {
202+
parsed_sql.rewrite_sql(use_dollar_notation)
203+
} else {
204+
input.sql.clone()
205+
};
206+
207+
// Store the rewritten SQL
208+
input.rewritten_sql = if input.parsed_sql.is_some() {
209+
Some(effective_sql.clone())
210+
} else {
211+
None
212+
};
213+
195214
// validate at the minimum that our args match the query's input parameters
196215
let num_parameters = match data.describe.parameters() {
197216
Some(Either::Left(params)) => Some(params.len()),
@@ -200,10 +219,17 @@ where
200219
None => None,
201220
};
202221

222+
// For named params, we need to count unique param names, not total occurrences
223+
let expected_args = if let Some(ref parsed_sql) = input.parsed_sql {
224+
parsed_sql.unique_names.len()
225+
} else {
226+
input.arg_exprs.len()
227+
};
228+
203229
if let Some(num) = num_parameters {
204-
if num != input.arg_exprs.len() {
230+
if num != expected_args {
205231
return Err(
206-
format!("expected {} parameters, got {}", num, input.arg_exprs.len()).into(),
232+
format!("expected {} parameters, got {}", num, expected_args).into(),
207233
);
208234
}
209235
}
@@ -221,7 +247,7 @@ where
221247
.all(|it| it.type_info().is_void())
222248
{
223249
let db_path = DB::db_path();
224-
let sql = &input.sql;
250+
let sql = input.effective_sql();
225251

226252
quote! {
227253
::sqlx::__query_with_result::<#db_path, _>(#sql, #query_args)

0 commit comments

Comments
 (0)