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 Query builder #1780

Merged
merged 6 commits into from
Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sqlx-core/src/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ pub trait Arguments<'q>: Send + Sized + Default {
fn add<T>(&mut self, value: T)
where
T: 'q + Send + Encode<'q, Self::Database> + Type<Self::Database>;

fn place_holder(&self, _argument_count: u16) -> String {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nit: argument_count shouldn't be necessary as the Arguments impl should already know how many arguments have been pushed. Personally, I also think "placeholder" should be one word, not two.

The intermediate String is also a wasted allocation. An alternative signature might look like this:

use std::fmt::{Self, Write};

fn format_placeholder<W: Write>(&self, mut writer: W) -> fmt::Result {
    writer.write_str("?")
}

and the Postgres implementation would look like this:

fn format_placeholder<W: Write>(&self, mut writer: W) -> fmt::Result {
    write!(writer, "${}", self.count)
}

QueryBuilder would then simply invoke it like:

// This is highly unlikely to return an error so panicking is fine.
arguments.format_placeholder(&mut self.query).expect("error in format_placeholder")

"?".to_string()
}
}

pub trait IntoArguments<'q, DB: HasArguments<'q>>: Sized + Send {
Expand Down
1 change: 1 addition & 0 deletions sqlx-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ mod io;
mod logger;
mod net;
pub mod query_as;
pub mod query_builder;
pub mod query_scalar;
pub mod row;
pub mod type_info;
Expand Down
4 changes: 4 additions & 0 deletions sqlx-core/src/postgres/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ impl<'q> Arguments<'q> for PgArguments {
{
self.add(value)
}

fn place_holder(&self, argument_count: u16) -> String {
format!("${}", argument_count)
}
}

impl PgArgumentBuffer {
Expand Down
141 changes: 141 additions & 0 deletions sqlx-core/src/query_builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
use std::fmt::Display;

use crate::arguments::Arguments;
use crate::database::{Database, HasArguments};
use crate::encode::Encode;
use crate::query::Query;
use crate::types::Type;
use either::Either;
use std::marker::PhantomData;

pub struct QueryBuilder<'a, DB>
where
DB: Database,
{
query: String,
arguments: Option<<DB as HasArguments<'a>>::Arguments>,
variable_count: u16,
}

impl<'a, DB: Database> QueryBuilder<'a, DB>
where
DB: Database,
{
pub fn new(init: impl Into<String>) -> Self
where
<DB as HasArguments<'a>>::Arguments: Default,
{
QueryBuilder {
query: init.into(),
arguments: Some(Default::default()),
variable_count: 0,
}
}

pub fn push(&mut self, sql: impl Display) -> &mut Self {
self.query.push_str(&format!(" {}", sql));
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
self.query.push_str(&format!(" {}", sql));
// An error here is also highly unlikely but ignoring it is a code smell.
write!(self.query, " {}", sql).expect("error formatting `sql`");

It is a bit weird to insert a space automatically, though. What if someone is trying to concatenate an identifier using this method, or is building a string literal where formatting matters? This violates the principle of least surprise.


self
}

pub fn push_bind<A>(&mut self, value: A) -> &mut Self
where
A: 'a + Encode<'a, DB> + Send + Type<DB>,
{
match self.arguments {
Some(ref mut arguments) => {
arguments.add(value);
self.variable_count += 1;
self.query
.push_str(&arguments.place_holder(self.variable_count));
}
None => panic!("Arguments taken already"),
}

self
}

pub fn build(&mut self) -> Query<'_, DB, <DB as HasArguments<'a>>::Arguments> {
Query {
statement: Either::Left(&self.query),
arguments: match self.arguments.take() {
Some(arguments) => Some(arguments),
None => None,
},
database: PhantomData,
persistent: true,
}
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::postgres::Postgres;

#[test]
fn test_new() {
let qb: QueryBuilder<'_, Postgres> = QueryBuilder::new("SELECT * FROM users");
assert_eq!(qb.query, "SELECT * FROM users");
}

#[test]
fn test_push() {
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new("SELECT * FROM users");
let second_line = "WHERE last_name LIKE '[A-N]%;";
qb.push(second_line);

assert_eq!(
qb.query,
"SELECT * FROM users WHERE last_name LIKE '[A-N]%;".to_string(),
);
}

#[test]
fn test_push_bind() {
let mut qb: QueryBuilder<'_, Postgres> =
QueryBuilder::new("SELECT * FROM users WHERE id = ");

qb.push_bind(42i32)
.push("OR membership_level = ")
.push_bind(3i32);

assert_eq!(
qb.query,
"SELECT * FROM users WHERE id = $1 OR membership_level = $2"
);
assert_eq!(qb.variable_count, 2);
}

#[test]
fn test_push_bind_handles_strings() {
let mut qb: QueryBuilder<'_, Postgres> =
QueryBuilder::new("SELECT * FROM users WHERE id = ");

qb.push_bind(42i32)
.push("OR last_name = ")
.push_bind("'Doe'")
.push("AND membership_level = ")
.push_bind(3i32);

assert_eq!(
qb.query,
"SELECT * FROM users WHERE id = $1 OR last_name = $2 AND membership_level = $3"
);
assert_eq!(qb.variable_count, 3);
}

#[test]
fn test_build() {
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new("SELECT * FROM users");

qb.push("WHERE id = ").push_bind(42i32);
let query = qb.build();

assert_eq!(
query.statement.unwrap_left(),
"SELECT * FROM users WHERE id = $1"
);
assert_eq!(query.persistent, true);
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub use sqlx_core::from_row::FromRow;
pub use sqlx_core::pool::{self, Pool};
pub use sqlx_core::query::{query, query_with};
pub use sqlx_core::query_as::{query_as, query_as_with};
pub use sqlx_core::query_builder::QueryBuilder;
pub use sqlx_core::query_scalar::{query_scalar, query_scalar_with};
pub use sqlx_core::row::Row;
pub use sqlx_core::statement::Statement;
Expand Down