use super::bound_sql::bound;
pub use super::bound_sql::{BoundPart, BoundPiece, BoundSql};
use crate::{Expr, ExprTrait, Quote, Value, error::RenderError};
pub(crate) use super::json_path::{JsonPathStep, json_path_text, parse_json_path};
pub const MATCH_NOTHING: &str = "0 = 1";
pub const LONG_LIST: usize = 1_000;
const LIKE_ESCAPE: char = '!';
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonContainment {
Contains,
ContainedBy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonExistence {
Key,
Path,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArrayOperator {
Contains,
ContainedBy,
Overlaps,
}
pub trait SqlDialect: Send + Sync {
fn identifier_quote(&self) -> Quote;
fn push_identifier(&self, out: &mut String, name: &str) {
super::write_identifier(out, self.identifier_quote(), name);
}
fn marker(&self, index: usize) -> String;
fn numbered_markers(&self) -> bool;
fn expression(&self, sql: String, values: Vec<Value>) -> Result<Expr, RenderError>;
fn inline_values(&self, sql: &str, values: &[Value]) -> Result<String, RenderError>;
fn string_literal(&self, text: &str) -> String;
fn native_arrays(&self) -> bool {
false
}
fn json_equals(&self, column: &str, value: &serde_json::Value, negated: bool) -> BoundSql;
fn json_containment(
&self,
column: &str,
value: &serde_json::Value,
containment: JsonContainment,
) -> BoundSql;
fn json_exists(
&self,
column: &str,
existence: JsonExistence,
target: &str,
negated: bool,
) -> Result<BoundSql, RenderError>;
fn array_predicate(
&self,
column: &str,
operator: ArrayOperator,
elements: Vec<Value>,
null_allowed: bool,
) -> BoundSql;
fn array_append(&self, column: &str, element: Value) -> BoundSql;
fn array_remove(&self, column: &str, source: &str, element: Value) -> BoundSql;
fn json_set(&self, column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql;
fn window_default(
&self,
function: &str,
column: &str,
offset: &str,
default: &str,
over: &str,
) -> String {
format!("{function}({column}, {offset}, {default}) OVER ({over})")
}
fn open_limit(&self) -> Option<&'static str> {
None
}
fn limit_in_subquery(&self) -> bool {
true
}
fn groups_frames(&self) -> bool {
true
}
fn update_limit(&self) -> bool {
false
}
fn exact_key(&self, column: &str) -> String;
fn limit_offset(&self, limit: Option<u64>, offset: Option<u64>) -> BoundSql {
let mut bound = match (limit, offset) {
(Some(limit), _) => BoundSql::sql(format!(" LIMIT {limit}")),
(None, Some(_)) => match self.open_limit() {
Some(open) => BoundSql::sql(format!(" LIMIT {open}")),
None => BoundSql::default(),
},
(None, None) => BoundSql::default(),
};
if let Some(offset) = offset {
bound.push(" OFFSET ").push(Value::from(offset));
}
bound
}
fn literal_match(
&self,
column: &str,
literal: &str,
leading: bool,
trailing: bool,
) -> Result<BoundSql, RenderError> {
let mut pattern = String::with_capacity(literal.len() + 2);
if leading {
pattern.push('%');
}
for character in literal.chars() {
if matches!(character, LIKE_ESCAPE | '%' | '_') {
pattern.push(LIKE_ESCAPE);
}
pattern.push(character);
}
if trailing {
pattern.push('%');
}
Ok(bound!(
format!("{column} LIKE "),
Value::String(Some(pattern)),
format!(" ESCAPE '{LIKE_ESCAPE}'")
))
}
fn in_list(&self, column: Expr, values: Vec<Value>, negated: bool) -> Expr {
in_list(column, values, negated)
}
}
pub(crate) fn in_list(column: Expr, values: Vec<Value>, negated: bool) -> Expr {
let literals = values.len() > LONG_LIST
&& values.iter().all(|value| {
matches!(
value,
Value::TinyInt(Some(_))
| Value::SmallInt(Some(_))
| Value::Int(Some(_))
| Value::BigInt(Some(_))
| Value::TinyUnsigned(Some(_))
| Value::SmallUnsigned(Some(_))
| Value::Unsigned(Some(_))
| Value::BigUnsigned(Some(_))
)
});
let list = values.into_iter().map(|value| {
if literals {
Expr::Constant(value)
} else {
Expr::Value(value)
}
});
if negated {
column.is_not_in(list)
} else {
column.is_in(list)
}
}
macro_rules! builder_dialect {
($builder:expr) => {
fn identifier_quote(&self) -> $crate::Quote {
$crate::QuotedBuilder::quote(&$builder)
}
fn marker(&self, index: usize) -> String {
match $crate::QueryBuilder::placeholder(&$builder) {
(marker, true) => format!("{marker}{index}"),
(marker, false) => marker.to_string(),
}
}
fn numbered_markers(&self) -> bool {
$crate::QueryBuilder::placeholder(&$builder).1
}
fn expression(
&self,
sql: String,
values: Vec<$crate::Value>,
) -> Result<$crate::Expr, $crate::error::RenderError> {
$crate::Expr::cust_with_values(sql, values, &$builder)
}
fn inline_values(
&self,
sql: &str,
values: &[$crate::Value],
) -> Result<String, $crate::error::RenderError> {
$crate::inject_parameters(sql, values, &$builder)
}
fn string_literal(&self, text: &str) -> String {
let mut literal = String::with_capacity(text.len() + 2);
$crate::QueryBuilder::write_string_quoted(&$builder, text, &mut literal);
literal
}
};
}
pub(crate) use builder_dialect;
pub(crate) fn unknown_when_null(column: &str, test: BoundSql) -> BoundSql {
bound!(
format!("CASE WHEN {column} IS NOT NULL THEN "),
test,
" END"
)
}
pub(crate) fn negated(sql: BoundSql, negated: bool) -> BoundSql {
if negated {
bound!("NOT (", sql, ")")
} else {
sql
}
}
pub(crate) fn json_text(value: &serde_json::Value) -> Value {
Value::String(Some(value.to_string()))
}
pub(crate) fn document(value: &Value) -> serde_json::Value {
crate::value_to_json_value(value).unwrap_or(serde_json::Value::Null)
}
pub(crate) fn existence_steps(
existence: JsonExistence,
target: &str,
backend: &str,
) -> Result<Vec<JsonPathStep>, RenderError> {
match existence {
JsonExistence::Key => Ok(vec![JsonPathStep::Member(target.to_string())]),
JsonExistence::Path => parse_json_path(target).ok_or_else(|| {
RenderError::Unsupported(format!(
"'{target}' is not a JSON path {backend} can test; write `$` followed by \
`.key`, `.\"quoted key\"` or `[index]` steps"
))
}),
}
}
pub(crate) fn all_elements(column: &str, checks: Vec<BoundSql>) -> BoundSql {
joined(checks, " AND ", &format!("{column} IS NOT NULL"))
}
pub(crate) fn any_element(checks: Vec<BoundSql>) -> BoundSql {
joined(checks, " OR ", MATCH_NOTHING)
}
pub(crate) fn joined(checks: Vec<BoundSql>, combine: &str, empty: &str) -> BoundSql {
if checks.is_empty() {
return BoundSql::sql(empty);
}
bound!("(", BoundSql::join(checks, combine), ")")
}
pub(crate) fn array_contained_by(
column: &str,
source: &str,
offending: Option<BoundSql>,
) -> BoundSql {
let rows = format!("({column} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM {source}");
match offending {
None => BoundSql::sql(format!("{rows}))")),
Some(offending) => bound!(format!("{rows} WHERE "), offending, "))"),
}
}
#[cfg(test)]
#[path = "../../tests/unit/in_list_tests.rs"]
mod tests;