Skip to content

Commit

Permalink
#68 Escape ?? in CustomWithValues
Browse files Browse the repository at this point in the history
  • Loading branch information
tyt2y3 committed Jul 12, 2021
1 parent bb891d8 commit 52f3306
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 4 deletions.
17 changes: 15 additions & 2 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,12 +284,25 @@ pub trait QueryBuilder: QuotedBuilder {
write!(sql, "{}", s).unwrap();
}
SimpleExpr::CustomWithValues(expr, values) => {
let tokenizer = Tokenizer::new(expr);
let mut tokenizer = Tokenizer::new(expr).iter().peekable();
let mut count = 0;
for tok in tokenizer.iter() {
while let Some(tok) = tokenizer.next() {
match tok {
Token::Punctuation(mark) => {
if mark == "?" {
if let Some(nxt) = tokenizer.peek() {
match nxt {
Token::Punctuation(mark) => {
// escape '??'
if mark == "?" {
write!(sql, "{}", mark).unwrap();
tokenizer.next();
continue;
}
}
_ => {}
}
}
self.prepare_value(&values[count], sql, collector);
count += 1;
} else {
Expand Down
33 changes: 33 additions & 0 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,39 @@ impl Expr {
/// r#"SELECT `character`, `size_w`, `size_h` FROM `character` WHERE `id` = 1 AND 6 = 2 * 3"#
/// );
/// ```
/// ```
/// use sea_query::{*, tests_cfg::*};
///
/// let query = Query::select()
/// .expr(Expr::cust_with_values("6 = ? * ?", vec![2, 3]))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"SELECT 6 = 2 * 3"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT 6 = 2 * 3"#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"SELECT 6 = 2 * 3"#
/// );
/// ```
/// Postgres only: use `??` to escape `?`
/// ```
/// use sea_query::{*, tests_cfg::*};
///
/// let query = Query::select()
/// .expr(Expr::cust_with_values("? ?? ?", vec!["a", "b"]))
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT 'a' ? 'b'"#
/// );
/// ```
pub fn cust_with_values<V, I>(s: &str, v: I) -> SimpleExpr
where
V: Into<Value>,
Expand Down
4 changes: 2 additions & 2 deletions src/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ where
let token = &tokens[i];
match token {
Token::Punctuation(mark) => {
if mark == "?" {
if (mark.as_ref(), false) == query_builder.placeholder() {
output.push(query_builder.value_to_string(&params[counter]));
counter += 1;
i += 1;
continue;
} else if mark == "$" && i + 1 < tokens.len() {
} else if (mark.as_ref(), true) == query_builder.placeholder() && i + 1 < tokens.len() {
if let Token::Unquoted(next) = &tokens[i + 1] {
if let Ok(num) = next.parse::<usize>() {
output.push(query_builder.value_to_string(&params[num - 1]));
Expand Down

0 comments on commit 52f3306

Please sign in to comment.