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::{
45    DerivedRef, ExprContext, ExprTarget, IntoExprTarget, ProjectedField, Resolve, ResolvedRef,
46};
47
48mod delete;
49pub use delete::Delete;
50
51mod direction;
52pub use direction::Direction;
53
54mod document_storage_text;
55pub use document_storage_text::DocumentStorageText;
56
57mod entry;
58pub use entry::Entry;
59
60mod entry_mut;
61pub use entry_mut::EntryMut;
62
63mod entry_path;
64pub use entry_path::EntryPath;
65
66mod eval;
67
68mod expr;
69pub use expr::Expr;
70
71mod expr_all_op;
72pub use expr_all_op::ExprAllOp;
73
74mod expr_and;
75pub use expr_and::ExprAnd;
76
77mod expr_between;
78pub use expr_between::ExprBetween;
79
80mod expr_any;
81pub use expr_any::ExprAny;
82
83mod expr_any_op;
84pub use expr_any_op::ExprAnyOp;
85
86mod expr_arg;
87pub use expr_arg::ExprArg;
88
89mod expr_binary_op;
90pub use expr_binary_op::ExprBinaryOp;
91
92mod expr_cast;
93pub use expr_cast::ExprCast;
94
95mod expr_error;
96pub use expr_error::ExprError;
97
98mod expr_exists;
99pub use expr_exists::ExprExists;
100
101mod expr_func;
102pub use expr_func::ExprFunc;
103
104mod expr_in_list;
105pub use expr_in_list::ExprInList;
106
107mod expr_in_subquery;
108pub use expr_in_subquery::ExprInSubquery;
109
110mod expr_incoming;
111pub use expr_incoming::ExprIncoming;
112
113mod expr_intersects;
114pub use expr_intersects::ExprIntersects;
115
116mod expr_is_null;
117pub use expr_is_null::ExprIsNull;
118
119mod expr_is_superset;
120pub use expr_is_superset::ExprIsSuperset;
121
122mod expr_is_variant;
123pub use expr_is_variant::ExprIsVariant;
124
125mod expr_variant;
126pub use expr_variant::ExprVariant;
127
128mod expr_length;
129pub use expr_length::ExprLength;
130
131mod expr_let;
132pub use expr_let::ExprLet;
133
134mod expr_like;
135pub use expr_like::ExprLike;
136
137mod expr_list;
138pub use expr_list::ExprList;
139
140mod expr_map;
141pub use expr_map::ExprMap;
142
143mod expr_match;
144pub use expr_match::{ExprMatch, MatchArm};
145
146mod expr_not;
147pub use expr_not::ExprNot;
148
149mod expr_or;
150pub use expr_or::ExprOr;
151
152mod expr_project;
153pub use expr_project::ExprProject;
154
155mod expr_record;
156pub use expr_record::ExprRecord;
157
158mod expr_reference;
159pub use expr_reference::{ExprColumn, ExprReference};
160
161mod expr_set;
162pub use expr_set::ExprSet;
163
164mod expr_set_op;
165pub use expr_set_op::ExprSetOp;
166
167mod expr_starts_with;
168pub use expr_starts_with::ExprStartsWith;
169
170mod expr_stmt;
171pub use expr_stmt::ExprStmt;
172
173mod filter;
174pub use filter::Filter;
175
176mod hash_index;
177pub use hash_index::HashIndex;
178
179mod sorted_index;
180pub use sorted_index::SortedIndex;
181
182mod func_count;
183pub use func_count::FuncCount;
184
185mod func_json_extract;
186pub use func_json_extract::FuncJsonExtract;
187
188mod func_last_insert_id;
189pub use func_last_insert_id::FuncLastInsertId;
190
191mod include;
192pub use include::Include;
193
194mod insert;
195pub use insert::{Insert, Upsert, UpsertAction, UpsertTarget};
196
197mod insert_table;
198pub use insert_table::InsertTable;
199
200mod insert_target;
201pub use insert_target::InsertTarget;
202
203mod input;
204pub(crate) use input::InputResolve;
205pub use input::{ConstInput, Input, TypedInput};
206
207mod join;
208pub use join::{Join, JoinOp};
209
210mod limit;
211pub use limit::{Limit, LimitCursor, LimitOffset};
212
213#[cfg(feature = "assert-struct")]
214mod like;
215
216mod node;
217pub use node::Node;
218
219mod num;
220
221mod op_binary;
222pub use op_binary::BinaryOp;
223
224mod order_by;
225pub use order_by::OrderBy;
226
227mod order_by_expr;
228pub use order_by_expr::OrderByExpr;
229
230mod op_set;
231pub use op_set::SetOp;
232
233mod path;
234pub use path::{Path, PathRoot};
235
236mod path_field_set;
237pub use path_field_set::PathFieldSet;
238
239mod projection;
240pub use projection::{Project, Projection};
241
242mod query;
243pub use query::{Lock, Query};
244
245mod returning;
246pub use returning::Returning;
247
248mod select;
249pub use select::Select;
250
251mod source;
252pub use source::{Source, SourceModel};
253
254mod source_table;
255pub use source_table::SourceTable;
256
257mod source_table_id;
258pub use source_table_id::SourceTableId;
259
260mod sparse_record;
261pub use sparse_record::SparseRecord;
262
263mod substitute;
264use substitute::Substitute;
265
266mod table_derived;
267pub use table_derived::TableDerived;
268
269mod table_ref;
270pub use table_ref::TableRef;
271
272mod table_factor;
273pub use table_factor::TableFactor;
274
275mod table_with_joins;
276pub use table_with_joins::TableWithJoins;
277
278mod ty;
279pub use ty::Type;
280
281#[cfg(feature = "bigdecimal")]
282pub use bigdecimal::BigDecimal;
283#[cfg(feature = "net")]
284pub use cidr::{IpCidr, IpInet};
285#[cfg(feature = "jiff")]
286pub use jiff::{
287    Timestamp, Zoned,
288    civil::{Date, DateTime, Time},
289};
290#[cfg(feature = "net")]
291pub use macaddr::{MacAddr6, MacAddr8};
292#[cfg(feature = "rust_decimal")]
293pub use rust_decimal::Decimal;
294pub use uuid::Uuid;
295
296mod ty_union;
297pub use ty_union::TypeUnion;
298
299#[cfg(feature = "jiff")]
300mod ty_jiff;
301
302#[cfg(feature = "net")]
303mod ty_net;
304
305mod update;
306pub use update::{Update, UpdateTarget};
307
308mod value;
309pub use value::Value;
310
311mod value_cmp;
312
313mod values;
314pub use values::Values;
315
316#[cfg(feature = "jiff")]
317mod value_jiff;
318
319#[cfg(feature = "net")]
320mod value_net;
321
322mod value_object;
323pub use value_object::ValueObject;
324
325mod value_record;
326pub use value_record::ValueRecord;
327
328mod value_set;
329pub use value_set::ValueSet;
330
331/// Mutable AST visitor trait and helpers.
332pub mod visit_mut;
333pub use visit_mut::VisitMut;
334
335mod value_list;
336
337mod value_stream;
338pub use value_stream::ValueStream;
339
340/// Read-only AST visitor trait and helpers.
341pub mod visit;
342pub use visit::Visit;
343
344mod with;
345pub use with::With;
346
347use crate::schema::db::TableId;
348use std::fmt;
349
350/// A top-level statement in Toasty's AST.
351///
352/// Each variant corresponds to one of the four fundamental database operations.
353/// A `Statement` is the primary input to the query engine's compilation
354/// pipeline and the output of code generated by `#[derive(Model)]`.
355///
356/// # Examples
357///
358/// ```ignore
359/// use toasty_core::stmt::{Statement, Query, Values};
360///
361/// let query = Query::unit();
362/// let stmt = Statement::from(query);
363/// assert!(stmt.is_query());
364/// assert!(!stmt.is_insert());
365/// ```
366#[derive(Clone, PartialEq)]
367pub enum Statement {
368    /// Delete one or more existing records.
369    Delete(Delete),
370
371    /// Create one or more new records.
372    Insert(Insert),
373
374    /// Query (read) records from the database.
375    Query(Query),
376
377    /// Update one or more existing records.
378    Update(Update),
379}
380
381impl Statement {
382    /// Returns the statement variant name for logging.
383    pub fn name(&self) -> &str {
384        match self {
385            Statement::Query(_) => "query",
386            Statement::Insert(_) => "insert",
387            Statement::Update(_) => "update",
388            Statement::Delete(_) => "delete",
389        }
390    }
391
392    /// Substitutes argument placeholders in this statement with concrete values
393    /// from `input`.
394    pub fn substitute(&mut self, input: impl Input) {
395        Substitute::new(input).visit_stmt_mut(self);
396    }
397
398    /// Returns `true` if this statement is a query whose body contains only
399    /// constant values (no table references or subqueries) and has no CTEs.
400    pub fn is_const(&self) -> bool {
401        match self {
402            Statement::Query(query) => {
403                if query.with.is_some() {
404                    return false;
405                }
406
407                query.body.is_const()
408            }
409            _ => false,
410        }
411    }
412
413    /// Attempts to return a reference to an inner [`Update`].
414    ///
415    /// * If `self` is a [`Statement::Update`], a reference to the inner [`Update`] is
416    ///   returned wrapped in [`Some`].
417    /// * Else, [`None`] is returned.
418    pub fn as_update(&self) -> Option<&Update> {
419        match self {
420            Self::Update(update) => Some(update),
421            _ => None,
422        }
423    }
424
425    /// Consumes `self` and attempts to return the inner [`Update`].
426    ///
427    /// * If `self` is a [`Statement::Update`], inner [`Update`] is returned wrapped in
428    ///   [`Some`].
429    /// * Else, [`None`] is returned.
430    pub fn into_update(self) -> Option<Update> {
431        match self {
432            Self::Update(update) => Some(update),
433            _ => None,
434        }
435    }
436
437    /// Returns `true` if this statement expects at most one result row.
438    pub fn is_single(&self) -> bool {
439        match self {
440            Statement::Query(q) => q.single,
441            Statement::Insert(i) => i.source.single,
442            Statement::Update(i) => match &i.target {
443                UpdateTarget::Query(q) => q.single,
444                UpdateTarget::Model(_) => true,
445                _ => false,
446            },
447            Statement::Delete(d) => d.selection().single,
448        }
449    }
450
451    /// Consumes `self` and returns the inner [`Update`].
452    ///
453    /// # Panics
454    ///
455    /// If `self` is not a [`Statement::Update`].
456    pub fn into_update_unwrap(self) -> Update {
457        match self {
458            Self::Update(update) => update,
459            v => panic!("expected `Update`, found {v:#?}"),
460        }
461    }
462}
463
464impl Node for Statement {
465    fn visit<V: Visit>(&self, mut visit: V) {
466        visit.visit_stmt(self);
467    }
468
469    fn visit_mut<V: VisitMut>(&mut self, mut visit: V) {
470        visit.visit_stmt_mut(self);
471    }
472}
473
474impl fmt::Debug for Statement {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476        match self {
477            Self::Delete(v) => v.fmt(f),
478            Self::Insert(v) => v.fmt(f),
479            Self::Query(v) => v.fmt(f),
480            Self::Update(v) => v.fmt(f),
481        }
482    }
483}