1pub use crate::ast::{Condition, Direction, JsonPathSegment, SimpleOperator};
28pub use crate::client::Transaction;
29pub use crate::ivm::{ViewEntry, ViewValue};
30pub use crate::json::{Object, Value};
31pub use crate::query::{AnyGroupedQuery, AnyQuery, ExistsOptions, StaticParameter};
32pub use crate::schema::Schema;
33
34use crate::ast::{System, ValuePosition};
35use crate::client::Error;
36use crate::query::{ExpressionBuilder, JsonPathReference};
37use std::fmt;
38use std::marker::PhantomData;
39use std::sync::Arc;
40
41#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct ZeroValueError(pub String);
44
45impl ZeroValueError {
46 pub fn mismatch(expected: &str, value: &Value) -> Self {
48 ZeroValueError(format!(
49 "expected {expected}, got {} {}",
50 value.type_name(),
51 crate::json::stringify(value)
52 ))
53 }
54}
55
56impl fmt::Display for ZeroValueError {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 f.write_str(&self.0)
59 }
60}
61
62impl std::error::Error for ZeroValueError {}
63
64pub trait ZeroValue: Sized {
67 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError>;
69 fn to_zero_value(&self) -> Value;
71 fn value_for_null() -> Option<Self> {
77 None
78 }
79}
80
81impl ZeroValue for String {
82 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
83 value
84 .as_str()
85 .map(str::to_owned)
86 .ok_or_else(|| ZeroValueError::mismatch("a string", value))
87 }
88 fn to_zero_value(&self) -> Value {
89 Value::String(self.clone())
90 }
91 fn value_for_null() -> Option<Self> {
92 Some(String::new())
93 }
94}
95
96impl ZeroValue for f64 {
97 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
98 value
99 .as_f64()
100 .ok_or_else(|| ZeroValueError::mismatch("a number", value))
101 }
102 fn to_zero_value(&self) -> Value {
103 Value::Number(*self)
104 }
105 fn value_for_null() -> Option<Self> {
106 Some(0.0)
107 }
108}
109
110impl ZeroValue for i64 {
113 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
114 const MAX_SAFE: f64 = 9_007_199_254_740_992.0;
115 match value.as_f64() {
116 Some(n) if n.fract() == 0.0 && n.abs() <= MAX_SAFE => Ok(n as i64),
117 _ => Err(ZeroValueError::mismatch("an integer", value)),
118 }
119 }
120 fn to_zero_value(&self) -> Value {
121 Value::Number(*self as f64)
122 }
123 fn value_for_null() -> Option<Self> {
124 Some(0)
125 }
126}
127
128impl ZeroValue for bool {
129 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
130 value
131 .as_bool()
132 .ok_or_else(|| ZeroValueError::mismatch("a boolean", value))
133 }
134 fn to_zero_value(&self) -> Value {
135 Value::Bool(*self)
136 }
137 fn value_for_null() -> Option<Self> {
138 Some(false)
139 }
140}
141
142impl ZeroValue for Value {
143 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
144 Ok(value.clone())
145 }
146 fn to_zero_value(&self) -> Value {
147 self.clone()
148 }
149}
150
151impl<T: ZeroValue> ZeroValue for Option<T> {
153 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
154 if value.is_null() {
155 Ok(None)
156 } else {
157 T::from_zero_value(value).map(Some)
158 }
159 }
160 fn to_zero_value(&self) -> Value {
161 self.as_ref().map_or(Value::Null, T::to_zero_value)
162 }
163}
164
165impl<T: ZeroValue> ZeroValue for Vec<T> {
167 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
168 value
169 .as_array()
170 .ok_or_else(|| ZeroValueError::mismatch("an array", value))?
171 .iter()
172 .map(T::from_zero_value)
173 .collect()
174 }
175 fn to_zero_value(&self) -> Value {
176 Value::Array(self.iter().map(T::to_zero_value).collect())
177 }
178}
179
180pub trait NumericZeroValue: ZeroValue {}
182impl NumericZeroValue for f64 {}
183impl NumericZeroValue for i64 {}
184impl<T: NumericZeroValue> NumericZeroValue for Option<T> {}
185
186pub trait OrderedZeroValue: ZeroValue {
190 type Unwrapped: ZeroValue + OptionalQueryElement;
192}
193impl OrderedZeroValue for f64 {
194 type Unwrapped = f64;
195}
196impl OrderedZeroValue for i64 {
197 type Unwrapped = i64;
198}
199impl OrderedZeroValue for String {
200 type Unwrapped = String;
201}
202impl<T: OrderedZeroValue> OrderedZeroValue for Option<T> {
203 type Unwrapped = T::Unwrapped;
204}
205
206pub fn decode<V: ZeroValue>(name: &str, value: Option<&Value>) -> Result<V, ZeroValueError> {
209 let value = value.unwrap_or(&Value::Null);
210 if value.is_null()
211 && let Some(fallback) = V::value_for_null()
212 {
213 return Ok(fallback);
214 }
215 V::from_zero_value(value).map_err(|e| ZeroValueError(format!("{name}: {e}")))
216}
217
218pub fn column<V: ZeroValue>(
222 entry: &ViewEntry,
223 name: &str,
224 index: usize,
225) -> Result<V, ZeroValueError> {
226 match entry.row.get_index(index) {
227 Some((k, v)) if k == name => decode(name, Some(v)),
228 _ => decode(name, entry.row.get(name)),
229 }
230}
231
232pub fn many<R: QueryElement>(
236 entry: &ViewEntry,
237 name: &str,
238) -> Result<Option<Vec<R>>, ZeroValueError> {
239 match entry.relationship(name) {
240 None | Some(ViewValue::Value(_)) => Ok(None),
241 Some(v) => v
242 .entries()
243 .into_iter()
244 .map(R::from_entry)
245 .collect::<Result<_, _>>()
246 .map(Some),
247 }
248}
249
250pub fn one<R: QueryElement>(
253 entry: &ViewEntry,
254 name: &str,
255) -> Result<Option<Box<R>>, ZeroValueError> {
256 match entry
257 .relationship(name)
258 .and_then(|v| v.entries().first().copied())
259 {
260 Some(e) => R::from_entry(e).map(|r| Some(Box::new(r))),
261 None => Ok(None),
262 }
263}
264
265pub fn object<'a>(value: &'a Value, type_name: &str) -> Result<&'a Object, ZeroValueError> {
267 value
268 .as_object()
269 .ok_or_else(|| ZeroValueError::mismatch(&format!("a {type_name} object"), value))
270}
271
272pub fn field<V: ZeroValue>(object: &Object, name: &str) -> Result<V, ZeroValueError> {
275 V::from_zero_value(object.get(name).unwrap_or(&Value::Null))
276 .map_err(|e| ZeroValueError(format!("{name}: {e}")))
277}
278
279pub fn schema_from_json(json: &str) -> Arc<Schema> {
282 let value = crate::json::parse(json).expect("the generated schema is JSON");
283 Arc::new(Schema::from_json(&value).expect("the generated schema is a schema"))
284}
285
286pub trait QueryElement: Sized {
289 fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError>;
291}
292
293pub trait ZeroRow: QueryElement {
297 const TABLE: &'static str;
299 type Update: ColumnValues;
302 type Key: ColumnValues;
304 fn column_values(&self) -> Object;
306}
307
308pub trait ColumnValues {
311 fn column_values(&self) -> Object;
313}
314
315pub struct TypedTableMutator<'tx, R> {
323 tx: &'tx Transaction,
324 row: PhantomData<fn() -> R>,
325}
326
327impl<'tx, R: ZeroRow> TypedTableMutator<'tx, R> {
328 pub fn new(tx: &'tx Transaction) -> Self {
330 TypedTableMutator {
331 tx,
332 row: PhantomData,
333 }
334 }
335
336 pub fn insert(&self, row: &R) -> Result<(), Error> {
338 self.tx.table(R::TABLE).insert(&row.column_values())
339 }
340
341 pub fn upsert(&self, row: &R) -> Result<(), Error> {
346 self.tx.table(R::TABLE).upsert(&row.column_values())
347 }
348
349 pub fn update(&self, value: &R::Update) -> Result<(), Error> {
352 self.tx.table(R::TABLE).update(&value.column_values())
353 }
354
355 pub fn delete(&self, key: &R::Key) -> Result<(), Error> {
357 self.tx.table(R::TABLE).delete(&key.column_values())
358 }
359}
360
361#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
365pub enum ColumnUpdate<V> {
366 #[default]
367 Unchanged,
369 Null,
371 Set(V),
373}
374
375impl<V> From<Option<V>> for ColumnUpdate<V> {
376 fn from(value: Option<V>) -> Self {
378 value.map_or(ColumnUpdate::Null, ColumnUpdate::Set)
379 }
380}
381
382impl<V: ZeroValue> ColumnUpdate<V> {
383 pub fn to_zero_value(&self) -> Option<Value> {
386 match self {
387 ColumnUpdate::Unchanged => None,
388 ColumnUpdate::Null => Some(Value::Null),
389 ColumnUpdate::Set(v) => Some(v.to_zero_value()),
390 }
391 }
392}
393
394pub trait QueryValue: Sized {
397 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError>;
399}
400
401impl<E: QueryElement> QueryValue for Vec<E> {
402 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
403 view.entries().into_iter().map(E::from_entry).collect()
404 }
405}
406
407pub trait OptionalQueryElement: Sized {
412 fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError>;
415}
416
417impl<T: OptionalQueryElement> QueryValue for Option<T> {
418 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
419 T::optional_from_view(view)
420 }
421}
422
423impl QueryValue for i64 {
425 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
426 i64::from_zero_value(aggregate_value(view)?)
427 }
428}
429
430fn aggregate_value(view: &ViewValue) -> Result<&Value, ZeroValueError> {
431 match view {
432 ViewValue::Value(v) => Ok(v),
433 _ => Err(ZeroValueError(
434 "expected the value of an aggregate, got rows".into(),
435 )),
436 }
437}
438
439pub fn optional_row<R: QueryElement>(view: &ViewValue) -> Result<Option<R>, ZeroValueError> {
441 view.entries().first().map(|e| R::from_entry(e)).transpose()
442}
443
444pub fn optional_value<V: ZeroValue>(view: &ViewValue) -> Result<Option<V>, ZeroValueError> {
446 let value = aggregate_value(view)?;
447 if value.is_null() {
448 Ok(None)
449 } else {
450 V::from_zero_value(value).map(Some)
451 }
452}
453
454macro_rules! optional_values {
455 ($($t:ty),*) => {$(
456 impl OptionalQueryElement for $t {
457 fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError> {
458 optional_value(view)
459 }
460 }
461 )*};
462}
463optional_values!(f64, i64, String, bool, Value);
464
465pub struct Column<R, V> {
468 name: &'static str,
469 types: PhantomData<fn() -> (R, V)>,
470}
471
472impl<R, V> Clone for Column<R, V> {
473 fn clone(&self) -> Self {
474 *self
475 }
476}
477impl<R, V> Copy for Column<R, V> {}
478
479impl<R, V> fmt::Debug for Column<R, V> {
480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481 f.debug_tuple("Column").field(&self.name).finish()
482 }
483}
484
485impl<R, V> Column<R, V> {
486 pub const fn new(name: &'static str) -> Self {
488 Column {
489 name,
490 types: PhantomData,
491 }
492 }
493
494 pub fn name(&self) -> &'static str {
496 self.name
497 }
498
499 fn compare(self, op: SimpleOperator, right: ValuePosition) -> Condition {
500 Condition::Simple {
501 op,
502 left: ValuePosition::Column(self.name.to_owned()),
503 right,
504 }
505 }
506
507 pub fn cmp_param(self, op: SimpleOperator, param: &StaticParameter) -> Condition {
510 self.compare(
511 op,
512 ValuePosition::Static {
513 anchor: param.anchor,
514 field: param.field.clone(),
515 },
516 )
517 }
518}
519
520impl<R, V: ZeroValue> Column<R, V> {
521 pub fn cmp(self, op: SimpleOperator, value: V) -> Condition {
523 self.compare(op, ValuePosition::Literal(value.to_zero_value()))
524 }
525
526 pub fn eq(self, value: V) -> Condition {
529 let value = value.to_zero_value();
530 let op = if value.is_null() {
531 SimpleOperator::Is
532 } else {
533 SimpleOperator::Eq
534 };
535 self.compare(op, ValuePosition::Literal(value))
536 }
537
538 pub fn ne(self, value: V) -> Condition {
540 let value = value.to_zero_value();
541 let op = if value.is_null() {
542 SimpleOperator::IsNot
543 } else {
544 SimpleOperator::Ne
545 };
546 self.compare(op, ValuePosition::Literal(value))
547 }
548
549 pub fn lt(self, value: V) -> Condition {
551 self.cmp(SimpleOperator::Lt, value)
552 }
553 pub fn le(self, value: V) -> Condition {
555 self.cmp(SimpleOperator::Le, value)
556 }
557 pub fn gt(self, value: V) -> Condition {
559 self.cmp(SimpleOperator::Gt, value)
560 }
561 pub fn ge(self, value: V) -> Condition {
563 self.cmp(SimpleOperator::Ge, value)
564 }
565 pub fn is(self, value: V) -> Condition {
567 self.cmp(SimpleOperator::Is, value)
568 }
569 pub fn is_not(self, value: V) -> Condition {
571 self.cmp(SimpleOperator::IsNot, value)
572 }
573
574 pub fn is_in(self, values: Vec<V>) -> Condition {
576 self.compare(SimpleOperator::In, ValuePosition::Literal(array(values)))
577 }
578
579 pub fn not_in(self, values: Vec<V>) -> Condition {
581 self.compare(SimpleOperator::NotIn, ValuePosition::Literal(array(values)))
582 }
583}
584
585fn array<V: ZeroValue>(values: Vec<V>) -> Value {
586 Value::Array(values.iter().map(V::to_zero_value).collect())
587}
588
589macro_rules! like {
590 ($t:ty) => {
591 impl<R> Column<R, $t> {
592 pub fn like(self, pattern: &str) -> Condition {
595 self.pattern(SimpleOperator::Like, pattern)
596 }
597 pub fn not_like(self, pattern: &str) -> Condition {
599 self.pattern(SimpleOperator::NotLike, pattern)
600 }
601 pub fn ilike(self, pattern: &str) -> Condition {
603 self.pattern(SimpleOperator::Ilike, pattern)
604 }
605 pub fn not_ilike(self, pattern: &str) -> Condition {
608 self.pattern(SimpleOperator::NotIlike, pattern)
609 }
610 fn pattern(self, op: SimpleOperator, pattern: &str) -> Condition {
611 self.compare(
612 op,
613 ValuePosition::Literal(Value::String(pattern.to_owned())),
614 )
615 }
616 }
617 };
618}
619like!(String);
620like!(Option<String>);
621
622pub struct ColumnRef<R> {
625 name: &'static str,
626 row: PhantomData<fn() -> R>,
627}
628
629impl<R> Clone for ColumnRef<R> {
630 fn clone(&self) -> Self {
631 *self
632 }
633}
634impl<R> Copy for ColumnRef<R> {}
635
636impl<R> fmt::Debug for ColumnRef<R> {
637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638 f.debug_tuple("ColumnRef").field(&self.name).finish()
639 }
640}
641
642impl<R> ColumnRef<R> {
643 pub fn name(&self) -> &'static str {
645 self.name
646 }
647}
648
649impl<R, V> From<Column<R, V>> for ColumnRef<R> {
650 fn from(c: Column<R, V>) -> Self {
651 ColumnRef {
652 name: c.name,
653 row: PhantomData,
654 }
655 }
656}
657
658pub struct Relationship<R, D> {
661 name: &'static str,
662 types: PhantomData<fn() -> (R, D)>,
663}
664
665impl<R, D> Clone for Relationship<R, D> {
666 fn clone(&self) -> Self {
667 *self
668 }
669}
670impl<R, D> Copy for Relationship<R, D> {}
671
672impl<R, D> fmt::Debug for Relationship<R, D> {
673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674 f.debug_tuple("Relationship").field(&self.name).finish()
675 }
676}
677
678impl<R, D> Relationship<R, D> {
679 pub const fn new(name: &'static str) -> Self {
681 Relationship {
682 name,
683 types: PhantomData,
684 }
685 }
686
687 pub fn name(&self) -> &'static str {
689 self.name
690 }
691}
692
693pub struct RelationshipAggregates<R> {
698 pub values: Vec<(String, Value)>,
700 row: PhantomData<fn() -> R>,
701}
702
703impl<R> Clone for RelationshipAggregates<R> {
704 fn clone(&self) -> Self {
705 RelationshipAggregates {
706 values: self.values.clone(),
707 row: PhantomData,
708 }
709 }
710}
711
712impl<R> fmt::Debug for RelationshipAggregates<R> {
713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
714 f.debug_map()
715 .entries(self.values.iter().map(|(k, v)| (k, v)))
716 .finish()
717 }
718}
719
720impl<R> PartialEq for RelationshipAggregates<R> {
721 fn eq(&self, other: &Self) -> bool {
722 self.values == other.values
723 }
724}
725
726impl<R> Default for RelationshipAggregates<R> {
727 fn default() -> Self {
728 RelationshipAggregates {
729 values: Vec::new(),
730 row: PhantomData,
731 }
732 }
733}
734
735impl<R> RelationshipAggregates<R> {
736 pub fn from_entry(entry: &ViewEntry) -> Self {
739 RelationshipAggregates {
740 values: entry
741 .relationships
742 .iter()
743 .filter_map(|(name, v)| match v {
744 ViewValue::Value(v) => Some((name.clone(), v.clone())),
745 _ => None,
746 })
747 .collect(),
748 row: PhantomData,
749 }
750 }
751
752 pub fn is_empty(&self) -> bool {
754 self.values.is_empty()
755 }
756
757 pub fn count<D>(&self, relationship: Relationship<R, D>) -> Option<i64> {
760 self.value(relationship)
761 }
762
763 pub fn sum<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
766 self.value(relationship)
767 }
768
769 pub fn avg<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
772 self.value(relationship)
773 }
774
775 pub fn value<V: ZeroValue, D>(&self, relationship: Relationship<R, D>) -> Option<V> {
779 let (_, v) = self.values.iter().find(|(k, _)| k == relationship.name)?;
780 if v.is_null() {
781 return None;
782 }
783 V::from_zero_value(v).ok()
784 }
785}
786
787pub struct Query<R, T = Vec<R>> {
790 any: AnyQuery,
791 types: PhantomData<fn() -> (R, T)>,
792}
793
794impl<R, T> Clone for Query<R, T> {
795 fn clone(&self) -> Self {
796 Query::from_any(self.any.clone())
797 }
798}
799
800impl<R, T> fmt::Debug for Query<R, T> {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 f.debug_tuple("Query").field(&self.any).finish()
803 }
804}
805
806impl<R, T> Query<R, T> {
807 pub fn from_any(any: AnyQuery) -> Self {
809 Query {
810 any,
811 types: PhantomData,
812 }
813 }
814
815 pub fn any(&self) -> &AnyQuery {
817 &self.any
818 }
819
820 pub fn into_any(self) -> AnyQuery {
822 self.any
823 }
824
825 fn map(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Self {
826 Query::from_any(f(self.any))
827 }
828
829 fn to<U>(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Query<R, U> {
830 Query::from_any(f(self.any))
831 }
832}
833
834impl<R: ZeroRow> Query<R> {
835 pub fn table(schema: Arc<Schema>) -> Self {
837 Query::from_any(AnyQuery::new(schema, R::TABLE, System::Client))
838 }
839}
840
841impl<R: ZeroRow, T> Query<R, T> {
842 pub fn where_eq<V: ZeroValue>(self, column: Column<R, V>, value: V) -> Self {
844 self.where_condition(column.eq(value))
845 }
846
847 pub fn where_<V: ZeroValue>(self, column: Column<R, V>, op: SimpleOperator, value: V) -> Self {
849 self.map(|q| q.where_(column.name, op, value.to_zero_value()))
850 }
851
852 pub fn where_in<V: ZeroValue>(
854 self,
855 column: Column<R, V>,
856 op: SimpleOperator,
857 values: Vec<V>,
858 ) -> Self {
859 self.map(|q| q.where_(column.name, op, array(values)))
860 }
861
862 pub fn where_param<V>(
864 self,
865 column: Column<R, V>,
866 op: SimpleOperator,
867 param: &StaticParameter,
868 ) -> Self {
869 self.map(|q| q.where_param(column.name, op, param))
870 }
871
872 pub fn where_condition(self, condition: Condition) -> Self {
874 self.map(|q| q.where_condition(condition))
875 }
876
877 pub fn where_expr(self, factory: impl FnOnce(&RowExpression<'_, '_, R>) -> Condition) -> Self {
880 self.map(|q| {
881 q.where_expr(|eb| {
882 factory(&RowExpression {
883 builder: eb,
884 row: PhantomData,
885 })
886 })
887 })
888 }
889
890 pub fn where_exists<D: ZeroRow>(
892 self,
893 relationship: Relationship<R, D>,
894 options: ExistsOptions,
895 sub: impl FnOnce(Query<D>) -> Query<D>,
896 ) -> Self {
897 self.map(|q| q.where_exists(relationship.name, options, untyped(sub)))
898 }
899
900 pub fn related<D: ZeroRow, S>(
904 self,
905 relationship: Relationship<R, D>,
906 sub: impl FnOnce(Query<D>) -> Query<D, S>,
907 ) -> Self {
908 self.map(|q| q.related(relationship.name, |a| sub(Query::from_any(a)).any))
909 }
910
911 pub fn order_by<V>(self, column: Column<R, V>, direction: Direction) -> Self {
914 self.map(|q| q.order_by(column.name, direction))
915 }
916
917 pub fn limit(self, limit: i64) -> Self {
919 self.map(|q| q.limit(limit))
920 }
921
922 pub fn start(self, row: &R, inclusive: bool) -> Self {
924 self.map(|q| q.start(row.column_values(), inclusive))
925 }
926
927 pub fn start_values(self, values: Vec<(ColumnRef<R>, Value)>, inclusive: bool) -> Self {
931 let row = values.into_iter().map(|(c, v)| (c.name, v)).collect();
932 self.map(|q| q.start(row, inclusive))
933 }
934
935 pub fn one(self) -> Query<R, Option<R>> {
937 self.to(AnyQuery::one)
938 }
939
940 pub fn count(self) -> Query<R, i64> {
943 self.to(AnyQuery::count)
944 }
945
946 pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
948 self.to(|q| q.sum(column.name))
949 }
950
951 pub fn sum_json<V>(
954 self,
955 column: Column<R, V>,
956 path: Vec<JsonPathSegment>,
957 ) -> Query<R, Option<f64>> {
958 self.to(|q| q.sum_json(column.name, path))
959 }
960
961 pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
963 self.to(|q| q.avg(column.name))
964 }
965
966 pub fn avg_json<V>(
969 self,
970 column: Column<R, V>,
971 path: Vec<JsonPathSegment>,
972 ) -> Query<R, Option<f64>> {
973 self.to(|q| q.avg_json(column.name, path))
974 }
975
976 pub fn min<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
978 self.to(|q| q.min(column.name))
979 }
980
981 pub fn min_json<V>(
983 self,
984 column: Column<R, V>,
985 path: Vec<JsonPathSegment>,
986 ) -> Query<R, Option<Value>> {
987 self.to(|q| q.min_json(column.name, path))
988 }
989
990 pub fn max<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
993 self.to(|q| q.max(column.name))
994 }
995
996 pub fn max_json<V>(
998 self,
999 column: Column<R, V>,
1000 path: Vec<JsonPathSegment>,
1001 ) -> Query<R, Option<Value>> {
1002 self.to(|q| q.max_json(column.name, path))
1003 }
1004
1005 pub fn distinct(self, columns: Vec<ColumnRef<R>>) -> Query<R, Vec<DistinctRow<R>>> {
1008 self.to(|q| q.distinct(names(columns)))
1009 }
1010
1011 pub fn group_by(self, columns: Vec<ColumnRef<R>>) -> GroupedQuery<R> {
1014 GroupedQuery {
1015 any: self.any.group_by(names(columns)),
1016 row: PhantomData,
1017 }
1018 }
1019}
1020
1021impl<C, R, T> crate::query::ZeroQuery<C> for Query<R, T> {
1022 fn any_query(&self, _: &C) -> std::borrow::Cow<'_, AnyQuery> {
1023 std::borrow::Cow::Borrowed(&self.any)
1024 }
1025}
1026
1027impl<R, T: QueryValue> Query<R, T> {
1028 pub fn read(&self, view: &ViewValue) -> Result<T, ZeroValueError> {
1030 T::from_view(view)
1031 }
1032}
1033
1034fn names<R>(columns: Vec<ColumnRef<R>>) -> Vec<String> {
1035 columns.into_iter().map(|c| c.name.to_owned()).collect()
1036}
1037
1038fn untyped<D>(sub: impl FnOnce(Query<D>) -> Query<D>) -> impl FnOnce(AnyQuery) -> AnyQuery {
1039 |a| sub(Query::from_any(a)).any
1040}
1041
1042pub struct RowExpression<'a, 'q, R> {
1046 builder: &'a ExpressionBuilder<'q>,
1047 row: PhantomData<fn() -> R>,
1048}
1049
1050impl<R> RowExpression<'_, '_, R> {
1051 pub fn json<V>(&self, column: Column<R, V>, path: Vec<JsonPathSegment>) -> JsonPath<'_, '_> {
1054 JsonPath {
1055 builder: self.builder,
1056 reference: self.builder.json(column.name, path),
1057 }
1058 }
1059
1060 pub fn exists<D: ZeroRow>(
1062 &self,
1063 relationship: Relationship<R, D>,
1064 options: ExistsOptions,
1065 sub: impl FnOnce(Query<D>) -> Query<D>,
1066 ) -> Condition {
1067 self.builder
1068 .exists(relationship.name, options, untyped(sub))
1069 }
1070
1071 pub fn and(&self, conditions: Vec<Condition>) -> Condition {
1073 self.builder.and(conditions)
1074 }
1075
1076 pub fn or(&self, conditions: Vec<Condition>) -> Condition {
1078 self.builder.or(conditions)
1079 }
1080
1081 pub fn not(&self, condition: Condition) -> Condition {
1083 self.builder.not(condition)
1084 }
1085}
1086
1087pub struct JsonPath<'a, 'q> {
1091 builder: &'a ExpressionBuilder<'q>,
1092 reference: JsonPathReference,
1093}
1094
1095impl JsonPath<'_, '_> {
1096 pub fn cmp(&self, op: SimpleOperator, value: Value) -> Condition {
1098 self.builder.cmp_json(&self.reference, op, value)
1099 }
1100
1101 pub fn cmp_param(&self, op: SimpleOperator, param: &StaticParameter) -> Condition {
1103 self.builder.cmp_json_param(&self.reference, op, param)
1104 }
1105
1106 pub fn eq(&self, value: Value) -> Condition {
1108 let op = if value.is_null() {
1109 SimpleOperator::Is
1110 } else {
1111 SimpleOperator::Eq
1112 };
1113 self.cmp(op, value)
1114 }
1115
1116 pub fn ne(&self, value: Value) -> Condition {
1118 let op = if value.is_null() {
1119 SimpleOperator::IsNot
1120 } else {
1121 SimpleOperator::Ne
1122 };
1123 self.cmp(op, value)
1124 }
1125
1126 pub fn lt(&self, value: Value) -> Condition {
1128 self.cmp(SimpleOperator::Lt, value)
1129 }
1130 pub fn le(&self, value: Value) -> Condition {
1132 self.cmp(SimpleOperator::Le, value)
1133 }
1134 pub fn gt(&self, value: Value) -> Condition {
1136 self.cmp(SimpleOperator::Gt, value)
1137 }
1138 pub fn ge(&self, value: Value) -> Condition {
1140 self.cmp(SimpleOperator::Ge, value)
1141 }
1142 pub fn is(&self, value: Value) -> Condition {
1144 self.cmp(SimpleOperator::Is, value)
1145 }
1146 pub fn is_not(&self, value: Value) -> Condition {
1148 self.cmp(SimpleOperator::IsNot, value)
1149 }
1150 pub fn is_in(&self, values: Vec<Value>) -> Condition {
1152 self.cmp(SimpleOperator::In, Value::Array(values))
1153 }
1154 pub fn not_in(&self, values: Vec<Value>) -> Condition {
1156 self.cmp(SimpleOperator::NotIn, Value::Array(values))
1157 }
1158 pub fn like(&self, pattern: &str) -> Condition {
1160 self.cmp(SimpleOperator::Like, Value::String(pattern.to_owned()))
1161 }
1162 pub fn not_like(&self, pattern: &str) -> Condition {
1164 self.cmp(SimpleOperator::NotLike, Value::String(pattern.to_owned()))
1165 }
1166 pub fn ilike(&self, pattern: &str) -> Condition {
1168 self.cmp(SimpleOperator::Ilike, Value::String(pattern.to_owned()))
1169 }
1170 pub fn not_ilike(&self, pattern: &str) -> Condition {
1172 self.cmp(SimpleOperator::NotIlike, Value::String(pattern.to_owned()))
1173 }
1174}
1175
1176pub type Grouped<R, V> = Query<R, Vec<GroupRow<R, V>>>;
1178
1179pub struct GroupedQuery<R> {
1183 any: AnyGroupedQuery,
1184 row: PhantomData<fn() -> R>,
1185}
1186
1187impl<R> GroupedQuery<R> {
1188 pub fn any(&self) -> &AnyGroupedQuery {
1190 &self.any
1191 }
1192
1193 pub fn count(self) -> Grouped<R, i64> {
1195 Query::from_any(self.any.count())
1196 }
1197
1198 pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
1200 Query::from_any(self.any.sum(column.name))
1201 }
1202
1203 pub fn sum_json<V>(
1205 self,
1206 column: Column<R, V>,
1207 path: Vec<JsonPathSegment>,
1208 ) -> Grouped<R, Option<f64>> {
1209 Query::from_any(self.any.sum_json(column.name, path))
1210 }
1211
1212 pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
1214 Query::from_any(self.any.avg(column.name))
1215 }
1216
1217 pub fn avg_json<V>(
1219 self,
1220 column: Column<R, V>,
1221 path: Vec<JsonPathSegment>,
1222 ) -> Grouped<R, Option<f64>> {
1223 Query::from_any(self.any.avg_json(column.name, path))
1224 }
1225
1226 pub fn min<V: OrderedZeroValue>(
1228 self,
1229 column: Column<R, V>,
1230 ) -> Grouped<R, Option<V::Unwrapped>> {
1231 Query::from_any(self.any.min(column.name))
1232 }
1233
1234 pub fn min_json<V>(
1236 self,
1237 column: Column<R, V>,
1238 path: Vec<JsonPathSegment>,
1239 ) -> Grouped<R, Option<Value>> {
1240 Query::from_any(self.any.min_json(column.name, path))
1241 }
1242
1243 pub fn max<V: OrderedZeroValue>(
1245 self,
1246 column: Column<R, V>,
1247 ) -> Grouped<R, Option<V::Unwrapped>> {
1248 Query::from_any(self.any.max(column.name))
1249 }
1250
1251 pub fn max_json<V>(
1253 self,
1254 column: Column<R, V>,
1255 path: Vec<JsonPathSegment>,
1256 ) -> Grouped<R, Option<Value>> {
1257 Query::from_any(self.any.max_json(column.name, path))
1258 }
1259}
1260
1261pub struct GroupRow<R, V> {
1264 pub value: V,
1266 pub columns: Object,
1268 row: PhantomData<fn() -> R>,
1269}
1270
1271impl<R, V: Clone> Clone for GroupRow<R, V> {
1272 fn clone(&self) -> Self {
1273 GroupRow {
1274 value: self.value.clone(),
1275 columns: self.columns.clone(),
1276 row: PhantomData,
1277 }
1278 }
1279}
1280
1281impl<R, V: fmt::Debug> fmt::Debug for GroupRow<R, V> {
1282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1283 f.debug_struct("GroupRow")
1284 .field("value", &self.value)
1285 .field("columns", &self.columns)
1286 .finish()
1287 }
1288}
1289
1290impl<R, V: PartialEq> PartialEq for GroupRow<R, V> {
1291 fn eq(&self, other: &Self) -> bool {
1292 self.value == other.value && self.columns == other.columns
1293 }
1294}
1295
1296impl<R, V: ZeroValue> QueryElement for GroupRow<R, V> {
1297 fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
1298 let mut columns: Object = (*entry.row).clone();
1301 let last = columns
1302 .get_index(columns.len().wrapping_sub(1))
1303 .map(|(k, v)| (k.clone(), v.clone()))
1304 .ok_or_else(|| ZeroValueError("a group row has no value".into()))?;
1305 columns.remove(&last.0);
1306 Ok(GroupRow {
1307 value: decode(&last.0, Some(&last.1))?,
1308 columns,
1309 row: PhantomData,
1310 })
1311 }
1312}
1313
1314impl<R, V> GroupRow<R, V> {
1315 pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
1317 group_column(&self.columns, column)
1318 }
1319}
1320
1321pub struct DistinctRow<R> {
1324 pub columns: Object,
1326 row: PhantomData<fn() -> R>,
1327}
1328
1329impl<R> Clone for DistinctRow<R> {
1330 fn clone(&self) -> Self {
1331 DistinctRow {
1332 columns: self.columns.clone(),
1333 row: PhantomData,
1334 }
1335 }
1336}
1337
1338impl<R> fmt::Debug for DistinctRow<R> {
1339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1340 f.debug_tuple("DistinctRow").field(&self.columns).finish()
1341 }
1342}
1343
1344impl<R> PartialEq for DistinctRow<R> {
1345 fn eq(&self, other: &Self) -> bool {
1346 self.columns == other.columns
1347 }
1348}
1349
1350impl<R> QueryElement for DistinctRow<R> {
1351 fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
1352 Ok(DistinctRow {
1353 columns: (*entry.row).clone(),
1354 row: PhantomData,
1355 })
1356 }
1357}
1358
1359impl<R> DistinctRow<R> {
1360 pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
1362 group_column(&self.columns, column)
1363 }
1364}
1365
1366fn group_column<R, C: ZeroValue>(
1367 columns: &Object,
1368 column: Column<R, C>,
1369) -> Result<C, ZeroValueError> {
1370 match columns.get(column.name) {
1371 Some(v) => decode(column.name, Some(v)),
1372 None => Err(ZeroValueError(format!(
1373 "{} is not a column of the group",
1374 column.name
1375 ))),
1376 }
1377}