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