Skip to main content

ursa_engine/graph/
node.rs

1//! The graph function plan node.
2//!
3//! [`GraphAlgorithmNode`] takes its edges as a child plan: the graph's edge
4//! table, projected to the source and destination columns. Anything that
5//! produces edge rows can sit under it (a scan, a view's filter, a join), and
6//! DataFusion's optimizer works on that child as on any plan: projections and
7//! filters reach the scan.
8//!
9//! A node whose calls take a `weight =>` has a second child: the same edge
10//! table projected to the endpoints and one column per distinct weight
11//! expression ([`WEIGHTED_SOURCE`], [`WEIGHTED_DESTINATION`],
12//! [`weight_column`]). The first child stays exactly the plan an unweighted
13//! call has, so its fingerprint, which keys the index cache, does not depend on
14//! the weights: a weighted and an unweighted query over one graph share one
15//! index. When the node runs with weights it reads only the second child (see
16//! [`super::exec`]).
17//!
18//! A graph with a vertex table has its keys as its nodes (#311): the node
19//! then has one more child after the edge plans, the vertex table projected
20//! to its key ([`GraphAlgorithmNode::vertices`]). It runs when the node
21//! builds its index, before the edges.
22//!
23//! A neighbour aggregation (`neighbors_agg`) reads one value per node. Its
24//! node has one more child, last: the values, a plan of two columns, node ids
25//! then values (see [`GraphAlgorithmNode::values`]). Like a traversal's node
26//! ids, it runs when the node runs.
27//!
28//! The node's output is `id` (for per-node functions) plus one column per
29//! [`Output`]: one per algorithm, two per layout (`x` and `y`), and a
30//! statistic's columns, in one row and with no `id`.
31
32use std::cmp::Ordering;
33use std::fmt;
34use std::hash::{Hash, Hasher};
35use std::sync::Arc;
36
37use datafusion::arrow::datatypes::{DataType, Field, Schema};
38use datafusion::common::{DFSchema, DFSchemaRef};
39use datafusion::error::Result;
40use datafusion::logical_expr::{Expr, ExprSchemable, LogicalPlan, UserDefinedLogicalNodeCore};
41use ursa_core::catalog::{Call, FunctionSpec, OutputKind};
42
43use super::functions::{display_call, plan};
44use super::provenance;
45use super::traversal::Traversal;
46
47/// The source column of a node's weighted edge plan.
48pub const WEIGHTED_SOURCE: &str = "__ursa_source";
49/// The destination column of a node's weighted edge plan.
50pub const WEIGHTED_DESTINATION: &str = "__ursa_destination";
51
52/// The column of a node's weighted edge plan that holds weight expression `i`.
53pub fn weight_column(i: usize) -> String {
54    format!("__ursa_weight_{i}")
55}
56
57/// One output column of a graph node: output `field` of `call`, named `name`.
58#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
59pub struct Output {
60    /// The column's name.
61    pub name: String,
62    pub call: Call,
63    /// Which of the call's outputs (a layout's `x` is 0 and `y` is 1).
64    pub field: usize,
65    /// The weight expression the call reads, as an index into the node's
66    /// weights; `None` is unweighted.
67    pub weight: Option<usize>,
68}
69
70/// Run graph functions over the edges its input produces.
71#[derive(Debug, Clone)]
72pub struct GraphAlgorithmNode {
73    /// The graph's name, for plans and messages. The index is keyed by the
74    /// edges, not by this.
75    pub graph: String,
76    /// The edge rows, projected to the endpoints.
77    pub input: Arc<LogicalPlan>,
78    /// The edge rows projected to the endpoints and the weights, when an
79    /// output reads a weight (see the module docs).
80    pub weighted: Option<Arc<LogicalPlan>>,
81    /// The graph's vertex table projected to its key, one column, when it
82    /// has one: its keys are the graph's nodes (see the module docs).
83    pub vertices: Option<Arc<LogicalPlan>>,
84    /// The node values a neighbour aggregation reads: a plan of two columns,
85    /// node ids then values.
86    pub values: Option<Arc<LogicalPlan>>,
87    /// The source and destination of each edge: column references into
88    /// `input`.
89    pub source: Expr,
90    pub destination: Expr,
91    /// The distinct weight expressions, as written, for `EXPLAIN`.
92    pub weights: Vec<String>,
93    /// What the node computes, one value column each.
94    pub outputs: Vec<Output>,
95    /// One row per node with an `id` column, or one row for the whole graph.
96    pub per_node: bool,
97    /// The node id type: the endpoints' type, with every integer type read as
98    /// `Int64` and every string type as `Utf8`, as the Python library reads
99    /// them.
100    pub id_type: DataType,
101    /// The graph's vertex table (its element name), if it has one: the label
102    /// of the node keys, for the output's field metadata
103    /// ([`super::provenance`]).
104    pub vertex_label: Option<String>,
105    schema: DFSchemaRef,
106}
107
108impl GraphAlgorithmNode {
109    #[allow(clippy::too_many_arguments)]
110    pub fn try_new(
111        graph: String,
112        input: Arc<LogicalPlan>,
113        weighted: Option<Arc<LogicalPlan>>,
114        vertices: Option<Arc<LogicalPlan>>,
115        values: Option<Arc<LogicalPlan>>,
116        source: Expr,
117        destination: Expr,
118        weights: Vec<String>,
119        outputs: Vec<Output>,
120        per_node: bool,
121        vertex_label: Option<String>,
122    ) -> Result<Self> {
123        let id_type = endpoint_id_type(&graph, &input, &source, &destination)?;
124        check_vertices(&graph, vertices.as_deref())?;
125        if let Some(values) = &values {
126            let columns = values.schema().fields().len();
127            if columns != 2 {
128                return Err(plan(format!(
129                    "the node values of graph '{graph}' must be two columns, node ids then \
130                     values; the query returns {columns}"
131                )));
132            }
133        }
134        let mut fields = Vec::new();
135        // Each field says what it is (`provenance`): the node key, then a
136        // metric or a category per algorithm. A statistic's columns and a
137        // layout's positions have no role.
138        if per_node {
139            fields.push(provenance::field(
140                Field::new("id", id_type.clone(), false),
141                provenance::ROLE_NODE,
142                &graph,
143                vertex_label.as_deref(),
144            ));
145        }
146        for o in &outputs {
147            let spec = super::functions::outputs(o.call.spec())[o.field];
148            // A neighbour aggregation's type depends on its values' type.
149            let ty = match (&o.call, &values) {
150                (Call::NeighborAgg { agg, .. }, Some(values)) => {
151                    super::kernels::neighbors_agg_type(*agg, values.schema().field(1).data_type())
152                }
153                _ => spec.ty.data_type(),
154            };
155            let field = Field::new(&o.name, ty, spec.nullable);
156            fields.push(match output_role(o.call.spec(), field.data_type()) {
157                Some(role) => provenance::field(field, role, &graph, None),
158                None => field,
159            });
160        }
161        let schema = Arc::new(DFSchema::try_from(Schema::new(fields))?);
162        Ok(Self {
163            graph,
164            input,
165            weighted,
166            vertices,
167            values,
168            source,
169            destination,
170            weights,
171            outputs,
172            per_node,
173            id_type,
174            vertex_label,
175            schema,
176        })
177    }
178
179    /// The positions of the source and destination columns in the input.
180    pub fn endpoint_indices(&self) -> Result<(usize, usize)> {
181        endpoint_positions(&self.graph, &self.input, &self.source, &self.destination)
182    }
183
184    /// The outputs as SQL would spell them, for `EXPLAIN`: `name: call`, or
185    /// just the call when the column is named after its function.
186    pub(crate) fn display_outputs(&self) -> String {
187        let outputs: Vec<String> = self
188            .outputs
189            .iter()
190            .map(|o| {
191                let weight = o.weight.map(|i| self.weights[i].as_str());
192                let call = display_call(&o.call, weight);
193                let spec = o.call.spec();
194                if spec.outputs.len() == 1 && o.name == spec.outputs[0].name {
195                    call
196                } else {
197                    format!("{}: {call}", o.name)
198                }
199            })
200            .collect();
201        outputs.join(", ")
202    }
203}
204
205/// What a per-node output column of `spec` is, as its field's `ursa.role`
206/// says: the catalog's kind, a metric or a category. A neighbour aggregation
207/// is a metric when it is a number (`min` of names is not).
208fn output_role(spec: &FunctionSpec, ty: &DataType) -> Option<&'static str> {
209    match spec.output_kind()? {
210        OutputKind::Category => Some(provenance::ROLE_CATEGORY),
211        OutputKind::Metric if ty.is_numeric() => Some(provenance::ROLE_METRIC),
212        OutputKind::Metric => None,
213    }
214}
215
216/// The node id type of a graph whose edges `input` holds, with endpoint
217/// columns `source` and `destination`: both integer or both string.
218pub(crate) fn endpoint_id_type(
219    graph: &str,
220    input: &LogicalPlan,
221    source: &Expr,
222    destination: &Expr,
223) -> Result<DataType> {
224    let source_type = source.get_type(input.schema())?;
225    let destination_type = destination.get_type(input.schema())?;
226    match (id_type(&source_type), id_type(&destination_type)) {
227        (Some(s), Some(d)) if s == d => Ok(s),
228        (Some(_), Some(_)) => Err(plan(format!(
229            "graph '{graph}': the source and destination columns must have one id type \
230             (both integer or both string); got {source_type} and {destination_type}"
231        ))),
232        (None, _) | (_, None) => {
233            let bad = if id_type(&source_type).is_none() {
234                source_type
235            } else {
236                destination_type
237            };
238            Err(plan(format!(
239                "graph '{graph}': node ids must be an integer or string column; got {bad}"
240            )))
241        }
242    }
243}
244
245/// A vertex input is one column: the keys of the graph's vertex table.
246pub(crate) fn check_vertices(graph: &str, vertices: Option<&LogicalPlan>) -> Result<()> {
247    match vertices.map(|v| v.schema().fields().len()) {
248        None | Some(1) => Ok(()),
249        Some(n) => Err(plan(format!(
250            "graph '{graph}': the vertex keys must be one column; got {n}"
251        ))),
252    }
253}
254
255/// The positions of the endpoint columns `source` and `destination` in
256/// `input`.
257fn endpoint_positions(
258    graph: &str,
259    input: &LogicalPlan,
260    source: &Expr,
261    destination: &Expr,
262) -> Result<(usize, usize)> {
263    let index = |e: &Expr| -> Result<usize> {
264        match e {
265            Expr::Column(c) => input.schema().index_of_column(c),
266            other => Err(plan(format!(
267                "graph '{graph}': an edge endpoint must be a column; got {other}"
268            ))),
269        }
270    };
271    Ok((index(source)?, index(destination)?))
272}
273
274/// The node id type a column of `t` gives: integers as `Int64`, strings as
275/// `Utf8`, or `None` if `t` cannot hold node ids. The rule every source shares
276/// (`ursa_io::ids`), so a graph's ids are the Python library's.
277pub(crate) fn id_type(t: &DataType) -> Option<DataType> {
278    ursa_io::ids::canonical_id_type(t)
279}
280
281/// What identifies a node besides its plans and expressions.
282type Key<'a> = (
283    &'a String,
284    &'a Vec<Output>,
285    &'a Vec<String>,
286    bool,
287    &'a Option<String>,
288);
289
290impl GraphAlgorithmNode {
291    fn key(&self) -> Key<'_> {
292        (
293            &self.graph,
294            &self.outputs,
295            &self.weights,
296            self.per_node,
297            &self.vertex_label,
298        )
299    }
300}
301
302// The schema is derived from the other fields, so equality, hashing and order
303// leave it out.
304impl PartialEq for GraphAlgorithmNode {
305    fn eq(&self, other: &Self) -> bool {
306        self.key() == other.key()
307            && self.source == other.source
308            && self.destination == other.destination
309            && self.input == other.input
310            && self.weighted == other.weighted
311            && self.vertices == other.vertices
312            && self.values == other.values
313    }
314}
315
316impl Eq for GraphAlgorithmNode {}
317
318impl Hash for GraphAlgorithmNode {
319    fn hash<H: Hasher>(&self, state: &mut H) {
320        self.key().hash(state);
321        self.source.hash(state);
322        self.destination.hash(state);
323        self.input.hash(state);
324        self.weighted.hash(state);
325        self.vertices.hash(state);
326        self.values.hash(state);
327    }
328}
329
330impl PartialOrd for GraphAlgorithmNode {
331    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
332        match self.key().cmp(&other.key()) {
333            Ordering::Equal => {}
334            unequal => return Some(unequal),
335        }
336        match self.source.partial_cmp(&other.source)? {
337            Ordering::Equal => {}
338            unequal => return Some(unequal),
339        }
340        match self.destination.partial_cmp(&other.destination)? {
341            Ordering::Equal => {}
342            unequal => return Some(unequal),
343        }
344        match self.input.partial_cmp(&other.input)? {
345            Ordering::Equal => {}
346            unequal => return Some(unequal),
347        }
348        match self.weighted.partial_cmp(&other.weighted)? {
349            Ordering::Equal => {}
350            unequal => return Some(unequal),
351        }
352        match self.vertices.partial_cmp(&other.vertices)? {
353            Ordering::Equal => {}
354            unequal => return Some(unequal),
355        }
356        self.values.partial_cmp(&other.values)
357    }
358}
359
360impl UserDefinedLogicalNodeCore for GraphAlgorithmNode {
361    fn name(&self) -> &str {
362        "GraphAlgorithm"
363    }
364
365    fn inputs(&self) -> Vec<&LogicalPlan> {
366        let mut inputs = vec![self.input.as_ref()];
367        inputs.extend(self.weighted.as_deref());
368        inputs.extend(self.vertices.as_deref());
369        inputs.extend(self.values.as_deref());
370        inputs
371    }
372
373    fn schema(&self) -> &DFSchemaRef {
374        &self.schema
375    }
376
377    /// The endpoint columns, so DataFusion keeps them in the input.
378    fn expressions(&self) -> Vec<Expr> {
379        vec![self.source.clone(), self.destination.clone()]
380    }
381
382    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
383        write!(
384            f,
385            "GraphAlgorithm: graph={}, edges=({}, {}), outputs=[{}]",
386            self.graph,
387            self.source,
388            self.destination,
389            self.display_outputs()
390        )
391    }
392
393    fn with_exprs_and_inputs(&self, exprs: Vec<Expr>, inputs: Vec<LogicalPlan>) -> Result<Self> {
394        let [source, destination]: [Expr; 2] = exprs
395            .try_into()
396            .map_err(|_| plan("GraphAlgorithm takes two expressions".into()))?;
397        let expected = 1
398            + usize::from(self.weighted.is_some())
399            + usize::from(self.vertices.is_some())
400            + usize::from(self.values.is_some());
401        if inputs.len() != expected {
402            return Err(plan(format!(
403                "GraphAlgorithm takes {expected} inputs; got {}",
404                inputs.len()
405            )));
406        }
407        let mut inputs = inputs.into_iter().map(Arc::new);
408        let input = inputs.next().expect("checked above");
409        let weighted = self.weighted.as_ref().and_then(|_| inputs.next());
410        let vertices = self.vertices.as_ref().and_then(|_| inputs.next());
411        let values = self.values.as_ref().and_then(|_| inputs.next());
412        Self::try_new(
413            self.graph.clone(),
414            input,
415            weighted,
416            vertices,
417            values,
418            source,
419            destination,
420            self.weights.clone(),
421            self.outputs.clone(),
422            self.per_node,
423            self.vertex_label.clone(),
424        )
425    }
426
427    /// Every output needs both endpoints and nothing else of the first input,
428    /// every column of the weighted input, the vertex key, and both columns of
429    /// the values.
430    fn necessary_children_exprs(&self, _output_columns: &[usize]) -> Option<Vec<Vec<usize>>> {
431        let (source, destination) = self.endpoint_indices().ok()?;
432        let mut needed = vec![source, destination];
433        needed.sort_unstable();
434        needed.dedup();
435        let mut children = vec![needed];
436        if let Some(weighted) = &self.weighted {
437            children.push((0..weighted.schema().fields().len()).collect());
438        }
439        if self.vertices.is_some() {
440            children.push(vec![0]);
441        }
442        if self.values.is_some() {
443            children.push(vec![0, 1]);
444        }
445        Some(children)
446    }
447
448    /// Filters on the output are about nodes, not edges: none moves below.
449    fn prevent_predicate_push_down_columns(&self) -> std::collections::HashSet<String> {
450        self.schema
451            .fields()
452            .iter()
453            .map(|f| f.name().clone())
454            .collect()
455    }
456}
457
458/// Run a traversal (`hop`, `shortest_path`, `random_walk`, `induced_edges`)
459/// over the edges its
460/// first input produces.
461///
462/// Its inputs, in order:
463///
464/// 1. the edge rows projected to the endpoints, exactly as a
465///    [`GraphAlgorithmNode`]'s first input, so the two share one index;
466/// 2. for a weighted `shortest_path`, the weighted edge plan, as a
467///    [`GraphAlgorithmNode`]'s second input (with one weight column);
468/// 3. for a graph with a vertex table, its keys, as a
469///    [`GraphAlgorithmNode`]'s;
470/// 4. one plan per node-id parameter (`seeds`; `source` and `target`;
471///    `start`), each of one column: a `VALUES` list for a literal, or the
472///    planned subquery. They run when the node runs, never while the query is
473///    planned, and their values are cast to the graph's id type then.
474///
475/// The output is the traversal's own rows (see [`super::traversal`]).
476#[derive(Debug, Clone)]
477pub struct GraphTraversalNode {
478    /// The graph's name, for plans and messages.
479    pub graph: String,
480    pub traversal: Traversal,
481    /// The edge rows, projected to the endpoints.
482    pub input: Arc<LogicalPlan>,
483    /// The edge rows projected to the endpoints and the weight, for a
484    /// weighted shortest path.
485    pub weighted: Option<Arc<LogicalPlan>>,
486    /// The graph's vertex keys (see [`GraphAlgorithmNode::vertices`]).
487    pub vertices: Option<Arc<LogicalPlan>>,
488    /// The weight expression, as written, for `EXPLAIN`.
489    pub weight: Option<String>,
490    /// One plan per node-id parameter, in the spec's order.
491    pub nodes: Vec<Arc<LogicalPlan>>,
492    /// Each node-id argument as written, for `EXPLAIN`.
493    pub written: Vec<String>,
494    /// Whether each node-id argument is a subquery, whose ids that are not
495    /// nodes are skipped; a literal one is an error (#416).
496    pub from_query: Vec<bool>,
497    /// The source and destination of each edge: column references into
498    /// `input`.
499    pub source: Expr,
500    pub destination: Expr,
501    /// The node id type (see [`GraphAlgorithmNode::id_type`]).
502    pub id_type: DataType,
503    /// The graph's vertex table (see [`GraphAlgorithmNode::vertex_label`]).
504    pub vertex_label: Option<String>,
505    /// The graph's edge table (its element name): the label of an edge row
506    /// in the output's field metadata.
507    pub edge_label: String,
508    schema: DFSchemaRef,
509}
510
511impl GraphTraversalNode {
512    #[allow(clippy::too_many_arguments)]
513    pub fn try_new(
514        graph: String,
515        traversal: Traversal,
516        input: Arc<LogicalPlan>,
517        weighted: Option<Arc<LogicalPlan>>,
518        vertices: Option<Arc<LogicalPlan>>,
519        weight: Option<String>,
520        nodes: Vec<Arc<LogicalPlan>>,
521        written: Vec<String>,
522        from_query: Vec<bool>,
523        source: Expr,
524        destination: Expr,
525        vertex_label: Option<String>,
526        edge_label: String,
527    ) -> Result<Self> {
528        let id_type = endpoint_id_type(&graph, &input, &source, &destination)?;
529        check_vertices(&graph, vertices.as_deref())?;
530        let spec = traversal.spec();
531        let expected = spec.node_params().count();
532        if nodes.len() != expected || written.len() != expected || from_query.len() != expected {
533            return Err(plan(format!(
534                "{}() takes {expected} node-id inputs; got {}",
535                spec.name,
536                nodes.len()
537            )));
538        }
539        if weighted.is_some() != weight.is_some() {
540            return Err(plan(format!(
541                "{}(): a weighted plan needs its weight expression",
542                spec.name
543            )));
544        }
545        for (p, n) in spec.node_params().zip(&nodes) {
546            let columns = n.schema().fields().len();
547            if columns != 1 {
548                return Err(plan(format!(
549                    "{}({} =>) must be one column of node ids; the query returns {columns} \
550                     columns",
551                    spec.name, p.name
552                )));
553            }
554        }
555        let schema = Arc::new(DFSchema::try_from(spec.schema(
556            &graph,
557            vertex_label.as_deref(),
558            &edge_label,
559            &id_type,
560        ))?);
561        Ok(Self {
562            graph,
563            traversal,
564            input,
565            weighted,
566            vertices,
567            weight,
568            nodes,
569            written,
570            from_query,
571            source,
572            destination,
573            id_type,
574            vertex_label,
575            edge_label,
576            schema,
577        })
578    }
579
580    /// The positions of the source and destination columns in the input.
581    pub fn endpoint_indices(&self) -> Result<(usize, usize)> {
582        endpoint_positions(&self.graph, &self.input, &self.source, &self.destination)
583    }
584
585    /// The call as SQL would spell it, for `EXPLAIN`.
586    pub(crate) fn display_call(&self) -> String {
587        self.traversal
588            .display(&self.written, self.weight.as_deref())
589    }
590}
591
592/// What identifies a traversal node besides its plans and expressions.
593type TraversalKey<'a> = (
594    &'a String,
595    &'a Traversal,
596    &'a Option<String>,
597    &'a Vec<String>,
598    &'a Vec<bool>,
599    &'a Option<String>,
600    &'a String,
601);
602
603impl GraphTraversalNode {
604    fn key(&self) -> TraversalKey<'_> {
605        (
606            &self.graph,
607            &self.traversal,
608            &self.weight,
609            &self.written,
610            &self.from_query,
611            &self.vertex_label,
612            &self.edge_label,
613        )
614    }
615}
616
617// The schema and id type are derived from the other fields, so equality,
618// hashing and order leave them out.
619impl PartialEq for GraphTraversalNode {
620    fn eq(&self, other: &Self) -> bool {
621        self.key() == other.key()
622            && self.source == other.source
623            && self.destination == other.destination
624            && self.input == other.input
625            && self.weighted == other.weighted
626            && self.vertices == other.vertices
627            && self.nodes == other.nodes
628    }
629}
630
631impl Eq for GraphTraversalNode {}
632
633impl Hash for GraphTraversalNode {
634    fn hash<H: Hasher>(&self, state: &mut H) {
635        self.key().hash(state);
636        self.source.hash(state);
637        self.destination.hash(state);
638        self.input.hash(state);
639        self.weighted.hash(state);
640        self.vertices.hash(state);
641        self.nodes.hash(state);
642    }
643}
644
645impl PartialOrd for GraphTraversalNode {
646    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
647        match self.key().cmp(&other.key()) {
648            Ordering::Equal => {}
649            unequal => return Some(unequal),
650        }
651        match self.source.partial_cmp(&other.source)? {
652            Ordering::Equal => {}
653            unequal => return Some(unequal),
654        }
655        match self.destination.partial_cmp(&other.destination)? {
656            Ordering::Equal => {}
657            unequal => return Some(unequal),
658        }
659        match self.input.partial_cmp(&other.input)? {
660            Ordering::Equal => {}
661            unequal => return Some(unequal),
662        }
663        match self.weighted.partial_cmp(&other.weighted)? {
664            Ordering::Equal => {}
665            unequal => return Some(unequal),
666        }
667        match self.vertices.partial_cmp(&other.vertices)? {
668            Ordering::Equal => {}
669            unequal => return Some(unequal),
670        }
671        self.nodes.partial_cmp(&other.nodes)
672    }
673}
674
675impl UserDefinedLogicalNodeCore for GraphTraversalNode {
676    fn name(&self) -> &str {
677        "GraphTraversal"
678    }
679
680    fn inputs(&self) -> Vec<&LogicalPlan> {
681        let mut inputs = vec![self.input.as_ref()];
682        inputs.extend(self.weighted.as_deref());
683        inputs.extend(self.vertices.as_deref());
684        inputs.extend(self.nodes.iter().map(Arc::as_ref));
685        inputs
686    }
687
688    fn schema(&self) -> &DFSchemaRef {
689        &self.schema
690    }
691
692    /// The endpoint columns, so DataFusion keeps them in the input.
693    fn expressions(&self) -> Vec<Expr> {
694        vec![self.source.clone(), self.destination.clone()]
695    }
696
697    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
698        write!(
699            f,
700            "GraphTraversal: graph={}, edges=({}, {}), call={}",
701            self.graph,
702            self.source,
703            self.destination,
704            self.display_call()
705        )
706    }
707
708    fn with_exprs_and_inputs(&self, exprs: Vec<Expr>, inputs: Vec<LogicalPlan>) -> Result<Self> {
709        let [source, destination]: [Expr; 2] = exprs
710            .try_into()
711            .map_err(|_| plan("GraphTraversal takes two expressions".into()))?;
712        let weighted = usize::from(self.weighted.is_some());
713        let vertices = usize::from(self.vertices.is_some());
714        let expected = 1 + weighted + vertices + self.nodes.len();
715        if inputs.len() != expected {
716            return Err(plan(format!(
717                "GraphTraversal takes {expected} inputs; got {}",
718                inputs.len()
719            )));
720        }
721        let mut inputs = inputs.into_iter().map(Arc::new);
722        let input = inputs.next().expect("checked above");
723        let weighted = (weighted == 1).then(|| inputs.next().expect("checked above"));
724        let vertices = (vertices == 1).then(|| inputs.next().expect("checked above"));
725        Self::try_new(
726            self.graph.clone(),
727            self.traversal,
728            input,
729            weighted,
730            vertices,
731            self.weight.clone(),
732            inputs.collect(),
733            self.written.clone(),
734            self.from_query.clone(),
735            source,
736            destination,
737            self.vertex_label.clone(),
738            self.edge_label.clone(),
739        )
740    }
741
742    /// Both endpoints of the first input, every column of the weighted input,
743    /// the vertex key, and the one column of each node-id input.
744    fn necessary_children_exprs(&self, _output_columns: &[usize]) -> Option<Vec<Vec<usize>>> {
745        let (source, destination) = self.endpoint_indices().ok()?;
746        let mut needed = vec![source, destination];
747        needed.sort_unstable();
748        needed.dedup();
749        let mut children = vec![needed];
750        if let Some(weighted) = &self.weighted {
751            children.push((0..weighted.schema().fields().len()).collect());
752        }
753        if self.vertices.is_some() {
754            children.push(vec![0]);
755        }
756        children.extend(self.nodes.iter().map(|_| vec![0]));
757        Some(children)
758    }
759
760    /// Filters on the output are about the traversal's rows, not the edges or
761    /// the node ids: none moves below.
762    fn prevent_predicate_push_down_columns(&self) -> std::collections::HashSet<String> {
763        self.schema
764            .fields()
765            .iter()
766            .map(|f| f.name().clone())
767            .collect()
768    }
769}