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 <austin.bonander@gmail.com>

* fmt

---------

Co-authored-by: Bastian Schubert <bastian.schubert@dock.financial>
Co-authored-by: Austin Bonander <austin.bonander@gmail.com>
This commit is contained in:
Bastian 2023-06-30 23:26:25 +02:00 committed by GitHub
parent 3fdb79d03c
commit c2e54eae6f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,7 +4,7 @@ use std::fmt::Display;
use std::fmt::Write;
use std::marker::PhantomData;
use crate::arguments::Arguments;
use crate::arguments::{Arguments, IntoArguments};
use crate::database::{Database, HasArguments};
use crate::encode::Encode;
use crate::from_row::FromRow;
@ -49,6 +49,24 @@ where
}
}
/// Construct a `QueryBuilder` with existing SQL and arguments.
///
/// ### Note
/// This does *not* check if `arguments` is valid for the given SQL.
pub fn with_arguments<A>(init: impl Into<String>, arguments: A) -> Self
where
DB: Database,
A: IntoArguments<'args, DB>,
{
let init = init.into();
QueryBuilder {
init_len: init.len(),
query: init,
arguments: Some(arguments.into_arguments()),
}
}
#[inline]
fn sanity_check(&self) {
assert!(
@ -635,4 +653,23 @@ mod test {
"SELECT * FROM users WHERE id = 99"
);
}
#[test]
fn test_query_builder_with_args() {
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new("");
let query = qb
.push("SELECT * FROM users WHERE id = ")
.push_bind(42i32)
.build();
let mut qb: QueryBuilder<'_, Postgres> =
QueryBuilder::new_with(query.sql(), query.take_arguments());
let query = qb.push("OR membership_level =").push_bind(3i32).build();
assert_eq!(
query.sql(),
"SELECT * FROM users WHERE id = $1 OR membership_level = $2"
);
}
}