1use std::sync::Arc;
49
50use async_trait::async_trait;
51use datafusion::arrow::array::{Array, AsArray, RecordBatch};
52use datafusion::arrow::compute::{cast, concat_batches};
53use datafusion::arrow::datatypes::{DataType, SchemaRef, UInt64Type};
54use datafusion::common::TableReference;
55use datafusion::dataframe::DataFrame;
56use datafusion::datasource::provider_as_source;
57use datafusion::error::{DataFusionError, Result};
58use datafusion::logical_expr::LogicalPlanBuilder;
59use datafusion::prelude::SessionContext;
60use ursa_viz::model::{
61 Column as ModelColumn, ColumnRole, EdgeBatch, Encodings, GraphDelta, GraphResult, Highlights,
62 KeyType, NodeBatch, NodeLabel, Op, Provenance, Role, Strings, Target, Values, NO_ROW, NULL,
63};
64
65use crate::graph::schema::graph_table;
66use crate::graph::{edges_plan, registry_of, GraphDef, PropertyGraph};
67
68mod build;
69pub mod clauses;
70pub mod find;
71pub mod inspect;
72mod positions;
73pub mod rules;
74pub mod session;
75mod style;
76
77#[cfg(test)]
78mod tests;
79
80use build::{build_within, EdgeList, NodeIndex};
81pub use clauses::{identifier, parse, As, Name, Style, USAGE};
82pub use rules::Rule;
83use rules::{MatchEdge, Shape};
84pub use session::{Command, Outcome, Session, Step};
85use style::{
86 color_by, degree_column, resolve, run_algorithms, size_by, vertex_column, ColorBy, Found,
87 NodeValues,
88};
89pub use ursa_viz::model::Positions;
91
92pub const MAX_EDGES: usize = 5_000_000;
96pub const MAX_NODES: usize = 4_000_000;
98pub const MAX_CATEGORIES: usize = 8;
101
102pub const COLOR_SUFFIX: &str = " (colour)";
107pub const SIZE_SUFFIX: &str = " (size)";
110
111pub(crate) fn plan_err<T>(message: impl Into<String>) -> Result<T> {
112 Err(DataFusionError::Plan(message.into()))
113}
114
115pub type Rows = (SchemaRef, Vec<RecordBatch>);
117
118#[async_trait]
121pub trait RunSql: Send + Sync {
122 async fn run(&self, ctx: &SessionContext, text: &str) -> Result<Rows>;
123}
124
125#[derive(Debug, Clone, Copy, Default)]
129pub struct DataFusionSql;
130
131#[async_trait]
132impl RunSql for DataFusionSql {
133 async fn run(&self, ctx: &SessionContext, text: &str) -> Result<Rows> {
134 let frame = ctx.sql(text).await?;
135 let schema = Arc::new(frame.schema().as_arrow().clone());
136 Ok((schema, frame.collect().await?))
137 }
138}
139
140pub(crate) fn thousands(n: usize) -> String {
142 let digits = n.to_string();
143 let mut out = String::new();
144 for (i, c) in digits.chars().enumerate() {
145 if i > 0 && (digits.len() - i).is_multiple_of(3) {
146 out.push(',');
147 }
148 out.push(c);
149 }
150 out
151}
152
153pub(crate) fn raise_max_edges(edges: usize) -> String {
156 let limit = edges.div_ceil(1_000_000).max(1) * 1_000_000;
157 format!("SET ursa.graph_max_edges = {limit}")
158}
159
160pub enum Source {
162 Graph(Arc<PropertyGraph>),
163 Rows {
164 schema: SchemaRef,
165 batches: Vec<RecordBatch>,
166 sql: Option<String>,
168 },
169}
170
171impl Source {
172 pub async fn of_text(ctx: &SessionContext, sql: &dyn RunSql, text: &str) -> Result<Source> {
175 if let Some(name) = identifier(text) {
176 if let Some(graph) = registry_of(ctx).get(&name) {
177 return Ok(Source::Graph(graph));
178 }
179 let table = TableReference::bare(name.as_str());
180 if !ctx.table_exist(table.clone())? {
181 return plan_err(format!(
182 "no graph or table named '{name}'; .graphs lists the graphs and .tables the \
183 tables, or give a query: .graph SELECT src, dst FROM …"
184 ));
185 }
186 let frame = ctx.table(table).await?;
187 let schema = Arc::new(frame.schema().as_arrow().clone());
188 return Ok(Source::Rows {
189 schema,
190 batches: frame.collect().await?,
191 sql: Some(format!("SELECT * FROM {}", text.trim())),
192 });
193 }
194 let (schema, batches) = sql.run(ctx, text).await?;
195 Ok(Source::Rows {
196 schema,
197 batches,
198 sql: Some(text.trim().to_string()),
199 })
200 }
201
202 pub fn of_rows((schema, batches): Rows) -> Source {
204 Source::Rows {
205 schema,
206 batches,
207 sql: None,
208 }
209 }
210}
211
212#[derive(Debug, Clone, PartialEq)]
214pub struct GraphView {
215 pub result: GraphResult,
221 pub skipped: usize,
223 pub positions: Option<Positions>,
230}
231
232impl GraphView {
233 pub fn placed(&self) -> GraphResult {
237 let mut result = self.result.clone();
238 if let Some(positions) = &self.positions {
239 let op = result.set_positions_op(Some(positions.clone()));
240 result
241 .apply(&GraphDelta::new(vec![op]))
242 .expect("a place per node");
243 }
244 result
245 }
246
247 pub fn legend(&self) -> Option<Legend> {
249 Legend::of(&self.result)
250 }
251
252 pub fn drawn_as(&self) -> String {
254 drawn_as(&self.result)
255 }
256}
257
258pub fn drawn_as(result: &GraphResult) -> String {
264 let provenance = result.provenance();
265 let Some(rule) = provenance.rule.as_deref() else {
266 return String::new();
267 };
268 let paths = result.highlights().paths.len();
269 let (what, joins) = match rule {
270 "graph" => ("the graph".to_string(), " "),
271 "edges" => ("edges".to_string(), " of "),
272 "path" if paths > 1 => (format!("{} paths", thousands(paths)), " on "),
273 "path" => ("a path".to_string(), " on "),
274 "rings" => ("rings".to_string(), " on "),
275 "pattern" => ("pattern matches".to_string(), " on "),
276 "nodes" => ("nodes".to_string(), " of "),
277 other => (other.to_string(), " on "),
278 };
279 let mut out = what;
280 if let Some(graph) = result.graph() {
281 out.push_str(joins);
282 out.push_str(graph);
283 }
284 if !provenance.roles.is_empty() {
285 let columns: Vec<&str> = provenance.roles.iter().map(|r| r.column.as_str()).collect();
286 out.push_str(&format!(" ({})", columns.join(", ")));
287 }
288 for note in &provenance.notes {
289 out.push_str(" · ");
290 out.push_str(note);
291 }
292 out
293}
294
295#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct Legend {
299 pub by: String,
301 pub labels: Vec<String>,
304 pub counts: Vec<u32>,
306 pub other: u32,
308 pub missing: u32,
310}
311
312impl Legend {
313 pub fn of(result: &GraphResult) -> Option<Legend> {
316 let name = result.encodings().color_by.as_deref()?;
317 let Values::Dict { values, codes } = &result.node_column(name)?.values else {
318 return None;
319 };
320 let by = match name.strip_suffix(COLOR_SUFFIX) {
321 Some(by) if result.node_column(by).is_some() => by,
322 _ => name,
323 };
324 let top = values.len().min(MAX_CATEGORIES);
325 let mut legend = Legend {
326 by: by.to_string(),
327 labels: values.iter().take(top).map(str::to_string).collect(),
328 counts: vec![0; top],
329 other: 0,
330 missing: 0,
331 };
332 for &code in codes {
333 match code {
334 NULL => legend.missing += 1,
335 c if (c as usize) < top => legend.counts[c as usize] += 1,
336 _ => legend.other += 1,
337 }
338 }
339 Some(legend)
340 }
341}
342
343pub async fn of_command(
346 ctx: &SessionContext,
347 sql: &dyn RunSql,
348 text: &str,
349 last: Option<Rows>,
350) -> Result<GraphView> {
351 let (text, style) = parse(text)?;
352 let source = if !text.is_empty() {
353 Source::of_text(ctx, sql, &text).await?
354 } else {
355 let Some(rows) = last else {
356 return plan_err(
357 "no result to draw yet: run a query whose rows are edges (columns src and dst, \
358 or else the first two), then .graph; or .graph NAME for a property graph",
359 );
360 };
361 Source::of_rows(rows)
362 };
363 draw(ctx, sql, source, &style).await
364}
365
366pub async fn draw(
369 ctx: &SessionContext,
370 sql: &dyn RunSql,
371 source: Source,
372 style: &Style,
373) -> Result<GraphView> {
374 if let (Some(_), Some(layout)) = (&style.positions, style.layout) {
375 return plan_err(format!(
376 "POSITIONS (…) and LAYOUT {} both say where the nodes go; give one. POSITIONS \
377 draws the nodes where its query puts them, and no layout runs",
378 layout_name(layout)
379 ));
380 }
381 let max_edges = crate::options::graph_max_edges(ctx.state().config());
382 let (mut drawing, text) = match source {
383 Source::Graph(g) => {
384 if let Some(shape) = &style.shape {
386 return plan_err(format!(
387 "{} says how to read a result's rows, and '{}' is a property graph, drawn \
388 whole. Leave the clause out (.graph {}), or draw a query's rows: .graph \
389 SELECT … FROM … {}",
390 shape.shown(),
391 g.name,
392 g.name,
393 shape.shown()
394 ));
395 }
396 if let Some(on) = &style.on {
397 return plan_err(format!(
398 "ON {} names the graph a result's ids belong to, and '{}' is a property graph \
399 already. Leave the clause out (.graph {}), or draw a query's rows: .graph \
400 SELECT … FROM … ON {}",
401 on.shown, g.name, g.name, on.shown
402 ));
403 }
404 let (edges, index) = property_graph_indexed(ctx, &g, max_edges).await?;
405 (Drawing::of_graph(edges, index, g), None)
406 }
407 Source::Rows {
408 schema,
409 batches,
410 sql: text,
411 } => (
412 read_rows(ctx, sql, schema, batches, style, max_edges).await?,
413 text,
414 ),
415 };
416 apply_style(ctx, sql, &mut drawing, style).await?;
417 if let Some(layout) = style.layout {
418 set_layout(&mut drawing, layout)?;
419 }
420 let saved = match &style.positions {
421 Some(query) => {
422 let saved = positions::saved(ctx, sql, query, &drawing.edges, &drawing.index).await?;
423 drawing.edges.layout = ursa_viz::model::Layout::Force;
426 drawing.notes.extend(saved.notes);
427 Some(saved.positions)
428 }
429 None => None,
430 };
431 let provenance = Provenance {
432 sql: text,
433 rule: Some(drawing.rule.name().to_string()),
434 roles: drawing
435 .roles
436 .iter()
437 .map(|(column, role)| ColumnRole::new(column, role))
438 .collect(),
439 notes: std::mem::take(&mut drawing.notes),
440 };
441 let graph = drawing.graph.as_ref().map(|g| g.name.clone());
442 let mut view = to_view(drawing.edges, &drawing.index.key_type, graph, provenance)?;
443 view.positions = saved;
444 Ok(view)
445}
446
447fn layout_name(layout: ursa_viz::model::Layout) -> &'static str {
448 use ursa_viz::model::Layout;
449 match layout {
450 Layout::Force => "force",
451 Layout::Rings => "rings",
452 Layout::Layers => "layers",
453 }
454}
455
456pub async fn interpret(
464 ctx: &SessionContext,
465 sql: &dyn RunSql,
466 schema: SchemaRef,
467 batches: Vec<RecordBatch>,
468) -> Result<GraphView> {
469 interpret_with(ctx, sql, schema, batches, &Style::default()).await
470}
471
472pub async fn interpret_with(
476 ctx: &SessionContext,
477 sql: &dyn RunSql,
478 schema: SchemaRef,
479 batches: Vec<RecordBatch>,
480 style: &Style,
481) -> Result<GraphView> {
482 let source = Source::of_rows((schema, batches));
483 draw(ctx, sql, source, style).await
484}
485
486fn set_layout(drawing: &mut Drawing, layout: ursa_viz::model::Layout) -> Result<()> {
490 use ursa_viz::model::Layout;
491 let name = layout_name(layout);
492 if layout != Layout::Force && drawing.edges.level.is_none() {
493 let what = match drawing.rule {
494 Rule::Graph => "a property graph",
495 Rule::Edges => "edges",
496 Rule::Matches => "pattern matches",
497 Rule::Nodes => "nodes",
498 Rule::Path | Rule::Rings => "this drawing",
499 };
500 return plan_err(format!(
501 "LAYOUT {name} places each node by its distance from a seed or its step along a path, \
502 and {what} {} neither. Draw a hop result or paths (.graph SELECT * FROM hop(g, seeds \
503 => [1], steps => 2) LAYOUT {name}), say which columns are one (AS hops(seed, id, \
504 distance)), or use LAYOUT force",
505 if what == "this drawing" || what == "a property graph" {
506 "has"
507 } else {
508 "have"
509 }
510 ));
511 }
512 drawing.edges.layout = layout;
513 Ok(())
514}
515
516struct Drawing {
519 edges: EdgeList,
520 index: NodeIndex,
521 rule: Rule,
522 graph: Option<Arc<PropertyGraph>>,
524 own: Option<NodeValues>,
526 size: Option<Name>,
528 color: Option<Name>,
529 roles: Vec<(String, String)>,
530 notes: Vec<String>,
531}
532
533impl Drawing {
534 fn of_graph(edges: EdgeList, index: NodeIndex, graph: Arc<PropertyGraph>) -> Drawing {
535 Drawing {
536 edges,
537 index,
538 rule: Rule::Graph,
539 graph: Some(graph),
540 own: None,
541 size: None,
542 color: None,
543 roles: Vec::new(),
544 notes: Vec::new(),
545 }
546 }
547}
548
549fn graph_of(
553 ctx: &SessionContext,
554 reading: &rules::Reading,
555 on: Option<&Name>,
556 or_the_only: bool,
557 notes: &mut Vec<String>,
558) -> Result<Option<Arc<PropertyGraph>>> {
559 let registry = registry_of(ctx);
560 if let Some(on) = on {
561 let Some(found) = registry.get(&on.ident) else {
562 let mut names: Vec<String> = registry.all().iter().map(|g| g.name.clone()).collect();
563 names.sort();
564 return plan_err(format!(
565 "ON {}: there is no property graph named '{}'. {}",
566 on.shown,
567 on.ident,
568 if names.is_empty() {
569 "This session has none: make one with CREATE PROPERTY GRAPH, or leave the \
570 clause out"
571 .to_string()
572 } else {
573 format!("The graphs are {}; name one of them", names.join(", "))
574 }
575 ));
576 };
577 if let Some(theirs) = reading.graph.as_deref().filter(|g| *g != found.name) {
578 notes.push(format!(
579 "read on {} as ON says; the columns are from {theirs}",
580 found.name
581 ));
582 }
583 return Ok(Some(found));
584 }
585 Ok(graph_of_columns(®istry, reading, or_the_only, notes))
586}
587
588fn graph_of_columns(
589 registry: &crate::graph::GraphRegistry,
590 reading: &rules::Reading,
591 or_the_only: bool,
592 notes: &mut Vec<String>,
593) -> Option<Arc<PropertyGraph>> {
594 if let Some(name) = &reading.graph {
595 let found = registry.get(name);
596 if found.is_none() {
597 notes.push(format!("the graph '{name}' is not in this session"));
598 }
599 return found;
600 }
601 let mut all = registry.all();
602 match (or_the_only, all.len()) {
603 (true, 1) => all.pop(),
604 _ => None,
605 }
606}
607
608async fn read_rows(
610 ctx: &SessionContext,
611 sql: &dyn RunSql,
612 schema: SchemaRef,
613 batches: Vec<RecordBatch>,
614 style: &Style,
615 max_edges: usize,
616) -> Result<Drawing> {
617 let reading = match &style.shape {
619 Some(shape) => rules::read_as(&schema, shape, style.on.is_some())?,
620 None => rules::read(&schema)?,
621 };
622 let mut notes = reading.notes.clone();
623 let name = |column: usize| schema.field(column).name().as_str();
624 let whole = || concat_batches(&schema, &batches);
626 let label_names = |keys: &[usize]| -> (Vec<String>, Vec<u16>) {
627 let mut labels: Vec<String> = Vec::new();
628 let of_key = keys
629 .iter()
630 .map(|&k| {
631 let label = reading.label_of(k).unwrap_or("");
632 let at = labels.iter().position(|l| l == label).unwrap_or_else(|| {
633 labels.push(label.to_string());
634 labels.len() - 1
635 });
636 at as u16
637 })
638 .collect();
639 (labels, of_key)
640 };
641 let mut own = None;
642 let (mut size, mut color) = (None, None);
643 let mut graph = graph_of(
644 ctx,
645 &reading,
646 style.on.as_ref(),
647 matches!(reading.shape, Shape::Hop { .. } | Shape::Nodes { .. }),
648 &mut notes,
649 )?;
650 let guessed = reading.graph.is_none() && style.on.is_none();
653 let mut key_labels: Vec<(usize, u16)> = Vec::new();
655 let (mut edges, index) = match &reading.shape {
656 Shape::Edges { src, dst } => {
657 let (labels, of_key) = label_names(&[*src, *dst]);
658 if labels.len() > 1 {
659 let batch = whole()?;
661 key_labels = vec![(*src, of_key[0]), (*dst, of_key[1])];
662 let edge = MatchEdge {
663 from: 0,
664 to: 1,
665 directed: true,
666 label: reading.edge_label.clone().unwrap_or_default(),
667 };
668 build::matches_of(&batch, &key_labels, &labels, &[edge], max_edges)?
669 } else {
670 let (mut edges, index) = build::edges_of(&batches, *src, *dst, max_edges)?;
671 if reading.marked {
672 edges.labels = labels;
673 edges.edge_labels = reading.edge_label.iter().cloned().collect();
674 }
675 if !reading.attributes.is_empty() {
676 let batch = whole()?;
677 let (s, d) = (batch.column(*src), batch.column(*dst));
678 let kept: Vec<usize> = (0..batch.num_rows())
679 .filter(|&i| s.is_valid(i) && d.is_valid(i))
680 .collect();
681 for &a in &reading.attributes {
682 let role = meta_role(&schema, a);
683 edges.edge_columns.push(build::edge_attribute(
684 name(a),
685 role,
686 batch.column(a),
687 &kept,
688 )?);
689 }
690 }
691 (edges, index)
692 }
693 }
694 Shape::Path {
695 nodes,
696 edges,
697 elements,
698 } => {
699 let (mut drawn, index) =
700 build::paths_of(&whole()?, *nodes, *edges, *elements, &reading, max_edges)?;
701 let anchor = nodes.or(*elements).expect("a path column");
702 if reading.label_of(anchor).is_some() {
703 drawn.labels = label_names(&[anchor]).0;
704 }
705 (drawn, index)
706 }
707 Shape::Steps { src, dst, step } => {
708 let batch = whole()?;
709 let (mut edges, index, kept) = build::steps_of(&batch, *src, *dst, *step)?;
710 let (labels, _) = label_names(&[*src, *dst]);
711 if labels.len() == 1 {
712 edges.labels = labels;
713 }
714 for &a in &reading.attributes {
715 let role = meta_role(&schema, a);
716 edges.edge_columns.push(build::edge_attribute(
717 name(a),
718 role,
719 batch.column(a),
720 &kept,
721 )?);
722 }
723 (edges, index)
724 }
725 Shape::Hop { seed, id, distance } => {
726 let batch = whole()?;
727 let (mut edges, index, rows) = build::hop_of(&batch, *seed, *id, *distance)?;
728 if reading.label_of(*id).is_some() {
729 edges.labels = label_names(&[*id]).0;
730 }
731 let read = match &graph {
732 Some(g) => induced(ctx, sql, g, &mut edges, &index, max_edges).await,
733 None => Err("there is no property graph to read the edges from".to_string()),
734 };
735 if let Err(why) = read {
736 if guessed {
737 graph = None;
738 }
739 for i in 0..rows.reached.len() {
741 if rows.distance[i] == 1 && rows.seeds[i] != NULL && rows.reached[i] != NULL {
742 edges.src.push(rows.seeds[i]);
743 edges.dst.push(rows.reached[i]);
744 }
745 }
746 notes.push(format!(
747 "{why}: only each seed's edges to the nodes one step away are drawn"
748 ));
749 }
750 (edges, index)
751 }
752 Shape::Matches { keys, edges } => {
753 let (labels, of_key) = label_names(keys);
754 key_labels = keys.iter().copied().zip(of_key).collect();
755 build::matches_of(&whole()?, &key_labels, &labels, edges, max_edges)?
756 }
757 Shape::Nodes { id } => {
758 let batch = whole()?;
759 let (mut edges, index) = build::nodes_of(&batch, *id)?;
760 if reading.label_of(*id).is_some() {
761 edges.labels = label_names(&[*id]).0;
762 }
763 let read = match &graph {
764 Some(g) => induced(ctx, sql, g, &mut edges, &index, max_edges).await,
765 None => Err("there is no property graph to read the edges from".to_string()),
766 };
767 if let Err(why) = read {
768 if guessed {
769 graph = None;
770 }
771 notes.push(format!("{why}: the nodes are drawn without edges"));
772 }
773 let named = |column: usize| Name {
774 ident: name(column).to_string(),
775 shown: name(column).to_string(),
776 };
777 size = reading.size.map(named);
778 color = reading.color.map(named);
779 own = Some(NodeValues::of_rows(
780 Arc::clone(&schema),
781 batches.clone(),
782 *id,
783 ));
784 (edges, index)
785 }
786 };
787 if key_labels.is_empty() {
788 if let Shape::Edges { src, dst } = &reading.shape {
789 key_labels = vec![(*src, 0), (*dst, 0)];
790 }
791 }
792 if !reading.properties.is_empty() {
794 let batch = whole()?;
795 let several = edges.labels.len() > 1;
796 for &(column, key) in &reading.properties {
797 let label = key_labels
798 .iter()
799 .find(|(k, _)| *k == key)
800 .map(|(_, l)| *l)
801 .filter(|_| several);
802 let values = style::Column::of_keys(
803 Arc::clone(batch.column(key)),
804 Arc::clone(batch.column(column)),
805 label,
806 )
807 .per_node(&index, edges.n as usize)?;
808 let taken = |n: &str| edges.node_columns.iter().any(|c| c.name == n);
809 if !taken(name(column)) {
810 edges
811 .node_columns
812 .push(style::property_column(name(column), &values)?);
813 }
814 }
815 }
816 Ok(Drawing {
817 edges,
818 index,
819 rule: reading.shape.rule(),
820 graph,
821 own,
822 size,
823 color,
824 roles: reading.roles,
825 notes,
826 })
827}
828
829fn meta_role(schema: &SchemaRef, column: usize) -> Option<Role> {
832 use crate::graph::provenance as meta;
833 match schema.field(column).metadata().get(meta::ROLE)?.as_str() {
834 meta::ROLE_METRIC => Some(Role::Metric),
835 meta::ROLE_CATEGORY => Some(Role::Category),
836 meta::ROLE_PROPERTY => Some(Role::Property),
837 meta::ROLE_DISTANCE => Some(Role::Distance),
838 _ => None,
839 }
840}
841
842async fn induced(
845 ctx: &SessionContext,
846 sql: &dyn RunSql,
847 graph: &PropertyGraph,
848 edges: &mut EdgeList,
849 index: &NodeIndex,
850 max_edges: usize,
851) -> std::result::Result<(), String> {
852 use crate::graph::provenance as meta;
853 let quoted = !index.key_type.is_integer();
854 let mut list = String::with_capacity(edges.ids.len() * 8);
855 for (i, id) in edges.ids.iter().enumerate() {
856 if i > 0 {
857 list.push(',');
858 }
859 if quoted {
860 list.push('\'');
861 list.push_str(&id.replace('\'', "''"));
862 list.push('\'');
863 } else {
864 list.push_str(id);
865 }
866 }
867 let query = format!(
868 "SELECT src, dst, edge FROM induced_edges(\"{}\", nodes => [{list}]) LIMIT {}",
869 graph.name.replace('"', "\"\""),
870 max_edges.saturating_add(1)
871 );
872 drop(list);
873 let (schema, batches) = sql.run(ctx, &query).await.map_err(|e| {
874 format!(
875 "the edges of '{}' could not be read ({})",
876 graph.name,
877 crate::user_message(&e)
878 )
879 })?;
880 let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
881 if rows > max_edges {
882 return Err(format!(
883 "there are more than {} edges among the nodes, the most the graph view draws \
884 (ursa.graph_max_edges)",
885 thousands(max_edges)
886 ));
887 }
888 let fail = |e: DataFusionError| crate::user_message(&e);
889 let mut edge_rows = Vec::with_capacity(rows);
890 for b in &batches {
891 let (s, d) = (
892 index.lookup(b.column(0)).map_err(fail)?,
893 index.lookup(b.column(1)).map_err(fail)?,
894 );
895 let row = cast(b.column(2), &DataType::UInt64).map_err(|e| e.to_string())?;
896 let row = row.as_primitive::<UInt64Type>();
897 for i in 0..b.num_rows() {
898 if let (Some(s), Some(d)) = (s[i], d[i]) {
899 edges.src.push(s);
900 edges.dst.push(d);
901 edge_rows.push(if row.is_valid(i) {
902 row.value(i)
903 } else {
904 NO_ROW
905 });
906 }
907 }
908 }
909 if edge_rows.iter().any(|&r| r != NO_ROW) {
910 edges.edge_rows = Some(edge_rows);
911 }
912 if let Some(label) = schema.field(2).metadata().get(meta::LABEL) {
913 edges.edge_labels = vec![label.clone()];
914 }
915 Ok(())
916}
917
918async fn apply_style(
921 ctx: &SessionContext,
922 sql: &dyn RunSql,
923 drawing: &mut Drawing,
924 style: &Style,
925) -> Result<()> {
926 if style.size.is_none() && style.color.is_none() && style.nodes.is_some() {
927 return plan_err(
928 "NODES (…) gives values for SIZE BY or COLOR BY to use; add one, as in \
929 .graph … NODES (SELECT id, score FROM …) SIZE BY score",
930 );
931 }
932 let graph = drawing.graph.clone();
933 let graph = graph.as_deref();
934 let nodes = match &style.nodes {
935 Some(query) => Some(NodeValues::of_query(ctx, sql, query).await?),
936 None => None,
937 };
938 let own = drawing.own.as_ref();
939 let mut found = Vec::new();
943 for (clause, asked, default) in [
944 ("SIZE BY", &style.size, &drawing.size),
945 ("COLOR BY", &style.color, &drawing.color),
946 ] {
947 match (asked, default) {
948 (Some(name), _) => found.push((
949 clause,
950 name.clone(),
951 resolve(ctx, graph, nodes.as_ref(), own, clause, name).await?,
952 true,
953 )),
954 (None, Some(name)) => {
955 if let Ok(f) = resolve(ctx, None, None, own, clause, name).await {
956 found.push((clause, name.clone(), f, false));
957 }
958 }
959 (None, None) => {}
960 }
961 }
962 let mut algorithms: Vec<&'static str> = Vec::new();
963 for (_, _, f, _) in &found {
964 if let Found::Algorithm(name) = f {
965 if !algorithms.contains(name) {
966 algorithms.push(name);
967 }
968 }
969 }
970 let computed = match (graph, algorithms.is_empty()) {
971 (Some(g), false) => Some(run_algorithms(ctx, sql, g, &algorithms).await?),
972 _ => None,
973 };
974 let edges = &mut drawing.edges;
975 for (clause, name, f, asked) in found {
976 let column = match f {
977 Found::Nodes(i) => nodes.as_ref().expect("NODES was given").column(i),
978 Found::Own(i) => own.expect("the result's rows").column(i),
979 Found::Vertex => vertex_column(ctx, graph.expect("a graph"), &name.ident).await?,
980 Found::Algorithm(algorithm) => computed.as_ref().expect("ran").column_named(algorithm),
981 Found::Degree => degree_column(edges),
982 };
983 let values = column.per_node(&drawing.index, edges.n as usize)?;
984 if clause == "SIZE BY" {
985 match size_by(&name.shown, &values) {
986 Ok(size) => edges.size = Some(size),
987 Err(e) if asked => return Err(e),
988 Err(_) => {}
989 }
990 } else {
991 match color_by(&name.shown, &values) {
992 Ok(color) => edges.color = Some(color),
993 Err(e) if asked => return Err(e),
994 Err(_) => {}
995 }
996 }
997 }
998 if edges.color.is_none() {
999 edges.color = default_color(edges);
1000 }
1001 Ok(())
1002}
1003
1004fn default_color(edges: &EdgeList) -> Option<ColorBy> {
1007 let (by, names, codes): (&str, Vec<String>, Vec<u32>) = if edges.labels.len() > 1 {
1010 (
1011 LABEL,
1012 edges.labels.clone(),
1013 edges.node_label.iter().map(|&l| u32::from(l)).collect(),
1014 )
1015 } else if edges.level.as_deref() == Some(build::DISTANCE) {
1016 let column = edges
1017 .node_columns
1018 .iter()
1019 .find(|c| c.name == build::DISTANCE)?;
1020 let Values::U32(level) = &column.values else {
1021 return None;
1022 };
1023 let furthest = level.iter().filter(|&&d| d != NULL).max()?;
1024 (
1025 build::DISTANCE,
1026 (0..=*furthest).map(|d| d.to_string()).collect(),
1027 level.clone(),
1028 )
1029 } else {
1030 return None;
1031 };
1032 let mut counts = vec![0u32; names.len()];
1033 let mut missing = 0;
1034 for &c in &codes {
1035 match counts.get_mut(c as usize) {
1036 Some(n) => *n += 1,
1037 None => missing += 1,
1038 }
1039 }
1040 Some(ColorBy {
1041 by: by.to_string(),
1042 values: names,
1043 counts,
1044 codes,
1045 missing,
1046 })
1047}
1048
1049pub const LABEL: &str = "label";
1051
1052async fn property_graph_indexed(
1055 ctx: &SessionContext,
1056 graph: &PropertyGraph,
1057 max_edges: usize,
1058) -> Result<(EdgeList, NodeIndex)> {
1059 let state = ctx.state();
1060 let mut vertices = Vec::new();
1061 for v in &graph.vertex_tables {
1062 let batches = scan_columns(ctx, graph, &v.table, &[v.key.as_str()]).await?;
1063 vertices.extend(batches.iter().map(|b| Arc::clone(b.column(0))));
1064 }
1065 let mut edges = Vec::new();
1066 for e in &graph.edge_tables {
1067 let def = GraphDef {
1068 name: graph.name.clone(),
1069 edges: e.clone(),
1070 vertices: None,
1071 };
1072 let plan = edges_plan(&state, &def).await?;
1073 let batches = DataFrame::new(state.clone(), plan)
1074 .select_columns(&[e.source.as_str(), e.destination.as_str()])?
1075 .collect()
1076 .await?;
1077 edges.extend(
1078 batches
1079 .iter()
1080 .map(|b| (Arc::clone(b.column(0)), Arc::clone(b.column(1)))),
1081 );
1082 }
1083 if graph.edge_tables.is_empty() {
1084 return plan_err(format!(
1085 "graph '{}' has no edge tables: there are no edges to draw",
1086 graph.name
1087 ));
1088 }
1089 build_within(&vertices, &edges, max_edges)
1090}
1091
1092pub(crate) async fn scan_columns(
1094 ctx: &SessionContext,
1095 graph: &PropertyGraph,
1096 table: &TableReference,
1097 columns: &[&str],
1098) -> Result<Vec<RecordBatch>> {
1099 let state = ctx.state();
1100 let provider = graph_table(&state, &graph.name, table).await?;
1101 let plan =
1102 LogicalPlanBuilder::scan(table.clone(), provider_as_source(provider), None)?.build()?;
1103 DataFrame::new(state.clone(), plan)
1104 .select_columns(columns)?
1105 .collect()
1106 .await
1107}
1108
1109fn key_type_of(key_type: &DataType, ids: &[String]) -> KeyType {
1112 let fits = match key_type {
1113 DataType::Int8
1114 | DataType::Int16
1115 | DataType::Int32
1116 | DataType::Int64
1117 | DataType::UInt8
1118 | DataType::UInt16
1119 | DataType::UInt32 => true,
1120 DataType::UInt64 => ids.iter().all(|id| id.parse::<i64>().is_ok()),
1122 _ => false,
1123 };
1124 if fits {
1125 KeyType::Int
1126 } else {
1127 KeyType::Text
1128 }
1129}
1130
1131fn to_view(
1135 edges: EdgeList,
1136 key_type: &DataType,
1137 graph: Option<String>,
1138 provenance: Provenance,
1139) -> Result<GraphView> {
1140 let model = |e: ursa_viz::model::ModelError| {
1141 DataFusionError::Plan(format!("the graph cannot be drawn: {e}"))
1142 };
1143 let EdgeList {
1144 n,
1145 src,
1146 dst,
1147 ids,
1148 skipped,
1149 size,
1150 color,
1151 mut labels,
1152 node_label,
1153 mut edge_labels,
1154 edge_label,
1155 edge_rows,
1156 node_columns,
1157 edge_columns,
1158 paths,
1159 seeds,
1160 level,
1161 layout,
1162 } = edges;
1163 if labels.is_empty() {
1164 labels.push(String::new());
1165 }
1166 if edge_labels.is_empty() {
1167 edge_labels.push(String::new());
1168 }
1169 let key = key_type_of(key_type, &ids);
1170 let nodes = NodeBatch {
1171 labels: if node_label.is_empty() {
1172 vec![0; n as usize]
1173 } else {
1174 node_label
1175 },
1176 keys: ids.iter().collect::<Strings>(),
1177 ..NodeBatch::default()
1178 };
1179 drop(ids);
1180 let mut batch = EdgeBatch::of_label(0, src, dst);
1181 if !edge_label.is_empty() {
1182 batch.labels = edge_label;
1183 }
1184 batch.rows = edge_rows;
1185 let mut ops: Vec<Op> = labels
1186 .into_iter()
1187 .map(|name| Op::AddNodeLabel(NodeLabel::new(name, key)))
1188 .collect();
1189 ops.extend(edge_labels.into_iter().map(Op::AddEdgeLabel));
1190 ops.push(Op::AddNodes(nodes));
1191 ops.push(Op::AddEdges(batch));
1192 let base = GraphDelta::new(ops);
1193 let mut result = GraphResult::build(graph, provenance, &base).map_err(model)?;
1194 drop(base);
1195
1196 let mut encodings = Encodings {
1197 layout,
1198 ..Encodings::default()
1199 };
1200 let mut columns: Vec<(Target, ModelColumn)> = Vec::new();
1201 columns.extend(node_columns.into_iter().map(|c| (Target::Nodes, c)));
1202 columns.extend(edge_columns.into_iter().map(|c| (Target::Edges, c)));
1203 let taken = |columns: &[(Target, ModelColumn)], name: &str| {
1205 columns
1206 .iter()
1207 .any(|(t, c)| *t == Target::Nodes && c.name == name)
1208 };
1209 if let Some(size) = size {
1210 let name = if taken(&columns, &size.by) {
1211 format!("{}{SIZE_SUFFIX}", size.by)
1212 } else {
1213 size.by
1214 };
1215 encodings.size_by = Some(name.clone());
1216 columns.push((
1217 Target::Nodes,
1218 ModelColumn::new(name, Some(Role::Metric), Values::F32(size.values)),
1219 ));
1220 }
1221 if let Some(color) = color {
1222 let name = if taken(&columns, &color.by) {
1223 format!("{}{COLOR_SUFFIX}", color.by)
1224 } else {
1225 color.by
1226 };
1227 encodings.color_by = Some(name.clone());
1228 columns.push((
1229 Target::Nodes,
1230 ModelColumn::new(
1231 name,
1232 Some(Role::Category),
1233 Values::Dict {
1234 values: color.values.iter().collect(),
1235 codes: color.codes,
1236 },
1237 ),
1238 ));
1239 }
1240 for (target, column) in columns {
1241 let op = result.set_column_op(target, column);
1242 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
1243 }
1244 let highlights = Highlights {
1245 paths,
1246 seeds,
1247 distance: level,
1248 };
1249 if !highlights.is_empty() {
1250 let op = result.set_highlights_op(highlights);
1251 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
1252 }
1253 if encodings != Encodings::default() {
1254 let op = result.set_encodings_op(encodings);
1255 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
1256 }
1257 Ok(GraphView {
1258 result,
1259 skipped,
1260 positions: None,
1261 })
1262}