Skip to main content

toasty_core/
stmt.rs

1//! Statement AST types for Toasty's query compilation pipeline.
2//!
3//! This module defines the abstract syntax tree (AST) for statements that
4//! Toasty's query engine processes. The top-level type is [`Statement`], which
5//! represents one of four operations: [`Query`], [`Insert`], [`Update`], or
6//! [`Delete`].
7//!
8//! Statements exist at two layers:
9//!
10//! - **Model-level**: references models, fields, and associations from the app
11//!   schema. This is what user-facing code produces.
12//! - **Table-level**: references tables, columns, and joins from the DB schema.
13//!   This is what the query engine lowers model-level statements into before
14//!   handing them to a database driver.
15//!
16//! The query engine pipeline transforms statements through several phases:
17//! simplify, lower, plan, and execute. Types in this module appear throughout
18//! all phases.
19//!
20//! # Examples
21//!
22//! ```ignore
23//! use toasty_core::stmt::{Statement, Query, Values};
24//!
25//! // Create a simple values-based query statement
26//! let query = Query::unit();
27//! let stmt = Statement::Query(query);
28//! assert!(stmt.is_query());
29//! ```
30
31mod assignments;
32pub use assignments::{Assignment, Assignments};
33
34mod association;
35pub use association::Association;
36
37mod condition;
38pub use condition::Condition;
39
40mod cte;
41pub use cte::Cte;
42
43mod cx;
44pub use cx::{DerivedRef, ExprContext, ExprTarget, IntoExprTarget, Resolve, ResolvedRef};
45
46mod delete;
47pub use delete::Delete;
48
49mod direction;
50pub use direction::Direction;
51
52mod entry;
53pub use entry::Entry;
54
55mod entry_mut;
56pub use entry_mut::EntryMut;
57
58mod entry_path;
59pub use entry_path::EntryPath;
60
61mod eval;
62
63mod expr;
64pub use expr::Expr;
65
66mod expr_all_op;
67pub use expr_all_op::ExprAllOp;
68
69mod expr_and;
70pub use expr_and::ExprAnd;
71
72mod expr_between;
73pub use expr_between::ExprBetween;
74
75mod expr_any;
76pub use expr_any::ExprAny;
77
78mod expr_any_op;
79pub use expr_any_op::ExprAnyOp;
80
81mod expr_arg;
82pub use expr_arg::ExprArg;
83
84mod expr_binary_op;
85pub use expr_binary_op::ExprBinaryOp;
86
87mod expr_cast;
88pub use expr_cast::ExprCast;
89
90mod expr_error;
91pub use expr_error::ExprError;
92
93mod expr_exists;
94pub use expr_exists::ExprExists;
95
96mod expr_func;
97pub use expr_func::ExprFunc;
98
99mod expr_in_list;
100pub use expr_in_list::ExprInList;
101
102mod expr_in_subquery;
103pub use expr_in_subquery::ExprInSubquery;
104
105mod expr_intersects;
106pub use expr_intersects::ExprIntersects;
107
108mod expr_is_null;
109pub use expr_is_null::ExprIsNull;
110
111mod expr_is_superset;
112pub use expr_is_superset::ExprIsSuperset;
113
114mod expr_is_variant;
115pub use expr_is_variant::ExprIsVariant;
116
117mod expr_length;
118pub use expr_length::ExprLength;
119
120mod expr_let;
121pub use expr_let::ExprLet;
122
123mod expr_like;
124pub use expr_like::ExprLike;
125
126mod expr_list;
127pub use expr_list::ExprList;
128
129mod expr_map;
130pub use expr_map::ExprMap;
131
132mod expr_match;
133pub use expr_match::{ExprMatch, MatchArm};
134
135mod expr_not;
136pub use expr_not::ExprNot;
137
138mod expr_or;
139pub use expr_or::ExprOr;
140
141mod expr_project;
142pub use expr_project::ExprProject;
143
144mod expr_record;
145pub use expr_record::ExprRecord;
146
147mod expr_reference;
148pub use expr_reference::{ExprColumn, ExprReference};
149
150mod expr_set;
151pub use expr_set::ExprSet;
152
153mod expr_set_op;
154pub use expr_set_op::ExprSetOp;
155
156mod expr_starts_with;
157pub use expr_starts_with::ExprStartsWith;
158
159mod expr_stmt;
160pub use expr_stmt::ExprStmt;
161
162mod filter;
163pub use filter::Filter;
164
165mod hash_index;
166pub use hash_index::HashIndex;
167
168mod sorted_index;
169pub use sorted_index::SortedIndex;
170
171mod func_count;
172pub use func_count::FuncCount;
173
174mod func_last_insert_id;
175pub use func_last_insert_id::FuncLastInsertId;
176
177mod insert;
178pub use insert::Insert;
179
180mod insert_table;
181pub use insert_table::InsertTable;
182
183mod insert_target;
184pub use insert_target::InsertTarget;
185
186mod input;
187pub use input::{ConstInput, Input, TypedInput};
188
189mod join;
190pub use join::{Join, JoinOp};
191
192mod limit;
193pub use limit::{Limit, LimitCursor, LimitOffset};
194
195#[cfg(feature = "assert-struct")]
196mod like;
197
198mod node;
199pub use node::Node;
200
201mod num;
202
203mod op_binary;
204pub use op_binary::BinaryOp;
205
206mod order_by;
207pub use order_by::OrderBy;
208
209mod order_by_expr;
210pub use order_by_expr::OrderByExpr;
211
212mod op_set;
213pub use op_set::SetOp;
214
215mod path;
216pub use path::{Path, PathRoot};
217
218mod path_field_set;
219pub use path_field_set::PathFieldSet;
220
221mod projection;
222pub use projection::{Project, Projection};
223
224mod query;
225pub use query::{Lock, Query};
226
227mod returning;
228pub use returning::Returning;
229
230mod select;
231pub use select::Select;
232
233mod source;
234pub use source::{Source, SourceModel};
235
236mod source_table;
237pub use source_table::SourceTable;
238
239mod source_table_id;
240pub use source_table_id::SourceTableId;
241
242mod sparse_record;
243pub use sparse_record::SparseRecord;
244
245mod substitute;
246use substitute::Substitute;
247
248mod table_derived;
249pub use table_derived::TableDerived;
250
251mod table_ref;
252pub use table_ref::TableRef;
253
254mod table_factor;
255pub use table_factor::TableFactor;
256
257mod table_with_joins;
258pub use table_with_joins::TableWithJoins;
259
260mod ty;
261pub use ty::Type;
262
263mod ty_union;
264pub use ty_union::TypeUnion;
265
266#[cfg(feature = "jiff")]
267mod ty_jiff;
268
269mod update;
270pub use update::{Update, UpdateTarget};
271
272mod value;
273pub use value::Value;
274
275mod value_cmp;
276
277mod values;
278pub use values::Values;
279
280#[cfg(feature = "jiff")]
281mod value_jiff;
282
283mod value_record;
284pub use value_record::ValueRecord;
285
286mod value_set;
287pub use value_set::ValueSet;
288
289/// Mutable AST visitor trait and helpers.
290pub mod visit_mut;
291pub use visit_mut::VisitMut;
292
293mod value_list;
294
295mod value_stream;
296pub use value_stream::ValueStream;
297
298/// Read-only AST visitor trait and helpers.
299pub mod visit;
300pub use visit::Visit;
301
302mod with;
303pub use with::With;
304
305use crate::schema::db::TableId;
306use std::fmt;
307
308/// A top-level statement in Toasty's AST.
309///
310/// Each variant corresponds to one of the four fundamental database operations.
311/// A `Statement` is the primary input to the query engine's compilation
312/// pipeline and the output of code generated by `#[derive(Model)]`.
313///
314/// # Examples
315///
316/// ```ignore
317/// use toasty_core::stmt::{Statement, Query, Values};
318///
319/// let query = Query::unit();
320/// let stmt = Statement::from(query);
321/// assert!(stmt.is_query());
322/// assert!(!stmt.is_insert());
323/// ```
324#[derive(Clone, PartialEq)]
325pub enum Statement {
326    /// Delete one or more existing records.
327    Delete(Delete),
328
329    /// Create one or more new records.
330    Insert(Insert),
331
332    /// Query (read) records from the database.
333    Query(Query),
334
335    /// Update one or more existing records.
336    Update(Update),
337}
338
339impl Statement {
340    /// Returns the statement variant name for logging.
341    pub fn name(&self) -> &str {
342        match self {
343            Statement::Query(_) => "query",
344            Statement::Insert(_) => "insert",
345            Statement::Update(_) => "update",
346            Statement::Delete(_) => "delete",
347        }
348    }
349
350    /// Substitutes argument placeholders in this statement with concrete values
351    /// from `input`.
352    pub fn substitute(&mut self, input: impl Input) {
353        Substitute::new(input).visit_stmt_mut(self);
354    }
355
356    /// Returns `true` if this statement is a query whose body contains only
357    /// constant values (no table references or subqueries) and has no CTEs.
358    pub fn is_const(&self) -> bool {
359        match self {
360            Statement::Query(query) => {
361                if query.with.is_some() {
362                    return false;
363                }
364
365                query.body.is_const()
366            }
367            _ => false,
368        }
369    }
370
371    /// Attempts to return a reference to an inner [`Update`].
372    ///
373    /// * If `self` is a [`Statement::Update`], a reference to the inner [`Update`] is
374    ///   returned wrapped in [`Some`].
375    /// * Else, [`None`] is returned.
376    pub fn as_update(&self) -> Option<&Update> {
377        match self {
378            Self::Update(update) => Some(update),
379            _ => None,
380        }
381    }
382
383    /// Consumes `self` and attempts to return the inner [`Update`].
384    ///
385    /// * If `self` is a [`Statement::Update`], inner [`Update`] is returned wrapped in
386    ///   [`Some`].
387    /// * Else, [`None`] is returned.
388    pub fn into_update(self) -> Option<Update> {
389        match self {
390            Self::Update(update) => Some(update),
391            _ => None,
392        }
393    }
394
395    /// Returns `true` if this statement expects at most one result row.
396    pub fn is_single(&self) -> bool {
397        match self {
398            Statement::Query(q) => q.single,
399            Statement::Insert(i) => i.source.single,
400            Statement::Update(i) => match &i.target {
401                UpdateTarget::Query(q) => q.single,
402                UpdateTarget::Model(_) => true,
403                _ => false,
404            },
405            Statement::Delete(d) => d.selection().single,
406        }
407    }
408
409    /// Consumes `self` and returns the inner [`Update`].
410    ///
411    /// # Panics
412    ///
413    /// If `self` is not a [`Statement::Update`].
414    pub fn into_update_unwrap(self) -> Update {
415        match self {
416            Self::Update(update) => update,
417            v => panic!("expected `Update`, found {v:#?}"),
418        }
419    }
420}
421
422impl Node for Statement {
423    fn visit<V: Visit>(&self, mut visit: V) {
424        visit.visit_stmt(self);
425    }
426
427    fn visit_mut<V: VisitMut>(&mut self, mut visit: V) {
428        visit.visit_stmt_mut(self);
429    }
430}
431
432impl fmt::Debug for Statement {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        match self {
435            Self::Delete(v) => v.fmt(f),
436            Self::Insert(v) => v.fmt(f),
437            Self::Query(v) => v.fmt(f),
438            Self::Update(v) => v.fmt(f),
439        }
440    }
441}