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//! | `same_as`    | for another system's name, the Ursa function it runs; else NULL |
26//! | `duckpgq`    | whether DuckPGQ has the function by this name, with these columns |
27//!
28//! DuckPGQ's names for Ursa's functions (#298), `weakly_connected_component`
29//! and `local_clustering_coefficient`, are rows of their own, last: their own name, column and summary, the parameters
30//! of the function they run less the ones the name fixes, and `same_as`
31//! naming that function. They are other systems' spellings, not old names of
32//! Ursa's own. `duckpgq` is true on them and on `pagerank`, which DuckPGQ
33//! has by the same name.
34//!
35//! A parameter's `type` is how SQL writes it (`number`, `number or NULL`,
36//! `integer`, `integer or NULL`, `boolean`, `string`, `expression`, `query`
37//! for `neighbors_agg`'s values, and for a traversal's node ids `node ids` or
38//! `node id`), and its `default` is the
39//! literal SQL would write (`0.85`, `'out'`, `NULL`), or `required`. Its
40//! `range` is the numbers it accepts, in words (`between 0 and 1`, `above 0
41//! and at most 1`, `at least 1`), or NULL when any value of its type is
42//! accepted (#416); a value outside it is an error that says the range. A
43//! traversal's node-id output columns have the graph's id type, `Int64 or
44//! Utf8`, and `neighbors_agg`'s column a type that depends on its `agg` and
45//! its values ([`NEIGHBORS_AGG_TYPE`]).
46
47use std::sync::Arc;
48
49/// The output type `ursa_functions()` gives `neighbors_agg`, whose column's
50/// type depends on `agg` and the values (`kernels::neighbors_agg_type`).
51pub const NEIGHBORS_AGG_TYPE: &str =
52    "Float64; UInt32 for count and n_unique; the values' type for min and max of strings, \
53     dates or times";
54
55use datafusion::arrow::array::UInt32Array;
56use datafusion::arrow::array::{
57    ArrayRef, BooleanBuilder, ListBuilder, StringBuilder, StructBuilder,
58};
59use datafusion::arrow::compute::take_record_batch;
60use datafusion::arrow::datatypes::{DataType, Field, Fields, Schema, SchemaRef};
61use datafusion::arrow::record_batch::RecordBatch;
62use datafusion::catalog::{TableFunctionArgs, TableFunctionImpl, TableProvider};
63use datafusion::datasource::MemTable;
64use datafusion::error::Result;
65use ursa_core::catalog::Family;
66
67use super::functions::{self, plan, sql_value, ALGORITHMS, URSA_FUNCTIONS};
68use super::traversal::{OutputType, TraversalParamType, TRAVERSALS};
69
70/// The `ursa_functions()` table function.
71#[derive(Debug)]
72pub struct UrsaFunctions;
73
74impl TableFunctionImpl for UrsaFunctions {
75    fn call_with_args(&self, args: TableFunctionArgs) -> Result<Arc<dyn TableProvider>> {
76        if !args.exprs().is_empty() {
77            return Err(plan(format!(
78                "{URSA_FUNCTIONS}() takes no arguments: SELECT * FROM {URSA_FUNCTIONS}()"
79            )));
80        }
81        let batch = functions_batch()?;
82        Ok(Arc::new(MemTable::try_new(
83            batch.schema(),
84            vec![vec![batch]],
85        )?))
86    }
87}
88
89fn parameter_fields() -> Fields {
90    Fields::from(vec![
91        Field::new("name", DataType::Utf8, false),
92        Field::new("type", DataType::Utf8, false),
93        Field::new("default", DataType::Utf8, false),
94        Field::new(
95            "choices",
96            DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
97            false,
98        ),
99        Field::new("range", DataType::Utf8, true),
100        Field::new("doc", DataType::Utf8, false),
101    ])
102}
103
104fn output_fields() -> Fields {
105    Fields::from(vec![
106        Field::new("name", DataType::Utf8, false),
107        Field::new("type", DataType::Utf8, false),
108        Field::new("nullable", DataType::Boolean, false),
109    ])
110}
111
112/// The schema of `ursa_functions()`.
113pub fn schema() -> SchemaRef {
114    let list = |item: DataType| DataType::List(Arc::new(Field::new("item", item, true)));
115    Arc::new(Schema::new(vec![
116        Field::new("name", DataType::Utf8, false),
117        Field::new("family", DataType::Utf8, false),
118        Field::new("summary", DataType::Utf8, false),
119        Field::new("networkx", DataType::Utf8, true),
120        Field::new(
121            "parameters",
122            list(DataType::Struct(parameter_fields())),
123            false,
124        ),
125        Field::new("directions", list(DataType::Utf8), false),
126        Field::new("outputs", list(DataType::Struct(output_fields())), false),
127        Field::new("same_as", DataType::Utf8, true),
128        Field::new("duckpgq", DataType::Boolean, false),
129    ]))
130}
131
132fn family_name(family: Family) -> &'static str {
133    match family {
134        Family::Algorithm => "algorithm",
135        Family::Layout => "layout",
136        Family::Aggregation => "aggregation",
137        Family::Statistic => "statistic",
138    }
139}
140
141/// The summary of the `algorithms` row.
142const ALGORITHMS_SUMMARY: &str = "Several per-node functions over one index, one row per node: \
143     algorithms(g, degree(direction => 'both'), community => louvain(seed => 1)). Each argument \
144     is a call with named parameters; its column is named by its key or after the function.";
145
146/// The rows of `ursa_functions()`.
147pub fn functions_batch() -> Result<RecordBatch> {
148    let mut name = StringBuilder::new();
149    let mut family = StringBuilder::new();
150    let mut summary = StringBuilder::new();
151    let mut networkx = StringBuilder::new();
152    let mut parameters =
153        ListBuilder::new(StructBuilder::from_fields(parameter_fields(), 0)).with_field(Arc::new(
154            Field::new("item", DataType::Struct(parameter_fields()), true),
155        ));
156    let mut directions = ListBuilder::new(StringBuilder::new());
157    let mut outputs = ListBuilder::new(StructBuilder::from_fields(output_fields(), 0)).with_field(
158        Arc::new(Field::new("item", DataType::Struct(output_fields()), true)),
159    );
160
161    let mut same_as = StringBuilder::new();
162    let mut duckpgq = BooleanBuilder::new();
163
164    // The catalog's functions, then DuckPGQ's names for some of them (moved
165    // to the end below).
166    let rows = functions::specs()
167        .map(|spec| (spec.name, spec.summary.to_string(), spec, None))
168        .chain(
169            functions::DUCKPGQ_NAMES
170                .iter()
171                .map(|d| (d.name, d.summary(), d.spec(), Some(d))),
172        );
173    for (row_name, row_summary, spec, compat) in rows {
174        name.append_value(row_name);
175        family.append_value(family_name(spec.family));
176        summary.append_value(row_summary);
177        networkx.append_option(spec.networkx);
178        same_as.append_option(compat.map(|d| d.function));
179        duckpgq.append_value(compat.is_some() || functions::DUCKPGQ_SAME.contains(&row_name));
180        let params = parameters.values();
181        let fixed = |p: &str| compat.is_some_and(|d| d.fixed.iter().any(|(f, _)| *f == p));
182        for p in functions::sql_params(spec).filter(|p| !fixed(p.name)) {
183            params
184                .field_builder::<StringBuilder>(0)
185                .expect("name")
186                .append_value(p.name);
187            params
188                .field_builder::<StringBuilder>(1)
189                .expect("type")
190                .append_value(functions::sql_type(p.name, p.ty));
191            params
192                .field_builder::<StringBuilder>(2)
193                .expect("default")
194                .append_value(sql_value(&p.default));
195            let choices = params
196                .field_builder::<ListBuilder<Box<dyn datafusion::arrow::array::ArrayBuilder>>>(3)
197                .expect("choices");
198            for c in p.ty.choices() {
199                choices
200                    .values()
201                    .as_any_mut()
202                    .downcast_mut::<StringBuilder>()
203                    .expect("choices are strings")
204                    .append_value(c);
205            }
206            choices.append(true);
207            params
208                .field_builder::<StringBuilder>(4)
209                .expect("range")
210                .append_option(functions::range_text(&p.range));
211            params
212                .field_builder::<StringBuilder>(5)
213                .expect("doc")
214                .append_value(functions::sql_doc(p));
215            params.append(true);
216        }
217        parameters.append(true);
218        for d in spec.directions() {
219            directions.values().append_value(d);
220        }
221        directions.append(true);
222        let outs = outputs.values();
223        for o in functions::outputs(spec) {
224            outs.field_builder::<StringBuilder>(0)
225                .expect("name")
226                .append_value(compat.map_or(o.name, |d| d.column));
227            // A neighbour aggregation's type depends on `agg` and the values.
228            let ty = if spec.reads_attribute() {
229                NEIGHBORS_AGG_TYPE.to_string()
230            } else {
231                o.ty.data_type().to_string()
232            };
233            outs.field_builder::<StringBuilder>(1)
234                .expect("type")
235                .append_value(ty);
236            outs.field_builder::<BooleanBuilder>(2)
237                .expect("nullable")
238                .append_value(o.nullable);
239            outs.append(true);
240        }
241        outputs.append(true);
242    }
243
244    for spec in TRAVERSALS {
245        name.append_value(spec.name);
246        family.append_value("traversal");
247        same_as.append_null();
248        duckpgq.append_value(false);
249        summary.append_value(spec.summary);
250        networkx.append_option(spec.networkx);
251        let params = parameters.values();
252        for p in spec.params {
253            let (ty, choices): (&str, &[&str]) = match &p.ty {
254                TraversalParamType::Nodes => ("node ids", &[]),
255                TraversalParamType::Node => ("node id", &[]),
256                TraversalParamType::Param(ty) => (functions::sql_type(p.name, *ty), ty.choices()),
257            };
258            params
259                .field_builder::<StringBuilder>(0)
260                .expect("name")
261                .append_value(p.name);
262            params
263                .field_builder::<StringBuilder>(1)
264                .expect("type")
265                .append_value(ty);
266            params
267                .field_builder::<StringBuilder>(2)
268                .expect("default")
269                .append_value(p.default.as_ref().map_or("required".to_string(), sql_value));
270            let choice_list = params
271                .field_builder::<ListBuilder<Box<dyn datafusion::arrow::array::ArrayBuilder>>>(3)
272                .expect("choices");
273            for c in choices {
274                choice_list
275                    .values()
276                    .as_any_mut()
277                    .downcast_mut::<StringBuilder>()
278                    .expect("choices are strings")
279                    .append_value(c);
280            }
281            choice_list.append(true);
282            // No traversal parameter has a range: any count is a traversal.
283            params
284                .field_builder::<StringBuilder>(4)
285                .expect("range")
286                .append_null();
287            params
288                .field_builder::<StringBuilder>(5)
289                .expect("doc")
290                .append_value(p.doc);
291            params.append(true);
292        }
293        parameters.append(true);
294        for d in spec.directions() {
295            directions.values().append_value(d);
296        }
297        directions.append(true);
298        let outs = outputs.values();
299        for o in spec.outputs {
300            let ty = match o.ty {
301                OutputType::Id => "Int64 or Utf8".to_string(),
302                other => other.data_type(&DataType::Null).to_string(),
303            };
304            outs.field_builder::<StringBuilder>(0)
305                .expect("name")
306                .append_value(o.name);
307            outs.field_builder::<StringBuilder>(1)
308                .expect("type")
309                .append_value(ty);
310            outs.field_builder::<BooleanBuilder>(2)
311                .expect("nullable")
312                .append_value(false);
313            outs.append(true);
314        }
315        outputs.append(true);
316    }
317
318    name.append_value(ALGORITHMS);
319    family.append_value("combinator");
320    same_as.append_null();
321    duckpgq.append_value(false);
322    summary.append_value(ALGORITHMS_SUMMARY);
323    networkx.append_null();
324    parameters.append(true);
325    directions.append(true);
326    outputs.append(true);
327
328    let columns: Vec<ArrayRef> = vec![
329        Arc::new(name.finish()),
330        Arc::new(family.finish()),
331        Arc::new(summary.finish()),
332        Arc::new(networkx.finish()),
333        Arc::new(parameters.finish()),
334        Arc::new(directions.finish()),
335        Arc::new(outputs.finish()),
336        Arc::new(same_as.finish()),
337        Arc::new(duckpgq.finish()),
338    ];
339    let batch = RecordBatch::try_new(schema(), columns)?;
340    // DuckPGQ's names go last, after `algorithms`: they were built beside
341    // the catalog's functions, whose code they share.
342    let (specs, duckpgq) = (functions::specs().count(), functions::DUCKPGQ_NAMES.len());
343    let order: Vec<u32> = (0..specs)
344        .chain(specs + duckpgq..batch.num_rows())
345        .chain(specs..specs + duckpgq)
346        .map(|i| i as u32)
347        .collect();
348    Ok(take_record_batch(&batch, &UInt32Array::from(order))?)
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn one_row_per_function() {
357        let batch = functions_batch().unwrap();
358        let expected = functions::names().count() + functions::DUCKPGQ_NAMES.len();
359        assert_eq!(batch.num_rows(), expected);
360        assert_eq!(batch.schema(), schema());
361    }
362}