1use std::fmt;
41
42use datafusion::error::{DataFusionError, Result};
43use ursa_core::catalog::{
44 self, Arg, Call, ColumnType, Expected, Family, FunctionSpec, OutputSpec, ParamError,
45 ParamErrorKind, ParamSpec, ParamType, Range, Shape, Value,
46};
47
48pub const ALGORITHMS: &str = "algorithms";
50
51pub const URSA_FUNCTIONS: &str = "ursa_functions";
53
54fn in_sql(spec: &FunctionSpec) -> bool {
59 spec.family != Family::Layout || SQL_LAYOUTS.contains(&spec.name)
60}
61
62const SQL_LAYOUTS: &[&str] = &["layout_fa2", "layout_fr"];
64
65pub fn lookup(name: &str) -> Option<&'static FunctionSpec> {
67 catalog::lookup(name).filter(|s| in_sql(s))
68}
69
70pub fn specs() -> impl Iterator<Item = &'static FunctionSpec> {
72 catalog::FUNCTIONS.iter().filter(|s| in_sql(s))
73}
74
75pub fn names() -> impl Iterator<Item = &'static str> {
78 specs()
79 .map(|s| s.name)
80 .chain(super::traversal::TRAVERSALS.iter().map(|t| t.name))
81 .chain([ALGORITHMS])
82}
83
84pub const N_DROPPED_EDGES: OutputSpec = OutputSpec {
88 name: "n_dropped_edges",
89 ty: ColumnType::Int64,
90 nullable: false,
91};
92
93pub fn outputs(spec: &FunctionSpec) -> Vec<OutputSpec> {
97 let mut outputs = spec.outputs.to_vec();
98 if spec.name == "describe" {
99 outputs.push(N_DROPPED_EDGES);
100 }
101 outputs
102}
103
104pub fn is_per_node(spec: &FunctionSpec) -> bool {
107 spec.shape == Shape::PerNode
108}
109
110pub const VALUES: ParamSpec = ParamSpec {
114 name: "values",
115 ty: ParamType::Attribute,
116 default: Value::Null,
117 range: Range::ANY,
118 doc: "A query of two columns, node ids then values: the value of each node. Give this or \
119 attribute.",
120};
121
122const ATTRIBUTE_DOC: &str =
124 "An expression over the graph's node table, the value of each node. Give this or values.";
125
126const AGG_DOC: &str = "The aggregation; mean and sum need numbers, and min and max take numbers, \
129 strings, dates or times. count and n_unique return integers.";
130
131pub fn sql_params(spec: &FunctionSpec) -> impl Iterator<Item = &'static ParamSpec> {
134 let params: &'static [ParamSpec] = spec.params;
135 let values = spec.reads_attribute().then_some(&VALUES);
136 values
137 .into_iter()
138 .chain(params.iter().filter(|p| p.ty != ParamType::Dtype))
139}
140
141pub fn sql_doc(p: &ParamSpec) -> &'static str {
143 match (p.ty, p.name) {
144 (ParamType::Attribute, "attribute") => ATTRIBUTE_DOC,
145 (ParamType::Choice(_), "agg") => AGG_DOC,
146 _ => p.doc,
147 }
148}
149
150pub fn sql_type(name: &str, ty: ParamType) -> &'static str {
153 match ty {
154 ParamType::Float => "number",
155 ParamType::OptionalFloat => "number or NULL",
156 ParamType::Count => "integer",
157 ParamType::OptionalCount => "integer or NULL",
158 ParamType::Seed => "integer or NULL",
159 ParamType::Bool => "boolean",
160 ParamType::Choice(_) | ParamType::Direction(_) | ParamType::Dtype => "string",
161 ParamType::Attribute if name == VALUES.name => "query",
162 ParamType::Weight | ParamType::Attribute => "expression",
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum Given {
171 Integer,
172 Number,
174 String,
175 Boolean,
176 Null,
177 List,
179 Query,
181 Expression,
183}
184
185impl Given {
186 pub fn of_literal(literal: &Literal) -> Given {
188 match literal {
189 Literal::Number(n) if n.parse::<i128>().is_ok() => Given::Integer,
190 Literal::Number(_) => Given::Number,
191 Literal::String(_) => Given::String,
192 Literal::Boolean(_) => Given::Boolean,
193 Literal::Null => Given::Null,
194 }
195 }
196}
197
198pub fn takes(name: &str, ty: ParamType, given: Given) -> bool {
201 use Given::*;
202 match ty {
203 ParamType::Float => matches!(given, Integer | Number),
204 ParamType::OptionalFloat => matches!(given, Integer | Number | Null),
205 ParamType::Count => given == Integer,
206 ParamType::OptionalCount | ParamType::Seed => matches!(given, Integer | Null),
207 ParamType::Bool => given == Boolean,
208 ParamType::Choice(_) | ParamType::Direction(_) | ParamType::Dtype => given == String,
209 ParamType::Attribute if name == VALUES.name => given == Query,
210 ParamType::Weight => matches!(given, Integer | Number | Null | Expression),
211 ParamType::Attribute => !matches!(given, List | Query),
212 }
213}
214
215pub const OTHER_NAMES: &[(&str, &[&str])] = &[
221 (
222 "seeds",
223 &[
224 "start",
225 "starts",
226 "start_nodes",
227 "sources",
228 "seed_nodes",
229 "roots",
230 ],
231 ),
232 (
233 "steps",
234 &[
235 "n",
236 "k",
237 "hops",
238 "max_hops",
239 "depth",
240 "max_depth",
241 "length",
242 "walk_length",
243 ],
244 ),
245 ("random_seed", &["seed", "rng_seed", "random_state"]),
246 ("source", &["src", "start_node", "from"]),
247 ("target", &["dst", "end_node", "to"]),
248 ("walks_per_node", &["walks", "num_walks", "n_walks"]),
249 ("damping", &["alpha", "damping_factor"]),
250 ("direction", &["dir", "orientation"]),
251 ("weight", &["weights", "weight_column"]),
252];
253
254pub fn suggest<'a>(
259 name: &str,
260 given: Option<Given>,
261 params: &[(&'a str, &dyn Fn(Given) -> bool)],
262) -> Option<&'a str> {
263 let fits = |takes: &dyn Fn(Given) -> bool| given.is_none_or(takes);
264 let fitting: Vec<&'a str> = params
265 .iter()
266 .filter(|(_, takes)| fits(*takes))
267 .map(|(n, _)| *n)
268 .collect();
269 OTHER_NAMES
270 .iter()
271 .filter(|(_, others)| others.contains(&name))
272 .find_map(|(ours, _)| fitting.iter().find(|n| *n == ours).copied())
273 .or_else(|| did_you_mean(name, fitting.iter().copied()))
274}
275
276pub fn unknown_param_text(
278 function: &str,
279 name: &str,
280 given: Option<Given>,
281 params: &[(&str, &dyn Fn(Given) -> bool)],
282) -> String {
283 let names: Vec<&str> = params.iter().map(|(n, _)| *n).collect();
284 let hint = suggest(name, given, params)
285 .map(|s| format!("; did you mean '{s}'?"))
286 .unwrap_or_else(|| ".".to_string());
287 format!(
288 "{function}() has no parameter '{name}'{hint} Its parameters are: {}",
289 names.join(", ")
290 )
291}
292
293pub fn direction_arg(function: &str, param: &str, text: &str) -> Result<String> {
297 let lower = text.to_lowercase();
298 if lower == "undirected" {
299 return Err(plan(format!(
300 "{function}({param} => '{}') is not supported; use 'both', which reads every edge \
301 both ways (the undirected view)",
302 text.replace('\'', "''")
303 )));
304 }
305 Ok(lower)
306}
307
308#[derive(Debug, Clone, PartialEq)]
311pub enum Literal {
312 Number(String),
315 String(String),
316 Boolean(bool),
317 Null,
318}
319
320impl fmt::Display for Literal {
321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322 match self {
323 Literal::Number(n) => write!(f, "{n}"),
324 Literal::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
325 Literal::Boolean(b) => write!(f, "{b}"),
326 Literal::Null => write!(f, "NULL"),
327 }
328 }
329}
330
331impl Literal {
332 fn to_arg(&self) -> Arg {
335 match self {
336 Literal::Number(n) => n
337 .parse::<i128>()
338 .map(Arg::Int)
339 .or_else(|_| n.parse::<f64>().map(Arg::Float))
340 .unwrap_or(Arg::Other),
341 Literal::String(s) => Arg::Str(s.clone()),
342 Literal::Boolean(b) => Arg::Bool(*b),
343 Literal::Null => Arg::Null,
344 }
345 }
346}
347
348pub fn resolve(spec: &'static FunctionSpec, args: &[(String, Literal)]) -> Result<Call> {
351 if spec.narrows() {
352 if let Some((name, _)) = args.iter().find(|(n, _)| n == "dtype") {
353 let column = spec.outputs.first().map_or(spec.name, |o| o.name);
354 return Err(plan(format!(
355 "{}() has no parameter '{name}' in SQL; cast its column instead, for example \
356 CAST({column} AS REAL)",
357 spec.name
358 )));
359 }
360 }
361 let mut read = Vec::with_capacity(args.len());
363 for (name, literal) in args {
364 let literal = match (spec.param(name).map(|p| p.ty), literal) {
365 (Some(ParamType::Direction(_)), Literal::String(text)) => {
366 Literal::String(direction_arg(spec.name, name, text)?)
367 }
368 (_, other) => other.clone(),
369 };
370 read.push((name.as_str(), literal));
371 }
372 spec.resolve(read.iter().map(|(n, l)| (*n, l.to_arg())))
373 .map(|resolved| resolved.call)
374 .map_err(|e| param_error(spec, &e, args))
375}
376
377fn param_error(spec: &FunctionSpec, e: &ParamError, args: &[(String, Literal)]) -> DataFusionError {
379 let (f, p) = (spec.name, e.param.as_str());
380 let given = || {
381 args.iter()
382 .find(|(n, _)| n == p)
383 .map_or(Literal::Null, |(_, l)| l.clone())
384 };
385 match e.kind {
386 ParamErrorKind::Unknown => {
387 let given = args
388 .iter()
389 .find(|(n, _)| n == p)
390 .map(|(_, l)| Given::of_literal(l));
391 unknown_param(spec, p, given)
392 }
393 ParamErrorKind::Duplicate => plan(format!("{f}() was given '{p}' more than once")),
394 ParamErrorKind::Expected(want) => plan(format!(
395 "{f}({p} =>) must be {}; got {}",
396 expected_text(want),
397 given()
398 )),
399 ParamErrorKind::OutOfRange(range) => plan(format!(
400 "{f}({p} =>) must be {}; got {}",
401 range_text(&range).unwrap_or_else(|| "a number".into()),
402 given()
403 )),
404 ParamErrorKind::NotOneOf(options) => {
405 let options: Vec<String> = options.iter().map(|o| format!("'{o}'")).collect();
406 plan(format!(
407 "{f}({p} => {}) is not supported; use one of {}",
408 given(),
409 options.join(", ")
410 ))
411 }
412 ParamErrorKind::Expression => plan(format!(
413 "{f}({p} =>) takes an expression over the edge table's columns; got {}",
414 given()
415 )),
416 }
417}
418
419pub(crate) fn expected_text(want: Expected) -> &'static str {
421 match want {
422 Expected::Number => "a number",
423 Expected::FiniteNumber => "a finite number",
424 Expected::Count => "a non-negative integer below 2^32",
425 Expected::CountOrNull => "a non-negative integer below 2^32, or NULL",
426 Expected::Seed => "a non-negative integer or NULL",
427 Expected::NumberOrNull => "a number or NULL",
428 Expected::Bool => "a boolean",
429 }
430}
431
432pub fn range_text(range: &Range) -> Option<String> {
437 range.describe()
438}
439
440pub fn unknown_param(spec: &FunctionSpec, name: &str, given: Option<Given>) -> DataFusionError {
443 let params: Vec<&ParamSpec> = sql_params(spec).collect();
444 if params.is_empty() {
445 return plan(format!(
446 "{}() takes no parameters besides the graph; got '{name}'",
447 spec.name
448 ));
449 }
450 if name == "direction" {
452 if let Some(mode) = spec.param("mode") {
453 let choices: Vec<String> = mode.ty.choices().iter().map(|c| format!("'{c}'")).collect();
454 return plan(format!(
455 "{}() has no parameter 'direction'; use mode => {} ('weak' ignores edge \
456 direction, 'strong' needs a path each way)",
457 spec.name,
458 choices.join(" or ")
459 ));
460 }
461 }
462 let takers: Vec<Box<dyn Fn(Given) -> bool>> = params
463 .iter()
464 .map(|p| {
465 let (n, ty) = (p.name, p.ty);
466 Box::new(move |g| takes(n, ty, g)) as Box<dyn Fn(Given) -> bool>
467 })
468 .collect();
469 let entries: Vec<(&str, &dyn Fn(Given) -> bool)> = params
470 .iter()
471 .zip(&takers)
472 .map(|(p, t)| (p.name, t.as_ref()))
473 .collect();
474 plan(unknown_param_text(spec.name, name, given, &entries))
475}
476
477pub fn sql_value(value: &Value) -> String {
479 match value {
480 Value::Null => "NULL".to_string(),
481 Value::Bool(b) => b.to_string(),
482 Value::UInt(u) => u.to_string(),
483 Value::Float(f) => format!("{f:?}"),
484 Value::Str(s) => format!("'{s}'"),
485 }
486}
487
488fn defaults(spec: &FunctionSpec) -> Vec<String> {
492 sql_params(spec)
493 .filter_map(|p| match (p.ty, p.name) {
494 (ParamType::Attribute, "values") => Some(format!("{} => {VALUES_QUERY}", p.name)),
495 (ParamType::Attribute, _) => None,
496 _ => Some(format!("{} => {}", p.name, sql_value(&p.default))),
497 })
498 .collect()
499}
500
501pub const VALUES_QUERY: &str = "(SELECT id, value FROM ...)";
503
504pub fn signature(spec: &FunctionSpec) -> String {
507 let mut parts = vec!["<graph>".to_string()];
508 parts.extend(defaults(spec));
509 format!("{}({})", spec.name, parts.join(", "))
510}
511
512pub fn nested_signature(spec: &FunctionSpec) -> String {
514 format!("{}({})", spec.name, defaults(spec).join(", "))
515}
516
517pub fn display_call(call: &Call, weight: Option<&str>) -> String {
520 let values = call.values();
521 let parts: Vec<String> = sql_params(call.spec())
522 .filter_map(|p| {
523 if p.ty == ParamType::Weight {
524 return weight.map(|w| format!("{} => {w}", p.name));
525 }
526 values
527 .iter()
528 .find(|(q, _)| q.name == p.name)
529 .map(|(_, v)| format!("{} => {}", p.name, sql_value(v)))
530 })
531 .collect();
532 format!("{}({})", call.name(), parts.join(", "))
533}
534
535pub(crate) fn plan(message: String) -> DataFusionError {
537 DataFusionError::Plan(message)
538}
539
540pub fn did_you_mean<'a>(
543 name: &str,
544 candidates: impl IntoIterator<Item = &'a str>,
545) -> Option<&'a str> {
546 super::closest_name(name, candidates)
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552 use ursa_core::catalog::Value;
553 use ursa_core::Direction;
554
555 fn call(name: &str, args: &[(&str, Literal)]) -> Result<Call> {
556 let args: Vec<(String, Literal)> = args
557 .iter()
558 .map(|(n, v)| (n.to_string(), v.clone()))
559 .collect();
560 resolve(lookup(name).unwrap(), &args)
561 }
562
563 fn num(n: &str) -> Literal {
564 Literal::Number(n.into())
565 }
566
567 fn s(v: &str) -> Literal {
568 Literal::String(v.into())
569 }
570
571 fn message(r: Result<Call>) -> String {
572 crate::user_message(&r.unwrap_err())
573 }
574
575 #[test]
576 fn defaults_match_python() {
577 assert_eq!(
578 call("pagerank", &[]).unwrap(),
579 Call::PageRank {
580 damping: 0.85,
581 max_iter: 30,
582 tol: 1e-6,
583 direction: Direction::Out
584 }
585 );
586 assert_eq!(
587 call("degree", &[]).unwrap(),
588 Call::Degree {
589 direction: Direction::Out
590 }
591 );
592 assert_eq!(
593 call("connected_components", &[]).unwrap(),
594 Call::ConnectedComponents { strong: false }
595 );
596 assert_eq!(
597 call("louvain", &[]).unwrap(),
598 Call::Louvain {
599 resolution: 1.0,
600 seed: None,
601 parallel: false
602 }
603 );
604 assert_eq!(call("triangle_count", &[]).unwrap(), Call::TriangleCount);
605 assert_eq!(
606 call("diameter", &[]).unwrap(),
607 Call::Diameter {
608 approximate: true,
609 direction: Direction::Out
610 }
611 );
612 }
613
614 #[test]
615 fn reads_arguments() {
616 assert_eq!(
617 call(
618 "pagerank",
619 &[
620 ("damping", num("0.9")),
621 ("max_iter", num("100")),
622 ("tol", num("1e-10")),
623 ("direction", s("both"))
624 ]
625 )
626 .unwrap(),
627 Call::PageRank {
628 damping: 0.9,
629 max_iter: 100,
630 tol: 1e-10,
631 direction: Direction::Both
632 }
633 );
634 assert!(call("pagerank", &[("damping", num("1"))]).is_ok());
636 for (function, param, value) in [
639 ("pagerank", "damping", num("0")),
640 ("pagerank", "max_iter", num("1")),
641 ("pagerank", "tol", num("0")),
642 ("betweenness", "sample", num("1")),
643 ("betweenness", "sample", num("1e-9")),
644 ("betweenness", "sample", Literal::Null),
645 ("avg_path_length", "sample", num("1.0")),
646 ("layout_fa2", "gravity", num("0")),
647 ("layout_fa2", "theta", num("0")),
648 ("layout_fa2", "theta", Literal::Null),
649 ("layout_fa2", "iterations", num("0")),
650 ("layout_fr", "iterations", num("0")),
651 ] {
652 assert!(
653 call(function, &[(param, value)]).is_ok(),
654 "{function} {param}"
655 );
656 }
657 assert_eq!(
658 call("louvain", &[("seed", num("7")), ("resolution", num("0.5"))]).unwrap(),
659 Call::Louvain {
660 resolution: 0.5,
661 seed: Some(7),
662 parallel: false
663 }
664 );
665 assert_eq!(
666 call("louvain", &[("seed", Literal::Null)]).unwrap(),
667 call("louvain", &[]).unwrap()
668 );
669 assert_eq!(
670 call("connected_components", &[("mode", s("strong"))]).unwrap(),
671 Call::ConnectedComponents { strong: true }
672 );
673 assert_eq!(
674 call("diameter", &[("approximate", Literal::Boolean(false))]).unwrap(),
675 Call::Diameter {
676 approximate: false,
677 direction: Direction::Out
678 }
679 );
680 assert_eq!(
681 call("betweenness", &[("sample", Literal::Null)]).unwrap(),
682 call("betweenness", &[]).unwrap()
683 );
684 }
685
686 #[test]
687 fn explains_bad_arguments() {
688 assert_eq!(
689 message(call("pagerank", &[("dampng", num("0.9"))])),
690 "pagerank() has no parameter 'dampng'; did you mean 'damping'? Its parameters are: \
691 damping, max_iter, tol, weight, direction"
692 );
693 assert_eq!(
694 message(call("pagerank", &[("color", num("1"))])),
695 "pagerank() has no parameter 'color'. Its parameters are: damping, max_iter, tol, \
696 weight, direction"
697 );
698 assert_eq!(
699 message(call("triangle_count", &[("direction", s("both"))])),
700 "triangle_count() takes no parameters besides the graph; got 'direction'"
701 );
702 assert_eq!(
703 message(call(
704 "pagerank",
705 &[("damping", num("0.9")), ("damping", num("0.8"))]
706 )),
707 "pagerank() was given 'damping' more than once"
708 );
709 assert_eq!(
710 message(call("pagerank", &[("damping", s("high"))])),
711 "pagerank(damping =>) must be a number; got 'high'"
712 );
713 assert_eq!(
714 message(call("pagerank", &[("damping", num("1e999"))])),
715 "pagerank(damping =>) must be a finite number; got 1e999"
716 );
717 assert_eq!(
718 message(call("pagerank", &[("max_iter", num("-1"))])),
719 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got -1"
720 );
721 assert_eq!(
722 message(call("pagerank", &[("max_iter", num("2.5"))])),
723 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got 2.5"
724 );
725 assert_eq!(
726 message(call("pagerank", &[("max_iter", num("4294967296"))])),
727 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got 4294967296"
728 );
729 assert_eq!(
730 message(call("pagerank", &[("max_iter", Literal::Null)])),
731 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got NULL"
732 );
733 assert_eq!(
734 message(call("louvain", &[("seed", num("-3"))])),
735 "louvain(seed =>) must be a non-negative integer or NULL; got -3"
736 );
737 assert_eq!(
738 message(call("betweenness", &[("sample", s("half"))])),
739 "betweenness(sample =>) must be a number or NULL; got 'half'"
740 );
741 for (function, param, value, range) in [
744 ("pagerank", "damping", "-1", "between 0 and 1"),
745 ("pagerank", "damping", "1.5", "between 0 and 1"),
746 ("pagerank", "max_iter", "0", "at least 1"),
747 ("pagerank", "tol", "-1", "at least 0"),
748 ("label_propagation", "max_iter", "0", "at least 1"),
749 ("betweenness", "sample", "2", "above 0 and at most 1"),
750 ("betweenness", "sample", "-1", "above 0 and at most 1"),
751 ("betweenness", "sample", "0", "above 0 and at most 1"),
752 ("avg_path_length", "sample", "5", "above 0 and at most 1"),
753 ("louvain", "resolution", "-1", "above 0"),
754 ("louvain", "resolution", "0.0", "above 0"),
755 ("layout_fa2", "k", "0", "above 0"),
756 ("layout_fa2", "gravity", "-0.5", "at least 0"),
757 ("layout_fa2", "theta", "-1", "at least 0"),
758 ("layout_fa2", "jitter_tolerance", "0", "above 0"),
759 ("layout_fr", "k", "-2", "above 0"),
760 ("layout_fr", "gravity", "-1e-3", "at least 0"),
761 ] {
762 assert_eq!(
763 message(call(function, &[(param, num(value))])),
764 format!("{function}({param} =>) must be {range}; got {value}")
765 );
766 }
767 assert_eq!(
768 message(call("diameter", &[("approximate", num("1"))])),
769 "diameter(approximate =>) must be a boolean; got 1"
770 );
771 assert_eq!(
772 message(call("pagerank", &[("direction", s("up"))])),
773 "pagerank(direction => 'up') is not supported; use one of 'out', 'in', 'both'"
774 );
775 assert_eq!(
776 message(call("degree", &[("direction", s("sideways"))])),
777 "degree(direction => 'sideways') is not supported; use one of 'out', 'in', 'both'"
778 );
779 assert_eq!(
780 message(call("connected_components", &[("mode", num("1"))])),
781 "connected_components(mode => 1) is not supported; use one of 'weak', 'strong'"
782 );
783 assert_eq!(
784 message(call("closeness", &[("dtype", s("f32"))])),
785 "closeness() has no parameter 'dtype' in SQL; cast its column instead, for example \
786 CAST(closeness AS REAL)"
787 );
788 assert_eq!(
789 message(call("degree", &[("dtype", s("f32"))])),
790 "degree() has no parameter 'dtype'. Its parameters are: direction"
791 );
792 }
793
794 #[test]
797 fn directions_in_any_case() {
798 for (function, text, want) in [
799 ("pagerank", "BOTH", Direction::Both),
800 ("pagerank", "In", Direction::In),
801 ("betweenness", "in", Direction::In),
802 ("degree", "Out", Direction::Out),
803 ] {
804 let got = call(function, &[("direction", s(text))]).unwrap();
805 let direction = got
806 .values()
807 .into_iter()
808 .find(|(p, _)| p.name == "direction")
809 .map(|(_, v)| v);
810 assert_eq!(
811 direction,
812 Some(Value::Str(ursa_core::catalog::direction_name(want))),
813 "{function} {text}"
814 );
815 }
816 assert_eq!(
817 message(call("closeness", &[("direction", s("Undirected"))])),
818 "closeness(direction => 'Undirected') is not supported; use 'both', which reads \
819 every edge both ways (the undirected view)"
820 );
821 assert_eq!(
822 message(call("degree", &[("direction", s("Sideways"))])),
823 "degree(direction => 'Sideways') is not supported; use one of 'out', 'in', 'both'"
824 );
825 }
826
827 #[test]
830 fn suggestions_fit_the_value() {
831 assert_eq!(
832 message(call("pagerank", &[("alpha", num("0.5"))])),
833 "pagerank() has no parameter 'alpha'; did you mean 'damping'? Its parameters are: \
834 damping, max_iter, tol, weight, direction"
835 );
836 assert_eq!(
838 message(call("pagerank", &[("dampng", s("high"))])),
839 "pagerank() has no parameter 'dampng'. Its parameters are: damping, max_iter, tol, \
840 weight, direction"
841 );
842 assert_eq!(
843 message(call("connected_components", &[("direction", s("both"))])),
844 "connected_components() has no parameter 'direction'; use mode => 'weak' or \
845 'strong' ('weak' ignores edge direction, 'strong' needs a path each way)"
846 );
847 let spec = lookup("louvain").unwrap();
848 assert_eq!(
849 crate::user_message(&unknown_param(spec, "sed", Some(Given::Integer))),
850 "louvain() has no parameter 'sed'; did you mean 'seed'? Its parameters are: weight, \
851 resolution, seed, parallel"
852 );
853 assert_eq!(
854 crate::user_message(&unknown_param(spec, "sed", Some(Given::List))),
855 "louvain() has no parameter 'sed'. Its parameters are: weight, resolution, seed, \
856 parallel"
857 );
858 }
859
860 #[test]
864 fn one_name_per_role() {
865 use super::super::traversal::{TraversalParamType, TRAVERSALS};
866 let kind = |name: &str, ty: ParamType| sql_type(name, ty).trim_end_matches(" or NULL");
868 let mut params: Vec<(&str, &str, &str)> = Vec::new();
869 for spec in specs() {
870 for p in sql_params(spec) {
871 params.push((spec.name, p.name, kind(p.name, p.ty)));
872 }
873 }
874 for spec in TRAVERSALS {
875 for p in spec.params {
876 let k = match p.ty {
877 TraversalParamType::Nodes => "node ids",
878 TraversalParamType::Node => "node id",
879 TraversalParamType::Param(ty) => kind(p.name, ty),
880 };
881 params.push((spec.name, p.name, k));
882 }
883 }
884 const SPLIT: &[(&str, &str)] = &[("seed", "random_seed")];
888 const TWO_KINDS: &[&str] = &["nodes"];
892 for (f, name, k) in ¶ms {
894 for (g, other, l) in ¶ms {
895 assert!(
896 name != other || k == l || TWO_KINDS.contains(name),
897 "{f}({name}) takes {k} but {g}({other}) takes {l}"
898 );
899 }
900 }
901 for (ours, others) in OTHER_NAMES {
902 let kinds: Vec<&str> = params
903 .iter()
904 .filter(|(_, n, _)| n == ours)
905 .map(|(_, _, k)| *k)
906 .collect();
907 assert!(!kinds.is_empty(), "no function has a parameter '{ours}'");
908 for (f, name, k) in ¶ms {
910 if SPLIT.contains(&(*name, *ours)) {
911 continue;
912 }
913 assert!(
914 !(others.contains(name) && kinds.contains(k)),
915 "{f}({name}) is what the other functions call '{ours}'"
916 );
917 }
918 }
919 for (i, (ours, others)) in OTHER_NAMES.iter().enumerate() {
921 for (theirs, alternatives) in &OTHER_NAMES[i + 1..] {
922 for name in *others {
923 assert!(
924 !alternatives.contains(name),
925 "'{name}' points to both '{ours}' and '{theirs}'"
926 );
927 }
928 }
929 }
930 }
931
932 #[test]
933 fn suggests_names() {
934 assert_eq!(did_you_mean("pagerenk", names()), Some("pagerank"));
935 assert_eq!(did_you_mean("closenes", names()), Some("closeness"));
936 assert_eq!(did_you_mean("algorithm", names()), Some("algorithms"));
937 assert_eq!(
938 did_you_mean("shortest_paths", names()),
939 Some("shortest_path")
940 );
941 assert_eq!(did_you_mean("random_walks", names()), Some("random_walk"));
942 assert_eq!(did_you_mean("dijkstra", names()), None);
943 assert_eq!(did_you_mean("neighbor_agg", names()), Some("neighbors_agg"));
944 }
945
946 #[test]
947 fn neighbors_agg_takes_values_or_an_attribute() {
948 let spec = lookup("neighbors_agg").unwrap();
949 let params: Vec<&str> = sql_params(spec).map(|p| p.name).collect();
950 assert_eq!(params, ["values", "direction", "attribute", "agg"]);
951 assert_eq!(
952 signature(spec),
953 "neighbors_agg(<graph>, values => (SELECT id, value FROM ...), direction => 'out', \
954 agg => 'mean')"
955 );
956 assert_eq!(
957 call(
958 "neighbors_agg",
959 &[("agg", s("n_unique")), ("direction", s("both"))]
960 )
961 .unwrap(),
962 Call::NeighborAgg {
963 direction: Direction::Both,
964 agg: ursa_core::algo::AggKind::NUnique
965 }
966 );
967 assert_eq!(
968 message(call("neighbors_agg", &[("agg", s("median"))])),
969 "neighbors_agg(agg => 'median') is not supported; use one of 'mean', 'sum', 'min', \
970 'max', 'count', 'n_unique'"
971 );
972 }
973
974 #[test]
975 fn the_trivial_layouts_are_hidden() {
976 for name in ["layout_random", "layout_circle"] {
977 assert!(catalog::lookup(name).is_some(), "{name} is in the catalog");
978 assert!(lookup(name).is_none(), "{name} is hidden from SQL");
979 assert!(names().all(|n| n != name));
980 assert!(specs().all(|s| s.name != name));
981 }
982 for name in ["layout_fa2", "layout_fr"] {
983 assert!(lookup(name).is_some(), "{name} is in SQL");
984 assert!(names().any(|n| n == name));
985 }
986 for typo in ["layout_randm", "layout_circl"] {
988 let suggestion = did_you_mean(typo, names());
989 assert!(
990 !matches!(suggestion, Some("layout_random" | "layout_circle")),
991 "{typo}: {suggestion:?}"
992 );
993 }
994 assert_eq!(did_you_mean("layout_frr", names()), Some("layout_fr"));
995 }
996
997 #[test]
998 fn signatures_show_defaults() {
999 assert_eq!(
1000 signature(lookup("pagerank").unwrap()),
1001 "pagerank(<graph>, damping => 0.85, max_iter => 30, tol => 1e-6, weight => NULL, \
1002 direction => 'out')"
1003 );
1004 assert_eq!(
1005 nested_signature(lookup("louvain").unwrap()),
1006 "louvain(weight => NULL, resolution => 1.0, seed => NULL, parallel => false)"
1007 );
1008 }
1009
1010 #[test]
1011 fn explain_spells_the_call() {
1012 let pagerank = call("pagerank", &[]).unwrap();
1013 assert_eq!(
1014 display_call(&pagerank, None),
1015 "pagerank(damping => 0.85, max_iter => 30, tol => 1e-6, direction => 'out')"
1016 );
1017 assert_eq!(
1018 display_call(&pagerank, Some("w")),
1019 "pagerank(damping => 0.85, max_iter => 30, tol => 1e-6, weight => w, \
1020 direction => 'out')"
1021 );
1022 assert_eq!(
1023 display_call(&call("louvain", &[]).unwrap(), None),
1024 "louvain(resolution => 1.0, seed => NULL, parallel => false)"
1025 );
1026 assert_eq!(
1027 display_call(&call("triangle_count", &[]).unwrap(), None),
1028 "triangle_count()"
1029 );
1030 }
1031}