use serde::Serialize;
use super::statement::Sql;
use super::values::{Value, to_value};
pub fn or<I>(conditions: I) -> Sql
where
I: IntoIterator,
I::Item: Into<Sql>,
{
group(conditions, "or", "0")
}
pub fn and<I>(conditions: I) -> Sql
where
I: IntoIterator,
I::Item: Into<Sql>,
{
group(conditions, "and", "1")
}
pub fn eq<T: Serialize + ?Sized>(column: &str, value: &T) -> Sql {
let column = match quote(column) {
Ok(column) => column,
Err(why) => return Sql::refused(why),
};
match to_value(value) {
Ok(Value::Null) => Sql::piece(format!("{column} is null"), Vec::new(), true),
Ok(value) => Sql::piece(format!("{column} = ?"), vec![value], true),
Err(why) => Sql::refused(format!("{column}: {why}")),
}
}
pub fn is_in<T: Serialize>(column: &str, values: &[T]) -> Sql {
let column = match quote(column) {
Ok(column) => column,
Err(why) => return Sql::refused(why),
};
let listed = list(values);
let (text, values, refused) = listed.into_parts();
match refused {
Some(why) => Sql::refused(why),
None => Sql::piece(format!("{column} in {text}"), values, true),
}
}
pub fn list<T: Serialize>(values: &[T]) -> Sql {
match serde_json::to_string(values) {
Ok(json) => Sql::piece("(select value from json_each(?))".to_owned(), vec![Value::Text(json)], false),
Err(error) => Sql::refused(format!("a list's JSON: {error}")),
}
}
pub fn json<T: Serialize + ?Sized>(value: &T) -> Sql {
match serde_json::to_string(value) {
Ok(json) => Sql::piece("?".to_owned(), vec![Value::Text(json)], true),
Err(error) => Sql::refused(format!("a value's JSON: {error}")),
}
}
pub fn ident(name: &str) -> Sql {
match quote(name) {
Ok(quoted) => Sql::piece(quoted, Vec::new(), true),
Err(why) => Sql::refused(why),
}
}
pub fn has<T: Serialize + ?Sized>(column: &str, value: &T) -> Sql {
let column = match quote(column) {
Ok(column) => column,
Err(why) => return Sql::refused(why),
};
match to_value(value) {
Ok(value) => {
Sql::piece(format!("exists (select 1 from json_each({column}) where value = ?)"), vec![value], false)
}
Err(why) => Sql::refused(format!("{column}'s value: {why}")),
}
}
pub fn value<T: Serialize + ?Sized>(value: &T) -> Sql {
match to_value(value) {
Ok(value) => Sql::piece("?".to_owned(), vec![value], true),
Err(why) => Sql::refused(why),
}
}
fn group<I>(conditions: I, joiner: &str, empty: &str) -> Sql
where
I: IntoIterator,
I::Item: Into<Sql>,
{
let pieces: Vec<Sql> = conditions.into_iter().map(|condition| checked(condition.into())).collect();
if pieces.is_empty() {
return Sql::piece(empty.to_owned(), Vec::new(), false);
}
let joined = joined_with(pieces, joiner);
let (text, values, refused) = joined.into_parts();
match refused {
Some(why) => Sql::refused(why),
None => Sql::piece(format!("({text})"), values, false),
}
}
pub(crate) fn checked(piece: Sql) -> Sql {
if piece.why_refused().is_some() {
return piece;
}
let counted = placeholders(piece.text());
if !counted.named.is_empty() || counted.numbered {
return Sql::refused(format!("a piece of SQL takes its values at ? alone: {}", piece.text()));
}
if counted.positional != piece.values().len() {
return Sql::refused(format!(
"{} placeholders and {} values: each ? takes one value",
counted.positional,
piece.values().len()
));
}
match comment_at_end(piece.text()) {
Some(Comment::Line) => {
let bare = piece.is_bare();
let (text, values, _) = piece.into_parts();
Sql::piece(format!("{text}\n"), values, bare)
}
Some(Comment::Block) => Sql::refused(format!(
"a piece of SQL ends inside a /* comment, which would hide what the query writes after it: {}",
piece.text()
)),
None => piece,
}
}
#[derive(Debug, PartialEq, Eq)]
enum Comment {
Line,
Block,
}
fn comment_at_end(text: &str) -> Option<Comment> {
let chars: Vec<char> = text.chars().collect();
let mut at = 0;
while at < chars.len() {
let end = match chars[at] {
'[' => Some(find(&chars, at + 1, &[']']).unwrap_or(chars.len())),
_ => quoted_or_comment_end(&chars, at),
};
match end {
Some(end) if end >= chars.len() => {
return match chars[at] {
'-' => Some(Comment::Line),
'/' => Some(Comment::Block),
_ => None,
};
}
Some(end) => at = end + 1,
None => at += 1,
}
}
None
}
pub(crate) fn joined_with(pieces: Vec<Sql>, joiner: &str) -> Sql {
let several = pieces.len() > 1;
let mut texts = Vec::with_capacity(pieces.len());
let mut values = Vec::new();
for piece in pieces {
let wrapped = several && !piece.is_bare() && !stands_alone(piece.text());
let (text, piece_values, refused) = piece.into_parts();
if let Some(why) = refused {
return Sql::refused(why);
}
texts.push(if wrapped { format!("({text})") } else { text });
values.extend(piece_values);
}
Sql::piece(texts.join(&format!(" {joiner} ")), values, false)
}
pub(crate) fn quote(name: &str) -> Result<String, String> {
if name.is_empty() || name.contains('\0') {
return Err(format!("the name {name:?}: a name is text without NUL"));
}
Ok(name.split('.').map(crate::sqlite::quote_ident).collect::<Vec<_>>().join("."))
}
pub(crate) fn quote_all<S: AsRef<str>>(names: &[S]) -> crate::Result<Vec<String>> {
names.iter().map(|name| quote(name.as_ref())).collect::<Result<_, _>>().map_err(crate::Error::invalid)
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Counted {
pub(crate) positional: usize,
pub(crate) named: Vec<String>,
pub(crate) numbered: bool,
}
pub(crate) fn placeholders(text: &str) -> Counted {
let mut counted = Counted::default();
let chars: Vec<char> = text.chars().collect();
let mut at = 0;
while at < chars.len() {
if let Some(end) = quoted_or_comment_end(&chars, at) {
at = end + 1;
continue;
}
match chars[at] {
'[' => at = find(&chars, at + 1, &[']']).unwrap_or(chars.len()),
'?' if chars.get(at + 1).is_some_and(char::is_ascii_digit) => counted.numbered = true,
'?' => counted.positional += 1,
':' | '@' | '$' if chars.get(at + 1).is_some_and(|next| next.is_ascii_alphabetic() || *next == '_') => {
let name: String =
chars[at + 1..].iter().take_while(|c| c.is_ascii_alphanumeric() || **c == '_').collect();
at += name.chars().count();
if !counted.named.contains(&name) {
counted.named.push(name);
}
}
_ => {}
}
at += 1;
}
counted
}
fn quoted_or_comment_end(chars: &[char], at: usize) -> Option<usize> {
match chars[at] {
quote @ ('\'' | '"' | '`') => Some(closing(chars, at, quote)),
'-' if chars.get(at + 1) == Some(&'-') => Some(find(chars, at, &['\n']).unwrap_or(chars.len())),
'/' if chars.get(at + 1) == Some(&'*') => Some(find_pair(chars, at + 2).map_or(chars.len(), |end| end + 1)),
_ => None,
}
}
pub(crate) fn stands_alone(text: &str) -> bool {
if grouped(text) {
return true;
}
let chars: Vec<char> = text.chars().collect();
let mut depth = 0i32;
let mut at = 0;
while at < chars.len() {
if let Some(end) = quoted_or_comment_end(&chars, at) {
at = end + 1;
continue;
}
match chars[at] {
'(' => depth += 1,
')' => depth -= 1,
c if depth == 0
&& c.is_ascii_alphabetic()
&& !word_char(at.checked_sub(1).and_then(|at| chars.get(at))) =>
{
let word: String =
chars[at..].iter().take_while(|c| c.is_ascii_alphanumeric() || **c == '_' || **c == '$').collect();
if word.eq_ignore_ascii_case("and") || word.eq_ignore_ascii_case("or") {
return false;
}
at += word.chars().count() - 1;
}
_ => {}
}
at += 1;
}
true
}
pub(crate) fn grouped(text: &str) -> bool {
if !text.starts_with('(') || !text.ends_with(')') {
return text == "0" || text == "1";
}
let chars: Vec<char> = text.chars().collect();
let (mut depth, mut at) = (0i32, 0);
while at < chars.len() {
if let Some(end) = quoted_or_comment_end(&chars, at) {
at = end + 1;
continue;
}
match chars[at] {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
if depth == 0 && at < chars.len() - 1 {
return false;
}
at += 1;
}
depth == 0
}
fn word_char(c: Option<&char>) -> bool {
c.is_some_and(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
}
fn closing(chars: &[char], at: usize, quote: char) -> usize {
let mut next = at + 1;
while next < chars.len() {
if chars[next] == quote {
if chars.get(next + 1) == Some("e) {
next += 2;
continue;
}
return next;
}
next += 1;
}
chars.len()
}
fn find(chars: &[char], from: usize, any: &[char]) -> Option<usize> {
chars.get(from..)?.iter().position(|c| any.contains(c)).map(|at| from + at)
}
fn find_pair(chars: &[char], from: usize) -> Option<usize> {
(from..chars.len().saturating_sub(1)).find(|&at| chars[at] == '*' && chars[at + 1] == '/')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_question_mark_in_a_string_or_a_comment_is_no_placeholder() {
let counted = placeholders("a = ? and b = '?' -- why?\n and c = :c and d = ?3 /* ? */");
assert_eq!(counted, Counted { positional: 1, named: vec!["c".to_owned()], numbered: true });
}
#[test]
fn a_piece_with_an_and_or_an_or_of_its_own_does_not_stand_alone() {
assert!(stands_alone("amount >= ?"));
assert!(stands_alone("(a or b)"));
assert!(stands_alone("title = 'this or that'"));
assert!(stands_alone("lower(a) = ? -- and"));
assert!(!stands_alone("a = 1 or b = 2"));
assert!(!stands_alone("total between ? and ?"));
assert!(!stands_alone("(a) or (b)"));
assert!(!stands_alone("('(') or ('x')"), "a parenthesis in quotes opens nothing");
assert!(stands_alone("(title = ')')"));
}
#[test]
fn a_piece_that_ends_inside_a_comment_ends_at_a_newline_or_is_refused() {
assert_eq!(comment_at_end("a = 1 -- why"), Some(Comment::Line));
assert_eq!(comment_at_end("a = 1 -- a /* inside"), Some(Comment::Line));
assert_eq!(comment_at_end("a = 1 /* open"), Some(Comment::Block));
assert_eq!(comment_at_end("a = 1 /*/"), Some(Comment::Block));
assert_eq!(comment_at_end("a = 1 /* a -- inside"), Some(Comment::Block));
for closed in ["a = 1 -- why\n", "a = 1 /* why */", "a = '--' and b = '/*'", "[c--d] = 1", "a - 1 / 2"] {
assert_eq!(comment_at_end(closed), None, "{closed:?}");
}
assert_eq!(checked(Sql::new("a = 1 -- why")).text(), "a = 1 -- why\n");
assert_eq!(checked(Sql::new("a = 1 -- why\n")).text(), "a = 1 -- why\n", "an ended comment stays");
let refused = checked(Sql::new("a = 1 /* open"));
assert!(refused.why_refused().is_some_and(|why| why.contains("ends inside a /* comment")), "{refused:?}");
}
}