-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
abonander
merged 6 commits into
launchbadge:master
from
crajcan:crajcan/feature/query-builder
Apr 8, 2022
Merged
Add Query builder #1780
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
578f6c9
Add Query builder
crajcan 7900367
Run fmt
crajcan 08953cc
Redesign Arguments#format_placeholder in line with code review
crajcan 975b08a
Use write! to push sql to QueryBuilder
crajcan 9bf1066
Add QueryBuilder::reset to allow for QueryBuilder reuse
crajcan e798c4b
Run cargo fmt
crajcan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
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"), | ||||||||
abonander marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
} | ||||||||
|
||||||||
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); | ||||||||
} | ||||||||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 theArguments
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:and the Postgres implementation would look like this:
QueryBuilder
would then simply invoke it like: