Skip to main content

zero_client/ivm/
constraint.rs

1//! Column values a fetch must match (`packages/zql/src/ivm/constraint.ts`).
2
3use super::{Row, values_equal};
4use crate::ast::{Condition, SimpleOperator, ValuePosition};
5use crate::json::Value;
6use crate::strings;
7
8/// Keys keep insertion order, like the JS object: a memory source builds its
9/// index sort from it. A value is `None` where JS has `undefined`.
10#[derive(Clone, Debug, Default, PartialEq)]
11pub struct Constraint {
12    pub entries: Vec<(String, Option<Value>)>,
13}
14
15impl Constraint {
16    pub fn new(entries: Vec<(String, Option<Value>)>) -> Self {
17        Constraint { entries }
18    }
19
20    pub fn keys(&self) -> Vec<&str> {
21        self.entries.iter().map(|(k, _)| k.as_str()).collect()
22    }
23
24    pub fn len(&self) -> usize {
25        self.entries.len()
26    }
27
28    pub fn is_empty(&self) -> bool {
29        self.entries.is_empty()
30    }
31
32    pub fn has(&self, key: &str) -> bool {
33        self.entries.iter().any(|(k, _)| k == key)
34    }
35
36    /// The value for `key`; `None` when absent or `undefined`.
37    pub fn get(&self, key: &str) -> Option<&Value> {
38        self.entries
39            .iter()
40            .find(|(k, _)| k == key)
41            .and_then(|(_, v)| v.as_ref())
42    }
43
44    pub fn set(&mut self, key: &str, value: Option<Value>) {
45        match self.entries.iter_mut().find(|(k, _)| k == key) {
46            Some(e) => e.1 = value,
47            None => self.entries.push((key.to_owned(), value)),
48        }
49    }
50
51    /// `{...self, ...other}`.
52    pub fn merging(&self, other: &Constraint) -> Constraint {
53        let mut result = self.clone();
54        for (k, v) in &other.entries {
55            result.set(k, v.clone());
56        }
57        result
58    }
59
60    /// `constraintMatchesRow`.
61    pub fn matches(&self, row: &Row) -> bool {
62        self.entries
63            .iter()
64            .all(|(k, v)| values_equal(row.get(k), v.as_ref()))
65    }
66
67    /// `constraintsAreCompatible`: no shared key has different values.
68    pub fn is_compatible(&self, other: &Constraint) -> bool {
69        self.entries
70            .iter()
71            .all(|(k, v)| !other.has(k) || values_equal(v.as_ref(), other.get(k)))
72    }
73
74    /// `constraintMatchesPrimaryKey`.
75    pub fn matches_primary_key(&self, primary_key: &[String]) -> bool {
76        key_matches_primary_key(&self.keys(), primary_key)
77    }
78
79    /// `{key: row[key]}` for each of `keys`.
80    pub fn from_row(row: &Row, keys: &[String]) -> Constraint {
81        Constraint {
82            entries: keys
83                .iter()
84                .map(|k| (k.clone(), row.get(k).cloned()))
85                .collect(),
86        }
87    }
88}
89
90/// `keyMatchesPrimaryKey`. The primary key is sorted; `key` need not be.
91pub fn key_matches_primary_key(key: &[&str], primary_key: &[String]) -> bool {
92    if key.len() != primary_key.len() {
93        return false;
94    }
95    let mut sorted = key.to_vec();
96    sorted.sort_by(|a, b| strings::utf16(a, b));
97    sorted.iter().zip(primary_key).all(|(a, b)| *a == b)
98}
99
100/// `pullSimpleAndComponents`: the top-level AND conjuncts that are simple.
101pub fn pull_simple_and_components(condition: &Condition) -> Vec<&Condition> {
102    match condition {
103        Condition::And(c) => c.iter().flat_map(pull_simple_and_components).collect(),
104        Condition::Simple { .. } => vec![condition],
105        Condition::Or(c) if c.len() == 1 => pull_simple_and_components(&c[0]),
106        _ => Vec::new(),
107    }
108}
109
110/// `primaryKeyConstraintFromFilters`: the primary key lookup the filters
111/// amount to, if they do.
112pub fn primary_key_constraint_from_filters(
113    condition: Option<&Condition>,
114    primary_key: &[String],
115) -> Option<Constraint> {
116    let conditions = pull_simple_and_components(condition?);
117    if conditions.is_empty() {
118        return None;
119    }
120    let mut ret = Constraint::default();
121    for c in conditions {
122        let Condition::Simple {
123            op: SimpleOperator::Eq,
124            left: ValuePosition::Column(name),
125            right,
126        } = c
127        else {
128            continue;
129        };
130        let ValuePosition::Literal(value) = right else {
131            panic!("extractColumn: expected right side to be literal");
132        };
133        if primary_key.contains(name) {
134            ret.set(name, Some(value.clone()));
135        }
136    }
137    (ret.len() == primary_key.len()).then_some(ret)
138}