Skip to main content

ursa_engine/graph/
functions.rs

1//! The graph functions in SQL: which of `ursa_core::catalog`'s functions a
2//! query can call, how a call's SQL arguments become a catalog [`Call`], and
3//! the wording of every message about them.
4//!
5//! The catalog is the single source of truth for names, parameters, defaults,
6//! accepted values and output types, shared with the Python library, so a call
7//! means the same thing in both. This module only adds SQL's choices:
8//!
9//! - **Which functions.** Every algorithm, every statistic, the neighbour
10//!   aggregation, and the force-directed layouts `layout_fa2` and `layout_fr`
11//!   (#395), which return `(id, x, y)`. The trivial layouts (`layout_random`,
12//!   `layout_circle`) are left out ([`in_sql`]), as they are from the Python
13//!   library's public API: a call fails as an unknown function would, and no
14//!   message or listing names them.
15//! - **Node values.** The neighbour aggregation (`neighbors_agg`) reads one
16//!   value per node. SQL gives them as a query of `(id, value)` rows,
17//!   `values => (SELECT id, age FROM people)` ([`VALUES`], a parameter only
18//!   SQL has), or as an expression over the graph's node table, `attribute =>
19//!   age` (the catalog's `attribute`). Either is planned as a child of the
20//!   graph node, as a traversal's node ids are.
21//! - **No `dtype`.** SQL has `CAST`; a call never narrows its own column.
22//! - **`weight =>`** is an expression over the edge table's columns, planned by
23//!   the relation planner as a column of the node's edge plan, not a literal
24//!   resolved here.
25//! - **Messages**, worded for SQL: `pagerank(damping =>) must be a number; got
26//!   'high'`, and for a number outside the parameter's range (#416, declared
27//!   once, in the catalog): `pagerank(damping =>) must be between 0 and 1; got
28//!   -1`. An unknown parameter is answered with the one to use (#415): the
29//!   closest name, or the name Ursa gives a role others name differently
30//!   ([`OTHER_NAMES`]: `hop(n =>)` is `steps`), and never one whose type cannot
31//!   take the value given ([`Given`]).
32//! - **Direction values** are read in any case (`'BOTH'`); `'undirected'` is
33//!   refused with a pointer to `'both'` ([`direction_arg`]).
34//!
35//! Every role has one name across the graph functions (#415): the nodes to
36//! start from are `seeds`, a number of steps `steps`, and so on.
37//! [`OTHER_NAMES`] lists, for each name, what other systems call it; the
38//! registry test holds every parameter to it.
39
40use 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
48/// The multi-algorithm table function: `algorithms(g, degree(), c => louvain())`.
49pub const ALGORITHMS: &str = "algorithms";
50
51/// The function catalog as a table: `SELECT * FROM ursa_functions()`.
52pub const URSA_FUNCTIONS: &str = "ursa_functions";
53
54/// Whether SQL can call `spec` (see the module docs). Everything the engine
55/// reads from `ursa_core::catalog` goes through this predicate, so a function
56/// it rejects is unknown to SQL: not callable, not suggested, not listed by
57/// `ursa_functions()`.
58fn in_sql(spec: &FunctionSpec) -> bool {
59    spec.family != Family::Layout || SQL_LAYOUTS.contains(&spec.name)
60}
61
62/// The layouts SQL offers.
63const SQL_LAYOUTS: &[&str] = &["layout_fa2", "layout_fr"];
64
65/// The catalog function called `name`, if SQL can call it.
66pub fn lookup(name: &str) -> Option<&'static FunctionSpec> {
67    catalog::lookup(name).filter(|s| in_sql(s))
68}
69
70/// Every catalog function SQL can call, in catalog order.
71pub fn specs() -> impl Iterator<Item = &'static FunctionSpec> {
72    catalog::FUNCTIONS.iter().filter(|s| in_sql(s))
73}
74
75/// The names of the graph table functions: the catalog's, the traversals,
76/// then `algorithms`.
77pub 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/// `describe`'s count of the edges left out of the graph because an endpoint
85/// is not a key of its vertex table (#311). SQL's own column: a Python graph
86/// has no vertex table, so it would always be 0 there.
87pub const N_DROPPED_EDGES: OutputSpec = OutputSpec {
88    name: "n_dropped_edges",
89    ty: ColumnType::Int64,
90    nullable: false,
91};
92
93/// The columns a call to `spec` returns in SQL, besides `id`: the catalog's,
94/// then for `describe` [`N_DROPPED_EDGES`]. An output's `field` indexes this
95/// list; past the catalog's own, the engine computes it (`kernels`).
96pub 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
104/// Whether `spec` returns one row per node (an algorithm), as
105/// opposed to one row for the whole graph (a statistic).
106pub fn is_per_node(spec: &FunctionSpec) -> bool {
107    spec.shape == Shape::PerNode
108}
109
110/// `neighbors_agg(values => (SELECT id, value FROM ...))`: the node values as
111/// a query. SQL's alternative to the catalog's `attribute`, which in SQL is an
112/// expression over the graph's node table.
113pub 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
122/// The SQL description of the catalog's `attribute` parameter.
123const ATTRIBUTE_DOC: &str =
124    "An expression over the graph's node table, the value of each node. Give this or values.";
125
126/// `neighbors_agg`'s `agg` in SQL, where `min` and `max` also take strings,
127/// dates and times.
128const 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
131/// The parameters a SQL call can name: all but `dtype`, in the catalog's
132/// order, after [`VALUES`] for a function that reads node values.
133pub 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
141/// A parameter's one-line description, as SQL reads it.
142pub 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
150/// How SQL writes a value of parameter `name`, of type `ty`: `number`,
151/// `string`, `query` ...
152pub 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/// What an argument is, as written: what "did you mean" checks a suggested
167/// parameter can take (#415), so `random_walk(sed => [0])` points to `seeds`,
168/// not `random_seed`.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum Given {
171    Integer,
172    /// A number that is not an integer.
173    Number,
174    String,
175    Boolean,
176    Null,
177    /// A list literal, `[0, 1]`.
178    List,
179    /// A subquery, `(SELECT ...)`.
180    Query,
181    /// Any other expression.
182    Expression,
183}
184
185impl Given {
186    /// The shape of a literal.
187    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
198/// Whether a parameter of type `ty`, called `name`, can take an argument
199/// shaped `given`.
200pub 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
215/// The names other systems give a graph function's parameter, by the name
216/// Ursa gives it (#415): one name per role. "did you mean" answers each with
217/// Ursa's name, when the function has that parameter and it can take the value
218/// given; none is accepted. The registry test refuses a parameter named after
219/// another role's alternative.
220pub 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
254/// The name to suggest for the unknown parameter `name` of a function whose
255/// parameters are `params` (name, and whether it can take `given`): Ursa's
256/// name for the role (see [`OTHER_NAMES`]), else the closest name. Neither
257/// when no parameter that can take the value is close.
258pub 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
276/// The text after "has no parameter 'x'": the suggestion, then the list.
277pub 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
293/// A direction as written, read in any case (#415): `'BOTH'` is `'both'`.
294/// `'undirected'`, the word of NetworkX, igraph and DuckPGQ, is refused with
295/// a pointer to `'both'`, Ursa's one name for it.
296pub 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/// A literal argument as written: a (possibly signed) number, a string, a
309/// boolean or `NULL`.
310#[derive(Debug, Clone, PartialEq)]
311pub enum Literal {
312    /// The number's text, sign included, so it parses exactly as Python
313    /// parses the same text.
314    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    /// The catalog's view of the literal: an integer if the text is one, else
333    /// a float if it is one.
334    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
348/// Resolve the literal arguments of a call to `spec` (names already
349/// normalized; `weight` already taken out by the caller) to a [`Call`].
350pub 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    // A direction in any case (#415).
362    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
377/// A catalog [`ParamError`] in SQL's words.
378fn 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
419/// What a parameter expected, in SQL's words.
420pub(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
432/// The numbers a parameter accepts, in words: `between 0 and 1`, `above 0 and
433/// at most 1`, `at least 1`; `None` for a parameter with no limit. The text of
434/// the `range` field of `ursa_functions()` and of the error for a value
435/// outside it (#416).
436pub fn range_text(range: &Range) -> Option<String> {
437    range.describe()
438}
439
440/// "pagerank() has no parameter 'dampng'; did you mean 'damping'? ...":
441/// `given` is the argument's shape, if known, so the suggestion can take it.
442pub 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    // `connected_components` says which way edges count with `mode` (#415).
451    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
477/// A catalog value as SQL writes it: `NULL`, `'out'`, `30`, `0.85`, `1e-6`.
478pub 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
488/// The parameters of `spec` at their defaults: `damping => 0.85, ...`. Node
489/// values are shown as the query they take, and `attribute`, its
490/// alternative, is left out.
491fn 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
501/// The form of a `values =>` argument, for messages.
502pub const VALUES_QUERY: &str = "(SELECT id, value FROM ...)";
503
504/// `pagerank(<graph>, damping => 0.85, ...)`: the call with every parameter at
505/// its default, for messages.
506pub 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
512/// `pagerank(damping => 0.85, ...)`: a call as written inside `algorithms()`.
513pub fn nested_signature(spec: &FunctionSpec) -> String {
514    format!("{}({})", spec.name, defaults(spec).join(", "))
515}
516
517/// The call as SQL would spell it, every literal parameter shown, and the
518/// weight when there is one: for `EXPLAIN`.
519pub 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
535/// A plan error.
536pub(crate) fn plan(message: String) -> DataFusionError {
537    DataFusionError::Plan(message)
538}
539
540/// The closest of `candidates` to `name`, if one is close enough to be a typo
541/// (the graph DDL's rule, so every "did you mean" agrees).
542pub 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        // An integer is a number, as Python's float parameters take an int.
635        assert!(call("pagerank", &[("damping", num("1"))]).is_ok());
636        // The ends of a range that are values (#416), and a NULL where the
637        // type takes one.
638        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        // A number outside the parameter's range (#416): the range, and the
742        // value as written.
743        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    /// #415: a direction in any case; 'undirected' pointed to 'both'; 'in'
795    /// for pagerank and betweenness.
796    #[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    /// #415: "did you mean" names the parameter to use for a role others name
828    /// differently, and never one whose type cannot take the value.
829    #[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        // 'dampng' is close to 'damping', but a string is no damping factor.
837        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    /// #415, item 6: one name per role across the graph functions. A new
861    /// function that calls its start nodes `start`, its step count `n` or
862    /// `max_hops`, or uses a name for two kinds of value, fails here.
863    #[test]
864    fn one_name_per_role() {
865        use super::super::traversal::{TraversalParamType, TRAVERSALS};
866        // What a value of each parameter is, NULL aside.
867        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        // `seed` (the algorithms' and layouts' random seed) and
885        // `random_walk`'s `random_seed`, renamed apart from `seeds` (#415), are
886        // one role under two names until the algorithms' name is decided.
887        const SPLIT: &[(&str, &str)] = &[("seed", "random_seed")];
888        // `describe(nodes => 'touched')` chooses which nodes to describe;
889        // `induced_edges(nodes => [...])` is the node set. Both are the nodes
890        // the call is about, given two ways.
891        const TWO_KINDS: &[&str] = &["nodes"];
892        // One kind of value per name.
893        for (f, name, k) in &params {
894            for (g, other, l) in &params {
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            // No parameter of the same kind goes by another name of the role.
909            for (f, name, k) in &params {
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        // Each role's alternatives point to one name.
920        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        // No suggestion leads to a hidden name.
987        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}