Skip to main content

ursa_engine/graph/
schema.rs

1//! A graph as a schema: `<graph>.edges` and `<graph>.nodes`.
2//!
3//! Each graph registers a [`GraphSchema`] in the default catalog under its
4//! name. Its two tables are views ([`ViewTable`]s) whose plans are built from
5//! the graph's implied pair ([`PropertyGraph::default_pair`]: its edge table
6//! and the vertex table that edge table refers to) every time a query names
7//! them, so they always read the current contents of the tables (and files)
8//! the graph is defined over. A graph with several vertex or edge tables has no
9//! implied pair, and so no `nodes` or `edges` table: its element tables are
10//! session tables already, and `MATCH` reads across them.
11//!
12//! - `edges` is the edge table: every row and column, unchanged.
13//! - `nodes` is one row per node, the node id in a column named `id`:
14//!   - without a vertex table, the distinct non-null endpoints (`source` and
15//!     `destination` values) of the edges;
16//!   - with one, every row of the vertex table (its key renamed to `id`,
17//!     followed by its other columns), and nothing else: the vertex table
18//!     defines the node set, as in SQL/PGQ and DuckPGQ, and an edge whose
19//!     source or destination is not one of its keys is dropped by the
20//!     algorithms (#311). When the key and the endpoints have different types
21//!     (`Int32` and `Int64`, `Utf8` and a dictionary), `id` has their common
22//!     type, a dictionary as its values.
23//!
24//! The plan builders ([`edges_plan`], [`nodes_plan`] and their `_from`
25//! variants, which take table sources already resolved) are public so the graph
26//! algorithms can reuse them.
27//!
28//! A graph of the database that could not be defined when it was opened
29//! (#381) keeps its schema: its `edges` and `nodes` fail with why (#401).
30//!
31//! When a table under the graph cannot be read (it was deregistered through
32//! the DataFusion API, say), `edges` and `nodes` are still listed, with the
33//! columns they last had, and fail with the reason when a query reads them.
34//! Session listings (`SHOW TABLES`, `information_schema`) look every table up,
35//! so an error here would break them for the whole session.
36
37use std::collections::HashMap;
38use std::sync::{Arc, Mutex, Weak};
39
40use async_trait::async_trait;
41use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef};
42use datafusion::catalog::default_table_source::source_as_provider;
43use datafusion::catalog::{SchemaProvider, Session, TableProvider};
44use datafusion::common::{Column, TableReference};
45use datafusion::datasource::{provider_as_source, TableType, ViewTable};
46use datafusion::error::{DataFusionError, Result};
47use datafusion::execution::context::SessionState;
48use datafusion::logical_expr::expr_fn::cast;
49use datafusion::logical_expr::type_coercion::binary::comparison_coercion;
50use datafusion::logical_expr::{col, Expr, LogicalPlan, LogicalPlanBuilder, TableSource};
51use datafusion::physical_plan::ExecutionPlan;
52use parking_lot::RwLock;
53
54use super::{registry, GraphDef, PropertyGraph};
55use crate::database::UnavailableTable;
56
57/// The name of a graph's edge table in its schema.
58pub const EDGES: &str = "edges";
59/// The name of a graph's node table in its schema.
60pub const NODES: &str = "nodes";
61/// The node id column of `<graph>.nodes`.
62pub const ID: &str = "id";
63
64/// The schema of one graph: its `edges` and `nodes` tables.
65#[derive(Debug)]
66pub struct GraphSchema {
67    graph: String,
68    session: Weak<RwLock<SessionState>>,
69    /// The columns `edges` and `nodes` had when last planned.
70    last_columns: Mutex<HashMap<&'static str, SchemaRef>>,
71}
72
73impl GraphSchema {
74    pub(crate) fn new(graph: String, session: Weak<RwLock<SessionState>>) -> Self {
75        Self {
76            graph,
77            session,
78            last_columns: Mutex::default(),
79        }
80    }
81
82    /// The graph, if the session and the graph still exist.
83    fn graph(&self) -> Option<(SessionState, std::sync::Arc<PropertyGraph>)> {
84        let state = self.session.upgrade()?.read().clone();
85        let graph = registry(&state).get(&self.graph)?;
86        Some((state, graph))
87    }
88
89    /// Whether the graph has `nodes` and `edges` tables (an implied pair).
90    fn has_tables(&self) -> bool {
91        self.graph()
92            .is_some_and(|(_, graph)| graph.default_pair().is_some())
93    }
94
95    /// Why the graph is unavailable, if it is: the database's graph that
96    /// could not be defined when it was opened (#381).
97    fn unavailable(&self) -> Option<String> {
98        let state = self.session.upgrade()?.read().clone();
99        registry(&state).unavailable(&self.graph)
100    }
101}
102
103#[async_trait]
104impl SchemaProvider for GraphSchema {
105    fn table_names(&self) -> Vec<String> {
106        if self.has_tables() {
107            vec![EDGES.to_string(), NODES.to_string()]
108        } else {
109            Vec::new()
110        }
111    }
112
113    async fn table(&self, name: &str) -> Result<Option<Arc<dyn TableProvider>>> {
114        let name = match name {
115            EDGES => EDGES,
116            NODES => NODES,
117            _ => return Ok(None),
118        };
119        let state = self
120            .session
121            .upgrade()
122            .map(|state| state.read().clone())
123            .ok_or_else(|| DataFusionError::Internal("the session has been dropped".into()))?;
124        let graphs = registry(&state);
125        let Some(def) = graphs
126            .get(&self.graph)
127            .and_then(|graph| graph.default_pair())
128        else {
129            // An unavailable graph's tables fail with why, as its functions
130            // do (#401); they are not listed, since its definition is not
131            // known.
132            return Ok(graphs.unavailable(&self.graph).map(|why| {
133                Arc::new(UnavailableTable::new(why, TableType::View)) as Arc<dyn TableProvider>
134            }));
135        };
136        let plan = if name == EDGES {
137            edges_plan(&state, &def).await
138        } else {
139            nodes_plan(&state, &def).await
140        };
141        let mut last_columns = self.last_columns.lock().unwrap_or_else(|e| e.into_inner());
142        match plan {
143            Ok(plan) => {
144                let view = ViewTable::new(plan, None);
145                last_columns.insert(name, view.schema());
146                Ok(Some(Arc::new(view)))
147            }
148            Err(e) => Ok(Some(Arc::new(UnreadableTable {
149                schema: last_columns
150                    .get(name)
151                    .cloned()
152                    .unwrap_or_else(|| Arc::new(Schema::empty())),
153                message: format!(
154                    "cannot read {}.{name}: {}",
155                    def.name,
156                    crate::user_message(&e)
157                ),
158            }))),
159        }
160    }
161
162    fn table_exist(&self, name: &str) -> bool {
163        (name == EDGES || name == NODES) && (self.has_tables() || self.unavailable().is_some())
164    }
165}
166
167/// A graph table whose plan cannot be built: listed with the columns it last
168/// had, and failing with `message` when a query reads it.
169#[derive(Debug)]
170struct UnreadableTable {
171    schema: SchemaRef,
172    message: String,
173}
174
175#[async_trait]
176impl TableProvider for UnreadableTable {
177    fn schema(&self) -> SchemaRef {
178        Arc::clone(&self.schema)
179    }
180
181    fn table_type(&self) -> TableType {
182        TableType::View
183    }
184
185    async fn scan(
186        &self,
187        _state: &dyn Session,
188        _projection: Option<&Vec<usize>>,
189        _filters: &[Expr],
190        _limit: Option<usize>,
191    ) -> Result<Arc<dyn ExecutionPlan>> {
192        Err(DataFusionError::Plan(self.message.clone()))
193    }
194}
195
196/// The table `table` names for the graph called `graph`: one the graph opened
197/// from a file path when it was created, or else the table or view in `state`.
198pub async fn graph_table(
199    state: &SessionState,
200    graph: &str,
201    table: &TableReference,
202) -> Result<Arc<dyn TableProvider>> {
203    match registry(state).file_table(graph, table) {
204        Some(provider) => Ok(provider),
205        None => resolve_table(state, table).await,
206    }
207}
208
209/// The table provider `table` names in `state`, or an error saying it does not
210/// exist.
211pub async fn resolve_table(
212    state: &SessionState,
213    table: &TableReference,
214) -> Result<Arc<dyn TableProvider>> {
215    lookup_table(state, table)
216        .await?
217        .ok_or_else(|| DataFusionError::Plan(format!("table '{table}' not found")))
218}
219
220/// The table provider `table` names in `state`, if there is one.
221pub async fn lookup_table(
222    state: &SessionState,
223    table: &TableReference,
224) -> Result<Option<Arc<dyn TableProvider>>> {
225    match state.schema_for_ref(table.clone()) {
226        Ok(schema) => schema.table(table.table()).await,
227        Err(_) => Ok(None),
228    }
229}
230
231/// The plan of `<graph>.edges`: a scan of the edge table, as it is now.
232pub async fn edges_plan(state: &SessionState, def: &GraphDef) -> Result<LogicalPlan> {
233    let edges = graph_table(state, &def.name, &def.edges.table).await?;
234    edges_plan_from(def, provider_as_source(edges))
235}
236
237/// [`edges_plan`], with the edge table's source already resolved.
238pub fn edges_plan_from(def: &GraphDef, edges: Arc<dyn TableSource>) -> Result<LogicalPlan> {
239    LogicalPlanBuilder::scan(def.edges.table.clone(), edges, None)?.build()
240}
241
242/// The plan of `<graph>.nodes` (see the module docs).
243pub async fn nodes_plan(state: &SessionState, def: &GraphDef) -> Result<LogicalPlan> {
244    let edges = provider_as_source(graph_table(state, &def.name, &def.edges.table).await?);
245    let vertices = match &def.vertices {
246        Some(v) => Some(provider_as_source(
247            graph_table(state, &def.name, &v.table).await?,
248        )),
249        None => None,
250    };
251    nodes_plan_from(def, edges, vertices)
252}
253
254/// [`nodes_plan`], with the tables' sources already resolved. `vertices` must
255/// be given when the graph has a vertex table.
256pub fn nodes_plan_from(
257    def: &GraphDef,
258    edges: Arc<dyn TableSource>,
259    vertices: Option<Arc<dyn TableSource>>,
260) -> Result<LogicalPlan> {
261    let endpoint_type = column_type(&edges.schema(), &def.edges.table, &def.edges.source)?;
262    let (vertex_def, vertices) = match (&def.vertices, vertices) {
263        (None, _) => {
264            return endpoints(def, &edges)?.build();
265        }
266        (Some(v), Some(source)) => (v, source),
267        (Some(v), None) => {
268            return Err(DataFusionError::Internal(format!(
269                "nodes_plan_from: graph {} has vertex table {} but no source was given for it",
270                def.name, v.table
271            )))
272        }
273    };
274
275    let vertex_schema = vertices.schema();
276    let key_type = column_type(&vertex_schema, &vertex_def.table, &vertex_def.key)?;
277    let id_type = comparison_coercion(&key_type, &endpoint_type).ok_or_else(|| {
278        DataFusionError::Plan(format!(
279            "the key of vertex table '{}' is {key_type} and the edge endpoints are \
280             {endpoint_type}; they cannot be compared",
281            vertex_def.table
282        ))
283    })?;
284    // The key and the endpoints differ (say Int32 and Int64): `id` takes their
285    // common type, a dictionary as its values.
286    let id_type = match (key_type == endpoint_type, id_type) {
287        (true, _) => key_type.clone(),
288        (false, DataType::Dictionary(_, values)) => *values,
289        (false, other) => other,
290    };
291
292    // The vertex table: `key AS id`, then its other columns.
293    let others: Vec<_> = vertex_schema
294        .fields()
295        .iter()
296        .filter(|f| f.name() != &vertex_def.key)
297        .cloned()
298        .collect();
299    let mut vertex_exprs = vec![cast_to(
300        Expr::Column(Column::new(Some(vertex_def.table.clone()), &vertex_def.key)),
301        &key_type,
302        &id_type,
303    )
304    .alias(ID)];
305    vertex_exprs.extend(
306        others
307            .iter()
308            .map(|f| Expr::Column(Column::new(Some(vertex_def.table.clone()), f.name()))),
309    );
310    // Only the vertex table's rows: an endpoint that is not one of its keys
311    // is no node, and its edges are dropped (#311). Each row is one node: a
312    // key that repeats or is NULL is refused, as an index build refuses it
313    // (#411).
314    let vertices = match source_as_provider(&vertices) {
315        Ok(provider) => provider_as_source(super::vertex_keys::unique_keys(
316            &def.name,
317            &vertex_def.name,
318            &vertex_def.table,
319            &vertex_def.key,
320            provider,
321        )),
322        Err(_) => vertices,
323    };
324    LogicalPlanBuilder::scan(vertex_def.table.clone(), vertices, None)?
325        .project(vertex_exprs)?
326        .build()
327}
328
329/// The distinct non-null endpoints of the edges, as one column `id`.
330fn endpoints(def: &GraphDef, edges: &Arc<dyn TableSource>) -> Result<LogicalPlanBuilder> {
331    let side = |column: &str| -> Result<LogicalPlan> {
332        LogicalPlanBuilder::scan(def.edges.table.clone(), Arc::clone(edges), None)?
333            .project(vec![Expr::Column(Column::new(
334                Some(def.edges.table.clone()),
335                column,
336            ))
337            .alias(ID)])?
338            .build()
339    };
340    LogicalPlanBuilder::from(side(&def.edges.source)?)
341        .union_distinct(side(&def.edges.destination)?)?
342        .filter(col(ID).is_not_null())
343}
344
345fn cast_to(expr: Expr, from: &DataType, to: &DataType) -> Expr {
346    if from == to {
347        expr
348    } else {
349        cast(expr, to.clone())
350    }
351}
352
353fn column_type(schema: &Schema, table: &TableReference, column: &str) -> Result<DataType> {
354    schema
355        .field_with_name(column)
356        .map(|f| f.data_type().clone())
357        .map_err(|_| {
358            DataFusionError::Plan(format!("column '{column}' not found in table '{table}'"))
359        })
360}
361
362#[cfg(test)]
363mod tests {
364    use datafusion::arrow::array::{DictionaryArray, Int64Array, RecordBatch, StringArray};
365    use datafusion::arrow::datatypes::Int32Type;
366    use datafusion::datasource::MemTable;
367
368    use super::*;
369    use crate::graph::{create_graph, drop_graph, EdgeTable, VertexTable};
370
371    fn table(batch: RecordBatch) -> Arc<MemTable> {
372        Arc::new(MemTable::try_new(batch.schema(), vec![vec![batch]]).unwrap())
373    }
374
375    #[tokio::test]
376    async fn dictionary_ids_and_a_vertex_table_without_every_node() {
377        let ctx = crate::new_session();
378        let ids = |values: Vec<&str>| -> Arc<dyn datafusion::arrow::array::Array> {
379            Arc::new(values.into_iter().collect::<DictionaryArray<Int32Type>>())
380        };
381        let edges = RecordBatch::try_from_iter(vec![
382            ("a", ids(vec!["x", "y", "z", "z"])),
383            ("b", ids(vec!["y", "z", "x", "w"])),
384        ])
385        .unwrap();
386        let people = RecordBatch::try_from_iter(vec![
387            (
388                "name",
389                Arc::new(StringArray::from(vec!["x", "y", "z"])) as _,
390            ),
391            ("age", Arc::new(Int64Array::from(vec![30, 40, 50])) as _),
392        ])
393        .unwrap();
394        ctx.register_table("follows", table(edges)).unwrap();
395        ctx.register_table("people", table(people)).unwrap();
396
397        let def = GraphDef {
398            name: "social".into(),
399            edges: EdgeTable::new(TableReference::bare("follows"), "a", "b"),
400            vertices: Some(VertexTable::new(TableReference::bare("people"), "name")),
401        };
402        create_graph(&ctx, def.clone(), false, false).await.unwrap();
403
404        // The plans the algorithms can reuse.
405        let state = ctx.state();
406        let edges = edges_plan(&state, &def).await.unwrap();
407        assert_eq!(edges.schema().fields().len(), 2);
408        let nodes = nodes_plan(&state, &def).await.unwrap();
409        let columns: Vec<_> = nodes
410            .schema()
411            .fields()
412            .iter()
413            .map(|f| (f.name().clone(), f.data_type().clone()))
414            .collect();
415        assert_eq!(
416            columns,
417            [
418                (ID.to_string(), DataType::Utf8),
419                ("age".to_string(), DataType::Int64)
420            ]
421        );
422
423        // The vertex table's rows only: 'w', an endpoint that is not a key,
424        // is no node (#311).
425        let batches = ctx
426            .sql("SELECT id, age FROM social.nodes ORDER BY id")
427            .await
428            .unwrap()
429            .collect()
430            .await
431            .unwrap();
432        let formatted = datafusion::arrow::util::pretty::pretty_format_batches(&batches)
433            .unwrap()
434            .to_string();
435        assert_eq!(
436            formatted,
437            "\
438+----+-----+
439| id | age |
440+----+-----+
441| x  | 30  |
442| y  | 40  |
443| z  | 50  |
444+----+-----+"
445        );
446
447        drop_graph(&ctx, "social", false).unwrap();
448        assert!(ctx.sql("SELECT * FROM social.nodes").await.is_err());
449    }
450}