Skip to main content

trailbase_qs/
value.rs

1use std::str::FromStr;
2
3#[derive(Clone, Debug, PartialEq)]
4pub enum Value {
5  // Note that bytes are also strings, either UUID or url-safe-b64 encoded. Need to be decoded
6  // downstream based on content.
7  String(String),
8  Integer(i64),
9  Double(f64),
10}
11
12impl Value {
13  pub(crate) fn unparse(value: String) -> Self {
14    return if let Ok(i) = i64::from_str(&value) {
15      Value::Integer(i)
16    } else if let Ok(d) = f64::from_str(&value) {
17      Value::Double(d)
18    } else {
19      Value::String(value)
20    };
21  }
22}
23
24impl std::fmt::Display for Value {
25  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
26    return match self {
27      Self::String(s) => s.fmt(f),
28      Self::Integer(i) => i.fmt(f),
29      Self::Double(d) => d.fmt(f),
30    };
31  }
32}
33
34#[cfg(test)]
35mod tests {
36  use super::*;
37
38  use serde::Deserialize;
39  use serde_qs::Config;
40
41  use crate::column_rel_value::{ColumnOpValue, CompareOp};
42  use crate::filter::ValueOrComposite;
43
44  #[derive(Clone, Debug, Default, Deserialize)]
45  struct Query {
46    filter: Option<ValueOrComposite>,
47  }
48
49  #[test]
50  fn test_value() {
51    let qs = Config::new(5, false);
52
53    assert_eq!(
54      qs.deserialize_str::<Query>("filter[col0][$eq]=val0")
55        .unwrap()
56        .filter
57        .unwrap(),
58      ValueOrComposite::Value(ColumnOpValue {
59        column: "col0".to_string(),
60        op: CompareOp::Equal,
61        value: Value::String("val0".to_string()),
62      })
63    );
64
65    assert_eq!(
66      qs.deserialize_str::<Query>("filter[col0][$ne]=TRUE")
67        .unwrap()
68        .filter
69        .unwrap(),
70      ValueOrComposite::Value(ColumnOpValue {
71        column: "col0".to_string(),
72        op: CompareOp::NotEqual,
73        value: Value::String("TRUE".to_string()),
74      })
75    );
76
77    assert_eq!(
78      qs.deserialize_str::<Query>("filter[col0][$ne]=0")
79        .unwrap()
80        .filter
81        .unwrap(),
82      ValueOrComposite::Value(ColumnOpValue {
83        column: "col0".to_string(),
84        op: CompareOp::NotEqual,
85        value: Value::Integer(0),
86      })
87    );
88
89    assert_eq!(
90      qs.deserialize_str::<Query>("filter[col0][$ne]=0.0")
91        .unwrap()
92        .filter
93        .unwrap(),
94      ValueOrComposite::Value(ColumnOpValue {
95        column: "col0".to_string(),
96        op: CompareOp::NotEqual,
97        value: Value::Double(0.0),
98      })
99    );
100
101    assert_eq!(
102      qs.deserialize_str::<Query>("filter[col0][$is]=NULL")
103        .unwrap()
104        .filter
105        .unwrap(),
106      ValueOrComposite::Value(ColumnOpValue {
107        column: "col0".to_string(),
108        op: CompareOp::Is,
109        value: Value::String("NULL".to_string()),
110      })
111    );
112  }
113}