1use std::cmp::Ordering;
7use std::collections::{BTreeMap, BTreeSet};
8use std::sync::Arc;
9
10use crate::scope_lookup::{Judging, Lookup, Lookups, NoAnswer};
11use crate::scope_row::RowCondition;
12use crate::scope_window::{RowWindow, WindowQuestion};
13use crate::sql_value::SqlValue as Value;
14
15#[derive(Clone, Debug)]
18pub enum RowScope {
19 All,
21 Compare {
24 column: String,
26 value: Value,
28 ordering: Ordering,
30 inclusive: bool,
32 },
33 Null {
35 column: String,
37 not: bool,
39 },
40 In {
43 column: String,
45 values: Vec<Value>,
47 },
48 Row(Arc<RowCondition>),
51 Joined {
54 column: String,
56 lookup: Arc<Lookup>,
58 },
59 Window(Arc<RowWindow>),
62 And(Box<Self>, Box<Self>),
64 Or(Box<Self>, Box<Self>),
66}
67
68impl RowScope {
69 pub(crate) fn matches(
74 &self,
75 row: &RowImage,
76 lookups: &mut Lookups<'_>,
77 ) -> Result<bool, NoAnswer> {
78 Ok(match self {
79 Self::All => true,
80 Self::Compare { column, value, ordering, inclusive } => {
81 row.get(column).is_none_or(|actual| {
82 compare(actual, value)
83 .is_some_and(|found| found == *ordering || (*inclusive && found.is_eq()))
84 })
85 }
86 Self::Null { column, not } => {
87 row.get(column).is_none_or(|actual| matches!(actual, Value::Null) != *not)
88 }
89 Self::In { column, values } => row.get(column).is_none_or(|actual| {
90 !matches!(actual, Value::Null)
91 && values
92 .binary_search_by(|value| {
93 compare(value, actual).expect("neither value is NULL")
94 })
95 .is_ok()
96 }),
97 Self::Joined { column, lookup } => match row.get(column) {
98 None => true,
99 Some(Value::Null) if !lookup.nulls() => false,
102 Some(value) => lookups(Judging::Partner(lookup, value))?,
103 },
104 Self::Row(condition) => match condition.question(row) {
107 None => true,
108 Some((sql, parameters)) => lookups(Judging::Row(&sql, ¶meters))?,
109 },
110 Self::Window(window) => match window.question(row) {
111 WindowQuestion::Answered(passes) => passes,
112 WindowQuestion::Ask(sql, parameters) => lookups(Judging::Row(&sql, ¶meters))?,
113 },
114 Self::And(left, right) => left.matches(row, lookups)? && right.matches(row, lookups)?,
115 Self::Or(left, right) => left.matches(row, lookups)? || right.matches(row, lookups)?,
116 })
117 }
118
119 pub fn equal(column: String, mut values: Vec<Value>) -> Self {
121 values.retain(|value| !matches!(value, Value::Null));
122 values.sort_by(|left, right| compare(left, right).expect("NULLs were left out"));
123 values.dedup_by(|left, right| compare(left, right).is_some_and(Ordering::is_eq));
124 Self::In { column, values }
125 }
126
127 pub(crate) fn equal_values(&self, column: &str) -> Option<Vec<Value>> {
131 match self {
132 Self::In { column: tested, values } if tested == column => Some(values.clone()),
133 Self::Compare {
134 column: tested,
135 value,
136 ordering: Ordering::Equal,
137 inclusive: false,
138 } if tested == column => Some(vec![value.clone()]),
139 Self::And(left, right) => {
140 left.equal_values(column).or_else(|| right.equal_values(column))
141 }
142 Self::Or(left, right) => {
143 let mut values = left.equal_values(column)?;
144 values.extend(right.equal_values(column)?);
145 Some(values)
146 }
147 _ => None,
148 }
149 }
150
151 pub(crate) fn key(&self) -> Option<(&str, Vec<Value>)> {
157 let mut columns = Vec::new();
158 self.equality_columns(&mut columns);
159 columns.into_iter().find_map(|column| Some((column, self.equal_values(column)?)))
160 }
161
162 fn equality_columns<'a>(&'a self, into: &mut Vec<&'a str>) {
164 match self {
165 Self::In { column, .. }
166 | Self::Compare { column, ordering: Ordering::Equal, inclusive: false, .. } => {
167 into.push(column);
168 }
169 Self::And(left, right) | Self::Or(left, right) => {
170 left.equality_columns(into);
171 right.equality_columns(into);
172 }
173 Self::All
174 | Self::Compare { .. }
175 | Self::Null { .. }
176 | Self::Row(_)
177 | Self::Joined { .. }
178 | Self::Window(_) => {}
179 }
180 }
181
182 pub fn columns(&self, into: &mut std::collections::BTreeSet<String>) {
184 match self {
185 Self::All => {}
186 Self::Compare { column, .. }
187 | Self::Null { column, .. }
188 | Self::In { column, .. }
189 | Self::Joined { column, .. } => {
190 into.insert(column.clone());
191 }
192 Self::Row(condition) => {
193 into.extend(condition.term.columns.iter().map(|(column, _)| column.clone()));
194 }
195 Self::Window(window) => into.extend(window.columns().cloned()),
196 Self::And(left, right) | Self::Or(left, right) => {
197 left.columns(into);
198 right.columns(into);
199 }
200 }
201 }
202
203 pub fn and(self, other: Self) -> Self {
205 match (self, other) {
206 (Self::All, scope) | (scope, Self::All) => scope,
207 (left, right) => Self::And(Box::new(left), Box::new(right)),
208 }
209 }
210
211 pub(crate) fn or(self, other: Self) -> Self {
213 match (self, other) {
214 (Self::All, _) | (_, Self::All) => Self::All,
215 (left, right) => Self::Or(Box::new(left), Box::new(right)),
216 }
217 }
218}
219
220pub struct Scopes {
227 pub(crate) tables: BTreeMap<String, RowScope>,
228 pub(crate) inlined: BTreeSet<String>,
229 pub(crate) fts5_shadows: BTreeSet<String>,
232 pub(crate) unreported: std::sync::Arc<crate::unreported_columns::UnreportedColumns>,
237}
238
239impl Default for Scopes {
240 fn default() -> Self {
242 Self {
243 tables: BTreeMap::new(),
244 inlined: BTreeSet::new(),
245 fts5_shadows: BTreeSet::new(),
246 unreported: std::sync::Arc::new(crate::unreported_columns::UnreportedColumns::Known(
247 crate::read_set::ColumnSet::new(),
248 )),
249 }
250 }
251}
252
253#[derive(Clone, Debug, PartialEq)]
256pub struct RowImage {
257 columns: Arc<[String]>,
259 values: Vec<Option<Value>>,
261}
262
263impl RowImage {
264 pub fn new(columns: Arc<[String]>, values: Vec<Option<Value>>) -> Self {
266 assert_eq!(columns.len(), values.len(), "one value per column");
267 Self { columns, values }
268 }
269
270 pub(crate) fn get(&self, column: &str) -> Option<&Value> {
272 self.columns
273 .iter()
274 .position(|name| name == column)
275 .and_then(|index| self.values[index].as_ref())
276 }
277}
278
279pub(crate) fn compare(left: &Value, right: &Value) -> Option<Ordering> {
283 fn rank(value: &Value) -> u8 {
284 match value {
285 Value::Null => 0,
286 Value::Integer(_) | Value::Real(_) => 1,
287 Value::Text(_) => 2,
288 Value::Blob(_) => 3,
289 }
290 }
291 match (left, right) {
292 (Value::Null, _) | (_, Value::Null) => None,
293 (Value::Text(left), Value::Text(right)) => Some(left.cmp(right)),
294 (Value::Blob(left), Value::Blob(right)) => Some(left.cmp(right)),
295 (Value::Integer(left), Value::Integer(right)) => Some(left.cmp(right)),
296 (Value::Real(left), Value::Real(right)) => Some(compare_reals(*left, *right)),
297 (Value::Integer(left), Value::Real(right)) => Some(compare_integer_real(*left, *right)),
298 (Value::Real(left), Value::Integer(right)) => {
299 Some(compare_integer_real(*right, *left).reverse())
300 }
301 _ => Some(rank(left).cmp(&rank(right))),
302 }
303}
304
305fn compare_reals(left: f64, right: f64) -> Ordering {
307 left.partial_cmp(&right).expect("SQLite stores no NaN")
308}
309
310fn compare_integer_real(integer: i64, real: f64) -> Ordering {
313 if real < -9_223_372_036_854_775_808.0 {
315 return Ordering::Greater;
316 }
317 if real >= 9_223_372_036_854_775_808.0 {
318 return Ordering::Less;
319 }
320 let whole = real as i64;
322 integer.cmp(&whole).then_with(|| compare_reals(whole as f64, real))
323}
324
325#[cfg(test)]
326#[path = "row_scope_tests.rs"]
327mod tests;