use datafusion::arrow::array::{Array, AsArray, RecordBatch};
use datafusion::arrow::compute::cast;
use datafusion::arrow::datatypes::{DataType, UInt64Type};
use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
use datafusion::common::TableReference;
use datafusion::dataframe::DataFrame;
use datafusion::datasource::provider_as_source;
use datafusion::error::Result;
use datafusion::logical_expr::{Expr, LogicalPlanBuilder};
use datafusion::prelude::{ident, lit, SessionContext};
use ursa_viz::model::{GraphResult, KeyType};
use super::rows::take;
use super::{plan_err, RunSql};
use crate::graph::schema::graph_table;
use crate::graph::{registry_of, PropertyGraph};
pub const MAX_ROWS: usize = 20;
pub const MAX_VALUE_CHARS: usize = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Inspect<'a> {
Node {
node: u32,
key: &'a str,
},
Edge {
edge: u32,
src: &'a str,
dst: &'a str,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InspectedColumn {
pub name: String,
pub numeric: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Inspected {
pub table: Option<String>,
pub sql: Option<String>,
pub columns: Vec<InspectedColumn>,
pub rows: Vec<Vec<Option<String>>>,
pub row: Option<u64>,
pub note: Option<String>,
pub indexed: bool,
}
impl Inspected {
fn said(note: impl Into<String>) -> Inspected {
Inspected {
note: Some(note.into()),
..Inspected::default()
}
}
}
fn name(name: &str) -> String {
let plain = name
.chars()
.enumerate()
.all(|(i, c)| c == '_' || c.is_ascii_lowercase() || (i > 0 && c.is_ascii_digit()));
if plain && !name.is_empty() {
name.to_string()
} else {
format!("\"{}\"", name.replace('"', "\"\""))
}
}
fn table_name(ctx: &SessionContext, graph: &PropertyGraph, table: &TableReference) -> String {
if registry_of(ctx).file_table(&graph.name, table).is_some() {
format!("'{}'", table.table().replace('\'', "''"))
} else {
match table.schema() {
Some(schema) => format!("{}.{}", name(schema), name(table.table())),
None => name(table.table()),
}
}
}
fn literal(key: &str, ty: KeyType) -> (Expr, String) {
match (ty, key.parse::<i64>()) {
(KeyType::Int, Ok(n)) => (lit(n), key.to_string()),
_ => (lit(key), format!("'{}'", key.replace('\'', "''"))),
}
}
async fn read(
ctx: &SessionContext,
graph: &PropertyGraph,
table: &TableReference,
filter: Option<Expr>,
skip: usize,
limit: usize,
) -> Result<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)> {
let frame = scan(ctx, graph, table).await?;
let frame = match filter {
Some(filter) => frame.filter(filter)?,
None => frame,
};
let columns = columns_of(&frame);
let batches = frame.limit(skip, Some(limit))?.collect().await?;
Ok((columns, rows_of(&batches)?))
}
fn columns_of(frame: &DataFrame) -> Vec<InspectedColumn> {
frame
.schema()
.fields()
.iter()
.map(|f| InspectedColumn {
name: f.name().clone(),
numeric: f.data_type().is_numeric(),
})
.collect()
}
async fn read_rows(
ctx: &SessionContext,
graph: &PropertyGraph,
table: &TableReference,
rows: &[u64],
) -> Result<Option<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)>> {
let frame = scan(ctx, graph, table).await?;
let columns = columns_of(&frame);
match take(ctx, frame, rows).await? {
Some(taken) => Ok(Some((columns, rows_of(&taken)?))),
None => Ok(None),
}
}
async fn scan(
ctx: &SessionContext,
graph: &PropertyGraph,
table: &TableReference,
) -> Result<DataFrame> {
let state = ctx.state();
let provider = graph_table(&state, &graph.name, table).await?;
let plan =
LogicalPlanBuilder::scan(table.clone(), provider_as_source(provider), None)?.build()?;
Ok(DataFrame::new(state, plan))
}
fn rows_of(batches: &[RecordBatch]) -> Result<Vec<Vec<Option<String>>>> {
let options = FormatOptions::default();
let mut rows = Vec::new();
for batch in batches {
let shown = batch
.columns()
.iter()
.map(|c| ArrayFormatter::try_new(c.as_ref(), &options))
.collect::<std::result::Result<Vec<_>, _>>()?;
for i in 0..batch.num_rows() {
let row = batch
.columns()
.iter()
.zip(&shown)
.map(|(column, shown)| {
if column.is_null(i) {
return None;
}
let mut text = shown.value(i).to_string();
if let Some((at, _)) = text.char_indices().nth(MAX_VALUE_CHARS) {
text.truncate(at);
text.push('…');
}
Some(text)
})
.collect();
rows.push(row);
}
}
Ok(rows)
}
fn graph_of(
ctx: &SessionContext,
result: &GraphResult,
) -> std::result::Result<std::sync::Arc<PropertyGraph>, String> {
let Some(graph) = result.graph() else {
return Err(
"this drawing is not of a property graph, so there is no table row to show; draw \
a graph's (.graph NAME) or a query's on one"
.into(),
);
};
registry_of(ctx)
.get(graph)
.ok_or_else(|| format!("the graph '{graph}' is gone, and its tables with it"))
}
pub async fn inspect(
ctx: &SessionContext,
sql: &dyn RunSql,
result: &GraphResult,
what: Inspect<'_>,
) -> Result<Inspected> {
match what {
Inspect::Node { node, key } => {
let at = node as usize;
if at >= result.n_nodes() || result.node_keys().get(at) != key {
return plan_err(format!(
"the drawing has changed: its node {node} is not '{key}'; draw it again \
(.graph)"
));
}
inspect_node(ctx, result, at).await
}
Inspect::Edge { edge, src, dst } => {
let at = edge as usize;
let keys = result.node_keys();
if at >= result.n_edges()
|| keys.get(result.src()[at] as usize) != src
|| keys.get(result.dst()[at] as usize) != dst
{
return plan_err(format!(
"the drawing has changed: its edge {edge} does not join '{src}' and \
'{dst}'; draw it again (.graph)"
));
}
inspect_edge(ctx, sql, result, at).await
}
}
}
async fn inspect_node(
ctx: &SessionContext,
result: &GraphResult,
node: usize,
) -> Result<Inspected> {
let graph = match graph_of(ctx, result) {
Ok(graph) => graph,
Err(note) => return Ok(Inspected::said(note)),
};
if super::groups::is_group(result, node) {
return Ok(Inspected::said(format!(
"a group of {}'s nodes, not a row of its tables: its values are above, and .expand \
group:{} opens it",
graph.name,
result.node_keys().get(node)
)));
}
let label = &result.node_labels()[result.node_label()[node] as usize];
let key = result.node_keys().get(node);
let tables: Vec<_> = graph
.vertex_tables
.iter()
.filter(|v| label.name.is_empty() || v.name == label.name)
.collect();
if tables.is_empty() {
return Ok(Inspected::said(if graph.vertex_tables.is_empty() {
format!(
"the graph {} has no vertex tables: a node is its key and its edges",
graph.name
)
} else {
format!(
"the graph {} has no vertex table '{}'",
graph.name, label.name
)
}));
}
let mut first = None;
for v in tables {
let (value, shown) = literal(key, label.key);
let (columns, rows) =
read(ctx, &graph, &v.table, Some(ident(&v.key).eq(value)), 0, 1).await?;
let found = Inspected {
table: Some(v.name.clone()),
sql: Some(format!(
"SELECT * FROM {} WHERE {} = {shown}",
table_name(ctx, &graph, &v.table),
name(&v.key)
)),
columns,
rows,
row: None,
note: None,
indexed: false,
};
if !found.rows.is_empty() {
return Ok(found);
}
first.get_or_insert(found);
}
let mut none = first.expect("there is a table");
none.note = Some(format!(
"no row of {} has the key {key}: the node is named only by an edge",
none.table.as_deref().unwrap_or_default()
));
Ok(none)
}
async fn inspect_edge(
ctx: &SessionContext,
run: &dyn RunSql,
result: &GraphResult,
edge: usize,
) -> Result<Inspected> {
let graph = match graph_of(ctx, result) {
Ok(graph) => graph,
Err(note) => return Ok(Inspected::said(note)),
};
if super::groups::is_group(result, result.src()[edge] as usize) {
return Ok(Inspected::said(format!(
"the edges of {} between two groups, counted: not one row of its tables",
graph.name
)));
}
let label = &result.edge_labels()[result.edge_label()[edge] as usize];
let row = result.edge_row(edge);
let end = |node: u32| {
let at = node as usize;
let ty = result.node_labels()[result.node_label()[at] as usize].key;
(
result.node_keys().get(at),
literal(result.node_keys().get(at), ty),
)
};
let (s_key, (s, s_shown)) = end(result.src()[edge]);
let (d_key, (d, d_shown)) = end(result.dst()[edge]);
let tables: Vec<_> = graph
.edge_tables
.iter()
.filter(|e| label.is_empty() || &e.name == label)
.collect();
if tables.is_empty() {
return Ok(Inspected::said(format!(
"the graph {} has no edge table '{label}'",
graph.name
)));
}
let mut first = None;
for e in tables {
let (source, destination) = (ident(&e.source), ident(&e.destination));
let table = table_name(ctx, &graph, &e.table);
let (from, to) = (name(&e.source), name(&e.destination));
let mut filter = source
.clone()
.eq(s.clone())
.and(destination.clone().eq(d.clone()));
let mut sql =
format!("SELECT * FROM {table} WHERE {from} = {s_shown} AND {to} = {d_shown}");
let either_way = row.is_none() && s_shown != d_shown;
if either_way {
filter = filter.or(source.eq(d.clone()).and(destination.eq(s.clone())));
sql = format!(
"SELECT * FROM {table} WHERE ({from} = {s_shown} AND {to} = {d_shown}) OR \
({from} = {d_shown} AND {to} = {s_shown})"
);
}
let ends = Ends {
literals: [&s_shown, &d_shown],
keys: [s_key, d_key],
either_way,
};
let (numbers, (columns, rows)) = match between(ctx, run, &graph, e, &ends).await {
Some((numbers, found)) => (Some(numbers), found),
None => (
None,
read(ctx, &graph, &e.table, Some(filter), 0, MAX_ROWS + 1).await?,
),
};
let mut found = Inspected {
table: Some(e.name.clone()),
sql: Some(sql),
columns,
rows,
row,
note: None,
indexed: numbers.is_some(),
};
if found.rows.len() > 1 {
let among = |row: u64| numbers.as_ref()?.iter().position(|&n| n == row);
let one = match row {
Some(row) => match among(row) {
Some(i) => Some((row, vec![found.rows[i].clone()])),
None => read_rows(ctx, &graph, &e.table, &[row])
.await?
.filter(|(_, rows)| !rows.is_empty())
.map(|(_, rows)| (row, rows)),
},
None => None,
};
match one {
Some((row, rows)) => {
found.rows = rows;
found.sql = Some(format!("SELECT * FROM {table} LIMIT 1 OFFSET {row}"));
}
None => {
let more = found.rows.len() > MAX_ROWS;
found.rows.truncate(MAX_ROWS);
found.note = Some(format!(
"{}{} rows of {} join these two nodes; the drawing does not say which \
this edge is",
if more { "more than " } else { "" },
found.rows.len(),
e.name
));
}
}
}
if !found.rows.is_empty() {
return Ok(found);
}
first.get_or_insert(found);
}
let mut none = first.expect("there is a table");
none.note = Some(format!(
"no row of {} joins these two nodes: the edge is not the graph's (a query made it)",
none.table.as_deref().unwrap_or_default()
));
Ok(none)
}
struct Ends<'a> {
literals: [&'a str; 2],
keys: [&'a str; 2],
either_way: bool,
}
impl Ends<'_> {
fn joins(&self, src: Option<&str>, dst: Option<&str>) -> bool {
let [s, d] = self.keys.map(Some);
(src, dst) == (s, d) || (self.either_way && (src, dst) == (d, s))
}
}
async fn between(
ctx: &SessionContext,
run: &dyn RunSql,
graph: &PropertyGraph,
e: &crate::graph::EdgeTable,
ends: &Ends<'_>,
) -> Option<(Vec<u64>, (Vec<InspectedColumn>, Vec<Vec<Option<String>>>))> {
if graph.pair(None, None).ok()?.edges.name != e.name {
return None;
}
let [s, d] = ends.literals;
let (_, batches) = run
.run(
ctx,
&format!(
"SELECT src, dst, edge FROM induced_edges(\"{}\", nodes => [{s}, {d}])",
graph.name.replace('"', "\"\"")
),
)
.await
.ok()?;
let mut rows = Vec::new();
for batch in &batches {
let number = cast(batch.column(2), &DataType::UInt64).ok()?;
let number = number.as_primitive::<UInt64Type>();
let shown = rows_of(std::slice::from_ref(&batch.project(&[0, 1]).ok()?)).ok()?;
for (i, ends_of) in shown.into_iter().enumerate() {
if number.is_valid(i) && ends.joins(ends_of[0].as_deref(), ends_of[1].as_deref()) {
let ends_of: [Option<String>; 2] = ends_of.try_into().ok()?;
rows.push((number.value(i), ends_of));
}
}
}
rows.sort_unstable_by_key(|(row, _)| *row);
rows.dedup_by_key(|(row, _)| *row);
rows.truncate(MAX_ROWS + 1);
if rows.is_empty() {
return None;
}
let frame = scan(ctx, graph, &e.table).await.ok()?;
let columns = columns_of(&frame);
let at = |name: &str| columns.iter().position(|c| c.name == name);
let (src, dst) = (at(&e.source)?, at(&e.destination)?);
let numbers: Vec<u64> = rows.iter().map(|(row, _)| *row).collect();
if columns.len() == 2 && src != dst {
let found = rows
.into_iter()
.map(|(_, [s, d])| if src == 0 { vec![s, d] } else { vec![d, s] })
.collect();
return Some((numbers, (columns, found)));
}
let found = rows_of(&take(ctx, frame, &numbers).await.ok()??).ok()?;
let all = found.len() == numbers.len()
&& found
.iter()
.all(|row| ends.joins(row[src].as_deref(), row[dst].as_deref()));
all.then_some((numbers, (columns, found)))
}
pub async fn graph_neighbours(
ctx: &SessionContext,
sql: &dyn RunSql,
result: &GraphResult,
node: u32,
) -> Result<Option<u64>> {
let at = node as usize;
let Some(graph) = result.graph() else {
return Ok(None);
};
if at >= result.n_nodes() {
return plan_err(format!("the drawing has no node {node}"));
}
if super::groups::is_group(result, at) {
return Ok(None);
}
let ty = result.node_labels()[result.node_label()[at] as usize].key;
let (_, key) = literal(result.node_keys().get(at), ty);
let (_, batches) = sql
.run(
ctx,
&format!(
"SELECT count(*) FROM hop(\"{}\", seeds => [{key}], steps => 1, direction => 'both')",
graph.replace('"', "\"\"")
),
)
.await?;
for batch in &batches {
if batch.num_rows() > 0 {
let count = cast(batch.column(0), &DataType::UInt64)?;
let count = count.as_primitive::<UInt64Type>();
return Ok(count.is_valid(0).then(|| count.value(0)));
}
}
Ok(None)
}