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/// A DuckPGQ function name that Ursa runs as one of its own functions (#298):
85/// `weakly_connected_component(pg, Student, know)` is
86/// `connected_components(pg, Student, know, mode => 'weak')`, with DuckPGQ's
87/// column name.
88///
89/// These are other systems' spellings, accepted so DuckPGQ's queries run
90/// unchanged; they are not old names of Ursa's own (Ursa keeps none).
91/// `ursa_functions()` lists each as a row of its own, with `same_as` naming
92/// Ursa's function and `duckpgq` true.
93#[derive(Debug)]
94pub struct DuckPgqName {
95    /// DuckPGQ's name.
96    pub name: &'static str,
97    /// The Ursa function it runs.
98    pub function: &'static str,
99    /// Parameters the name fixes, as `(name, value)`; a call cannot give them.
100    pub fixed: &'static [(&'static str, &'static str)],
101    /// The output column, DuckPGQ's name for it. Unquoted identifiers are
102    /// folded to lower case, so DuckPGQ's `componentId` is `componentid`:
103    /// a query that writes `componentId` unquoted finds it.
104    pub column: &'static str,
105}
106
107/// DuckPGQ's names for Ursa's functions, where they differ. DuckPGQ's
108/// `pagerank` has Ursa's name and column already.
109pub 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
124/// The graph functions DuckPGQ has under the same name, with the same output
125/// column.
126pub const DUCKPGQ_SAME: &[&str] = &["pagerank"];
127
128/// DuckPGQ's name `name`, if Ursa runs it.
129pub fn duckpgq(name: &str) -> Option<&'static DuckPgqName> {
130    DUCKPGQ_NAMES.iter().find(|d| d.name == name)
131}
132
133impl DuckPgqName {
134    /// The Ursa function this name runs.
135    pub fn spec(&self) -> &'static FunctionSpec {
136        lookup(self.function).expect("a DuckPGQ name runs a function SQL has")
137    }
138
139    /// The Ursa call it is, as written: `connected_components(<graph>, mode
140    /// => 'weak')`.
141    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    /// The `ursa_functions()` summary of the name.
148    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    /// The message for a call that gives one of the parameters the name
158    /// fixes, if `param` is one.
159    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
172/// DuckPGQ's scalar path functions, the plumbing of its `MATCH` over a CSR,
173/// which Ursa does not have (#298), with what to write instead.
174pub const DUCKPGQ_PATH_FUNCTIONS: &[&str] = &[
175    "iterativelength",
176    "shortestpath",
177    "reachability",
178    "cheapest_path_length",
179];
180
181/// The message for a call of DuckPGQ's scalar path function `name`, if it is
182/// one.
183pub 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
195/// `describe`'s count of the edges left out of the graph because an endpoint
196/// is not a key of its vertex table (#311). SQL's own column: a Python graph
197/// has no vertex table, so it would always be 0 there.
198pub const N_DROPPED_EDGES: OutputSpec = OutputSpec {
199    name: "n_dropped_edges",
200    ty: ColumnType::Int64,
201    nullable: false,
202};
203
204/// The columns a call to `spec` returns in SQL, besides `id`: the catalog's,
205/// then for `describe` [`N_DROPPED_EDGES`]. An output's `field` indexes this
206/// list; past the catalog's own, the engine computes it (`kernels`).
207pub 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
215/// Whether `spec` returns one row per node (an algorithm), as
216/// opposed to one row for the whole graph (a statistic).
217pub fn is_per_node(spec: &FunctionSpec) -> bool {
218    spec.shape == Shape::PerNode
219}
220
221/// `neighbors_agg(values => (SELECT id, value FROM ...))`: the node values as
222/// a query. SQL's alternative to the catalog's `attribute`, which in SQL is an
223/// expression over the graph's node table.
224pub 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
233/// The SQL description of the catalog's `attribute` parameter.
234const ATTRIBUTE_DOC: &str =
235    "An expression over the graph's node table, the value of each node. Give this or values.";
236
237/// `neighbors_agg`'s `agg` in SQL, where `min` and `max` also take strings,
238/// dates and times.
239const 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
242/// The parameters a SQL call can name: all but `dtype`, in the catalog's
243/// order, after [`VALUES`] for a function that reads node values.
244pub 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
252/// A parameter's one-line description, as SQL reads it.
253pub 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
261/// How SQL writes a value of parameter `name`, of type `ty`: `number`,
262/// `string`, `query` ...
263pub 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/// What an argument is, as written: what "did you mean" checks a suggested
278/// parameter can take (#415), so `random_walk(sed => [0])` points to `seeds`,
279/// not `random_seed`.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum Given {
282    Integer,
283    /// A number that is not an integer.
284    Number,
285    String,
286    Boolean,
287    Null,
288    /// A list literal, `[0, 1]`.
289    List,
290    /// A subquery, `(SELECT ...)`.
291    Query,
292    /// Any other expression.
293    Expression,
294}
295
296impl Given {
297    /// The shape of a literal.
298    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
309/// Whether a parameter of type `ty`, called `name`, can take an argument
310/// shaped `given`.
311pub 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
326/// The names other systems give a graph function's parameter, by the name
327/// Ursa gives it (#415): one name per role. "did you mean" answers each with
328/// Ursa's name, when the function has that parameter and it can take the value
329/// given; none is accepted. The registry test refuses a parameter named after
330/// another role's alternative.
331pub 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
365/// The name to suggest for the unknown parameter `name` of a function whose
366/// parameters are `params` (name, and whether it can take `given`): Ursa's
367/// name for the role (see [`OTHER_NAMES`]), else the closest name. Neither
368/// when no parameter that can take the value is close.
369pub 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
387/// The text after "has no parameter 'x'": the suggestion, then the list.
388pub 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
404/// A direction as written, read in any case (#415): `'BOTH'` is `'both'`.
405/// `'undirected'`, the word of NetworkX, igraph and DuckPGQ, is refused with
406/// a pointer to `'both'`, Ursa's one name for it.
407pub 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/// A literal argument as written: a (possibly signed) number, a string, a
420/// boolean or `NULL`.
421#[derive(Debug, Clone, PartialEq)]
422pub enum Literal {
423    /// The number's text, sign included, so it parses exactly as Python
424    /// parses the same text.
425    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    /// The catalog's view of the literal: an integer if the text is one, else
444    /// a float if it is one.
445    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
459/// Resolve the literal arguments of a call to `spec` (names already
460/// normalized; `weight` already taken out by the caller) to a [`Call`].
461pub 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    // A direction in any case (#415).
473    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
488/// A catalog [`ParamError`] in SQL's words.
489fn 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
530/// What a parameter expected, in SQL's words.
531pub(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
543/// The numbers a parameter accepts, in words: `between 0 and 1`, `above 0 and
544/// at most 1`, `at least 1`; `None` for a parameter with no limit. The text of
545/// the `range` field of `ursa_functions()` and of the error for a value
546/// outside it (#416).
547pub fn range_text(range: &Range) -> Option<String> {
548    range.describe()
549}
550
551/// "pagerank() has no parameter 'dampng'; did you mean 'damping'? ...":
552/// `given` is the argument's shape, if known, so the suggestion can take it.
553pub 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    // `connected_components` says which way edges count with `mode` (#415).
562    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
588/// A catalog value as SQL writes it: `NULL`, `'out'`, `30`, `0.85`, `1e-6`.
589pub 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
599/// The parameters of `spec` at their defaults: `damping => 0.85, ...`. Node
600/// values are shown as the query they take, and `attribute`, its
601/// alternative, is left out.
602fn 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
612/// The form of a `values =>` argument, for messages.
613pub const VALUES_QUERY: &str = "(SELECT id, value FROM ...)";
614
615/// `pagerank(<graph>, damping => 0.85, ...)`: the call with every parameter at
616/// its default, for messages.
617pub 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
623/// `pagerank(damping => 0.85, ...)`: a call as written inside `algorithms()`.
624pub fn nested_signature(spec: &FunctionSpec) -> String {
625    format!("{}({})", spec.name, defaults(spec).join(", "))
626}
627
628/// The call as SQL would spell it, every literal parameter shown, and the
629/// weight when there is one: for `EXPLAIN`.
630pub 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
646/// A plan error.
647pub(crate) fn plan(message: String) -> DataFusionError {
648    DataFusionError::Plan(message)
649}
650
651/// The closest of `candidates` to `name`, if one is close enough to be a typo
652/// (the graph DDL's rule, so every "did you mean" agrees).
653pub 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        // An integer is a number, as Python's float parameters take an int.
746        assert!(call("pagerank", &[("damping", num("1"))]).is_ok());
747        // The ends of a range that are values (#416), and a NULL where the
748        // type takes one.
749        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        // A number outside the parameter's range (#416): the range, and the
853        // value as written.
854        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    /// #415: a direction in any case; 'undirected' pointed to 'both'; 'in'
906    /// for pagerank and betweenness.
907    #[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    /// #415: "did you mean" names the parameter to use for a role others name
939    /// differently, and never one whose type cannot take the value.
940    #[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        // 'dampng' is close to 'damping', but a string is no damping factor.
948        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    /// #415, item 6: one name per role across the graph functions. A new
972    /// function that calls its start nodes `start`, its step count `n` or
973    /// `max_hops`, or uses a name for two kinds of value, fails here.
974    #[test]
975    fn one_name_per_role() {
976        use super::super::traversal::{TraversalParamType, TRAVERSALS};
977        // What a value of each parameter is, NULL aside.
978        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        // `seed` (the algorithms' and layouts' random seed) and
996        // `random_walk`'s `random_seed`, renamed apart from `seeds` (#415), are
997        // one role under two names until the algorithms' name is decided.
998        const SPLIT: &[(&str, &str)] = &[("seed", "random_seed")];
999        // `describe(nodes => 'touched')` chooses which nodes to describe;
1000        // `induced_edges(nodes => [...])` is the node set. Both are the nodes
1001        // the call is about, given two ways.
1002        const TWO_KINDS: &[&str] = &["nodes"];
1003        // One kind of value per name.
1004        for (f, name, k) in &params {
1005            for (g, other, l) in &params {
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            // No parameter of the same kind goes by another name of the role.
1020            for (f, name, k) in &params {
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        // Each role's alternatives point to one name.
1031        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        // No suggestion leads to a hidden name.
1098        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}