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::rc::Rc;
40use std::sync::Arc;
41
42#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct ZeroValueError(pub String);
45
46impl ZeroValueError {
47 pub fn mismatch(expected: &str, value: &Value) -> Self {
49 ZeroValueError(format!(
50 "expected {expected}, got {} {}",
51 value.type_name(),
52 crate::json::stringify(value)
53 ))
54 }
55}
56
57impl fmt::Display for ZeroValueError {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str(&self.0)
60 }
61}
62
63impl std::error::Error for ZeroValueError {}
64
65pub trait ZeroValue: Sized {
68 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError>;
70 fn to_zero_value(&self) -> Value;
72 fn value_for_null() -> Option<Self> {
78 None
79 }
80}
81
82impl ZeroValue for String {
83 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
84 value
85 .as_str()
86 .map(str::to_owned)
87 .ok_or_else(|| ZeroValueError::mismatch("a string", value))
88 }
89 fn to_zero_value(&self) -> Value {
90 Value::String(self.clone())
91 }
92 fn value_for_null() -> Option<Self> {
93 Some(String::new())
94 }
95}
96
97impl ZeroValue for f64 {
98 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
99 value
100 .as_f64()
101 .ok_or_else(|| ZeroValueError::mismatch("a number", value))
102 }
103 fn to_zero_value(&self) -> Value {
104 Value::Number(*self)
105 }
106 fn value_for_null() -> Option<Self> {
107 Some(0.0)
108 }
109}
110
111impl ZeroValue for i64 {
114 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
115 const MAX_SAFE: f64 = 9_007_199_254_740_992.0;
116 match value.as_f64() {
117 Some(n) if n.fract() == 0.0 && n.abs() <= MAX_SAFE => Ok(n as i64),
118 _ => Err(ZeroValueError::mismatch("an integer", value)),
119 }
120 }
121 fn to_zero_value(&self) -> Value {
122 Value::Number(*self as f64)
123 }
124 fn value_for_null() -> Option<Self> {
125 Some(0)
126 }
127}
128
129impl ZeroValue for bool {
130 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
131 value
132 .as_bool()
133 .ok_or_else(|| ZeroValueError::mismatch("a boolean", value))
134 }
135 fn to_zero_value(&self) -> Value {
136 Value::Bool(*self)
137 }
138 fn value_for_null() -> Option<Self> {
139 Some(false)
140 }
141}
142
143impl ZeroValue for Value {
144 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
145 Ok(value.clone())
146 }
147 fn to_zero_value(&self) -> Value {
148 self.clone()
149 }
150}
151
152impl<T: ZeroValue> ZeroValue for Option<T> {
154 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
155 if value.is_null() {
156 Ok(None)
157 } else {
158 T::from_zero_value(value).map(Some)
159 }
160 }
161 fn to_zero_value(&self) -> Value {
162 self.as_ref().map_or(Value::Null, T::to_zero_value)
163 }
164}
165
166impl<T: ZeroValue> ZeroValue for Vec<T> {
168 fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
169 value
170 .as_array()
171 .ok_or_else(|| ZeroValueError::mismatch("an array", value))?
172 .iter()
173 .map(T::from_zero_value)
174 .collect()
175 }
176 fn to_zero_value(&self) -> Value {
177 Value::Array(self.iter().map(T::to_zero_value).collect())
178 }
179}
180
181pub trait NumericZeroValue: ZeroValue {}
183impl NumericZeroValue for f64 {}
184impl NumericZeroValue for i64 {}
185impl<T: NumericZeroValue> NumericZeroValue for Option<T> {}
186
187pub trait OrderedZeroValue: ZeroValue {
191 type Unwrapped: ZeroValue + OptionalQueryElement;
193}
194impl OrderedZeroValue for f64 {
195 type Unwrapped = f64;
196}
197impl OrderedZeroValue for i64 {
198 type Unwrapped = i64;
199}
200impl OrderedZeroValue for String {
201 type Unwrapped = String;
202}
203impl<T: OrderedZeroValue> OrderedZeroValue for Option<T> {
204 type Unwrapped = T::Unwrapped;
205}
206
207pub fn decode<V: ZeroValue>(name: &str, value: Option<&Value>) -> Result<V, ZeroValueError> {
210 let value = value.unwrap_or(&Value::Null);
211 if value.is_null()
212 && let Some(fallback) = V::value_for_null()
213 {
214 return Ok(fallback);
215 }
216 V::from_zero_value(value).map_err(|e| ZeroValueError(format!("{name}: {e}")))
217}
218
219pub fn column<V: ZeroValue>(
223 entry: &ViewEntry,
224 name: &str,
225 index: usize,
226) -> Result<V, ZeroValueError> {
227 match entry.row.get_index(index) {
228 Some((k, v)) if k == name => decode(name, Some(v)),
229 _ => decode(name, entry.row.get(name)),
230 }
231}
232
233pub fn many<R: QueryElement>(
237 entry: &ViewEntry,
238 name: &str,
239) -> Result<Option<Vec<R>>, ZeroValueError> {
240 match entry.relationship(name) {
241 None | Some(ViewValue::Value(_)) => Ok(None),
242 Some(v) => v
243 .entries()
244 .into_iter()
245 .map(R::from_entry)
246 .collect::<Result<_, _>>()
247 .map(Some),
248 }
249}
250
251pub fn one<R: QueryElement>(
254 entry: &ViewEntry,
255 name: &str,
256) -> Result<Option<Box<R>>, ZeroValueError> {
257 match entry
258 .relationship(name)
259 .and_then(|v| v.entries().first().copied())
260 {
261 Some(e) => R::from_entry(e).map(|r| Some(Box::new(r))),
262 None => Ok(None),
263 }
264}
265
266pub fn object<'a>(value: &'a Value, type_name: &str) -> Result<&'a Object, ZeroValueError> {
268 value
269 .as_object()
270 .ok_or_else(|| ZeroValueError::mismatch(&format!("a {type_name} object"), value))
271}
272
273pub fn field<V: ZeroValue>(object: &Object, name: &str) -> Result<V, ZeroValueError> {
276 V::from_zero_value(object.get(name).unwrap_or(&Value::Null))
277 .map_err(|e| ZeroValueError(format!("{name}: {e}")))
278}
279
280pub fn schema_from_json(json: &str) -> Arc<Schema> {
283 let value = crate::json::parse(json).expect("the generated schema is JSON");
284 Arc::new(Schema::from_json(&value).expect("the generated schema is a schema"))
285}
286
287pub trait QueryElement: Sized {
290 fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError>;
292}
293
294pub trait ZeroRow: QueryElement {
298 const TABLE: &'static str;
300 type Update: ColumnValues;
303 type Key: ColumnValues;
305 fn column_values(&self) -> Object;
307}
308
309pub trait ColumnValues {
312 fn column_values(&self) -> Object;
314}
315
316pub struct TypedTableMutator<'tx, R> {
324 tx: &'tx Transaction,
325 row: PhantomData<fn() -> R>,
326}
327
328impl<'tx, R: ZeroRow> TypedTableMutator<'tx, R> {
329 pub fn new(tx: &'tx Transaction) -> Self {
331 TypedTableMutator {
332 tx,
333 row: PhantomData,
334 }
335 }
336
337 pub fn insert(&self, row: &R) -> Result<(), Error> {
339 self.tx.table(R::TABLE).insert(&row.column_values())
340 }
341
342 pub fn upsert(&self, row: &R) -> Result<(), Error> {
347 self.tx.table(R::TABLE).upsert(&row.column_values())
348 }
349
350 pub fn update(&self, value: &R::Update) -> Result<(), Error> {
353 self.tx.table(R::TABLE).update(&value.column_values())
354 }
355
356 pub fn delete(&self, key: &R::Key) -> Result<(), Error> {
358 self.tx.table(R::TABLE).delete(&key.column_values())
359 }
360}
361
362#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
366pub enum ColumnUpdate<V> {
367 #[default]
368 Unchanged,
370 Null,
372 Set(V),
374}
375
376impl<V> From<Option<V>> for ColumnUpdate<V> {
377 fn from(value: Option<V>) -> Self {
379 value.map_or(ColumnUpdate::Null, ColumnUpdate::Set)
380 }
381}
382
383impl<V: ZeroValue> ColumnUpdate<V> {
384 pub fn to_zero_value(&self) -> Option<Value> {
387 match self {
388 ColumnUpdate::Unchanged => None,
389 ColumnUpdate::Null => Some(Value::Null),
390 ColumnUpdate::Set(v) => Some(v.to_zero_value()),
391 }
392 }
393}
394
395pub trait QueryValue: Sized {
398 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError>;
400
401 fn update_from_view(
408 &mut self,
409 previous: &mut ViewValue,
410 view: &ViewValue,
411 ) -> Result<(), ZeroValueError> {
412 *self = Self::from_view(view)?;
413 *previous = view.clone();
414 Ok(())
415 }
416}
417
418impl<E: QueryElement> QueryValue for Vec<E> {
419 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
420 view.entries().into_iter().map(E::from_entry).collect()
421 }
422
423 fn update_from_view(
430 &mut self,
431 previous: &mut ViewValue,
432 view: &ViewValue,
433 ) -> Result<(), ZeroValueError> {
434 let (ViewValue::Many(old), ViewValue::Many(new)) = (&mut *previous, view) else {
435 *self = Self::from_view(view)?;
436 *previous = view.clone();
437 return Ok(());
438 };
439 if old.len() != self.len() {
440 *self = Self::from_view(view)?;
441 *previous = view.clone();
442 return Ok(());
443 }
444 let mut runs: Vec<Run> = Vec::new();
448 let mut fresh = Vec::new();
449 let mut in_place = old.len() == new.len();
452 let mut j = 0;
453 for (i, entry) in new.iter().enumerate() {
454 let kept = if old.get(j).is_some_and(|o| same_entry(o, entry)) {
455 Some(j)
456 } else if old.get(j + 1).is_some_and(|o| same_entry(o, entry)) {
457 Some(j + 1)
458 } else {
459 None
460 };
461 match (kept, runs.last_mut()) {
462 (Some(k), Some(Run::Keep { from, len })) if *from + *len == k => *len += 1,
463 (Some(k), _) => runs.push(Run::Keep { from: k, len: 1 }),
464 (None, Some(Run::Fresh(len))) => *len += 1,
465 (None, _) => runs.push(Run::Fresh(1)),
466 }
467 match kept {
468 Some(k) => {
469 in_place &= k == i;
470 j = k + 1;
471 }
472 None => fresh.push(E::from_entry(entry)?),
473 }
474 }
475 if in_place && fresh.is_empty() {
476 return Ok(());
477 }
478 let mut fresh = fresh.into_iter();
479 apply_runs(self, &runs, in_place, new.len(), |_| {
480 fresh.next().expect("a row read for each new entry")
481 });
482 apply_runs(Rc::make_mut(old), &runs, in_place, new.len(), |i| {
483 new[i].clone()
484 });
485 Ok(())
486 }
487}
488
489fn same_entry(a: &ViewEntry, b: &ViewEntry) -> bool {
493 (Rc::ptr_eq(&a.row, &b.row) || a.row == b.row)
494 && a.relationships.len() == b.relationships.len()
495 && a.relationships
496 .iter()
497 .zip(&b.relationships)
498 .all(|((m, a), (n, b))| m == n && same_value(a, b))
499}
500
501fn same_value(a: &ViewValue, b: &ViewValue) -> bool {
502 match (a, b) {
503 (ViewValue::Many(a), ViewValue::Many(b)) => {
504 Rc::ptr_eq(a, b)
505 || (a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| same_entry(a, b)))
506 }
507 (ViewValue::One(Some(a)), ViewValue::One(Some(b))) => same_entry(a, b),
508 (a, b) => a == b,
509 }
510}
511
512enum Run {
514 Keep { from: usize, len: usize },
516 Fresh(usize),
518}
519
520fn apply_runs<X>(
524 items: &mut Vec<X>,
525 runs: &[Run],
526 in_place: bool,
527 len: usize,
528 mut fresh: impl FnMut(usize) -> X,
529) {
530 if in_place {
531 let mut at = 0;
532 for run in runs {
533 match *run {
534 Run::Keep { len, .. } => at += len,
535 Run::Fresh(n) => {
536 for (i, item) in items[at..at + n].iter_mut().enumerate() {
537 *item = fresh(at + i);
538 }
539 at += n;
540 }
541 }
542 }
543 return;
544 }
545 let mut out = Vec::with_capacity(len);
546 let mut old = std::mem::take(items).into_iter();
547 let mut next = 0;
548 for run in runs {
549 match *run {
550 Run::Keep { from, len } => {
551 if from > next {
552 old.nth(from - next - 1);
553 }
554 out.extend(old.by_ref().take(len));
555 next = from + len;
556 }
557 Run::Fresh(n) => {
558 let at = out.len();
559 out.extend((at..at + n).map(&mut fresh));
560 }
561 }
562 }
563 *items = out;
564}
565
566pub trait OptionalQueryElement: Sized {
571 fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError>;
574}
575
576impl<T: OptionalQueryElement> QueryValue for Option<T> {
577 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
578 T::optional_from_view(view)
579 }
580}
581
582impl QueryValue for i64 {
584 fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
585 i64::from_zero_value(aggregate_value(view)?)
586 }
587}
588
589fn aggregate_value(view: &ViewValue) -> Result<&Value, ZeroValueError> {
590 match view {
591 ViewValue::Value(v) => Ok(v),
592 _ => Err(ZeroValueError(
593 "expected the value of an aggregate, got rows".into(),
594 )),
595 }
596}
597
598pub fn optional_row<R: QueryElement>(view: &ViewValue) -> Result<Option<R>, ZeroValueError> {
600 view.entries().first().map(|e| R::from_entry(e)).transpose()
601}
602
603pub fn optional_value<V: ZeroValue>(view: &ViewValue) -> Result<Option<V>, ZeroValueError> {
605 let value = aggregate_value(view)?;
606 if value.is_null() {
607 Ok(None)
608 } else {
609 V::from_zero_value(value).map(Some)
610 }
611}
612
613macro_rules! optional_values {
614 ($($t:ty),*) => {$(
615 impl OptionalQueryElement for $t {
616 fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError> {
617 optional_value(view)
618 }
619 }
620 )*};
621}
622optional_values!(f64, i64, String, bool, Value);
623
624pub struct Column<R, V> {
627 name: &'static str,
628 types: PhantomData<fn() -> (R, V)>,
629}
630
631impl<R, V> Clone for Column<R, V> {
632 fn clone(&self) -> Self {
633 *self
634 }
635}
636impl<R, V> Copy for Column<R, V> {}
637
638impl<R, V> fmt::Debug for Column<R, V> {
639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640 f.debug_tuple("Column").field(&self.name).finish()
641 }
642}
643
644impl<R, V> Column<R, V> {
645 pub const fn new(name: &'static str) -> Self {
647 Column {
648 name,
649 types: PhantomData,
650 }
651 }
652
653 pub fn name(&self) -> &'static str {
655 self.name
656 }
657
658 fn compare(self, op: SimpleOperator, right: ValuePosition) -> Condition {
659 Condition::Simple {
660 op,
661 left: ValuePosition::Column(self.name.to_owned()),
662 right,
663 }
664 }
665
666 pub fn cmp_param(self, op: SimpleOperator, param: &StaticParameter) -> Condition {
669 self.compare(
670 op,
671 ValuePosition::Static {
672 anchor: param.anchor,
673 field: param.field.clone(),
674 },
675 )
676 }
677}
678
679impl<R, V: ZeroValue> Column<R, V> {
680 pub fn cmp(self, op: SimpleOperator, value: V) -> Condition {
682 self.compare(op, ValuePosition::Literal(value.to_zero_value()))
683 }
684
685 pub fn eq(self, value: V) -> Condition {
688 let value = value.to_zero_value();
689 let op = if value.is_null() {
690 SimpleOperator::Is
691 } else {
692 SimpleOperator::Eq
693 };
694 self.compare(op, ValuePosition::Literal(value))
695 }
696
697 pub fn ne(self, value: V) -> Condition {
699 let value = value.to_zero_value();
700 let op = if value.is_null() {
701 SimpleOperator::IsNot
702 } else {
703 SimpleOperator::Ne
704 };
705 self.compare(op, ValuePosition::Literal(value))
706 }
707
708 pub fn lt(self, value: V) -> Condition {
710 self.cmp(SimpleOperator::Lt, value)
711 }
712 pub fn le(self, value: V) -> Condition {
714 self.cmp(SimpleOperator::Le, value)
715 }
716 pub fn gt(self, value: V) -> Condition {
718 self.cmp(SimpleOperator::Gt, value)
719 }
720 pub fn ge(self, value: V) -> Condition {
722 self.cmp(SimpleOperator::Ge, value)
723 }
724 pub fn is(self, value: V) -> Condition {
726 self.cmp(SimpleOperator::Is, value)
727 }
728 pub fn is_not(self, value: V) -> Condition {
730 self.cmp(SimpleOperator::IsNot, value)
731 }
732
733 pub fn is_in(self, values: Vec<V>) -> Condition {
735 self.compare(SimpleOperator::In, ValuePosition::Literal(array(values)))
736 }
737
738 pub fn not_in(self, values: Vec<V>) -> Condition {
740 self.compare(SimpleOperator::NotIn, ValuePosition::Literal(array(values)))
741 }
742}
743
744fn array<V: ZeroValue>(values: Vec<V>) -> Value {
745 Value::Array(values.iter().map(V::to_zero_value).collect())
746}
747
748macro_rules! like {
749 ($t:ty) => {
750 impl<R> Column<R, $t> {
751 pub fn like(self, pattern: &str) -> Condition {
754 self.pattern(SimpleOperator::Like, pattern)
755 }
756 pub fn not_like(self, pattern: &str) -> Condition {
758 self.pattern(SimpleOperator::NotLike, pattern)
759 }
760 pub fn ilike(self, pattern: &str) -> Condition {
762 self.pattern(SimpleOperator::Ilike, pattern)
763 }
764 pub fn not_ilike(self, pattern: &str) -> Condition {
767 self.pattern(SimpleOperator::NotIlike, pattern)
768 }
769 fn pattern(self, op: SimpleOperator, pattern: &str) -> Condition {
770 self.compare(
771 op,
772 ValuePosition::Literal(Value::String(pattern.to_owned())),
773 )
774 }
775 }
776 };
777}
778like!(String);
779like!(Option<String>);
780
781pub struct ColumnRef<R> {
784 name: &'static str,
785 row: PhantomData<fn() -> R>,
786}
787
788impl<R> Clone for ColumnRef<R> {
789 fn clone(&self) -> Self {
790 *self
791 }
792}
793impl<R> Copy for ColumnRef<R> {}
794
795impl<R> fmt::Debug for ColumnRef<R> {
796 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
797 f.debug_tuple("ColumnRef").field(&self.name).finish()
798 }
799}
800
801impl<R> ColumnRef<R> {
802 pub fn name(&self) -> &'static str {
804 self.name
805 }
806}
807
808impl<R, V> From<Column<R, V>> for ColumnRef<R> {
809 fn from(c: Column<R, V>) -> Self {
810 ColumnRef {
811 name: c.name,
812 row: PhantomData,
813 }
814 }
815}
816
817pub struct Relationship<R, D> {
820 name: &'static str,
821 types: PhantomData<fn() -> (R, D)>,
822}
823
824impl<R, D> Clone for Relationship<R, D> {
825 fn clone(&self) -> Self {
826 *self
827 }
828}
829impl<R, D> Copy for Relationship<R, D> {}
830
831impl<R, D> fmt::Debug for Relationship<R, D> {
832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
833 f.debug_tuple("Relationship").field(&self.name).finish()
834 }
835}
836
837impl<R, D> Relationship<R, D> {
838 pub const fn new(name: &'static str) -> Self {
840 Relationship {
841 name,
842 types: PhantomData,
843 }
844 }
845
846 pub fn name(&self) -> &'static str {
848 self.name
849 }
850}
851
852pub struct RelationshipAggregates<R> {
857 pub values: Vec<(String, Value)>,
859 row: PhantomData<fn() -> R>,
860}
861
862impl<R> Clone for RelationshipAggregates<R> {
863 fn clone(&self) -> Self {
864 RelationshipAggregates {
865 values: self.values.clone(),
866 row: PhantomData,
867 }
868 }
869}
870
871impl<R> fmt::Debug for RelationshipAggregates<R> {
872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873 f.debug_map()
874 .entries(self.values.iter().map(|(k, v)| (k, v)))
875 .finish()
876 }
877}
878
879impl<R> PartialEq for RelationshipAggregates<R> {
880 fn eq(&self, other: &Self) -> bool {
881 self.values == other.values
882 }
883}
884
885impl<R> Default for RelationshipAggregates<R> {
886 fn default() -> Self {
887 RelationshipAggregates {
888 values: Vec::new(),
889 row: PhantomData,
890 }
891 }
892}
893
894impl<R> RelationshipAggregates<R> {
895 pub fn from_entry(entry: &ViewEntry) -> Self {
898 RelationshipAggregates {
899 values: entry
900 .relationships
901 .iter()
902 .filter_map(|(name, v)| match v {
903 ViewValue::Value(v) => Some((name.clone(), v.clone())),
904 _ => None,
905 })
906 .collect(),
907 row: PhantomData,
908 }
909 }
910
911 pub fn is_empty(&self) -> bool {
913 self.values.is_empty()
914 }
915
916 pub fn count<D>(&self, relationship: Relationship<R, D>) -> Option<i64> {
919 self.value(relationship)
920 }
921
922 pub fn sum<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
925 self.value(relationship)
926 }
927
928 pub fn avg<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
931 self.value(relationship)
932 }
933
934 pub fn value<V: ZeroValue, D>(&self, relationship: Relationship<R, D>) -> Option<V> {
938 let (_, v) = self.values.iter().find(|(k, _)| k == relationship.name)?;
939 if v.is_null() {
940 return None;
941 }
942 V::from_zero_value(v).ok()
943 }
944}
945
946pub struct Query<R, T = Vec<R>> {
949 any: AnyQuery,
950 types: PhantomData<fn() -> (R, T)>,
951}
952
953impl<R, T> Clone for Query<R, T> {
954 fn clone(&self) -> Self {
955 Query::from_any(self.any.clone())
956 }
957}
958
959impl<R, T> fmt::Debug for Query<R, T> {
960 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
961 f.debug_tuple("Query").field(&self.any).finish()
962 }
963}
964
965impl<R, T> Query<R, T> {
966 pub fn from_any(any: AnyQuery) -> Self {
968 Query {
969 any,
970 types: PhantomData,
971 }
972 }
973
974 pub fn any(&self) -> &AnyQuery {
976 &self.any
977 }
978
979 pub fn into_any(self) -> AnyQuery {
981 self.any
982 }
983
984 fn map(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Self {
985 Query::from_any(f(self.any))
986 }
987
988 fn to<U>(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Query<R, U> {
989 Query::from_any(f(self.any))
990 }
991}
992
993impl<R: ZeroRow> Query<R> {
994 pub fn table(schema: Arc<Schema>) -> Self {
996 Query::from_any(AnyQuery::new(schema, R::TABLE, System::Client))
997 }
998}
999
1000impl<R: ZeroRow, T> Query<R, T> {
1001 pub fn where_eq<V: ZeroValue>(self, column: Column<R, V>, value: V) -> Self {
1003 self.where_condition(column.eq(value))
1004 }
1005
1006 pub fn where_<V: ZeroValue>(self, column: Column<R, V>, op: SimpleOperator, value: V) -> Self {
1008 self.map(|q| q.where_(column.name, op, value.to_zero_value()))
1009 }
1010
1011 pub fn where_in<V: ZeroValue>(
1013 self,
1014 column: Column<R, V>,
1015 op: SimpleOperator,
1016 values: Vec<V>,
1017 ) -> Self {
1018 self.map(|q| q.where_(column.name, op, array(values)))
1019 }
1020
1021 pub fn where_param<V>(
1023 self,
1024 column: Column<R, V>,
1025 op: SimpleOperator,
1026 param: &StaticParameter,
1027 ) -> Self {
1028 self.map(|q| q.where_param(column.name, op, param))
1029 }
1030
1031 pub fn where_condition(self, condition: Condition) -> Self {
1033 self.map(|q| q.where_condition(condition))
1034 }
1035
1036 pub fn where_expr(self, factory: impl FnOnce(&RowExpression<'_, '_, R>) -> Condition) -> Self {
1039 self.map(|q| {
1040 q.where_expr(|eb| {
1041 factory(&RowExpression {
1042 builder: eb,
1043 row: PhantomData,
1044 })
1045 })
1046 })
1047 }
1048
1049 pub fn where_exists<D: ZeroRow>(
1051 self,
1052 relationship: Relationship<R, D>,
1053 options: ExistsOptions,
1054 sub: impl FnOnce(Query<D>) -> Query<D>,
1055 ) -> Self {
1056 self.map(|q| q.where_exists(relationship.name, options, untyped(sub)))
1057 }
1058
1059 pub fn related<D: ZeroRow, S>(
1063 self,
1064 relationship: Relationship<R, D>,
1065 sub: impl FnOnce(Query<D>) -> Query<D, S>,
1066 ) -> Self {
1067 self.map(|q| q.related(relationship.name, |a| sub(Query::from_any(a)).any))
1068 }
1069
1070 pub fn order_by<V>(self, column: Column<R, V>, direction: Direction) -> Self {
1073 self.map(|q| q.order_by(column.name, direction))
1074 }
1075
1076 pub fn limit(self, limit: i64) -> Self {
1078 self.map(|q| q.limit(limit))
1079 }
1080
1081 pub fn start(self, row: &R, inclusive: bool) -> Self {
1083 self.map(|q| q.start(row.column_values(), inclusive))
1084 }
1085
1086 pub fn start_values(self, values: Vec<(ColumnRef<R>, Value)>, inclusive: bool) -> Self {
1090 let row = values.into_iter().map(|(c, v)| (c.name, v)).collect();
1091 self.map(|q| q.start(row, inclusive))
1092 }
1093
1094 pub fn one(self) -> Query<R, Option<R>> {
1096 self.to(AnyQuery::one)
1097 }
1098
1099 pub fn count(self) -> Query<R, i64> {
1102 self.to(AnyQuery::count)
1103 }
1104
1105 pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
1107 self.to(|q| q.sum(column.name))
1108 }
1109
1110 pub fn sum_json<V>(
1113 self,
1114 column: Column<R, V>,
1115 path: Vec<JsonPathSegment>,
1116 ) -> Query<R, Option<f64>> {
1117 self.to(|q| q.sum_json(column.name, path))
1118 }
1119
1120 pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
1122 self.to(|q| q.avg(column.name))
1123 }
1124
1125 pub fn avg_json<V>(
1128 self,
1129 column: Column<R, V>,
1130 path: Vec<JsonPathSegment>,
1131 ) -> Query<R, Option<f64>> {
1132 self.to(|q| q.avg_json(column.name, path))
1133 }
1134
1135 pub fn min<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
1137 self.to(|q| q.min(column.name))
1138 }
1139
1140 pub fn min_json<V>(
1142 self,
1143 column: Column<R, V>,
1144 path: Vec<JsonPathSegment>,
1145 ) -> Query<R, Option<Value>> {
1146 self.to(|q| q.min_json(column.name, path))
1147 }
1148
1149 pub fn max<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
1152 self.to(|q| q.max(column.name))
1153 }
1154
1155 pub fn max_json<V>(
1157 self,
1158 column: Column<R, V>,
1159 path: Vec<JsonPathSegment>,
1160 ) -> Query<R, Option<Value>> {
1161 self.to(|q| q.max_json(column.name, path))
1162 }
1163
1164 pub fn distinct(self, columns: Vec<ColumnRef<R>>) -> Query<R, Vec<DistinctRow<R>>> {
1167 self.to(|q| q.distinct(names(columns)))
1168 }
1169
1170 pub fn group_by(self, columns: Vec<ColumnRef<R>>) -> GroupedQuery<R> {
1173 GroupedQuery {
1174 any: self.any.group_by(names(columns)),
1175 row: PhantomData,
1176 }
1177 }
1178}
1179
1180impl<C, R, T> crate::query::ZeroQuery<C> for Query<R, T> {
1181 fn any_query(&self, _: &C) -> std::borrow::Cow<'_, AnyQuery> {
1182 std::borrow::Cow::Borrowed(&self.any)
1183 }
1184}
1185
1186impl<R, T: QueryValue> Query<R, T> {
1187 pub fn read(&self, view: &ViewValue) -> Result<T, ZeroValueError> {
1189 T::from_view(view)
1190 }
1191}
1192
1193pub trait TypedQuery<C>: crate::query::ZeroQuery<C> {
1197 type Value: QueryValue;
1199}
1200
1201impl<C, R, T: QueryValue> TypedQuery<C> for Query<R, T> {
1202 type Value = T;
1203}
1204
1205fn names<R>(columns: Vec<ColumnRef<R>>) -> Vec<String> {
1206 columns.into_iter().map(|c| c.name.to_owned()).collect()
1207}
1208
1209fn untyped<D>(sub: impl FnOnce(Query<D>) -> Query<D>) -> impl FnOnce(AnyQuery) -> AnyQuery {
1210 |a| sub(Query::from_any(a)).any
1211}
1212
1213pub struct RowExpression<'a, 'q, R> {
1217 builder: &'a ExpressionBuilder<'q>,
1218 row: PhantomData<fn() -> R>,
1219}
1220
1221impl<R> RowExpression<'_, '_, R> {
1222 pub fn json<V>(&self, column: Column<R, V>, path: Vec<JsonPathSegment>) -> JsonPath<'_, '_> {
1225 JsonPath {
1226 builder: self.builder,
1227 reference: self.builder.json(column.name, path),
1228 }
1229 }
1230
1231 pub fn exists<D: ZeroRow>(
1233 &self,
1234 relationship: Relationship<R, D>,
1235 options: ExistsOptions,
1236 sub: impl FnOnce(Query<D>) -> Query<D>,
1237 ) -> Condition {
1238 self.builder
1239 .exists(relationship.name, options, untyped(sub))
1240 }
1241
1242 pub fn and(&self, conditions: Vec<Condition>) -> Condition {
1244 self.builder.and(conditions)
1245 }
1246
1247 pub fn or(&self, conditions: Vec<Condition>) -> Condition {
1249 self.builder.or(conditions)
1250 }
1251
1252 pub fn not(&self, condition: Condition) -> Condition {
1254 self.builder.not(condition)
1255 }
1256}
1257
1258pub struct JsonPath<'a, 'q> {
1262 builder: &'a ExpressionBuilder<'q>,
1263 reference: JsonPathReference,
1264}
1265
1266impl JsonPath<'_, '_> {
1267 pub fn cmp(&self, op: SimpleOperator, value: Value) -> Condition {
1269 self.builder.cmp_json(&self.reference, op, value)
1270 }
1271
1272 pub fn cmp_param(&self, op: SimpleOperator, param: &StaticParameter) -> Condition {
1274 self.builder.cmp_json_param(&self.reference, op, param)
1275 }
1276
1277 pub fn eq(&self, value: Value) -> Condition {
1279 let op = if value.is_null() {
1280 SimpleOperator::Is
1281 } else {
1282 SimpleOperator::Eq
1283 };
1284 self.cmp(op, value)
1285 }
1286
1287 pub fn ne(&self, value: Value) -> Condition {
1289 let op = if value.is_null() {
1290 SimpleOperator::IsNot
1291 } else {
1292 SimpleOperator::Ne
1293 };
1294 self.cmp(op, value)
1295 }
1296
1297 pub fn lt(&self, value: Value) -> Condition {
1299 self.cmp(SimpleOperator::Lt, value)
1300 }
1301 pub fn le(&self, value: Value) -> Condition {
1303 self.cmp(SimpleOperator::Le, value)
1304 }
1305 pub fn gt(&self, value: Value) -> Condition {
1307 self.cmp(SimpleOperator::Gt, value)
1308 }
1309 pub fn ge(&self, value: Value) -> Condition {
1311 self.cmp(SimpleOperator::Ge, value)
1312 }
1313 pub fn is(&self, value: Value) -> Condition {
1315 self.cmp(SimpleOperator::Is, value)
1316 }
1317 pub fn is_not(&self, value: Value) -> Condition {
1319 self.cmp(SimpleOperator::IsNot, value)
1320 }
1321 pub fn is_in(&self, values: Vec<Value>) -> Condition {
1323 self.cmp(SimpleOperator::In, Value::Array(values))
1324 }
1325 pub fn not_in(&self, values: Vec<Value>) -> Condition {
1327 self.cmp(SimpleOperator::NotIn, Value::Array(values))
1328 }
1329 pub fn like(&self, pattern: &str) -> Condition {
1331 self.cmp(SimpleOperator::Like, Value::String(pattern.to_owned()))
1332 }
1333 pub fn not_like(&self, pattern: &str) -> Condition {
1335 self.cmp(SimpleOperator::NotLike, Value::String(pattern.to_owned()))
1336 }
1337 pub fn ilike(&self, pattern: &str) -> Condition {
1339 self.cmp(SimpleOperator::Ilike, Value::String(pattern.to_owned()))
1340 }
1341 pub fn not_ilike(&self, pattern: &str) -> Condition {
1343 self.cmp(SimpleOperator::NotIlike, Value::String(pattern.to_owned()))
1344 }
1345}
1346
1347pub type Grouped<R, V> = Query<R, Vec<GroupRow<R, V>>>;
1349
1350pub struct GroupedQuery<R> {
1354 any: AnyGroupedQuery,
1355 row: PhantomData<fn() -> R>,
1356}
1357
1358impl<R> GroupedQuery<R> {
1359 pub fn any(&self) -> &AnyGroupedQuery {
1361 &self.any
1362 }
1363
1364 pub fn count(self) -> Grouped<R, i64> {
1366 Query::from_any(self.any.count())
1367 }
1368
1369 pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
1371 Query::from_any(self.any.sum(column.name))
1372 }
1373
1374 pub fn sum_json<V>(
1376 self,
1377 column: Column<R, V>,
1378 path: Vec<JsonPathSegment>,
1379 ) -> Grouped<R, Option<f64>> {
1380 Query::from_any(self.any.sum_json(column.name, path))
1381 }
1382
1383 pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
1385 Query::from_any(self.any.avg(column.name))
1386 }
1387
1388 pub fn avg_json<V>(
1390 self,
1391 column: Column<R, V>,
1392 path: Vec<JsonPathSegment>,
1393 ) -> Grouped<R, Option<f64>> {
1394 Query::from_any(self.any.avg_json(column.name, path))
1395 }
1396
1397 pub fn min<V: OrderedZeroValue>(
1399 self,
1400 column: Column<R, V>,
1401 ) -> Grouped<R, Option<V::Unwrapped>> {
1402 Query::from_any(self.any.min(column.name))
1403 }
1404
1405 pub fn min_json<V>(
1407 self,
1408 column: Column<R, V>,
1409 path: Vec<JsonPathSegment>,
1410 ) -> Grouped<R, Option<Value>> {
1411 Query::from_any(self.any.min_json(column.name, path))
1412 }
1413
1414 pub fn max<V: OrderedZeroValue>(
1416 self,
1417 column: Column<R, V>,
1418 ) -> Grouped<R, Option<V::Unwrapped>> {
1419 Query::from_any(self.any.max(column.name))
1420 }
1421
1422 pub fn max_json<V>(
1424 self,
1425 column: Column<R, V>,
1426 path: Vec<JsonPathSegment>,
1427 ) -> Grouped<R, Option<Value>> {
1428 Query::from_any(self.any.max_json(column.name, path))
1429 }
1430}
1431
1432pub struct GroupRow<R, V> {
1435 pub value: V,
1437 pub columns: Object,
1439 row: PhantomData<fn() -> R>,
1440}
1441
1442impl<R, V: Clone> Clone for GroupRow<R, V> {
1443 fn clone(&self) -> Self {
1444 GroupRow {
1445 value: self.value.clone(),
1446 columns: self.columns.clone(),
1447 row: PhantomData,
1448 }
1449 }
1450}
1451
1452impl<R, V: fmt::Debug> fmt::Debug for GroupRow<R, V> {
1453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454 f.debug_struct("GroupRow")
1455 .field("value", &self.value)
1456 .field("columns", &self.columns)
1457 .finish()
1458 }
1459}
1460
1461impl<R, V: PartialEq> PartialEq for GroupRow<R, V> {
1462 fn eq(&self, other: &Self) -> bool {
1463 self.value == other.value && self.columns == other.columns
1464 }
1465}
1466
1467impl<R, V: ZeroValue> QueryElement for GroupRow<R, V> {
1468 fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
1469 let mut columns: Object = (*entry.row).clone();
1472 let last = columns
1473 .get_index(columns.len().wrapping_sub(1))
1474 .map(|(k, v)| (k.clone(), v.clone()))
1475 .ok_or_else(|| ZeroValueError("a group row has no value".into()))?;
1476 columns.remove(&last.0);
1477 Ok(GroupRow {
1478 value: decode(&last.0, Some(&last.1))?,
1479 columns,
1480 row: PhantomData,
1481 })
1482 }
1483}
1484
1485impl<R, V> GroupRow<R, V> {
1486 pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
1488 group_column(&self.columns, column)
1489 }
1490}
1491
1492pub struct DistinctRow<R> {
1495 pub columns: Object,
1497 row: PhantomData<fn() -> R>,
1498}
1499
1500impl<R> Clone for DistinctRow<R> {
1501 fn clone(&self) -> Self {
1502 DistinctRow {
1503 columns: self.columns.clone(),
1504 row: PhantomData,
1505 }
1506 }
1507}
1508
1509impl<R> fmt::Debug for DistinctRow<R> {
1510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1511 f.debug_tuple("DistinctRow").field(&self.columns).finish()
1512 }
1513}
1514
1515impl<R> PartialEq for DistinctRow<R> {
1516 fn eq(&self, other: &Self) -> bool {
1517 self.columns == other.columns
1518 }
1519}
1520
1521impl<R> QueryElement for DistinctRow<R> {
1522 fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
1523 Ok(DistinctRow {
1524 columns: (*entry.row).clone(),
1525 row: PhantomData,
1526 })
1527 }
1528}
1529
1530impl<R> DistinctRow<R> {
1531 pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
1533 group_column(&self.columns, column)
1534 }
1535}
1536
1537fn group_column<R, C: ZeroValue>(
1538 columns: &Object,
1539 column: Column<R, C>,
1540) -> Result<C, ZeroValueError> {
1541 match columns.get(column.name) {
1542 Some(v) => decode(column.name, Some(v)),
1543 None => Err(ZeroValueError(format!(
1544 "{} is not a column of the group",
1545 column.name
1546 ))),
1547 }
1548}