Skip to main content

zero_client/ivm/
lift_field.rs

1//! `LiftField` (`packages/zql/src/ivm/lift-field.ts`).
2
3use super::*;
4use crate::ast::{Aggregate as AggregateSpec, AggregateFunction};
5use crate::json::Value;
6use crate::schema::{Column, ValueType};
7use std::cell::RefCell;
8use std::rc::{Rc, Weak};
9
10/// The column `LiftField` writes the destination's field into. A space
11/// can't start an identifier, so it never collides with a real column.
12pub const LIFTED_FIELD_COLUMN: &str = " lifted";
13
14struct Lift {
15    source_relationship: String,
16    field: String,
17    json_aggregate: Option<AggregateSpec>,
18}
19
20impl Lift {
21    /// The value to lift from a destination row.
22    fn read(&self, row: &Row) -> Value {
23        match &self.json_aggregate {
24            Some(a) => aggregate_value(a, row),
25            None => row.get(&self.field).cloned().unwrap_or(Value::Null),
26        }
27    }
28
29    /// `node`'s row with the destination's field lifted onto it.
30    fn lift(&self, node: &Node) -> Node {
31        let mut value = Value::Null;
32        if let Some(rel) = node.relationships.get(&self.source_relationship) {
33            for child in rel() {
34                value = self.read(&child.row);
35            }
36        }
37        Node::new(with_column(&node.row, value))
38    }
39
40    /// The lifted value before and after a change to the destination;
41    /// `None` when the destination row itself didn't change.
42    fn values(&self, change: &Change) -> Option<(Value, Value)> {
43        match change {
44            Change::Add(n) => Some((Value::Null, self.read(&n.row))),
45            Change::Remove(n) => Some((self.read(&n.row), Value::Null)),
46            Change::Edit { node, old_node } => {
47                Some((self.read(&old_node.row), self.read(&node.row)))
48            }
49            Change::Child(..) => None,
50        }
51    }
52}
53
54fn with_column(row: &Row, value: Value) -> Row {
55    let mut row = (**row).clone();
56    row.insert(LIFTED_FIELD_COLUMN, value);
57    Rc::new(row)
58}
59
60/// Lifts a field of a singular child relationship onto each row.
61///
62/// For a junction aggregate the value (`label.points`) lives one hop past
63/// the junction row (`issueLabel`). LiftField copies it onto the junction
64/// row, so the `Aggregate` after it reduces a flat field. A change to the
65/// destination arrives as a child change and becomes an edit of the lifted
66/// column; one from below the destination leaves the value as it was. For a
67/// JSON path (`json_aggregate`) it lifts the leaf, as [`aggregate_value`]
68/// reads it.
69///
70/// The rows it emits carry no relationships.
71pub struct LiftField {
72    input: Rc<dyn Input>,
73    lift: Rc<Lift>,
74    schema: Rc<SourceSchema>,
75    output: RefCell<Weak<dyn Output>>,
76}
77
78impl LiftField {
79    pub fn new(
80        input: Rc<dyn Input>,
81        source_relationship: impl Into<String>,
82        field: impl Into<String>,
83        json_aggregate: Option<AggregateSpec>,
84    ) -> Rc<Self> {
85        let source_relationship = source_relationship.into();
86        let field = field.into();
87        let input_schema = input.get_schema();
88        let mut columns = input_schema.columns.clone();
89        // Nullable: a junction row may have no destination for a while.
90        let column = match &json_aggregate {
91            Some(a) => Column {
92                type_: if matches!(a.fn_, AggregateFunction::Min | AggregateFunction::Max) {
93                    ValueType::Json
94                } else {
95                    ValueType::Number
96                },
97                optional: true,
98                server_name: None,
99            },
100            None => match input_schema
101                .relationship(&source_relationship)
102                .and_then(|r| r.columns.get(&field))
103            {
104                Some(c) => Column {
105                    optional: true,
106                    ..c.clone()
107                },
108                None => Column {
109                    type_: ValueType::Number,
110                    optional: true,
111                    server_name: None,
112                },
113            },
114        };
115        columns.insert(LIFTED_FIELD_COLUMN, column);
116        let schema = Rc::new(SourceSchema {
117            columns,
118            relationships: Vec::new(),
119            ..(*input_schema).clone()
120        });
121        let op = Rc::new(LiftField {
122            input: input.clone(),
123            lift: Rc::new(Lift {
124                source_relationship,
125                field,
126                json_aggregate,
127            }),
128            schema,
129            output: RefCell::new(no_output()),
130        });
131        input.set_output(Rc::downgrade(&op) as Weak<dyn Output>);
132        op
133    }
134
135    fn emit(&self, change: Change) {
136        let out = self.output.borrow().upgrade();
137        if let Some(out) = out {
138            out.push(change, self);
139        }
140    }
141}
142
143impl InputBase for LiftField {
144    fn get_schema(&self) -> Rc<SourceSchema> {
145        self.schema.clone()
146    }
147    fn destroy(&self) {
148        self.input.destroy()
149    }
150}
151
152impl Input for LiftField {
153    fn set_output(&self, output: Weak<dyn Output>) {
154        *self.output.borrow_mut() = output;
155    }
156
157    fn fetch(&self, req: &FetchRequest) -> NodeStream {
158        let lift = self.lift.clone();
159        Box::new(self.input.fetch(req).map(move |n| lift.lift(&n)))
160    }
161}
162
163impl Output for LiftField {
164    fn push(&self, change: Change, _pusher: &dyn InputBase) {
165        let lift = &self.lift;
166        match change {
167            Change::Add(n) => self.emit(Change::Add(lift.lift(&n))),
168            Change::Remove(n) => self.emit(Change::Remove(lift.lift(&n))),
169            Change::Edit { node, old_node } => self.emit(Change::Edit {
170                node: lift.lift(&node),
171                old_node: lift.lift(&old_node),
172            }),
173            Change::Child(node, child) => {
174                // A relationship this doesn't lift from, or a change below
175                // the destination.
176                if child.relationship_name != lift.source_relationship {
177                    return;
178                }
179                let Some((old, new)) = lift.values(&child.change) else {
180                    return;
181                };
182                self.emit(Change::Edit {
183                    node: Node::new(with_column(&node.row, new)),
184                    old_node: Node::new(with_column(&node.row, old)),
185                });
186            }
187        }
188    }
189
190    fn reconcile(&self, _pusher: &dyn InputBase) {
191        let out = self.output.borrow().upgrade();
192        if let Some(out) = out {
193            out.reconcile(self);
194        }
195    }
196}