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
84#[derive(Debug)]
94pub struct DuckPgqName {
95 pub name: &'static str,
97 pub function: &'static str,
99 pub fixed: &'static [(&'static str, &'static str)],
101 pub column: &'static str,
105}
106
107pub const DUCKPGQ_NAMES: &[DuckPgqName] = &[
110 DuckPgqName {
111 name: "weakly_connected_component",
112 function: "connected_components",
113 fixed: &[("mode", "weak")],
114 column: "componentid",
115 },
116 DuckPgqName {
117 name: "local_clustering_coefficient",
118 function: "clustering_coefficient",
119 fixed: &[],
120 column: "local_clustering_coefficient",
121 },
122];
123
124pub const DUCKPGQ_SAME: &[&str] = &["pagerank"];
127
128pub fn duckpgq(name: &str) -> Option<&'static DuckPgqName> {
130 DUCKPGQ_NAMES.iter().find(|d| d.name == name)
131}
132
133impl DuckPgqName {
134 pub fn spec(&self) -> &'static FunctionSpec {
136 lookup(self.function).expect("a DuckPGQ name runs a function SQL has")
137 }
138
139 pub fn ursa_call(&self) -> String {
142 let mut parts = vec!["<graph>".to_string()];
143 parts.extend(self.fixed.iter().map(|(p, v)| format!("{p} => '{v}'")));
144 format!("{}({})", self.function, parts.join(", "))
145 }
146
147 pub fn summary(&self) -> String {
149 format!(
150 "DuckPGQ's name for {}, with DuckPGQ's column name, {}. Values are Ursa's: {}",
151 self.ursa_call(),
152 self.column,
153 self.spec().summary
154 )
155 }
156
157 pub fn fixed_param(&self, param: &str) -> Option<String> {
160 self.fixed.iter().any(|(p, _)| *p == param).then(|| {
161 format!(
162 "{}() is DuckPGQ's name for {}, so it takes no '{param}'; for another \
163 {param}, call {}({param} => …)",
164 self.name,
165 self.ursa_call(),
166 self.function
167 )
168 })
169 }
170}
171
172pub const DUCKPGQ_PATH_FUNCTIONS: &[&str] = &[
175 "iterativelength",
176 "shortestpath",
177 "reachability",
178 "cheapest_path_length",
179];
180
181pub fn duckpgq_path_function(name: &str) -> Option<String> {
184 let name = name.to_ascii_lowercase();
185 DUCKPGQ_PATH_FUNCTIONS.contains(&name.as_str()).then(|| {
186 format!(
187 "{name}() is DuckPGQ's internal path function over its CSR, which Ursa does not \
188 have. Find paths with GRAPH_TABLE (g MATCH p = ANY SHORTEST (a)-[e]->*(b) \
189 COLUMNS (path_length(p) AS len)), or the table function shortest_path(g, \
190 source => …, target => …)"
191 )
192 })
193}
194
195pub const N_DROPPED_EDGES: OutputSpec = OutputSpec {
199 name: "n_dropped_edges",
200 ty: ColumnType::Int64,
201 nullable: false,
202};
203
204pub fn outputs(spec: &FunctionSpec) -> Vec<OutputSpec> {
208 let mut outputs = spec.outputs.to_vec();
209 if spec.name == "describe" {
210 outputs.push(N_DROPPED_EDGES);
211 }
212 outputs
213}
214
215pub fn is_per_node(spec: &FunctionSpec) -> bool {
218 spec.shape == Shape::PerNode
219}
220
221pub const VALUES: ParamSpec = ParamSpec {
225 name: "values",
226 ty: ParamType::Attribute,
227 default: Value::Null,
228 range: Range::ANY,
229 doc: "A query of two columns, node ids then values: the value of each node. Give this or \
230 attribute.",
231};
232
233const ATTRIBUTE_DOC: &str =
235 "An expression over the graph's node table, the value of each node. Give this or values.";
236
237const AGG_DOC: &str = "The aggregation; mean and sum need numbers, and min and max take numbers, \
240 strings, dates or times. count and n_unique return integers.";
241
242pub fn sql_params(spec: &FunctionSpec) -> impl Iterator<Item = &'static ParamSpec> {
245 let params: &'static [ParamSpec] = spec.params;
246 let values = spec.reads_attribute().then_some(&VALUES);
247 values
248 .into_iter()
249 .chain(params.iter().filter(|p| p.ty != ParamType::Dtype))
250}
251
252pub fn sql_doc(p: &ParamSpec) -> &'static str {
254 match (p.ty, p.name) {
255 (ParamType::Attribute, "attribute") => ATTRIBUTE_DOC,
256 (ParamType::Choice(_), "agg") => AGG_DOC,
257 _ => p.doc,
258 }
259}
260
261pub fn sql_type(name: &str, ty: ParamType) -> &'static str {
264 match ty {
265 ParamType::Float => "number",
266 ParamType::OptionalFloat => "number or NULL",
267 ParamType::Count => "integer",
268 ParamType::OptionalCount => "integer or NULL",
269 ParamType::Seed => "integer or NULL",
270 ParamType::Bool => "boolean",
271 ParamType::Choice(_) | ParamType::Direction(_) | ParamType::Dtype => "string",
272 ParamType::Attribute if name == VALUES.name => "query",
273 ParamType::Weight | ParamType::Attribute => "expression",
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum Given {
282 Integer,
283 Number,
285 String,
286 Boolean,
287 Null,
288 List,
290 Query,
292 Expression,
294}
295
296impl Given {
297 pub fn of_literal(literal: &Literal) -> Given {
299 match literal {
300 Literal::Number(n) if n.parse::<i128>().is_ok() => Given::Integer,
301 Literal::Number(_) => Given::Number,
302 Literal::String(_) => Given::String,
303 Literal::Boolean(_) => Given::Boolean,
304 Literal::Null => Given::Null,
305 }
306 }
307}
308
309pub fn takes(name: &str, ty: ParamType, given: Given) -> bool {
312 use Given::*;
313 match ty {
314 ParamType::Float => matches!(given, Integer | Number),
315 ParamType::OptionalFloat => matches!(given, Integer | Number | Null),
316 ParamType::Count => given == Integer,
317 ParamType::OptionalCount | ParamType::Seed => matches!(given, Integer | Null),
318 ParamType::Bool => given == Boolean,
319 ParamType::Choice(_) | ParamType::Direction(_) | ParamType::Dtype => given == String,
320 ParamType::Attribute if name == VALUES.name => given == Query,
321 ParamType::Weight => matches!(given, Integer | Number | Null | Expression),
322 ParamType::Attribute => !matches!(given, List | Query),
323 }
324}
325
326pub const OTHER_NAMES: &[(&str, &[&str])] = &[
332 (
333 "seeds",
334 &[
335 "start",
336 "starts",
337 "start_nodes",
338 "sources",
339 "seed_nodes",
340 "roots",
341 ],
342 ),
343 (
344 "steps",
345 &[
346 "n",
347 "k",
348 "hops",
349 "max_hops",
350 "depth",
351 "max_depth",
352 "length",
353 "walk_length",
354 ],
355 ),
356 ("random_seed", &["seed", "rng_seed", "random_state"]),
357 ("source", &["src", "start_node", "from"]),
358 ("target", &["dst", "end_node", "to"]),
359 ("walks_per_node", &["walks", "num_walks", "n_walks"]),
360 ("damping", &["alpha", "damping_factor"]),
361 ("direction", &["dir", "orientation"]),
362 ("weight", &["weights", "weight_column"]),
363];
364
365pub fn suggest<'a>(
370 name: &str,
371 given: Option<Given>,
372 params: &[(&'a str, &dyn Fn(Given) -> bool)],
373) -> Option<&'a str> {
374 let fits = |takes: &dyn Fn(Given) -> bool| given.is_none_or(takes);
375 let fitting: Vec<&'a str> = params
376 .iter()
377 .filter(|(_, takes)| fits(*takes))
378 .map(|(n, _)| *n)
379 .collect();
380 OTHER_NAMES
381 .iter()
382 .filter(|(_, others)| others.contains(&name))
383 .find_map(|(ours, _)| fitting.iter().find(|n| *n == ours).copied())
384 .or_else(|| did_you_mean(name, fitting.iter().copied()))
385}
386
387pub fn unknown_param_text(
389 function: &str,
390 name: &str,
391 given: Option<Given>,
392 params: &[(&str, &dyn Fn(Given) -> bool)],
393) -> String {
394 let names: Vec<&str> = params.iter().map(|(n, _)| *n).collect();
395 let hint = suggest(name, given, params)
396 .map(|s| format!("; did you mean '{s}'?"))
397 .unwrap_or_else(|| ".".to_string());
398 format!(
399 "{function}() has no parameter '{name}'{hint} Its parameters are: {}",
400 names.join(", ")
401 )
402}
403
404pub fn direction_arg(function: &str, param: &str, text: &str) -> Result<String> {
408 let lower = text.to_lowercase();
409 if lower == "undirected" {
410 return Err(plan(format!(
411 "{function}({param} => '{}') is not supported; use 'both', which reads every edge \
412 both ways (the undirected view)",
413 text.replace('\'', "''")
414 )));
415 }
416 Ok(lower)
417}
418
419#[derive(Debug, Clone, PartialEq)]
422pub enum Literal {
423 Number(String),
426 String(String),
427 Boolean(bool),
428 Null,
429}
430
431impl fmt::Display for Literal {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 match self {
434 Literal::Number(n) => write!(f, "{n}"),
435 Literal::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
436 Literal::Boolean(b) => write!(f, "{b}"),
437 Literal::Null => write!(f, "NULL"),
438 }
439 }
440}
441
442impl Literal {
443 fn to_arg(&self) -> Arg {
446 match self {
447 Literal::Number(n) => n
448 .parse::<i128>()
449 .map(Arg::Int)
450 .or_else(|_| n.parse::<f64>().map(Arg::Float))
451 .unwrap_or(Arg::Other),
452 Literal::String(s) => Arg::Str(s.clone()),
453 Literal::Boolean(b) => Arg::Bool(*b),
454 Literal::Null => Arg::Null,
455 }
456 }
457}
458
459pub fn resolve(spec: &'static FunctionSpec, args: &[(String, Literal)]) -> Result<Call> {
462 if spec.narrows() {
463 if let Some((name, _)) = args.iter().find(|(n, _)| n == "dtype") {
464 let column = spec.outputs.first().map_or(spec.name, |o| o.name);
465 return Err(plan(format!(
466 "{}() has no parameter '{name}' in SQL; cast its column instead, for example \
467 CAST({column} AS REAL)",
468 spec.name
469 )));
470 }
471 }
472 let mut read = Vec::with_capacity(args.len());
474 for (name, literal) in args {
475 let literal = match (spec.param(name).map(|p| p.ty), literal) {
476 (Some(ParamType::Direction(_)), Literal::String(text)) => {
477 Literal::String(direction_arg(spec.name, name, text)?)
478 }
479 (_, other) => other.clone(),
480 };
481 read.push((name.as_str(), literal));
482 }
483 spec.resolve(read.iter().map(|(n, l)| (*n, l.to_arg())))
484 .map(|resolved| resolved.call)
485 .map_err(|e| param_error(spec, &e, args))
486}
487
488fn param_error(spec: &FunctionSpec, e: &ParamError, args: &[(String, Literal)]) -> DataFusionError {
490 let (f, p) = (spec.name, e.param.as_str());
491 let given = || {
492 args.iter()
493 .find(|(n, _)| n == p)
494 .map_or(Literal::Null, |(_, l)| l.clone())
495 };
496 match e.kind {
497 ParamErrorKind::Unknown => {
498 let given = args
499 .iter()
500 .find(|(n, _)| n == p)
501 .map(|(_, l)| Given::of_literal(l));
502 unknown_param(spec, p, given)
503 }
504 ParamErrorKind::Duplicate => plan(format!("{f}() was given '{p}' more than once")),
505 ParamErrorKind::Expected(want) => plan(format!(
506 "{f}({p} =>) must be {}; got {}",
507 expected_text(want),
508 given()
509 )),
510 ParamErrorKind::OutOfRange(range) => plan(format!(
511 "{f}({p} =>) must be {}; got {}",
512 range_text(&range).unwrap_or_else(|| "a number".into()),
513 given()
514 )),
515 ParamErrorKind::NotOneOf(options) => {
516 let options: Vec<String> = options.iter().map(|o| format!("'{o}'")).collect();
517 plan(format!(
518 "{f}({p} => {}) is not supported; use one of {}",
519 given(),
520 options.join(", ")
521 ))
522 }
523 ParamErrorKind::Expression => plan(format!(
524 "{f}({p} =>) takes an expression over the edge table's columns; got {}",
525 given()
526 )),
527 }
528}
529
530pub(crate) fn expected_text(want: Expected) -> &'static str {
532 match want {
533 Expected::Number => "a number",
534 Expected::FiniteNumber => "a finite number",
535 Expected::Count => "a non-negative integer below 2^32",
536 Expected::CountOrNull => "a non-negative integer below 2^32, or NULL",
537 Expected::Seed => "a non-negative integer or NULL",
538 Expected::NumberOrNull => "a number or NULL",
539 Expected::Bool => "a boolean",
540 }
541}
542
543pub fn range_text(range: &Range) -> Option<String> {
548 range.describe()
549}
550
551pub fn unknown_param(spec: &FunctionSpec, name: &str, given: Option<Given>) -> DataFusionError {
554 let params: Vec<&ParamSpec> = sql_params(spec).collect();
555 if params.is_empty() {
556 return plan(format!(
557 "{}() takes no parameters besides the graph; got '{name}'",
558 spec.name
559 ));
560 }
561 if name == "direction" {
563 if let Some(mode) = spec.param("mode") {
564 let choices: Vec<String> = mode.ty.choices().iter().map(|c| format!("'{c}'")).collect();
565 return plan(format!(
566 "{}() has no parameter 'direction'; use mode => {} ('weak' ignores edge \
567 direction, 'strong' needs a path each way)",
568 spec.name,
569 choices.join(" or ")
570 ));
571 }
572 }
573 let takers: Vec<Box<dyn Fn(Given) -> bool>> = params
574 .iter()
575 .map(|p| {
576 let (n, ty) = (p.name, p.ty);
577 Box::new(move |g| takes(n, ty, g)) as Box<dyn Fn(Given) -> bool>
578 })
579 .collect();
580 let entries: Vec<(&str, &dyn Fn(Given) -> bool)> = params
581 .iter()
582 .zip(&takers)
583 .map(|(p, t)| (p.name, t.as_ref()))
584 .collect();
585 plan(unknown_param_text(spec.name, name, given, &entries))
586}
587
588pub fn sql_value(value: &Value) -> String {
590 match value {
591 Value::Null => "NULL".to_string(),
592 Value::Bool(b) => b.to_string(),
593 Value::UInt(u) => u.to_string(),
594 Value::Float(f) => format!("{f:?}"),
595 Value::Str(s) => format!("'{s}'"),
596 }
597}
598
599fn defaults(spec: &FunctionSpec) -> Vec<String> {
603 sql_params(spec)
604 .filter_map(|p| match (p.ty, p.name) {
605 (ParamType::Attribute, "values") => Some(format!("{} => {VALUES_QUERY}", p.name)),
606 (ParamType::Attribute, _) => None,
607 _ => Some(format!("{} => {}", p.name, sql_value(&p.default))),
608 })
609 .collect()
610}
611
612pub const VALUES_QUERY: &str = "(SELECT id, value FROM ...)";
614
615pub fn signature(spec: &FunctionSpec) -> String {
618 let mut parts = vec!["<graph>".to_string()];
619 parts.extend(defaults(spec));
620 format!("{}({})", spec.name, parts.join(", "))
621}
622
623pub fn nested_signature(spec: &FunctionSpec) -> String {
625 format!("{}({})", spec.name, defaults(spec).join(", "))
626}
627
628pub fn display_call(call: &Call, weight: Option<&str>) -> String {
631 let values = call.values();
632 let parts: Vec<String> = sql_params(call.spec())
633 .filter_map(|p| {
634 if p.ty == ParamType::Weight {
635 return weight.map(|w| format!("{} => {w}", p.name));
636 }
637 values
638 .iter()
639 .find(|(q, _)| q.name == p.name)
640 .map(|(_, v)| format!("{} => {}", p.name, sql_value(v)))
641 })
642 .collect();
643 format!("{}({})", call.name(), parts.join(", "))
644}
645
646pub(crate) fn plan(message: String) -> DataFusionError {
648 DataFusionError::Plan(message)
649}
650
651pub fn did_you_mean<'a>(
654 name: &str,
655 candidates: impl IntoIterator<Item = &'a str>,
656) -> Option<&'a str> {
657 super::closest_name(name, candidates)
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663 use ursa_core::catalog::Value;
664 use ursa_core::Direction;
665
666 fn call(name: &str, args: &[(&str, Literal)]) -> Result<Call> {
667 let args: Vec<(String, Literal)> = args
668 .iter()
669 .map(|(n, v)| (n.to_string(), v.clone()))
670 .collect();
671 resolve(lookup(name).unwrap(), &args)
672 }
673
674 fn num(n: &str) -> Literal {
675 Literal::Number(n.into())
676 }
677
678 fn s(v: &str) -> Literal {
679 Literal::String(v.into())
680 }
681
682 fn message(r: Result<Call>) -> String {
683 crate::user_message(&r.unwrap_err())
684 }
685
686 #[test]
687 fn defaults_match_python() {
688 assert_eq!(
689 call("pagerank", &[]).unwrap(),
690 Call::PageRank {
691 damping: 0.85,
692 max_iter: 30,
693 tol: 1e-6,
694 direction: Direction::Out
695 }
696 );
697 assert_eq!(
698 call("degree", &[]).unwrap(),
699 Call::Degree {
700 direction: Direction::Out
701 }
702 );
703 assert_eq!(
704 call("connected_components", &[]).unwrap(),
705 Call::ConnectedComponents { strong: false }
706 );
707 assert_eq!(
708 call("louvain", &[]).unwrap(),
709 Call::Louvain {
710 resolution: 1.0,
711 seed: None,
712 parallel: false
713 }
714 );
715 assert_eq!(call("triangle_count", &[]).unwrap(), Call::TriangleCount);
716 assert_eq!(
717 call("diameter", &[]).unwrap(),
718 Call::Diameter {
719 approximate: true,
720 direction: Direction::Out
721 }
722 );
723 }
724
725 #[test]
726 fn reads_arguments() {
727 assert_eq!(
728 call(
729 "pagerank",
730 &[
731 ("damping", num("0.9")),
732 ("max_iter", num("100")),
733 ("tol", num("1e-10")),
734 ("direction", s("both"))
735 ]
736 )
737 .unwrap(),
738 Call::PageRank {
739 damping: 0.9,
740 max_iter: 100,
741 tol: 1e-10,
742 direction: Direction::Both
743 }
744 );
745 assert!(call("pagerank", &[("damping", num("1"))]).is_ok());
747 for (function, param, value) in [
750 ("pagerank", "damping", num("0")),
751 ("pagerank", "max_iter", num("1")),
752 ("pagerank", "tol", num("0")),
753 ("betweenness", "sample", num("1")),
754 ("betweenness", "sample", num("1e-9")),
755 ("betweenness", "sample", Literal::Null),
756 ("avg_path_length", "sample", num("1.0")),
757 ("layout_fa2", "gravity", num("0")),
758 ("layout_fa2", "theta", num("0")),
759 ("layout_fa2", "theta", Literal::Null),
760 ("layout_fa2", "iterations", num("0")),
761 ("layout_fr", "iterations", num("0")),
762 ] {
763 assert!(
764 call(function, &[(param, value)]).is_ok(),
765 "{function} {param}"
766 );
767 }
768 assert_eq!(
769 call("louvain", &[("seed", num("7")), ("resolution", num("0.5"))]).unwrap(),
770 Call::Louvain {
771 resolution: 0.5,
772 seed: Some(7),
773 parallel: false
774 }
775 );
776 assert_eq!(
777 call("louvain", &[("seed", Literal::Null)]).unwrap(),
778 call("louvain", &[]).unwrap()
779 );
780 assert_eq!(
781 call("connected_components", &[("mode", s("strong"))]).unwrap(),
782 Call::ConnectedComponents { strong: true }
783 );
784 assert_eq!(
785 call("diameter", &[("approximate", Literal::Boolean(false))]).unwrap(),
786 Call::Diameter {
787 approximate: false,
788 direction: Direction::Out
789 }
790 );
791 assert_eq!(
792 call("betweenness", &[("sample", Literal::Null)]).unwrap(),
793 call("betweenness", &[]).unwrap()
794 );
795 }
796
797 #[test]
798 fn explains_bad_arguments() {
799 assert_eq!(
800 message(call("pagerank", &[("dampng", num("0.9"))])),
801 "pagerank() has no parameter 'dampng'; did you mean 'damping'? Its parameters are: \
802 damping, max_iter, tol, weight, direction"
803 );
804 assert_eq!(
805 message(call("pagerank", &[("color", num("1"))])),
806 "pagerank() has no parameter 'color'. Its parameters are: damping, max_iter, tol, \
807 weight, direction"
808 );
809 assert_eq!(
810 message(call("triangle_count", &[("direction", s("both"))])),
811 "triangle_count() takes no parameters besides the graph; got 'direction'"
812 );
813 assert_eq!(
814 message(call(
815 "pagerank",
816 &[("damping", num("0.9")), ("damping", num("0.8"))]
817 )),
818 "pagerank() was given 'damping' more than once"
819 );
820 assert_eq!(
821 message(call("pagerank", &[("damping", s("high"))])),
822 "pagerank(damping =>) must be a number; got 'high'"
823 );
824 assert_eq!(
825 message(call("pagerank", &[("damping", num("1e999"))])),
826 "pagerank(damping =>) must be a finite number; got 1e999"
827 );
828 assert_eq!(
829 message(call("pagerank", &[("max_iter", num("-1"))])),
830 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got -1"
831 );
832 assert_eq!(
833 message(call("pagerank", &[("max_iter", num("2.5"))])),
834 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got 2.5"
835 );
836 assert_eq!(
837 message(call("pagerank", &[("max_iter", num("4294967296"))])),
838 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got 4294967296"
839 );
840 assert_eq!(
841 message(call("pagerank", &[("max_iter", Literal::Null)])),
842 "pagerank(max_iter =>) must be a non-negative integer below 2^32; got NULL"
843 );
844 assert_eq!(
845 message(call("louvain", &[("seed", num("-3"))])),
846 "louvain(seed =>) must be a non-negative integer or NULL; got -3"
847 );
848 assert_eq!(
849 message(call("betweenness", &[("sample", s("half"))])),
850 "betweenness(sample =>) must be a number or NULL; got 'half'"
851 );
852 for (function, param, value, range) in [
855 ("pagerank", "damping", "-1", "between 0 and 1"),
856 ("pagerank", "damping", "1.5", "between 0 and 1"),
857 ("pagerank", "max_iter", "0", "at least 1"),
858 ("pagerank", "tol", "-1", "at least 0"),
859 ("label_propagation", "max_iter", "0", "at least 1"),
860 ("betweenness", "sample", "2", "above 0 and at most 1"),
861 ("betweenness", "sample", "-1", "above 0 and at most 1"),
862 ("betweenness", "sample", "0", "above 0 and at most 1"),
863 ("avg_path_length", "sample", "5", "above 0 and at most 1"),
864 ("louvain", "resolution", "-1", "above 0"),
865 ("louvain", "resolution", "0.0", "above 0"),
866 ("layout_fa2", "k", "0", "above 0"),
867 ("layout_fa2", "gravity", "-0.5", "at least 0"),
868 ("layout_fa2", "theta", "-1", "at least 0"),
869 ("layout_fa2", "jitter_tolerance", "0", "above 0"),
870 ("layout_fr", "k", "-2", "above 0"),
871 ("layout_fr", "gravity", "-1e-3", "at least 0"),
872 ] {
873 assert_eq!(
874 message(call(function, &[(param, num(value))])),
875 format!("{function}({param} =>) must be {range}; got {value}")
876 );
877 }
878 assert_eq!(
879 message(call("diameter", &[("approximate", num("1"))])),
880 "diameter(approximate =>) must be a boolean; got 1"
881 );
882 assert_eq!(
883 message(call("pagerank", &[("direction", s("up"))])),
884 "pagerank(direction => 'up') is not supported; use one of 'out', 'in', 'both'"
885 );
886 assert_eq!(
887 message(call("degree", &[("direction", s("sideways"))])),
888 "degree(direction => 'sideways') is not supported; use one of 'out', 'in', 'both'"
889 );
890 assert_eq!(
891 message(call("connected_components", &[("mode", num("1"))])),
892 "connected_components(mode => 1) is not supported; use one of 'weak', 'strong'"
893 );
894 assert_eq!(
895 message(call("closeness", &[("dtype", s("f32"))])),
896 "closeness() has no parameter 'dtype' in SQL; cast its column instead, for example \
897 CAST(closeness AS REAL)"
898 );
899 assert_eq!(
900 message(call("degree", &[("dtype", s("f32"))])),
901 "degree() has no parameter 'dtype'. Its parameters are: direction"
902 );
903 }
904
905 #[test]
908 fn directions_in_any_case() {
909 for (function, text, want) in [
910 ("pagerank", "BOTH", Direction::Both),
911 ("pagerank", "In", Direction::In),
912 ("betweenness", "in", Direction::In),
913 ("degree", "Out", Direction::Out),
914 ] {
915 let got = call(function, &[("direction", s(text))]).unwrap();
916 let direction = got
917 .values()
918 .into_iter()
919 .find(|(p, _)| p.name == "direction")
920 .map(|(_, v)| v);
921 assert_eq!(
922 direction,
923 Some(Value::Str(ursa_core::catalog::direction_name(want))),
924 "{function} {text}"
925 );
926 }
927 assert_eq!(
928 message(call("closeness", &[("direction", s("Undirected"))])),
929 "closeness(direction => 'Undirected') is not supported; use 'both', which reads \
930 every edge both ways (the undirected view)"
931 );
932 assert_eq!(
933 message(call("degree", &[("direction", s("Sideways"))])),
934 "degree(direction => 'Sideways') is not supported; use one of 'out', 'in', 'both'"
935 );
936 }
937
938 #[test]
941 fn suggestions_fit_the_value() {
942 assert_eq!(
943 message(call("pagerank", &[("alpha", num("0.5"))])),
944 "pagerank() has no parameter 'alpha'; did you mean 'damping'? Its parameters are: \
945 damping, max_iter, tol, weight, direction"
946 );
947 assert_eq!(
949 message(call("pagerank", &[("dampng", s("high"))])),
950 "pagerank() has no parameter 'dampng'. Its parameters are: damping, max_iter, tol, \
951 weight, direction"
952 );
953 assert_eq!(
954 message(call("connected_components", &[("direction", s("both"))])),
955 "connected_components() has no parameter 'direction'; use mode => 'weak' or \
956 'strong' ('weak' ignores edge direction, 'strong' needs a path each way)"
957 );
958 let spec = lookup("louvain").unwrap();
959 assert_eq!(
960 crate::user_message(&unknown_param(spec, "sed", Some(Given::Integer))),
961 "louvain() has no parameter 'sed'; did you mean 'seed'? Its parameters are: weight, \
962 resolution, seed, parallel"
963 );
964 assert_eq!(
965 crate::user_message(&unknown_param(spec, "sed", Some(Given::List))),
966 "louvain() has no parameter 'sed'. Its parameters are: weight, resolution, seed, \
967 parallel"
968 );
969 }
970
971 #[test]
975 fn one_name_per_role() {
976 use super::super::traversal::{TraversalParamType, TRAVERSALS};
977 let kind = |name: &str, ty: ParamType| sql_type(name, ty).trim_end_matches(" or NULL");
979 let mut params: Vec<(&str, &str, &str)> = Vec::new();
980 for spec in specs() {
981 for p in sql_params(spec) {
982 params.push((spec.name, p.name, kind(p.name, p.ty)));
983 }
984 }
985 for spec in TRAVERSALS {
986 for p in spec.params {
987 let k = match p.ty {
988 TraversalParamType::Nodes => "node ids",
989 TraversalParamType::Node => "node id",
990 TraversalParamType::Param(ty) => kind(p.name, ty),
991 };
992 params.push((spec.name, p.name, k));
993 }
994 }
995 const SPLIT: &[(&str, &str)] = &[("seed", "random_seed")];
999 const TWO_KINDS: &[&str] = &["nodes"];
1003 for (f, name, k) in ¶ms {
1005 for (g, other, l) in ¶ms {
1006 assert!(
1007 name != other || k == l || TWO_KINDS.contains(name),
1008 "{f}({name}) takes {k} but {g}({other}) takes {l}"
1009 );
1010 }
1011 }
1012 for (ours, others) in OTHER_NAMES {
1013 let kinds: Vec<&str> = params
1014 .iter()
1015 .filter(|(_, n, _)| n == ours)
1016 .map(|(_, _, k)| *k)
1017 .collect();
1018 assert!(!kinds.is_empty(), "no function has a parameter '{ours}'");
1019 for (f, name, k) in ¶ms {
1021 if SPLIT.contains(&(*name, *ours)) {
1022 continue;
1023 }
1024 assert!(
1025 !(others.contains(name) && kinds.contains(k)),
1026 "{f}({name}) is what the other functions call '{ours}'"
1027 );
1028 }
1029 }
1030 for (i, (ours, others)) in OTHER_NAMES.iter().enumerate() {
1032 for (theirs, alternatives) in &OTHER_NAMES[i + 1..] {
1033 for name in *others {
1034 assert!(
1035 !alternatives.contains(name),
1036 "'{name}' points to both '{ours}' and '{theirs}'"
1037 );
1038 }
1039 }
1040 }
1041 }
1042
1043 #[test]
1044 fn suggests_names() {
1045 assert_eq!(did_you_mean("pagerenk", names()), Some("pagerank"));
1046 assert_eq!(did_you_mean("closenes", names()), Some("closeness"));
1047 assert_eq!(did_you_mean("algorithm", names()), Some("algorithms"));
1048 assert_eq!(
1049 did_you_mean("shortest_paths", names()),
1050 Some("shortest_path")
1051 );
1052 assert_eq!(did_you_mean("random_walks", names()), Some("random_walk"));
1053 assert_eq!(did_you_mean("dijkstra", names()), None);
1054 assert_eq!(did_you_mean("neighbor_agg", names()), Some("neighbors_agg"));
1055 }
1056
1057 #[test]
1058 fn neighbors_agg_takes_values_or_an_attribute() {
1059 let spec = lookup("neighbors_agg").unwrap();
1060 let params: Vec<&str> = sql_params(spec).map(|p| p.name).collect();
1061 assert_eq!(params, ["values", "direction", "attribute", "agg"]);
1062 assert_eq!(
1063 signature(spec),
1064 "neighbors_agg(<graph>, values => (SELECT id, value FROM ...), direction => 'out', \
1065 agg => 'mean')"
1066 );
1067 assert_eq!(
1068 call(
1069 "neighbors_agg",
1070 &[("agg", s("n_unique")), ("direction", s("both"))]
1071 )
1072 .unwrap(),
1073 Call::NeighborAgg {
1074 direction: Direction::Both,
1075 agg: ursa_core::algo::AggKind::NUnique
1076 }
1077 );
1078 assert_eq!(
1079 message(call("neighbors_agg", &[("agg", s("median"))])),
1080 "neighbors_agg(agg => 'median') is not supported; use one of 'mean', 'sum', 'min', \
1081 'max', 'count', 'n_unique'"
1082 );
1083 }
1084
1085 #[test]
1086 fn the_trivial_layouts_are_hidden() {
1087 for name in ["layout_random", "layout_circle"] {
1088 assert!(catalog::lookup(name).is_some(), "{name} is in the catalog");
1089 assert!(lookup(name).is_none(), "{name} is hidden from SQL");
1090 assert!(names().all(|n| n != name));
1091 assert!(specs().all(|s| s.name != name));
1092 }
1093 for name in ["layout_fa2", "layout_fr"] {
1094 assert!(lookup(name).is_some(), "{name} is in SQL");
1095 assert!(names().any(|n| n == name));
1096 }
1097 for typo in ["layout_randm", "layout_circl"] {
1099 let suggestion = did_you_mean(typo, names());
1100 assert!(
1101 !matches!(suggestion, Some("layout_random" | "layout_circle")),
1102 "{typo}: {suggestion:?}"
1103 );
1104 }
1105 assert_eq!(did_you_mean("layout_frr", names()), Some("layout_fr"));
1106 }
1107
1108 #[test]
1109 fn signatures_show_defaults() {
1110 assert_eq!(
1111 signature(lookup("pagerank").unwrap()),
1112 "pagerank(<graph>, damping => 0.85, max_iter => 30, tol => 1e-6, weight => NULL, \
1113 direction => 'out')"
1114 );
1115 assert_eq!(
1116 nested_signature(lookup("louvain").unwrap()),
1117 "louvain(weight => NULL, resolution => 1.0, seed => NULL, parallel => false)"
1118 );
1119 }
1120
1121 #[test]
1122 fn explain_spells_the_call() {
1123 let pagerank = call("pagerank", &[]).unwrap();
1124 assert_eq!(
1125 display_call(&pagerank, None),
1126 "pagerank(damping => 0.85, max_iter => 30, tol => 1e-6, direction => 'out')"
1127 );
1128 assert_eq!(
1129 display_call(&pagerank, Some("w")),
1130 "pagerank(damping => 0.85, max_iter => 30, tol => 1e-6, weight => w, \
1131 direction => 'out')"
1132 );
1133 assert_eq!(
1134 display_call(&call("louvain", &[]).unwrap(), None),
1135 "louvain(resolution => 1.0, seed => NULL, parallel => false)"
1136 );
1137 assert_eq!(
1138 display_call(&call("triangle_count", &[]).unwrap(), None),
1139 "triangle_count()"
1140 );
1141 }
1142}