Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add args to query builder (#2494) #2506

Merged
merged 4 commits into from
Jun 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 38 additions & 1 deletion sqlx-core/src/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test isn't actually running because sqlx-core doesn't have a postgres feature anymore.

I'll have to migrate this to be an integration test or something.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, is this a blocker?

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"
);
}
}