1use 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#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct PropertyGraph {
101 pub name: String,
104 pub vertex_tables: Vec<VertexTable>,
105 pub edge_tables: Vec<EdgeTable>,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct GraphDef {
113 pub name: String,
115 pub edges: EdgeTable,
116 pub vertices: Option<VertexTable>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct EdgeTable {
123 pub name: String,
125 pub table: TableReference,
126 pub source: String,
128 pub destination: String,
130 pub source_vertex: Option<String>,
132 pub destination_vertex: Option<String>,
134 pub labels: Vec<Label>,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct VertexTable {
140 pub name: String,
142 pub table: TableReference,
143 pub key: String,
145 pub labels: Vec<Label>,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct Label {
151 pub name: String,
152 pub properties: Properties,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
157pub enum Properties {
158 AllColumns { except: Vec<String> },
161 Columns(Vec<(String, String)>),
163 None,
165}
166
167impl Label {
168 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
177fn 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 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 pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
200 labels_or_default(&self.labels, &self.name)
201 }
202
203 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 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 pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
235 labels_or_default(&self.labels, &self.name)
236 }
237
238 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
248impl 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 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 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 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 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 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 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#[derive(Debug, Clone)]
408pub struct FileTable {
409 pub table: TableReference,
411 pub provider: Arc<dyn TableProvider>,
412}
413
414#[derive(Debug, Default)]
417pub struct GraphRegistry {
418 graphs: RwLock<BTreeMap<String, Arc<PropertyGraph>>>,
419 files: RwLock<BTreeMap<String, Vec<FileTable>>>,
421 catalogs: OnceLock<Arc<dyn CatalogProviderList>>,
424 unavailable: RwLock<BTreeMap<String, UnavailableGraph>>,
427}
428
429#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct UnavailableGraph {
433 pub name: String,
435 pub message: String,
437 pub definition: Option<GraphSpec>,
440}
441
442impl GraphRegistry {
443 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 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 pub fn put(&self, def: impl Into<PropertyGraph>) -> Option<Arc<PropertyGraph>> {
464 self.put_with_files(def.into(), Vec::new())
465 }
466
467 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 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 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 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 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 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 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 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 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
581pub(crate) fn with_registry(config: SessionConfig) -> SessionConfig {
583 config.with_extension(Arc::new(GraphRegistry::default()))
584}
585
586pub 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
594pub 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 assert_eq!(registry_of(&ctx).names(), vec!["g".to_string()]);
615 }
616}