vlorql_core/schema/expressions.rs
1//! Tagged expressions and predicates used in query plans.
2//!
3//! Both [`Expression`] and [`Predicate`] are serialized as
4//! internally-tagged JSON enums (`{"type": "...", ...}`). The
5//! validators and the SQL compiler inspect the tag to decide how to
6//! type-check or render the node.
7
8use super::query_plan::{OrderByTerm, QueryPlan};
9use super::types::{BinaryOperator, ComparisonOperator, DataType};
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13/// An expression that can be selected, filtered, grouped, or ordered.
14///
15/// The enum is serialized with `#[serde(tag = "type", rename_all = "snake_case")]`,
16/// so a literal payload looks like
17/// `{"type": "literal", "value": 42, "data_type": "int"}` and a column
18/// reference looks like
19/// `{"type": "column_ref", "table": "users", "column": "id"}`.
20///
21/// # Examples
22///
23/// ```
24/// use vlorql_core::schema::{Expression, DataType};
25///
26/// let lit = Expression::Literal {
27/// value: serde_json::json!(42),
28/// data_type: DataType::Int,
29/// };
30/// let col = Expression::ColumnRef {
31/// table: Some("users".to_owned()),
32/// column: "id".to_owned(),
33/// };
34/// assert_ne!(lit, col);
35/// ```
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
38pub enum Expression {
39 /// A literal value together with its SQL type.
40 Literal {
41 /// The literal value as a JSON-compatible scalar (string,
42 /// number, boolean, or `null`).
43 value: serde_json::Value,
44 /// The declared SQL type of the literal.
45 data_type: DataType,
46 },
47 /// A reference to a column, optionally qualified by a table.
48 ColumnRef {
49 /// Source-table qualifier (may be `None` for an unqualified
50 /// reference, in which case the validator resolves it
51 /// against the plan's `from` and joined tables).
52 table: Option<String>,
53 /// The column name as it appears in the schema.
54 column: String,
55 },
56 /// A scalar or aggregate function call.
57 FunctionCall {
58 /// Function name as emitted to the SQL backend (case is
59 /// preserved).
60 name: String,
61 /// Arguments passed positionally to the function.
62 args: Vec<Expression>,
63 /// When `true`, the call is rendered as `DISTINCT` (subject
64 /// to the dialect profile's `allow_distinct` setting).
65 distinct: bool,
66 },
67 /// A binary operation between two expressions.
68 BinaryOp {
69 /// Left-hand operand.
70 left: Box<Expression>,
71 /// The operator to apply.
72 op: BinaryOperator,
73 /// Right-hand operand.
74 right: Box<Expression>,
75 },
76 /// A literal `*` (asterisk) used inside aggregate function calls
77 /// such as `COUNT(*)` or `COUNT(DISTINCT *)`.
78 Star,
79 /// A scalar subquery expression.
80 SubQuery {
81 /// The inner query plan.
82 query: Box<QueryPlan>,
83 },
84 /// A `CASE WHEN ... THEN ... ELSE ... END` expression.
85 Case {
86 /// Optional base expression for `CASE expr WHEN ... THEN ...` shorthand.
87 operand: Option<Box<Expression>>,
88 /// The list of `WHEN`/`THEN` pairs.
89 when_thens: Vec<WhenThen>,
90 /// Optional `ELSE` result expression.
91 else_result: Option<Box<Expression>>,
92 },
93 /// A window function call with an OVER clause, e.g. `ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)`.
94 /// The `name` and `args` fields work identically to [`FunctionCall`], but the result is
95 /// computed over a window frame rather than grouped rows.
96 WindowFunction {
97 /// Function name (e.g. `"row_number"`, `"lag"`, `"sum"`).
98 name: String,
99 /// Arguments passed positionally to the function.
100 args: Vec<Expression>,
101 /// When `true`, the call is rendered as `DISTINCT`.
102 distinct: bool,
103 /// The window specification (PARTITION BY, ORDER BY, frame).
104 over: WindowSpec,
105 },
106}
107
108/// A single `WHEN ... THEN ...` branch inside a `CASE` expression.
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
110#[serde(deny_unknown_fields)]
111pub struct WhenThen {
112 /// The boolean condition.
113 pub when: Expression,
114 /// The result expression when the condition evaluates to true.
115 pub then: Expression,
116}
117
118/// The window specification for a window function (`OVER (PARTITION BY ... ORDER BY ...)`).
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
120#[serde(deny_unknown_fields)]
121pub struct WindowSpec {
122 /// Columns to partition the window by (optional).
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub partition_by: Option<Vec<Expression>>,
125 /// Ordering of rows within each partition (optional).
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub order_by: Option<Vec<OrderByTerm>>,
128 /// Optional window frame clause (`ROWS` / `RANGE` / `GROUPS`).
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub frame: Option<WindowFrame>,
131}
132
133/// The frame clause of a window specification.
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
135#[serde(deny_unknown_fields)]
136pub struct WindowFrame {
137 /// The frame type: `ROWS`, `RANGE`, or `GROUPS`.
138 pub kind: WindowFrameKind,
139 /// The start bound of the frame.
140 pub start: WindowFrameBound,
141 /// The end bound of the frame (defaults to `CURRENT ROW` when `None`).
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub end: Option<WindowFrameBound>,
144}
145
146/// The kind of window frame.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
148#[serde(rename_all = "snake_case")]
149pub enum WindowFrameKind {
150 /// `ROWS` — frame is defined by physical row offsets.
151 Rows,
152 /// `RANGE` — frame is defined by logical value ranges.
153 Range,
154 /// `GROUPS` — frame is defined by groups of peers.
155 Groups,
156}
157
158/// A bound in a window frame clause.
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
160#[serde(rename_all = "snake_case")]
161pub enum WindowFrameBound {
162 /// `UNBOUNDED PRECEDING`.
163 UnboundedPreceding,
164 /// `<n> PRECEDING`.
165 Preceding(Box<Expression>),
166 /// `CURRENT ROW`.
167 CurrentRow,
168 /// `<n> FOLLOWING`.
169 Following(Box<Expression>),
170 /// `UNBOUNDED FOLLOWING`.
171 UnboundedFollowing,
172}
173
174/// The target of an `IN` predicate: either a list of literal values
175/// or a subquery.
176#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
177#[serde(untagged)]
178pub enum InTarget {
179 /// A list of literal expressions.
180 Values(Vec<Expression>),
181 /// A subquery.
182 SubQuery(Box<QueryPlan>),
183}
184
185/// A boolean condition used by `WHERE`, `HAVING`, and join clauses.
186///
187/// Like [`Expression`], this is serialized with an internal `type`
188/// tag. The `In` and `Between` variants are the only way to express
189/// list membership and range checks; the bare comparison operators
190/// of the same name are reserved for the dedicated predicate shapes.
191///
192/// # Examples
193///
194/// ```
195/// use vlorql_core::schema::{Predicate, Expression, ComparisonOperator, DataType};
196///
197/// let pred = Predicate::Comparison {
198/// left: Expression::ColumnRef {
199/// table: Some("users".to_owned()),
200/// column: "age".to_owned(),
201/// },
202/// op: ComparisonOperator::Gte,
203/// right: Expression::Literal {
204/// value: serde_json::json!(18),
205/// data_type: DataType::Int,
206/// },
207/// };
208/// assert!(matches!(pred, Predicate::Comparison { .. }));
209/// ```
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
211#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
212pub enum Predicate {
213 /// A comparison between two expressions.
214 Comparison {
215 /// Left-hand operand.
216 left: Expression,
217 /// The comparison operator.
218 op: ComparisonOperator,
219 /// Right-hand operand.
220 right: Expression,
221 },
222 /// The conjunction of two predicates.
223 And {
224 /// Left sub-predicate.
225 left: Box<Predicate>,
226 /// Right sub-predicate.
227 right: Box<Predicate>,
228 },
229 /// The disjunction of two predicates.
230 Or {
231 /// Left sub-predicate.
232 left: Box<Predicate>,
233 /// Right sub-predicate.
234 right: Box<Predicate>,
235 },
236 /// The negation of a predicate.
237 Not {
238 /// The predicate to negate.
239 child: Box<Predicate>,
240 },
241 /// A value constrained to an inclusive range.
242 Between {
243 /// The value being tested.
244 expr: Expression,
245 /// Inclusive lower bound.
246 low: Expression,
247 /// Inclusive upper bound.
248 high: Expression,
249 },
250 /// A value constrained to a list of expressions or a subquery.
251 In {
252 /// The value being tested.
253 expr: Expression,
254 /// Allowed values or a subquery.
255 target: InTarget,
256 },
257 /// A string pattern match.
258 Like {
259 /// The value being tested.
260 expr: Expression,
261 /// Pattern string (using `LIKE`/`ILIKE` wildcards).
262 pattern: String,
263 },
264 /// A null check.
265 IsNull {
266 /// The value being tested.
267 expr: Expression,
268 },
269 /// Tests whether a subquery returns any rows.
270 Exists {
271 /// The subquery to check.
272 query: Box<QueryPlan>,
273 },
274}