use std::cmp::Ordering;
use md5::{Digest, Md5};
use php_std::ArrayKey;
use php_std::json::{self, Flags};
use crate::enums::{CursorDirection, NullsPosition};
use crate::error::{Error, Result};
use crate::method::Method;
use crate::value::{self, Array, IntoValue, IntoValues, Object, Param, Value};
#[derive(Debug, Clone, PartialEq)]
pub struct Query {
method: Method,
attribute: String,
attribute_type: String,
on_array: bool,
values: Array,
alias: String,
alias_defaulted: bool,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ParsedQuery {
pub filters: Vec<Query>,
pub selections: Vec<Query>,
pub aggregations: Vec<Query>,
pub group_by: Vec<Value>,
pub having: Vec<Query>,
pub distinct: bool,
pub joins: Vec<Query>,
pub unions: Vec<Query>,
pub limit: Option<i64>,
pub offset: Option<i64>,
pub cursor: Option<Value>,
pub cursor_direction: Option<CursorDirection>,
pub time_buckets: Vec<TimeBucket>,
}
impl ParsedQuery {
#[allow(clippy::too_many_arguments)]
pub fn new(
filters: Vec<Query>,
selections: Vec<Query>,
aggregations: Vec<Query>,
group_by: Vec<Value>,
having: Vec<Query>,
distinct: bool,
joins: Vec<Query>,
unions: Vec<Query>,
limit: Option<i64>,
offset: Option<i64>,
cursor: Option<Value>,
cursor_direction: Option<CursorDirection>,
time_buckets: Vec<TimeBucket>,
) -> Self {
ParsedQuery {
filters,
selections,
aggregations,
group_by,
having,
distinct,
joins,
unions,
limit,
offset,
cursor,
cursor_direction,
time_buckets,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TimeBucket {
pub attribute: String,
pub interval: Value,
}
#[derive(Debug, Clone, Copy)]
pub enum QueryOrJson<'a> {
Query(&'a Query),
Json(&'a str),
}
pub trait Compiler {
fn compile_filter(&mut self, query: &Query) -> Result<String>;
fn compile_order(&mut self, query: &Query) -> Result<String>;
fn compile_limit(&mut self, query: &Query) -> Result<String>;
fn compile_offset(&mut self, query: &Query) -> Result<String>;
fn compile_select(&mut self, query: &Query) -> Result<String>;
fn compile_cursor(&mut self, query: &Query) -> Result<String>;
fn compile_aggregate(&mut self, query: &Query) -> Result<String>;
fn compile_group_by(&mut self, query: &Query) -> Result<String>;
fn compile_join(&mut self, query: &Query) -> Result<String>;
}
pub const GROUP_BY_TIME_BUCKET_INTERVALS: [&str; 7] = ["1m", "5m", "15m", "1h", "1d", "1w", "1M"];
pub const DEFAULT_ALIAS: &str = "main";
fn list(values: Vec<Value>) -> Array {
Array::from_list(values)
}
fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Array {
list(items.into_iter().map(|s| value::string(s.into())).collect())
}
fn queries(items: impl IntoIterator<Item = Query>) -> Array {
list(items.into_iter().map(Value::from).collect())
}
fn gettype(value: &Value) -> &'static str {
value.type_name()
}
impl Query {
pub fn new(method: Method, attribute: impl Into<String>, values: Array, alias: impl Into<String>) -> Self {
let attribute = attribute.into();
let alias = alias.into();
let alias_defaulted = method.is_join() && !alias.is_empty() && alias == attribute;
Query { method, attribute, attribute_type: String::new(), on_array: false, values, alias, alias_defaulted }
}
fn of(method: Method, attribute: impl Into<String>, values: Vec<Value>) -> Self {
Query::new(method, attribute, list(values), "")
}
pub fn method(&self) -> Method {
self.method
}
pub fn attribute(&self) -> &str {
&self.attribute
}
pub fn values(&self) -> &Array {
&self.values
}
pub fn value(&self) -> Option<&Value> {
self.values.get(&ArrayKey::Int(0)).filter(|v| !matches!(v, Value::Null))
}
pub fn alias(&self) -> &str {
&self.alias
}
pub fn is_alias_defaulted(&self) -> bool {
self.alias_defaulted
}
pub fn on_array(&self) -> bool {
self.on_array
}
pub fn attribute_type(&self) -> &str {
&self.attribute_type
}
pub fn set_method(&mut self, method: Method) -> &mut Self {
self.method = method;
self
}
pub fn set_attribute(&mut self, attribute: impl Into<String>) -> &mut Self {
self.attribute = attribute.into();
self
}
pub fn set_values(&mut self, values: Array) -> &mut Self {
self.values = values;
self
}
pub fn set_value(&mut self, value: Value) -> &mut Self {
self.values = list(vec![value]);
self
}
pub fn set_on_array(&mut self, on_array: bool) {
self.on_array = on_array;
}
pub fn set_attribute_type(&mut self, attribute_type: impl Into<String>) {
self.attribute_type = attribute_type.into();
}
pub fn is_nested_join(&self) -> bool {
self.method.is_join() && self.values.values().any(|v| matches!(v, Value::Ext(Object::Query(_))))
}
pub fn join_on_queries(&self) -> Vec<&Query> {
if !self.is_nested_join() {
return Vec::new();
}
self.nested().collect()
}
pub fn nested(&self) -> impl Iterator<Item = &Query> {
self.values.values().filter_map(|v| match v {
Value::Ext(Object::Query(q)) => Some(&**q),
_ => None,
})
}
pub fn is_method(value: &str) -> bool {
Method::try_from_value(value).is_some()
}
pub fn is_spatial_query(&self) -> bool {
self.method.is_spatial()
}
pub fn is_nested(&self) -> bool {
self.method.is_nested()
}
pub fn parse(query: &str, allow_raw: bool) -> Result<Query> {
Query::parse_bytes(query.as_bytes(), allow_raw)
}
pub fn parse_bytes(query: &[u8], allow_raw: bool) -> Result<Query> {
let decoded: Value = json::decode_ext(query, Some(true), json::DEFAULT_DEPTH, Flags::THROW_ON_ERROR)
.map_err(|e| Error::query(format!("Invalid query: {}", e.message())))?;
match decoded {
Value::Array(array) => Query::parse_query(&array, allow_raw),
other => Err(Error::query(format!("Invalid query. Must be an array, got {}", gettype(&other)))),
}
}
pub fn parse_query(query: &Array, allow_raw: bool) -> Result<Query> {
let get = |key: &str| query.get_str(key).filter(|v| !matches!(v, Value::Null));
let method = get("method").cloned().unwrap_or_else(|| value::string(""));
let attribute = get("attribute").cloned().unwrap_or_else(|| value::string(""));
let values = get("values").cloned().unwrap_or(Value::Array(Array::default()));
let alias = get("alias").cloned().unwrap_or_else(|| value::string(""));
let Value::Str(method) = method else {
return Err(Error::query(format!("Invalid query method. Must be a string, got {}", gettype(&method))));
};
let Some(method) = method.as_str().and_then(Method::try_from_value) else {
return Err(Error::query(format!("Invalid query method: {}", String::from_utf8_lossy(method.as_bytes()))));
};
let Value::Str(attribute) = attribute else {
return Err(Error::query(format!(
"Invalid query attribute. Must be a string, got {}",
gettype(&attribute)
)));
};
let Value::Array(mut values) = values else {
return Err(Error::query(format!("Invalid query values. Must be an array, got {}", gettype(&values))));
};
let Value::Str(alias) = alias else {
return Err(Error::query(format!("Invalid query alias. Must be a string, got {}", gettype(&alias))));
};
let attribute = lossy(attribute.as_bytes());
let mut alias = lossy(alias.as_bytes());
if method == Method::Raw && !allow_raw {
return Err(Error::Validation(
"Raw queries cannot be parsed from untrusted input; construct via Query::raw() in code".into(),
));
}
if method == Method::Distinct && (!attribute.is_empty() || !values.is_empty()) {
return Err(Error::query(
"Invalid distinct query: distinct takes no attribute or values, it deduplicates the attributes a select names",
));
}
if method.is_join() {
return Query::parse_join(method, attribute, &values, alias, allow_raw);
}
if method.is_aggregate() {
if alias.is_empty()
&& let Some(Value::Str(legacy)) = values.get(&ArrayKey::Int(0))
{
alias = lossy(legacy.as_bytes());
}
return Ok(Query::new(method, attribute, Array::default(), alias));
}
if method.is_nested() {
let mut parsed = Array::with_capacity(values.len());
for (key, value) in values.iter() {
let child =
Param::method("Utopia\\Query\\Query::parseQuery", 1, "query", "Query.php", 285).array(value)?;
parsed.set(key.to_owned(), Value::from(Query::parse_query(child, allow_raw)?));
}
values = parsed;
}
Ok(Query::new(method, attribute, values, alias))
}
fn parse_join(method: Method, collection: String, values: &Array, alias: String, allow_raw: bool) -> Result<Query> {
let mut on = Vec::new();
let mut names: Vec<String> = Vec::new();
for value in values.values() {
match value {
Value::Array(child) => on.push(Query::parse_query(child, allow_raw)?),
Value::Str(s) => names.push(lossy(s.as_bytes())),
other => {
return Err(Error::query(format!(
"Invalid join value. Must be a query or a string, got {}",
gettype(other)
)));
}
}
}
let column_form = on.is_empty() && names.len() >= 3;
if column_form {
on.push(Query::on(&names[0], &names[2], &names[1]));
}
let legacy = if column_form { names.get(3) } else { names.first() }.cloned().unwrap_or_default();
if names.len() > if column_form { 4 } else { 1 } {
return Err(Error::query(format!("Invalid join values for {} {}", method.as_str(), collection)));
}
Query::create_join(method, collection, if alias.is_empty() { legacy } else { alias }, on)
}
pub fn parse_queries<S: AsRef<str>>(queries: &[S], allow_raw: bool) -> Result<Vec<Query>> {
queries.iter().map(|q| Query::parse(q.as_ref(), allow_raw)).collect()
}
pub fn fingerprint(queries: &[QueryOrJson<'_>]) -> Result<String> {
let mut shapes = Vec::with_capacity(queries.len());
for query in queries {
shapes.push(match query {
QueryOrJson::Query(q) => q.shape(),
QueryOrJson::Json(json) => Query::parse(json, false)?.shape(),
});
}
shapes.sort_by(|a, b| compare_strings(a, b));
let digest = Md5::digest(shapes.join("|").as_bytes());
Ok(digest.iter().map(|b| format!("{b:02x}")).collect())
}
pub fn shape(&self) -> String {
let logical = matches!(self.method, Method::And | Method::Or | Method::ElemMatch | Method::Relationship);
if !logical && !self.is_nested_join() {
return format!("{}:{}", self.method.as_str(), self.attribute);
}
let mut children: Vec<String> = self.nested().map(Query::shape).collect();
children.sort_by(|a, b| compare_strings(a, b));
format!("{}:{}({})", self.method.as_str(), self.attribute, children.join("|"))
}
pub fn to_array(&self) -> Array {
let mut array = Array::with_capacity(4);
array.set(ArrayKey::from("method"), value::string(self.method.as_str()));
if !php_empty_str(&self.attribute) {
array.set(ArrayKey::from("attribute"), value::string(&self.attribute));
}
if !self.alias.is_empty() {
array.set(ArrayKey::from("alias"), value::string(&self.alias));
}
let values = self
.values
.values()
.map(|v| match v {
Value::Ext(Object::Query(q)) => Value::Array(q.to_array()),
other => other.clone(),
})
.collect();
array.set(ArrayKey::from("values"), Value::Array(list(values)));
array
}
#[allow(clippy::inherent_to_string_shadow_display, clippy::inherent_to_string)]
pub fn to_string(&self) -> Result<String> {
value::json_encode(&Value::Array(self.to_array()), Flags::THROW_ON_ERROR)
.map_err(|e| Error::query(format!("Invalid Json: {}", e.message())))
}
pub fn compile(&self, compiler: &mut dyn Compiler) -> Result<String> {
use Method::*;
match self.method {
OrderAsc | OrderDesc | OrderRandom => compiler.compile_order(self),
Limit => compiler.compile_limit(self),
Offset => compiler.compile_offset(self),
CursorAfter | CursorBefore => compiler.compile_cursor(self),
Select => compiler.compile_select(self),
m if m.is_aggregate() => compiler.compile_aggregate(self),
GroupBy | GroupByTimeBucket => compiler.compile_group_by(self),
m if m.is_join() => compiler.compile_join(self),
_ => compiler.compile_filter(self),
}
}
pub fn equal(attribute: impl Into<String>, values: impl IntoValues) -> Self {
Query::new(Method::Equal, attribute, values.into_values(), "")
}
pub fn not_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
let values = match value.into_value() {
Value::Array(a) if a.is_list() => a,
other => list(vec![other]),
};
Query::new(Method::NotEqual, attribute, values, "")
}
pub fn less_than(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::LessThan, attribute, vec![value.into_value()])
}
pub fn less_than_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::LessThanEqual, attribute, vec![value.into_value()])
}
pub fn greater_than(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::GreaterThan, attribute, vec![value.into_value()])
}
pub fn greater_than_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::GreaterThanEqual, attribute, vec![value.into_value()])
}
pub fn contains(attribute: impl Into<String>, values: impl IntoValues) -> Self {
Query::new(Method::Contains, attribute, values.into_values(), "")
}
pub fn contains_string(attribute: impl Into<String>, values: impl IntoValues) -> Self {
Query::new(Method::Contains, attribute, values.into_values(), "")
}
pub fn contains_any(attribute: impl Into<String>, values: impl IntoValues) -> Self {
Query::new(Method::ContainsAny, attribute, values.into_values(), "")
}
pub fn not_contains(attribute: impl Into<String>, values: impl IntoValues) -> Self {
Query::new(Method::NotContains, attribute, values.into_values(), "")
}
pub fn between(attribute: impl Into<String>, start: impl IntoValue, end: impl IntoValue) -> Self {
Query::of(Method::Between, attribute, vec![start.into_value(), end.into_value()])
}
pub fn not_between(attribute: impl Into<String>, start: impl IntoValue, end: impl IntoValue) -> Self {
Query::of(Method::NotBetween, attribute, vec![start.into_value(), end.into_value()])
}
pub fn search(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::Search, attribute, vec![value.into_value()])
}
pub fn not_search(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::NotSearch, attribute, vec![value.into_value()])
}
pub fn select<S: Into<String>>(attributes: impl IntoIterator<Item = S>) -> Self {
Query::new(Method::Select, "", strings(attributes), "")
}
pub fn select_values(values: Array) -> Self {
Query::new(Method::Select, "", values, "")
}
pub fn order_desc(attribute: impl Into<String>, nulls: Option<NullsPosition>) -> Self {
Query::of(Method::OrderDesc, attribute, nulls.map(Value::from).into_iter().collect())
}
pub fn order_asc(attribute: impl Into<String>, nulls: Option<NullsPosition>) -> Self {
Query::of(Method::OrderAsc, attribute, nulls.map(Value::from).into_iter().collect())
}
pub fn order_random() -> Self {
Query::of(Method::OrderRandom, "", Vec::new())
}
pub fn limit(value: i64) -> Self {
Query::of(Method::Limit, "", vec![Value::Int(value)])
}
pub fn offset(value: i64) -> Self {
Query::of(Method::Offset, "", vec![Value::Int(value)])
}
pub fn cursor_after(row: Value) -> Self {
Query::of(Method::CursorAfter, "", vec![row])
}
pub fn cursor_before(row: Value) -> Self {
Query::of(Method::CursorBefore, "", vec![row])
}
pub fn is_null(attribute: impl Into<String>) -> Self {
Query::of(Method::IsNull, attribute, Vec::new())
}
pub fn is_not_null(attribute: impl Into<String>) -> Self {
Query::of(Method::IsNotNull, attribute, Vec::new())
}
pub fn starts_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::StartsWith, attribute, vec![value.into_value()])
}
pub fn not_starts_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::NotStartsWith, attribute, vec![value.into_value()])
}
pub fn ends_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::EndsWith, attribute, vec![value.into_value()])
}
pub fn not_ends_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::NotEndsWith, attribute, vec![value.into_value()])
}
pub fn created_before(value: impl IntoValue) -> Self {
Query::less_than("$createdAt", value)
}
pub fn created_after(value: impl IntoValue) -> Self {
Query::greater_than("$createdAt", value)
}
pub fn updated_before(value: impl IntoValue) -> Self {
Query::less_than("$updatedAt", value)
}
pub fn updated_after(value: impl IntoValue) -> Self {
Query::greater_than("$updatedAt", value)
}
pub fn created_between(start: impl IntoValue, end: impl IntoValue) -> Self {
Query::between("$createdAt", start, end)
}
pub fn updated_between(start: impl IntoValue, end: impl IntoValue) -> Self {
Query::between("$updatedAt", start, end)
}
pub fn or(queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::Or, "", self::queries(queries), "")
}
pub fn and(queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::And, "", self::queries(queries), "")
}
pub fn logical(method: Method, values: Array) -> Self {
Query::new(method, "", values, "")
}
pub fn contains_all(attribute: impl Into<String>, values: impl IntoValues) -> Self {
Query::new(Method::ContainsAll, attribute, values.into_values(), "")
}
pub fn by_type<'a>(queries: &'a [Query], methods: &[Method]) -> Vec<&'a Query> {
queries.iter().filter(|q| methods.contains(&q.method)).collect()
}
pub fn cursor_queries(queries: &[Query]) -> Vec<&Query> {
Query::by_type(queries, &[Method::CursorAfter, Method::CursorBefore])
}
pub fn group_by_type(queries: &[Query]) -> ParsedQuery {
let mut parsed = ParsedQuery::default();
for query in queries {
let method = query.method;
let first = query.values.get(&ArrayKey::Int(0));
match method {
Method::OrderAsc | Method::OrderDesc | Method::OrderRandom => {}
Method::Limit => {
if parsed.limit.is_none() {
parsed.limit = first.and_then(to_integer);
}
}
Method::Offset => {
if parsed.offset.is_none() {
parsed.offset = first.and_then(to_integer);
}
}
Method::CursorAfter | Method::CursorBefore => {
if parsed.cursor.is_none() {
parsed.cursor = first.filter(|v| !matches!(v, Value::Null)).cloned();
parsed.cursor_direction = Some(if method == Method::CursorAfter {
CursorDirection::After
} else {
CursorDirection::Before
});
}
}
Method::Select => parsed.selections.push(query.clone()),
m if m.is_aggregate() => parsed.aggregations.push(query.clone()),
Method::GroupBy => parsed.group_by.extend(query.values.values().cloned()),
Method::GroupByTimeBucket => parsed.time_buckets.push(TimeBucket {
attribute: query.attribute.clone(),
interval: first.filter(|v| !matches!(v, Value::Null)).cloned().unwrap_or_else(|| value::string("")),
}),
Method::Having => parsed.having.push(query.clone()),
Method::Distinct => parsed.distinct = true,
m if m.is_join() => parsed.joins.push(query.clone()),
Method::Union | Method::UnionAll => parsed.unions.push(query.clone()),
_ => parsed.filters.push(query.clone()),
}
}
parsed
}
pub fn distance_equal(attribute: impl Into<String>, values: Array, distance: impl IntoValue, meters: bool) -> Self {
Query::distance(Method::DistanceEqual, attribute, values, distance.into_value(), meters)
}
pub fn distance_not_equal(
attribute: impl Into<String>,
values: Array,
distance: impl IntoValue,
meters: bool,
) -> Self {
Query::distance(Method::DistanceNotEqual, attribute, values, distance.into_value(), meters)
}
pub fn distance_greater_than(
attribute: impl Into<String>,
values: Array,
distance: impl IntoValue,
meters: bool,
) -> Self {
Query::distance(Method::DistanceGreaterThan, attribute, values, distance.into_value(), meters)
}
pub fn distance_less_than(
attribute: impl Into<String>,
values: Array,
distance: impl IntoValue,
meters: bool,
) -> Self {
Query::distance(Method::DistanceLessThan, attribute, values, distance.into_value(), meters)
}
fn distance(method: Method, attribute: impl Into<String>, values: Array, distance: Value, meters: bool) -> Self {
let tuple = list(vec![Value::Array(values), distance, Value::Bool(meters)]);
Query::of(method, attribute, vec![Value::Array(tuple)])
}
fn geometry(method: Method, attribute: impl Into<String>, values: Array) -> Self {
Query::of(method, attribute, vec![Value::Array(values)])
}
pub fn intersects(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::Intersects, attribute, values)
}
pub fn not_intersects(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::NotIntersects, attribute, values)
}
pub fn crosses(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::Crosses, attribute, values)
}
pub fn not_crosses(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::NotCrosses, attribute, values)
}
pub fn overlaps(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::Overlaps, attribute, values)
}
pub fn not_overlaps(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::NotOverlaps, attribute, values)
}
pub fn touches(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::Touches, attribute, values)
}
pub fn not_touches(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::NotTouches, attribute, values)
}
pub fn vector_dot(attribute: impl Into<String>, vector: Array) -> Self {
Query::geometry(Method::VectorDot, attribute, vector)
}
pub fn vector_cosine(attribute: impl Into<String>, vector: Array) -> Self {
Query::geometry(Method::VectorCosine, attribute, vector)
}
pub fn vector_euclidean(attribute: impl Into<String>, vector: Array) -> Self {
Query::geometry(Method::VectorEuclidean, attribute, vector)
}
pub fn regex(attribute: impl Into<String>, pattern: impl IntoValue) -> Self {
Query::of(Method::Regex, attribute, vec![pattern.into_value()])
}
pub fn exists(attributes: Array) -> Self {
Query::new(Method::Exists, "", attributes, "")
}
pub fn not_exists(attribute: impl IntoValue) -> Self {
let values = match attribute.into_value() {
Value::Array(a) => a,
other => list(vec![other]),
};
Query::new(Method::NotExists, "", values, "")
}
pub fn elem_match(attribute: impl Into<String>, queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::ElemMatch, attribute, self::queries(queries), "")
}
pub fn relationship(attribute: impl Into<String>, queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::Relationship, attribute, self::queries(queries), "")
}
fn aggregate(method: Method, attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::new(method, attribute, Array::default(), alias)
}
pub fn count(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Count, attribute, alias)
}
pub fn count_distinct(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::CountDistinct, attribute, alias)
}
pub fn sum(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Sum, attribute, alias)
}
pub fn avg(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Avg, attribute, alias)
}
pub fn min(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Min, attribute, alias)
}
pub fn max(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Max, attribute, alias)
}
pub fn stddev(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Stddev, attribute, alias)
}
pub fn stddev_pop(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::StddevPop, attribute, alias)
}
pub fn stddev_samp(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::StddevSamp, attribute, alias)
}
pub fn variance(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::Variance, attribute, alias)
}
pub fn var_pop(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::VarPop, attribute, alias)
}
pub fn var_samp(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::VarSamp, attribute, alias)
}
pub fn bit_and(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::BitAnd, attribute, alias)
}
pub fn bit_or(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::BitOr, attribute, alias)
}
pub fn bit_xor(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
Query::aggregate(Method::BitXor, attribute, alias)
}
pub fn group_by<S: Into<String>>(attributes: impl IntoIterator<Item = S>) -> Self {
Query::new(Method::GroupBy, "", strings(attributes), "")
}
pub fn group_by_time_bucket(attribute: impl Into<String>, interval: &str) -> Result<Self> {
if !GROUP_BY_TIME_BUCKET_INTERVALS.contains(&interval) {
return Err(Error::Validation(format!(
"Invalid groupByTimeBucket interval: {interval}. Allowed: {}",
GROUP_BY_TIME_BUCKET_INTERVALS.join(", ")
)));
}
Ok(Query::of(Method::GroupByTimeBucket, attribute, vec![value::string(interval)]))
}
pub fn having(queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::Having, "", self::queries(queries), "")
}
pub fn distinct() -> Self {
Query::of(Method::Distinct, "", Vec::new())
}
pub fn on(left: impl Into<String>, right: impl Into<String>, operator: impl Into<String>) -> Self {
Query::new(
Method::On,
"",
list(vec![value::string(left.into()), value::string(operator.into()), value::string(right.into())]),
"",
)
}
pub fn join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
Query::create_join(Method::Join, collection.into(), alias.into(), on)
}
pub fn left_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
Query::create_join(Method::LeftJoin, collection.into(), alias.into(), on)
}
pub fn right_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
Query::create_join(Method::RightJoin, collection.into(), alias.into(), on)
}
pub fn full_outer_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
Query::create_join(Method::FullOuterJoin, collection.into(), alias.into(), on)
}
pub fn cross_join(collection: impl Into<String>, alias: impl Into<String>) -> Result<Self> {
Query::create_join(Method::CrossJoin, collection.into(), alias.into(), Vec::new())
}
pub fn natural_join(collection: impl Into<String>, alias: impl Into<String>) -> Result<Self> {
Query::create_join(Method::NaturalJoin, collection.into(), alias.into(), Vec::new())
}
pub fn join_values(
method: Method,
collection: impl Into<String>,
alias: impl Into<String>,
on: Array,
) -> Result<Self> {
let mut conditions = Vec::with_capacity(on.len());
let collection = collection.into();
let alias = alias.into();
let alias = if alias.is_empty() { collection.clone() } else { alias };
Query::check_join_alias(method, &collection, &alias, on.is_empty())?;
for value in on.values() {
match value {
Value::Ext(Object::Query(q)) => conditions.push((**q).clone()),
_ => return Err(Error::Validation("Join ON conditions must be Query objects".into())),
}
}
Query::create_join(method, collection, alias, conditions)
}
fn check_join_alias(method: Method, collection: &str, alias: &str, empty: bool) -> Result<()> {
if alias.is_empty() {
return Err(Error::Validation(format!("Join alias is required: {} {}", method.as_str(), collection)));
}
let unconditioned = method == Method::CrossJoin || method == Method::NaturalJoin;
if unconditioned && !empty {
return Err(Error::Validation(format!("Join ON conditions are not allowed in {}", method.as_str())));
}
if !unconditioned && empty {
return Err(Error::Validation("Join ON requires at least one condition".into()));
}
Ok(())
}
fn create_join(method: Method, collection: String, alias: String, on: Vec<Query>) -> Result<Self> {
let alias = if alias.is_empty() { collection.clone() } else { alias };
Query::check_join_alias(method, &collection, &alias, on.is_empty())?;
for condition in &on {
Query::assert_join_condition(condition)?;
}
Ok(Query::new(method, collection, self::queries(on), alias))
}
fn assert_join_condition(condition: &Query) -> Result<()> {
let method = condition.method;
if !method.is_join_condition() {
return Err(Error::Validation(format!("Unsupported join ON condition: {}", method.as_str())));
}
if method != Method::And && method != Method::Or {
return Ok(());
}
for child in condition.values.values() {
match child {
Value::Ext(Object::Query(q)) => Query::assert_join_condition(q)?,
_ => return Err(Error::Validation("Join ON conditions must be Query objects".into())),
}
}
Ok(())
}
pub fn union(queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::Union, "", self::queries(queries), "")
}
pub fn union_all(queries: impl IntoIterator<Item = Query>) -> Self {
Query::new(Method::UnionAll, "", self::queries(queries), "")
}
pub fn json_contains(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::JsonContains, attribute, vec![value.into_value()])
}
pub fn json_not_contains(attribute: impl Into<String>, value: impl IntoValue) -> Self {
Query::of(Method::JsonNotContains, attribute, vec![value.into_value()])
}
pub fn json_overlaps(attribute: impl Into<String>, values: Array) -> Self {
Query::of(Method::JsonOverlaps, attribute, vec![Value::Array(values)])
}
pub fn json_path(
attribute: impl Into<String>,
path: impl Into<String>,
operator: impl Into<String>,
value: impl IntoValue,
) -> Self {
Query::of(
Method::JsonPath,
attribute,
vec![value::string(path.into()), value::string(operator.into()), value.into_value()],
)
}
pub fn covers(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::Covers, attribute, values)
}
pub fn not_covers(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::NotCovers, attribute, values)
}
pub fn spatial_equals(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::SpatialEquals, attribute, values)
}
pub fn not_spatial_equals(attribute: impl Into<String>, values: Array) -> Self {
Query::geometry(Method::NotSpatialEquals, attribute, values)
}
pub fn raw(sql: impl Into<String>, bindings: Array) -> Self {
Query::new(Method::Raw, sql, bindings, "")
}
pub fn page(page: i64, per_page: i64) -> Result<[Query; 2]> {
if page < 1 {
return Err(Error::Validation(format!("Page must be >= 1, got {page}")));
}
if per_page < 1 {
return Err(Error::Validation(format!("Per page must be >= 1, got {per_page}")));
}
Ok([Query::limit(per_page), Query::offset((page - 1).wrapping_mul(per_page))])
}
pub fn merge(a: &[Query], b: &[Query]) -> Vec<Query> {
let singular = [Method::Limit, Method::Offset, Method::CursorAfter, Method::CursorBefore];
let mut result = a.to_vec();
for query in b {
if singular.contains(&query.method) {
result.retain(|q| q.method != query.method);
}
result.push(query.clone());
}
result
}
pub fn diff(a: &[Query], b: &[Query]) -> Vec<Query> {
let b: Vec<Value> = b.iter().map(|q| Value::Array(q.to_array())).collect();
a.iter()
.filter(|q| {
let array = Value::Array(q.to_array());
!b.iter().any(|other| value::identical(&array, other))
})
.cloned()
.collect()
}
pub fn validate<S: AsRef<str>>(queries: &[Query], allowed: &[S]) -> Result<Vec<String>> {
let allowed: Vec<&str> = allowed.iter().map(AsRef::as_ref).collect();
let mut errors = Vec::new();
Query::validate_into(queries.iter(), &allowed, &mut errors)?;
Ok(errors)
}
fn validate_into<'a>(
queries: impl Iterator<Item = &'a Query>,
allowed: &[&str],
errors: &mut Vec<String>,
) -> Result<()> {
use Method::*;
for query in queries {
let method = query.method;
if matches!(
method,
Limit
| Offset
| CursorAfter
| CursorBefore
| OrderRandom
| Distinct
| Select
| Exists
| NotExists
| Relationship
) {
continue;
}
if method.is_nested() {
Query::validate_into(query.nested(), allowed, errors)?;
continue;
}
if method == GroupBy {
for column in query.values.values() {
let is_allowed =
matches!(column, Value::Str(s) if s.as_str().is_some_and(|s| allowed.contains(&s)));
if !is_allowed {
errors.push(format!(
"Invalid attribute \"{}\" used in {}",
value::concat(column)?,
method.as_str()
));
}
}
continue;
}
let attribute = query.attribute.as_str();
if attribute.is_empty() || attribute == "*" {
continue;
}
if !allowed.contains(&attribute) {
errors.push(format!("Invalid attribute \"{attribute}\" used in {}", method.as_str()));
}
}
Ok(())
}
}
impl From<NullsPosition> for Object {
fn from(nulls: NullsPosition) -> Self {
Object::Nulls(nulls)
}
}
fn php_empty_str(s: &str) -> bool {
s.is_empty() || s == "0"
}
pub(crate) fn is_numeric(value: &Value) -> bool {
match value {
Value::Int(_) | Value::Float(_) => true,
Value::Str(s) => php_std::value::numeric_bytes_ex(s.as_bytes()).is_some(),
_ => false,
}
}
fn to_integer(value: &Value) -> Option<i64> {
use php_std::filter as f;
let text = match value {
Value::Int(i) => return Some(*i),
_ if !is_numeric(value) => return None,
Value::Float(x) => f::Value::Float(*x),
Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
_ => return None,
};
if let Ok(f::Filtered { value: f::Value::Int(i), .. }) =
f::filter_var(&text, f::FILTER_VALIDATE_INT, &f::Options::Flags(0))
{
return Some(i);
}
let number = value.to_double();
if !number.is_finite() || number < i64::MIN as f64 || number >= i64::MAX as f64 {
return None;
}
Some(number as i64)
}
pub(crate) fn compare_strings(a: &str, b: &str) -> Ordering {
value::string(a).cmp_php(&value::string(b))
}
fn lossy(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}