Skip to main content

inillucent_sql/bind/
collation.rs

1//! Which collation a comparison, a sort or a grouping uses, and where an
2//! explicit `COLLATE` comes from.
3//!
4//! Invariant: **every collation the binder decides comes from the rules in
5//! this file, and they are SQLite's `sqlite3ExprCollSeq` and
6//! `sqlite3BinaryCompareCollSeq`, graded against the pinned 3.53.4 shell.**
7//! The executor's `expression_collation` used to be a second copy of them
8//! that looked only at the top node, and the binder's own two helpers did the
9//! same, so an explicit `COLLATE` inside an operand of `||` reached neither a
10//! comparison nor a `GROUP BY` (task-2089). One copy, here, is what keeps a
11//! comparison, an `ORDER BY`, a `DISTINCT` and a `PARTITION BY` agreeing
12//! about which values are equal. The cases that grade these rules are
13//! `crates/inillucent-compat/tests/corpora/differential-part8/task2089.cases`.
14
15use inillucent_value::Collation;
16
17use super::BoundExpr;
18use crate::ast::UnaryOp;
19
20impl BoundExpr {
21    /// Returns the collation this expression carries, if it has one.
22    ///
23    /// SQLite's `sqlite3ExprCollSeq`, in its order: a column has its declared
24    /// collation, a `CAST` and a unary `+` have their operand's, and any other
25    /// expression has the explicit collation of an operand, if one has one.
26    /// So `CAST(n AS TEXT) = 'A'` on a NOCASE column `n` compares with NOCASE,
27    /// and `n || '' = 'A'` compares with BINARY. Measured against 3.53.4
28    /// (task-2089): `CAST(n AS TEXT) = 'A'` and `+n = 'A'` answered 0 here
29    /// where SQLite answers 1.
30    pub fn collation(&self) -> Option<Collation> {
31        match self {
32            BoundExpr::Column { collation, .. } | BoundExpr::Generated { collation, .. } => {
33                Some(*collation)
34            }
35            BoundExpr::Cast { operand, .. }
36            | BoundExpr::Unary {
37                op: UnaryOp::Identity,
38                operand,
39            } => operand.collation(),
40            // One column of a subquery used as a row value reads the collation
41            // of the column it stands for, as SQLite does for a `SELECT_COLUMN`.
42            // A scalar subquery written alone carries Binary here and none.
43            BoundExpr::Subquery {
44                kind: super::SubqueryKind::Scalar,
45                collation,
46                ..
47            } if *collation != Collation::Binary => Some(*collation),
48            other => other.explicit_collation(),
49        }
50    }
51
52    /// Returns the collation an explicit `COLLATE` forced on this expression.
53    ///
54    /// This is *not* the same question as [`BoundExpr::collation`]. A column
55    /// declared `COLLATE NOCASE` has an implicit collation; `x COLLATE BINARY`
56    /// has an explicit one, and an explicit collation on either side of a
57    /// comparison beats an implicit one on the other side.
58    ///
59    /// **An explicit collation reaches up through every operator and function
60    /// argument (task-2089).** SQLite marks a node `EP_Collate` when any
61    /// operand has the mark, and reads the collation from the first operand
62    /// that has it, left first. This used to look only at the top node, so
63    /// `('a' COLLATE NOCASE || 'x') = 'AX'` compared with BINARY and answered
64    /// 0 where 3.53.4 answers 1, and `'a' COLLATE BINARY || 'b' COLLATE
65    /// NOCASE` has to answer BINARY because the left operand is asked first.
66    /// [`BoundExpr::children`] lists operands in SQLite's order for every node
67    /// whose value is text. A scalar subquery has no children here, and SQLite
68    /// does not carry a `COLLATE` out of one either. An aggregate or window
69    /// call has no children here either, because its arguments live in the
70    /// block's lists, so its reference carries the answer for them: see
71    /// `explicit_argument_collation`, in `aggregate.rs`.
72    pub fn explicit_collation(&self) -> Option<Collation> {
73        match self {
74            BoundExpr::Collate { collation, .. } => Some(*collation),
75            BoundExpr::Generated { .. } => None,
76            BoundExpr::Aggregate { collation, .. } | BoundExpr::WindowRef { collation, .. } => {
77                *collation
78            }
79            other => other
80                .children()
81                .into_iter()
82                .find_map(BoundExpr::explicit_collation),
83        }
84    }
85}
86
87/// Returns the collation a result column compares with.
88///
89/// `DISTINCT` and `GROUP BY` compare result values, and a NOCASE column makes
90/// `blue` and `Blue` the same value for both. Comparing them with BINARY
91/// instead returns more rows than SQLite does, which looks like a duplicate
92/// rather than like a bug.
93pub fn result_collation(expr: &BoundExpr) -> Collation {
94    expr.explicit_collation()
95        .or_else(|| expr.collation())
96        .unwrap_or(Collation::Binary)
97}
98
99/// Wraps an expression in the collation an explicit `COLLATE` names.
100///
101/// **A `COLLATE` above a comparison does not reach the comparison (task-1979,
102/// F5).** `a = b COLLATE NOCASE` parses as `a = (b COLLATE NOCASE)`, because
103/// `COLLATE` binds tighter than `=`, and the comparison then reads NOCASE off
104/// its own right operand through [`comparison_rules`]. `(a = b) COLLATE
105/// NOCASE` is the other tree: the comparison is finished and NOCASE applies to
106/// the integer it produced, where a text collation does nothing. This function
107/// used to stamp the collation onto a `BoundExpr::Compare` it was handed, which
108/// made the two trees answer the same and made the outer name win over the
109/// inner one: measured against 3.53.4, `SELECT ('B'<'a') COLLATE NOCASE`
110/// answered 0 where SQLite answers 1, and
111/// `SELECT ('a' = 'A' COLLATE NOCASE) COLLATE BINARY` answered 0 where SQLite
112/// answers 1 because the inner NOCASE is the comparison's and the outer BINARY
113/// is the result's.
114///
115/// The wrapper is what carries the collation onward: [`comparison_rules`] asks
116/// an operand for its [`BoundExpr::explicit_collation`], so a `COLLATE` on a
117/// literal still reaches the comparison that uses it.
118///
119/// @param expr - the operand the `COLLATE` was written on
120/// @param collation - the collation it names
121pub(super) fn apply_collation(expr: BoundExpr, collation: Collation) -> BoundExpr {
122    BoundExpr::Collate {
123        operand: Box::new(expr),
124        collation,
125    }
126}
127
128#[cfg(test)]
129mod tests;