Skip to main content

rust_ef/query/
state.rs

1//! `QueryState` — accumulator for a single query's intent.
2//!
3//! Holds filter conditions, JOINs, GROUP BY, HAVING, ORDER BY, pagination,
4//! includes, projections, window functions, CTEs, and set operations.
5//! `to_sql_with` compiles the state into a SQL string using the provider's
6//! placeholder syntax; `all_params` returns the bound parameter vector in
7//! the order expected by the generated SQL (CTE params first, then WHERE/
8//! HAVING, then set operation operand params).
9
10use crate::provider::DbValue;
11
12use super::ast::{BoolExpr, FilterCondition, HavingExpr, IncludePath, JoinSpec, OrderBy};
13use super::compile::{build_where_clauses, compile_bool_expr, PortablePlaceholderGenerator};
14use super::cte::{CteSpec, SetOpSpec, SetOperator};
15use super::window::WindowSpec;
16
17/// Accumulated intent for a single query.
18#[derive(Debug, Clone)]
19pub struct QueryState {
20    /// FROM table / subquery segment.
21    pub from: String,
22    /// WHERE clause conditions.
23    pub filters: Vec<FilterCondition>,
24    /// JOIN specifications.
25    pub joins: Vec<JoinSpec>,
26    /// GROUP BY columns.
27    pub group_bys: Vec<String>,
28    /// HAVING conditions stored as AST nodes so they can be compiled with the
29    /// provider-specific placeholder syntax (`?` vs `$N`) at SQL generation
30    /// time, rather than being pre-compiled to a fixed placeholder.
31    pub havings: Vec<HavingExpr>,
32    /// ORDER BY clauses.
33    pub orderings: Vec<OrderBy>,
34    /// OFFSET (Skip).
35    pub offset: Option<usize>,
36    /// LIMIT (Take).
37    pub limit: Option<usize>,
38    /// Include navigation paths.
39    pub includes: Vec<IncludePath>,
40    /// Whether this is a projection (SELECT col1, col2 instead of SELECT *).
41    pub projected_columns: Option<Vec<String>>,
42    /// Whether this is a COUNT query.
43    pub is_count: bool,
44    /// Whether this is an EXISTS sub-query.
45    pub is_exists: bool,
46    /// Aggregate function to apply: "SUM", "AVG", "MIN", "MAX", "COUNT"
47    pub aggregate: Option<String>,
48    /// The column to aggregate.
49    pub aggregate_column: Option<String>,
50    /// Collected parameter values in order of appearance.
51    pub parameters: Vec<DbValue>,
52    /// Boolean WHERE expression (preferred over `filters`).
53    pub where_expr: Option<BoolExpr>,
54    /// Whether to emit `SELECT DISTINCT`.
55    pub distinct: bool,
56    /// Window function projections (v1.1). Emitted in the SELECT list as
57    /// `func(col) OVER (PARTITION BY ... ORDER BY ...) AS alias`.
58    pub windows: Vec<WindowSpec>,
59    /// CTE definitions (v1.1). Emitted as `WITH name AS (...)` prefix
60    /// before the SELECT. CTE parameters are prepended to the query's
61    /// parameter list at execution time.
62    pub ctes: Vec<CteSpec>,
63    /// Set operations (UNION / INTERSECT / EXCEPT) appended after the main
64    /// SELECT. Multiple operations chain left-to-right.
65    pub set_operations: Vec<SetOpSpec>,
66}
67
68impl QueryState {
69    pub fn new(from: impl Into<String>) -> Self {
70        Self {
71            from: from.into(),
72            filters: Vec::new(),
73            joins: Vec::new(),
74            group_bys: Vec::new(),
75            havings: Vec::new(),
76            orderings: Vec::new(),
77            offset: None,
78            limit: None,
79            includes: Vec::new(),
80            projected_columns: None,
81            is_count: false,
82            is_exists: false,
83            aggregate: None,
84            aggregate_column: None,
85            parameters: Vec::new(),
86            where_expr: None,
87            distinct: false,
88            windows: Vec::new(),
89            ctes: Vec::new(),
90            set_operations: Vec::new(),
91        }
92    }
93
94    pub(crate) fn append_bool_expr(&mut self, expr: BoolExpr) {
95        self.where_expr = Some(match self.where_expr.take() {
96            None => expr,
97            Some(existing) => BoolExpr::And(Box::new(existing), Box::new(expr)),
98        });
99    }
100
101    pub(crate) fn append_filter(&mut self, condition: FilterCondition) {
102        self.filters.push(condition.clone());
103        self.append_bool_expr(BoolExpr::Filter(condition));
104    }
105
106    /// Compile the state into a SQL string using the provider's placeholder style.
107    pub fn to_sql_with(&self, gen: &dyn crate::provider::ISqlGenerator) -> String {
108        // CTE parameter count — the main query's PostgreSQL `$N` placeholders
109        // must continue from this offset to stay contiguous with CTE params.
110        let cte_param_count: usize = self.ctes.iter().map(|c| c.params.len()).sum();
111
112        let distinct_kw = if self.distinct { "DISTINCT " } else { "" };
113        let select = if self.is_count {
114            if self.distinct {
115                "SELECT COUNT(DISTINCT *)".to_string()
116            } else {
117                "SELECT COUNT(*)".to_string()
118            }
119        } else if self.is_exists {
120            "SELECT 1".to_string()
121        } else if let Some(ref agg) = self.aggregate {
122            let col = self.aggregate_column.as_deref().unwrap_or("*");
123            if self.distinct {
124                format!("SELECT {}(DISTINCT {})", agg, col)
125            } else {
126                format!("SELECT {}({})", agg, col)
127            }
128        } else if let Some(ref cols) = self.projected_columns {
129            let mut parts: Vec<String> = cols.to_vec();
130            // Window function projections are appended to explicit column lists.
131            for w in &self.windows {
132                parts.push(w.to_sql(gen));
133            }
134            format!("SELECT {}{}", distinct_kw, parts.join(", "))
135        } else {
136            // Default SELECT * — append window projections if present.
137            if self.windows.is_empty() {
138                format!("SELECT {}*", distinct_kw)
139            } else {
140                let mut parts: Vec<String> = vec![format!("{}*", distinct_kw)];
141                for w in &self.windows {
142                    parts.push(w.to_sql(gen));
143                }
144                format!("SELECT {}", parts.join(", "))
145            }
146        };
147
148        let mut sql = format!("{} FROM {}", select, self.from);
149
150        // JOINs
151        for join in &self.joins {
152            sql.push_str(&format!(" {}", join.to_sql()));
153        }
154
155        // Parameter index is shared across WHERE and HAVING so that
156        // PostgreSQL's 1-indexed `$N` placeholders remain contiguous and
157        // correctly ordered across both clauses. CTE parameters (if any)
158        // occupy the leading slots, so the main query starts after them.
159        let mut param_idx = 1usize + cte_param_count;
160
161        // WHERE
162        if let Some(ref expr) = self.where_expr {
163            sql.push_str(&format!(
164                " WHERE {}",
165                compile_bool_expr(expr, gen, &mut param_idx)
166            ));
167        } else if !self.filters.is_empty() {
168            sql.push_str(&format!(
169                " WHERE {}",
170                build_where_clauses(&self.filters, gen)
171            ));
172            // Advance `param_idx` past the legacy `filters` path so that
173            // HAVING placeholders (PostgreSQL `$N`) continue from the
174            // correct index. `build_where_clauses` always starts at index 1.
175            param_idx += self.filters.iter().map(|f| f.param_count()).sum::<usize>();
176        }
177
178        // GROUP BY
179        if !self.group_bys.is_empty() {
180            sql.push_str(&format!(" GROUP BY {}", self.group_bys.join(", ")));
181        }
182
183        // HAVING — compile each `HavingExpr` AST node with the provider's
184        // placeholder syntax, continuing the shared `param_idx` so PostgreSQL
185        // `$N` indices stay contiguous with the WHERE clause.
186        if !self.havings.is_empty() {
187            let compiled: Vec<String> = self
188                .havings
189                .iter()
190                .map(|h| h.to_sql(gen, &mut param_idx))
191                .collect();
192            sql.push_str(&format!(" HAVING {}", compiled.join(" AND ")));
193        }
194
195        // ORDER BY
196        if !self.orderings.is_empty() {
197            let ords: Vec<String> = self.orderings.iter().map(|o| o.to_sql()).collect();
198            sql.push_str(&format!(" ORDER BY {}", ords.join(", ")));
199        }
200
201        // LIMIT / OFFSET — delegated to the dialect-specific generator so
202        // that PostgreSQL emits `OFFSET x LIMIT y`, MySQL handles the
203        // offset-only case via `LIMIT 18446744073709551615 OFFSET y`, and
204        // SQLite/MySQL use `LIMIT x OFFSET y`.
205        let pagination = gen.pagination(self.offset, self.limit);
206        if !pagination.is_empty() {
207            sql.push(' ');
208            sql.push_str(&pagination);
209        }
210
211        // CTE prefix — emitted as `WITH name AS (body), ...` before the SELECT.
212        //
213        // Two modes:
214        // - **Raw mode** (`sql` non-empty): body is the pre-compiled SQL,
215        //   emitted verbatim with `?` placeholders.
216        // - **Typed mode** (`table` non-empty): body is compiled from
217        //   `where_expr` at this point using the provider's placeholder
218        //   syntax. Parameter values were already extracted into `params` at
219        //   construction time (see `with_cte_typed`), so `param_idx` for the
220        //   main query starts at `1 + cte_param_count` (computed above).
221        //
222        // `running_idx` accumulates across all CTEs so that PostgreSQL's
223        // 1-indexed `$N` placeholders stay contiguous across multiple typed
224        // CTEs and align with each CTE's slot in `all_params()`. Raw-mode
225        // CTEs advance `running_idx` by their param count for consistency,
226        // even though their `?` placeholders don't use the index.
227        if !self.ctes.is_empty() {
228            let mut running_idx = 1usize;
229            let mut cte_parts: Vec<String> = Vec::with_capacity(self.ctes.len());
230            let has_recursive = self.ctes.iter().any(|c| c.is_recursive);
231            for c in &self.ctes {
232                let body = if !c.table.is_empty() {
233                    // Typed mode: compile WHERE expression starting at the
234                    // running index. `cte_idx` advances as placeholders are
235                    // emitted; we then propagate it back to `running_idx`.
236                    let mut cte_idx = running_idx;
237                    let table = gen.quote_identifier(&c.table);
238                    let anchor = match &c.where_expr {
239                        Some(expr) => {
240                            let where_sql = compile_bool_expr(expr, gen, &mut cte_idx);
241                            format!("SELECT * FROM {} WHERE {}", table, where_sql)
242                        }
243                        None => format!("SELECT * FROM {}", table),
244                    };
245                    running_idx = cte_idx;
246                    if c.is_recursive {
247                        // Append recursive member:
248                        // SELECT t.* FROM <table> t JOIN <name> ON t.<fk> = <name>.<pk>
249                        let (fk, pk) = c
250                            .recursive_link
251                            .clone()
252                            .expect("recursive CTE must have recursive_link");
253                        let name = gen.quote_identifier(&c.name);
254                        let fk = gen.quote_identifier(&fk);
255                        let pk = gen.quote_identifier(&pk);
256                        format!(
257                            "{} UNION ALL SELECT t.* FROM {} t JOIN {} ON t.{} = {}.{}",
258                            anchor, table, name, fk, name, pk
259                        )
260                    } else {
261                        anchor
262                    }
263                } else {
264                    // Raw mode: pre-compiled SQL with `?` placeholders. The
265                    // index isn't consumed but advance for consistency with
266                    // `all_params()` ordering.
267                    running_idx = running_idx.saturating_add(c.params.len());
268                    c.sql.clone()
269                };
270
271                let part = if c.columns.is_empty() {
272                    format!("{} AS ({})", c.name, body)
273                } else {
274                    let cols = c
275                        .columns
276                        .iter()
277                        .map(|col| gen.quote_identifier(col))
278                        .collect::<Vec<_>>()
279                        .join(", ");
280                    format!("{} ({}) AS ({})", c.name, cols, body)
281                };
282                cte_parts.push(part);
283            }
284            let with_kw = if has_recursive {
285                "WITH RECURSIVE"
286            } else {
287                "WITH"
288            };
289            sql = format!("{} {} {}", with_kw, cte_parts.join(", "), sql);
290        }
291
292        // Set operations (UNION / INTERSECT / EXCEPT) — appended after the
293        // full SELECT (including CTE prefix). Operands are pre-compiled SQL
294        // strings; their params are appended in all_params() after the main
295        // query params. Per D5, operands should not contain ORDER BY / LIMIT.
296        for op in &self.set_operations {
297            let kw = match op.operator {
298                SetOperator::Union => " UNION ",
299                SetOperator::UnionAll => " UNION ALL ",
300                SetOperator::Intersect => " INTERSECT ",
301                SetOperator::Except => " EXCEPT ",
302            };
303            sql.push_str(kw);
304            sql.push_str(&op.operand_sql);
305        }
306
307        sql
308    }
309
310    /// Returns all parameter values for execution: CTE parameters first
311    /// (in declaration order), followed by WHERE/HAVING parameters, then
312    /// set operation operand params.
313    ///
314    /// This ordering matches the placeholder order in the generated SQL,
315    /// where CTE bodies appear before the main SELECT and set operations
316    /// appear after.
317    pub fn all_params(&self) -> Vec<DbValue> {
318        let mut params = Vec::new();
319        for cte in &self.ctes {
320            params.extend(cte.params.clone());
321        }
322        params.extend(self.parameters.clone());
323        for op in &self.set_operations {
324            params.extend(op.operand_params.clone());
325        }
326        params
327    }
328
329    /// Compile SQL with `?` placeholders (SQLite/MySQL style).
330    pub fn to_sql(&self) -> String {
331        self.to_sql_with(&PortablePlaceholderGenerator)
332    }
333
334    /// Returns the accumulated parameters.
335    pub fn params(&self) -> &[DbValue] {
336        &self.parameters
337    }
338}