Skip to main content

ursa_engine/graph/
catalog_table.rs

1//! `ursa_functions()`: the graph functions, as a table.
2//!
3//! One row per function SQL can call: every algorithm, statistic and
4//! aggregation of `ursa_core::catalog` that SQL offers (not the layouts,
5//! hidden until the visualization work; see [`functions`]), then the
6//! traversals, then `algorithms`. The list columns are Arrow lists and
7//! structs, not strings, so they stay usable both ways:
8//!
9//! - from SQL: `unnest(parameters)`, `array_has(directions, 'in')`,
10//!   `parameters[1]['default']`;
11//! - as JSON (`ursa --format json`), where they are real arrays and objects an agent
12//!   reads without parsing a format of ours.
13//!
14//! Columns:
15//!
16//! | column       | type                                                     |
17//! |--------------|----------------------------------------------------------|
18//! | `name`       | the function's name                                      |
19//! | `family`     | `algorithm`, `statistic`, `aggregation`, `traversal` or `combinator` |
20//! | `summary`    | one line on what it computes                             |
21//! | `networkx`   | the NetworkX call it matches, or NULL                    |
22//! | `parameters` | list of {name, type, default, choices, range, doc}, call order |
23//! | `directions` | the `direction =>` values it accepts; empty if none     |
24//! | `outputs`    | list of {name, type, nullable}: its columns besides `id` |
25//!
26//! A parameter's `type` is how SQL writes it (`number`, `number or NULL`,
27//! `integer`, `integer or NULL`, `boolean`, `string`, `expression`, `query`
28//! for `neighbors_agg`'s values, and for a traversal's node ids `node ids` or
29//! `node id`), and its `default` is the
30//! literal SQL would write (`0.85`, `'out'`, `NULL`), or `required`. Its
31//! `range` is the numbers it accepts, in words (`between 0 and 1`, `above 0
32//! and at most 1`, `at least 1`), or NULL when any value of its type is
33//! accepted (#416); a value outside it is an error that says the range. A
34//! traversal's node-id output columns have the graph's id type, `Int64 or
35//! Utf8`, and `neighbors_agg`'s column a type that depends on its `agg` and
36//! its values ([`NEIGHBORS_AGG_TYPE`]).
37
38use std::sync::Arc;
39
40/// The output type `ursa_functions()` gives `neighbors_agg`, whose column's
41/// type depends on `agg` and the values (`kernels::neighbors_agg_type`).
42pub const NEIGHBORS_AGG_TYPE: &str =
43    "Float64; UInt32 for count and n_unique; the values' type for min and max of strings, \
44     dates or times";
45
46use datafusion::arrow::array::{
47    ArrayRef, BooleanBuilder, ListBuilder, StringBuilder, StructBuilder,
48};
49use datafusion::arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef};
50use datafusion::arrow::record_batch::RecordBatch;
51use datafusion::catalog::{TableFunctionArgs, TableFunctionImpl, TableProvider};
52use datafusion::datasource::MemTable;
53use datafusion::error::Result;
54use ursa_core::catalog::Family;
55
56use super::functions::{self, plan, sql_value, ALGORITHMS, URSA_FUNCTIONS};
57use super::traversal::{OutputType, TraversalParamType, TRAVERSALS};
58
59/// The `ursa_functions()` table function.
60#[derive(Debug)]
61pub struct UrsaFunctions;
62
63impl TableFunctionImpl for UrsaFunctions {
64    fn call_with_args(&self, args: TableFunctionArgs) -> Result<Arc<dyn TableProvider>> {
65        if !args.exprs().is_empty() {
66            return Err(plan(format!(
67                "{URSA_FUNCTIONS}() takes no arguments: SELECT * FROM {URSA_FUNCTIONS}()"
68            )));
69        }
70        let batch = functions_batch()?;
71        Ok(Arc::new(MemTable::try_new(
72            batch.schema(),
73            vec![vec![batch]],
74        )?))
75    }
76}
77
78fn parameter_fields() -> Fields {
79    Fields::from(vec![
80        Field::new("name", DataType::Utf8, false),
81        Field::new("type", DataType::Utf8, false),
82        Field::new("default", DataType::Utf8, false),
83        Field::new(
84            "choices",
85            DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
86            false,
87        ),
88        Field::new("range", DataType::Utf8, true),
89        Field::new("doc", DataType::Utf8, false),
90    ])
91}
92
93fn output_fields() -> Fields {
94    Fields::from(vec![
95        Field::new("name", DataType::Utf8, false),
96        Field::new("type", DataType::Utf8, false),
97        Field::new("nullable", DataType::Boolean, false),
98    ])
99}
100
101/// The schema of `ursa_functions()`.
102pub fn schema() -> SchemaRef {
103    let list = |item: DataType| DataType::List(Arc::new(Field::new("item", item, true)));
104    Arc::new(Schema::new(vec![
105        Field::new("name", DataType::Utf8, false),
106        Field::new("family", DataType::Utf8, false),
107        Field::new("summary", DataType::Utf8, false),
108        Field::new("networkx", DataType::Utf8, true),
109        Field::new(
110            "parameters",
111            list(DataType::Struct(parameter_fields())),
112            false,
113        ),
114        Field::new("directions", list(DataType::Utf8), false),
115        Field::new("outputs", list(DataType::Struct(output_fields())), false),
116    ]))
117}
118
119fn family_name(family: Family) -> &'static str {
120    match family {
121        Family::Algorithm => "algorithm",
122        Family::Layout => "layout",
123        Family::Aggregation => "aggregation",
124        Family::Statistic => "statistic",
125    }
126}
127
128/// The summary of the `algorithms` row.
129const ALGORITHMS_SUMMARY: &str = "Several per-node functions over one index, one row per node: \
130     algorithms(g, degree(direction => 'both'), community => louvain(seed => 1)). Each argument \
131     is a call with named parameters; its column is named by its key or after the function.";
132
133/// The rows of `ursa_functions()`.
134pub fn functions_batch() -> Result<RecordBatch> {
135    let mut name = StringBuilder::new();
136    let mut family = StringBuilder::new();
137    let mut summary = StringBuilder::new();
138    let mut networkx = StringBuilder::new();
139    let mut parameters =
140        ListBuilder::new(StructBuilder::from_fields(parameter_fields(), 0)).with_field(Arc::new(
141            Field::new("item", DataType::Struct(parameter_fields()), true),
142        ));
143    let mut directions = ListBuilder::new(StringBuilder::new());
144    let mut outputs = ListBuilder::new(StructBuilder::from_fields(output_fields(), 0)).with_field(
145        Arc::new(Field::new("item", DataType::Struct(output_fields()), true)),
146    );
147
148    for spec in functions::specs() {
149        name.append_value(spec.name);
150        family.append_value(family_name(spec.family));
151        summary.append_value(spec.summary);
152        networkx.append_option(spec.networkx);
153        let params = parameters.values();
154        for p in functions::sql_params(spec) {
155            params
156                .field_builder::<StringBuilder>(0)
157                .expect("name")
158                .append_value(p.name);
159            params
160                .field_builder::<StringBuilder>(1)
161                .expect("type")
162                .append_value(functions::sql_type(p.name, p.ty));
163            params
164                .field_builder::<StringBuilder>(2)
165                .expect("default")
166                .append_value(sql_value(&p.default));
167            let choices = params
168                .field_builder::<ListBuilder<Box<dyn datafusion::arrow::array::ArrayBuilder>>>(3)
169                .expect("choices");
170            for c in p.ty.choices() {
171                choices
172                    .values()
173                    .as_any_mut()
174                    .downcast_mut::<StringBuilder>()
175                    .expect("choices are strings")
176                    .append_value(c);
177            }
178            choices.append(true);
179            params
180                .field_builder::<StringBuilder>(4)
181                .expect("range")
182                .append_option(functions::range_text(&p.range));
183            params
184                .field_builder::<StringBuilder>(5)
185                .expect("doc")
186                .append_value(functions::sql_doc(p));
187            params.append(true);
188        }
189        parameters.append(true);
190        for d in spec.directions() {
191            directions.values().append_value(d);
192        }
193        directions.append(true);
194        let outs = outputs.values();
195        for o in functions::outputs(spec) {
196            outs.field_builder::<StringBuilder>(0)
197                .expect("name")
198                .append_value(o.name);
199            // A neighbour aggregation's type depends on `agg` and the values.
200            let ty = if spec.reads_attribute() {
201                NEIGHBORS_AGG_TYPE.to_string()
202            } else {
203                o.ty.data_type().to_string()
204            };
205            outs.field_builder::<StringBuilder>(1)
206                .expect("type")
207                .append_value(ty);
208            outs.field_builder::<BooleanBuilder>(2)
209                .expect("nullable")
210                .append_value(o.nullable);
211            outs.append(true);
212        }
213        outputs.append(true);
214    }
215
216    for spec in TRAVERSALS {
217        name.append_value(spec.name);
218        family.append_value("traversal");
219        summary.append_value(spec.summary);
220        networkx.append_option(spec.networkx);
221        let params = parameters.values();
222        for p in spec.params {
223            let (ty, choices): (&str, &[&str]) = match &p.ty {
224                TraversalParamType::Nodes => ("node ids", &[]),
225                TraversalParamType::Node => ("node id", &[]),
226                TraversalParamType::Param(ty) => (functions::sql_type(p.name, *ty), ty.choices()),
227            };
228            params
229                .field_builder::<StringBuilder>(0)
230                .expect("name")
231                .append_value(p.name);
232            params
233                .field_builder::<StringBuilder>(1)
234                .expect("type")
235                .append_value(ty);
236            params
237                .field_builder::<StringBuilder>(2)
238                .expect("default")
239                .append_value(p.default.as_ref().map_or("required".to_string(), sql_value));
240            let choice_list = params
241                .field_builder::<ListBuilder<Box<dyn datafusion::arrow::array::ArrayBuilder>>>(3)
242                .expect("choices");
243            for c in choices {
244                choice_list
245                    .values()
246                    .as_any_mut()
247                    .downcast_mut::<StringBuilder>()
248                    .expect("choices are strings")
249                    .append_value(c);
250            }
251            choice_list.append(true);
252            // No traversal parameter has a range: any count is a traversal.
253            params
254                .field_builder::<StringBuilder>(4)
255                .expect("range")
256                .append_null();
257            params
258                .field_builder::<StringBuilder>(5)
259                .expect("doc")
260                .append_value(p.doc);
261            params.append(true);
262        }
263        parameters.append(true);
264        for d in spec.directions() {
265            directions.values().append_value(d);
266        }
267        directions.append(true);
268        let outs = outputs.values();
269        for o in spec.outputs {
270            let ty = match o.ty {
271                OutputType::Id => "Int64 or Utf8".to_string(),
272                other => other.data_type(&DataType::Null).to_string(),
273            };
274            outs.field_builder::<StringBuilder>(0)
275                .expect("name")
276                .append_value(o.name);
277            outs.field_builder::<StringBuilder>(1)
278                .expect("type")
279                .append_value(ty);
280            outs.field_builder::<BooleanBuilder>(2)
281                .expect("nullable")
282                .append_value(false);
283            outs.append(true);
284        }
285        outputs.append(true);
286    }
287
288    name.append_value(ALGORITHMS);
289    family.append_value("combinator");
290    summary.append_value(ALGORITHMS_SUMMARY);
291    networkx.append_null();
292    parameters.append(true);
293    directions.append(true);
294    outputs.append(true);
295
296    let columns: Vec<ArrayRef> = vec![
297        Arc::new(name.finish()),
298        Arc::new(family.finish()),
299        Arc::new(summary.finish()),
300        Arc::new(networkx.finish()),
301        Arc::new(parameters.finish()),
302        Arc::new(directions.finish()),
303        Arc::new(outputs.finish()),
304    ];
305    Ok(RecordBatch::try_new(schema(), columns)?)
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn one_row_per_function() {
314        let batch = functions_batch().unwrap();
315        let expected = functions::names().count();
316        assert_eq!(batch.num_rows(), expected);
317        assert_eq!(batch.schema(), schema());
318    }
319}