1use std::sync::Arc;
47
48use datafusion::arrow::array::{Array, ArrayRef, AsArray, Float64Array, Int64Array};
49use datafusion::arrow::compute::cast;
50use datafusion::arrow::datatypes::{DataType, Field, Schema};
51use datafusion::arrow::record_batch::RecordBatch;
52use datafusion::error::{DataFusionError, Result};
53use ursa_core::algo::{
54 induced_edges, k_hop_distances_masked, random_walk_masked, shortest_path_masked,
55 shortest_path_weighted_with_cost_masked,
56};
57use ursa_core::catalog::{
58 direction_name, parse_direction, Expected, ParamType, Value, ALL_DIRECTIONS,
59};
60use ursa_core::{Direction, IdMap, Topology};
61
62use super::functions::{
63 direction_arg, expected_text, plan, sql_value, takes, unknown_param_text, Given, Literal,
64};
65use super::provenance;
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum TraversalParamType {
70 Nodes,
73 Node,
75 Param(ParamType),
77}
78
79#[derive(Debug, Clone, Copy)]
81pub struct TraversalParam {
82 pub name: &'static str,
83 pub ty: TraversalParamType,
84 pub default: Option<Value>,
86 pub doc: &'static str,
88}
89
90impl TraversalParam {
91 pub fn takes_nodes(&self) -> bool {
93 matches!(
94 self.ty,
95 TraversalParamType::Nodes | TraversalParamType::Node
96 )
97 }
98
99 pub fn takes(&self, given: Given) -> bool {
102 match self.ty {
103 TraversalParamType::Nodes => given != Given::Number && given != Given::Boolean,
104 TraversalParamType::Node => {
105 !matches!(given, Given::Number | Given::Boolean | Given::List)
106 }
107 TraversalParamType::Param(ty) => takes(self.name, ty, given),
108 }
109 }
110
111 pub fn is_weight(&self) -> bool {
113 self.ty == TraversalParamType::Param(ParamType::Weight)
114 }
115
116 pub fn shown_default(&self) -> String {
119 match (self.default, self.ty) {
120 (Some(v), _) => sql_value(&v),
121 (None, TraversalParamType::Nodes) => "[<id>, ...]".to_string(),
122 (None, TraversalParamType::Node) => "<id>".to_string(),
123 (None, TraversalParamType::Param(_)) => "<integer>".to_string(),
124 }
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum OutputType {
131 Id,
133 Int64,
134 Float64,
135}
136
137impl OutputType {
138 pub fn data_type(&self, id_type: &DataType) -> DataType {
139 match self {
140 OutputType::Id => id_type.clone(),
141 OutputType::Int64 => DataType::Int64,
142 OutputType::Float64 => DataType::Float64,
143 }
144 }
145}
146
147#[derive(Debug, Clone, Copy)]
149pub struct TraversalOutput {
150 pub name: &'static str,
151 pub ty: OutputType,
152 pub role: Option<&'static str>,
155}
156
157#[derive(Debug)]
159pub struct TraversalSpec {
160 pub name: &'static str,
161 pub summary: &'static str,
163 pub networkx: Option<&'static str>,
165 pub params: &'static [TraversalParam],
167 pub outputs: &'static [TraversalOutput],
168 pub python: bool,
171 pub strict_ids: bool,
174}
175
176pub const PYTHON_NAMES: &[(&str, &str, &str)] = &[
179 ("hop", "steps", "n"),
180 ("random_walk", "seeds", "start"),
181 ("random_walk", "random_seed", "seed"),
182 ("random_walk", "id", "node"),
183 ("shortest_path", "step", "hop"),
184];
185
186impl TraversalSpec {
187 pub fn param(&self, name: &str) -> Option<&'static TraversalParam> {
189 let params: &'static [TraversalParam] = self.params;
190 params.iter().find(|p| p.name == name)
191 }
192
193 pub fn node_params(&self) -> impl Iterator<Item = &'static TraversalParam> {
196 let params: &'static [TraversalParam] = self.params;
197 params.iter().filter(|p| p.takes_nodes())
198 }
199
200 pub fn directions(&self) -> &'static [&'static str] {
203 self.params
204 .iter()
205 .find_map(|p| match p.ty {
206 TraversalParamType::Param(ParamType::Direction(d)) => Some(d),
207 _ => None,
208 })
209 .unwrap_or(&[])
210 }
211
212 pub fn weighted(&self) -> bool {
214 self.params.iter().any(TraversalParam::is_weight)
215 }
216
217 pub fn schema(
223 &self,
224 graph: &str,
225 vertices: Option<&str>,
226 edges: &str,
227 id_type: &DataType,
228 ) -> Schema {
229 Schema::new(
230 self.outputs
231 .iter()
232 .map(|o| {
233 let field = Field::new(o.name, o.ty.data_type(id_type), false);
234 let label = match (o.ty, o.role) {
235 (OutputType::Id, _) => vertices,
236 (_, Some(provenance::ROLE_EDGE)) => Some(edges),
237 _ => None,
238 };
239 match o.role {
240 Some(role) => provenance::field(field, role, graph, label),
241 None => field,
242 }
243 })
244 .collect::<Vec<_>>(),
245 )
246 }
247
248 pub fn signature(&self) -> String {
251 let mut parts = vec!["<graph>".to_string()];
252 parts.extend(
253 self.params
254 .iter()
255 .map(|p| format!("{} => {}", p.name, p.shown_default())),
256 );
257 format!("{}({})", self.name, parts.join(", "))
258 }
259}
260
261const fn param(
262 name: &'static str,
263 ty: TraversalParamType,
264 default: Option<Value>,
265 doc: &'static str,
266) -> TraversalParam {
267 TraversalParam {
268 name,
269 ty,
270 default,
271 doc,
272 }
273}
274
275const fn out(name: &'static str, ty: OutputType, role: Option<&'static str>) -> TraversalOutput {
276 TraversalOutput { name, ty, role }
277}
278
279const DIRECTION: TraversalParam = param(
280 "direction",
281 TraversalParamType::Param(ParamType::Direction(ALL_DIRECTIONS)),
282 Some(Value::Str("out")),
283 "Follow out-edges, in-edges, or both (the undirected view).",
284);
285
286pub static TRAVERSALS: &[TraversalSpec] = &[
288 TraversalSpec {
289 name: "hop",
290 summary: "The nodes within steps of each seed: one (seed, id, distance) row per seed \
291 and node reached, distance the fewest steps from the seed to it. A seed is not \
292 its own row; a repeated seed repeats its rows. The rows come in no particular \
293 order; use ORDER BY for one.",
294 networkx: Some(
295 "nx.single_source_shortest_path_length(G, seed, cutoff=steps), the seed left out \
296 (in: on G.reverse(); both: on U)",
297 ),
298 params: &[
299 param(
300 "seeds",
301 TraversalParamType::Nodes,
302 None,
303 "The nodes to start from: a list, a query of one column, or one id.",
304 ),
305 param(
306 "steps",
307 TraversalParamType::Param(ParamType::Count),
308 Some(Value::UInt(1)),
309 "How many steps to take.",
310 ),
311 DIRECTION,
312 ],
313 outputs: &[
314 out("seed", OutputType::Id, Some(provenance::ROLE_SEED)),
315 out("id", OutputType::Id, Some(provenance::ROLE_NODE)),
316 out(
317 "distance",
318 OutputType::Int64,
319 Some(provenance::ROLE_DISTANCE),
320 ),
321 ],
322 python: true,
323 strict_ids: true,
324 },
325 TraversalSpec {
326 name: "shortest_path",
327 summary: "One shortest path from source to target: one row per edge, in order, with its \
328 0-based position (step) and the cost from source to its end. No path, no \
329 rows; nor when source is target, as a path of no edges has no edge rows (to \
330 ask whether a path exists, use GRAPH_TABLE and path_length(p)).",
331 networkx: Some(
332 "nx.shortest_path(G, source, target) (weighted: nx.dijkstra_path(G, source, target, \
333 weight=...))",
334 ),
335 params: &[
336 param(
337 "source",
338 TraversalParamType::Node,
339 None,
340 "The node the path starts at: an id, or a query of one value.",
341 ),
342 param(
343 "target",
344 TraversalParamType::Node,
345 None,
346 "The node the path ends at: an id, or a query of one value.",
347 ),
348 param(
349 "weight",
350 TraversalParamType::Param(ParamType::Weight),
351 Some(Value::Null),
352 "A non-negative weight per edge for the least-cost path; null is the fewest \
353 edges.",
354 ),
355 DIRECTION,
356 ],
357 outputs: &[
358 out("src", OutputType::Id, Some(provenance::ROLE_SRC)),
359 out("dst", OutputType::Id, Some(provenance::ROLE_DST)),
360 out("step", OutputType::Int64, Some(provenance::ROLE_STEP)),
361 out("cost", OutputType::Float64, None),
362 ],
363 python: true,
364 strict_ids: true,
365 },
366 TraversalSpec {
367 name: "random_walk",
368 summary: "Random walks along out-edges from each seed: one (walk_id, step, id) row per \
369 step. A walk stops early at a node with no out-edges.",
370 networkx: None,
371 params: &[
372 param(
373 "seeds",
374 TraversalParamType::Nodes,
375 None,
376 "The nodes to start walks at: a list, a query of one column, or one id.",
377 ),
378 param(
379 "steps",
380 TraversalParamType::Param(ParamType::Count),
381 None,
382 "How many steps each walk takes at most.",
383 ),
384 param(
385 "walks_per_node",
386 TraversalParamType::Param(ParamType::Count),
387 Some(Value::UInt(1)),
388 "How many walks start at each seed.",
389 ),
390 param(
391 "random_seed",
392 TraversalParamType::Param(ParamType::Seed),
393 Some(Value::Null),
394 "Seed for the deterministic random stream; null is a fixed default.",
395 ),
396 ],
397 outputs: &[
398 out("walk_id", OutputType::Int64, Some(provenance::ROLE_WALK)),
399 out("step", OutputType::Int64, Some(provenance::ROLE_STEP)),
400 out("id", OutputType::Id, Some(provenance::ROLE_NODE)),
401 ],
402 python: true,
403 strict_ids: true,
404 },
405 TraversalSpec {
406 name: "induced_edges",
407 summary: "The graph's edges whose two ends are both in nodes: one (src, dst, edge) row \
408 per edge, in the direction the graph stores it, edge its row in the edge \
409 table. Read from the index, in time proportional to the nodes' degrees. \
410 Parallel edges are separate rows; rows are ordered by edge.",
411 networkx: Some("G.subgraph(nodes).edges()"),
412 params: &[param(
413 "nodes",
414 TraversalParamType::Nodes,
415 None,
416 "The nodes whose edges to return: a list, a query of one column, or one id.",
417 )],
418 outputs: &[
419 out("src", OutputType::Id, Some(provenance::ROLE_SRC)),
420 out("dst", OutputType::Id, Some(provenance::ROLE_DST)),
421 out("edge", OutputType::Int64, Some(provenance::ROLE_EDGE)),
422 ],
423 python: false,
424 strict_ids: false,
425 },
426];
427
428pub fn lookup(name: &str) -> Option<&'static TraversalSpec> {
430 TRAVERSALS.iter().find(|t| t.name == name)
431}
432
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
436pub enum Traversal {
437 Hop {
438 steps: u32,
439 direction: Direction,
440 },
441 ShortestPath {
442 direction: Direction,
443 },
444 RandomWalk {
445 steps: u32,
446 walks_per_node: u32,
447 random_seed: Option<u64>,
448 },
449 InducedEdges,
450}
451
452impl Traversal {
453 pub fn spec(&self) -> &'static TraversalSpec {
454 let name = match self {
455 Traversal::Hop { .. } => "hop",
456 Traversal::ShortestPath { .. } => "shortest_path",
457 Traversal::RandomWalk { .. } => "random_walk",
458 Traversal::InducedEdges => "induced_edges",
459 };
460 lookup(name).expect("every traversal has a spec")
461 }
462
463 pub fn name(&self) -> &'static str {
464 self.spec().name
465 }
466
467 fn value(&self, name: &str) -> Option<Value> {
469 let seed = |s: Option<u64>| s.map_or(Value::Null, Value::UInt);
470 Some(match (self, name) {
471 (Traversal::Hop { steps, .. }, "steps")
472 | (Traversal::RandomWalk { steps, .. }, "steps") => Value::UInt(u64::from(*steps)),
473 (Traversal::Hop { direction, .. }, "direction")
474 | (Traversal::ShortestPath { direction }, "direction") => {
475 Value::Str(direction_name(*direction))
476 }
477 (Traversal::RandomWalk { walks_per_node, .. }, "walks_per_node") => {
478 Value::UInt(u64::from(*walks_per_node))
479 }
480 (Traversal::RandomWalk { random_seed, .. }, "random_seed") => seed(*random_seed),
481 _ => return None,
482 })
483 }
484
485 pub fn display(&self, nodes: &[String], weight: Option<&str>) -> String {
488 let mut nodes = nodes.iter();
489 let parts: Vec<String> = self
490 .spec()
491 .params
492 .iter()
493 .filter_map(|p| {
494 if p.takes_nodes() {
495 return nodes.next().map(|n| format!("{} => {n}", p.name));
496 }
497 if p.is_weight() {
498 return weight.map(|w| format!("{} => {w}", p.name));
499 }
500 self.value(p.name)
501 .map(|v| format!("{} => {}", p.name, sql_value(&v)))
502 })
503 .collect();
504 format!("{}({})", self.name(), parts.join(", "))
505 }
506}
507
508pub fn unknown_param(spec: &TraversalSpec, name: &str, given: Option<Given>) -> DataFusionError {
511 let takers: Vec<Box<dyn Fn(Given) -> bool>> = spec
512 .params
513 .iter()
514 .map(|p| Box::new(move |g| p.takes(g)) as Box<dyn Fn(Given) -> bool>)
515 .collect();
516 let entries: Vec<(&str, &dyn Fn(Given) -> bool)> = spec
517 .params
518 .iter()
519 .zip(&takers)
520 .map(|(p, t)| (p.name, t.as_ref()))
521 .collect();
522 plan(unknown_param_text(spec.name, name, given, &entries))
523}
524
525pub fn missing_param(spec: &TraversalSpec, param: &TraversalParam) -> DataFusionError {
527 plan(format!(
528 "{}() needs '{}': {}",
529 spec.name,
530 param.name,
531 spec.signature()
532 ))
533}
534
535pub fn not_node_ids(
539 function: &str,
540 param: &TraversalParam,
541 graph: &str,
542 id_type: &DataType,
543 got: &str,
544) -> String {
545 let (integer, string) = match param.ty {
546 TraversalParamType::Node => (
547 "a node id of graph '{graph}', which is an integer",
548 "a node id of graph '{graph}', which is a string",
549 ),
550 _ => (
551 "node ids of graph '{graph}', which are integers",
552 "node ids of graph '{graph}', which are strings",
553 ),
554 };
555 let expected = match id_type {
556 DataType::Int64 => integer,
557 _ => string,
558 }
559 .replace("{graph}", graph);
560 format!(
561 "{function}({} =>) must be {expected}; got {got}",
562 param.name
563 )
564}
565
566pub fn is_node_id_type(from: &DataType, id_type: &DataType) -> bool {
577 debug_assert!(matches!(id_type, DataType::Int64 | DataType::Utf8));
578 match from {
579 DataType::Null | DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => true,
580 DataType::Dictionary(_, values) => is_node_id_type(values, id_type),
581 t => t.is_integer(),
582 }
583}
584
585pub fn is_integer_text(text: &str) -> bool {
589 let digits = text.strip_prefix(['-', '+']).unwrap_or(text);
590 !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
591}
592
593pub fn first_refused_node_id(values: &ArrayRef, id_type: &DataType) -> Option<usize> {
599 let valid = |i: &usize| values.is_valid(*i);
600 if !is_node_id_type(values.data_type(), id_type) {
601 return (0..values.len()).find(valid);
602 }
603 if id_type != &DataType::Int64 || values.data_type().is_integer() {
604 return None;
605 }
606 let text = cast(values, &DataType::Utf8).ok()?;
607 let text = text.as_string::<i32>();
608 (0..text.len()).find(|i| valid(i) && !is_integer_text(text.value(*i)))
609}
610
611fn check(spec: &TraversalSpec, name: &str, ty: ParamType, literal: &Literal) -> Result<Value> {
613 let expected = |want: Expected| {
614 plan(format!(
615 "{}({name} =>) must be {}; got {literal}",
616 spec.name,
617 expected_text(want)
618 ))
619 };
620 let int = || match literal {
621 Literal::Number(n) => n.parse::<i128>().ok(),
622 _ => None,
623 };
624 match ty {
625 ParamType::Count => match int() {
626 Some(i) if (0..=i128::from(u32::MAX)).contains(&i) => Ok(Value::UInt(i as u64)),
627 _ => Err(expected(Expected::Count)),
628 },
629 ParamType::Seed => match (literal, int()) {
630 (Literal::Null, _) => Ok(Value::Null),
631 (_, Some(i)) if (0..=i128::from(u64::MAX)).contains(&i) => Ok(Value::UInt(i as u64)),
632 _ => Err(expected(Expected::Seed)),
633 },
634 ParamType::Direction(choices) => match literal {
635 Literal::String(s) => {
636 let s = direction_arg(spec.name, name, s)?;
638 match choices.iter().find(|c| **c == s.as_str()) {
639 Some(c) => Ok(Value::Str(c)),
640 None => {
641 let options: Vec<String> =
642 choices.iter().map(|o| format!("'{o}'")).collect();
643 Err(plan(format!(
644 "{}({name} => {literal}) is not supported; use one of {}",
645 spec.name,
646 options.join(", ")
647 )))
648 }
649 }
650 }
651 _ => {
652 let options: Vec<String> = choices.iter().map(|o| format!("'{o}'")).collect();
653 Err(plan(format!(
654 "{}({name} => {literal}) is not supported; use one of {}",
655 spec.name,
656 options.join(", ")
657 )))
658 }
659 },
660 other => Err(DataFusionError::Internal(format!(
661 "{}({name}): no check for a parameter of type {other:?}",
662 spec.name
663 ))),
664 }
665}
666
667pub fn resolve(spec: &'static TraversalSpec, literals: &[(String, Literal)]) -> Result<Traversal> {
671 let mut values: Vec<(&'static str, Value)> = Vec::new();
672 for p in spec.params {
673 let TraversalParamType::Param(ty) = p.ty else {
674 continue;
675 };
676 if ty == ParamType::Weight {
677 continue;
678 }
679 let value = match literals.iter().find(|(n, _)| n == p.name) {
680 Some((_, literal)) => check(spec, p.name, ty, literal)?,
681 None => p.default.ok_or_else(|| missing_param(spec, p))?,
682 };
683 values.push((p.name, value));
684 }
685 let get = |name: &str| {
686 values
687 .iter()
688 .find(|(n, _)| *n == name)
689 .map(|(_, v)| *v)
690 .expect("every literal parameter has a value")
691 };
692 let count = |name: &str| match get(name) {
693 Value::UInt(u) => u as u32,
694 other => unreachable!("a count is checked: {other:?}"),
695 };
696 let seed = |name: &str| match get(name) {
697 Value::UInt(u) => Some(u),
698 _ => None,
699 };
700 let direction = |name: &str| match get(name) {
701 Value::Str(s) => parse_direction(s).expect("a direction is checked"),
702 other => unreachable!("a direction is checked: {other:?}"),
703 };
704 Ok(match spec.name {
705 "hop" => Traversal::Hop {
706 steps: count("steps"),
707 direction: direction("direction"),
708 },
709 "shortest_path" => Traversal::ShortestPath {
710 direction: direction("direction"),
711 },
712 "random_walk" => Traversal::RandomWalk {
713 steps: count("steps"),
714 walks_per_node: count("walks_per_node"),
715 random_seed: seed("random_seed"),
716 },
717 "induced_edges" => Traversal::InducedEdges,
718 other => unreachable!("no traversal {other}"),
719 })
720}
721
722pub fn batch(
728 topology: &Topology,
729 ids: &IdMap,
730 traversal: &Traversal,
731 nodes: &[Vec<Option<u32>>],
732 weights: Option<&[f64]>,
733 edge_row: &dyn Fn(u32) -> u64,
734 schema: Arc<Schema>,
735) -> Result<RecordBatch> {
736 let known = |i: usize| -> Vec<u32> { nodes[i].iter().flatten().copied().collect() };
738 let columns: Vec<ArrayRef> = match *traversal {
739 Traversal::Hop { steps, direction } => {
740 let (seed, reached, distance) =
741 k_hop_distances_masked(topology, None, &known(0), steps, direction);
742 let distance: Vec<i64> = distance.into_iter().map(i64::from).collect();
743 vec![
744 ids.gather_user(&seed),
745 ids.gather_user(&reached),
746 Arc::new(Int64Array::from(distance)),
747 ]
748 }
749 Traversal::ShortestPath { direction } => {
750 let one = |i: usize| nodes[i].first().copied().flatten();
751 let route = match (one(0), one(1)) {
752 (Some(source), Some(target)) => match weights {
753 Some(w) => shortest_path_weighted_with_cost_masked(
754 topology, None, w, source, target, direction,
755 )
756 .map(|(path, costs)| (path, Some(costs))),
757 None => shortest_path_masked(topology, None, source, target, direction)
758 .map(|path| (path, None)),
759 },
760 _ => None,
761 };
762 let (mut src, mut dst, mut step, mut cost) = (vec![], vec![], vec![], vec![]);
763 if let Some((path, costs)) = route {
764 for (i, pair) in path.windows(2).enumerate() {
765 src.push(pair[0]);
766 dst.push(pair[1]);
767 step.push(i as i64);
768 cost.push(match &costs {
771 Some(c) => c[i + 1],
772 None => (i + 1) as f64,
773 });
774 }
775 }
776 vec![
777 ids.gather_user(&src),
778 ids.gather_user(&dst),
779 Arc::new(Int64Array::from(step)),
780 Arc::new(Float64Array::from(cost)),
781 ]
782 }
783 Traversal::RandomWalk {
784 steps,
785 walks_per_node,
786 random_seed,
787 } => {
788 let walks = random_walk_masked(
789 topology,
790 None,
791 &known(0),
792 steps,
793 walks_per_node,
794 random_seed,
795 );
796 vec![
797 Arc::new(Int64Array::from(walks.walk_id)),
798 Arc::new(Int64Array::from(walks.step)),
799 ids.gather_user(&walks.node),
800 ]
801 }
802 Traversal::InducedEdges => {
803 let edges = induced_edges(topology, &known(0));
805 let rows: Vec<i64> = edges.edge.iter().map(|&e| edge_row(e) as i64).collect();
806 vec![
807 ids.gather_user(&edges.src),
808 ids.gather_user(&edges.dst),
809 Arc::new(Int64Array::from(rows)),
810 ]
811 }
812 };
813 RecordBatch::try_new(schema, columns)
814 .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820
821 #[test]
822 fn node_id_rule() {
823 for ok in ["0", "7", "-3", "+12", "9223372036854775808"] {
824 assert!(is_integer_text(ok), "{ok}");
825 }
826 for refused in ["", "-", "1.5", "2.0", " 1", "1 ", "1e3", "0x10", "one"] {
827 assert!(!is_integer_text(refused), "{refused}");
828 }
829 for id_type in [DataType::Int64, DataType::Utf8] {
830 for ok in [
831 DataType::Null,
832 DataType::Int8,
833 DataType::UInt64,
834 DataType::Utf8View,
835 ] {
836 assert!(is_node_id_type(&ok, &id_type), "{ok}");
837 }
838 for refused in [DataType::Float64, DataType::Boolean, DataType::Date32] {
839 assert!(!is_node_id_type(&refused, &id_type), "{refused}");
840 }
841 }
842 let strings: ArrayRef = Arc::new(datafusion::arrow::array::StringArray::from(vec![
843 Some("1"),
844 None,
845 Some("2.0"),
846 ]));
847 assert_eq!(first_refused_node_id(&strings, &DataType::Int64), Some(2));
848 assert_eq!(first_refused_node_id(&strings, &DataType::Utf8), None);
849 let floats: ArrayRef = Arc::new(Float64Array::from(vec![None, Some(1.0)]));
850 assert_eq!(first_refused_node_id(&floats, &DataType::Int64), Some(1));
851 }
852
853 fn call(name: &str, args: &[(&str, Literal)]) -> Result<Traversal> {
854 let args: Vec<(String, Literal)> = args
855 .iter()
856 .map(|(n, v)| (n.to_string(), v.clone()))
857 .collect();
858 resolve(lookup(name).unwrap(), &args)
859 }
860
861 fn num(n: &str) -> Literal {
862 Literal::Number(n.into())
863 }
864
865 fn message(r: Result<Traversal>) -> String {
866 crate::user_message(&r.unwrap_err())
867 }
868
869 #[test]
870 fn defaults_match_python() {
871 assert_eq!(
872 call("hop", &[]).unwrap(),
873 Traversal::Hop {
874 steps: 1,
875 direction: Direction::Out
876 }
877 );
878 assert_eq!(
879 call("shortest_path", &[]).unwrap(),
880 Traversal::ShortestPath {
881 direction: Direction::Out
882 }
883 );
884 assert_eq!(
885 call("random_walk", &[("steps", num("4"))]).unwrap(),
886 Traversal::RandomWalk {
887 steps: 4,
888 walks_per_node: 1,
889 random_seed: None
890 }
891 );
892 }
893
894 #[test]
895 fn explains_bad_arguments() {
896 assert_eq!(
897 message(call("hop", &[("steps", num("-1"))])),
898 "hop(steps =>) must be a non-negative integer below 2^32; got -1"
899 );
900 assert_eq!(
901 message(call("hop", &[("steps", num("1.5"))])),
902 "hop(steps =>) must be a non-negative integer below 2^32; got 1.5"
903 );
904 assert_eq!(
905 message(call("hop", &[("direction", Literal::String("up".into()))])),
906 "hop(direction => 'up') is not supported; use one of 'out', 'in', 'both'"
907 );
908 assert_eq!(
909 message(call("random_walk", &[])),
910 "random_walk() needs 'steps': random_walk(<graph>, seeds => [<id>, ...], steps => \
911 <integer>, walks_per_node => 1, random_seed => NULL)"
912 );
913 assert_eq!(
914 message(call(
915 "random_walk",
916 &[
917 ("steps", num("2")),
918 ("random_seed", Literal::String("x".into()))
919 ]
920 )),
921 "random_walk(random_seed =>) must be a non-negative integer or NULL; got 'x'"
922 );
923 assert_eq!(
924 message(call(
925 "hop",
926 &[("direction", Literal::String("UNDIRECTED".into()))]
927 )),
928 "hop(direction => 'UNDIRECTED') is not supported; use 'both', which reads every \
929 edge both ways (the undirected view)"
930 );
931 assert_eq!(
932 call("hop", &[("direction", Literal::String("Both".into()))]).unwrap(),
933 Traversal::Hop {
934 steps: 1,
935 direction: Direction::Both
936 }
937 );
938 }
939
940 #[test]
943 fn suggests_the_name_to_use() {
944 let hint = |function: &str, name: &str, given: Given| {
945 crate::user_message(&unknown_param(lookup(function).unwrap(), name, Some(given)))
946 };
947 for (function, name, given, want) in [
948 ("hop", "n", Given::Integer, "steps"),
949 ("hop", "max_hops", Given::Integer, "steps"),
950 ("hop", "depth", Given::Integer, "steps"),
951 ("hop", "k", Given::Integer, "steps"),
952 ("hop", "start", Given::List, "seeds"),
953 ("hop", "stepz", Given::Integer, "steps"),
954 ("random_walk", "start", Given::List, "seeds"),
955 ("random_walk", "n", Given::Integer, "steps"),
956 ("random_walk", "seed", Given::Integer, "random_seed"),
957 ("random_walk", "seed", Given::List, "seeds"),
960 ("random_walk", "sed", Given::List, "seeds"),
961 ("shortest_path", "src", Given::Integer, "source"),
962 ("shortest_path", "dst", Given::Integer, "target"),
963 ] {
964 let message = hint(function, name, given);
965 assert!(
966 message.contains(&format!("did you mean '{want}'?")),
967 "{function}({name}): {message}"
968 );
969 }
970 assert_eq!(
971 hint("hop", "n", Given::Integer),
972 "hop() has no parameter 'n'; did you mean 'steps'? Its parameters are: seeds, \
973 steps, direction"
974 );
975 assert_eq!(
977 hint("random_walk", "stepz", Given::String),
978 "random_walk() has no parameter 'stepz'. Its parameters are: seeds, steps, \
979 walks_per_node, random_seed"
980 );
981 }
982
983 #[test]
986 fn python_names_are_sql_names() {
987 for (function, sql, _) in PYTHON_NAMES {
988 let spec = lookup(function).unwrap();
989 assert!(
990 spec.param(sql).is_some() || spec.outputs.iter().any(|o| o.name == *sql),
991 "{function} has no {sql}"
992 );
993 }
994 }
995
996 #[test]
997 fn signatures_show_defaults() {
998 assert_eq!(
999 lookup("hop").unwrap().signature(),
1000 "hop(<graph>, seeds => [<id>, ...], steps => 1, direction => 'out')"
1001 );
1002 assert_eq!(
1003 lookup("shortest_path").unwrap().signature(),
1004 "shortest_path(<graph>, source => <id>, target => <id>, weight => NULL, direction \
1005 => 'out')"
1006 );
1007 }
1008
1009 #[test]
1010 fn explain_spells_the_call() {
1011 let hop = call("hop", &[("steps", num("2"))]).unwrap();
1012 assert_eq!(
1013 hop.display(&["[0]".into()], None),
1014 "hop(seeds => [0], steps => 2, direction => 'out')"
1015 );
1016 let path = call("shortest_path", &[]).unwrap();
1017 assert_eq!(
1018 path.display(&["0".into(), "33".into()], Some("weight")),
1019 "shortest_path(source => 0, target => 33, weight => weight, direction => 'out')"
1020 );
1021 }
1022}