1use std::cmp::Ordering;
5
6use md5::{Digest, Md5};
7use php_std::ArrayKey;
8use php_std::json::{self, Flags};
9
10use crate::enums::{CursorDirection, NullsPosition};
11use crate::error::{Error, Result};
12use crate::method::Method;
13use crate::value::{self, Array, IntoValue, IntoValues, Object, Param, Value};
14
15#[derive(Debug, Clone, PartialEq)]
40pub struct Query {
41 method: Method,
42 attribute: String,
43 attribute_type: String,
44 on_array: bool,
45 values: Array,
46 alias: String,
47 alias_defaulted: bool,
48}
49
50#[derive(Debug, Clone, PartialEq, Default)]
54pub struct ParsedQuery {
55 pub filters: Vec<Query>,
57 pub selections: Vec<Query>,
59 pub aggregations: Vec<Query>,
61 pub group_by: Vec<Value>,
64 pub having: Vec<Query>,
66 pub distinct: bool,
68 pub joins: Vec<Query>,
70 pub unions: Vec<Query>,
72 pub limit: Option<i64>,
74 pub offset: Option<i64>,
76 pub cursor: Option<Value>,
78 pub cursor_direction: Option<CursorDirection>,
80 pub time_buckets: Vec<TimeBucket>,
82}
83
84impl ParsedQuery {
85 #[allow(clippy::too_many_arguments)]
89 pub fn new(
90 filters: Vec<Query>,
91 selections: Vec<Query>,
92 aggregations: Vec<Query>,
93 group_by: Vec<Value>,
94 having: Vec<Query>,
95 distinct: bool,
96 joins: Vec<Query>,
97 unions: Vec<Query>,
98 limit: Option<i64>,
99 offset: Option<i64>,
100 cursor: Option<Value>,
101 cursor_direction: Option<CursorDirection>,
102 time_buckets: Vec<TimeBucket>,
103 ) -> Self {
104 ParsedQuery {
105 filters,
106 selections,
107 aggregations,
108 group_by,
109 having,
110 distinct,
111 joins,
112 unions,
113 limit,
114 offset,
115 cursor,
116 cursor_direction,
117 time_buckets,
118 }
119 }
120}
121
122#[derive(Debug, Clone, PartialEq)]
124pub struct TimeBucket {
125 pub attribute: String,
127 pub interval: Value,
130}
131
132#[derive(Debug, Clone, Copy)]
134pub enum QueryOrJson<'a> {
135 Query(&'a Query),
137 Json(&'a str),
139}
140
141pub trait Compiler {
145 fn compile_filter(&mut self, query: &Query) -> Result<String>;
147 fn compile_order(&mut self, query: &Query) -> Result<String>;
149 fn compile_limit(&mut self, query: &Query) -> Result<String>;
151 fn compile_offset(&mut self, query: &Query) -> Result<String>;
153 fn compile_select(&mut self, query: &Query) -> Result<String>;
155 fn compile_cursor(&mut self, query: &Query) -> Result<String>;
157 fn compile_aggregate(&mut self, query: &Query) -> Result<String>;
159 fn compile_group_by(&mut self, query: &Query) -> Result<String>;
161 fn compile_join(&mut self, query: &Query) -> Result<String>;
163}
164
165pub const GROUP_BY_TIME_BUCKET_INTERVALS: [&str; 7] = ["1m", "5m", "15m", "1h", "1d", "1w", "1M"];
169
170pub const DEFAULT_ALIAS: &str = "main";
174
175fn list(values: Vec<Value>) -> Array {
176 Array::from_list(values)
177}
178
179fn strings<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Array {
180 list(items.into_iter().map(|s| value::string(s.into())).collect())
181}
182
183fn queries(items: impl IntoIterator<Item = Query>) -> Array {
184 list(items.into_iter().map(Value::from).collect())
185}
186
187fn gettype(value: &Value) -> &'static str {
189 value.type_name()
190}
191
192impl Query {
193 pub fn new(method: Method, attribute: impl Into<String>, values: Array, alias: impl Into<String>) -> Self {
197 let attribute = attribute.into();
198 let alias = alias.into();
199 let alias_defaulted = method.is_join() && !alias.is_empty() && alias == attribute;
200 Query { method, attribute, attribute_type: String::new(), on_array: false, values, alias, alias_defaulted }
201 }
202
203 fn of(method: Method, attribute: impl Into<String>, values: Vec<Value>) -> Self {
204 Query::new(method, attribute, list(values), "")
205 }
206
207 pub fn method(&self) -> Method {
211 self.method
212 }
213
214 pub fn attribute(&self) -> &str {
218 &self.attribute
219 }
220
221 pub fn values(&self) -> &Array {
225 &self.values
226 }
227
228 pub fn value(&self) -> Option<&Value> {
232 self.values.get(&ArrayKey::Int(0)).filter(|v| !matches!(v, Value::Null))
233 }
234
235 pub fn alias(&self) -> &str {
239 &self.alias
240 }
241
242 pub fn is_alias_defaulted(&self) -> bool {
248 self.alias_defaulted
249 }
250
251 pub fn on_array(&self) -> bool {
255 self.on_array
256 }
257
258 pub fn attribute_type(&self) -> &str {
262 &self.attribute_type
263 }
264
265 pub fn set_method(&mut self, method: Method) -> &mut Self {
269 self.method = method;
270 self
271 }
272
273 pub fn set_attribute(&mut self, attribute: impl Into<String>) -> &mut Self {
277 self.attribute = attribute.into();
278 self
279 }
280
281 pub fn set_values(&mut self, values: Array) -> &mut Self {
285 self.values = values;
286 self
287 }
288
289 pub fn set_value(&mut self, value: Value) -> &mut Self {
293 self.values = list(vec![value]);
294 self
295 }
296
297 pub fn set_on_array(&mut self, on_array: bool) {
301 self.on_array = on_array;
302 }
303
304 pub fn set_attribute_type(&mut self, attribute_type: impl Into<String>) {
308 self.attribute_type = attribute_type.into();
309 }
310
311 pub fn is_nested_join(&self) -> bool {
315 self.method.is_join() && self.values.values().any(|v| matches!(v, Value::Ext(Object::Query(_))))
316 }
317
318 pub fn join_on_queries(&self) -> Vec<&Query> {
322 if !self.is_nested_join() {
323 return Vec::new();
324 }
325 self.nested().collect()
326 }
327
328 pub fn nested(&self) -> impl Iterator<Item = &Query> {
330 self.values.values().filter_map(|v| match v {
331 Value::Ext(Object::Query(q)) => Some(&**q),
332 _ => None,
333 })
334 }
335
336 pub fn is_method(value: &str) -> bool {
340 Method::try_from_value(value).is_some()
341 }
342
343 pub fn is_spatial_query(&self) -> bool {
347 self.method.is_spatial()
348 }
349
350 pub fn is_nested(&self) -> bool {
354 self.method.is_nested()
355 }
356
357 pub fn parse(query: &str, allow_raw: bool) -> Result<Query> {
378 Query::parse_bytes(query.as_bytes(), allow_raw)
379 }
380
381 pub fn parse_bytes(query: &[u8], allow_raw: bool) -> Result<Query> {
383 let decoded: Value = json::decode_ext(query, Some(true), json::DEFAULT_DEPTH, Flags::THROW_ON_ERROR)
384 .map_err(|e| Error::query(format!("Invalid query: {}", e.message())))?;
385 match decoded {
386 Value::Array(array) => Query::parse_query(&array, allow_raw),
387 other => Err(Error::query(format!("Invalid query. Must be an array, got {}", gettype(&other)))),
388 }
389 }
390
391 pub fn parse_query(query: &Array, allow_raw: bool) -> Result<Query> {
396 let get = |key: &str| query.get_str(key).filter(|v| !matches!(v, Value::Null));
397 let method = get("method").cloned().unwrap_or_else(|| value::string(""));
398 let attribute = get("attribute").cloned().unwrap_or_else(|| value::string(""));
399 let values = get("values").cloned().unwrap_or(Value::Array(Array::default()));
400 let alias = get("alias").cloned().unwrap_or_else(|| value::string(""));
401
402 let Value::Str(method) = method else {
403 return Err(Error::query(format!("Invalid query method. Must be a string, got {}", gettype(&method))));
404 };
405 let Some(method) = method.as_str().and_then(Method::try_from_value) else {
406 return Err(Error::query(format!("Invalid query method: {}", String::from_utf8_lossy(method.as_bytes()))));
407 };
408 let Value::Str(attribute) = attribute else {
409 return Err(Error::query(format!(
410 "Invalid query attribute. Must be a string, got {}",
411 gettype(&attribute)
412 )));
413 };
414 let Value::Array(mut values) = values else {
415 return Err(Error::query(format!("Invalid query values. Must be an array, got {}", gettype(&values))));
416 };
417 let Value::Str(alias) = alias else {
418 return Err(Error::query(format!("Invalid query alias. Must be a string, got {}", gettype(&alias))));
419 };
420 let attribute = lossy(attribute.as_bytes());
421 let mut alias = lossy(alias.as_bytes());
422
423 if method == Method::Raw && !allow_raw {
424 return Err(Error::Validation(
425 "Raw queries cannot be parsed from untrusted input; construct via Query::raw() in code".into(),
426 ));
427 }
428
429 if method == Method::Distinct && (!attribute.is_empty() || !values.is_empty()) {
430 return Err(Error::query(
431 "Invalid distinct query: distinct takes no attribute or values, it deduplicates the attributes a select names",
432 ));
433 }
434
435 if method.is_join() {
436 return Query::parse_join(method, attribute, &values, alias, allow_raw);
437 }
438
439 if method.is_aggregate() {
440 if alias.is_empty()
441 && let Some(Value::Str(legacy)) = values.get(&ArrayKey::Int(0))
442 {
443 alias = lossy(legacy.as_bytes());
444 }
445 return Ok(Query::new(method, attribute, Array::default(), alias));
446 }
447
448 if method.is_nested() {
449 let mut parsed = Array::with_capacity(values.len());
450 for (key, value) in values.iter() {
451 let child =
452 Param::method("Utopia\\Query\\Query::parseQuery", 1, "query", "Query.php", 285).array(value)?;
453 parsed.set(key.to_owned(), Value::from(Query::parse_query(child, allow_raw)?));
454 }
455 values = parsed;
456 }
457
458 Ok(Query::new(method, attribute, values, alias))
459 }
460
461 fn parse_join(method: Method, collection: String, values: &Array, alias: String, allow_raw: bool) -> Result<Query> {
465 let mut on = Vec::new();
466 let mut names: Vec<String> = Vec::new();
467 for value in values.values() {
468 match value {
469 Value::Array(child) => on.push(Query::parse_query(child, allow_raw)?),
470 Value::Str(s) => names.push(lossy(s.as_bytes())),
471 other => {
472 return Err(Error::query(format!(
473 "Invalid join value. Must be a query or a string, got {}",
474 gettype(other)
475 )));
476 }
477 }
478 }
479 let column_form = on.is_empty() && names.len() >= 3;
480 if column_form {
481 on.push(Query::on(&names[0], &names[2], &names[1]));
482 }
483 let legacy = if column_form { names.get(3) } else { names.first() }.cloned().unwrap_or_default();
484 if names.len() > if column_form { 4 } else { 1 } {
485 return Err(Error::query(format!("Invalid join values for {} {}", method.as_str(), collection)));
486 }
487 Query::create_join(method, collection, if alias.is_empty() { legacy } else { alias }, on)
488 }
489
490 pub fn parse_queries<S: AsRef<str>>(queries: &[S], allow_raw: bool) -> Result<Vec<Query>> {
494 queries.iter().map(|q| Query::parse(q.as_ref(), allow_raw)).collect()
495 }
496
497 pub fn fingerprint(queries: &[QueryOrJson<'_>]) -> Result<String> {
519 let mut shapes = Vec::with_capacity(queries.len());
520 for query in queries {
521 shapes.push(match query {
522 QueryOrJson::Query(q) => q.shape(),
523 QueryOrJson::Json(json) => Query::parse(json, false)?.shape(),
524 });
525 }
526 shapes.sort_by(|a, b| compare_strings(a, b));
527 let digest = Md5::digest(shapes.join("|").as_bytes());
528 Ok(digest.iter().map(|b| format!("{b:02x}")).collect())
529 }
530
531 pub fn shape(&self) -> String {
537 let logical = matches!(self.method, Method::And | Method::Or | Method::ElemMatch | Method::Relationship);
538 if !logical && !self.is_nested_join() {
539 return format!("{}:{}", self.method.as_str(), self.attribute);
540 }
541 let mut children: Vec<String> = self.nested().map(Query::shape).collect();
542 children.sort_by(|a, b| compare_strings(a, b));
543 format!("{}:{}({})", self.method.as_str(), self.attribute, children.join("|"))
544 }
545
546 pub fn to_array(&self) -> Array {
551 let mut array = Array::with_capacity(4);
552 array.set(ArrayKey::from("method"), value::string(self.method.as_str()));
553 if !php_empty_str(&self.attribute) {
554 array.set(ArrayKey::from("attribute"), value::string(&self.attribute));
555 }
556 if !self.alias.is_empty() {
557 array.set(ArrayKey::from("alias"), value::string(&self.alias));
558 }
559 let values = self
560 .values
561 .values()
562 .map(|v| match v {
563 Value::Ext(Object::Query(q)) => Value::Array(q.to_array()),
564 other => other.clone(),
565 })
566 .collect();
567 array.set(ArrayKey::from("values"), Value::Array(list(values)));
568 array
569 }
570
571 #[allow(clippy::inherent_to_string_shadow_display, clippy::inherent_to_string)]
575 pub fn to_string(&self) -> Result<String> {
576 value::json_encode(&Value::Array(self.to_array()), Flags::THROW_ON_ERROR)
577 .map_err(|e| Error::query(format!("Invalid Json: {}", e.message())))
578 }
579
580 pub fn compile(&self, compiler: &mut dyn Compiler) -> Result<String> {
584 use Method::*;
585 match self.method {
586 OrderAsc | OrderDesc | OrderRandom => compiler.compile_order(self),
587 Limit => compiler.compile_limit(self),
588 Offset => compiler.compile_offset(self),
589 CursorAfter | CursorBefore => compiler.compile_cursor(self),
590 Select => compiler.compile_select(self),
591 m if m.is_aggregate() => compiler.compile_aggregate(self),
592 GroupBy | GroupByTimeBucket => compiler.compile_group_by(self),
593 m if m.is_join() => compiler.compile_join(self),
594 _ => compiler.compile_filter(self),
595 }
596 }
597
598 pub fn equal(attribute: impl Into<String>, values: impl IntoValues) -> Self {
602 Query::new(Method::Equal, attribute, values.into_values(), "")
603 }
604
605 pub fn not_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
610 let values = match value.into_value() {
611 Value::Array(a) if a.is_list() => a,
612 other => list(vec![other]),
613 };
614 Query::new(Method::NotEqual, attribute, values, "")
615 }
616
617 pub fn less_than(attribute: impl Into<String>, value: impl IntoValue) -> Self {
621 Query::of(Method::LessThan, attribute, vec![value.into_value()])
622 }
623
624 pub fn less_than_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
628 Query::of(Method::LessThanEqual, attribute, vec![value.into_value()])
629 }
630
631 pub fn greater_than(attribute: impl Into<String>, value: impl IntoValue) -> Self {
635 Query::of(Method::GreaterThan, attribute, vec![value.into_value()])
636 }
637
638 pub fn greater_than_equal(attribute: impl Into<String>, value: impl IntoValue) -> Self {
642 Query::of(Method::GreaterThanEqual, attribute, vec![value.into_value()])
643 }
644
645 pub fn contains(attribute: impl Into<String>, values: impl IntoValues) -> Self {
651 Query::new(Method::Contains, attribute, values.into_values(), "")
652 }
653
654 pub fn contains_string(attribute: impl Into<String>, values: impl IntoValues) -> Self {
658 Query::new(Method::Contains, attribute, values.into_values(), "")
659 }
660
661 pub fn contains_any(attribute: impl Into<String>, values: impl IntoValues) -> Self {
665 Query::new(Method::ContainsAny, attribute, values.into_values(), "")
666 }
667
668 pub fn not_contains(attribute: impl Into<String>, values: impl IntoValues) -> Self {
672 Query::new(Method::NotContains, attribute, values.into_values(), "")
673 }
674
675 pub fn between(attribute: impl Into<String>, start: impl IntoValue, end: impl IntoValue) -> Self {
679 Query::of(Method::Between, attribute, vec![start.into_value(), end.into_value()])
680 }
681
682 pub fn not_between(attribute: impl Into<String>, start: impl IntoValue, end: impl IntoValue) -> Self {
686 Query::of(Method::NotBetween, attribute, vec![start.into_value(), end.into_value()])
687 }
688
689 pub fn search(attribute: impl Into<String>, value: impl IntoValue) -> Self {
693 Query::of(Method::Search, attribute, vec![value.into_value()])
694 }
695
696 pub fn not_search(attribute: impl Into<String>, value: impl IntoValue) -> Self {
700 Query::of(Method::NotSearch, attribute, vec![value.into_value()])
701 }
702
703 pub fn select<S: Into<String>>(attributes: impl IntoIterator<Item = S>) -> Self {
707 Query::new(Method::Select, "", strings(attributes), "")
708 }
709
710 pub fn select_values(values: Array) -> Self {
712 Query::new(Method::Select, "", values, "")
713 }
714
715 pub fn order_desc(attribute: impl Into<String>, nulls: Option<NullsPosition>) -> Self {
719 Query::of(Method::OrderDesc, attribute, nulls.map(Value::from).into_iter().collect())
720 }
721
722 pub fn order_asc(attribute: impl Into<String>, nulls: Option<NullsPosition>) -> Self {
726 Query::of(Method::OrderAsc, attribute, nulls.map(Value::from).into_iter().collect())
727 }
728
729 pub fn order_random() -> Self {
733 Query::of(Method::OrderRandom, "", Vec::new())
734 }
735
736 pub fn limit(value: i64) -> Self {
740 Query::of(Method::Limit, "", vec![Value::Int(value)])
741 }
742
743 pub fn offset(value: i64) -> Self {
747 Query::of(Method::Offset, "", vec![Value::Int(value)])
748 }
749
750 pub fn cursor_after(row: Value) -> Self {
755 Query::of(Method::CursorAfter, "", vec![row])
756 }
757
758 pub fn cursor_before(row: Value) -> Self {
762 Query::of(Method::CursorBefore, "", vec![row])
763 }
764
765 pub fn is_null(attribute: impl Into<String>) -> Self {
769 Query::of(Method::IsNull, attribute, Vec::new())
770 }
771
772 pub fn is_not_null(attribute: impl Into<String>) -> Self {
776 Query::of(Method::IsNotNull, attribute, Vec::new())
777 }
778
779 pub fn starts_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
783 Query::of(Method::StartsWith, attribute, vec![value.into_value()])
784 }
785
786 pub fn not_starts_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
790 Query::of(Method::NotStartsWith, attribute, vec![value.into_value()])
791 }
792
793 pub fn ends_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
797 Query::of(Method::EndsWith, attribute, vec![value.into_value()])
798 }
799
800 pub fn not_ends_with(attribute: impl Into<String>, value: impl IntoValue) -> Self {
804 Query::of(Method::NotEndsWith, attribute, vec![value.into_value()])
805 }
806
807 pub fn created_before(value: impl IntoValue) -> Self {
811 Query::less_than("$createdAt", value)
812 }
813
814 pub fn created_after(value: impl IntoValue) -> Self {
818 Query::greater_than("$createdAt", value)
819 }
820
821 pub fn updated_before(value: impl IntoValue) -> Self {
825 Query::less_than("$updatedAt", value)
826 }
827
828 pub fn updated_after(value: impl IntoValue) -> Self {
832 Query::greater_than("$updatedAt", value)
833 }
834
835 pub fn created_between(start: impl IntoValue, end: impl IntoValue) -> Self {
839 Query::between("$createdAt", start, end)
840 }
841
842 pub fn updated_between(start: impl IntoValue, end: impl IntoValue) -> Self {
846 Query::between("$updatedAt", start, end)
847 }
848
849 pub fn or(queries: impl IntoIterator<Item = Query>) -> Self {
853 Query::new(Method::Or, "", self::queries(queries), "")
854 }
855
856 pub fn and(queries: impl IntoIterator<Item = Query>) -> Self {
860 Query::new(Method::And, "", self::queries(queries), "")
861 }
862
863 pub fn logical(method: Method, values: Array) -> Self {
865 Query::new(method, "", values, "")
866 }
867
868 pub fn contains_all(attribute: impl Into<String>, values: impl IntoValues) -> Self {
872 Query::new(Method::ContainsAll, attribute, values.into_values(), "")
873 }
874
875 pub fn by_type<'a>(queries: &'a [Query], methods: &[Method]) -> Vec<&'a Query> {
879 queries.iter().filter(|q| methods.contains(&q.method)).collect()
880 }
881
882 pub fn cursor_queries(queries: &[Query]) -> Vec<&Query> {
886 Query::by_type(queries, &[Method::CursorAfter, Method::CursorBefore])
887 }
888
889 pub fn group_by_type(queries: &[Query]) -> ParsedQuery {
893 let mut parsed = ParsedQuery::default();
894 for query in queries {
895 let method = query.method;
896 let first = query.values.get(&ArrayKey::Int(0));
897 match method {
898 Method::OrderAsc | Method::OrderDesc | Method::OrderRandom => {}
899 Method::Limit => {
900 if parsed.limit.is_none() {
901 parsed.limit = first.and_then(to_integer);
902 }
903 }
904 Method::Offset => {
905 if parsed.offset.is_none() {
906 parsed.offset = first.and_then(to_integer);
907 }
908 }
909 Method::CursorAfter | Method::CursorBefore => {
910 if parsed.cursor.is_none() {
911 parsed.cursor = first.filter(|v| !matches!(v, Value::Null)).cloned();
912 parsed.cursor_direction = Some(if method == Method::CursorAfter {
913 CursorDirection::After
914 } else {
915 CursorDirection::Before
916 });
917 }
918 }
919 Method::Select => parsed.selections.push(query.clone()),
920 m if m.is_aggregate() => parsed.aggregations.push(query.clone()),
921 Method::GroupBy => parsed.group_by.extend(query.values.values().cloned()),
922 Method::GroupByTimeBucket => parsed.time_buckets.push(TimeBucket {
923 attribute: query.attribute.clone(),
924 interval: first.filter(|v| !matches!(v, Value::Null)).cloned().unwrap_or_else(|| value::string("")),
925 }),
926 Method::Having => parsed.having.push(query.clone()),
927 Method::Distinct => parsed.distinct = true,
928 m if m.is_join() => parsed.joins.push(query.clone()),
929 Method::Union | Method::UnionAll => parsed.unions.push(query.clone()),
930 _ => parsed.filters.push(query.clone()),
931 }
932 }
933 parsed
934 }
935
936 pub fn distance_equal(attribute: impl Into<String>, values: Array, distance: impl IntoValue, meters: bool) -> Self {
941 Query::distance(Method::DistanceEqual, attribute, values, distance.into_value(), meters)
942 }
943
944 pub fn distance_not_equal(
948 attribute: impl Into<String>,
949 values: Array,
950 distance: impl IntoValue,
951 meters: bool,
952 ) -> Self {
953 Query::distance(Method::DistanceNotEqual, attribute, values, distance.into_value(), meters)
954 }
955
956 pub fn distance_greater_than(
960 attribute: impl Into<String>,
961 values: Array,
962 distance: impl IntoValue,
963 meters: bool,
964 ) -> Self {
965 Query::distance(Method::DistanceGreaterThan, attribute, values, distance.into_value(), meters)
966 }
967
968 pub fn distance_less_than(
972 attribute: impl Into<String>,
973 values: Array,
974 distance: impl IntoValue,
975 meters: bool,
976 ) -> Self {
977 Query::distance(Method::DistanceLessThan, attribute, values, distance.into_value(), meters)
978 }
979
980 fn distance(method: Method, attribute: impl Into<String>, values: Array, distance: Value, meters: bool) -> Self {
981 let tuple = list(vec![Value::Array(values), distance, Value::Bool(meters)]);
982 Query::of(method, attribute, vec![Value::Array(tuple)])
983 }
984
985 fn geometry(method: Method, attribute: impl Into<String>, values: Array) -> Self {
986 Query::of(method, attribute, vec![Value::Array(values)])
987 }
988
989 pub fn intersects(attribute: impl Into<String>, values: Array) -> Self {
993 Query::geometry(Method::Intersects, attribute, values)
994 }
995
996 pub fn not_intersects(attribute: impl Into<String>, values: Array) -> Self {
1000 Query::geometry(Method::NotIntersects, attribute, values)
1001 }
1002
1003 pub fn crosses(attribute: impl Into<String>, values: Array) -> Self {
1007 Query::geometry(Method::Crosses, attribute, values)
1008 }
1009
1010 pub fn not_crosses(attribute: impl Into<String>, values: Array) -> Self {
1014 Query::geometry(Method::NotCrosses, attribute, values)
1015 }
1016
1017 pub fn overlaps(attribute: impl Into<String>, values: Array) -> Self {
1021 Query::geometry(Method::Overlaps, attribute, values)
1022 }
1023
1024 pub fn not_overlaps(attribute: impl Into<String>, values: Array) -> Self {
1028 Query::geometry(Method::NotOverlaps, attribute, values)
1029 }
1030
1031 pub fn touches(attribute: impl Into<String>, values: Array) -> Self {
1035 Query::geometry(Method::Touches, attribute, values)
1036 }
1037
1038 pub fn not_touches(attribute: impl Into<String>, values: Array) -> Self {
1042 Query::geometry(Method::NotTouches, attribute, values)
1043 }
1044
1045 pub fn vector_dot(attribute: impl Into<String>, vector: Array) -> Self {
1049 Query::geometry(Method::VectorDot, attribute, vector)
1050 }
1051
1052 pub fn vector_cosine(attribute: impl Into<String>, vector: Array) -> Self {
1056 Query::geometry(Method::VectorCosine, attribute, vector)
1057 }
1058
1059 pub fn vector_euclidean(attribute: impl Into<String>, vector: Array) -> Self {
1063 Query::geometry(Method::VectorEuclidean, attribute, vector)
1064 }
1065
1066 pub fn regex(attribute: impl Into<String>, pattern: impl IntoValue) -> Self {
1070 Query::of(Method::Regex, attribute, vec![pattern.into_value()])
1071 }
1072
1073 pub fn exists(attributes: Array) -> Self {
1077 Query::new(Method::Exists, "", attributes, "")
1078 }
1079
1080 pub fn not_exists(attribute: impl IntoValue) -> Self {
1084 let values = match attribute.into_value() {
1085 Value::Array(a) => a,
1086 other => list(vec![other]),
1087 };
1088 Query::new(Method::NotExists, "", values, "")
1089 }
1090
1091 pub fn elem_match(attribute: impl Into<String>, queries: impl IntoIterator<Item = Query>) -> Self {
1095 Query::new(Method::ElemMatch, attribute, self::queries(queries), "")
1096 }
1097
1098 pub fn relationship(attribute: impl Into<String>, queries: impl IntoIterator<Item = Query>) -> Self {
1115 Query::new(Method::Relationship, attribute, self::queries(queries), "")
1116 }
1117
1118 fn aggregate(method: Method, attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1119 Query::new(method, attribute, Array::default(), alias)
1120 }
1121
1122 pub fn count(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1126 Query::aggregate(Method::Count, attribute, alias)
1127 }
1128
1129 pub fn count_distinct(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1133 Query::aggregate(Method::CountDistinct, attribute, alias)
1134 }
1135
1136 pub fn sum(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1140 Query::aggregate(Method::Sum, attribute, alias)
1141 }
1142
1143 pub fn avg(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1147 Query::aggregate(Method::Avg, attribute, alias)
1148 }
1149
1150 pub fn min(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1154 Query::aggregate(Method::Min, attribute, alias)
1155 }
1156
1157 pub fn max(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1161 Query::aggregate(Method::Max, attribute, alias)
1162 }
1163
1164 pub fn stddev(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1168 Query::aggregate(Method::Stddev, attribute, alias)
1169 }
1170
1171 pub fn stddev_pop(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1175 Query::aggregate(Method::StddevPop, attribute, alias)
1176 }
1177
1178 pub fn stddev_samp(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1182 Query::aggregate(Method::StddevSamp, attribute, alias)
1183 }
1184
1185 pub fn variance(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1189 Query::aggregate(Method::Variance, attribute, alias)
1190 }
1191
1192 pub fn var_pop(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1196 Query::aggregate(Method::VarPop, attribute, alias)
1197 }
1198
1199 pub fn var_samp(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1203 Query::aggregate(Method::VarSamp, attribute, alias)
1204 }
1205
1206 pub fn bit_and(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1210 Query::aggregate(Method::BitAnd, attribute, alias)
1211 }
1212
1213 pub fn bit_or(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1217 Query::aggregate(Method::BitOr, attribute, alias)
1218 }
1219
1220 pub fn bit_xor(attribute: impl Into<String>, alias: impl Into<String>) -> Self {
1224 Query::aggregate(Method::BitXor, attribute, alias)
1225 }
1226
1227 pub fn group_by<S: Into<String>>(attributes: impl IntoIterator<Item = S>) -> Self {
1231 Query::new(Method::GroupBy, "", strings(attributes), "")
1232 }
1233
1234 pub fn group_by_time_bucket(attribute: impl Into<String>, interval: &str) -> Result<Self> {
1239 if !GROUP_BY_TIME_BUCKET_INTERVALS.contains(&interval) {
1240 return Err(Error::Validation(format!(
1241 "Invalid groupByTimeBucket interval: {interval}. Allowed: {}",
1242 GROUP_BY_TIME_BUCKET_INTERVALS.join(", ")
1243 )));
1244 }
1245 Ok(Query::of(Method::GroupByTimeBucket, attribute, vec![value::string(interval)]))
1246 }
1247
1248 pub fn having(queries: impl IntoIterator<Item = Query>) -> Self {
1252 Query::new(Method::Having, "", self::queries(queries), "")
1253 }
1254
1255 pub fn distinct() -> Self {
1259 Query::of(Method::Distinct, "", Vec::new())
1260 }
1261
1262 pub fn on(left: impl Into<String>, right: impl Into<String>, operator: impl Into<String>) -> Self {
1266 Query::new(
1267 Method::On,
1268 "",
1269 list(vec![value::string(left.into()), value::string(operator.into()), value::string(right.into())]),
1270 "",
1271 )
1272 }
1273
1274 pub fn join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1278 Query::create_join(Method::Join, collection.into(), alias.into(), on)
1279 }
1280
1281 pub fn left_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1285 Query::create_join(Method::LeftJoin, collection.into(), alias.into(), on)
1286 }
1287
1288 pub fn right_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1292 Query::create_join(Method::RightJoin, collection.into(), alias.into(), on)
1293 }
1294
1295 pub fn full_outer_join(collection: impl Into<String>, alias: impl Into<String>, on: Vec<Query>) -> Result<Self> {
1299 Query::create_join(Method::FullOuterJoin, collection.into(), alias.into(), on)
1300 }
1301
1302 pub fn cross_join(collection: impl Into<String>, alias: impl Into<String>) -> Result<Self> {
1306 Query::create_join(Method::CrossJoin, collection.into(), alias.into(), Vec::new())
1307 }
1308
1309 pub fn natural_join(collection: impl Into<String>, alias: impl Into<String>) -> Result<Self> {
1313 Query::create_join(Method::NaturalJoin, collection.into(), alias.into(), Vec::new())
1314 }
1315
1316 pub fn join_values(
1318 method: Method,
1319 collection: impl Into<String>,
1320 alias: impl Into<String>,
1321 on: Array,
1322 ) -> Result<Self> {
1323 let mut conditions = Vec::with_capacity(on.len());
1324 let collection = collection.into();
1325 let alias = alias.into();
1326 let alias = if alias.is_empty() { collection.clone() } else { alias };
1327 Query::check_join_alias(method, &collection, &alias, on.is_empty())?;
1328 for value in on.values() {
1329 match value {
1330 Value::Ext(Object::Query(q)) => conditions.push((**q).clone()),
1331 _ => return Err(Error::Validation("Join ON conditions must be Query objects".into())),
1332 }
1333 }
1334 Query::create_join(method, collection, alias, conditions)
1335 }
1336
1337 fn check_join_alias(method: Method, collection: &str, alias: &str, empty: bool) -> Result<()> {
1338 if alias.is_empty() {
1339 return Err(Error::Validation(format!("Join alias is required: {} {}", method.as_str(), collection)));
1341 }
1342 let unconditioned = method == Method::CrossJoin || method == Method::NaturalJoin;
1343 if unconditioned && !empty {
1344 return Err(Error::Validation(format!("Join ON conditions are not allowed in {}", method.as_str())));
1345 }
1346 if !unconditioned && empty {
1347 return Err(Error::Validation("Join ON requires at least one condition".into()));
1348 }
1349 Ok(())
1350 }
1351
1352 fn create_join(method: Method, collection: String, alias: String, on: Vec<Query>) -> Result<Self> {
1354 let alias = if alias.is_empty() { collection.clone() } else { alias };
1355 Query::check_join_alias(method, &collection, &alias, on.is_empty())?;
1356 for condition in &on {
1357 Query::assert_join_condition(condition)?;
1358 }
1359 Ok(Query::new(method, collection, self::queries(on), alias))
1360 }
1361
1362 fn assert_join_condition(condition: &Query) -> Result<()> {
1363 let method = condition.method;
1364 if !method.is_join_condition() {
1365 return Err(Error::Validation(format!("Unsupported join ON condition: {}", method.as_str())));
1366 }
1367 if method != Method::And && method != Method::Or {
1368 return Ok(());
1369 }
1370 for child in condition.values.values() {
1371 match child {
1372 Value::Ext(Object::Query(q)) => Query::assert_join_condition(q)?,
1373 _ => return Err(Error::Validation("Join ON conditions must be Query objects".into())),
1374 }
1375 }
1376 Ok(())
1377 }
1378
1379 pub fn union(queries: impl IntoIterator<Item = Query>) -> Self {
1383 Query::new(Method::Union, "", self::queries(queries), "")
1384 }
1385
1386 pub fn union_all(queries: impl IntoIterator<Item = Query>) -> Self {
1390 Query::new(Method::UnionAll, "", self::queries(queries), "")
1391 }
1392
1393 pub fn json_contains(attribute: impl Into<String>, value: impl IntoValue) -> Self {
1397 Query::of(Method::JsonContains, attribute, vec![value.into_value()])
1398 }
1399
1400 pub fn json_not_contains(attribute: impl Into<String>, value: impl IntoValue) -> Self {
1404 Query::of(Method::JsonNotContains, attribute, vec![value.into_value()])
1405 }
1406
1407 pub fn json_overlaps(attribute: impl Into<String>, values: Array) -> Self {
1411 Query::of(Method::JsonOverlaps, attribute, vec![Value::Array(values)])
1412 }
1413
1414 pub fn json_path(
1418 attribute: impl Into<String>,
1419 path: impl Into<String>,
1420 operator: impl Into<String>,
1421 value: impl IntoValue,
1422 ) -> Self {
1423 Query::of(
1424 Method::JsonPath,
1425 attribute,
1426 vec![value::string(path.into()), value::string(operator.into()), value.into_value()],
1427 )
1428 }
1429
1430 pub fn covers(attribute: impl Into<String>, values: Array) -> Self {
1434 Query::geometry(Method::Covers, attribute, values)
1435 }
1436
1437 pub fn not_covers(attribute: impl Into<String>, values: Array) -> Self {
1441 Query::geometry(Method::NotCovers, attribute, values)
1442 }
1443
1444 pub fn spatial_equals(attribute: impl Into<String>, values: Array) -> Self {
1448 Query::geometry(Method::SpatialEquals, attribute, values)
1449 }
1450
1451 pub fn not_spatial_equals(attribute: impl Into<String>, values: Array) -> Self {
1455 Query::geometry(Method::NotSpatialEquals, attribute, values)
1456 }
1457
1458 pub fn raw(sql: impl Into<String>, bindings: Array) -> Self {
1462 Query::new(Method::Raw, sql, bindings, "")
1463 }
1464
1465 pub fn page(page: i64, per_page: i64) -> Result<[Query; 2]> {
1469 if page < 1 {
1470 return Err(Error::Validation(format!("Page must be >= 1, got {page}")));
1471 }
1472 if per_page < 1 {
1473 return Err(Error::Validation(format!("Per page must be >= 1, got {per_page}")));
1474 }
1475 Ok([Query::limit(per_page), Query::offset((page - 1).wrapping_mul(per_page))])
1476 }
1477
1478 pub fn merge(a: &[Query], b: &[Query]) -> Vec<Query> {
1483 let singular = [Method::Limit, Method::Offset, Method::CursorAfter, Method::CursorBefore];
1484 let mut result = a.to_vec();
1485 for query in b {
1486 if singular.contains(&query.method) {
1487 result.retain(|q| q.method != query.method);
1488 }
1489 result.push(query.clone());
1490 }
1491 result
1492 }
1493
1494 pub fn diff(a: &[Query], b: &[Query]) -> Vec<Query> {
1498 let b: Vec<Value> = b.iter().map(|q| Value::Array(q.to_array())).collect();
1499 a.iter()
1500 .filter(|q| {
1501 let array = Value::Array(q.to_array());
1502 !b.iter().any(|other| value::identical(&array, other))
1503 })
1504 .cloned()
1505 .collect()
1506 }
1507
1508 pub fn validate<S: AsRef<str>>(queries: &[Query], allowed: &[S]) -> Result<Vec<String>> {
1514 let allowed: Vec<&str> = allowed.iter().map(AsRef::as_ref).collect();
1515 let mut errors = Vec::new();
1516 Query::validate_into(queries.iter(), &allowed, &mut errors)?;
1517 Ok(errors)
1518 }
1519
1520 fn validate_into<'a>(
1521 queries: impl Iterator<Item = &'a Query>,
1522 allowed: &[&str],
1523 errors: &mut Vec<String>,
1524 ) -> Result<()> {
1525 use Method::*;
1526 for query in queries {
1527 let method = query.method;
1528 if matches!(
1531 method,
1532 Limit
1533 | Offset
1534 | CursorAfter
1535 | CursorBefore
1536 | OrderRandom
1537 | Distinct
1538 | Select
1539 | Exists
1540 | NotExists
1541 | Relationship
1542 ) {
1543 continue;
1544 }
1545 if method.is_nested() {
1546 Query::validate_into(query.nested(), allowed, errors)?;
1547 continue;
1548 }
1549 if method == GroupBy {
1550 for column in query.values.values() {
1551 let is_allowed =
1552 matches!(column, Value::Str(s) if s.as_str().is_some_and(|s| allowed.contains(&s)));
1553 if !is_allowed {
1554 errors.push(format!(
1555 "Invalid attribute \"{}\" used in {}",
1556 value::concat(column)?,
1557 method.as_str()
1558 ));
1559 }
1560 }
1561 continue;
1562 }
1563 let attribute = query.attribute.as_str();
1564 if attribute.is_empty() || attribute == "*" {
1565 continue;
1566 }
1567 if !allowed.contains(&attribute) {
1568 errors.push(format!("Invalid attribute \"{attribute}\" used in {}", method.as_str()));
1569 }
1570 }
1571 Ok(())
1572 }
1573}
1574
1575impl From<NullsPosition> for Object {
1576 fn from(nulls: NullsPosition) -> Self {
1578 Object::Nulls(nulls)
1579 }
1580}
1581
1582fn php_empty_str(s: &str) -> bool {
1584 s.is_empty() || s == "0"
1585}
1586
1587pub(crate) fn is_numeric(value: &Value) -> bool {
1589 match value {
1590 Value::Int(_) | Value::Float(_) => true,
1591 Value::Str(s) => php_std::value::numeric_bytes_ex(s.as_bytes()).is_some(),
1592 _ => false,
1593 }
1594}
1595
1596fn to_integer(value: &Value) -> Option<i64> {
1599 use php_std::filter as f;
1600 let text = match value {
1601 Value::Int(i) => return Some(*i),
1602 _ if !is_numeric(value) => return None,
1603 Value::Float(x) => f::Value::Float(*x),
1604 Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
1605 _ => return None,
1606 };
1607 if let Ok(f::Filtered { value: f::Value::Int(i), .. }) =
1608 f::filter_var(&text, f::FILTER_VALIDATE_INT, &f::Options::Flags(0))
1609 {
1610 return Some(i);
1611 }
1612 let number = value.to_double();
1613 if !number.is_finite() || number < i64::MIN as f64 || number >= i64::MAX as f64 {
1614 return None;
1615 }
1616 Some(number as i64)
1617}
1618
1619pub(crate) fn compare_strings(a: &str, b: &str) -> Ordering {
1622 value::string(a).cmp_php(&value::string(b))
1623}
1624
1625fn lossy(bytes: &[u8]) -> String {
1626 String::from_utf8_lossy(bytes).into_owned()
1627}