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, 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 relation;
71mod session;
72pub mod traversal;
73
74pub use catalog_table::UrsaFunctions;
75pub use exec::{
76 GraphAlgorithmExec, GraphPlanner, GraphTraversalExec, KeepEdgeOrder, UrsaQueryPlanner,
77};
78pub use index::{
79 index_builds, index_loads, BuildInfo, BuildSize, FileIdentity, GraphIndex, IndexCache,
80 IndexHeld, Weights,
81};
82pub use node::{GraphAlgorithmNode, GraphTraversalNode, Output};
83pub(crate) use session::{edge_order_rule, query_planner, register_functions, with_algorithms};
84
85#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct PropertyGraph {
92 pub name: String,
95 pub vertex_tables: Vec<VertexTable>,
96 pub edge_tables: Vec<EdgeTable>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct GraphDef {
104 pub name: String,
106 pub edges: EdgeTable,
107 pub vertices: Option<VertexTable>,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct EdgeTable {
114 pub name: String,
116 pub table: TableReference,
117 pub source: String,
119 pub destination: String,
121 pub source_vertex: Option<String>,
123 pub destination_vertex: Option<String>,
125 pub labels: Vec<Label>,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct VertexTable {
131 pub name: String,
133 pub table: TableReference,
134 pub key: String,
136 pub labels: Vec<Label>,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Label {
142 pub name: String,
143 pub properties: Properties,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum Properties {
149 AllColumns { except: Vec<String> },
152 Columns(Vec<(String, String)>),
154 None,
156}
157
158impl Label {
159 pub fn default_for(element: &str) -> Self {
161 Label {
162 name: element.to_string(),
163 properties: Properties::AllColumns { except: Vec::new() },
164 }
165 }
166}
167
168fn labels_or_default<'a>(labels: &'a [Label], name: &str) -> std::borrow::Cow<'a, [Label]> {
170 if labels.is_empty() {
171 std::borrow::Cow::Owned(vec![Label::default_for(name)])
172 } else {
173 std::borrow::Cow::Borrowed(labels)
174 }
175}
176
177impl VertexTable {
178 pub fn new(table: impl Into<TableReference>, key: impl Into<String>) -> Self {
180 let table = table.into();
181 VertexTable {
182 name: table.table().to_string(),
183 table,
184 key: key.into(),
185 labels: Vec::new(),
186 }
187 }
188
189 pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
191 labels_or_default(&self.labels, &self.name)
192 }
193
194 pub fn answers_to(&self, label: &str) -> bool {
196 self.name.eq_ignore_ascii_case(label)
197 || self
198 .labels
199 .iter()
200 .any(|l| l.name.eq_ignore_ascii_case(label))
201 }
202}
203
204impl EdgeTable {
205 pub fn new(
208 table: impl Into<TableReference>,
209 source: impl Into<String>,
210 destination: impl Into<String>,
211 ) -> Self {
212 let table = table.into();
213 EdgeTable {
214 name: table.table().to_string(),
215 table,
216 source: source.into(),
217 destination: destination.into(),
218 source_vertex: None,
219 destination_vertex: None,
220 labels: Vec::new(),
221 }
222 }
223
224 pub fn labels(&self) -> std::borrow::Cow<'_, [Label]> {
226 labels_or_default(&self.labels, &self.name)
227 }
228
229 pub fn answers_to(&self, label: &str) -> bool {
231 self.name.eq_ignore_ascii_case(label)
232 || self
233 .labels
234 .iter()
235 .any(|l| l.name.eq_ignore_ascii_case(label))
236 }
237}
238
239impl From<GraphDef> for PropertyGraph {
241 fn from(def: GraphDef) -> Self {
242 PropertyGraph {
243 name: def.name,
244 vertex_tables: def.vertices.into_iter().collect(),
245 edge_tables: vec![def.edges],
246 }
247 }
248}
249
250impl PropertyGraph {
251 pub fn tables(&self) -> impl Iterator<Item = &TableReference> {
253 self.vertex_tables
254 .iter()
255 .map(|v| &v.table)
256 .chain(self.edge_tables.iter().map(|e| &e.table))
257 }
258
259 pub fn vertex_table(&self, label: &str) -> Option<&VertexTable> {
261 self.vertex_tables
262 .iter()
263 .find(|v| v.name.eq_ignore_ascii_case(label))
264 .or_else(|| self.vertex_tables.iter().find(|v| v.answers_to(label)))
265 }
266
267 pub fn edge_table(&self, label: &str) -> Option<&EdgeTable> {
269 self.edge_tables
270 .iter()
271 .find(|e| e.name.eq_ignore_ascii_case(label))
272 .or_else(|| self.edge_tables.iter().find(|e| e.answers_to(label)))
273 }
274
275 pub fn endpoint_vertex(&self, edge: &EdgeTable, source: bool) -> Option<&VertexTable> {
278 let named = if source {
279 &edge.source_vertex
280 } else {
281 &edge.destination_vertex
282 };
283 match named {
284 Some(name) => self.vertex_tables.iter().find(|v| &v.name == name),
285 None if self.vertex_tables.len() == 1 => self.vertex_tables.first(),
286 None => None,
287 }
288 }
289
290 pub fn pair(
295 &self,
296 vertex: Option<&str>,
297 edge: Option<&str>,
298 ) -> datafusion::error::Result<GraphDef> {
299 use datafusion::error::DataFusionError;
300 let plan_err = |m: String| Err(DataFusionError::Plan(m));
301 let edges = match edge {
302 Some(label) => match self.edge_table(label) {
303 Some(e) => e,
304 None => {
305 let names: Vec<&str> =
306 self.edge_tables.iter().map(|e| e.name.as_str()).collect();
307 return plan_err(format!(
308 "graph '{}' has no edge table '{label}'; its edge tables are {}",
309 self.name,
310 if names.is_empty() {
311 "none".to_string()
312 } else {
313 names.join(", ")
314 }
315 ));
316 }
317 },
318 None => match self.edge_tables.as_slice() {
319 [only] => only,
320 [] => {
321 return plan_err(format!(
322 "graph '{}' has no edge tables, so there is nothing for an algorithm to \
323 run on",
324 self.name
325 ))
326 }
327 several => {
328 let names: Vec<&str> = several.iter().map(|e| e.name.as_str()).collect();
329 return plan_err(format!(
330 "graph '{}' has {} edge tables ({}); name the vertex and edge table to \
331 run on, as in pagerank({}, <vertex table>, <edge table>)",
332 self.name,
333 several.len(),
334 names.join(", "),
335 self.name
336 ));
337 }
338 },
339 };
340 let source = self.endpoint_vertex(edges, true);
341 let destination = self.endpoint_vertex(edges, false);
342 if let (Some(s), Some(d)) = (source, destination) {
343 if s.name != d.name {
344 return plan_err(format!(
345 "edge table '{}' of graph '{}' goes from vertex table '{}' to '{}'; an \
346 algorithm runs on edges between one vertex table",
347 edges.name, self.name, s.name, d.name
348 ));
349 }
350 }
351 let vertices = source.or(destination);
352 if let Some(label) = vertex {
353 let Some(asked) = self.vertex_table(label) else {
354 let names: Vec<&str> = self.vertex_tables.iter().map(|v| v.name.as_str()).collect();
355 return plan_err(format!(
356 "graph '{}' has no vertex table '{label}'; its vertex tables are {}",
357 self.name,
358 if names.is_empty() {
359 "none".to_string()
360 } else {
361 names.join(", ")
362 }
363 ));
364 };
365 if vertices.is_some_and(|v| v.name != asked.name) {
366 return plan_err(format!(
367 "edge table '{}' of graph '{}' connects vertex table '{}', not '{}'",
368 edges.name,
369 self.name,
370 vertices.map(|v| v.name.as_str()).unwrap_or_default(),
371 asked.name
372 ));
373 }
374 return Ok(GraphDef {
375 name: self.name.clone(),
376 edges: edges.clone(),
377 vertices: Some(asked.clone()),
378 });
379 }
380 Ok(GraphDef {
381 name: self.name.clone(),
382 edges: edges.clone(),
383 vertices: vertices.cloned(),
384 })
385 }
386
387 pub fn default_pair(&self) -> Option<GraphDef> {
390 if self.vertex_tables.len() > 1 {
391 return None;
392 }
393 self.pair(None, None).ok()
394 }
395}
396
397#[derive(Debug, Clone)]
399pub struct FileTable {
400 pub table: TableReference,
402 pub provider: Arc<dyn TableProvider>,
403}
404
405#[derive(Debug, Default)]
408pub struct GraphRegistry {
409 graphs: RwLock<BTreeMap<String, Arc<PropertyGraph>>>,
410 files: RwLock<BTreeMap<String, Vec<FileTable>>>,
412 catalogs: OnceLock<Arc<dyn CatalogProviderList>>,
415}
416
417impl GraphRegistry {
418 pub fn get(&self, name: &str) -> Option<Arc<PropertyGraph>> {
420 self.graphs
421 .read()
422 .unwrap_or_else(|e| e.into_inner())
423 .get(name)
424 .cloned()
425 }
426
427 pub fn all(&self) -> Vec<Arc<PropertyGraph>> {
429 self.graphs
430 .read()
431 .unwrap_or_else(|e| e.into_inner())
432 .values()
433 .cloned()
434 .collect()
435 }
436
437 pub fn put(&self, def: impl Into<PropertyGraph>) -> Option<Arc<PropertyGraph>> {
439 self.put_with_files(def.into(), Vec::new())
440 }
441
442 pub fn put_with_files(
444 &self,
445 def: PropertyGraph,
446 files: Vec<FileTable>,
447 ) -> Option<Arc<PropertyGraph>> {
448 let mut graphs = self.graphs.write().unwrap_or_else(|e| e.into_inner());
449 let mut all_files = self.files.write().unwrap_or_else(|e| e.into_inner());
450 if files.is_empty() {
451 all_files.remove(&def.name);
452 } else {
453 all_files.insert(def.name.clone(), files);
454 }
455 graphs.insert(def.name.clone(), Arc::new(def))
456 }
457
458 pub fn remove(&self, name: &str) -> Option<Arc<PropertyGraph>> {
460 let mut graphs = self.graphs.write().unwrap_or_else(|e| e.into_inner());
461 self.files
462 .write()
463 .unwrap_or_else(|e| e.into_inner())
464 .remove(name);
465 graphs.remove(name)
466 }
467
468 pub fn file_table(
471 &self,
472 graph: &str,
473 table: &TableReference,
474 ) -> Option<Arc<dyn TableProvider>> {
475 self.files
476 .read()
477 .unwrap_or_else(|e| e.into_inner())
478 .get(graph)?
479 .iter()
480 .find(|f| &f.table == table)
481 .map(|f| Arc::clone(&f.provider))
482 }
483
484 pub(crate) fn set_catalogs(&self, catalogs: Arc<dyn CatalogProviderList>) {
486 let _ = self.catalogs.set(catalogs);
487 }
488
489 pub(crate) fn catalogs(&self) -> Option<&Arc<dyn CatalogProviderList>> {
490 self.catalogs.get()
491 }
492
493 pub fn names(&self) -> Vec<String> {
495 self.graphs
496 .read()
497 .unwrap_or_else(|e| e.into_inner())
498 .keys()
499 .cloned()
500 .collect()
501 }
502}
503
504pub(crate) fn with_registry(config: SessionConfig) -> SessionConfig {
506 config.with_extension(Arc::new(GraphRegistry::default()))
507}
508
509pub fn registry(state: &SessionState) -> Arc<GraphRegistry> {
511 state
512 .config()
513 .get_extension::<GraphRegistry>()
514 .expect("an Ursa session has a graph registry (built by ursa_engine::new_session)")
515}
516
517pub fn registry_of(ctx: &SessionContext) -> Arc<GraphRegistry> {
519 registry(&ctx.state())
520}
521
522#[cfg(test)]
523mod tests {
524 use super::*;
525
526 #[test]
527 fn a_session_has_an_empty_registry() {
528 let ctx = crate::new_session();
529 let graphs = registry_of(&ctx);
530 assert!(graphs.all().is_empty());
531 graphs.put(PropertyGraph {
532 name: "g".into(),
533 vertex_tables: Vec::new(),
534 edge_tables: vec![EdgeTable::new(TableReference::bare("e"), "a", "b")],
535 });
536 assert_eq!(registry_of(&ctx).names(), vec!["g".to_string()]);
538 }
539}