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::{
84    collapse_held_rule, edge_order_rule, query_planner, register_functions, with_algorithms,
85};
86
87/// One graph, as `CREATE PROPERTY GRAPH` defined it: its vertex and edge
88/// tables (SQL/PGQ's element tables), with their keys resolved (#295).
89///
90/// `MATCH` spans every table. An algorithm runs on one vertex table and one
91/// edge table, a [`GraphDef`], as in DuckPGQ: see [`PropertyGraph::pair`].
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct PropertyGraph {
94    /// The graph's name: also the name of the schema holding its `nodes` and
95    /// `edges` tables (when it has one implied pair; see [`Self::pair`]).
96    pub name: String,
97    pub vertex_tables: Vec<VertexTable>,
98    pub edge_tables: Vec<EdgeTable>,
99}
100
101/// A graph as an algorithm sees it: one edge table, and the vertex table its
102/// endpoints refer to, if any. A whole graph before #295; now one pair of a
103/// [`PropertyGraph`].
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct GraphDef {
106    /// The graph's name.
107    pub name: String,
108    pub edges: EdgeTable,
109    /// The vertex table, if the pair has one.
110    pub vertices: Option<VertexTable>,
111}
112
113/// An edge table: each row is an edge from `source` to `destination`.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct EdgeTable {
116    /// Its element name: the `AS` name, or else the table's name.
117    pub name: String,
118    pub table: TableReference,
119    /// `SOURCE KEY (column)`.
120    pub source: String,
121    /// `DESTINATION KEY (column)`.
122    pub destination: String,
123    /// The vertex table (element name) `SOURCE … REFERENCES`, if any.
124    pub source_vertex: Option<String>,
125    /// The vertex table (element name) `DESTINATION … REFERENCES`, if any.
126    pub destination_vertex: Option<String>,
127    pub labels: Vec<Label>,
128}
129
130/// A vertex table: each row is a node, keyed by `key`.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct VertexTable {
133    /// Its element name: the `AS` name, or else the table's name.
134    pub name: String,
135    pub table: TableReference,
136    /// `KEY (column)`, or the key inferred when `KEY` was left out.
137    pub key: String,
138    pub labels: Vec<Label>,
139}
140
141/// A label of an element table, and the properties it exposes.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Label {
144    pub name: String,
145    pub properties: Properties,
146}
147
148/// The properties a label exposes.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum Properties {
151    /// Every column but `except`: no properties clause, or `PROPERTIES ARE
152    /// ALL COLUMNS [EXCEPT (…)]`.
153    AllColumns { except: Vec<String> },
154    /// `PROPERTIES (column [AS name], …)`: (column, property name) pairs.
155    Columns(Vec<(String, String)>),
156    /// `NO PROPERTIES`.
157    None,
158}
159
160impl Label {
161    /// The default label of an element table: its name, with every column.
162    pub fn default_for(element: &str) -> Self {
163        Label {
164            name: element.to_string(),
165            properties: Properties::AllColumns { except: Vec::new() },
166        }
167    }
168}
169
170/// An element table's labels, or its default label when none were written.
171fn labels_or_default<'a>(labels: &'a [Label], name: &str) -> std::borrow::Cow<'a, [Label]> {
172    if labels.is_empty() {
173        std::borrow::Cow::Owned(vec![Label::default_for(name)])
174    } else {
175        std::borrow::Cow::Borrowed(labels)
176    }
177}
178
179impl VertexTable {
180    /// A vertex table named after its table, with its default label.
181    pub fn new(table: impl Into<TableReference>, key: impl Into<String>) -> Self {
182        let table = table.into();
183        VertexTable {
184            name: table.table().to_string(),
185            table,
186            key: key.into(),
187            labels: Vec::new(),
188        }
189    }
190
191    /// Its labels, the default one if none were written.
192    pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
193        labels_or_default(&self.labels, &self.name)
194    }
195
196    /// Whether `label` names this table: its element name or one of its labels.
197    pub fn answers_to(&self, label: &str) -> bool {
198        self.name.eq_ignore_ascii_case(label)
199            || self
200                .labels
201                .iter()
202                .any(|l| l.name.eq_ignore_ascii_case(label))
203    }
204}
205
206impl EdgeTable {
207    /// An edge table named after its table, with its default label and no
208    /// `REFERENCES`.
209    pub fn new(
210        table: impl Into<TableReference>,
211        source: impl Into<String>,
212        destination: impl Into<String>,
213    ) -> Self {
214        let table = table.into();
215        EdgeTable {
216            name: table.table().to_string(),
217            table,
218            source: source.into(),
219            destination: destination.into(),
220            source_vertex: None,
221            destination_vertex: None,
222            labels: Vec::new(),
223        }
224    }
225
226    /// Its labels, the default one if none were written.
227    pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
228        labels_or_default(&self.labels, &self.name)
229    }
230
231    /// Whether `label` names this table: its element name or one of its labels.
232    pub fn answers_to(&self, label: &str) -> bool {
233        self.name.eq_ignore_ascii_case(label)
234            || self
235                .labels
236                .iter()
237                .any(|l| l.name.eq_ignore_ascii_case(label))
238    }
239}
240
241/// A graph of one pair: what every graph was before #295.
242impl From<GraphDef> for PropertyGraph {
243    fn from(def: GraphDef) -> Self {
244        PropertyGraph {
245            name: def.name,
246            vertex_tables: def.vertices.into_iter().collect(),
247            edge_tables: vec![def.edges],
248        }
249    }
250}
251
252impl PropertyGraph {
253    /// Every table the graph reads, vertex tables first.
254    pub fn tables(&self) -> impl Iterator<Item = &TableReference> {
255        self.vertex_tables
256            .iter()
257            .map(|v| &v.table)
258            .chain(self.edge_tables.iter().map(|e| &e.table))
259    }
260
261    /// The vertex table called (or labelled) `label`.
262    pub fn vertex_table(&self, label: &str) -> Option<&VertexTable> {
263        self.vertex_tables
264            .iter()
265            .find(|v| v.name.eq_ignore_ascii_case(label))
266            .or_else(|| self.vertex_tables.iter().find(|v| v.answers_to(label)))
267    }
268
269    /// The edge table called (or labelled) `label`.
270    pub fn edge_table(&self, label: &str) -> Option<&EdgeTable> {
271        self.edge_tables
272            .iter()
273            .find(|e| e.name.eq_ignore_ascii_case(label))
274            .or_else(|| self.edge_tables.iter().find(|e| e.answers_to(label)))
275    }
276
277    /// The vertex table an endpoint of `edge` refers to: its `REFERENCES`, or
278    /// without one, the graph's only vertex table (`None` if it has none).
279    pub fn endpoint_vertex(&self, edge: &EdgeTable, source: bool) -> Option<&VertexTable> {
280        let named = if source {
281            &edge.source_vertex
282        } else {
283            &edge.destination_vertex
284        };
285        match named {
286            Some(name) => self.vertex_tables.iter().find(|v| &v.name == name),
287            None if self.vertex_tables.len() == 1 => self.vertex_tables.first(),
288            None => None,
289        }
290    }
291
292    /// The pair an algorithm runs on: an edge table, and the vertex table both
293    /// its endpoints refer to (if any), as DuckPGQ's `pagerank(g, vertex,
294    /// edge)`. With no labels the pair is implied when the graph has one edge
295    /// table: every graph before #295 has one.
296    pub fn pair(
297        &self,
298        vertex: Option<&str>,
299        edge: Option<&str>,
300    ) -> datafusion::error::Result<GraphDef> {
301        use datafusion::error::DataFusionError;
302        let plan_err = |m: String| Err(DataFusionError::Plan(m));
303        let edges = match edge {
304            Some(label) => match self.edge_table(label) {
305                Some(e) => e,
306                None => {
307                    let names: Vec<&str> =
308                        self.edge_tables.iter().map(|e| e.name.as_str()).collect();
309                    return plan_err(format!(
310                        "graph '{}' has no edge table '{label}'; its edge tables are {}",
311                        self.name,
312                        if names.is_empty() {
313                            "none".to_string()
314                        } else {
315                            names.join(", ")
316                        }
317                    ));
318                }
319            },
320            None => match self.edge_tables.as_slice() {
321                [only] => only,
322                [] => {
323                    return plan_err(format!(
324                        "graph '{}' has no edge tables, so there is nothing for an algorithm to \
325                         run on",
326                        self.name
327                    ))
328                }
329                several => {
330                    let names: Vec<&str> = several.iter().map(|e| e.name.as_str()).collect();
331                    return plan_err(format!(
332                        "graph '{}' has {} edge tables ({}); name the vertex and edge table to \
333                         run on, as in pagerank({}, <vertex table>, <edge table>)",
334                        self.name,
335                        several.len(),
336                        names.join(", "),
337                        self.name
338                    ));
339                }
340            },
341        };
342        let source = self.endpoint_vertex(edges, true);
343        let destination = self.endpoint_vertex(edges, false);
344        if let (Some(s), Some(d)) = (source, destination) {
345            if s.name != d.name {
346                return plan_err(format!(
347                    "edge table '{}' of graph '{}' goes from vertex table '{}' to '{}'; an \
348                     algorithm runs on edges between one vertex table",
349                    edges.name, self.name, s.name, d.name
350                ));
351            }
352        }
353        let vertices = source.or(destination);
354        if let Some(label) = vertex {
355            let Some(asked) = self.vertex_table(label) else {
356                let names: Vec<&str> = self.vertex_tables.iter().map(|v| v.name.as_str()).collect();
357                return plan_err(format!(
358                    "graph '{}' has no vertex table '{label}'; its vertex tables are {}",
359                    self.name,
360                    if names.is_empty() {
361                        "none".to_string()
362                    } else {
363                        names.join(", ")
364                    }
365                ));
366            };
367            if vertices.is_some_and(|v| v.name != asked.name) {
368                return plan_err(format!(
369                    "edge table '{}' of graph '{}' connects vertex table '{}', not '{}'",
370                    edges.name,
371                    self.name,
372                    vertices.map(|v| v.name.as_str()).unwrap_or_default(),
373                    asked.name
374                ));
375            }
376            return Ok(GraphDef {
377                name: self.name.clone(),
378                edges: edges.clone(),
379                vertices: Some(asked.clone()),
380            });
381        }
382        Ok(GraphDef {
383            name: self.name.clone(),
384            edges: edges.clone(),
385            vertices: vertices.cloned(),
386        })
387    }
388
389    /// The implied pair, when there is one: the graph's `nodes` and `edges`
390    /// tables are this pair's.
391    pub fn default_pair(&self) -> Option<GraphDef> {
392        if self.vertex_tables.len() > 1 {
393            return None;
394        }
395        self.pair(None, None).ok()
396    }
397}
398
399/// A table a graph opened from a file path or URL when it was created.
400#[derive(Debug, Clone)]
401pub struct FileTable {
402    /// The table reference the definition names: the path, as written.
403    pub table: TableReference,
404    pub provider: Arc<dyn TableProvider>,
405}
406
407/// The graphs defined in one session, by name. Names are compared as given
408/// (the DDL normalizes identifiers the way DataFusion does for tables).
409#[derive(Debug, Default)]
410pub struct GraphRegistry {
411    graphs: RwLock<BTreeMap<String, Arc<PropertyGraph>>>,
412    /// Per graph, the tables it opened from file paths (see the module docs).
413    files: RwLock<BTreeMap<String, Vec<FileTable>>>,
414    /// The session's catalogs before the file-table wrapper: graph schemas are
415    /// registered and dropped there (the wrapper cannot drop a schema).
416    catalogs: OnceLock<Arc<dyn CatalogProviderList>>,
417    /// Graphs of the session's database that could not be defined when it
418    /// was opened, by name, with why (see [`crate::database::unavailable`]).
419    unavailable: RwLock<BTreeMap<String, String>>,
420}
421
422impl GraphRegistry {
423    /// The graph called `name`.
424    pub fn get(&self, name: &str) -> Option<Arc<PropertyGraph>> {
425        self.graphs
426            .read()
427            .unwrap_or_else(|e| e.into_inner())
428            .get(name)
429            .cloned()
430    }
431
432    /// Every graph, sorted by name.
433    pub fn all(&self) -> Vec<Arc<PropertyGraph>> {
434        self.graphs
435            .read()
436            .unwrap_or_else(|e| e.into_inner())
437            .values()
438            .cloned()
439            .collect()
440    }
441
442    /// Add or replace `def`; returns the definition it replaced.
443    pub fn put(&self, def: impl Into<PropertyGraph>) -> Option<Arc<PropertyGraph>> {
444        self.put_with_files(def.into(), Vec::new())
445    }
446
447    /// Add or replace `def`, with the tables it opened from file paths.
448    pub fn put_with_files(
449        &self,
450        def: PropertyGraph,
451        files: Vec<FileTable>,
452    ) -> Option<Arc<PropertyGraph>> {
453        let mut graphs = self.graphs.write().unwrap_or_else(|e| e.into_inner());
454        let mut all_files = self.files.write().unwrap_or_else(|e| e.into_inner());
455        if files.is_empty() {
456            all_files.remove(&def.name);
457        } else {
458            all_files.insert(def.name.clone(), files);
459        }
460        graphs.insert(def.name.clone(), Arc::new(def))
461    }
462
463    /// Remove the graph called `name`; returns it if it existed.
464    pub fn remove(&self, name: &str) -> Option<Arc<PropertyGraph>> {
465        let mut graphs = self.graphs.write().unwrap_or_else(|e| e.into_inner());
466        self.files
467            .write()
468            .unwrap_or_else(|e| e.into_inner())
469            .remove(name);
470        graphs.remove(name)
471    }
472
473    /// The table graph `graph` opened from the file path `table`, if `table`
474    /// is one of its file tables.
475    pub fn file_table(
476        &self,
477        graph: &str,
478        table: &TableReference,
479    ) -> Option<Arc<dyn TableProvider>> {
480        self.files
481            .read()
482            .unwrap_or_else(|e| e.into_inner())
483            .get(graph)?
484            .iter()
485            .find(|f| &f.table == table)
486            .map(|f| Arc::clone(&f.provider))
487    }
488
489    /// Record the session's unwrapped catalog list (done by `new_session`).
490    pub(crate) fn set_catalogs(&self, catalogs: Arc<dyn CatalogProviderList>) {
491        let _ = self.catalogs.set(catalogs);
492    }
493
494    pub(crate) fn catalogs(&self) -> Option<&Arc<dyn CatalogProviderList>> {
495        self.catalogs.get()
496    }
497
498    /// Mark the graph called `name` unavailable: it could not be defined when
499    /// the database was opened, and `message` says why. Using it fails with
500    /// `message` until it is dropped or replaced.
501    pub fn mark_unavailable(&self, name: &str, message: impl Into<String>) {
502        self.unavailable
503            .write()
504            .unwrap_or_else(|e| e.into_inner())
505            .insert(name.to_string(), message.into());
506    }
507
508    /// Why the graph called `name` is unavailable, if it is.
509    pub fn unavailable(&self, name: &str) -> Option<String> {
510        self.unavailable
511            .read()
512            .unwrap_or_else(|e| e.into_inner())
513            .get(name)
514            .cloned()
515    }
516
517    /// Forget that the graph called `name` is unavailable (it was dropped or
518    /// replaced); whether it was.
519    pub fn clear_unavailable(&self, name: &str) -> bool {
520        self.unavailable
521            .write()
522            .unwrap_or_else(|e| e.into_inner())
523            .remove(name)
524            .is_some()
525    }
526
527    /// The names of all graphs, sorted: for "did you mean" suggestions.
528    pub fn names(&self) -> Vec<String> {
529        self.graphs
530            .read()
531            .unwrap_or_else(|e| e.into_inner())
532            .keys()
533            .cloned()
534            .collect()
535    }
536}
537
538/// Install an empty registry on `config` (done by `new_session`).
539pub(crate) fn with_registry(config: SessionConfig) -> SessionConfig {
540    config.with_extension(Arc::new(GraphRegistry::default()))
541}
542
543/// The session's graph registry.
544pub fn registry(state: &SessionState) -> Arc<GraphRegistry> {
545    state
546        .config()
547        .get_extension::<GraphRegistry>()
548        .expect("an Ursa session has a graph registry (built by ursa_engine::new_session)")
549}
550
551/// The graph registry of `ctx`.
552pub fn registry_of(ctx: &SessionContext) -> Arc<GraphRegistry> {
553    registry(&ctx.state())
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    #[test]
561    fn a_session_has_an_empty_registry() {
562        let ctx = crate::new_session();
563        let graphs = registry_of(&ctx);
564        assert!(graphs.all().is_empty());
565        graphs.put(PropertyGraph {
566            name: "g".into(),
567            vertex_tables: Vec::new(),
568            edge_tables: vec![EdgeTable::new(TableReference::bare("e"), "a", "b")],
569        });
570        // The registry is shared by every handle on the session.
571        assert_eq!(registry_of(&ctx).names(), vec!["g".to_string()]);
572    }
573}