toasty_core/stmt/condition.rs
1use crate::stmt::{Expr, Node, Statement, Visit, VisitMut};
2
3/// A guard condition on an [`Update`](super::Update) statement.
4///
5/// Unlike a [`Filter`](super::Filter), a condition does not select which rows
6/// to operate on. Instead, it is evaluated after the filter and determines
7/// whether the update should actually be applied. If the condition is not met,
8/// the update is silently skipped.
9///
10/// When `expr` is `None`, no condition is applied (the update always proceeds).
11///
12/// # Examples
13///
14/// ```
15/// use toasty_core::stmt::Condition;
16///
17/// let cond = Condition::default();
18/// assert!(cond.is_none());
19/// ```
20#[derive(Debug, Default, Clone, PartialEq)]
21pub struct Condition {
22 /// The condition expression, or `None` for unconditional updates.
23 pub expr: Option<Expr>,
24}
25
26impl Condition {
27 /// Creates a condition from an expression.
28 pub fn new(expr: impl Into<Expr>) -> Condition {
29 Condition {
30 expr: Some(expr.into()),
31 }
32 }
33
34 /// Returns `true` if a condition expression is set.
35 pub fn is_some(&self) -> bool {
36 self.expr.is_some()
37 }
38
39 /// Returns `true` if no condition expression is set.
40 pub fn is_none(&self) -> bool {
41 self.expr.is_none()
42 }
43}
44
45impl Statement {
46 /// Returns a reference to this statement's condition, if it has one and it
47 /// is set. Only `Update` statements support conditions.
48 pub fn condition(&self) -> Option<&Condition> {
49 match self {
50 Statement::Update(update) if update.condition.is_some() => Some(&update.condition),
51 _ => None,
52 }
53 }
54
55 /// Returns a mutable reference to the statement's condition.
56 ///
57 /// Returns `None` for statements that do not support conditions.
58 pub fn condition_mut(&mut self) -> Option<&mut Condition> {
59 match self {
60 Statement::Update(update) => Some(&mut update.condition),
61 _ => None,
62 }
63 }
64
65 /// Returns a mutable reference to the statement's condition.
66 ///
67 /// # Panics
68 ///
69 /// Panics if the statement does not support conditions.
70 #[track_caller]
71 pub fn condition_mut_unwrap(&mut self) -> &mut Condition {
72 match self {
73 Statement::Update(update) => &mut update.condition,
74 _ => panic!("expected Statement with condition"),
75 }
76 }
77}
78
79impl Node for Condition {
80 fn visit<V: Visit>(&self, mut visit: V) {
81 visit.visit_condition(self);
82 }
83
84 fn visit_mut<V: VisitMut>(&mut self, mut visit: V) {
85 visit.visit_condition_mut(self);
86 }
87}
88
89impl<T> From<T> for Condition
90where
91 Expr: From<T>,
92{
93 fn from(value: T) -> Self {
94 Condition {
95 expr: Some(value.into()),
96 }
97 }
98}