Skip to main content

ursa_engine/graph/
mod.rs

1//! Graphs in a session: their definitions and where they are kept.
2//!
3//! A graph is defined by `CREATE PROPERTY GRAPH` (SQL/PGQ) over tables or views
4//! already in the session: one edge table with a source and a destination
5//! column, and optionally one vertex table keyed by an id column. Without a
6//! vertex table, the nodes are the endpoints of the edges.
7//!
8//! This module is the contract between the graph DDL (which creates and drops
9//! [`GraphDef`]s) and everything that reads graphs: the `<graph>.nodes` and
10//! `<graph>.edges` tables and the algorithm table functions. Definitions are
11//! held per session in a [`GraphRegistry`], stored as a session config
12//! extension so any code holding the session state can reach it.
13//!
14//! A definition names tables; it does not copy or pin their rows. Every query
15//! plans the edge table afresh, so a graph over a view of a file sees the
16//! file's current contents.
17//!
18//! An edge or vertex table may also be a file path or URL, as in `FROM`
19//! (`EDGE TABLES ('edges.csv' SOURCE KEY (src) DESTINATION KEY (dst))`). It is
20//! opened once, when the graph is created, as a listing table that the
21//! registry keeps for that graph ([`GraphRegistry::file_table`]); it is not
22//! registered under any name, so it never shows in a listing. Like a view over
23//! the file, it fixes the file's columns at that point and reads the file's
24//! current rows on every query.
25//!
26//! Tables a graph uses cannot be dropped, or replaced by ones the graph's
27//! definition no longer fits, while the graph exists ([`check_drop`],
28//! [`check_replace`]). If one disappears anyway (through the DataFusion API),
29//! `<graph>.nodes` and `<graph>.edges` fail when queried, and session listings
30//! keep working.
31//!
32//! Algorithms over a graph are table functions, `FROM pagerank(g)`, planned
33//! as a [`GraphAlgorithmNode`] whose child is the edge table ([`functions`],
34//! `relation`, `node`, `exec`), with the built index cached per session
35//! ([`IndexCache`]).
36//!
37//! Traversals (`hop`, `shortest_path`, `random_walk`) are table functions
38//! too, planned as a [`GraphTraversalNode`] over the same edge plan, with one
39//! more child per node-id argument (a list, or a subquery that runs when the
40//! node runs); see [`traversal`].
41
42use std::collections::BTreeMap;
43use std::sync::{Arc, OnceLock, RwLock};
44
45use datafusion::catalog::{CatalogProviderList, TableProvider};
46use datafusion::common::TableReference;
47use datafusion::execution::context::SessionState;
48use datafusion::prelude::{SessionConfig, SessionContext};
49
50mod define;
51mod describe;
52pub mod schema;
53
54pub use define::{
55    check_ddl, check_drop, check_drop_schema, check_replace, closest_name, create_graph,
56    drop_graph, unknown_graph, EdgeSpec, GraphSpec, VertexSpec,
57};
58pub use describe::{describe_graph, show_graphs};
59pub use schema::{edges_plan, edges_plan_from, nodes_plan, nodes_plan_from, GraphSchema};
60
61mod catalog_table;
62mod exec;
63pub mod functions;
64mod in_order;
65mod index;
66mod kernels;
67mod node;
68pub mod path_search;
69pub mod pattern;
70mod relation;
71mod session;
72pub mod traversal;
73
74pub use catalog_table::UrsaFunctions;
75pub use exec::{
76    GraphAlgorithmExec, GraphPlanner, GraphTraversalExec, KeepEdgeOrder, UrsaQueryPlanner,
77};
78pub use index::{
79    index_builds, index_loads, BuildInfo, BuildSize, FileIdentity, GraphIndex, IndexCache,
80    IndexHeld, Weights,
81};
82pub use node::{GraphAlgorithmNode, GraphTraversalNode, Output};
83pub(crate) use session::{edge_order_rule, query_planner, register_functions, with_algorithms};
84
85/// One graph, as `CREATE PROPERTY GRAPH` defined it: its vertex and edge
86/// tables (SQL/PGQ's element tables), with their keys resolved (#295).
87///
88/// `MATCH` spans every table. An algorithm runs on one vertex table and one
89/// edge table, a [`GraphDef`], as in DuckPGQ: see [`PropertyGraph::pair`].
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct PropertyGraph {
92    /// The graph's name: also the name of the schema holding its `nodes` and
93    /// `edges` tables (when it has one implied pair; see [`Self::pair`]).
94    pub name: String,
95    pub vertex_tables: Vec<VertexTable>,
96    pub edge_tables: Vec<EdgeTable>,
97}
98
99/// A graph as an algorithm sees it: one edge table, and the vertex table its
100/// endpoints refer to, if any. A whole graph before #295; now one pair of a
101/// [`PropertyGraph`].
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct GraphDef {
104    /// The graph's name.
105    pub name: String,
106    pub edges: EdgeTable,
107    /// The vertex table, if the pair has one.
108    pub vertices: Option<VertexTable>,
109}
110
111/// An edge table: each row is an edge from `source` to `destination`.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct EdgeTable {
114    /// Its element name: the `AS` name, or else the table's name.
115    pub name: String,
116    pub table: TableReference,
117    /// `SOURCE KEY (column)`.
118    pub source: String,
119    /// `DESTINATION KEY (column)`.
120    pub destination: String,
121    /// The vertex table (element name) `SOURCE … REFERENCES`, if any.
122    pub source_vertex: Option<String>,
123    /// The vertex table (element name) `DESTINATION … REFERENCES`, if any.
124    pub destination_vertex: Option<String>,
125    pub labels: Vec<Label>,
126}
127
128/// A vertex table: each row is a node, keyed by `key`.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct VertexTable {
131    /// Its element name: the `AS` name, or else the table's name.
132    pub name: String,
133    pub table: TableReference,
134    /// `KEY (column)`, or the key inferred when `KEY` was left out.
135    pub key: String,
136    pub labels: Vec<Label>,
137}
138
139/// A label of an element table, and the properties it exposes.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Label {
142    pub name: String,
143    pub properties: Properties,
144}
145
146/// The properties a label exposes.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum Properties {
149    /// Every column but `except`: no properties clause, or `PROPERTIES ARE
150    /// ALL COLUMNS [EXCEPT (…)]`.
151    AllColumns { except: Vec<String> },
152    /// `PROPERTIES (column [AS name], …)`: (column, property name) pairs.
153    Columns(Vec<(String, String)>),
154    /// `NO PROPERTIES`.
155    None,
156}
157
158impl Label {
159    /// The default label of an element table: its name, with every column.
160    pub fn default_for(element: &str) -> Self {
161        Label {
162            name: element.to_string(),
163            properties: Properties::AllColumns { except: Vec::new() },
164        }
165    }
166}
167
168/// An element table's labels, or its default label when none were written.
169fn labels_or_default<'a>(labels: &'a [Label], name: &str) -> std::borrow::Cow<'a, [Label]> {
170    if labels.is_empty() {
171        std::borrow::Cow::Owned(vec![Label::default_for(name)])
172    } else {
173        std::borrow::Cow::Borrowed(labels)
174    }
175}
176
177impl VertexTable {
178    /// A vertex table named after its table, with its default label.
179    pub fn new(table: impl Into<TableReference>, key: impl Into<String>) -> Self {
180        let table = table.into();
181        VertexTable {
182            name: table.table().to_string(),
183            table,
184            key: key.into(),
185            labels: Vec::new(),
186        }
187    }
188
189    /// Its labels, the default one if none were written.
190    pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
191        labels_or_default(&self.labels, &self.name)
192    }
193
194    /// Whether `label` names this table: its element name or one of its labels.
195    pub fn answers_to(&self, label: &str) -> bool {
196        self.name.eq_ignore_ascii_case(label)
197            || self
198                .labels
199                .iter()
200                .any(|l| l.name.eq_ignore_ascii_case(label))
201    }
202}
203
204impl EdgeTable {
205    /// An edge table named after its table, with its default label and no
206    /// `REFERENCES`.
207    pub fn new(
208        table: impl Into<TableReference>,
209        source: impl Into<String>,
210        destination: impl Into<String>,
211    ) -> Self {
212        let table = table.into();
213        EdgeTable {
214            name: table.table().to_string(),
215            table,
216            source: source.into(),
217            destination: destination.into(),
218            source_vertex: None,
219            destination_vertex: None,
220            labels: Vec::new(),
221        }
222    }
223
224    /// Its labels, the default one if none were written.
225    pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
226        labels_or_default(&self.labels, &self.name)
227    }
228
229    /// Whether `label` names this table: its element name or one of its labels.
230    pub fn answers_to(&self, label: &str) -> bool {
231        self.name.eq_ignore_ascii_case(label)
232            || self
233                .labels
234                .iter()
235                .any(|l| l.name.eq_ignore_ascii_case(label))
236    }
237}
238
239/// A graph of one pair: what every graph was before #295.
240impl From<GraphDef> for PropertyGraph {
241    fn from(def: GraphDef) -> Self {
242        PropertyGraph {
243            name: def.name,
244            vertex_tables: def.vertices.into_iter().collect(),
245            edge_tables: vec![def.edges],
246        }
247    }
248}
249
250impl PropertyGraph {
251    /// Every table the graph reads, vertex tables first.
252    pub fn tables(&self) -> impl Iterator<Item = &TableReference> {
253        self.vertex_tables
254            .iter()
255            .map(|v| &v.table)
256            .chain(self.edge_tables.iter().map(|e| &e.table))
257    }
258
259    /// The vertex table called (or labelled) `label`.
260    pub fn vertex_table(&self, label: &str) -> Option<&VertexTable> {
261        self.vertex_tables
262            .iter()
263            .find(|v| v.name.eq_ignore_ascii_case(label))
264            .or_else(|| self.vertex_tables.iter().find(|v| v.answers_to(label)))
265    }
266
267    /// The edge table called (or labelled) `label`.
268    pub fn edge_table(&self, label: &str) -> Option<&EdgeTable> {
269        self.edge_tables
270            .iter()
271            .find(|e| e.name.eq_ignore_ascii_case(label))
272            .or_else(|| self.edge_tables.iter().find(|e| e.answers_to(label)))
273    }
274
275    /// The vertex table an endpoint of `edge` refers to: its `REFERENCES`, or
276    /// without one, the graph's only vertex table (`None` if it has none).
277    pub fn endpoint_vertex(&self, edge: &EdgeTable, source: bool) -> Option<&VertexTable> {
278        let named = if source {
279            &edge.source_vertex
280        } else {
281            &edge.destination_vertex
282        };
283        match named {
284            Some(name) => self.vertex_tables.iter().find(|v| &v.name == name),
285            None if self.vertex_tables.len() == 1 => self.vertex_tables.first(),
286            None => None,
287        }
288    }
289
290    /// The pair an algorithm runs on: an edge table, and the vertex table both
291    /// its endpoints refer to (if any), as DuckPGQ's `pagerank(g, vertex,
292    /// edge)`. With no labels the pair is implied when the graph has one edge
293    /// table: every graph before #295 has one.
294    pub fn pair(
295        &self,
296        vertex: Option<&str>,
297        edge: Option<&str>,
298    ) -> datafusion::error::Result<GraphDef> {
299        use datafusion::error::DataFusionError;
300        let plan_err = |m: String| Err(DataFusionError::Plan(m));
301        let edges = match edge {
302            Some(label) => match self.edge_table(label) {
303                Some(e) => e,
304                None => {
305                    let names: Vec<&str> =
306                        self.edge_tables.iter().map(|e| e.name.as_str()).collect();
307                    return plan_err(format!(
308                        "graph '{}' has no edge table '{label}'; its edge tables are {}",
309                        self.name,
310                        if names.is_empty() {
311                            "none".to_string()
312                        } else {
313                            names.join(", ")
314                        }
315                    ));
316                }
317            },
318            None => match self.edge_tables.as_slice() {
319                [only] => only,
320                [] => {
321                    return plan_err(format!(
322                        "graph '{}' has no edge tables, so there is nothing for an algorithm to \
323                         run on",
324                        self.name
325                    ))
326                }
327                several => {
328                    let names: Vec<&str> = several.iter().map(|e| e.name.as_str()).collect();
329                    return plan_err(format!(
330                        "graph '{}' has {} edge tables ({}); name the vertex and edge table to \
331                         run on, as in pagerank({}, <vertex table>, <edge table>)",
332                        self.name,
333                        several.len(),
334                        names.join(", "),
335                        self.name
336                    ));
337                }
338            },
339        };
340        let source = self.endpoint_vertex(edges, true);
341        let destination = self.endpoint_vertex(edges, false);
342        if let (Some(s), Some(d)) = (source, destination) {
343            if s.name != d.name {
344                return plan_err(format!(
345                    "edge table '{}' of graph '{}' goes from vertex table '{}' to '{}'; an \
346                     algorithm runs on edges between one vertex table",
347                    edges.name, self.name, s.name, d.name
348                ));
349            }
350        }
351        let vertices = source.or(destination);
352        if let Some(label) = vertex {
353            let Some(asked) = self.vertex_table(label) else {
354                let names: Vec<&str> = self.vertex_tables.iter().map(|v| v.name.as_str()).collect();
355                return plan_err(format!(
356                    "graph '{}' has no vertex table '{label}'; its vertex tables are {}",
357                    self.name,
358                    if names.is_empty() {
359                        "none".to_string()
360                    } else {
361                        names.join(", ")
362                    }
363                ));
364            };
365            if vertices.is_some_and(|v| v.name != asked.name) {
366                return plan_err(format!(
367                    "edge table '{}' of graph '{}' connects vertex table '{}', not '{}'",
368                    edges.name,
369                    self.name,
370                    vertices.map(|v| v.name.as_str()).unwrap_or_default(),
371                    asked.name
372                ));
373            }
374            return Ok(GraphDef {
375                name: self.name.clone(),
376                edges: edges.clone(),
377                vertices: Some(asked.clone()),
378            });
379        }
380        Ok(GraphDef {
381            name: self.name.clone(),
382            edges: edges.clone(),
383            vertices: vertices.cloned(),
384        })
385    }
386
387    /// The implied pair, when there is one: the graph's `nodes` and `edges`
388    /// tables are this pair's.
389    pub fn default_pair(&self) -> Option<GraphDef> {
390        if self.vertex_tables.len() > 1 {
391            return None;
392        }
393        self.pair(None, None).ok()
394    }
395}
396
397/// A table a graph opened from a file path or URL when it was created.
398#[derive(Debug, Clone)]
399pub struct FileTable {
400    /// The table reference the definition names: the path, as written.
401    pub table: TableReference,
402    pub provider: Arc<dyn TableProvider>,
403}
404
405/// The graphs defined in one session, by name. Names are compared as given
406/// (the DDL normalizes identifiers the way DataFusion does for tables).
407#[derive(Debug, Default)]
408pub struct GraphRegistry {
409    graphs: RwLock<BTreeMap<String, Arc<PropertyGraph>>>,
410    /// Per graph, the tables it opened from file paths (see the module docs).
411    files: RwLock<BTreeMap<String, Vec<FileTable>>>,
412    /// The session's catalogs before the file-table wrapper: graph schemas are
413    /// registered and dropped there (the wrapper cannot drop a schema).
414    catalogs: OnceLock<Arc<dyn CatalogProviderList>>,
415}
416
417impl GraphRegistry {
418    /// The graph called `name`.
419    pub fn get(&self, name: &str) -> Option<Arc<PropertyGraph>> {
420        self.graphs
421            .read()
422            .unwrap_or_else(|e| e.into_inner())
423            .get(name)
424            .cloned()
425    }
426
427    /// Every graph, sorted by name.
428    pub fn all(&self) -> Vec<Arc<PropertyGraph>> {
429        self.graphs
430            .read()
431            .unwrap_or_else(|e| e.into_inner())
432            .values()
433            .cloned()
434            .collect()
435    }
436
437    /// Add or replace `def`; returns the definition it replaced.
438    pub fn put(&self, def: impl Into<PropertyGraph>) -> Option<Arc<PropertyGraph>> {
439        self.put_with_files(def.into(), Vec::new())
440    }
441
442    /// Add or replace `def`, with the tables it opened from file paths.
443    pub fn put_with_files(
444        &self,
445        def: PropertyGraph,
446        files: Vec<FileTable>,
447    ) -> Option<Arc<PropertyGraph>> {
448        let mut graphs = self.graphs.write().unwrap_or_else(|e| e.into_inner());
449        let mut all_files = self.files.write().unwrap_or_else(|e| e.into_inner());
450        if files.is_empty() {
451            all_files.remove(&def.name);
452        } else {
453            all_files.insert(def.name.clone(), files);
454        }
455        graphs.insert(def.name.clone(), Arc::new(def))
456    }
457
458    /// Remove the graph called `name`; returns it if it existed.
459    pub fn remove(&self, name: &str) -> Option<Arc<PropertyGraph>> {
460        let mut graphs = self.graphs.write().unwrap_or_else(|e| e.into_inner());
461        self.files
462            .write()
463            .unwrap_or_else(|e| e.into_inner())
464            .remove(name);
465        graphs.remove(name)
466    }
467
468    /// The table graph `graph` opened from the file path `table`, if `table`
469    /// is one of its file tables.
470    pub fn file_table(
471        &self,
472        graph: &str,
473        table: &TableReference,
474    ) -> Option<Arc<dyn TableProvider>> {
475        self.files
476            .read()
477            .unwrap_or_else(|e| e.into_inner())
478            .get(graph)?
479            .iter()
480            .find(|f| &f.table == table)
481            .map(|f| Arc::clone(&f.provider))
482    }
483
484    /// Record the session's unwrapped catalog list (done by `new_session`).
485    pub(crate) fn set_catalogs(&self, catalogs: Arc<dyn CatalogProviderList>) {
486        let _ = self.catalogs.set(catalogs);
487    }
488
489    pub(crate) fn catalogs(&self) -> Option<&Arc<dyn CatalogProviderList>> {
490        self.catalogs.get()
491    }
492
493    /// The names of all graphs, sorted: for "did you mean" suggestions.
494    pub fn names(&self) -> Vec<String> {
495        self.graphs
496            .read()
497            .unwrap_or_else(|e| e.into_inner())
498            .keys()
499            .cloned()
500            .collect()
501    }
502}
503
504/// Install an empty registry on `config` (done by `new_session`).
505pub(crate) fn with_registry(config: SessionConfig) -> SessionConfig {
506    config.with_extension(Arc::new(GraphRegistry::default()))
507}
508
509/// The session's graph registry.
510pub fn registry(state: &SessionState) -> Arc<GraphRegistry> {
511    state
512        .config()
513        .get_extension::<GraphRegistry>()
514        .expect("an Ursa session has a graph registry (built by ursa_engine::new_session)")
515}
516
517/// The graph registry of `ctx`.
518pub fn registry_of(ctx: &SessionContext) -> Arc<GraphRegistry> {
519    registry(&ctx.state())
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525
526    #[test]
527    fn a_session_has_an_empty_registry() {
528        let ctx = crate::new_session();
529        let graphs = registry_of(&ctx);
530        assert!(graphs.all().is_empty());
531        graphs.put(PropertyGraph {
532            name: "g".into(),
533            vertex_tables: Vec::new(),
534            edge_tables: vec![EdgeTable::new(TableReference::bare("e"), "a", "b")],
535        });
536        // The registry is shared by every handle on the session.
537        assert_eq!(registry_of(&ctx).names(), vec!["g".to_string()]);
538    }
539}