Skip to main content

ursa_engine/graph/view/
inspect.rs

1//! What a graph's tables say of one node or one edge of a drawing: the
2//! inspector's rows (design §4, #444).
3//!
4//! A drawing's node is a key of a vertex table, and its edge a row of an
5//! edge table, when the drawing names a property graph. [`inspect`] reads
6//! that row with one query by key:
7//!
8//! - **a node:** `SELECT * FROM members WHERE id = 33`, on the vertex table
9//!   its label names. A drawing with one label `""` (`.graph NAME`, a plain
10//!   result on a graph) reads the graph's vertex tables in turn, and gives
11//!   the first that has the key.
12//! - **an edge:** `SELECT * FROM ties WHERE src = 0 AND dst = 33`, the rows
13//!   of the edge table between its two ends. Where several rows join them
14//!   (parallel edges) and the drawing knows the edge's row number, that row
15//!   alone is read (`LIMIT 1 OFFSET row`), when the table is read as one
16//!   partition, as it is in the browser: there the scan's order is the row
17//!   numbers'. Otherwise all the rows between the ends are given, and
18//!   [`Inspected::note`] says so. An edge with no row number may be drawn
19//!   against the way the table stores it (a path's steps are), so its rows
20//!   are looked for both ways.
21//!
22//! The queries are built as plans, not as text, so a table that is a file
23//! path, and any name, reads the same; [`Inspected::sql`] is the query as a
24//! user would type it. Nothing here changes the session or its last result.
25//!
26//! [`graph_neighbours`] is how many neighbours a node has in the whole graph,
27//! for "9 drawn, 17 neighbours in karate".
28
29use datafusion::arrow::array::{Array, AsArray, RecordBatch};
30use datafusion::arrow::compute::cast;
31use datafusion::arrow::datatypes::{DataType, UInt64Type};
32use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
33use datafusion::common::TableReference;
34use datafusion::dataframe::DataFrame;
35use datafusion::datasource::provider_as_source;
36use datafusion::error::Result;
37use datafusion::logical_expr::{Expr, LogicalPlanBuilder};
38use datafusion::physical_plan::ExecutionPlanProperties;
39use datafusion::prelude::{ident, lit, SessionContext};
40use ursa_viz::model::{GraphResult, KeyType};
41
42use super::{plan_err, RunSql};
43use crate::graph::schema::graph_table;
44use crate::graph::{registry_of, PropertyGraph};
45
46/// The most rows given for one edge: the edges between two nodes, when the
47/// drawing cannot say which of them it drew.
48pub const MAX_ROWS: usize = 20;
49
50/// The most characters of one value; a longer one ends with `…`.
51pub const MAX_VALUE_CHARS: usize = 4096;
52
53/// What to inspect: a node or an edge of the drawing, by its index, with the
54/// keys the asker shows for it. The keys are checked against the drawing, so
55/// an asker whose picture is not the session's is told, not shown another
56/// node's row.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Inspect<'a> {
59    Node {
60        node: u32,
61        key: &'a str,
62    },
63    Edge {
64        edge: u32,
65        src: &'a str,
66        dst: &'a str,
67    },
68}
69
70/// A column of an inspected row.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct InspectedColumn {
73    pub name: String,
74    /// Whether its values are numbers: what `SIZE BY` can read.
75    pub numeric: bool,
76}
77
78/// The rows the graph's tables have for a node or an edge.
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
80pub struct Inspected {
81    /// The table read: the vertex or edge table's element name. `None` when
82    /// there is none to read ([`Self::note`] says why).
83    pub table: Option<String>,
84    /// The query, as a user would type it.
85    pub sql: Option<String>,
86    pub columns: Vec<InspectedColumn>,
87    /// Each row's values as the shell prints them, `None` for NULL. One row
88    /// for a node; for an edge, one, or every row between its ends.
89    pub rows: Vec<Vec<Option<String>>>,
90    /// An edge's row number in its table, where the drawing knows it.
91    pub row: Option<u64>,
92    /// What a reader should know: why there is no row, or that the rows are
93    /// several edges'.
94    pub note: Option<String>,
95}
96
97impl Inspected {
98    fn said(note: impl Into<String>) -> Inspected {
99        Inspected {
100            note: Some(note.into()),
101            ..Inspected::default()
102        }
103    }
104}
105
106/// `name` as SQL reads an identifier: bare when it is a plain lower-case
107/// name, else quoted.
108fn name(name: &str) -> String {
109    let plain = name
110        .chars()
111        .enumerate()
112        .all(|(i, c)| c == '_' || c.is_ascii_lowercase() || (i > 0 && c.is_ascii_digit()));
113    if plain && !name.is_empty() {
114        name.to_string()
115    } else {
116        format!("\"{}\"", name.replace('"', "\"\""))
117    }
118}
119
120/// `table` as a query names it: its name, or a file path as a string.
121fn table_name(ctx: &SessionContext, graph: &PropertyGraph, table: &TableReference) -> String {
122    if registry_of(ctx).file_table(&graph.name, table).is_some() {
123        format!("'{}'", table.table().replace('\'', "''"))
124    } else {
125        match table.schema() {
126            Some(schema) => format!("{}.{}", name(schema), name(table.table())),
127            None => name(table.table()),
128        }
129    }
130}
131
132/// `key` as a literal, to compare and to print.
133fn literal(key: &str, ty: KeyType) -> (Expr, String) {
134    match (ty, key.parse::<i64>()) {
135        (KeyType::Int, Ok(n)) => (lit(n), key.to_string()),
136        _ => (lit(key), format!("'{}'", key.replace('\'', "''"))),
137    }
138}
139
140/// Every row of `table` that `filter` keeps, up to `limit`, after `skip`.
141async fn read(
142    ctx: &SessionContext,
143    graph: &PropertyGraph,
144    table: &TableReference,
145    filter: Option<Expr>,
146    skip: usize,
147    limit: usize,
148) -> Result<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)> {
149    let frame = scan(ctx, graph, table).await?;
150    let frame = match filter {
151        Some(filter) => frame.filter(filter)?,
152        None => frame,
153    };
154    let columns = frame
155        .schema()
156        .fields()
157        .iter()
158        .map(|f| InspectedColumn {
159            name: f.name().clone(),
160            numeric: f.data_type().is_numeric(),
161        })
162        .collect();
163    let batches = frame.limit(skip, Some(limit))?.collect().await?;
164    Ok((columns, rows_of(&batches)?))
165}
166
167async fn scan(
168    ctx: &SessionContext,
169    graph: &PropertyGraph,
170    table: &TableReference,
171) -> Result<DataFrame> {
172    let state = ctx.state();
173    let provider = graph_table(&state, &graph.name, table).await?;
174    let plan =
175        LogicalPlanBuilder::scan(table.clone(), provider_as_source(provider), None)?.build()?;
176    Ok(DataFrame::new(state, plan))
177}
178
179/// The batches' rows as text, as the shell prints a value.
180fn rows_of(batches: &[RecordBatch]) -> Result<Vec<Vec<Option<String>>>> {
181    let options = FormatOptions::default();
182    let mut rows = Vec::new();
183    for batch in batches {
184        let shown = batch
185            .columns()
186            .iter()
187            .map(|c| ArrayFormatter::try_new(c.as_ref(), &options))
188            .collect::<std::result::Result<Vec<_>, _>>()?;
189        for i in 0..batch.num_rows() {
190            let row = batch
191                .columns()
192                .iter()
193                .zip(&shown)
194                .map(|(column, shown)| {
195                    if column.is_null(i) {
196                        return None;
197                    }
198                    let mut text = shown.value(i).to_string();
199                    if let Some((at, _)) = text.char_indices().nth(MAX_VALUE_CHARS) {
200                        text.truncate(at);
201                        text.push('…');
202                    }
203                    Some(text)
204                })
205                .collect();
206            rows.push(row);
207        }
208    }
209    Ok(rows)
210}
211
212/// The property graph `result` names, or why there is none to read.
213fn graph_of(
214    ctx: &SessionContext,
215    result: &GraphResult,
216) -> std::result::Result<std::sync::Arc<PropertyGraph>, String> {
217    let Some(graph) = result.graph() else {
218        return Err(
219            "this drawing is not of a property graph, so there is no table row to show; draw \
220             a graph's (.graph NAME) or a query's on one"
221                .into(),
222        );
223    };
224    registry_of(ctx)
225        .get(graph)
226        .ok_or_else(|| format!("the graph '{graph}' is gone, and its tables with it"))
227}
228
229/// The row of the graph's tables for one node or edge of `result`: see the
230/// [module](self). A drawing with no table to read gives no rows and a
231/// [`note`](Inspected::note), not an error; an index or a key that is not the
232/// drawing's is an error.
233pub async fn inspect(
234    ctx: &SessionContext,
235    result: &GraphResult,
236    what: Inspect<'_>,
237) -> Result<Inspected> {
238    match what {
239        Inspect::Node { node, key } => {
240            let at = node as usize;
241            if at >= result.n_nodes() || result.node_keys().get(at) != key {
242                return plan_err(format!(
243                    "the drawing has changed: its node {node} is not '{key}'; draw it again \
244                     (.graph)"
245                ));
246            }
247            inspect_node(ctx, result, at).await
248        }
249        Inspect::Edge { edge, src, dst } => {
250            let at = edge as usize;
251            let keys = result.node_keys();
252            if at >= result.n_edges()
253                || keys.get(result.src()[at] as usize) != src
254                || keys.get(result.dst()[at] as usize) != dst
255            {
256                return plan_err(format!(
257                    "the drawing has changed: its edge {edge} does not join '{src}' and \
258                     '{dst}'; draw it again (.graph)"
259                ));
260            }
261            inspect_edge(ctx, result, at).await
262        }
263    }
264}
265
266async fn inspect_node(
267    ctx: &SessionContext,
268    result: &GraphResult,
269    node: usize,
270) -> Result<Inspected> {
271    let graph = match graph_of(ctx, result) {
272        Ok(graph) => graph,
273        Err(note) => return Ok(Inspected::said(note)),
274    };
275    let label = &result.node_labels()[result.node_label()[node] as usize];
276    let key = result.node_keys().get(node);
277    // The label's vertex table; with no label, each of the graph's in turn.
278    let tables: Vec<_> = graph
279        .vertex_tables
280        .iter()
281        .filter(|v| label.name.is_empty() || v.name == label.name)
282        .collect();
283    if tables.is_empty() {
284        return Ok(Inspected::said(if graph.vertex_tables.is_empty() {
285            format!(
286                "the graph {} has no vertex tables: a node is its key and its edges",
287                graph.name
288            )
289        } else {
290            format!(
291                "the graph {} has no vertex table '{}'",
292                graph.name, label.name
293            )
294        }));
295    }
296    let mut first = None;
297    for v in tables {
298        let (value, shown) = literal(key, label.key);
299        let (columns, rows) =
300            read(ctx, &graph, &v.table, Some(ident(&v.key).eq(value)), 0, 1).await?;
301        let found = Inspected {
302            table: Some(v.name.clone()),
303            sql: Some(format!(
304                "SELECT * FROM {} WHERE {} = {shown}",
305                table_name(ctx, &graph, &v.table),
306                name(&v.key)
307            )),
308            columns,
309            rows,
310            row: None,
311            note: None,
312        };
313        if !found.rows.is_empty() {
314            return Ok(found);
315        }
316        first.get_or_insert(found);
317    }
318    let mut none = first.expect("there is a table");
319    none.note = Some(format!(
320        "no row of {} has the key {key}: the node is named only by an edge",
321        none.table.as_deref().unwrap_or_default()
322    ));
323    Ok(none)
324}
325
326async fn inspect_edge(
327    ctx: &SessionContext,
328    result: &GraphResult,
329    edge: usize,
330) -> Result<Inspected> {
331    let graph = match graph_of(ctx, result) {
332        Ok(graph) => graph,
333        Err(note) => return Ok(Inspected::said(note)),
334    };
335    let label = &result.edge_labels()[result.edge_label()[edge] as usize];
336    let row = result.edge_row(edge);
337    let end = |node: u32| {
338        let at = node as usize;
339        let ty = result.node_labels()[result.node_label()[at] as usize].key;
340        literal(result.node_keys().get(at), ty)
341    };
342    let (s, s_shown) = end(result.src()[edge]);
343    let (d, d_shown) = end(result.dst()[edge]);
344    let tables: Vec<_> = graph
345        .edge_tables
346        .iter()
347        .filter(|e| label.is_empty() || &e.name == label)
348        .collect();
349    if tables.is_empty() {
350        return Ok(Inspected::said(format!(
351            "the graph {} has no edge table '{label}'",
352            graph.name
353        )));
354    }
355    let mut first = None;
356    for e in tables {
357        let (source, destination) = (ident(&e.source), ident(&e.destination));
358        let table = table_name(ctx, &graph, &e.table);
359        let (from, to) = (name(&e.source), name(&e.destination));
360        let mut filter = source
361            .clone()
362            .eq(s.clone())
363            .and(destination.clone().eq(d.clone()));
364        let mut sql =
365            format!("SELECT * FROM {table} WHERE {from} = {s_shown} AND {to} = {d_shown}");
366        // With no row number, the drawing may have it the other way round.
367        if row.is_none() && s_shown != d_shown {
368            filter = filter.or(source.eq(d.clone()).and(destination.eq(s.clone())));
369            sql = format!(
370                "SELECT * FROM {table} WHERE ({from} = {s_shown} AND {to} = {d_shown}) OR \
371                 ({from} = {d_shown} AND {to} = {s_shown})"
372            );
373        }
374        let (columns, rows) = read(ctx, &graph, &e.table, Some(filter), 0, MAX_ROWS + 1).await?;
375        let mut found = Inspected {
376            table: Some(e.name.clone()),
377            sql: Some(sql),
378            columns,
379            rows,
380            row,
381            note: None,
382        };
383        if found.rows.len() > 1 {
384            // Parallel edges: the one row, where its number finds it.
385            let one = match row {
386                Some(row) if one_partition(ctx, &graph, &e.table).await? => {
387                    let (_, rows) = read(ctx, &graph, &e.table, None, row as usize, 1).await?;
388                    (!rows.is_empty()).then_some((row, rows))
389                }
390                _ => None,
391            };
392            match one {
393                Some((row, rows)) => {
394                    found.rows = rows;
395                    found.sql = Some(format!("SELECT * FROM {table} LIMIT 1 OFFSET {row}"));
396                }
397                None => {
398                    let more = found.rows.len() > MAX_ROWS;
399                    found.rows.truncate(MAX_ROWS);
400                    found.note = Some(format!(
401                        "{}{} rows of {} join these two nodes; the drawing does not say which \
402                         this edge is",
403                        if more { "more than " } else { "" },
404                        found.rows.len(),
405                        e.name
406                    ));
407                }
408            }
409        }
410        if !found.rows.is_empty() {
411            return Ok(found);
412        }
413        first.get_or_insert(found);
414    }
415    let mut none = first.expect("there is a table");
416    none.note = Some(format!(
417        "no row of {} joins these two nodes: the edge is not the graph's (a query made it)",
418        none.table.as_deref().unwrap_or_default()
419    ));
420    Ok(none)
421}
422
423/// Whether `table` is read as one partition: then its rows come in the order
424/// the edge index numbered them.
425async fn one_partition(
426    ctx: &SessionContext,
427    graph: &PropertyGraph,
428    table: &TableReference,
429) -> Result<bool> {
430    let plan = scan(ctx, graph, table)
431        .await?
432        .create_physical_plan()
433        .await?;
434    Ok(plan.output_partitioning().partition_count() == 1)
435}
436
437/// How many neighbours node `node` has in the whole graph `result` names,
438/// whichever way the edges run: `SELECT count(*) FROM hop(G, seeds => [key],
439/// steps => 1, direction => 'both')`, run by `sql`. It reads the node's edges
440/// from the graph's index, not every edge, so it costs what the node's degree
441/// does. On a graph with no parallel edges and no loops it is the node's
442/// degree. `None` when the drawing names no graph.
443pub async fn graph_neighbours(
444    ctx: &SessionContext,
445    sql: &dyn RunSql,
446    result: &GraphResult,
447    node: u32,
448) -> Result<Option<u64>> {
449    let at = node as usize;
450    let Some(graph) = result.graph() else {
451        return Ok(None);
452    };
453    if at >= result.n_nodes() {
454        return plan_err(format!("the drawing has no node {node}"));
455    }
456    let ty = result.node_labels()[result.node_label()[at] as usize].key;
457    let (_, key) = literal(result.node_keys().get(at), ty);
458    let (_, batches) = sql
459        .run(
460            ctx,
461            &format!(
462                "SELECT count(*) FROM hop(\"{}\", seeds => [{key}], steps => 1, direction => 'both')",
463                graph.replace('"', "\"\"")
464            ),
465        )
466        .await?;
467    for batch in &batches {
468        if batch.num_rows() > 0 {
469            let count = cast(batch.column(0), &DataType::UInt64)?;
470            let count = count.as_primitive::<UInt64Type>();
471            return Ok(count.is_valid(0).then(|| count.value(0)));
472        }
473    }
474    Ok(None)
475}