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    Column {
17        /// Source-table qualifier, if the column reference should be
18        /// qualified in the rendered SQL.
19        table: Option<String>,
20        /// The column name as it appears in the schema.
21        column: String,
22        /// Optional alias (`AS <alias>`).
23        alias: Option<String>,
24    },
25    /// Select a computed expression.
26    Expr {
27        /// The expression to render.
28        expression: Expression,
29        /// Optional alias (`AS <alias>`).
30        alias: Option<String>,
31    },
32    /// Select all columns from an optional table qualifier.
33    Star {
34        /// When `Some(table)`, render as `<table>.*`; when `None`,
35        /// render as a bare `*`.
36        table: Option<String>,
37    },
38}
39
40/// The source table for a query or join.
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
42#[serde(deny_unknown_fields)]
43pub struct FromClause {
44    /// The table name as it appears in the schema snapshot.
45    pub table: String,
46    /// Optional alias (`AS <alias>`).
47    pub alias: Option<String>,
48}
49
50/// A join between the current relation and another table.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
52#[serde(deny_unknown_fields)]
53pub struct JoinClause {
54    /// The kind of join to emit.
55    pub join_type: JoinType,
56    /// The right-hand side of the join (table + optional alias).
57    pub right_table: FromClause,
58    /// The boolean expression that decides which rows match.
59    /// `CROSS JOIN` is the only join type that ignores this field.
60    pub on: Predicate,
61}
62
63/// An expression and its requested sort direction.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
65#[serde(deny_unknown_fields)]
66pub struct OrderByTerm {
67    /// The expression whose value determines the ordering.
68    pub expr: Expression,
69    /// `true` to sort in descending order, `false` for ascending.
70    pub descending: bool,
71}
72
73/// A named common table expression.
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
75#[serde(deny_unknown_fields)]
76pub struct CommonTableExpression {
77    /// The CTE name exposed to the outer query.
78    pub name: String,
79    /// The query that produces the CTE's rows.
80    pub query: Box<QueryPlan>,
81}
82
83/// A complete structured query plan.
84///
85/// The plan is what the LLM is expected to emit (as JSON) and what
86/// the validator and SQL compiler consume. The serde annotations
87/// turn the plan into a self-describing JSON object with
88/// `snake_case` field names, omit `None` pagination values, and
89/// reject unknown keys (so the LLM cannot smuggle in extra fields).
90///
91/// # Examples
92///
93/// ```
94/// use vlorql_core::schema::{QueryPlan, Projection, FromClause, Expression, Predicate, DataType, ComparisonOperator};
95///
96/// let plan = QueryPlan {
97///     select: vec![Projection::Column {
98///         table: Some("users".to_owned()),
99///         column: "id".to_owned(),
100///         alias: None,
101///     }],
102///     from: FromClause { table: "users".to_owned(), alias: None },
103///     r#where: Some(Predicate::Comparison {
104///         left: Expression::ColumnRef {
105///             table: Some("users".to_owned()),
106///             column: "id".to_owned(),
107///         },
108///         op: ComparisonOperator::Gt,
109///         right: Expression::Literal {
110///             value: serde_json::json!(10),
111///             data_type: DataType::Int,
112///         },
113///     }),
114///     group_by: None,
115///     having: None,
116///     order_by: None,
117///     limit: None,
118///     offset: None,
119///     joins: None,
120///     ctes: None,
121/// };
122/// assert_eq!(plan.select.len(), 1);
123/// assert!(plan.r#where.is_some());
124/// ```
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
126#[serde(deny_unknown_fields)]
127pub struct QueryPlan {
128    /// The projection list.
129    pub select: Vec<Projection>,
130    /// The primary source table.
131    pub from: FromClause,
132    /// Optional `WHERE` predicate.
133    #[serde(default)]
134    pub r#where: Option<Predicate>,
135    /// Optional `GROUP BY` expressions.
136    #[serde(default)]
137    pub group_by: Option<Vec<Expression>>,
138    /// Optional `HAVING` predicate.
139    #[serde(default)]
140    pub having: Option<Predicate>,
141    /// Optional `ORDER BY` terms.
142    #[serde(default)]
143    pub order_by: Option<Vec<OrderByTerm>>,
144    /// Optional `LIMIT` clause (the maximum number of rows to return).
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub limit: Option<u64>,
147    /// Optional `OFFSET` clause (the number of rows to skip).
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub offset: Option<u64>,
150    /// Optional list of joins applied after `from`.
151    #[serde(default)]
152    pub joins: Option<Vec<JoinClause>>,
153    /// Optional list of `WITH` CTEs.
154    #[serde(default)]
155    pub ctes: Option<Vec<CommonTableExpression>>,
156}