sqlive/scope_row.rs
1//! A condition on one table's row that sqlive's own comparisons can't read,
2//! an expression over one table's row compared with another source's value,
3//! and an ORDER BY term's expression over one table's row, judged by asking
4//! SQLite (ยง4).
5//!
6//! A WHERE or ON conjunct whose every name is a stored, BINARY column of one
7//! table of its own SELECT, and that holds no subquery, no clock and no
8//! function that isn't deterministic, narrows that table to the rows it holds
9//! for: a function of a column, a CASE, LIKE and GLOB, `<>`, a row value, a
10//! COLLATE. sqlive compares none of this itself. A write asks SQLite whether
11//! the changed row's old and new values pass: a SELECT over a row of those
12//! values, each with its column's type, so the condition compares as it does
13//! in the table. A value sqlive can't give its column's type, one the write
14//! didn't record, an error and a question past the lookups' step limit count
15//! as a match.
16//!
17//! The condition may be true of the NULLs a missing right row gives, so it
18//! never makes a LEFT JOIN inner, and it isn't passed into a view's or
19//! subquery's rows.
20//!
21//! An expression over such columns that an equality compares with another
22//! source's value narrows the table to the rows whose value some row of that
23//! source gives in its scope: the question asks whether the expression's
24//! value in the changed row is IN the values the other source's rows give
25//! (`scope_lookup::joined`), as the statement's equality compares them. The
26//! expression is NULL wherever its columns are, or its table is no LEFT
27//! JOIN's (`Planner::member_expression`), so the equality, as an edge, can
28//! make a LEFT JOIN inner.
29//!
30//! An ORDER BY term's expression over such columns, or a generated column's,
31//! bounds a full run's rows by the last row's value (`scope_order.rs`): the
32//! question tests whether the changed row's value is NULL, or how it compares
33//! with that value.
34
35use std::cmp::Ordering;
36use std::sync::Arc;
37
38use crate::row_scope::RowImage;
39use crate::scope_lookup::Lookup;
40use crate::scope_plan::Planner;
41use crate::scope_term::Affinity;
42use crate::select_syntax::{Functions, Part};
43use crate::sql_value::SqlValue as Value;
44use sqlite3_parser::ast::Expr;
45
46/// An expression over one table's row, a conjunct or an ORDER BY term's
47/// value, and what it names, before a run's values.
48#[derive(Debug)]
49pub(crate) struct RowTerm {
50 /// The expression as SQL, its parameters numbered as the plan's
51 /// statement numbers them.
52 pub(crate) sql: String,
53 /// How the statement names the table's rows.
54 pub(crate) qualifier: String,
55 /// The columns it names, lowercase, with their affinities.
56 pub(crate) columns: Vec<(String, Affinity)>,
57}
58
59/// An expression over one table's row, with the affinity SQLite gives its
60/// value: an ORDER BY term's, which has none, or a generated column's own.
61#[derive(Clone, Debug)]
62pub(crate) struct RowExpression {
63 pub(crate) term: Arc<RowTerm>,
64 pub(crate) affinity: Affinity,
65}
66
67/// The term `expr`, a condition or a value whose names resolve to the table
68/// item `item` of `core`, gives, when SQLite can evaluate it row by row;
69/// `parts` are its parts.
70pub(crate) fn item_row_term(
71 planner: &Planner,
72 core: usize,
73 item: usize,
74 expr: &Expr<'_>,
75 parts: &[Part<'_>],
76) -> Option<Arc<RowTerm>> {
77 let from = &planner.items[item];
78 from.source.table.as_ref()?;
79 row_term(planner.functions, &from.source.qualifier, expr, parts, &|name| {
80 let (_, column) = planner.resolve(core, name)?;
81 let affinity = from.columns.affinity(&column)?;
82 Some((column, affinity))
83 })
84}
85
86/// The term `expr` gives a table's rows, which the statement names by
87/// `qualifier`, when SQLite can evaluate it row by row: `column` gives the
88/// column, lowercase, and the affinity of each name in it, when sqlive
89/// compares that column's values, and the connection's `functions` tell
90/// whether each call repeats; `parts` are its parts.
91pub(crate) fn row_term(
92 functions: &Functions,
93 qualifier: &str,
94 expr: &Expr<'_>,
95 parts: &[Part<'_>],
96 column: &dyn Fn(&Expr<'_>) -> Option<(String, Affinity)>,
97) -> Option<Arc<RowTerm>> {
98 let mut columns: Vec<(String, Affinity)> = Vec::new();
99 for part in parts {
100 match part {
101 Part::Name(name) => {
102 // A name qualified by a database isn't one the judging
103 // statement could resolve.
104 if matches!(name, Expr::DoublyQualified(..)) {
105 return None;
106 }
107 let (column, affinity) = column(name)?;
108 if !columns.iter().any(|(named, _)| *named == column) {
109 columns.push((column, affinity));
110 }
111 }
112 Part::Function(name, arguments, window) => {
113 if *window || !functions.repeats(name, *arguments) {
114 return None;
115 }
116 }
117 Part::Collation => {}
118 Part::Select(_) | Part::Subquery(_) | Part::Table(_) | Part::Clock => return None,
119 }
120 }
121 if columns.is_empty() {
122 return None;
123 }
124 Some(Arc::new(RowTerm { sql: expr.to_string(), qualifier: qualifier.to_owned(), columns }))
125}
126
127/// A run's condition: what it tests of a term, with the run's parameters.
128#[derive(Debug)]
129pub struct RowCondition {
130 pub(crate) term: Arc<RowTerm>,
131 pub(crate) parameters: Vec<Value>,
132 pub(crate) test: RowTest,
133}
134
135/// What a run's condition tests of its term.
136#[derive(Debug)]
137pub(crate) enum RowTest {
138 /// That the term, a condition, holds.
139 Holds,
140 /// That the term's value is NULL, or isn't when `not`.
141 Null { not: bool },
142 /// That the term's value, given `affinity`, compares with `value`, which
143 /// isn't NULL, as `ordering`, as an ORDER BY compares two values.
144 Compare { ordering: Ordering, value: Value, affinity: Affinity },
145 /// That the term's value equals a value some row of the lookup's
146 /// partner gives in its scope, as the statement's equality compares
147 /// them: a member's expression joined to its partner.
148 Joined(Arc<Lookup>),
149}
150
151impl RowCondition {
152 /// The condition as SQL over the row the term's qualifier names, with
153 /// the value it compares with appended to `bound` as a parameter.
154 /// `None` when no cast gives that value the term's affinity and keeps it
155 /// as it is.
156 pub(crate) fn sql(&self, bound: &mut Vec<Value>) -> Option<String> {
157 let sql = &self.term.sql;
158 Some(match &self.test {
159 RowTest::Holds => format!("({sql})"),
160 RowTest::Null { not } => {
161 format!("({sql}) IS {}NULL", if *not { "NOT " } else { "" })
162 }
163 RowTest::Compare { ordering, value, affinity } => {
164 let typed = typed(&format!("?{}", bound.len() + 1), *affinity, value)?;
165 bound.push(value.clone());
166 let operator = match ordering {
167 Ordering::Less => "<",
168 Ordering::Equal => "=",
169 Ordering::Greater => ">",
170 };
171 // A unary plus takes away the expression's affinity, so the
172 // comparison converts its value only to the affinity the
173 // typed value carries, as a generated column's value has it.
174 format!("+({sql}) {operator} {typed}")
175 }
176 RowTest::Joined(lookup) => {
177 crate::scope_lookup::joined(&format!("({sql})"), lookup, bound)
178 }
179 })
180 }
181
182 /// The SQL that asks whether the row `image` passes, and its parameters:
183 /// the run's, then any value the condition compares with, then the
184 /// image's values. `None` when sqlive can't ask, which counts as a
185 /// match: the image lacks a column, or a value is one no cast would keep
186 /// as it is in its column's type.
187 pub(crate) fn question(&self, image: &RowImage) -> Option<(String, Vec<Value>)> {
188 let term = &self.term;
189 let mut bound = self.parameters.clone();
190 let condition = self.sql(&mut bound)?;
191 let mut row = Vec::with_capacity(term.columns.len());
192 for (column, affinity) in &term.columns {
193 let value = image.get(column)?;
194 let typed = typed(&format!("?{}", bound.len() + 1), *affinity, value)?;
195 row.push(format!("{typed} AS {}", crate::sql::identifier(column)));
196 bound.push(value.clone());
197 }
198 let sql = format!(
199 "SELECT 1 FROM (SELECT {}) AS {} WHERE {condition} LIMIT 1",
200 row.join(","),
201 term.qualifier,
202 );
203 Some((sql, bound))
204 }
205}
206
207/// The parameter `placeholder`, bound to `value`, as SQL of `affinity`: a
208/// subquery's column, and a comparison's operand, take the affinity of their
209/// expression, so a cast gives the value its own. `None` for a value no cast
210/// keeps as it is.
211pub(crate) fn typed(placeholder: &str, affinity: Affinity, value: &Value) -> Option<String> {
212 Some(match (affinity, value) {
213 (_, Value::Null) | (Affinity::Blob, _) => placeholder.to_owned(),
214 (Affinity::Text, Value::Text(_)) => format!("CAST({placeholder} AS TEXT)"),
215 (Affinity::Numeric, Value::Integer(_)) => format!("CAST({placeholder} AS INTEGER)"),
216 (Affinity::Numeric, Value::Real(_)) => format!("CAST({placeholder} AS REAL)"),
217 _ => return None,
218 })
219}