1use std::sync::Arc;
52
53use async_trait::async_trait;
54use datafusion::arrow::array::{Array, AsArray, RecordBatch};
55use datafusion::arrow::compute::{cast, concat_batches};
56use datafusion::arrow::datatypes::{DataType, SchemaRef, UInt64Type};
57use datafusion::common::TableReference;
58use datafusion::dataframe::DataFrame;
59use datafusion::datasource::provider_as_source;
60use datafusion::error::{DataFusionError, Result};
61use datafusion::logical_expr::LogicalPlanBuilder;
62use datafusion::prelude::SessionContext;
63use ursa_viz::model::{
64 Column as ModelColumn, ColumnRole, EdgeBatch, Encodings, GraphDelta, GraphResult, Highlights,
65 KeyType, NodeBatch, NodeLabel, Op, Provenance, Role, Strings, Target, Values, NO_ROW, NULL,
66};
67
68use crate::graph::schema::graph_table;
69use crate::graph::{edges_plan, registry_of, GraphDef, PropertyGraph};
70
71mod build;
72pub mod clauses;
73pub mod find;
74pub mod groups;
75pub mod inspect;
76mod positions;
77pub mod rows;
78pub mod rules;
79pub mod session;
80mod style;
81
82#[cfg(test)]
83mod tests;
84
85use build::{build_within, EdgeList, NodeIndex};
86pub use clauses::{identifier, parse, As, Name, Style, USAGE};
87pub use groups::Grouping;
88pub use rules::Rule;
89use rules::{MatchEdge, Shape};
90pub use session::{Command, Outcome, Session, Step};
91use style::{
92 color_by, degree_column, resolve, run_algorithms, size_by, vertex_column, ColorBy, Found,
93 NodeValues,
94};
95pub use ursa_viz::model::Positions;
97
98pub const MAX_EDGES: usize = 5_000_000;
102pub const MAX_NODES: usize = 4_000_000;
104pub const MAX_CATEGORIES: usize = 8;
107
108pub const COLOR_SUFFIX: &str = " (colour)";
113pub const SIZE_SUFFIX: &str = " (size)";
116
117pub(crate) fn plan_err<T>(message: impl Into<String>) -> Result<T> {
118 Err(DataFusionError::Plan(message.into()))
119}
120
121pub type Rows = (SchemaRef, Vec<RecordBatch>);
123
124#[async_trait]
127pub trait RunSql: Send + Sync {
128 async fn run(&self, ctx: &SessionContext, text: &str) -> Result<Rows>;
129}
130
131#[derive(Debug, Clone, Copy, Default)]
135pub struct DataFusionSql;
136
137#[async_trait]
138impl RunSql for DataFusionSql {
139 async fn run(&self, ctx: &SessionContext, text: &str) -> Result<Rows> {
140 let frame = ctx.sql(text).await?;
141 let schema = Arc::new(frame.schema().as_arrow().clone());
142 Ok((schema, frame.collect().await?))
143 }
144}
145
146pub(crate) fn thousands(n: usize) -> String {
148 let digits = n.to_string();
149 let mut out = String::new();
150 for (i, c) in digits.chars().enumerate() {
151 if i > 0 && (digits.len() - i).is_multiple_of(3) {
152 out.push(',');
153 }
154 out.push(c);
155 }
156 out
157}
158
159pub(crate) fn raise_max_edges(edges: usize) -> String {
162 let limit = edges.div_ceil(1_000_000).max(1) * 1_000_000;
163 format!("SET ursa.graph_max_edges = {limit}")
164}
165
166pub enum Source {
168 Graph(Arc<PropertyGraph>),
169 Rows {
170 schema: SchemaRef,
171 batches: Vec<RecordBatch>,
172 sql: Option<String>,
174 },
175}
176
177impl Source {
178 pub async fn of_text(ctx: &SessionContext, sql: &dyn RunSql, text: &str) -> Result<Source> {
181 if let Some(name) = identifier(text) {
182 if let Some(graph) = registry_of(ctx).get(&name) {
183 return Ok(Source::Graph(graph));
184 }
185 let table = TableReference::bare(name.as_str());
186 if !ctx.table_exist(table.clone())? {
187 return plan_err(format!(
188 "no graph or table named '{name}'; .graphs lists the graphs and .tables the \
189 tables, or give a query: .graph SELECT src, dst FROM …"
190 ));
191 }
192 let frame = ctx.table(table).await?;
193 let schema = Arc::new(frame.schema().as_arrow().clone());
194 return Ok(Source::Rows {
195 schema,
196 batches: frame.collect().await?,
197 sql: Some(format!("SELECT * FROM {}", text.trim())),
198 });
199 }
200 let (schema, batches) = sql.run(ctx, text).await?;
201 Ok(Source::Rows {
202 schema,
203 batches,
204 sql: Some(text.trim().to_string()),
205 })
206 }
207
208 pub fn of_rows((schema, batches): Rows) -> Source {
210 Source::Rows {
211 schema,
212 batches,
213 sql: None,
214 }
215 }
216}
217
218#[derive(Debug, Clone, PartialEq)]
220pub struct GraphView {
221 pub result: GraphResult,
227 pub skipped: usize,
229 pub positions: Option<Positions>,
236 pub groups: Option<Grouping>,
240}
241
242impl GraphView {
243 pub fn placed(&self) -> GraphResult {
247 let mut result = self.result.clone();
248 if let Some(positions) = &self.positions {
249 let op = result.set_positions_op(Some(positions.clone()));
250 result
251 .apply(&GraphDelta::new(vec![op]))
252 .expect("a place per node");
253 }
254 result
255 }
256
257 pub fn legend(&self) -> Option<Legend> {
259 Legend::of(&self.result)
260 }
261
262 pub fn grouped_by(&self) -> Option<String> {
265 let groups = self.groups.as_ref()?;
266 groups::legend(&self.result, groups.by())
267 }
268
269 pub fn drawn_as(&self) -> String {
271 drawn_as(&self.result)
272 }
273}
274
275pub fn drawn_as(result: &GraphResult) -> String {
281 let provenance = result.provenance();
282 let Some(rule) = provenance.rule.as_deref() else {
283 return String::new();
284 };
285 let paths = result.highlights().paths.len();
286 let (what, joins) = match rule {
287 "graph" => ("the graph".to_string(), " "),
288 "edges" => ("edges".to_string(), " of "),
289 "path" if paths > 1 => (format!("{} paths", thousands(paths)), " on "),
290 "path" => ("a path".to_string(), " on "),
291 "rings" => ("rings".to_string(), " on "),
292 "pattern" => ("pattern matches".to_string(), " on "),
293 "nodes" => ("nodes".to_string(), " of "),
294 groups::RULE => ("groups".to_string(), " of "),
295 other => (other.to_string(), " on "),
296 };
297 let mut out = what;
298 if let Some(graph) = result.graph() {
299 out.push_str(joins);
300 out.push_str(graph);
301 }
302 if !provenance.roles.is_empty() {
303 let columns: Vec<&str> = provenance.roles.iter().map(|r| r.column.as_str()).collect();
304 out.push_str(&format!(" ({})", columns.join(", ")));
305 }
306 for note in &provenance.notes {
307 out.push_str(" · ");
308 out.push_str(note);
309 }
310 out
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct Legend {
317 pub by: String,
319 pub labels: Vec<String>,
322 pub counts: Vec<u32>,
324 pub other: u32,
326 pub missing: u32,
328}
329
330impl Legend {
331 pub fn of(result: &GraphResult) -> Option<Legend> {
334 let name = result.encodings().color_by.as_deref()?;
335 let Values::Dict { values, codes } = &result.node_column(name)?.values else {
336 return None;
337 };
338 let by = match name.strip_suffix(COLOR_SUFFIX) {
339 Some(by) if result.node_column(by).is_some() => by,
340 _ => name,
341 };
342 let top = values.len().min(MAX_CATEGORIES);
343 let mut legend = Legend {
344 by: by.to_string(),
345 labels: values.iter().take(top).map(str::to_string).collect(),
346 counts: vec![0; top],
347 other: 0,
348 missing: 0,
349 };
350 for &code in codes {
351 match code {
352 NULL => legend.missing += 1,
353 c if (c as usize) < top => legend.counts[c as usize] += 1,
354 _ => legend.other += 1,
355 }
356 }
357 Some(legend)
358 }
359}
360
361pub async fn of_command(
364 ctx: &SessionContext,
365 sql: &dyn RunSql,
366 text: &str,
367 last: Option<Rows>,
368) -> Result<GraphView> {
369 let (text, style) = parse(text)?;
370 let source = if !text.is_empty() {
371 Source::of_text(ctx, sql, &text).await?
372 } else {
373 let Some(rows) = last else {
374 return plan_err(
375 "no result to draw yet: run a query whose rows are edges (columns src and dst, \
376 or else the first two), then .graph; or .graph NAME for a property graph",
377 );
378 };
379 Source::of_rows(rows)
380 };
381 draw(ctx, sql, source, &style).await
382}
383
384pub async fn draw(
387 ctx: &SessionContext,
388 sql: &dyn RunSql,
389 source: Source,
390 style: &Style,
391) -> Result<GraphView> {
392 if let (Some(_), Some(layout)) = (&style.positions, style.layout) {
393 return plan_err(format!(
394 "POSITIONS (…) and LAYOUT {} both say where the nodes go; give one. POSITIONS \
395 draws the nodes where its query puts them, and no layout runs",
396 layout_name(layout)
397 ));
398 }
399 let max_edges = crate::options::graph_max_edges(ctx.state().config());
400 let (mut drawing, text) = match source {
401 Source::Graph(g) => {
402 if let Some(shape) = &style.shape {
404 return plan_err(format!(
405 "{} says how to read a result's rows, and '{}' is a property graph, drawn \
406 whole. Leave the clause out (.graph {}), or draw a query's rows: .graph \
407 SELECT … FROM … {}",
408 shape.shown(),
409 g.name,
410 g.name,
411 shape.shown()
412 ));
413 }
414 if let Some(on) = &style.on {
415 return plan_err(format!(
416 "ON {} names the graph a result's ids belong to, and '{}' is a property graph \
417 already. Leave the clause out (.graph {}), or draw a query's rows: .graph \
418 SELECT … FROM … ON {}",
419 on.shown, g.name, g.name, on.shown
420 ));
421 }
422 let (edges, index) = property_graph_indexed(ctx, &g, max_edges).await?;
423 (Drawing::of_graph(edges, index, g), None)
424 }
425 Source::Rows {
426 schema,
427 batches,
428 sql: text,
429 } => (
430 read_rows(ctx, sql, schema, batches, style, max_edges).await?,
431 text,
432 ),
433 };
434 if let Some(by) = &style.group {
435 return group(ctx, sql, drawing, style, by, text).await;
436 }
437 apply_style(ctx, sql, &mut drawing, style).await?;
438 if let Some(layout) = style.layout {
439 set_layout(&mut drawing, layout)?;
440 }
441 let saved = match &style.positions {
442 Some(query) => {
443 let saved = positions::saved(ctx, sql, query, &drawing.edges, &drawing.index).await?;
444 drawing.edges.layout = ursa_viz::model::Layout::Force;
447 drawing.notes.extend(saved.notes);
448 Some(saved.positions)
449 }
450 None => None,
451 };
452 let provenance = Provenance {
453 sql: text,
454 rule: Some(drawing.rule.name().to_string()),
455 roles: drawing
456 .roles
457 .iter()
458 .map(|(column, role)| ColumnRole::new(column, role))
459 .collect(),
460 notes: std::mem::take(&mut drawing.notes),
461 };
462 let graph = drawing.graph.as_ref().map(|g| g.name.clone());
463 let mut view = to_view(drawing.edges, &drawing.index.key_type, graph, provenance)?;
464 view.positions = saved;
465 Ok(view)
466}
467
468async fn group(
473 ctx: &SessionContext,
474 sql: &dyn RunSql,
475 mut drawing: Drawing,
476 style: &Style,
477 by: &Name,
478 text: Option<String>,
479) -> Result<GraphView> {
480 let shown = &by.shown;
481 for (clause, given) in [
482 ("SIZE BY", style.size.as_ref().map(|n| n.shown.clone())),
483 ("COLOR BY", style.color.as_ref().map(|n| n.shown.clone())),
484 (
485 "LAYOUT",
486 style.layout.map(|layout| layout_name(layout).to_string()),
487 ),
488 (
489 "POSITIONS",
490 style.positions.as_ref().map(|_| "(…)".to_string()),
491 ),
492 ] {
493 if let Some(given) = given {
494 let why = match clause {
495 "SIZE BY" => "a group's disc is sized by how many members it has",
496 "COLOR BY" => "a group's disc takes its group's colour",
497 _ => "the groups are laid out by the edges between them",
498 };
499 return plan_err(format!(
500 "GROUP BY {shown} draws a disc for each group, and {clause} {given} is of the \
501 nodes: {why}. Leave {clause} out, or GROUP BY"
502 ));
503 }
504 }
505 let graph = drawing.graph.clone();
506 let graph = graph.as_deref();
507 let nodes = match &style.nodes {
508 Some(query) => Some(NodeValues::of_query(ctx, sql, query).await?),
509 None => None,
510 };
511 let own = drawing.own.as_ref();
512 let found = resolve(ctx, graph, nodes.as_ref(), own, "GROUP BY", by).await?;
513 let column = match found {
514 Found::Nodes(i) => nodes.as_ref().expect("NODES was given").column(i),
515 Found::Own(i) => own.expect("the result's rows").column(i),
516 Found::Vertex => vertex_column(ctx, graph.expect("a graph"), &by.ident).await?,
517 Found::Algorithm(algorithm) => {
518 let graph = graph.expect("an algorithm has a graph");
519 run_algorithms(ctx, sql, graph, &[algorithm])
520 .await?
521 .column_named(algorithm)
522 }
523 Found::Degree => degree_column(&drawing.edges),
524 };
525 let values = column.per_node(&drawing.index, drawing.edges.n as usize)?;
526 let provenance = Provenance {
527 sql: text,
528 rule: None,
529 roles: drawing
530 .roles
531 .iter()
532 .map(|(column, role)| ColumnRole::new(column, role))
533 .collect(),
534 notes: std::mem::take(&mut drawing.notes),
535 };
536 groups::grouped(
537 drawing.edges,
538 &drawing.index.key_type,
539 graph.map(|g| g.name.clone()),
540 provenance,
541 shown,
542 &values,
543 )
544}
545
546fn layout_name(layout: ursa_viz::model::Layout) -> &'static str {
547 use ursa_viz::model::Layout;
548 match layout {
549 Layout::Force => "force",
550 Layout::Rings => "rings",
551 Layout::Layers => "layers",
552 }
553}
554
555pub async fn interpret(
563 ctx: &SessionContext,
564 sql: &dyn RunSql,
565 schema: SchemaRef,
566 batches: Vec<RecordBatch>,
567) -> Result<GraphView> {
568 interpret_with(ctx, sql, schema, batches, &Style::default()).await
569}
570
571pub async fn interpret_with(
575 ctx: &SessionContext,
576 sql: &dyn RunSql,
577 schema: SchemaRef,
578 batches: Vec<RecordBatch>,
579 style: &Style,
580) -> Result<GraphView> {
581 let source = Source::of_rows((schema, batches));
582 draw(ctx, sql, source, style).await
583}
584
585fn set_layout(drawing: &mut Drawing, layout: ursa_viz::model::Layout) -> Result<()> {
589 use ursa_viz::model::Layout;
590 let name = layout_name(layout);
591 if layout != Layout::Force && drawing.edges.level.is_none() {
592 let what = match drawing.rule {
593 Rule::Graph => "a property graph",
594 Rule::Edges => "edges",
595 Rule::Matches => "pattern matches",
596 Rule::Nodes => "nodes",
597 Rule::Path | Rule::Rings => "this drawing",
598 };
599 return plan_err(format!(
600 "LAYOUT {name} places each node by its distance from a seed or its step along a path, \
601 and {what} {} neither. Draw a hop result or paths (.graph SELECT * FROM hop(g, seeds \
602 => [1], steps => 2) LAYOUT {name}), say which columns are one (AS hops(seed, id, \
603 distance)), or use LAYOUT force",
604 if what == "this drawing" || what == "a property graph" {
605 "has"
606 } else {
607 "have"
608 }
609 ));
610 }
611 drawing.edges.layout = layout;
612 Ok(())
613}
614
615struct Drawing {
618 edges: EdgeList,
619 index: NodeIndex,
620 rule: Rule,
621 graph: Option<Arc<PropertyGraph>>,
623 own: Option<NodeValues>,
625 size: Option<Name>,
627 color: Option<Name>,
628 roles: Vec<(String, String)>,
629 notes: Vec<String>,
630}
631
632impl Drawing {
633 fn of_graph(edges: EdgeList, index: NodeIndex, graph: Arc<PropertyGraph>) -> Drawing {
634 Drawing {
635 edges,
636 index,
637 rule: Rule::Graph,
638 graph: Some(graph),
639 own: None,
640 size: None,
641 color: None,
642 roles: Vec::new(),
643 notes: Vec::new(),
644 }
645 }
646}
647
648fn graph_of(
652 ctx: &SessionContext,
653 reading: &rules::Reading,
654 on: Option<&Name>,
655 or_the_only: bool,
656 notes: &mut Vec<String>,
657) -> Result<Option<Arc<PropertyGraph>>> {
658 let registry = registry_of(ctx);
659 if let Some(on) = on {
660 let Some(found) = registry.get(&on.ident) else {
661 let mut names: Vec<String> = registry.all().iter().map(|g| g.name.clone()).collect();
662 names.sort();
663 return plan_err(format!(
664 "ON {}: there is no property graph named '{}'. {}",
665 on.shown,
666 on.ident,
667 if names.is_empty() {
668 "This session has none: make one with CREATE PROPERTY GRAPH, or leave the \
669 clause out"
670 .to_string()
671 } else {
672 format!("The graphs are {}; name one of them", names.join(", "))
673 }
674 ));
675 };
676 if let Some(theirs) = reading.graph.as_deref().filter(|g| *g != found.name) {
677 notes.push(format!(
678 "read on {} as ON says; the columns are from {theirs}",
679 found.name
680 ));
681 }
682 return Ok(Some(found));
683 }
684 Ok(graph_of_columns(®istry, reading, or_the_only, notes))
685}
686
687fn graph_of_columns(
688 registry: &crate::graph::GraphRegistry,
689 reading: &rules::Reading,
690 or_the_only: bool,
691 notes: &mut Vec<String>,
692) -> Option<Arc<PropertyGraph>> {
693 if let Some(name) = &reading.graph {
694 let found = registry.get(name);
695 if found.is_none() {
696 notes.push(format!("the graph '{name}' is not in this session"));
697 }
698 return found;
699 }
700 let mut all = registry.all();
701 match (or_the_only, all.len()) {
702 (true, 1) => all.pop(),
703 _ => None,
704 }
705}
706
707async fn read_rows(
709 ctx: &SessionContext,
710 sql: &dyn RunSql,
711 schema: SchemaRef,
712 batches: Vec<RecordBatch>,
713 style: &Style,
714 max_edges: usize,
715) -> Result<Drawing> {
716 let reading = match &style.shape {
718 Some(shape) => rules::read_as(&schema, shape, style.on.is_some())?,
719 None => rules::read(&schema)?,
720 };
721 let mut notes = reading.notes.clone();
722 let name = |column: usize| schema.field(column).name().as_str();
723 let whole = || concat_batches(&schema, &batches);
725 let label_names = |keys: &[usize]| -> (Vec<String>, Vec<u16>) {
726 let mut labels: Vec<String> = Vec::new();
727 let of_key = keys
728 .iter()
729 .map(|&k| {
730 let label = reading.label_of(k).unwrap_or("");
731 let at = labels.iter().position(|l| l == label).unwrap_or_else(|| {
732 labels.push(label.to_string());
733 labels.len() - 1
734 });
735 at as u16
736 })
737 .collect();
738 (labels, of_key)
739 };
740 let mut own = None;
741 let (mut size, mut color) = (None, None);
742 let mut graph = graph_of(
743 ctx,
744 &reading,
745 style.on.as_ref(),
746 matches!(reading.shape, Shape::Hop { .. } | Shape::Nodes { .. }),
747 &mut notes,
748 )?;
749 let guessed = reading.graph.is_none() && style.on.is_none();
752 let mut key_labels: Vec<(usize, u16)> = Vec::new();
754 let (mut edges, index) = match &reading.shape {
755 Shape::Edges { src, dst } => {
756 let (labels, of_key) = label_names(&[*src, *dst]);
757 if labels.len() > 1 {
758 let batch = whole()?;
760 key_labels = vec![(*src, of_key[0]), (*dst, of_key[1])];
761 let edge = MatchEdge {
762 from: 0,
763 to: 1,
764 directed: true,
765 label: reading.edge_label.clone().unwrap_or_default(),
766 };
767 build::matches_of(&batch, &key_labels, &labels, &[edge], max_edges)?
768 } else {
769 let (mut edges, index) = build::edges_of(&batches, *src, *dst, max_edges)?;
770 if reading.marked {
771 edges.labels = labels;
772 edges.edge_labels = reading.edge_label.iter().cloned().collect();
773 }
774 if !reading.attributes.is_empty() {
775 let batch = whole()?;
776 let (s, d) = (batch.column(*src), batch.column(*dst));
777 let kept: Vec<usize> = (0..batch.num_rows())
778 .filter(|&i| s.is_valid(i) && d.is_valid(i))
779 .collect();
780 for &a in &reading.attributes {
781 let role = meta_role(&schema, a);
782 edges.edge_columns.push(build::edge_attribute(
783 name(a),
784 role,
785 batch.column(a),
786 &kept,
787 )?);
788 }
789 }
790 (edges, index)
791 }
792 }
793 Shape::Path {
794 nodes,
795 edges,
796 elements,
797 } => {
798 let (mut drawn, index) =
799 build::paths_of(&whole()?, *nodes, *edges, *elements, &reading, max_edges)?;
800 let anchor = nodes.or(*elements).expect("a path column");
801 if reading.label_of(anchor).is_some() {
802 drawn.labels = label_names(&[anchor]).0;
803 }
804 (drawn, index)
805 }
806 Shape::Steps { src, dst, step } => {
807 let batch = whole()?;
808 let (mut edges, index, kept) = build::steps_of(&batch, *src, *dst, *step)?;
809 let (labels, _) = label_names(&[*src, *dst]);
810 if labels.len() == 1 {
811 edges.labels = labels;
812 }
813 for &a in &reading.attributes {
814 let role = meta_role(&schema, a);
815 edges.edge_columns.push(build::edge_attribute(
816 name(a),
817 role,
818 batch.column(a),
819 &kept,
820 )?);
821 }
822 (edges, index)
823 }
824 Shape::Hop { seed, id, distance } => {
825 let batch = whole()?;
826 let (mut edges, index, rows) = build::hop_of(&batch, *seed, *id, *distance)?;
827 if reading.label_of(*id).is_some() {
828 edges.labels = label_names(&[*id]).0;
829 }
830 let read = match &graph {
831 Some(g) => induced(ctx, sql, g, &mut edges, &index, max_edges).await,
832 None => Err("there is no property graph to read the edges from".to_string()),
833 };
834 if let Err(why) = read {
835 if guessed {
836 graph = None;
837 }
838 for i in 0..rows.reached.len() {
840 if rows.distance[i] == 1 && rows.seeds[i] != NULL && rows.reached[i] != NULL {
841 edges.src.push(rows.seeds[i]);
842 edges.dst.push(rows.reached[i]);
843 }
844 }
845 notes.push(format!(
846 "{why}: only each seed's edges to the nodes one step away are drawn"
847 ));
848 }
849 (edges, index)
850 }
851 Shape::Matches { keys, edges } => {
852 let (labels, of_key) = label_names(keys);
853 key_labels = keys.iter().copied().zip(of_key).collect();
854 build::matches_of(&whole()?, &key_labels, &labels, edges, max_edges)?
855 }
856 Shape::Nodes { id } => {
857 let batch = whole()?;
858 let (mut edges, index) = build::nodes_of(&batch, *id)?;
859 if reading.label_of(*id).is_some() {
860 edges.labels = label_names(&[*id]).0;
861 }
862 let read = match &graph {
863 Some(g) => induced(ctx, sql, g, &mut edges, &index, max_edges).await,
864 None => Err("there is no property graph to read the edges from".to_string()),
865 };
866 if let Err(why) = read {
867 if guessed {
868 graph = None;
869 }
870 notes.push(format!("{why}: the nodes are drawn without edges"));
871 }
872 let named = |column: usize| Name {
873 ident: name(column).to_string(),
874 shown: name(column).to_string(),
875 };
876 size = reading.size.map(named);
877 color = reading.color.map(named);
878 own = Some(NodeValues::of_rows(
879 Arc::clone(&schema),
880 batches.clone(),
881 *id,
882 ));
883 (edges, index)
884 }
885 };
886 if key_labels.is_empty() {
887 if let Shape::Edges { src, dst } = &reading.shape {
888 key_labels = vec![(*src, 0), (*dst, 0)];
889 }
890 }
891 if !reading.properties.is_empty() {
893 let batch = whole()?;
894 let several = edges.labels.len() > 1;
895 for &(column, key) in &reading.properties {
896 let label = key_labels
897 .iter()
898 .find(|(k, _)| *k == key)
899 .map(|(_, l)| *l)
900 .filter(|_| several);
901 let values = style::Column::of_keys(
902 Arc::clone(batch.column(key)),
903 Arc::clone(batch.column(column)),
904 label,
905 )
906 .per_node(&index, edges.n as usize)?;
907 let taken = |n: &str| edges.node_columns.iter().any(|c| c.name == n);
908 if !taken(name(column)) {
909 edges
910 .node_columns
911 .push(style::property_column(name(column), &values)?);
912 }
913 }
914 }
915 Ok(Drawing {
916 edges,
917 index,
918 rule: reading.shape.rule(),
919 graph,
920 own,
921 size,
922 color,
923 roles: reading.roles,
924 notes,
925 })
926}
927
928fn meta_role(schema: &SchemaRef, column: usize) -> Option<Role> {
931 use crate::graph::provenance as meta;
932 match schema.field(column).metadata().get(meta::ROLE)?.as_str() {
933 meta::ROLE_METRIC => Some(Role::Metric),
934 meta::ROLE_CATEGORY => Some(Role::Category),
935 meta::ROLE_PROPERTY => Some(Role::Property),
936 meta::ROLE_DISTANCE => Some(Role::Distance),
937 _ => None,
938 }
939}
940
941async fn induced(
944 ctx: &SessionContext,
945 sql: &dyn RunSql,
946 graph: &PropertyGraph,
947 edges: &mut EdgeList,
948 index: &NodeIndex,
949 max_edges: usize,
950) -> std::result::Result<(), String> {
951 use crate::graph::provenance as meta;
952 let quoted = !index.key_type.is_integer();
953 let mut list = String::with_capacity(edges.ids.len() * 8);
954 for (i, id) in edges.ids.iter().enumerate() {
955 if i > 0 {
956 list.push(',');
957 }
958 if quoted {
959 list.push('\'');
960 list.push_str(&id.replace('\'', "''"));
961 list.push('\'');
962 } else {
963 list.push_str(id);
964 }
965 }
966 let query = format!(
967 "SELECT src, dst, edge FROM induced_edges(\"{}\", nodes => [{list}]) LIMIT {}",
968 graph.name.replace('"', "\"\""),
969 max_edges.saturating_add(1)
970 );
971 drop(list);
972 let (schema, batches) = sql.run(ctx, &query).await.map_err(|e| {
973 format!(
974 "the edges of '{}' could not be read ({})",
975 graph.name,
976 crate::user_message(&e)
977 )
978 })?;
979 let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
980 if rows > max_edges {
981 return Err(format!(
982 "there are more than {} edges among the nodes, the most the graph view draws \
983 (ursa.graph_max_edges)",
984 thousands(max_edges)
985 ));
986 }
987 let fail = |e: DataFusionError| crate::user_message(&e);
988 let mut edge_rows = Vec::with_capacity(rows);
989 for b in &batches {
990 let (s, d) = (
991 index.lookup(b.column(0)).map_err(fail)?,
992 index.lookup(b.column(1)).map_err(fail)?,
993 );
994 let row = cast(b.column(2), &DataType::UInt64).map_err(|e| e.to_string())?;
995 let row = row.as_primitive::<UInt64Type>();
996 for i in 0..b.num_rows() {
997 if let (Some(s), Some(d)) = (s[i], d[i]) {
998 edges.src.push(s);
999 edges.dst.push(d);
1000 edge_rows.push(if row.is_valid(i) {
1001 row.value(i)
1002 } else {
1003 NO_ROW
1004 });
1005 }
1006 }
1007 }
1008 if edge_rows.iter().any(|&r| r != NO_ROW) {
1009 edges.edge_rows = Some(edge_rows);
1010 }
1011 if let Some(label) = schema.field(2).metadata().get(meta::LABEL) {
1012 edges.edge_labels = vec![label.clone()];
1013 }
1014 Ok(())
1015}
1016
1017async fn apply_style(
1020 ctx: &SessionContext,
1021 sql: &dyn RunSql,
1022 drawing: &mut Drawing,
1023 style: &Style,
1024) -> Result<()> {
1025 if style.size.is_none() && style.color.is_none() && style.nodes.is_some() {
1026 return plan_err(
1027 "NODES (…) gives values for SIZE BY or COLOR BY to use; add one, as in \
1028 .graph … NODES (SELECT id, score FROM …) SIZE BY score",
1029 );
1030 }
1031 let graph = drawing.graph.clone();
1032 let graph = graph.as_deref();
1033 let nodes = match &style.nodes {
1034 Some(query) => Some(NodeValues::of_query(ctx, sql, query).await?),
1035 None => None,
1036 };
1037 let own = drawing.own.as_ref();
1038 let mut found = Vec::new();
1042 for (clause, asked, default) in [
1043 ("SIZE BY", &style.size, &drawing.size),
1044 ("COLOR BY", &style.color, &drawing.color),
1045 ] {
1046 match (asked, default) {
1047 (Some(name), _) => found.push((
1048 clause,
1049 name.clone(),
1050 resolve(ctx, graph, nodes.as_ref(), own, clause, name).await?,
1051 true,
1052 )),
1053 (None, Some(name)) => {
1054 if let Ok(f) = resolve(ctx, None, None, own, clause, name).await {
1055 found.push((clause, name.clone(), f, false));
1056 }
1057 }
1058 (None, None) => {}
1059 }
1060 }
1061 let mut algorithms: Vec<&'static str> = Vec::new();
1062 for (_, _, f, _) in &found {
1063 if let Found::Algorithm(name) = f {
1064 if !algorithms.contains(name) {
1065 algorithms.push(name);
1066 }
1067 }
1068 }
1069 let computed = match (graph, algorithms.is_empty()) {
1070 (Some(g), false) => Some(run_algorithms(ctx, sql, g, &algorithms).await?),
1071 _ => None,
1072 };
1073 let edges = &mut drawing.edges;
1074 for (clause, name, f, asked) in found {
1075 let column = match f {
1076 Found::Nodes(i) => nodes.as_ref().expect("NODES was given").column(i),
1077 Found::Own(i) => own.expect("the result's rows").column(i),
1078 Found::Vertex => vertex_column(ctx, graph.expect("a graph"), &name.ident).await?,
1079 Found::Algorithm(algorithm) => computed.as_ref().expect("ran").column_named(algorithm),
1080 Found::Degree => degree_column(edges),
1081 };
1082 let values = column.per_node(&drawing.index, edges.n as usize)?;
1083 if clause == "SIZE BY" {
1084 match size_by(&name.shown, &values) {
1085 Ok(size) => edges.size = Some(size),
1086 Err(e) if asked => return Err(e),
1087 Err(_) => {}
1088 }
1089 } else {
1090 match color_by(&name.shown, &values) {
1091 Ok(color) => edges.color = Some(color),
1092 Err(e) if asked => return Err(e),
1093 Err(_) => {}
1094 }
1095 }
1096 }
1097 if edges.color.is_none() {
1098 edges.color = default_color(edges);
1099 }
1100 Ok(())
1101}
1102
1103fn default_color(edges: &EdgeList) -> Option<ColorBy> {
1106 let (by, names, codes): (&str, Vec<String>, Vec<u32>) = if edges.labels.len() > 1 {
1109 (
1110 LABEL,
1111 edges.labels.clone(),
1112 edges.node_label.iter().map(|&l| u32::from(l)).collect(),
1113 )
1114 } else if edges.level.as_deref() == Some(build::DISTANCE) {
1115 let column = edges
1116 .node_columns
1117 .iter()
1118 .find(|c| c.name == build::DISTANCE)?;
1119 let Values::U32(level) = &column.values else {
1120 return None;
1121 };
1122 let furthest = level.iter().filter(|&&d| d != NULL).max()?;
1123 (
1124 build::DISTANCE,
1125 (0..=*furthest).map(|d| d.to_string()).collect(),
1126 level.clone(),
1127 )
1128 } else {
1129 return None;
1130 };
1131 let mut counts = vec![0u32; names.len()];
1132 let mut missing = 0;
1133 for &c in &codes {
1134 match counts.get_mut(c as usize) {
1135 Some(n) => *n += 1,
1136 None => missing += 1,
1137 }
1138 }
1139 Some(ColorBy {
1140 by: by.to_string(),
1141 values: names,
1142 counts,
1143 codes,
1144 missing,
1145 })
1146}
1147
1148pub const LABEL: &str = "label";
1150
1151async fn property_graph_indexed(
1154 ctx: &SessionContext,
1155 graph: &PropertyGraph,
1156 max_edges: usize,
1157) -> Result<(EdgeList, NodeIndex)> {
1158 if let Some(drawn) = from_index(ctx, graph, max_edges).await {
1159 return Ok(drawn);
1160 }
1161 from_rows(ctx, graph, max_edges).await
1162}
1163
1164async fn from_rows(
1167 ctx: &SessionContext,
1168 graph: &PropertyGraph,
1169 max_edges: usize,
1170) -> Result<(EdgeList, NodeIndex)> {
1171 let state = ctx.state();
1172 let mut vertices = Vec::new();
1173 for v in &graph.vertex_tables {
1174 let batches = scan_columns(ctx, graph, &v.table, &[v.key.as_str()]).await?;
1175 vertices.extend(batches.iter().map(|b| Arc::clone(b.column(0))));
1176 }
1177 let mut edges = Vec::new();
1178 for e in &graph.edge_tables {
1179 let def = GraphDef {
1180 name: graph.name.clone(),
1181 edges: e.clone(),
1182 vertices: None,
1183 };
1184 let plan = edges_plan(&state, &def).await?;
1185 let batches = DataFrame::new(state.clone(), plan)
1186 .select_columns(&[e.source.as_str(), e.destination.as_str()])?
1187 .collect()
1188 .await?;
1189 edges.extend(
1190 batches
1191 .iter()
1192 .map(|b| (Arc::clone(b.column(0)), Arc::clone(b.column(1)))),
1193 );
1194 }
1195 if graph.edge_tables.is_empty() {
1196 return plan_err(format!(
1197 "graph '{}' has no edge tables: there are no edges to draw",
1198 graph.name
1199 ));
1200 }
1201 build_within(&vertices, &edges, max_edges)
1202}
1203
1204async fn from_index(
1218 ctx: &SessionContext,
1219 graph: &PropertyGraph,
1220 max_edges: usize,
1221) -> Option<(EdgeList, NodeIndex)> {
1222 let [e] = &graph.edge_tables[..] else {
1223 return None;
1224 };
1225 if !graph.vertex_tables.is_empty() {
1226 return None;
1227 }
1228 let state = ctx.state();
1229 let def = GraphDef {
1230 name: graph.name.clone(),
1231 edges: e.clone(),
1232 vertices: None,
1233 };
1234 let plan = edges_plan(&state, &def).await.ok()?;
1236 let schema = plan.schema();
1237 let type_of = |column: &str| {
1238 let i = schema.index_of_column_by_name(None, column)?;
1239 Some(schema.field(i).data_type().clone())
1240 };
1241 let key_type = type_of(&e.source)?;
1242 if type_of(&e.destination)? != key_type || !build::index_key(&key_type) {
1243 return None;
1244 }
1245 let query = format!(
1247 "SELECT id FROM degree(\"{}\")",
1248 graph.name.replace('"', "\"\"")
1249 );
1250 let physical = ctx
1251 .sql(&query)
1252 .await
1253 .ok()?
1254 .create_physical_plan()
1255 .await
1256 .ok()?;
1257 let index = crate::graph::index_under(&physical, &ctx.task_ctx())
1258 .await
1259 .ok()??;
1260 let edges = index.topology.n_edges();
1261 if index.n_dropped() > 0 || edges == 0 || edges > max_edges {
1262 return None;
1263 }
1264 build::of_index(&index.topology, &index.ids.user_id_array(), key_type).ok()?
1265}
1266
1267pub(crate) async fn scan_columns(
1269 ctx: &SessionContext,
1270 graph: &PropertyGraph,
1271 table: &TableReference,
1272 columns: &[&str],
1273) -> Result<Vec<RecordBatch>> {
1274 let state = ctx.state();
1275 let provider = graph_table(&state, &graph.name, table).await?;
1276 let plan =
1277 LogicalPlanBuilder::scan(table.clone(), provider_as_source(provider), None)?.build()?;
1278 DataFrame::new(state.clone(), plan)
1279 .select_columns(columns)?
1280 .collect()
1281 .await
1282}
1283
1284fn key_type_of(key_type: &DataType, ids: &[String]) -> KeyType {
1287 let fits = match key_type {
1288 DataType::Int8
1289 | DataType::Int16
1290 | DataType::Int32
1291 | DataType::Int64
1292 | DataType::UInt8
1293 | DataType::UInt16
1294 | DataType::UInt32 => true,
1295 DataType::UInt64 => ids.iter().all(|id| id.parse::<i64>().is_ok()),
1297 _ => false,
1298 };
1299 if fits {
1300 KeyType::Int
1301 } else {
1302 KeyType::Text
1303 }
1304}
1305
1306fn to_view(
1310 edges: EdgeList,
1311 key_type: &DataType,
1312 graph: Option<String>,
1313 provenance: Provenance,
1314) -> Result<GraphView> {
1315 let model = |e: ursa_viz::model::ModelError| {
1316 DataFusionError::Plan(format!("the graph cannot be drawn: {e}"))
1317 };
1318 let EdgeList {
1319 n,
1320 src,
1321 dst,
1322 ids,
1323 skipped,
1324 size,
1325 color,
1326 mut labels,
1327 node_label,
1328 mut edge_labels,
1329 edge_label,
1330 edge_rows,
1331 node_columns,
1332 edge_columns,
1333 paths,
1334 seeds,
1335 level,
1336 layout,
1337 } = edges;
1338 if labels.is_empty() {
1339 labels.push(String::new());
1340 }
1341 if edge_labels.is_empty() {
1342 edge_labels.push(String::new());
1343 }
1344 let key = key_type_of(key_type, &ids);
1345 let nodes = NodeBatch {
1346 labels: if node_label.is_empty() {
1347 vec![0; n as usize]
1348 } else {
1349 node_label
1350 },
1351 keys: ids.iter().collect::<Strings>(),
1352 ..NodeBatch::default()
1353 };
1354 drop(ids);
1355 let mut batch = EdgeBatch::of_label(0, src, dst);
1356 if !edge_label.is_empty() {
1357 batch.labels = edge_label;
1358 }
1359 batch.rows = edge_rows;
1360 let mut ops: Vec<Op> = labels
1361 .into_iter()
1362 .map(|name| Op::AddNodeLabel(NodeLabel::new(name, key)))
1363 .collect();
1364 ops.extend(edge_labels.into_iter().map(Op::AddEdgeLabel));
1365 ops.push(Op::AddNodes(nodes));
1366 ops.push(Op::AddEdges(batch));
1367 let base = GraphDelta::new(ops);
1368 let mut result = GraphResult::build(graph, provenance, &base).map_err(model)?;
1369 drop(base);
1370
1371 let mut encodings = Encodings {
1372 layout,
1373 ..Encodings::default()
1374 };
1375 let mut columns: Vec<(Target, ModelColumn)> = Vec::new();
1376 columns.extend(node_columns.into_iter().map(|c| (Target::Nodes, c)));
1377 columns.extend(edge_columns.into_iter().map(|c| (Target::Edges, c)));
1378 let taken = |columns: &[(Target, ModelColumn)], name: &str| {
1380 columns
1381 .iter()
1382 .any(|(t, c)| *t == Target::Nodes && c.name == name)
1383 };
1384 if let Some(size) = size {
1385 let name = if taken(&columns, &size.by) {
1386 format!("{}{SIZE_SUFFIX}", size.by)
1387 } else {
1388 size.by
1389 };
1390 encodings.size_by = Some(name.clone());
1391 columns.push((
1392 Target::Nodes,
1393 ModelColumn::new(name, Some(Role::Metric), Values::F32(size.values)),
1394 ));
1395 }
1396 if let Some(color) = color {
1397 let name = if taken(&columns, &color.by) {
1398 format!("{}{COLOR_SUFFIX}", color.by)
1399 } else {
1400 color.by
1401 };
1402 encodings.color_by = Some(name.clone());
1403 columns.push((
1404 Target::Nodes,
1405 ModelColumn::new(
1406 name,
1407 Some(Role::Category),
1408 Values::Dict {
1409 values: color.values.iter().collect(),
1410 codes: color.codes,
1411 },
1412 ),
1413 ));
1414 }
1415 for (target, column) in columns {
1416 let op = result.set_column_op(target, column);
1417 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
1418 }
1419 let highlights = Highlights {
1420 paths,
1421 seeds,
1422 distance: level,
1423 };
1424 if !highlights.is_empty() {
1425 let op = result.set_highlights_op(highlights);
1426 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
1427 }
1428 if encodings != Encodings::default() {
1429 let op = result.set_encodings_op(encodings);
1430 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
1431 }
1432 Ok(GraphView {
1433 result,
1434 skipped,
1435 positions: None,
1436 groups: None,
1437 })
1438}