1use crate::ctx::Context;
2use crate::dbs::{Options, Transaction};
3use crate::err::Error;
4use crate::fmt::Fmt;
5use crate::idiom::Idiom;
6use crate::operator::Operator;
7use crate::value::Value;
8use revision::revisioned;
9use serde::{Deserialize, Serialize};
10use std::fmt::{self, Display, Formatter};
11
12#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Hash)]
13#[revisioned(revision = 1)]
14pub enum Data {
15 EmptyExpression,
16 SetExpression(Vec<(Idiom, Operator, Value)>),
17 UnsetExpression(Vec<Idiom>),
18 PatchExpression(Value),
19 MergeExpression(Value),
20 ReplaceExpression(Value),
21 ContentExpression(Value),
22 SingleExpression(Value),
23 ValuesExpression(Vec<Vec<(Idiom, Value)>>),
24 UpdateExpression(Vec<(Idiom, Operator, Value)>),
25}
26
27impl Default for Data {
28 fn default() -> Self {
29 Self::EmptyExpression
30 }
31}
32
33impl Data {
34 pub(crate) async fn rid(
36 &self,
37 ctx: &Context<'_>,
38 opt: &Options,
39 txn: &Transaction,
40 ) -> Result<Option<Value>, Error> {
41 match self {
42 Self::MergeExpression(v) => {
43 Ok(v.compute(ctx, opt, txn, None).await?.rid().some())
45 }
46 Self::ReplaceExpression(v) => {
47 Ok(v.compute(ctx, opt, txn, None).await?.rid().some())
49 }
50 Self::ContentExpression(v) => {
51 Ok(v.compute(ctx, opt, txn, None).await?.rid().some())
53 }
54 Self::SetExpression(v) => match v.iter().find(|f| f.0.is_id()) {
55 Some((_, _, v)) => {
56 Ok(v.compute(ctx, opt, txn, None).await?.some())
58 }
59 _ => Ok(None),
61 },
62 _ => Ok(None),
64 }
65 }
66}
67
68impl Display for Data {
69 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
70 match self {
71 Self::EmptyExpression => Ok(()),
72 Self::SetExpression(v) => write!(
73 f,
74 "SET {}",
75 Fmt::comma_separated(
76 v.iter().map(|args| Fmt::new(args, |(l, o, r), f| write!(f, "{l} {o} {r}",)))
77 )
78 ),
79 Self::UnsetExpression(v) => write!(
80 f,
81 "UNSET {}",
82 Fmt::comma_separated(v.iter().map(|args| Fmt::new(args, |l, f| write!(f, "{l}",))))
83 ),
84 Self::PatchExpression(v) => write!(f, "PATCH {v}"),
85 Self::MergeExpression(v) => write!(f, "MERGE {v}"),
86 Self::ReplaceExpression(v) => write!(f, "REPLACE {v}"),
87 Self::ContentExpression(v) => write!(f, "CONTENT {v}"),
88 Self::SingleExpression(v) => Display::fmt(v, f),
89 Self::ValuesExpression(v) => write!(
90 f,
91 "({}) VALUES {}",
92 Fmt::comma_separated(v.first().unwrap().iter().map(|(v, _)| v)),
93 Fmt::comma_separated(v.iter().map(|v| Fmt::new(v, |v, f| write!(
94 f,
95 "({})",
96 Fmt::comma_separated(v.iter().map(|(_, v)| v))
97 ))))
98 ),
99 Self::UpdateExpression(v) => write!(
100 f,
101 "ON DUPLICATE KEY UPDATE {}",
102 Fmt::comma_separated(
103 v.iter().map(|args| Fmt::new(args, |(l, o, r), f| write!(f, "{l} {o} {r}",)))
104 )
105 ),
106 }
107 }
108}