1use super::Row;
5use crate::ast::{Direction, OrderPart};
6use crate::compare;
7use crate::json::Value;
8use std::cell::Cell;
9use std::cmp::Ordering;
10use std::rc::Rc;
11
12pub type Comparator = Rc<dyn Fn(&Row, &Row) -> Ordering>;
14
15static NULL: Value = Value::Null;
16
17pub fn value<'a>(row: &'a Row, column: &str) -> &'a Value {
19 row.get(column).unwrap_or(&NULL)
20}
21
22pub fn compare_values(a: Option<&Value>, b: Option<&Value>) -> Ordering {
24 compare::compare(a.unwrap_or(&NULL), b.unwrap_or(&NULL))
25}
26
27pub fn values_equal(a: Option<&Value>, b: Option<&Value>) -> bool {
30 match (a, b) {
31 (Some(a), Some(b)) => compare::equal(a, b),
32 _ => false,
33 }
34}
35
36pub fn identical(a: Option<&Value>, b: Option<&Value>) -> bool {
39 match (a, b) {
40 (None, None) => true,
41 (Some(Value::Null), Some(Value::Null)) => true,
42 (Some(Value::String(x)), Some(Value::String(y))) => x == y,
43 (Some(Value::Number(x)), Some(Value::Number(y))) => x == y,
44 (Some(Value::Bool(x)), Some(Value::Bool(y))) => x == y,
45 _ => false,
46 }
47}
48
49pub fn make_comparator(order: &[OrderPart], reverse: bool) -> Comparator {
51 let parts: Vec<(String, bool, Cell<usize>)> = order
52 .iter()
53 .map(|p| (p.field.clone(), p.direction == Direction::Asc, Cell::new(0)))
54 .collect();
55 Rc::new(move |a: &Row, b: &Row| {
56 for (field, asc, hint) in &parts {
57 let c = compare_values(a.get_hinted(field, hint), b.get_hinted(field, hint));
58 if c != Ordering::Equal {
59 let c = if *asc { c } else { c.reverse() };
60 return if reverse { c.reverse() } else { c };
61 }
62 }
63 Ordering::Equal
64 })
65}