-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Add Query builder #1780
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
Merged
abonander
merged 6 commits into
launchbadge:master
from
crajcan:crajcan/feature/query-builder
Apr 8, 2022
Merged
Add Query builder #1780
Changes from all 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,175 @@ | ||
use std::fmt::Display; | ||
use std::fmt::Write; | ||
|
||
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>, | ||
} | ||
|
||
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()), | ||
} | ||
} | ||
|
||
pub fn push(&mut self, sql: impl Display) -> &mut Self { | ||
if self.arguments.is_none() { | ||
panic!("QueryBuilder must be reset before reuse") | ||
} | ||
|
||
write!(self.query, "{}", sql).expect("error formatting `sql`"); | ||
|
||
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); | ||
|
||
arguments | ||
.format_placeholder(&mut self.query) | ||
.expect("error in format_placeholder"); | ||
} | ||
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, | ||
} | ||
} | ||
|
||
pub fn reset(&mut self) -> &mut Self { | ||
self.query.clear(); | ||
self.arguments = Some(Default::default()); | ||
|
||
self | ||
} | ||
} | ||
|
||
#[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] | ||
#[should_panic] | ||
fn test_push_panics_when_no_arguments() { | ||
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new("SELECT * FROM users;"); | ||
qb.arguments = None; | ||
|
||
qb.push("SELECT * FROM users;"); | ||
} | ||
|
||
#[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" | ||
); | ||
} | ||
|
||
#[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); | ||
} | ||
|
||
#[test] | ||
fn test_reset() { | ||
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new(""); | ||
|
||
let _query = qb | ||
.push("SELECT * FROM users WHERE id = ") | ||
.push_bind(42i32) | ||
.build(); | ||
|
||
qb.reset(); | ||
|
||
assert_eq!(qb.query, ""); | ||
} | ||
|
||
#[test] | ||
fn test_query_builder_reuse() { | ||
let mut qb: QueryBuilder<'_, Postgres> = QueryBuilder::new(""); | ||
|
||
let _query = qb | ||
.push("SELECT * FROM users WHERE id = ") | ||
.push_bind(42i32) | ||
.build(); | ||
|
||
qb.reset(); | ||
|
||
let query = qb.push("SELECT * FROM users WHERE id = 99").build(); | ||
|
||
assert_eq!( | ||
query.statement.unwrap_left(), | ||
"SELECT * FROM users WHERE id = 99" | ||
); | ||
} | ||
} |
This file contains hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.