pub use crate::ast::{Condition, Direction, JsonPathSegment, SimpleOperator};
pub use crate::client::Transaction;
pub use crate::ivm::{ViewEntry, ViewValue};
pub use crate::json::{Object, Value};
pub use crate::query::{AnyGroupedQuery, AnyQuery, ExistsOptions, StaticParameter};
pub use crate::schema::Schema;
use crate::ast::{System, ValuePosition};
use crate::client::Error;
use crate::query::{ExpressionBuilder, JsonPathReference};
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ZeroValueError(pub String);
impl ZeroValueError {
pub fn mismatch(expected: &str, value: &Value) -> Self {
ZeroValueError(format!(
"expected {expected}, got {} {}",
value.type_name(),
crate::json::stringify(value)
))
}
}
impl fmt::Display for ZeroValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ZeroValueError {}
pub trait ZeroValue: Sized {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError>;
fn to_zero_value(&self) -> Value;
fn value_for_null() -> Option<Self> {
None
}
}
impl ZeroValue for String {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
value
.as_str()
.map(str::to_owned)
.ok_or_else(|| ZeroValueError::mismatch("a string", value))
}
fn to_zero_value(&self) -> Value {
Value::String(self.clone())
}
fn value_for_null() -> Option<Self> {
Some(String::new())
}
}
impl ZeroValue for f64 {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
value
.as_f64()
.ok_or_else(|| ZeroValueError::mismatch("a number", value))
}
fn to_zero_value(&self) -> Value {
Value::Number(*self)
}
fn value_for_null() -> Option<Self> {
Some(0.0)
}
}
impl ZeroValue for i64 {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
const MAX_SAFE: f64 = 9_007_199_254_740_992.0;
match value.as_f64() {
Some(n) if n.fract() == 0.0 && n.abs() <= MAX_SAFE => Ok(n as i64),
_ => Err(ZeroValueError::mismatch("an integer", value)),
}
}
fn to_zero_value(&self) -> Value {
Value::Number(*self as f64)
}
fn value_for_null() -> Option<Self> {
Some(0)
}
}
impl ZeroValue for bool {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
value
.as_bool()
.ok_or_else(|| ZeroValueError::mismatch("a boolean", value))
}
fn to_zero_value(&self) -> Value {
Value::Bool(*self)
}
fn value_for_null() -> Option<Self> {
Some(false)
}
}
impl ZeroValue for Value {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
Ok(value.clone())
}
fn to_zero_value(&self) -> Value {
self.clone()
}
}
impl<T: ZeroValue> ZeroValue for Option<T> {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
if value.is_null() {
Ok(None)
} else {
T::from_zero_value(value).map(Some)
}
}
fn to_zero_value(&self) -> Value {
self.as_ref().map_or(Value::Null, T::to_zero_value)
}
}
impl<T: ZeroValue> ZeroValue for Vec<T> {
fn from_zero_value(value: &Value) -> Result<Self, ZeroValueError> {
value
.as_array()
.ok_or_else(|| ZeroValueError::mismatch("an array", value))?
.iter()
.map(T::from_zero_value)
.collect()
}
fn to_zero_value(&self) -> Value {
Value::Array(self.iter().map(T::to_zero_value).collect())
}
}
pub trait NumericZeroValue: ZeroValue {}
impl NumericZeroValue for f64 {}
impl NumericZeroValue for i64 {}
impl<T: NumericZeroValue> NumericZeroValue for Option<T> {}
pub trait OrderedZeroValue: ZeroValue {
type Unwrapped: ZeroValue + OptionalQueryElement;
}
impl OrderedZeroValue for f64 {
type Unwrapped = f64;
}
impl OrderedZeroValue for i64 {
type Unwrapped = i64;
}
impl OrderedZeroValue for String {
type Unwrapped = String;
}
impl<T: OrderedZeroValue> OrderedZeroValue for Option<T> {
type Unwrapped = T::Unwrapped;
}
pub fn decode<V: ZeroValue>(name: &str, value: Option<&Value>) -> Result<V, ZeroValueError> {
let value = value.unwrap_or(&Value::Null);
if value.is_null()
&& let Some(fallback) = V::value_for_null()
{
return Ok(fallback);
}
V::from_zero_value(value).map_err(|e| ZeroValueError(format!("{name}: {e}")))
}
pub fn column<V: ZeroValue>(
entry: &ViewEntry,
name: &str,
index: usize,
) -> Result<V, ZeroValueError> {
match entry.row.get_index(index) {
Some((k, v)) if k == name => decode(name, Some(v)),
_ => decode(name, entry.row.get(name)),
}
}
pub fn many<R: QueryElement>(
entry: &ViewEntry,
name: &str,
) -> Result<Option<Vec<R>>, ZeroValueError> {
match entry.relationship(name) {
None | Some(ViewValue::Value(_)) => Ok(None),
Some(v) => v
.entries()
.into_iter()
.map(R::from_entry)
.collect::<Result<_, _>>()
.map(Some),
}
}
pub fn one<R: QueryElement>(
entry: &ViewEntry,
name: &str,
) -> Result<Option<Box<R>>, ZeroValueError> {
match entry
.relationship(name)
.and_then(|v| v.entries().first().copied())
{
Some(e) => R::from_entry(e).map(|r| Some(Box::new(r))),
None => Ok(None),
}
}
pub fn object<'a>(value: &'a Value, type_name: &str) -> Result<&'a Object, ZeroValueError> {
value
.as_object()
.ok_or_else(|| ZeroValueError::mismatch(&format!("a {type_name} object"), value))
}
pub fn field<V: ZeroValue>(object: &Object, name: &str) -> Result<V, ZeroValueError> {
V::from_zero_value(object.get(name).unwrap_or(&Value::Null))
.map_err(|e| ZeroValueError(format!("{name}: {e}")))
}
pub fn schema_from_json(json: &str) -> Arc<Schema> {
let value = crate::json::parse(json).expect("the generated schema is JSON");
Arc::new(Schema::from_json(&value).expect("the generated schema is a schema"))
}
pub trait QueryElement: Sized {
fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError>;
}
pub trait ZeroRow: QueryElement {
const TABLE: &'static str;
type Update: ColumnValues;
type Key: ColumnValues;
fn column_values(&self) -> Object;
}
pub trait ColumnValues {
fn column_values(&self) -> Object;
}
pub struct TypedTableMutator<'tx, R> {
tx: &'tx Transaction,
row: PhantomData<fn() -> R>,
}
impl<'tx, R: ZeroRow> TypedTableMutator<'tx, R> {
pub fn new(tx: &'tx Transaction) -> Self {
TypedTableMutator {
tx,
row: PhantomData,
}
}
pub fn insert(&self, row: &R) -> Result<(), Error> {
self.tx.table(R::TABLE).insert(&row.column_values())
}
pub fn upsert(&self, row: &R) -> Result<(), Error> {
self.tx.table(R::TABLE).upsert(&row.column_values())
}
pub fn update(&self, value: &R::Update) -> Result<(), Error> {
self.tx.table(R::TABLE).update(&value.column_values())
}
pub fn delete(&self, key: &R::Key) -> Result<(), Error> {
self.tx.table(R::TABLE).delete(&key.column_values())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum ColumnUpdate<V> {
#[default]
Unchanged,
Null,
Set(V),
}
impl<V> From<Option<V>> for ColumnUpdate<V> {
fn from(value: Option<V>) -> Self {
value.map_or(ColumnUpdate::Null, ColumnUpdate::Set)
}
}
impl<V: ZeroValue> ColumnUpdate<V> {
pub fn to_zero_value(&self) -> Option<Value> {
match self {
ColumnUpdate::Unchanged => None,
ColumnUpdate::Null => Some(Value::Null),
ColumnUpdate::Set(v) => Some(v.to_zero_value()),
}
}
}
pub trait QueryValue: Sized {
fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError>;
fn update_from_view(
&mut self,
previous: &mut ViewValue,
view: &ViewValue,
) -> Result<(), ZeroValueError> {
*self = Self::from_view(view)?;
*previous = view.clone();
Ok(())
}
}
impl<E: QueryElement> QueryValue for Vec<E> {
fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
view.entries().into_iter().map(E::from_entry).collect()
}
fn update_from_view(
&mut self,
previous: &mut ViewValue,
view: &ViewValue,
) -> Result<(), ZeroValueError> {
let (ViewValue::Many(old), ViewValue::Many(new)) = (&mut *previous, view) else {
*self = Self::from_view(view)?;
*previous = view.clone();
return Ok(());
};
if old.len() != self.len() {
*self = Self::from_view(view)?;
*previous = view.clone();
return Ok(());
}
let mut runs: Vec<Run> = Vec::new();
let mut fresh = Vec::new();
let mut in_place = old.len() == new.len();
let mut j = 0;
for (i, entry) in new.iter().enumerate() {
let kept = if old.get(j).is_some_and(|o| same_entry(o, entry)) {
Some(j)
} else if old.get(j + 1).is_some_and(|o| same_entry(o, entry)) {
Some(j + 1)
} else {
None
};
match (kept, runs.last_mut()) {
(Some(k), Some(Run::Keep { from, len })) if *from + *len == k => *len += 1,
(Some(k), _) => runs.push(Run::Keep { from: k, len: 1 }),
(None, Some(Run::Fresh(len))) => *len += 1,
(None, _) => runs.push(Run::Fresh(1)),
}
match kept {
Some(k) => {
in_place &= k == i;
j = k + 1;
}
None => fresh.push(E::from_entry(entry)?),
}
}
if in_place && fresh.is_empty() {
return Ok(());
}
let mut fresh = fresh.into_iter();
apply_runs(self, &runs, in_place, new.len(), |_| {
fresh.next().expect("a row read for each new entry")
});
apply_runs(Rc::make_mut(old), &runs, in_place, new.len(), |i| {
new[i].clone()
});
Ok(())
}
}
fn same_entry(a: &ViewEntry, b: &ViewEntry) -> bool {
(Rc::ptr_eq(&a.row, &b.row) || a.row == b.row)
&& a.relationships.len() == b.relationships.len()
&& a.relationships
.iter()
.zip(&b.relationships)
.all(|((m, a), (n, b))| m == n && same_value(a, b))
}
fn same_value(a: &ViewValue, b: &ViewValue) -> bool {
match (a, b) {
(ViewValue::Many(a), ViewValue::Many(b)) => {
Rc::ptr_eq(a, b)
|| (a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| same_entry(a, b)))
}
(ViewValue::One(Some(a)), ViewValue::One(Some(b))) => same_entry(a, b),
(a, b) => a == b,
}
}
enum Run {
Keep { from: usize, len: usize },
Fresh(usize),
}
fn apply_runs<X>(
items: &mut Vec<X>,
runs: &[Run],
in_place: bool,
len: usize,
mut fresh: impl FnMut(usize) -> X,
) {
if in_place {
let mut at = 0;
for run in runs {
match *run {
Run::Keep { len, .. } => at += len,
Run::Fresh(n) => {
for (i, item) in items[at..at + n].iter_mut().enumerate() {
*item = fresh(at + i);
}
at += n;
}
}
}
return;
}
let mut out = Vec::with_capacity(len);
let mut old = std::mem::take(items).into_iter();
let mut next = 0;
for run in runs {
match *run {
Run::Keep { from, len } => {
if from > next {
old.nth(from - next - 1);
}
out.extend(old.by_ref().take(len));
next = from + len;
}
Run::Fresh(n) => {
let at = out.len();
out.extend((at..at + n).map(&mut fresh));
}
}
}
*items = out;
}
pub trait OptionalQueryElement: Sized {
fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError>;
}
impl<T: OptionalQueryElement> QueryValue for Option<T> {
fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
T::optional_from_view(view)
}
}
impl QueryValue for i64 {
fn from_view(view: &ViewValue) -> Result<Self, ZeroValueError> {
i64::from_zero_value(aggregate_value(view)?)
}
}
fn aggregate_value(view: &ViewValue) -> Result<&Value, ZeroValueError> {
match view {
ViewValue::Value(v) => Ok(v),
_ => Err(ZeroValueError(
"expected the value of an aggregate, got rows".into(),
)),
}
}
pub fn optional_row<R: QueryElement>(view: &ViewValue) -> Result<Option<R>, ZeroValueError> {
view.entries().first().map(|e| R::from_entry(e)).transpose()
}
pub fn optional_value<V: ZeroValue>(view: &ViewValue) -> Result<Option<V>, ZeroValueError> {
let value = aggregate_value(view)?;
if value.is_null() {
Ok(None)
} else {
V::from_zero_value(value).map(Some)
}
}
macro_rules! optional_values {
($($t:ty),*) => {$(
impl OptionalQueryElement for $t {
fn optional_from_view(view: &ViewValue) -> Result<Option<Self>, ZeroValueError> {
optional_value(view)
}
}
)*};
}
optional_values!(f64, i64, String, bool, Value);
pub struct Column<R, V> {
name: &'static str,
types: PhantomData<fn() -> (R, V)>,
}
impl<R, V> Clone for Column<R, V> {
fn clone(&self) -> Self {
*self
}
}
impl<R, V> Copy for Column<R, V> {}
impl<R, V> fmt::Debug for Column<R, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Column").field(&self.name).finish()
}
}
impl<R, V> Column<R, V> {
pub const fn new(name: &'static str) -> Self {
Column {
name,
types: PhantomData,
}
}
pub fn name(&self) -> &'static str {
self.name
}
fn compare(self, op: SimpleOperator, right: ValuePosition) -> Condition {
Condition::Simple {
op,
left: ValuePosition::Column(self.name.to_owned()),
right,
}
}
pub fn cmp_param(self, op: SimpleOperator, param: &StaticParameter) -> Condition {
self.compare(
op,
ValuePosition::Static {
anchor: param.anchor,
field: param.field.clone(),
},
)
}
}
impl<R, V: ZeroValue> Column<R, V> {
pub fn cmp(self, op: SimpleOperator, value: V) -> Condition {
self.compare(op, ValuePosition::Literal(value.to_zero_value()))
}
pub fn eq(self, value: V) -> Condition {
let value = value.to_zero_value();
let op = if value.is_null() {
SimpleOperator::Is
} else {
SimpleOperator::Eq
};
self.compare(op, ValuePosition::Literal(value))
}
pub fn ne(self, value: V) -> Condition {
let value = value.to_zero_value();
let op = if value.is_null() {
SimpleOperator::IsNot
} else {
SimpleOperator::Ne
};
self.compare(op, ValuePosition::Literal(value))
}
pub fn lt(self, value: V) -> Condition {
self.cmp(SimpleOperator::Lt, value)
}
pub fn le(self, value: V) -> Condition {
self.cmp(SimpleOperator::Le, value)
}
pub fn gt(self, value: V) -> Condition {
self.cmp(SimpleOperator::Gt, value)
}
pub fn ge(self, value: V) -> Condition {
self.cmp(SimpleOperator::Ge, value)
}
pub fn is(self, value: V) -> Condition {
self.cmp(SimpleOperator::Is, value)
}
pub fn is_not(self, value: V) -> Condition {
self.cmp(SimpleOperator::IsNot, value)
}
pub fn is_in(self, values: Vec<V>) -> Condition {
self.compare(SimpleOperator::In, ValuePosition::Literal(array(values)))
}
pub fn not_in(self, values: Vec<V>) -> Condition {
self.compare(SimpleOperator::NotIn, ValuePosition::Literal(array(values)))
}
}
fn array<V: ZeroValue>(values: Vec<V>) -> Value {
Value::Array(values.iter().map(V::to_zero_value).collect())
}
macro_rules! like {
($t:ty) => {
impl<R> Column<R, $t> {
pub fn like(self, pattern: &str) -> Condition {
self.pattern(SimpleOperator::Like, pattern)
}
pub fn not_like(self, pattern: &str) -> Condition {
self.pattern(SimpleOperator::NotLike, pattern)
}
pub fn ilike(self, pattern: &str) -> Condition {
self.pattern(SimpleOperator::Ilike, pattern)
}
pub fn not_ilike(self, pattern: &str) -> Condition {
self.pattern(SimpleOperator::NotIlike, pattern)
}
fn pattern(self, op: SimpleOperator, pattern: &str) -> Condition {
self.compare(
op,
ValuePosition::Literal(Value::String(pattern.to_owned())),
)
}
}
};
}
like!(String);
like!(Option<String>);
pub struct ColumnRef<R> {
name: &'static str,
row: PhantomData<fn() -> R>,
}
impl<R> Clone for ColumnRef<R> {
fn clone(&self) -> Self {
*self
}
}
impl<R> Copy for ColumnRef<R> {}
impl<R> fmt::Debug for ColumnRef<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("ColumnRef").field(&self.name).finish()
}
}
impl<R> ColumnRef<R> {
pub fn name(&self) -> &'static str {
self.name
}
}
impl<R, V> From<Column<R, V>> for ColumnRef<R> {
fn from(c: Column<R, V>) -> Self {
ColumnRef {
name: c.name,
row: PhantomData,
}
}
}
pub struct Relationship<R, D> {
name: &'static str,
types: PhantomData<fn() -> (R, D)>,
}
impl<R, D> Clone for Relationship<R, D> {
fn clone(&self) -> Self {
*self
}
}
impl<R, D> Copy for Relationship<R, D> {}
impl<R, D> fmt::Debug for Relationship<R, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Relationship").field(&self.name).finish()
}
}
impl<R, D> Relationship<R, D> {
pub const fn new(name: &'static str) -> Self {
Relationship {
name,
types: PhantomData,
}
}
pub fn name(&self) -> &'static str {
self.name
}
}
pub struct RelationshipAggregates<R> {
pub values: Vec<(String, Value)>,
row: PhantomData<fn() -> R>,
}
impl<R> Clone for RelationshipAggregates<R> {
fn clone(&self) -> Self {
RelationshipAggregates {
values: self.values.clone(),
row: PhantomData,
}
}
}
impl<R> fmt::Debug for RelationshipAggregates<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map()
.entries(self.values.iter().map(|(k, v)| (k, v)))
.finish()
}
}
impl<R> PartialEq for RelationshipAggregates<R> {
fn eq(&self, other: &Self) -> bool {
self.values == other.values
}
}
impl<R> Default for RelationshipAggregates<R> {
fn default() -> Self {
RelationshipAggregates {
values: Vec::new(),
row: PhantomData,
}
}
}
impl<R> RelationshipAggregates<R> {
pub fn from_entry(entry: &ViewEntry) -> Self {
RelationshipAggregates {
values: entry
.relationships
.iter()
.filter_map(|(name, v)| match v {
ViewValue::Value(v) => Some((name.clone(), v.clone())),
_ => None,
})
.collect(),
row: PhantomData,
}
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn count<D>(&self, relationship: Relationship<R, D>) -> Option<i64> {
self.value(relationship)
}
pub fn sum<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
self.value(relationship)
}
pub fn avg<D>(&self, relationship: Relationship<R, D>) -> Option<f64> {
self.value(relationship)
}
pub fn value<V: ZeroValue, D>(&self, relationship: Relationship<R, D>) -> Option<V> {
let (_, v) = self.values.iter().find(|(k, _)| k == relationship.name)?;
if v.is_null() {
return None;
}
V::from_zero_value(v).ok()
}
}
pub struct Query<R, T = Vec<R>> {
any: AnyQuery,
types: PhantomData<fn() -> (R, T)>,
}
impl<R, T> Clone for Query<R, T> {
fn clone(&self) -> Self {
Query::from_any(self.any.clone())
}
}
impl<R, T> fmt::Debug for Query<R, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Query").field(&self.any).finish()
}
}
impl<R, T> Query<R, T> {
pub fn from_any(any: AnyQuery) -> Self {
Query {
any,
types: PhantomData,
}
}
pub fn any(&self) -> &AnyQuery {
&self.any
}
pub fn into_any(self) -> AnyQuery {
self.any
}
fn map(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Self {
Query::from_any(f(self.any))
}
fn to<U>(self, f: impl FnOnce(AnyQuery) -> AnyQuery) -> Query<R, U> {
Query::from_any(f(self.any))
}
}
impl<R: ZeroRow> Query<R> {
pub fn table(schema: Arc<Schema>) -> Self {
Query::from_any(AnyQuery::new(schema, R::TABLE, System::Client))
}
}
impl<R: ZeroRow, T> Query<R, T> {
pub fn where_eq<V: ZeroValue>(self, column: Column<R, V>, value: V) -> Self {
self.where_condition(column.eq(value))
}
pub fn where_<V: ZeroValue>(self, column: Column<R, V>, op: SimpleOperator, value: V) -> Self {
self.map(|q| q.where_(column.name, op, value.to_zero_value()))
}
pub fn where_in<V: ZeroValue>(
self,
column: Column<R, V>,
op: SimpleOperator,
values: Vec<V>,
) -> Self {
self.map(|q| q.where_(column.name, op, array(values)))
}
pub fn where_param<V>(
self,
column: Column<R, V>,
op: SimpleOperator,
param: &StaticParameter,
) -> Self {
self.map(|q| q.where_param(column.name, op, param))
}
pub fn where_condition(self, condition: Condition) -> Self {
self.map(|q| q.where_condition(condition))
}
pub fn where_expr(self, factory: impl FnOnce(&RowExpression<'_, '_, R>) -> Condition) -> Self {
self.map(|q| {
q.where_expr(|eb| {
factory(&RowExpression {
builder: eb,
row: PhantomData,
})
})
})
}
pub fn where_exists<D: ZeroRow>(
self,
relationship: Relationship<R, D>,
options: ExistsOptions,
sub: impl FnOnce(Query<D>) -> Query<D>,
) -> Self {
self.map(|q| q.where_exists(relationship.name, options, untyped(sub)))
}
pub fn related<D: ZeroRow, S>(
self,
relationship: Relationship<R, D>,
sub: impl FnOnce(Query<D>) -> Query<D, S>,
) -> Self {
self.map(|q| q.related(relationship.name, |a| sub(Query::from_any(a)).any))
}
pub fn order_by<V>(self, column: Column<R, V>, direction: Direction) -> Self {
self.map(|q| q.order_by(column.name, direction))
}
pub fn limit(self, limit: i64) -> Self {
self.map(|q| q.limit(limit))
}
pub fn start(self, row: &R, inclusive: bool) -> Self {
self.map(|q| q.start(row.column_values(), inclusive))
}
pub fn start_values(self, values: Vec<(ColumnRef<R>, Value)>, inclusive: bool) -> Self {
let row = values.into_iter().map(|(c, v)| (c.name, v)).collect();
self.map(|q| q.start(row, inclusive))
}
pub fn one(self) -> Query<R, Option<R>> {
self.to(AnyQuery::one)
}
pub fn count(self) -> Query<R, i64> {
self.to(AnyQuery::count)
}
pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
self.to(|q| q.sum(column.name))
}
pub fn sum_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Query<R, Option<f64>> {
self.to(|q| q.sum_json(column.name, path))
}
pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Query<R, Option<f64>> {
self.to(|q| q.avg(column.name))
}
pub fn avg_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Query<R, Option<f64>> {
self.to(|q| q.avg_json(column.name, path))
}
pub fn min<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
self.to(|q| q.min(column.name))
}
pub fn min_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Query<R, Option<Value>> {
self.to(|q| q.min_json(column.name, path))
}
pub fn max<V: OrderedZeroValue>(self, column: Column<R, V>) -> Query<R, Option<V::Unwrapped>> {
self.to(|q| q.max(column.name))
}
pub fn max_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Query<R, Option<Value>> {
self.to(|q| q.max_json(column.name, path))
}
pub fn distinct(self, columns: Vec<ColumnRef<R>>) -> Query<R, Vec<DistinctRow<R>>> {
self.to(|q| q.distinct(names(columns)))
}
pub fn group_by(self, columns: Vec<ColumnRef<R>>) -> GroupedQuery<R> {
GroupedQuery {
any: self.any.group_by(names(columns)),
row: PhantomData,
}
}
}
impl<C, R, T> crate::query::ZeroQuery<C> for Query<R, T> {
fn any_query(&self, _: &C) -> std::borrow::Cow<'_, AnyQuery> {
std::borrow::Cow::Borrowed(&self.any)
}
}
impl<R, T: QueryValue> Query<R, T> {
pub fn read(&self, view: &ViewValue) -> Result<T, ZeroValueError> {
T::from_view(view)
}
}
pub trait TypedQuery<C>: crate::query::ZeroQuery<C> {
type Value: QueryValue;
}
impl<C, R, T: QueryValue> TypedQuery<C> for Query<R, T> {
type Value = T;
}
fn names<R>(columns: Vec<ColumnRef<R>>) -> Vec<String> {
columns.into_iter().map(|c| c.name.to_owned()).collect()
}
fn untyped<D>(sub: impl FnOnce(Query<D>) -> Query<D>) -> impl FnOnce(AnyQuery) -> AnyQuery {
|a| sub(Query::from_any(a)).any
}
pub struct RowExpression<'a, 'q, R> {
builder: &'a ExpressionBuilder<'q>,
row: PhantomData<fn() -> R>,
}
impl<R> RowExpression<'_, '_, R> {
pub fn json<V>(&self, column: Column<R, V>, path: Vec<JsonPathSegment>) -> JsonPath<'_, '_> {
JsonPath {
builder: self.builder,
reference: self.builder.json(column.name, path),
}
}
pub fn exists<D: ZeroRow>(
&self,
relationship: Relationship<R, D>,
options: ExistsOptions,
sub: impl FnOnce(Query<D>) -> Query<D>,
) -> Condition {
self.builder
.exists(relationship.name, options, untyped(sub))
}
pub fn and(&self, conditions: Vec<Condition>) -> Condition {
self.builder.and(conditions)
}
pub fn or(&self, conditions: Vec<Condition>) -> Condition {
self.builder.or(conditions)
}
pub fn not(&self, condition: Condition) -> Condition {
self.builder.not(condition)
}
}
pub struct JsonPath<'a, 'q> {
builder: &'a ExpressionBuilder<'q>,
reference: JsonPathReference,
}
impl JsonPath<'_, '_> {
pub fn cmp(&self, op: SimpleOperator, value: Value) -> Condition {
self.builder.cmp_json(&self.reference, op, value)
}
pub fn cmp_param(&self, op: SimpleOperator, param: &StaticParameter) -> Condition {
self.builder.cmp_json_param(&self.reference, op, param)
}
pub fn eq(&self, value: Value) -> Condition {
let op = if value.is_null() {
SimpleOperator::Is
} else {
SimpleOperator::Eq
};
self.cmp(op, value)
}
pub fn ne(&self, value: Value) -> Condition {
let op = if value.is_null() {
SimpleOperator::IsNot
} else {
SimpleOperator::Ne
};
self.cmp(op, value)
}
pub fn lt(&self, value: Value) -> Condition {
self.cmp(SimpleOperator::Lt, value)
}
pub fn le(&self, value: Value) -> Condition {
self.cmp(SimpleOperator::Le, value)
}
pub fn gt(&self, value: Value) -> Condition {
self.cmp(SimpleOperator::Gt, value)
}
pub fn ge(&self, value: Value) -> Condition {
self.cmp(SimpleOperator::Ge, value)
}
pub fn is(&self, value: Value) -> Condition {
self.cmp(SimpleOperator::Is, value)
}
pub fn is_not(&self, value: Value) -> Condition {
self.cmp(SimpleOperator::IsNot, value)
}
pub fn is_in(&self, values: Vec<Value>) -> Condition {
self.cmp(SimpleOperator::In, Value::Array(values))
}
pub fn not_in(&self, values: Vec<Value>) -> Condition {
self.cmp(SimpleOperator::NotIn, Value::Array(values))
}
pub fn like(&self, pattern: &str) -> Condition {
self.cmp(SimpleOperator::Like, Value::String(pattern.to_owned()))
}
pub fn not_like(&self, pattern: &str) -> Condition {
self.cmp(SimpleOperator::NotLike, Value::String(pattern.to_owned()))
}
pub fn ilike(&self, pattern: &str) -> Condition {
self.cmp(SimpleOperator::Ilike, Value::String(pattern.to_owned()))
}
pub fn not_ilike(&self, pattern: &str) -> Condition {
self.cmp(SimpleOperator::NotIlike, Value::String(pattern.to_owned()))
}
}
pub type Grouped<R, V> = Query<R, Vec<GroupRow<R, V>>>;
pub struct GroupedQuery<R> {
any: AnyGroupedQuery,
row: PhantomData<fn() -> R>,
}
impl<R> GroupedQuery<R> {
pub fn any(&self) -> &AnyGroupedQuery {
&self.any
}
pub fn count(self) -> Grouped<R, i64> {
Query::from_any(self.any.count())
}
pub fn sum<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
Query::from_any(self.any.sum(column.name))
}
pub fn sum_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Grouped<R, Option<f64>> {
Query::from_any(self.any.sum_json(column.name, path))
}
pub fn avg<V: NumericZeroValue>(self, column: Column<R, V>) -> Grouped<R, Option<f64>> {
Query::from_any(self.any.avg(column.name))
}
pub fn avg_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Grouped<R, Option<f64>> {
Query::from_any(self.any.avg_json(column.name, path))
}
pub fn min<V: OrderedZeroValue>(
self,
column: Column<R, V>,
) -> Grouped<R, Option<V::Unwrapped>> {
Query::from_any(self.any.min(column.name))
}
pub fn min_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Grouped<R, Option<Value>> {
Query::from_any(self.any.min_json(column.name, path))
}
pub fn max<V: OrderedZeroValue>(
self,
column: Column<R, V>,
) -> Grouped<R, Option<V::Unwrapped>> {
Query::from_any(self.any.max(column.name))
}
pub fn max_json<V>(
self,
column: Column<R, V>,
path: Vec<JsonPathSegment>,
) -> Grouped<R, Option<Value>> {
Query::from_any(self.any.max_json(column.name, path))
}
}
pub struct GroupRow<R, V> {
pub value: V,
pub columns: Object,
row: PhantomData<fn() -> R>,
}
impl<R, V: Clone> Clone for GroupRow<R, V> {
fn clone(&self) -> Self {
GroupRow {
value: self.value.clone(),
columns: self.columns.clone(),
row: PhantomData,
}
}
}
impl<R, V: fmt::Debug> fmt::Debug for GroupRow<R, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GroupRow")
.field("value", &self.value)
.field("columns", &self.columns)
.finish()
}
}
impl<R, V: PartialEq> PartialEq for GroupRow<R, V> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.columns == other.columns
}
}
impl<R, V: ZeroValue> QueryElement for GroupRow<R, V> {
fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
let mut columns: Object = (*entry.row).clone();
let last = columns
.get_index(columns.len().wrapping_sub(1))
.map(|(k, v)| (k.clone(), v.clone()))
.ok_or_else(|| ZeroValueError("a group row has no value".into()))?;
columns.remove(&last.0);
Ok(GroupRow {
value: decode(&last.0, Some(&last.1))?,
columns,
row: PhantomData,
})
}
}
impl<R, V> GroupRow<R, V> {
pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
group_column(&self.columns, column)
}
}
pub struct DistinctRow<R> {
pub columns: Object,
row: PhantomData<fn() -> R>,
}
impl<R> Clone for DistinctRow<R> {
fn clone(&self) -> Self {
DistinctRow {
columns: self.columns.clone(),
row: PhantomData,
}
}
}
impl<R> fmt::Debug for DistinctRow<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("DistinctRow").field(&self.columns).finish()
}
}
impl<R> PartialEq for DistinctRow<R> {
fn eq(&self, other: &Self) -> bool {
self.columns == other.columns
}
}
impl<R> QueryElement for DistinctRow<R> {
fn from_entry(entry: &ViewEntry) -> Result<Self, ZeroValueError> {
Ok(DistinctRow {
columns: (*entry.row).clone(),
row: PhantomData,
})
}
}
impl<R> DistinctRow<R> {
pub fn get<C: ZeroValue>(&self, column: Column<R, C>) -> Result<C, ZeroValueError> {
group_column(&self.columns, column)
}
}
fn group_column<R, C: ZeroValue>(
columns: &Object,
column: Column<R, C>,
) -> Result<C, ZeroValueError> {
match columns.get(column.name) {
Some(v) => decode(column.name, Some(v)),
None => Err(ZeroValueError(format!(
"{} is not a column of the group",
column.name
))),
}
}