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