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