Skip to main content

sql_builder/query/condition/
constant.rs

1//! Conditions that fold to a constant.
2
3use super::{Condition, ConditionExpression, ConditionType};
4use crate::{
5    BinOper, Expr, UnOper, Value,
6    lexer::{Dialect, Kind, tokens},
7};
8
9impl Condition {
10    /// Whether the condition holds for every row, whatever the row holds:
11    /// it folds to TRUE, as an empty [`Condition::all`] does, or `x NOT IN ()`,
12    /// or an OR with a TRUE branch.
13    ///
14    /// A condition that only might hold everywhere (`col = col`) is not
15    /// trivially true; what is not a constant is left unknown.
16    ///
17    /// ```
18    /// use sql_builder::*;
19    ///
20    /// assert!(Cond::all().is_trivially_true());
21    /// assert!(Cond::any().add(Expr::col("id").eq(1)).add(Expr::val(true)).is_trivially_true());
22    /// assert!(!Cond::all().add(Expr::col("id").eq(1)).is_trivially_true());
23    /// ```
24    pub fn is_trivially_true(&self) -> bool {
25        self.constant() == Some(true)
26    }
27
28    /// The value the condition folds to, if it is a constant.
29    fn constant(&self) -> Option<bool> {
30        let values = self.conditions.iter().map(|condition| match condition {
31            ConditionExpression::Condition(condition) => condition.constant(),
32            ConditionExpression::Expr(expr) => expr_constant(expr),
33        });
34        let folded = match self.condition_type {
35            ConditionType::All => all(values),
36            ConditionType::Any => any(values),
37        };
38        folded.map(|value| value != self.negate)
39    }
40}
41
42/// AND of `values`: FALSE when one is, TRUE when all are, else unknown.
43fn all(values: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
44    let mut known = Some(true);
45    for value in values {
46        match value {
47            Some(false) => return Some(false),
48            Some(true) => {}
49            None => known = None,
50        }
51    }
52    known
53}
54
55/// OR of `values`: TRUE when one is, FALSE when all are, else unknown.
56fn any(values: impl IntoIterator<Item = Option<bool>>) -> Option<bool> {
57    all(values.into_iter().map(|value| value.map(|value| !value))).map(|value| !value)
58}
59
60fn expr_constant(expr: &Expr) -> Option<bool> {
61    match expr {
62        Expr::Value(Value::Bool(Some(value))) | Expr::Constant(Value::Bool(Some(value))) => {
63            Some(*value)
64        }
65        Expr::Unary(UnOper::Not, inner) => expr_constant(inner).map(|value| !value),
66        Expr::Binary(left, operator, right) => match (operator, right.as_ref()) {
67            (BinOper::In, Expr::Tuple(list)) if list.is_empty() => Some(false),
68            (BinOper::NotIn, Expr::Tuple(list)) if list.is_empty() => Some(true),
69            (BinOper::And, _) => all([expr_constant(left), expr_constant(right)]),
70            (BinOper::Or, _) => any([expr_constant(left), expr_constant(right)]),
71            (BinOper::Equal, _) => equal(left, right),
72            (BinOper::NotEqual, _) => equal(left, right).map(|value| !value),
73            _ => None,
74        },
75        Expr::Custom(sql) => custom_constant(sql),
76        _ => None,
77    }
78}
79
80/// Whether two literal values are equal; unknown for NULL, a column or
81/// values of different types, which the database may compare otherwise.
82fn equal(left: &Expr, right: &Expr) -> Option<bool> {
83    let literal = |expr: &Expr| match expr {
84        Expr::Value(value) | Expr::Constant(value) if *value != value.as_null() => {
85            Some(value.clone())
86        }
87        _ => None,
88    };
89    let (left, right) = (literal(left)?, literal(right)?);
90    (std::mem::discriminant(&left) == std::mem::discriminant(&right)).then(|| left == right)
91}
92
93/// The constant a fragment of SQL text spells: `TRUE`, `1`, `1 = 1`,
94/// `TRUE = TRUE` or their false forms, parenthesized or not. Any other text
95/// is unknown.
96fn custom_constant(sql: &str) -> Option<bool> {
97    let mut spelled = String::new();
98    for token in tokens(sql, Dialect::Any) {
99        match token.kind {
100            Kind::Space => {}
101            Kind::Symbol if matches!(token.text, "(" | ")") => {}
102            Kind::Word | Kind::Symbol => spelled.push_str(&token.text.to_ascii_uppercase()),
103            _ => return None,
104        }
105    }
106    match spelled.as_str() {
107        "TRUE" | "1" | "1=1" | "TRUE=TRUE" => Some(true),
108        "FALSE" | "0" | "0=1" | "1=0" | "1=2" | "FALSE=TRUE" | "TRUE=FALSE" => Some(false),
109        _ => None,
110    }
111}
112
113#[cfg(test)]
114#[path = "../../../tests/unit/condition_constant_tests.rs"]
115mod tests;