1use std::cmp::Ordering;
7use std::sync::Arc;
8
9use crate::row_scope::{compare, RowScope};
10use crate::scope_row::{RowCondition, RowTerm, RowTest};
11use crate::sql_value::SqlValue as Value;
12use rusqlite::Connection;
13use sqlite3_parser::ast::{Expr, Literal, Operator, UnaryOperator};
14
15#[derive(Clone)]
18pub(crate) enum ScopeTerm {
19 Compare {
20 column: String,
21 affinity: Affinity,
22 operand: Operand,
23 ordering: Ordering,
24 inclusive: bool,
25 },
26 In {
27 column: String,
28 affinity: Affinity,
29 operands: Vec<Operand>,
30 },
31 Null {
33 column: String,
34 not: bool,
35 },
36 Truth {
40 condition: Truth,
41 ordering: Ordering,
44 inclusive: bool,
45 is: bool,
46 operand: Operand,
47 },
48 Row(Arc<RowTerm>),
51 Is {
54 column: String,
55 affinity: Affinity,
56 operand: Operand,
57 },
58 And(Box<Self>, Box<Self>),
59 Or(Box<Self>, Box<Self>),
60}
61
62impl ScopeTerm {
63 pub(crate) fn bind(&self, parameters: &[Value]) -> Option<RowScope> {
66 match self {
67 Self::Compare { column, affinity, operand, ordering, inclusive } => {
68 let value = operand.value(parameters);
69 affinity.compares(value).then(|| RowScope::Compare {
70 column: column.clone(),
71 value: value.clone(),
72 ordering: *ordering,
73 inclusive: *inclusive,
74 })
75 }
76 Self::In { column, affinity, operands } => {
77 let values: Vec<Value> =
78 operands.iter().map(|operand| operand.value(parameters).clone()).collect();
79 values
80 .iter()
81 .all(|value| affinity.compares(value))
82 .then(|| RowScope::equal(column.clone(), values))
83 }
84 Self::Null { column, not } => {
85 Some(RowScope::Null { column: column.clone(), not: *not })
86 }
87 Self::Row(term) => Some(RowScope::Row(Arc::new(RowCondition {
88 term: Arc::clone(term),
89 parameters: parameters.to_vec(),
90 test: RowTest::Holds,
91 }))),
92 Self::Truth { condition, ordering, inclusive, is, operand } => {
93 let value = operand.value(parameters);
94 let passes = |truth: Option<i64>| match (truth, value) {
95 (None, value) => *is && matches!(value, Value::Null),
96 (Some(_), Value::Null) => false,
97 (Some(truth), value) => {
98 compare(&Value::Integer(truth), value).is_some_and(|found| {
99 if *is {
100 found.is_eq()
101 } else {
102 found == *ordering || (*inclusive && found.is_eq())
103 }
104 })
105 }
106 };
107 let mut scope = None;
108 for (truth, holds) in [(Some(1), true), (Some(0), false), (None, false)] {
109 if !passes(truth) {
110 continue;
111 }
112 let found = match truth {
113 None => condition.when_null(parameters),
114 _ => condition.when(holds, parameters),
115 }?;
116 scope = Some(match scope {
117 Some(other) => RowScope::or(other, found),
118 None => found,
119 });
120 }
121 Some(
122 scope.unwrap_or_else(|| RowScope::equal(condition.column().to_owned(), vec![])),
123 )
124 }
125 Self::Is { column, affinity, operand } => {
126 let value = operand.value(parameters);
127 if matches!(value, Value::Null) {
128 Some(RowScope::Null { column: column.clone(), not: false })
129 } else {
130 affinity.compares(value).then(|| RowScope::Compare {
131 column: column.clone(),
132 value: value.clone(),
133 ordering: Ordering::Equal,
134 inclusive: false,
135 })
136 }
137 }
138 Self::And(left, right) => match (left.bind(parameters), right.bind(parameters)) {
139 (Some(left), Some(right)) => Some(left.and(right)),
140 (scope, None) | (None, scope) => scope,
141 },
142 Self::Or(left, right) => Some(left.bind(parameters)?.or(right.bind(parameters)?)),
143 }
144 }
145
146 pub(crate) fn may_hold_on_nulls(&self) -> bool {
151 match self {
152 Self::Compare { .. } | Self::In { .. } => false,
153 Self::Null { not, .. } => !not,
154 Self::Is { .. } | Self::Truth { .. } | Self::Row(_) => true,
155 Self::And(left, right) => left.may_hold_on_nulls() && right.may_hold_on_nulls(),
156 Self::Or(left, right) => left.may_hold_on_nulls() || right.may_hold_on_nulls(),
157 }
158 }
159
160 pub(crate) fn and(self, other: Self) -> Self {
162 Self::And(Box::new(self), Box::new(other))
163 }
164
165 pub(crate) fn add_to(found: &mut Option<Self>, term: Self) {
168 *found = Some(match found.take() {
169 Some(existing) => existing.and(term),
170 None => term,
171 });
172 }
173
174 pub(crate) fn columns(&self, into: &mut Vec<String>) {
176 match self {
177 Self::Compare { column, .. }
178 | Self::In { column, .. }
179 | Self::Null { column, .. }
180 | Self::Is { column, .. } => {
181 if !into.contains(column) {
182 into.push(column.clone());
183 }
184 }
185 Self::Truth { condition, .. } => {
186 if !into.iter().any(|column| column == condition.column()) {
187 into.push(condition.column().to_owned());
188 }
189 }
190 Self::Row(term) => {
191 for (column, _) in &term.columns {
192 if !into.contains(column) {
193 into.push(column.clone());
194 }
195 }
196 }
197 Self::And(left, right) | Self::Or(left, right) => {
198 left.columns(into);
199 right.columns(into);
200 }
201 }
202 }
203
204 pub(crate) fn renamed(&self, column: &dyn Fn(&str) -> Option<String>) -> Option<Self> {
209 match self {
210 Self::Compare { column: tested, affinity, operand, ordering, inclusive } => {
211 Some(Self::Compare {
212 column: column(tested)?,
213 affinity: *affinity,
214 operand: operand.clone(),
215 ordering: *ordering,
216 inclusive: *inclusive,
217 })
218 }
219 Self::In { column: tested, affinity, operands } => Some(Self::In {
220 column: column(tested)?,
221 affinity: *affinity,
222 operands: operands.clone(),
223 }),
224 Self::Null { column: tested, not } => {
225 Some(Self::Null { column: column(tested)?, not: *not })
226 }
227 Self::Row(_) => None,
230 Self::Truth { condition, ordering, inclusive, is, operand } => Some(Self::Truth {
231 condition: condition.renamed(column)?,
232 ordering: *ordering,
233 inclusive: *inclusive,
234 is: *is,
235 operand: operand.clone(),
236 }),
237 Self::Is { column: tested, affinity, operand } => Some(Self::Is {
238 column: column(tested)?,
239 affinity: *affinity,
240 operand: operand.clone(),
241 }),
242 Self::And(left, right) => match (left.renamed(column), right.renamed(column)) {
243 (Some(left), Some(right)) => Some(left.and(right)),
244 (term, None) | (None, term) => term,
245 },
246 Self::Or(left, right) => {
247 Some(Self::Or(Box::new(left.renamed(column)?), Box::new(right.renamed(column)?)))
248 }
249 }
250 }
251}
252
253#[derive(Clone)]
257pub(crate) enum Truth {
258 Null {
259 column: String,
260 not: bool,
261 },
262 Compare {
263 column: String,
264 affinity: Affinity,
265 operand: Operand,
266 ordering: Ordering,
267 inclusive: bool,
268 },
269}
270
271impl Truth {
272 fn column(&self) -> &str {
273 match self {
274 Self::Null { column, .. } | Self::Compare { column, .. } => column,
275 }
276 }
277
278 fn renamed(&self, rename: &dyn Fn(&str) -> Option<String>) -> Option<Self> {
279 Some(match self {
280 Self::Null { column, not } => Self::Null { column: rename(column)?, not: *not },
281 Self::Compare { column, affinity, operand, ordering, inclusive } => Self::Compare {
282 column: rename(column)?,
283 affinity: *affinity,
284 operand: operand.clone(),
285 ordering: *ordering,
286 inclusive: *inclusive,
287 },
288 })
289 }
290
291 fn when(&self, holds: bool, parameters: &[Value]) -> Option<RowScope> {
294 match self {
295 Self::Null { column, not } => {
296 Some(RowScope::Null { column: column.clone(), not: *not == holds })
297 }
298 Self::Compare { column, affinity, operand, ordering, inclusive } => {
299 let value = operand.value(parameters);
300 if !affinity.compares(value) {
301 return None;
302 }
303 if matches!(value, Value::Null) {
305 return Some(RowScope::equal(column.clone(), vec![]));
306 }
307 let compare = |ordering, inclusive| RowScope::Compare {
308 column: column.clone(),
309 value: value.clone(),
310 ordering,
311 inclusive,
312 };
313 Some(match (holds, ordering) {
314 (true, _) => compare(*ordering, *inclusive),
315 (false, Ordering::Equal) => RowScope::or(
317 compare(Ordering::Less, false),
318 compare(Ordering::Greater, false),
319 ),
320 (false, ordering) => compare(ordering.reverse(), !inclusive),
321 })
322 }
323 }
324 }
325
326 fn when_null(&self, parameters: &[Value]) -> Option<RowScope> {
328 match self {
329 Self::Null { column, .. } => Some(RowScope::equal(column.clone(), vec![])),
331 Self::Compare { column, affinity, operand, .. } => {
332 let value = operand.value(parameters);
333 if !affinity.compares(value) {
334 return None;
335 }
336 Some(if matches!(value, Value::Null) {
337 RowScope::All
338 } else {
339 RowScope::Null { column: column.clone(), not: false }
340 })
341 }
342 }
343 }
344}
345
346#[derive(Clone, Debug)]
348pub(crate) enum Operand {
349 Constant(Value),
350 Parameter(usize),
352}
353
354impl Operand {
355 pub(crate) fn value<'a>(&'a self, parameters: &'a [Value]) -> &'a Value {
356 match self {
357 Self::Constant(value) => value,
358 Self::Parameter(index) => ¶meters[*index],
359 }
360 }
361}
362
363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
365pub enum Affinity {
366 Numeric,
368 Text,
370 Blob,
372}
373
374impl Affinity {
375 pub fn declared(declared: &str) -> Self {
377 let declared = declared.to_ascii_uppercase();
378 if declared.contains("INT") {
379 Self::Numeric
380 } else if ["CHAR", "CLOB", "TEXT"].iter().any(|word| declared.contains(word)) {
381 Self::Text
382 } else if declared.contains("BLOB") || declared.is_empty() {
383 Self::Blob
384 } else {
385 Self::Numeric
386 }
387 }
388
389 pub(crate) fn compares(self, value: &Value) -> bool {
393 matches!(
394 (self, value),
395 (_, Value::Null | Value::Blob(_))
396 | (Self::Blob, _)
397 | (Self::Numeric, Value::Integer(_) | Value::Real(_))
398 | (Self::Text, Value::Text(_))
399 )
400 }
401}
402
403pub(crate) type SourceColumn<'a> = dyn Fn(&Expr<'_>) -> Option<(String, Affinity)> + 'a;
407
408pub(crate) fn term(
411 connection: &Connection,
412 column: &SourceColumn<'_>,
413 expr: &Expr<'_>,
414) -> rusqlite::Result<Option<ScopeTerm>> {
415 let expr = crate::sql::unparenthesized(expr);
416 if let Some((tested, not)) = null_test(expr) {
417 if let Some((named, _)) = column(through_collation(tested)) {
418 return Ok(Some(ScopeTerm::Null { column: named, not }));
419 }
420 }
421 if let Expr::Binary(
422 left,
423 op @ (Operator::Equals
424 | Operator::Less
425 | Operator::LessEquals
426 | Operator::Greater
427 | Operator::GreaterEquals
428 | Operator::Is),
429 right,
430 ) = expr
431 {
432 if let Some(truth) = truth(connection, column, left, *op, right)? {
433 return Ok(Some(truth));
434 }
435 }
436 let result = match expr {
437 Expr::Binary(left, op @ (Operator::And | Operator::Or), right) => {
438 match (term(connection, column, left)?, term(connection, column, right)?) {
439 (Some(left), Some(right)) => Some(if *op == Operator::And {
440 left.and(right)
441 } else {
442 ScopeTerm::Or(Box::new(left), Box::new(right))
443 }),
444 (Some(found), None) | (None, Some(found)) if *op == Operator::And => Some(found),
445 _ => None,
446 }
447 }
448 Expr::Binary(left, op, right) => {
449 let (named, operand_expr, reverse) = if let Some(named) = column(left) {
450 (named, right, false)
451 } else if let Some(named) = column(right) {
452 (named, left, true)
453 } else {
454 return Ok(None);
455 };
456 let (mut ordering, inclusive) = match op {
457 Operator::Equals | Operator::Is => (Ordering::Equal, false),
458 Operator::Less => (Ordering::Less, false),
459 Operator::LessEquals => (Ordering::Less, true),
460 Operator::Greater => (Ordering::Greater, false),
461 Operator::GreaterEquals => (Ordering::Greater, true),
462 _ => return Ok(None),
463 };
464 if reverse {
465 ordering = ordering.reverse();
466 }
467 let (named, affinity) = named;
468 operand(connection, operand_expr, affinity)?.map(|operand| {
469 if *op == Operator::Is && matches!(operand, Operand::Parameter(_)) {
472 ScopeTerm::Is { column: named, affinity, operand }
473 } else {
474 ScopeTerm::Compare { column: named, affinity, operand, ordering, inclusive }
475 }
476 })
477 }
478 Expr::InList { lhs, not: false, rhs } => {
479 let Some((named, affinity)) = column(lhs) else {
480 return Ok(None);
481 };
482 let mut operands = Vec::new();
483 for expr in rhs.iter().flat_map(|exprs| exprs.iter()) {
484 let Some(operand) = operand(connection, expr, affinity)? else {
485 return Ok(None);
486 };
487 operands.push(operand);
488 }
489 Some(ScopeTerm::In { column: named, affinity, operands })
490 }
491 _ => None,
492 };
493 Ok(result)
494}
495
496fn truth(
500 connection: &Connection,
501 column: &SourceColumn<'_>,
502 left: &Expr<'_>,
503 op: Operator,
504 right: &Expr<'_>,
505) -> rusqlite::Result<Option<ScopeTerm>> {
506 let (condition_expr, value_expr, reversed) =
507 match (condition(connection, column, left)?, condition(connection, column, right)?) {
508 (Some(condition), None) => (condition, right, false),
509 (None, Some(condition)) => (condition, left, true),
510 _ => return Ok(None),
511 };
512 let (ordering, inclusive) = match op {
513 Operator::Equals | Operator::Is => (Ordering::Equal, false),
514 Operator::Less => (Ordering::Less, false),
515 Operator::LessEquals => (Ordering::Less, true),
516 Operator::Greater => (Ordering::Greater, false),
517 _ => (Ordering::Greater, true),
518 };
519 let ordering = if reversed { ordering.reverse() } else { ordering };
520 let operand = if matches!(crate::sql::unparenthesized(value_expr), Expr::Literal(Literal::Null))
522 {
523 Some(Operand::Constant(Value::Null))
524 } else {
525 operand(connection, value_expr, Affinity::Blob)?
526 };
527 Ok(operand.map(|operand| ScopeTerm::Truth {
528 condition: condition_expr,
529 ordering,
530 inclusive,
531 is: op == Operator::Is,
532 operand,
533 }))
534}
535
536fn condition(
538 connection: &Connection,
539 column: &SourceColumn<'_>,
540 expr: &Expr<'_>,
541) -> rusqlite::Result<Option<Truth>> {
542 let expr = crate::sql::unparenthesized(expr);
543 if let Some((tested, not)) = null_test(expr) {
544 return Ok(
545 column(through_collation(tested)).map(|(named, _)| Truth::Null { column: named, not })
546 );
547 }
548 let Expr::Binary(left, op, right) = expr else {
549 return Ok(None);
550 };
551 let (mut ordering, inclusive) = match op {
552 Operator::Equals => (Ordering::Equal, false),
553 Operator::Less => (Ordering::Less, false),
554 Operator::LessEquals => (Ordering::Less, true),
555 Operator::Greater => (Ordering::Greater, false),
556 Operator::GreaterEquals => (Ordering::Greater, true),
557 _ => return Ok(None),
558 };
559 let ((named, affinity), operand_expr) = if let Some(named) = column(left) {
560 (named, *right)
561 } else if let Some(named) = column(right) {
562 ordering = ordering.reverse();
563 (named, *left)
564 } else {
565 return Ok(None);
566 };
567 Ok(operand(connection, operand_expr, affinity)?.map(|operand| Truth::Compare {
568 column: named,
569 affinity,
570 operand,
571 ordering,
572 inclusive,
573 }))
574}
575
576fn null_test<'a>(expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, bool)> {
580 let is_null =
581 |expr: &Expr<'_>| matches!(crate::sql::unparenthesized(expr), Expr::Literal(Literal::Null));
582 match expr {
583 Expr::IsNull(tested) => Some((tested, false)),
584 Expr::NotNull(tested) => Some((tested, true)),
585 Expr::Binary(left, op @ (Operator::Is | Operator::IsNot), right) => {
586 let not = *op == Operator::IsNot;
587 if is_null(right) {
588 Some((left, not))
589 } else if is_null(left) {
590 Some((right, not))
591 } else {
592 None
593 }
594 }
595 _ => None,
596 }
597}
598
599fn through_collation<'a>(expr: &'a Expr<'a>) -> &'a Expr<'a> {
602 match crate::sql::unparenthesized(expr) {
603 Expr::Collate(inner, _) => through_collation(inner),
604 expr => expr,
605 }
606}
607
608pub(crate) fn operand(
611 connection: &Connection,
612 expr: &Expr<'_>,
613 affinity: Affinity,
614) -> rusqlite::Result<Option<Operand>> {
615 let expr = crate::sql::unparenthesized(expr);
616 if let Expr::Variable(index) = expr {
617 return Ok(Some(Operand::Parameter(
618 index.parse::<usize>().expect("parameters were numbered before parsing") - 1,
619 )));
620 }
621 match expr {
622 Expr::Literal(Literal::Numeric(_) | Literal::String(_) | Literal::Blob(_))
623 | Expr::Unary(
624 UnaryOperator::Negative | UnaryOperator::Positive,
625 Expr::Literal(Literal::Numeric(_)),
626 ) => {}
627 _ => return Ok(None),
628 }
629 let value =
632 connection.query_row(&format!("SELECT {expr}"), [], |row| row.get::<_, Value>(0))?;
633 Ok(affinity.compares(&value).then_some(Operand::Constant(value)))
634}
635
636#[cfg(test)]
637#[path = "scope_term_tests.rs"]
638mod tests;