Skip to main content

link_cli/graphql/
tables.rs

1//! The tables of the Deep schema: their relations, as Hasura's metadata
2//! declares them, and how rows are compared.
3
4use regex_lite::RegexBuilder;
5
6use super::json::Json;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct Relation {
10    pub local: &'static str,
11    pub target: &'static str,
12    pub remote: &'static str,
13    /// An array relation yields many rows, an object relation at most one.
14    pub many: bool,
15}
16
17const fn one(local: &'static str, target: &'static str, remote: &'static str) -> Relation {
18    Relation {
19        local,
20        target,
21        remote,
22        many: false,
23    }
24}
25
26const fn many(local: &'static str, target: &'static str, remote: &'static str) -> Relation {
27    Relation {
28        local,
29        target,
30        remote,
31        many: true,
32    }
33}
34
35pub const TABLES: [&str; 10] = [
36    "links",
37    "strings",
38    "numbers",
39    "objects",
40    "can",
41    "tree",
42    "selectors",
43    "handlers",
44    "mp",
45    "healthz",
46];
47
48pub fn relation(table: &str, name: &str) -> Option<Relation> {
49    Some(match (table, name) {
50        ("links", "from") => one("from_id", "links", "id"),
51        ("links", "to") => one("to_id", "links", "id"),
52        ("links", "type") => one("type_id", "links", "id"),
53        ("links", "string") => one("id", "strings", "link_id"),
54        ("links", "number") => one("id", "numbers", "link_id"),
55        ("links", "object") => one("id", "objects", "link_id"),
56        ("links", "in") => many("id", "links", "to_id"),
57        ("links", "out") => many("id", "links", "from_id"),
58        ("links", "typed") => many("id", "links", "type_id"),
59        ("links", "can_action") => many("id", "can", "action_id"),
60        ("links", "can_object") => many("id", "can", "object_id"),
61        ("links", "can_rule") => many("id", "can", "rule_id"),
62        ("links", "can_subject") => many("id", "can", "subject_id"),
63        ("links", "down") => many("id", "tree", "parent_id"),
64        ("links", "up") => many("id", "tree", "link_id"),
65        ("links", "tree") => many("id", "tree", "tree_id"),
66        ("links", "root") => many("id", "tree", "root_id"),
67        ("links", "selected") => many("id", "selectors", "selector_id"),
68        ("links", "selectors") => many("id", "selectors", "item_id"),
69        ("links", "_by_group") => many("id", "mp", "group_id"),
70        ("links", "_by_item") => many("id", "mp", "item_id"),
71        ("links", "_by_path_item") => many("id", "mp", "path_item_id"),
72        ("links", "_by_root") => many("id", "mp", "root_id"),
73        ("strings" | "numbers" | "objects", "link") => one("link_id", "links", "id"),
74        ("can", "action") => one("action_id", "links", "id"),
75        ("can", "object") => one("object_id", "links", "id"),
76        ("can", "rule") => one("rule_id", "links", "id"),
77        ("can", "subject") => one("subject_id", "links", "id"),
78        ("tree", "link") => one("link_id", "links", "id"),
79        ("tree", "parent") => one("parent_id", "links", "id"),
80        ("tree", "root") => one("root_id", "links", "id"),
81        ("tree", "tree" | "by_tree") => one("tree_id", "links", "id"),
82        ("tree", "by_link") => many("link_id", "tree", "link_id"),
83        ("tree", "by_parent") => many("parent_id", "tree", "parent_id"),
84        ("tree", "by_position") => many("position_id", "tree", "position_id"),
85        ("tree", "by_root") => many("root_id", "tree", "root_id"),
86        ("selectors", "item") => one("item_id", "links", "id"),
87        ("selectors", "selector") => one("selector_id", "links", "id"),
88        ("selectors", "query") => many("query_id", "links", "id"),
89        ("handlers", "dist") => one("dist_id", "links", "id"),
90        ("handlers", "execution_provider") => one("execution_provider_id", "links", "id"),
91        ("handlers", "handler") => one("handler_id", "links", "id"),
92        ("handlers", "isolation_provider") => one("isolation_provider_id", "links", "id"),
93        ("handlers", "src") => one("src_id", "links", "id"),
94        _ => return None,
95    })
96}
97
98pub fn columns(table: &str) -> &'static [&'static str] {
99    match table {
100        "links" => &["id", "type_id", "from_id", "to_id"],
101        "strings" | "numbers" | "objects" => &["id", "link_id", "value"],
102        "can" => &["rule_id", "action_id", "object_id", "subject_id"],
103        "tree" => &[
104            "id",
105            "link_id",
106            "tree_id",
107            "root_id",
108            "parent_id",
109            "depth",
110            "position_id",
111            "self",
112        ],
113        "selectors" => &["item_id", "selector_id", "selector_include_id", "query_id"],
114        "handlers" => &[
115            "dist_id",
116            "src_id",
117            "handler_id",
118            "isolation_provider_id",
119            "execution_provider_id",
120        ],
121        "mp" => &[
122            "id",
123            "item_id",
124            "path_item_id",
125            "path_item_depth",
126            "root_id",
127            "position_id",
128            "group_id",
129        ],
130        "healthz" => &["status"],
131        _ => &[],
132    }
133}
134
135/// Numbers compare as numbers, whatever way they were written.
136pub fn compare(left: &Json, right: &Json) -> Option<std::cmp::Ordering> {
137    match (left, right) {
138        (Json::String(left), Json::String(right)) => Some(left.cmp(right)),
139        (Json::Bool(left), Json::Bool(right)) => Some(left.cmp(right)),
140        _ => left.as_f64()?.partial_cmp(&right.as_f64()?),
141    }
142}
143
144/// SQL's `LIKE`: `%` is any run and `_` any one character.
145fn like(text: &str, pattern: &str, insensitive: bool) -> bool {
146    let fold = |value: &str| -> Vec<char> {
147        if insensitive {
148            value.to_lowercase().chars().collect()
149        } else {
150            value.chars().collect()
151        }
152    };
153    let (text, pattern) = (fold(text), fold(pattern));
154    let (mut at, mut position) = (0, 0);
155    let mut retry = None;
156    while at < text.len() {
157        match pattern.get(position) {
158            Some('%') => {
159                retry = Some((at, position));
160                position += 1;
161            }
162            Some(&expected) if expected == '_' || expected == text[at] => {
163                at += 1;
164                position += 1;
165            }
166            _ => match retry {
167                Some((from, star)) => {
168                    at = from + 1;
169                    retry = Some((from + 1, star));
170                    position = star + 1;
171                }
172                None => return false,
173            },
174        }
175    }
176    pattern[position..]
177        .iter()
178        .all(|&character| character == '%')
179}
180
181fn regex(text: &str, pattern: &str, insensitive: bool) -> bool {
182    RegexBuilder::new(pattern)
183        .case_insensitive(insensitive)
184        .build()
185        .map(|regex| regex.is_match(text))
186        .unwrap_or(false)
187}
188
189fn contains(outer: &Json, inner: &Json) -> bool {
190    match (outer, inner) {
191        (Json::Object(_), Json::Object(pairs)) => pairs
192            .iter()
193            .all(|(key, value)| outer.get(key).is_some_and(|found| contains(found, value))),
194        (Json::Array(items), Json::Array(wanted)) => wanted
195            .iter()
196            .all(|item| items.iter().any(|found| contains(found, item))),
197        (left, right) => compare(left, right) == Some(std::cmp::Ordering::Equal) || left == right,
198    }
199}
200
201/// Whether a column's value passes `{_op: argument}`; SQL's null compares
202/// false to everything but `_is_null`.
203pub fn passes(value: &Json, operator: &str, argument: &Json) -> Result<bool, String> {
204    use std::cmp::Ordering::{Equal, Greater, Less};
205    if operator == "_is_null" {
206        return Ok(value.is_null() == matches!(argument, Json::Bool(true)));
207    }
208    if value.is_null() {
209        return Ok(false);
210    }
211    let text = value.as_str().unwrap_or("");
212    let pattern = argument.as_str().unwrap_or("");
213    Ok(match operator {
214        "_eq" => compare(value, argument) == Some(Equal) || value == argument,
215        "_neq" => {
216            compare(value, argument) != Some(Equal) && value != argument && !argument.is_null()
217        }
218        "_gt" => compare(value, argument) == Some(Greater),
219        "_gte" => matches!(compare(value, argument), Some(Greater | Equal)),
220        "_lt" => compare(value, argument) == Some(Less),
221        "_lte" => matches!(compare(value, argument), Some(Less | Equal)),
222        "_in" => argument
223            .as_list()
224            .iter()
225            .any(|item| compare(value, item) == Some(Equal)),
226        "_nin" => !argument
227            .as_list()
228            .iter()
229            .any(|item| compare(value, item) == Some(Equal)),
230        "_like" => like(text, pattern, false),
231        "_nlike" => !like(text, pattern, false),
232        "_ilike" => like(text, pattern, true),
233        "_nilike" => !like(text, pattern, true),
234        "_regex" => regex(text, pattern, false),
235        "_nregex" => !regex(text, pattern, false),
236        "_iregex" => regex(text, pattern, true),
237        "_niregex" => !regex(text, pattern, true),
238        "_contains" => contains(value, argument),
239        "_contained_in" => contains(argument, value),
240        "_has_key" => value.get(pattern).is_some(),
241        other => {
242            return Err(format!(
243                "field '{other}' not found in type: 'comparison_exp'"
244            ))
245        }
246    })
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn like_handles_wildcards_and_case() {
255        assert!(like("Hello", "H%o", false));
256        assert!(like("Hello", "_ello", false));
257        assert!(!like("Hello", "h%", false));
258        assert!(like("Hello", "h%", true));
259    }
260
261    #[test]
262    fn null_passes_only_is_null() {
263        assert!(passes(&Json::Null, "_is_null", &Json::Bool(true)).unwrap());
264        assert!(!passes(&Json::Null, "_neq", &Json::Int(1)).unwrap());
265    }
266}