1use 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
57pub const EDGES: &str = "edges";
59pub const NODES: &str = "nodes";
61pub const ID: &str = "id";
63
64#[derive(Debug)]
66pub struct GraphSchema {
67 graph: String,
68 session: Weak<RwLock<SessionState>>,
69 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 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 fn has_tables(&self) -> bool {
91 self.graph()
92 .is_some_and(|(_, graph)| graph.default_pair().is_some())
93 }
94
95 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 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#[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
196pub 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
209pub 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
220pub 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
231pub 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
237pub fn edges_plan_from(def: &GraphDef, edges: Arc<dyn TableSource>) -> Result<LogicalPlan> {
239 LogicalPlanBuilder::scan(def.edges.table.clone(), edges, None)?.build()
240}
241
242pub 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
254pub 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 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 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 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
329fn 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 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 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}