1use 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
46pub const MAX_ROWS: usize = 20;
49
50pub const MAX_VALUE_CHARS: usize = 4096;
52
53#[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#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct InspectedColumn {
73 pub name: String,
74 pub numeric: bool,
76}
77
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
80pub struct Inspected {
81 pub table: Option<String>,
84 pub sql: Option<String>,
86 pub columns: Vec<InspectedColumn>,
87 pub rows: Vec<Vec<Option<String>>>,
90 pub row: Option<u64>,
92 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
106fn 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
120fn 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
132fn 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
140async 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
179fn 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
212fn 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
229pub 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 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 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 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
423async 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
437pub 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}