Skip to main content

vlorql_core/schema/
query_plan.rs

1//! The structured query plan emitted by an LLM.
2
3use super::expressions::{Expression, Predicate};
4use super::types::JoinType;
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8/// A projection in the `SELECT` list.
9///
10/// Every variant is rendered as a single column expression in the
11/// compiled SQL, optionally paired with an `AS <alias>`.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
13#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
14pub enum Projection {
15    /// Select one named column.
16    #[serde(rename = "column_ref")]
17    Column {
18        /// Source-table qualifier, if the column reference should be
19        /// qualified in the rendered SQL.
20        table: Option<String>,
21        /// The column name as it appears in the schema.
22        column: String,
23        /// Optional alias (`AS <alias>`).
24        alias: Option<String>,
25    },
26    /// Select a computed expression.
27    Expr {
28        /// The expression to render.
29        expression: Expression,
30        /// Optional alias (`AS <alias>`).
31        alias: Option<String>,
32    },
33    /// Select all columns from an optional table qualifier.
34    Star {
35        /// When `Some(table)`, render as `<table>.*`; when `None`,
36        /// render as a bare `*`.
37        table: Option<String>,
38    },
39}
40
41/// The source table for a query or join.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
43#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
44pub enum FromClause {
45    /// A named table reference.
46    Table {
47        /// The table name as it appears in the schema snapshot.
48        table: String,
49        /// Optional alias (`AS <alias>`).
50        alias: Option<String>,
51    },
52    /// A subquery reference.
53    Subquery {
54        /// The subquery plan.
55        query: Box<QueryPlan>,
56        /// Optional alias (`AS <alias>`).
57        alias: Option<String>,
58    },
59}
60
61impl FromClause {
62    /// Create a `Table` variant.
63    #[must_use]
64    pub fn table(name: impl Into<String>, alias: Option<String>) -> Self {
65        Self::Table {
66            table: name.into(),
67            alias,
68        }
69    }
70
71    /// Return the table name if this is a `Table` variant.
72    #[must_use]
73    pub fn table_name(&self) -> Option<&str> {
74        match self {
75            Self::Table { table, .. } => Some(table.as_str()),
76            Self::Subquery { .. } => None,
77        }
78    }
79
80    /// Return the alias, if any, regardless of variant.
81    #[must_use]
82    pub fn alias(&self) -> Option<String> {
83        match self {
84            Self::Table { alias, .. } | Self::Subquery { alias, .. } => alias.clone(),
85        }
86    }
87}
88
89/// A join between the current relation and another table.
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
91#[serde(deny_unknown_fields)]
92pub struct JoinClause {
93    /// The kind of join to emit.
94    pub join_type: JoinType,
95    /// The right-hand side of the join (table + optional alias).
96    pub right_table: FromClause,
97    /// The boolean expression that decides which rows match.
98    /// `CROSS JOIN` is the only join type that ignores this field.
99    pub on: Predicate,
100}
101
102/// An expression and its requested sort direction.
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
104#[serde(deny_unknown_fields)]
105pub struct OrderByTerm {
106    /// The expression whose value determines the ordering.
107    pub expr: Expression,
108    /// `true` to sort in descending order, `false` for ascending.
109    pub descending: bool,
110}
111
112/// A named common table expression.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
114#[serde(deny_unknown_fields)]
115pub struct CommonTableExpression {
116    /// The CTE name exposed to the outer query.
117    pub name: String,
118    /// Whether this CTE is recursive (`WITH RECURSIVE`).
119    #[serde(default)]
120    pub recursive: bool,
121    /// The query that produces the CTE's rows.
122    pub query: Box<QueryPlan>,
123}
124
125/// The type of set operation between two queries.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
127#[serde(rename_all = "snake_case")]
128pub enum SetOperation {
129    /// `UNION ALL` — concatenate results (no dedup).
130    UnionAll,
131    /// `UNION` — concatenate and deduplicate results.
132    Union,
133    /// `INTERSECT` — keep rows present in both results.
134    Intersect,
135    /// `EXCEPT` — keep rows present in the first result but not the second.
136    Except,
137}
138
139/// A set operation (UNION / INTERSECT / EXCEPT) that combines this query with another.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
141#[serde(deny_unknown_fields)]
142pub struct SetOperationClause {
143    /// The set operation type.
144    pub operation: SetOperation,
145    /// The right-hand side query plan.
146    pub right: Box<QueryPlan>,
147}
148
149/// A complete structured query plan.
150///
151/// The plan is what the LLM is expected to emit (as JSON) and what
152/// the validator and SQL compiler consume. The serde annotations
153/// turn the plan into a self-describing JSON object with
154/// `snake_case` field names, omit `None` pagination values, and
155/// reject unknown keys (so the LLM cannot smuggle in extra fields).
156///
157/// # Examples
158///
159/// ```
160/// use vlorql_core::schema::{QueryPlan, Projection, FromClause, Expression, Predicate, DataType, ComparisonOperator};
161///
162/// let plan = QueryPlan {
163///     select: vec![Projection::Column {
164///         table: Some("users".to_owned()),
165///         column: "id".to_owned(),
166///         alias: None,
167///     }],
168///     from: FromClause::table("users".to_owned(), None),
169///     r#where: Some(Predicate::Comparison {
170///         left: Box::new(Expression::ColumnRef {
171///             table: Some("users".to_owned()),
172///             column: "id".to_owned(),
173///         }),
174///         op: ComparisonOperator::Gt,
175///         right: Box::new(Expression::Literal {
176///             value: serde_json::json!(10),
177///             data_type: DataType::Int,
178///         }),
179///     }),
180///     group_by: None,
181///     having: None,
182///     order_by: None,
183///     limit: None,
184///     offset: None,
185///     joins: None,
186///     ctes: None,
187///     distinct: false,
188///     distinct_on: None,
189///     set_operation: None,
190/// };
191/// assert_eq!(plan.select.len(), 1);
192/// assert!(plan.r#where.is_some());
193/// ```
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
195#[serde(deny_unknown_fields)]
196pub struct QueryPlan {
197    /// The projection list.
198    pub select: Vec<Projection>,
199    /// Whether to emit `SELECT DISTINCT` (de-duplicate rows across the entire result).
200    #[serde(default)]
201    pub distinct: bool,
202    /// PostgreSQL `SELECT DISTINCT ON (exprs)` — only effective when `distinct` is true.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub distinct_on: Option<Vec<Expression>>,
205    /// The primary source table.
206    pub from: FromClause,
207    /// Optional `WHERE` predicate.
208    #[serde(default)]
209    pub r#where: Option<Predicate>,
210    /// Optional `GROUP BY` expressions.
211    #[serde(default)]
212    pub group_by: Option<Vec<Expression>>,
213    /// Optional `HAVING` predicate.
214    #[serde(default)]
215    pub having: Option<Predicate>,
216    /// Optional `ORDER BY` terms.
217    #[serde(default)]
218    pub order_by: Option<Vec<OrderByTerm>>,
219    /// Optional `LIMIT` clause (the maximum number of rows to return).
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub limit: Option<u64>,
222    /// Optional `OFFSET` clause (the number of rows to skip).
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub offset: Option<u64>,
225    /// Optional list of joins applied after `from`.
226    #[serde(default)]
227    pub joins: Option<Vec<JoinClause>>,
228    /// Optional list of `WITH` CTEs.
229    #[serde(default)]
230    pub ctes: Option<Vec<CommonTableExpression>>,
231    /// Optional set operation combining this query with another (e.g. `UNION ALL`, `INTERSECT`).
232    /// When set, the current query is the left-hand side and the operation/right describe the
233    /// right-hand side.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub set_operation: Option<SetOperationClause>,
236}