Skip to main content

ursa_engine/graph/view/
mod.rs

1//! A result as a graph (design §3 and §6, #425): what `.graph` draws, as a
2//! [`GraphResult`] any front end can show: the browser shell, and the CLI
3//! and the notebook after it.
4//!
5//! [`of_command`] reads `.graph`'s text, `[SOURCE] [ON graph] [AS …]
6//! [NODES (query)] [SIZE BY x] [COLOR BY y] [LAYOUT l] [POSITIONS (query)]`:
7//!
8//! 1. [`clauses`] splits the text into its source and its [`Style`].
9//! 2. A [`Source`] is found: the last result, a query's, a table's rows, or a
10//!    property graph.
11//! 3. [`rules`] chooses the result → graph rule that draws it (design §3,
12//!    #433), by what its columns are: their `ursa.*` metadata, or else their
13//!    names and types. Rows are paths, a hop's rings, edges, a pattern's
14//!    matches, or nodes; or they are not a graph, and the error says what
15//!    would be. A property graph is its edge tables and its vertex tables'
16//!    keys, so a node with no edges is drawn too. [`interpret`] is this step
17//!    alone, on a result. `AS …` is rule 0 (#434): it names the shape and
18//!    its columns, and nothing is inferred. `ON graph` names the graph the
19//!    ids belong to, and `LAYOUT` the layout, whatever the rule chose.
20//! 4. Ids become dense node indexes `0..n`, in the order they are first
21//!    seen, so the same rows always give the same graph.
22//! 5. `SIZE BY` and `COLOR BY` each become a node column, which the result's
23//!    encodings name.
24//! 6. `POSITIONS (query)` gives the result positions ([`positions`], #502):
25//!    a front end draws it there and runs no layout.
26//!
27//! A drawing has at most `ursa.graph_max_edges` edges ([`MAX_EDGES`] by
28//! default): more is refused, with a message that names the setting.
29//!
30//! The result's provenance says the SQL it came from, the rule that drew
31//! it, the columns the rule read and what it left out ([`drawn_as`] is the
32//! sentence a status line shows). Its highlights are the paths, the seeds
33//! and each node's level, for the view to draw. [`GraphView::legend`] is the
34//! legend of `COLOR BY`.
35//!
36//! [`Session`] is the explore session of a drawing (design §4, #440): the
37//! commands that change it (`.expand`, `.hide`, `.show`, `.undo`, `.redo`),
38//! each as SQL and a [`GraphDelta`] for the view. [`find`] is its search
39//! (#445): the nodes that match a text or a condition, for the view to
40//! select.
41//!
42//! This module runs SQL text (a source that is a query, `NODES (…)`, the
43//! algorithms of `SIZE BY pagerank`), and the SQL front end is `ursa-sql`,
44//! which depends on this crate. So the caller hands in how to run it, as a
45//! [`RunSql`]: `ursa_sql::Sql` for Ursa's whole dialect, or [`DataFusionSql`]
46//! for DataFusion's alone.
47
48use 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};
89/// A place per node: what [`GraphView::positions`] holds.
90pub use ursa_viz::model::Positions;
91
92/// The most edges a view draws unless `ursa.graph_max_edges` says otherwise
93/// (#502): what a desktop browser draws within its frame budget, and 40 MB
94/// of node indexes to hand it. A front end on a phone sets less.
95pub const MAX_EDGES: usize = 5_000_000;
96/// The most nodes, for a property graph whose vertex tables are large.
97pub const MAX_NODES: usize = 4_000_000;
98/// The most categories `COLOR BY` colours; the rest are drawn as "other". A
99/// front end's palette has as many colours, then other's.
100pub const MAX_CATEGORIES: usize = 8;
101
102/// What the colour column is called when `SIZE BY` and `COLOR BY` name the
103/// same thing: the name, then this. A result's node columns have distinct
104/// names, and the size column has the name itself. [`Legend::by`] is the
105/// name without it.
106pub const COLOR_SUFFIX: &str = " (colour)";
107/// What the size column is called when a column of the rule's (a hop's
108/// `distance`, a pattern's property) already has `SIZE BY`'s name.
109pub 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
115/// A result's schema and its rows.
116pub type Rows = (SchemaRef, Vec<RecordBatch>);
117
118/// How SQL text is run on a session: every statement, giving the rows of the
119/// last.
120#[async_trait]
121pub trait RunSql: Send + Sync {
122    async fn run(&self, ctx: &SessionContext, text: &str) -> Result<Rows>;
123}
124
125/// [`RunSql`] by `SessionContext::sql`: DataFusion's dialect and one
126/// statement, without Ursa's own (`GRAPH_TABLE`, `FROM`-first queries,
127/// `CREATE PROPERTY GRAPH`). A front end with `ursa-sql` uses `ursa_sql::Sql`.
128#[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
140/// `n` with thousands separators: 2,000,000.
141pub(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
153/// The `SET` that lets a drawing of `edges` edges through: the limit
154/// raised to the next million.
155pub(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
160/// What `.graph` draws: a property graph, or rows.
161pub enum Source {
162    Graph(Arc<PropertyGraph>),
163    Rows {
164        schema: SchemaRef,
165        batches: Vec<RecordBatch>,
166        /// The SQL the rows are the result of, if known, for the provenance.
167        sql: Option<String>,
168    },
169}
170
171impl Source {
172    /// What `.graph TEXT` names: the property graph TEXT names, a table's
173    /// rows, or a query's result (its last statement's).
174    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    /// Rows whose SQL is not known: the shell's last result.
203    pub fn of_rows((schema, batches): Rows) -> Source {
204        Source::Rows {
205            schema,
206            batches,
207            sql: None,
208        }
209    }
210}
211
212/// A graph to draw, and what was left out of it.
213#[derive(Debug, Clone, PartialEq)]
214pub struct GraphView {
215    /// The nodes, the edges, and the columns the rule and `SIZE BY` and
216    /// `COLOR BY` made, which its encodings name. A property graph's nodes
217    /// and a plain table's have the one label `""`, and their edges' rows
218    /// are not known; a rule that reads metadata names the vertex and edge
219    /// tables, and gives the rows it knows.
220    pub result: GraphResult,
221    /// Rows left out because an endpoint is NULL.
222    pub skipped: usize,
223    /// Where `POSITIONS (query)` puts each node (#502), one place per node
224    /// of `result`: a front end draws them there and runs no layout. They
225    /// are beside the result, not in it, because an explore session's deltas
226    /// are of a result without positions: a view keeps where its nodes are,
227    /// and moves them as the drawing grows. [`GraphView::placed`] is the
228    /// result with them, for a front end that only shows it.
229    pub positions: Option<Positions>,
230}
231
232impl GraphView {
233    /// The result with `POSITIONS`'s positions in it (UGR's `nodes.x` and
234    /// `nodes.y`): a drawing that opens drawn. The result as it is when
235    /// there are none.
236    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    /// The legend of `COLOR BY`, if it was asked.
248    pub fn legend(&self) -> Option<Legend> {
249        Legend::of(&self.result)
250    }
251
252    /// What the result was drawn as, for a status line (see [`drawn_as`]).
253    pub fn drawn_as(&self) -> String {
254        drawn_as(&self.result)
255    }
256}
257
258/// What `result` was drawn as, by its provenance: the rule, the graph, the
259/// columns read, and the rule's notes. `a path on karate (members, ties)`;
260/// `nodes of karate (id, pagerank, community)`; `edges (src, dst)`; `the
261/// graph karate`. A status line says `drawn as` and then this. Empty when
262/// the result names no rule. (The page's `graph-data.js` says the same.)
263pub 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/// `COLOR BY`'s legend: the categories coloured, the largest first, and the
296/// nodes that are in none of them.
297#[derive(Debug, Clone, PartialEq, Eq)]
298pub struct Legend {
299    /// What the nodes are coloured by, as typed.
300    pub by: String,
301    /// The categories coloured, at most [`MAX_CATEGORIES`], by colour index:
302    /// their values as the shell prints them.
303    pub labels: Vec<String>,
304    /// How many nodes each has.
305    pub counts: Vec<u32>,
306    /// Nodes in the categories past the coloured ones.
307    pub other: u32,
308    /// Nodes with no value (NULL, or none given).
309    pub missing: u32,
310}
311
312impl Legend {
313    /// The legend of the column `result`'s encodings colour by: a dictionary
314    /// column whose values are in order of rank, as [`of_command`] writes it.
315    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
343/// What `.graph TEXT` draws: `[SOURCE] [NODES (query)] [SIZE BY x]
344/// [COLOR BY y]`. With no source, it is `last`: the shell's last result.
345pub 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
366/// The graph `source` draws, styled as `style` says (`SIZE BY`, `COLOR BY`,
367/// `NODES`).
368pub 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            // A property graph is drawn whole: there is nothing to read.
385            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            // The nodes are where the query puts them, whatever layout the
424            // rule would have asked for.
425            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
456/// What the result → graph rules (design §3, [`rules`]) make of a result:
457/// its rows as a graph, drawn by the first rule that matches, with that
458/// rule's defaults. This is `.graph` after a query, with no clauses.
459///
460/// Rules 2 and 5 read the graph's edges among the result's nodes
461/// (`induced_edges`), from the graph the columns say they are from
462/// (`ursa.graph`), or else the session's only property graph.
463pub 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
472/// [`interpret`] with `.graph`'s clauses (`style`): `AS …` in place of the
473/// rules (rule 0), `ON graph` for the graph the ids belong to, `LAYOUT`,
474/// and `SIZE BY`, `COLOR BY` and `NODES`.
475pub 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
486/// `LAYOUT`: the layout of `drawing`, whatever its rule chose. Rings and
487/// layers place each node by its level (a hop's distance, a path's step), so
488/// a drawing without one cannot have them.
489fn 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
516/// A drawing before its style: the nodes and edges a rule read, and what
517/// `SIZE BY` and `COLOR BY` may use.
518struct Drawing {
519    edges: EdgeList,
520    index: NodeIndex,
521    rule: Rule,
522    /// The graph the nodes belong to, if known: what an algorithm runs on.
523    graph: Option<Arc<PropertyGraph>>,
524    /// The result's own rows, when each is a node (rule 5).
525    own: Option<NodeValues>,
526    /// The rule's defaults for `SIZE BY` and `COLOR BY`.
527    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
549/// The graph a result's nodes belong to: the one `ON graph` names (`on`),
550/// else the one its columns name, or else (`or_the_only`) the session's only
551/// property graph.
552fn 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(&registry, 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
608/// The drawing of a result's rows, by the rule that matches them.
609async 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    // Rule 0: what `AS …` says; else the first rule that matches.
618    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    // One batch, for the rules that read rows by position.
625    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    // The session's only graph is a guess until its edges are read: ids
651    // that are not its own are of no graph.
652    let guessed = reading.graph.is_none() && style.on.is_none();
653    // The label of each key column, for the nodes' properties.
654    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                // Two vertex tables: a node is its table and its key.
660                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                // The rows' own edges: each seed's to the nodes one step away.
740                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    // The properties of the pattern's variables, on their nodes.
793    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
829/// The model's role of column `column`, if its metadata says one the model
830/// has.
831fn 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
842/// Add `graph`'s edges among the nodes of `edges` (`induced_edges`), each
843/// with its row in the edge table. `Err` says why they could not be read.
844async 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
918/// `SIZE BY` and `COLOR BY` on `drawing`: what `style` asks, or else the
919/// rule's defaults.
920async 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    // Where each name's values come from; the algorithms run together. A
940    // default that cannot be drawn is left out; what was asked for is an
941    // error.
942    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
1004/// What colours the nodes when nothing else does: a hop's distances, or the
1005/// vertex tables when there are several.
1006fn default_color(edges: &EdgeList) -> Option<ColorBy> {
1007    // Each node's group, and the groups' names, in their own order (not by
1008    // size: distance 0, then 1, then 2).
1009    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
1049/// What the nodes are coloured by when they are of several vertex tables.
1050pub const LABEL: &str = "label";
1051
1052/// The edges of `graph`: every edge table's source and destination columns,
1053/// and every vertex table's keys, so nodes with no edges are drawn too.
1054async 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
1092/// The columns `columns` of one of `graph`'s tables, every row.
1093pub(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
1109/// The type of the keys of a label whose ids were read as `key_type` and
1110/// print as `ids`: integers, where every one is an `i64` in decimal.
1111fn 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        // Past i64::MAX a key is text.
1121        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
1131/// `edges` as a [`GraphResult`]: its node and edge labels (one of each,
1132/// `""`, when the rule names none), the node columns of the rule and of
1133/// `SIZE BY` and `COLOR BY`, the highlights, and the encodings.
1134fn 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    // A column of the rule's keeps its name; SIZE BY's and COLOR BY's give way.
1204    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}