Skip to content

Commit c2e54ea

Browse files
cemoktraBastian Schubertabonander
authored
add args to query builder (#2494) (#2506)
* add args to query builder (#2494) * add test * Update sqlx-core/src/query_builder.rs Co-authored-by: Austin Bonander <[email protected]> * fmt --------- Co-authored-by: Bastian Schubert <[email protected]> Co-authored-by: Austin Bonander <[email protected]>
1 parent 3fdb79d commit c2e54ea

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

sqlx-core/src/query_builder.rs

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::fmt::Display;
44
use std::fmt::Write;
55
use std::marker::PhantomData;
66

7-
use crate::arguments::Arguments;
7+
use crate::arguments::{Arguments, IntoArguments};
88
use crate::database::{Database, HasArguments};
99
use crate::encode::Encode;
1010
use crate::from_row::FromRow;
@@ -49,6 +49,24 @@ where
4949
}
5050
}
5151

52+
/// Construct a `QueryBuilder` with existing SQL and arguments.
53+
///
54+
/// ### Note
55+
/// This does *not* check if `arguments` is valid for the given SQL.
56+
pub fn with_arguments<A>(init: impl Into<String>, arguments: A) -> Self
57+
where
58+
DB: Database,
59+
A: IntoArguments<'args, DB>,
60+
{
61+
let init = init.into();
62+
63+
QueryBuilder {
64+
init_len: init.len(),
65+
query: init,
66+
arguments: Some(arguments.into_arguments()),
67+
}
68+
}
69+
5270
#[inline]
5371
fn sanity_check(&self) {
5472
assert!(
@@ -635,4 +653,23 @@ mod test {
635653
"SELECT * FROM users WHERE id = 99"
636654
);
637655
}
656+
657+
#[test]
658+
fn test_query_builder_with_args() {
659+
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new("");
660+
661+
let query = qb
662+
.push("SELECT * FROM users WHERE id = ")
663+
.push_bind(42i32)
664+
.build();
665+
666+
let mut qb: QueryBuilder<'_, Postgres> =
667+
QueryBuilder::new_with(query.sql(), query.take_arguments());
668+
let query = qb.push("OR membership_level =").push_bind(3i32).build();
669+
670+
assert_eq!(
671+
query.sql(),
672+
"SELECT * FROM users WHERE id = $1 OR membership_level = $2"
673+
);
674+
}
638675
}

0 commit comments

Comments
 (0)