1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#[macro_use]
extern crate lazy_static;
extern crate serde_json;

use std::collections::HashMap;
use serde_json::Value;

mod error;
use error::Error;

type Handle = fn(Vec<String>) -> String;

fn has(operands: Vec<String>) -> String {
    format!("{} IS NOT NULL", operands[0].trim_matches('\''))
}

fn has_not(operands: Vec<String>) -> String {
    format!("{} IS NULL", operands[0].trim_matches('\''))
}

fn eq(operands: Vec<String>) -> String {
    format!("{} = {}", operands[0].trim_matches('\''), operands[1])
}

fn not_eq(operands: Vec<String>) -> String {
    format!("{} <> {}", operands[0].trim_matches('\''), operands[1])
}

fn gt(operands: Vec<String>) -> String {
    format!("{} > {}", operands[0].trim_matches('\''), operands[1])
}

fn gte(operands: Vec<String>) -> String {
    format!("{} >= {}", operands[0].trim_matches('\''), operands[1])
}

fn lt(operands: Vec<String>) -> String {
    format!("{} < {}", operands[0].trim_matches('\''), operands[1])
}

fn lte(operands: Vec<String>) -> String {
    format!("{} <= {}", operands[0].trim_matches('\''), operands[1])
}

fn is_in(operands: Vec<String>) -> String {
    let (key, values) = operands.split_first().unwrap();
    format!("{} IN ({})", key.trim_matches('\''), values.join(", "))
}

fn not_in(operands: Vec<String>) -> String {
    let (key, values) = operands.split_first().unwrap();
    format!("{} NOT IN ({})", key.trim_matches('\''), values.join(", "))
}

fn all(operands: Vec<String>) -> String {
    operands.join(" AND ")
}

fn any(operands: Vec<String>) -> String {
    operands.join(" OR ")
}

lazy_static! {
    static ref OPERATORS: HashMap<&'static str, Handle> = {
        let mut m = HashMap::new();
        m.insert("has", has as Handle);
        m.insert("!has", has_not as Handle);
        m.insert("==", eq as Handle);
        m.insert("!=", not_eq as Handle);
        m.insert(">", gt as Handle);
        m.insert(">=", gte as Handle);
        m.insert("<", lt as Handle);
        m.insert("<=", lte as Handle);
        m.insert("in", is_in as Handle);
        m.insert("!in", not_in as Handle);
        m.insert("all", all as Handle);
        m.insert("any", any as Handle);
        m
    };
}

pub fn to_sql(expression: &Value) -> Result<String, Error> {
    if !expression.is_array() {
        return match expression.clone() {
            Value::String(str) => Ok(format!("'{}'", str)),
            _ => {
                let operand: String = serde_json::to_string(&expression)?;
                Ok(operand)
            }
        };
    }

    let array = expression.as_array().unwrap().as_slice();
    let (operator, operands) = match array.split_first() {
        Some((operator, operands)) => {
            if operator.is_string() {
                (operator.as_str().unwrap(), operands)
            } else {
                return Err(Error::UnknownOperator(operator.to_string()));
            }
        }
        None => return Err(Error::NoOperands),
    };

    let f = match OPERATORS.get(operator) {
        Some(f) => f,
        None => return Err(Error::UnknownOperator(operator.to_string())),
    };

    let str_operands: Vec<String> = operands
        .into_iter()
        .filter_map(|operand| to_sql(operand).ok())
        .collect();

    Ok(f(str_operands))
}

pub fn parse(expression: &str) -> Result<String, Error> {
    let value: Value = serde_json::from_str(expression)?;
    to_sql(&value)
}

#[cfg(test)]
mod tests {
    use super::parse;

    #[test]
    fn test_existential() {
        assert_eq!(parse(r#"["has", "key"]"#).unwrap(), "key IS NOT NULL");
        assert_eq!(parse(r#"["!has", "key"]"#).unwrap(), "key IS NULL");
    }

    #[test]
    fn test_comparison() {
        assert_eq!(parse(r#"["==", "key", 42]"#).unwrap(), r#"key = 42"#);
        assert_eq!(parse(r#"["==", "key", "value"]"#).unwrap(), "key = 'value'");
        assert_eq!(
            parse(r#"["!=", "key", "value"]"#).unwrap(),
            "key <> 'value'"
        );
        assert_eq!(parse(r#"[">", "key", "value"]"#).unwrap(), "key > 'value'");
        assert_eq!(
            parse(r#"[">=", "key", "value"]"#).unwrap(),
            "key >= 'value'"
        );
        assert_eq!(parse(r#"["<", "key", "value"]"#).unwrap(), "key < 'value'");
        assert_eq!(
            parse(r#"["<=", "key", "value"]"#).unwrap(),
            "key <= 'value'"
        );
    }

    #[test]
    fn test_set_membership() {
        assert_eq!(
            parse(r#"["in", "key", "v0", "v1", "v2"]"#).unwrap(),
            "key IN ('v0', 'v1', 'v2')"
        );
        assert_eq!(
            parse(r#"["!in", "key", "v0", "v1", "v2"]"#).unwrap(),
            "key NOT IN ('v0', 'v1', 'v2')"
        );
    }

    #[test]
    fn test_combining() {
        assert_eq!(
            parse(r#"["all", ["==", "key0", "value0"], ["==", "key1", "value1"], ["==", "key2", "value2"]]"#).unwrap(),
            r#"key0 = 'value0' AND key1 = 'value1' AND key2 = 'value2'"#
        );

        assert_eq!(
            parse(r#"["any", ["==", "key0", "value0"], ["==", "key1", "value1"], ["==", "key2", "value2"]]"#).unwrap(),
            r#"key0 = 'value0' OR key1 = 'value1' OR key2 = 'value2'"#
        );
    }
}