1use 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
47pub const WEIGHTED_SOURCE: &str = "__ursa_source";
49pub const WEIGHTED_DESTINATION: &str = "__ursa_destination";
51
52pub fn weight_column(i: usize) -> String {
54 format!("__ursa_weight_{i}")
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
59pub struct Output {
60 pub name: String,
62 pub call: Call,
63 pub field: usize,
65 pub weight: Option<usize>,
68}
69
70#[derive(Debug, Clone)]
72pub struct GraphAlgorithmNode {
73 pub graph: String,
76 pub input: Arc<LogicalPlan>,
78 pub weighted: Option<Arc<LogicalPlan>>,
81 pub vertices: Option<Arc<LogicalPlan>>,
84 pub values: Option<Arc<LogicalPlan>>,
87 pub source: Expr,
90 pub destination: Expr,
91 pub weights: Vec<String>,
93 pub outputs: Vec<Output>,
95 pub per_node: bool,
97 pub id_type: DataType,
101 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 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 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 pub fn endpoint_indices(&self) -> Result<(usize, usize)> {
181 endpoint_positions(&self.graph, &self.input, &self.source, &self.destination)
182 }
183
184 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
205fn 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
216pub(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
245pub(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
255fn 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
274pub(crate) fn id_type(t: &DataType) -> Option<DataType> {
278 ursa_io::ids::canonical_id_type(t)
279}
280
281type 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
302impl 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 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 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 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#[derive(Debug, Clone)]
477pub struct GraphTraversalNode {
478 pub graph: String,
480 pub traversal: Traversal,
481 pub input: Arc<LogicalPlan>,
483 pub weighted: Option<Arc<LogicalPlan>>,
486 pub vertices: Option<Arc<LogicalPlan>>,
488 pub weight: Option<String>,
490 pub nodes: Vec<Arc<LogicalPlan>>,
492 pub written: Vec<String>,
494 pub from_query: Vec<bool>,
497 pub source: Expr,
500 pub destination: Expr,
501 pub id_type: DataType,
503 pub vertex_label: Option<String>,
505 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 pub fn endpoint_indices(&self) -> Result<(usize, usize)> {
582 endpoint_positions(&self.graph, &self.input, &self.source, &self.destination)
583 }
584
585 pub(crate) fn display_call(&self) -> String {
587 self.traversal
588 .display(&self.written, self.weight.as_deref())
589 }
590}
591
592type 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
617impl 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 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 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 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}