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(deny_unknown_fields)]
44pub struct FromClause {
45    /// The table name as it appears in the schema snapshot.
46    pub table: String,
47    /// Optional alias (`AS <alias>`).
48    pub alias: Option<String>,
49}
50
51/// A join between the current relation and another table.
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
53#[serde(deny_unknown_fields)]
54pub struct JoinClause {
55    /// The kind of join to emit.
56    pub join_type: JoinType,
57    /// The right-hand side of the join (table + optional alias).
58    pub right_table: FromClause,
59    /// The boolean expression that decides which rows match.
60    /// `CROSS JOIN` is the only join type that ignores this field.
61    pub on: Predicate,
62}
63
64/// An expression and its requested sort direction.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
66#[serde(deny_unknown_fields)]
67pub struct OrderByTerm {
68    /// The expression whose value determines the ordering.
69    pub expr: Expression,
70    /// `true` to sort in descending order, `false` for ascending.
71    pub descending: bool,
72}
73
74/// A named common table expression.
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
76#[serde(deny_unknown_fields)]
77pub struct CommonTableExpression {
78    /// The CTE name exposed to the outer query.
79    pub name: String,
80    /// Whether this CTE is recursive (`WITH RECURSIVE`).
81    #[serde(default)]
82    pub recursive: bool,
83    /// The query that produces the CTE's rows.
84    pub query: Box<QueryPlan>,
85}
86
87/// The type of set operation between two queries.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
89#[serde(rename_all = "snake_case")]
90pub enum SetOperation {
91    /// `UNION ALL` — concatenate results (no dedup).
92    UnionAll,
93    /// `UNION` — concatenate and deduplicate results.
94    Union,
95    /// `INTERSECT` — keep rows present in both results.
96    Intersect,
97    /// `EXCEPT` — keep rows present in the first result but not the second.
98    Except,
99}
100
101/// A set operation (UNION / INTERSECT / EXCEPT) that combines this query with another.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
103#[serde(deny_unknown_fields)]
104pub struct SetOperationClause {
105    /// The set operation type.
106    pub operation: SetOperation,
107    /// The right-hand side query plan.
108    pub right: Box<QueryPlan>,
109}
110
111/// A complete structured query plan.
112///
113/// The plan is what the LLM is expected to emit (as JSON) and what
114/// the validator and SQL compiler consume. The serde annotations
115/// turn the plan into a self-describing JSON object with
116/// `snake_case` field names, omit `None` pagination values, and
117/// reject unknown keys (so the LLM cannot smuggle in extra fields).
118///
119/// # Examples
120///
121/// ```
122/// use vlorql_core::schema::{QueryPlan, Projection, FromClause, Expression, Predicate, DataType, ComparisonOperator};
123///
124/// let plan = QueryPlan {
125///     select: vec![Projection::Column {
126///         table: Some("users".to_owned()),
127///         column: "id".to_owned(),
128///         alias: None,
129///     }],
130///     from: FromClause { table: "users".to_owned(), alias: None },
131///     r#where: Some(Predicate::Comparison {
132///         left: Expression::ColumnRef {
133///             table: Some("users".to_owned()),
134///             column: "id".to_owned(),
135///         },
136///         op: ComparisonOperator::Gt,
137///         right: Expression::Literal {
138///             value: serde_json::json!(10),
139///             data_type: DataType::Int,
140///         },
141///     }),
142///     group_by: None,
143///     having: None,
144///     order_by: None,
145///     limit: None,
146///     offset: None,
147///     joins: None,
148///     ctes: None,
149///     distinct: false,
150///     distinct_on: None,
151///     set_operation: None,
152/// };
153/// assert_eq!(plan.select.len(), 1);
154/// assert!(plan.r#where.is_some());
155/// ```
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
157#[serde(deny_unknown_fields)]
158pub struct QueryPlan {
159    /// The projection list.
160    pub select: Vec<Projection>,
161    /// Whether to emit `SELECT DISTINCT` (de-duplicate rows across the entire result).
162    #[serde(default)]
163    pub distinct: bool,
164    /// PostgreSQL `SELECT DISTINCT ON (exprs)` — only effective when `distinct` is true.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub distinct_on: Option<Vec<Expression>>,
167    /// The primary source table.
168    pub from: FromClause,
169    /// Optional `WHERE` predicate.
170    #[serde(default)]
171    pub r#where: Option<Predicate>,
172    /// Optional `GROUP BY` expressions.
173    #[serde(default)]
174    pub group_by: Option<Vec<Expression>>,
175    /// Optional `HAVING` predicate.
176    #[serde(default)]
177    pub having: Option<Predicate>,
178    /// Optional `ORDER BY` terms.
179    #[serde(default)]
180    pub order_by: Option<Vec<OrderByTerm>>,
181    /// Optional `LIMIT` clause (the maximum number of rows to return).
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub limit: Option<u64>,
184    /// Optional `OFFSET` clause (the number of rows to skip).
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub offset: Option<u64>,
187    /// Optional list of joins applied after `from`.
188    #[serde(default)]
189    pub joins: Option<Vec<JoinClause>>,
190    /// Optional list of `WITH` CTEs.
191    #[serde(default)]
192    pub ctes: Option<Vec<CommonTableExpression>>,
193    /// Optional set operation combining this query with another (e.g. `UNION ALL`, `INTERSECT`).
194    /// When set, the current query is the left-hand side and the operation/right describe the
195    /// right-hand side.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub set_operation: Option<SetOperationClause>,
198}