Skip to main content

qail_core/ast/
operators.rs

1use serde::{Deserialize, Serialize};
2
3/// The action type (SQL operation).
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
5pub enum Action {
6    Get,
7    Cnt,
8    Set,
9    Del,
10    Add,
11    Gen,
12    Make,
13    Drop,
14    Mod,
15    Over,
16    With,
17    Index,
18    DropIndex,
19    Alter,
20    AlterDrop,
21    AlterType,
22    TxnStart,
23    TxnCommit,
24    TxnRollback,
25    Put,
26    DropCol,
27    RenameCol,
28    JsonTable,
29    Export,
30    Truncate,
31    Explain,
32    ExplainAnalyze,
33    Lock,
34    CreateMaterializedView,
35    RefreshMaterializedView,
36    DropMaterializedView,
37    Listen,
38    Notify,
39    Unlisten,
40    Savepoint,
41    ReleaseSavepoint,
42    RollbackToSavepoint,
43    CreateView,
44    DropView,
45    Search,
46    Upsert,
47    Scroll,
48    CreateCollection,
49    DeleteCollection,
50    CreateFunction,
51    DropFunction,
52    CreateTrigger,
53    DropTrigger,
54    RedisGet,
55    RedisSet,
56    RedisDel,
57    RedisIncr,
58    RedisDecr,
59    RedisTtl,
60    RedisExpire,
61    RedisExists,
62    RedisMGet,
63    RedisMSet,
64    RedisPing,
65    CreateExtension,
66    DropExtension,
67    CommentOn,
68    CreateSequence,
69    DropSequence,
70    CreateEnum,
71    DropEnum,
72    AlterEnumAddValue,
73}
74
75impl std::fmt::Display for Action {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Action::Get => write!(f, "GET"),
79            Action::Cnt => write!(f, "CNT"),
80            Action::Set => write!(f, "SET"),
81            Action::Del => write!(f, "DEL"),
82            Action::Add => write!(f, "ADD"),
83            Action::Gen => write!(f, "GEN"),
84            Action::Make => write!(f, "MAKE"),
85            Action::Drop => write!(f, "DROP"),
86            Action::Mod => write!(f, "MOD"),
87            Action::Over => write!(f, "OVER"),
88            Action::With => write!(f, "WITH"),
89            Action::Index => write!(f, "INDEX"),
90            Action::DropIndex => write!(f, "DROP_INDEX"),
91            Action::Alter => write!(f, "ALTER"),
92            Action::AlterDrop => write!(f, "ALTER_DROP"),
93            Action::AlterType => write!(f, "ALTER_TYPE"),
94            Action::TxnStart => write!(f, "TXN_START"),
95            Action::TxnCommit => write!(f, "TXN_COMMIT"),
96            Action::TxnRollback => write!(f, "TXN_ROLLBACK"),
97            Action::Put => write!(f, "PUT"),
98            Action::DropCol => write!(f, "DROP_COL"),
99            Action::RenameCol => write!(f, "RENAME_COL"),
100            Action::JsonTable => write!(f, "JSON_TABLE"),
101            Action::Export => write!(f, "EXPORT"),
102            Action::Truncate => write!(f, "TRUNCATE"),
103            Action::Explain => write!(f, "EXPLAIN"),
104            Action::ExplainAnalyze => write!(f, "EXPLAIN_ANALYZE"),
105            Action::Lock => write!(f, "LOCK"),
106            Action::CreateMaterializedView => write!(f, "CREATE_MATERIALIZED_VIEW"),
107            Action::RefreshMaterializedView => write!(f, "REFRESH_MATERIALIZED_VIEW"),
108            Action::DropMaterializedView => write!(f, "DROP_MATERIALIZED_VIEW"),
109            Action::Listen => write!(f, "LISTEN"),
110            Action::Notify => write!(f, "NOTIFY"),
111            Action::Unlisten => write!(f, "UNLISTEN"),
112            Action::Savepoint => write!(f, "SAVEPOINT"),
113            Action::ReleaseSavepoint => write!(f, "RELEASE_SAVEPOINT"),
114            Action::RollbackToSavepoint => write!(f, "ROLLBACK_TO_SAVEPOINT"),
115            Action::CreateView => write!(f, "CREATE_VIEW"),
116            Action::DropView => write!(f, "DROP_VIEW"),
117            Action::Search => write!(f, "SEARCH"),
118            Action::Upsert => write!(f, "UPSERT"),
119            Action::Scroll => write!(f, "SCROLL"),
120            Action::CreateCollection => write!(f, "CREATE_COLLECTION"),
121            Action::DeleteCollection => write!(f, "DELETE_COLLECTION"),
122            Action::CreateFunction => write!(f, "CREATE_FUNCTION"),
123            Action::DropFunction => write!(f, "DROP_FUNCTION"),
124            Action::CreateTrigger => write!(f, "CREATE_TRIGGER"),
125            Action::DropTrigger => write!(f, "DROP_TRIGGER"),
126            Action::RedisGet => write!(f, "REDIS_GET"),
127            Action::RedisSet => write!(f, "REDIS_SET"),
128            Action::RedisDel => write!(f, "REDIS_DEL"),
129            Action::RedisIncr => write!(f, "REDIS_INCR"),
130            Action::RedisDecr => write!(f, "REDIS_DECR"),
131            Action::RedisTtl => write!(f, "REDIS_TTL"),
132            Action::RedisExpire => write!(f, "REDIS_EXPIRE"),
133            Action::RedisExists => write!(f, "REDIS_EXISTS"),
134            Action::RedisMGet => write!(f, "REDIS_MGET"),
135            Action::RedisMSet => write!(f, "REDIS_MSET"),
136            Action::RedisPing => write!(f, "REDIS_PING"),
137            Action::CreateExtension => write!(f, "CREATE_EXTENSION"),
138            Action::DropExtension => write!(f, "DROP_EXTENSION"),
139            Action::CommentOn => write!(f, "COMMENT_ON"),
140            Action::CreateSequence => write!(f, "CREATE_SEQUENCE"),
141            Action::DropSequence => write!(f, "DROP_SEQUENCE"),
142            Action::CreateEnum => write!(f, "CREATE_ENUM"),
143            Action::DropEnum => write!(f, "DROP_ENUM"),
144            Action::AlterEnumAddValue => write!(f, "ALTER_ENUM_ADD_VALUE"),
145        }
146    }
147}
148
149/// Logical operator between conditions.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
151pub enum LogicalOp {
152    #[default]
153    And,
154    Or,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
158pub enum SortOrder {
159    Asc,
160    Desc,
161    AscNullsFirst,
162    AscNullsLast,
163    DescNullsFirst,
164    DescNullsLast,
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168pub enum Operator {
169    Eq,
170    Ne,
171    Gt,
172    Gte,
173    Lt,
174    Lte,
175    Fuzzy,
176    In,
177    NotIn,
178    IsNull,
179    IsNotNull,
180    Contains,
181    KeyExists,
182    JsonExists,
183    JsonQuery,
184    JsonValue,
185    Like,
186    NotLike,
187    ILike,
188    NotILike,
189    Between,
190    NotBetween,
191    Exists,
192    NotExists,
193    Regex,
194    RegexI,
195    SimilarTo,
196    ContainedBy,
197    Overlaps,
198}
199
200impl Operator {
201    /// For simple operators, returns the symbol directly.
202    /// For complex operators (BETWEEN, EXISTS), returns the keyword.
203    pub fn sql_symbol(&self) -> &'static str {
204        match self {
205            Operator::Eq => "=",
206            Operator::Ne => "!=",
207            Operator::Gt => ">",
208            Operator::Gte => ">=",
209            Operator::Lt => "<",
210            Operator::Lte => "<=",
211            Operator::Fuzzy => "ILIKE",
212            Operator::In => "IN",
213            Operator::NotIn => "NOT IN",
214            Operator::IsNull => "IS NULL",
215            Operator::IsNotNull => "IS NOT NULL",
216            Operator::Contains => "@>",
217            Operator::KeyExists => "?",
218            Operator::JsonExists => "JSON_EXISTS",
219            Operator::JsonQuery => "JSON_QUERY",
220            Operator::JsonValue => "JSON_VALUE",
221            Operator::Like => "LIKE",
222            Operator::NotLike => "NOT LIKE",
223            Operator::ILike => "ILIKE",
224            Operator::NotILike => "NOT ILIKE",
225            Operator::Between => "BETWEEN",
226            Operator::NotBetween => "NOT BETWEEN",
227            Operator::Exists => "EXISTS",
228            Operator::NotExists => "NOT EXISTS",
229            Operator::Regex => "~",
230            Operator::RegexI => "~*",
231            Operator::SimilarTo => "SIMILAR TO",
232            Operator::ContainedBy => "<@",
233            Operator::Overlaps => "&&",
234        }
235    }
236
237    /// IS NULL, IS NOT NULL, EXISTS, NOT EXISTS don't need values.
238    pub fn needs_value(&self) -> bool {
239        !matches!(
240            self,
241            Operator::IsNull | Operator::IsNotNull | Operator::Exists | Operator::NotExists
242        )
243    }
244
245    pub fn is_simple_binary(&self) -> bool {
246        matches!(
247            self,
248            Operator::Eq
249                | Operator::Ne
250                | Operator::Gt
251                | Operator::Gte
252                | Operator::Lt
253                | Operator::Lte
254                | Operator::Like
255                | Operator::NotLike
256                | Operator::ILike
257                | Operator::NotILike
258        )
259    }
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
263pub enum AggregateFunc {
264    Count,
265    Sum,
266    Avg,
267    Min,
268    Max,
269    ArrayAgg,
270    StringAgg,
271    JsonAgg,
272    JsonbAgg,
273    BoolAnd,
274    BoolOr,
275}
276
277impl std::fmt::Display for AggregateFunc {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        match self {
280            AggregateFunc::Count => write!(f, "COUNT"),
281            AggregateFunc::Sum => write!(f, "SUM"),
282            AggregateFunc::Avg => write!(f, "AVG"),
283            AggregateFunc::Min => write!(f, "MIN"),
284            AggregateFunc::Max => write!(f, "MAX"),
285            AggregateFunc::ArrayAgg => write!(f, "ARRAY_AGG"),
286            AggregateFunc::StringAgg => write!(f, "STRING_AGG"),
287            AggregateFunc::JsonAgg => write!(f, "JSON_AGG"),
288            AggregateFunc::JsonbAgg => write!(f, "JSONB_AGG"),
289            AggregateFunc::BoolAnd => write!(f, "BOOL_AND"),
290            AggregateFunc::BoolOr => write!(f, "BOOL_OR"),
291        }
292    }
293}
294
295/// Join Type
296#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
297pub enum JoinKind {
298    Inner,
299    Left,
300    Right,
301    Lateral,
302    Full,
303    Cross,
304}
305
306/// Set operation type for combining queries
307#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
308pub enum SetOp {
309    Union,
310    UnionAll,
311    Intersect,
312    Except,
313}
314
315#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
316pub enum ModKind {
317    Add,
318    Drop,
319}
320
321/// GROUP BY mode for advanced aggregations
322#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
323pub enum GroupByMode {
324    #[default]
325    Simple,
326    Rollup,
327    Cube,
328    GroupingSets(Vec<Vec<String>>),
329}
330
331impl GroupByMode {
332    /// Check if this is the default Simple mode (for serde skip)
333    pub fn is_simple(&self) -> bool {
334        matches!(self, GroupByMode::Simple)
335    }
336}
337
338/// Row locking mode for SELECT...FOR UPDATE/SHARE
339#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
340pub enum LockMode {
341    Update,
342    NoKeyUpdate,
343    Share,
344    KeyShare,
345}
346
347/// OVERRIDING clause for INSERT with GENERATED columns
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
349pub enum OverridingKind {
350    SystemValue,
351    UserValue,
352}
353
354/// TABLESAMPLE sampling method
355#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
356pub enum SampleMethod {
357    Bernoulli,
358    System,
359}
360
361/// Distance metric for vector similarity
362#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
363pub enum Distance {
364    #[default]
365    Cosine,
366    Euclid,
367    Dot,
368}