use super::PostgresQueryBuilder;
use crate::backend::bound_sql::bound;
use crate::backend::dialect::{
ArrayOperator, BoundSql, JsonContainment, JsonExistence, JsonPathStep, LONG_LIST, SqlDialect,
all_elements, any_element, array_contained_by, builder_dialect, in_list, json_path_text,
json_text, negated, parse_json_path, unknown_when_null,
};
use crate::extension::postgres::PgFunc;
use crate::{ArrayType, Expr, ExprTrait, Value, error::RenderError};
const ARRAY_ELEMENT: &str = "tideorm_array_element";
impl SqlDialect for PostgresQueryBuilder {
builder_dialect!(PostgresQueryBuilder);
fn native_arrays(&self) -> bool {
true
}
fn exact_key(&self, column: &str) -> String {
format!("CAST({column} AS TEXT) COLLATE \"C\"")
}
fn in_list(&self, column: Expr, values: Vec<Value>, negated: bool) -> Expr {
if values.len() > LONG_LIST
&& let Some(array_type) = shared_array_type(&values)
{
let decimals = array_type == ArrayType::Decimal;
let mut array = Expr::val(Value::Array(array_type, Some(Box::new(values))));
if decimals {
array = array.cast_as("NUMERIC[]");
}
return if negated {
column.ne(PgFunc::all(array))
} else {
column.eq(PgFunc::any(array))
};
}
if values
.iter()
.any(|value| matches!(value, Value::Decimal(Some(_))))
{
let list = values.into_iter().map(|value| match value {
Value::Decimal(Some(_)) => Expr::val(value).cast_as("NUMERIC"),
value => Expr::val(value),
});
return if negated {
column.is_not_in(list)
} else {
column.is_in(list)
};
}
in_list(column, values, negated)
}
fn json_equals(&self, column: &str, value: &serde_json::Value, negated: bool) -> BoundSql {
let operator = if negated { " <> " } else { " = " };
bound!(jsonb(column), operator, Value::from(value.clone()))
}
fn json_containment(
&self,
column: &str,
value: &serde_json::Value,
containment: JsonContainment,
) -> BoundSql {
let operator = match containment {
JsonContainment::Contains => " @> ",
JsonContainment::ContainedBy => " <@ ",
};
bound!(jsonb(column), operator, Value::from(value.clone()))
}
fn json_exists(
&self,
column: &str,
existence: JsonExistence,
target: &str,
negate: bool,
) -> Result<BoundSql, RenderError> {
let jsonb = jsonb(column);
let text = |text: String| Value::String(Some(text));
let sql = match existence {
JsonExistence::Key => unknown_when_null(
column,
bound!(
format!("(jsonb_typeof({jsonb}) = 'object' AND {jsonb} ? "),
text(target.to_string()),
")"
),
),
JsonExistence::Path => match parse_json_path(target) {
Some(steps) => unknown_when_null(
column,
bound!(
format!("COALESCE(jsonb_path_exists({jsonb}, ("),
text(format!("strict {}", json_path_text(&steps))),
"::jsonpath), '{}', TRUE), FALSE)"
),
),
None => bound!(
format!("{jsonb} @? ("),
text(target.to_string()),
"::jsonpath)"
),
},
};
Ok(negated(sql, negate))
}
fn array_predicate(
&self,
column: &str,
operator: ArrayOperator,
elements: Vec<Value>,
null_allowed: bool,
) -> BoundSql {
let checks = || {
elements
.iter()
.map(|element| bound!(element.clone(), format!(" = ANY({column})")))
.collect()
};
match operator {
ArrayOperator::Contains => all_elements(column, checks()),
ArrayOperator::Overlaps => any_element(checks()),
ArrayOperator::ContainedBy => contained_by(column, elements, null_allowed),
}
}
fn array_append(&self, column: &str, element: Value) -> BoundSql {
bound!(format!("array_append({column}, "), element, ")")
}
fn array_remove(&self, column: &str, _source: &str, element: Value) -> BoundSql {
bound!(format!("array_remove({column}, "), element, ")")
}
fn json_set(&self, column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql {
let jsonb = jsonb(column);
if path.is_empty() {
return BoundSql::sql(jsonb);
}
let guards = path.iter().enumerate().map(|(index, step)| {
let kind = match step {
JsonPathStep::Member(_) => "object",
JsonPathStep::Element(_) => "array",
};
bound!(
format!("jsonb_typeof({jsonb} #> "),
Value::String(Some(path_array(&path[..index]))),
format!("::text[]) = '{kind}'")
)
});
bound!(
"CASE WHEN ",
BoundSql::join(guards, " AND "),
format!(" THEN jsonb_set({jsonb}, "),
Value::String(Some(path_array(path))),
"::text[], CAST(",
json_text(value),
format!(" AS jsonb)) ELSE {jsonb} END")
)
}
}
fn jsonb(column: &str) -> String {
format!("({column})::jsonb")
}
fn path_array(steps: &[JsonPathStep]) -> String {
let elements: Vec<String> = steps
.iter()
.map(|step| {
let text = match step {
JsonPathStep::Member(key) => key.clone(),
JsonPathStep::Element(index) => index.to_string(),
};
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
})
.collect();
format!("{{{}}}", elements.join(","))
}
fn contained_by(column: &str, elements: Vec<Value>, null_allowed: bool) -> BoundSql {
let element = format!("{ARRAY_ELEMENT}.element");
let empty = elements.is_empty();
let list = bound!(
format!("{element} NOT IN ("),
BoundSql::join(elements.into_iter().map(|value| bound!(value)), ", "),
")"
);
let offending = match (empty, null_allowed) {
(true, false) => None,
(true, true) => Some(BoundSql::sql(format!("{element} IS NOT NULL"))),
(false, false) => Some(bound!(format!("{element} IS NULL OR "), list)),
(false, true) => Some(list),
};
array_contained_by(
column,
&format!("unnest({column}) AS {ARRAY_ELEMENT}(element)"),
offending,
)
}
fn shared_array_type(values: &[Value]) -> Option<ArrayType> {
let array_type = values.first()?.array_type();
values
.iter()
.all(|value| value.array_type() == array_type)
.then_some(array_type)
}
#[cfg(test)]
#[path = "../../../tests/unit/postgres_dialect_tests.rs"]
mod tests;