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 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#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct PropertyGraph {
100 pub name: String,
103 pub vertex_tables: Vec<VertexTable>,
104 pub edge_tables: Vec<EdgeTable>,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct GraphDef {
112 pub name: String,
114 pub edges: EdgeTable,
115 pub vertices: Option<VertexTable>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct EdgeTable {
122 pub name: String,
124 pub table: TableReference,
125 pub source: String,
127 pub destination: String,
129 pub source_vertex: Option<String>,
131 pub destination_vertex: Option<String>,
133 pub labels: Vec<Label>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct VertexTable {
139 pub name: String,
141 pub table: TableReference,
142 pub key: String,
144 pub labels: Vec<Label>,
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Label {
150 pub name: String,
151 pub properties: Properties,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Properties {
157 AllColumns { except: Vec<String> },
160 Columns(Vec<(String, String)>),
162 None,
164}
165
166impl Label {
167 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
176fn 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 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 pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
199 labels_or_default(&self.labels, &self.name)
200 }
201
202 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 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 pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
234 labels_or_default(&self.labels, &self.name)
235 }
236
237 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
247impl 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 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 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 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 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 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 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#[derive(Debug, Clone)]
407pub struct FileTable {
408 pub table: TableReference,
410 pub provider: Arc<dyn TableProvider>,
411}
412
413#[derive(Debug, Default)]
416pub struct GraphRegistry {
417 graphs: RwLock<BTreeMap<String, Arc<PropertyGraph>>>,
418 files: RwLock<BTreeMap<String, Vec<FileTable>>>,
420 catalogs: OnceLock<Arc<dyn CatalogProviderList>>,
423 unavailable: RwLock<BTreeMap<String, UnavailableGraph>>,
426}
427
428#[derive(Debug, Clone, PartialEq, Eq)]
431pub struct UnavailableGraph {
432 pub name: String,
434 pub message: String,
436 pub definition: Option<GraphSpec>,
439}
440
441impl GraphRegistry {
442 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 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 pub fn put(&self, def: impl Into<PropertyGraph>) -> Option<Arc<PropertyGraph>> {
463 self.put_with_files(def.into(), Vec::new())
464 }
465
466 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 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 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 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 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 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 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 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 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
580pub(crate) fn with_registry(config: SessionConfig) -> SessionConfig {
582 config.with_extension(Arc::new(GraphRegistry::default()))
583}
584
585pub 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
593pub 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 assert_eq!(registry_of(&ctx).names(), vec!["g".to_string()]);
614 }
615}