1mod coding;
4mod normalize;
5pub mod strict;
6
7pub(crate) use coding::is_homogeneous;
8pub(crate) use normalize::cmp_related;
9pub use normalize::normalize_condition;
10
11use crate::json::{Object, Value};
12
13#[derive(Clone, Debug, PartialEq, Default)]
15pub struct Ast {
16 pub schema: Option<String>,
17 pub table: String,
18 pub alias: Option<String>,
20 pub where_: Option<Condition>,
21 pub related: Option<Vec<CorrelatedSubquery>>,
22 pub start: Option<Bound>,
23 pub limit: Option<f64>,
24 pub order_by: Option<Vec<OrderPart>>,
25 pub aggregate: Option<Aggregate>,
28 pub group_by: Option<Vec<String>>,
31}
32
33impl Ast {
34 pub fn new(table: impl Into<String>) -> Self {
35 Ast {
36 table: table.into(),
37 ..Ast::default()
38 }
39 }
40}
41
42macro_rules! string_enum {
43 ($(#[$m:meta])* $name:ident { $($variant:ident = $s:literal),* $(,)? }) => {
44 $(#[$m])*
45 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
46 pub enum $name { $(#[doc = concat!("`", $s, "`")] $variant),* }
47
48 impl $name {
49 pub const ALL: &[$name] = &[$($name::$variant),*];
51
52 pub fn as_str(self) -> &'static str {
54 match self { $($name::$variant => $s),* }
55 }
56
57 pub fn parse(s: &str) -> Option<$name> {
59 match s { $($s => Some($name::$variant),)* _ => None }
60 }
61 }
62 };
63}
64pub(crate) use string_enum;
65
66string_enum!(
67 AggregateFunction { Count = "count", Sum = "sum", Avg = "avg", Min = "min", Max = "max" }
69);
70
71string_enum!(System { Permissions = "permissions", Client = "client", Test = "test" });
72
73string_enum!(Direction { Asc = "asc", Desc = "desc" });
74
75string_enum!(SimpleOperator {
76 Eq = "=",
77 Ne = "!=",
78 Is = "IS",
79 IsNot = "IS NOT",
80 Lt = "<",
81 Gt = ">",
82 Le = "<=",
83 Ge = ">=",
84 Like = "LIKE",
85 NotLike = "NOT LIKE",
86 Ilike = "ILIKE",
87 NotIlike = "NOT ILIKE",
88 In = "IN",
89 NotIn = "NOT IN",
90});
91
92string_enum!(CorrelatedSubqueryOperator { Exists = "EXISTS", NotExists = "NOT EXISTS" });
93
94string_enum!(Anchor { AuthData = "authData", PreMutationRow = "preMutationRow" });
95
96#[derive(Clone, Debug, PartialEq, Eq, Hash)]
98pub enum JsonPathSegment {
99 Key(String),
100 Index(u32),
101}
102
103impl JsonPathSegment {
104 pub fn to_json(&self) -> Value {
105 match self {
106 JsonPathSegment::Key(k) => Value::String(k.clone()),
107 JsonPathSegment::Index(i) => Value::Number(f64::from(*i)),
108 }
109 }
110}
111
112pub const MAX_JSON_PATH_INDEX: u32 = i32::MAX as u32;
114
115#[derive(Clone, Debug, PartialEq)]
117pub struct Aggregate {
118 pub fn_: AggregateFunction,
119 pub field: Option<String>,
121 pub path: Option<Vec<JsonPathSegment>>,
123 pub distinct: Option<Vec<String>>,
125}
126
127impl Aggregate {
128 pub fn new(fn_: AggregateFunction) -> Self {
129 Aggregate {
130 fn_,
131 field: None,
132 path: None,
133 distinct: None,
134 }
135 }
136}
137
138#[derive(Clone, Debug, PartialEq)]
139pub struct Bound {
140 pub row: Object,
142 pub exclusive: bool,
143}
144
145#[derive(Clone, Debug, PartialEq)]
146pub struct OrderPart {
147 pub field: String,
148 pub direction: Direction,
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub enum StaticField {
153 Single(String),
154 Path(Vec<String>),
155}
156
157impl StaticField {
158 pub fn to_json(&self) -> Value {
159 match self {
160 StaticField::Single(s) => Value::String(s.clone()),
161 StaticField::Path(p) => crate::decode::strings_json(p),
162 }
163 }
164}
165
166#[derive(Clone, Debug, PartialEq)]
169pub enum ValuePosition {
170 Literal(Value),
171 Column(String),
172 Json {
174 column: String,
175 path: Vec<JsonPathSegment>,
176 },
177 Static {
178 anchor: Anchor,
179 field: StaticField,
180 },
181}
182
183#[derive(Clone, Debug, PartialEq)]
184pub enum Condition {
185 Simple {
186 op: SimpleOperator,
187 left: ValuePosition,
188 right: ValuePosition,
189 },
190 And(Vec<Condition>),
191 Or(Vec<Condition>),
192 CorrelatedSubquery {
193 related: CorrelatedSubquery,
194 op: CorrelatedSubqueryOperator,
195 flip: Option<bool>,
196 scalar: Option<bool>,
197 },
198}
199
200impl Condition {
201 pub fn conditions(&self) -> Option<&[Condition]> {
203 match self {
204 Condition::And(c) | Condition::Or(c) => Some(c),
205 _ => None,
206 }
207 }
208}
209
210#[derive(Clone, Debug, PartialEq)]
211pub struct Correlation {
212 pub parent_field: Vec<String>,
213 pub child_field: Vec<String>,
214}
215
216#[derive(Clone, Debug, PartialEq)]
217pub struct CorrelatedSubquery {
218 pub correlation: Correlation,
219 pub subquery: Box<Ast>,
220 pub system: Option<System>,
221 pub hidden: Option<bool>,
224 pub aggregate: Option<Aggregate>,
226}
227
228pub fn json_value_at<'a>(path: &[JsonPathSegment], value: Option<&'a Value>) -> &'a Value {
232 static NULL: Value = Value::Null;
233 let mut v = value.unwrap_or(&NULL);
234 for segment in path {
235 v = match (v, segment) {
236 (Value::Object(o), JsonPathSegment::Key(k)) => o.get(k).unwrap_or(&NULL),
237 (Value::Array(a), JsonPathSegment::Index(i)) => a.get(*i as usize).unwrap_or(&NULL),
238 _ => &NULL,
239 };
240 }
241 v
242}
243
244pub fn format_json_path(column: &str, path: &[JsonPathSegment]) -> String {
246 let mut out = column.to_owned();
247 for segment in path {
248 match segment {
249 JsonPathSegment::Key(k) => {
250 out.push('.');
251 out.push_str(k);
252 }
253 JsonPathSegment::Index(i) => out.push_str(&format!("[{i}]")),
254 }
255 }
256 out
257}