1use datafusion::arrow::array::{Array, AsArray, RecordBatch};
45use datafusion::arrow::compute::cast;
46use datafusion::arrow::datatypes::{DataType, UInt64Type};
47use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
48use datafusion::common::TableReference;
49use datafusion::dataframe::DataFrame;
50use datafusion::datasource::provider_as_source;
51use datafusion::error::Result;
52use datafusion::logical_expr::{Expr, LogicalPlanBuilder};
53use datafusion::prelude::{ident, lit, SessionContext};
54use ursa_viz::model::{GraphResult, KeyType};
55
56use super::rows::take;
57use super::{plan_err, RunSql};
58use crate::graph::schema::graph_table;
59use crate::graph::{registry_of, PropertyGraph};
60
61pub const MAX_ROWS: usize = 20;
64
65pub const MAX_VALUE_CHARS: usize = 4096;
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Inspect<'a> {
74 Node {
75 node: u32,
76 key: &'a str,
77 },
78 Edge {
79 edge: u32,
80 src: &'a str,
81 dst: &'a str,
82 },
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct InspectedColumn {
88 pub name: String,
89 pub numeric: bool,
91}
92
93#[derive(Debug, Clone, Default, PartialEq, Eq)]
95pub struct Inspected {
96 pub table: Option<String>,
99 pub sql: Option<String>,
101 pub columns: Vec<InspectedColumn>,
102 pub rows: Vec<Vec<Option<String>>>,
105 pub row: Option<u64>,
107 pub note: Option<String>,
110 pub indexed: bool,
114}
115
116impl Inspected {
117 fn said(note: impl Into<String>) -> Inspected {
118 Inspected {
119 note: Some(note.into()),
120 ..Inspected::default()
121 }
122 }
123}
124
125fn name(name: &str) -> String {
128 let plain = name
129 .chars()
130 .enumerate()
131 .all(|(i, c)| c == '_' || c.is_ascii_lowercase() || (i > 0 && c.is_ascii_digit()));
132 if plain && !name.is_empty() {
133 name.to_string()
134 } else {
135 format!("\"{}\"", name.replace('"', "\"\""))
136 }
137}
138
139fn table_name(ctx: &SessionContext, graph: &PropertyGraph, table: &TableReference) -> String {
141 if registry_of(ctx).file_table(&graph.name, table).is_some() {
142 format!("'{}'", table.table().replace('\'', "''"))
143 } else {
144 match table.schema() {
145 Some(schema) => format!("{}.{}", name(schema), name(table.table())),
146 None => name(table.table()),
147 }
148 }
149}
150
151fn literal(key: &str, ty: KeyType) -> (Expr, String) {
153 match (ty, key.parse::<i64>()) {
154 (KeyType::Int, Ok(n)) => (lit(n), key.to_string()),
155 _ => (lit(key), format!("'{}'", key.replace('\'', "''"))),
156 }
157}
158
159async fn read(
161 ctx: &SessionContext,
162 graph: &PropertyGraph,
163 table: &TableReference,
164 filter: Option<Expr>,
165 skip: usize,
166 limit: usize,
167) -> Result<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)> {
168 let frame = scan(ctx, graph, table).await?;
169 let frame = match filter {
170 Some(filter) => frame.filter(filter)?,
171 None => frame,
172 };
173 let columns = columns_of(&frame);
174 let batches = frame.limit(skip, Some(limit))?.collect().await?;
175 Ok((columns, rows_of(&batches)?))
176}
177
178fn columns_of(frame: &DataFrame) -> Vec<InspectedColumn> {
180 frame
181 .schema()
182 .fields()
183 .iter()
184 .map(|f| InspectedColumn {
185 name: f.name().clone(),
186 numeric: f.data_type().is_numeric(),
187 })
188 .collect()
189}
190
191async fn read_rows(
195 ctx: &SessionContext,
196 graph: &PropertyGraph,
197 table: &TableReference,
198 rows: &[u64],
199) -> Result<Option<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)>> {
200 let frame = scan(ctx, graph, table).await?;
201 let columns = columns_of(&frame);
202 match take(ctx, frame, rows).await? {
203 Some(taken) => Ok(Some((columns, rows_of(&taken)?))),
204 None => Ok(None),
205 }
206}
207
208async fn scan(
209 ctx: &SessionContext,
210 graph: &PropertyGraph,
211 table: &TableReference,
212) -> Result<DataFrame> {
213 let state = ctx.state();
214 let provider = graph_table(&state, &graph.name, table).await?;
215 let plan =
216 LogicalPlanBuilder::scan(table.clone(), provider_as_source(provider), None)?.build()?;
217 Ok(DataFrame::new(state, plan))
218}
219
220fn rows_of(batches: &[RecordBatch]) -> Result<Vec<Vec<Option<String>>>> {
222 let options = FormatOptions::default();
223 let mut rows = Vec::new();
224 for batch in batches {
225 let shown = batch
226 .columns()
227 .iter()
228 .map(|c| ArrayFormatter::try_new(c.as_ref(), &options))
229 .collect::<std::result::Result<Vec<_>, _>>()?;
230 for i in 0..batch.num_rows() {
231 let row = batch
232 .columns()
233 .iter()
234 .zip(&shown)
235 .map(|(column, shown)| {
236 if column.is_null(i) {
237 return None;
238 }
239 let mut text = shown.value(i).to_string();
240 if let Some((at, _)) = text.char_indices().nth(MAX_VALUE_CHARS) {
241 text.truncate(at);
242 text.push('…');
243 }
244 Some(text)
245 })
246 .collect();
247 rows.push(row);
248 }
249 }
250 Ok(rows)
251}
252
253fn graph_of(
255 ctx: &SessionContext,
256 result: &GraphResult,
257) -> std::result::Result<std::sync::Arc<PropertyGraph>, String> {
258 let Some(graph) = result.graph() else {
259 return Err(
260 "this drawing is not of a property graph, so there is no table row to show; draw \
261 a graph's (.graph NAME) or a query's on one"
262 .into(),
263 );
264 };
265 registry_of(ctx)
266 .get(graph)
267 .ok_or_else(|| format!("the graph '{graph}' is gone, and its tables with it"))
268}
269
270pub async fn inspect(
275 ctx: &SessionContext,
276 sql: &dyn RunSql,
277 result: &GraphResult,
278 what: Inspect<'_>,
279) -> Result<Inspected> {
280 match what {
281 Inspect::Node { node, key } => {
282 let at = node as usize;
283 if at >= result.n_nodes() || result.node_keys().get(at) != key {
284 return plan_err(format!(
285 "the drawing has changed: its node {node} is not '{key}'; draw it again \
286 (.graph)"
287 ));
288 }
289 inspect_node(ctx, result, at).await
290 }
291 Inspect::Edge { edge, src, dst } => {
292 let at = edge as usize;
293 let keys = result.node_keys();
294 if at >= result.n_edges()
295 || keys.get(result.src()[at] as usize) != src
296 || keys.get(result.dst()[at] as usize) != dst
297 {
298 return plan_err(format!(
299 "the drawing has changed: its edge {edge} does not join '{src}' and \
300 '{dst}'; draw it again (.graph)"
301 ));
302 }
303 inspect_edge(ctx, sql, result, at).await
304 }
305 }
306}
307
308async fn inspect_node(
309 ctx: &SessionContext,
310 result: &GraphResult,
311 node: usize,
312) -> Result<Inspected> {
313 let graph = match graph_of(ctx, result) {
314 Ok(graph) => graph,
315 Err(note) => return Ok(Inspected::said(note)),
316 };
317 if super::groups::is_group(result, node) {
318 return Ok(Inspected::said(format!(
319 "a group of {}'s nodes, not a row of its tables: its values are above, and .expand \
320 group:{} opens it",
321 graph.name,
322 result.node_keys().get(node)
323 )));
324 }
325 let label = &result.node_labels()[result.node_label()[node] as usize];
326 let key = result.node_keys().get(node);
327 let tables: Vec<_> = graph
329 .vertex_tables
330 .iter()
331 .filter(|v| label.name.is_empty() || v.name == label.name)
332 .collect();
333 if tables.is_empty() {
334 return Ok(Inspected::said(if graph.vertex_tables.is_empty() {
335 format!(
336 "the graph {} has no vertex tables: a node is its key and its edges",
337 graph.name
338 )
339 } else {
340 format!(
341 "the graph {} has no vertex table '{}'",
342 graph.name, label.name
343 )
344 }));
345 }
346 let mut first = None;
347 for v in tables {
348 let (value, shown) = literal(key, label.key);
349 let (columns, rows) =
350 read(ctx, &graph, &v.table, Some(ident(&v.key).eq(value)), 0, 1).await?;
351 let found = Inspected {
352 table: Some(v.name.clone()),
353 sql: Some(format!(
354 "SELECT * FROM {} WHERE {} = {shown}",
355 table_name(ctx, &graph, &v.table),
356 name(&v.key)
357 )),
358 columns,
359 rows,
360 row: None,
361 note: None,
362 indexed: false,
363 };
364 if !found.rows.is_empty() {
365 return Ok(found);
366 }
367 first.get_or_insert(found);
368 }
369 let mut none = first.expect("there is a table");
370 none.note = Some(format!(
371 "no row of {} has the key {key}: the node is named only by an edge",
372 none.table.as_deref().unwrap_or_default()
373 ));
374 Ok(none)
375}
376
377async fn inspect_edge(
378 ctx: &SessionContext,
379 run: &dyn RunSql,
380 result: &GraphResult,
381 edge: usize,
382) -> Result<Inspected> {
383 let graph = match graph_of(ctx, result) {
384 Ok(graph) => graph,
385 Err(note) => return Ok(Inspected::said(note)),
386 };
387 if super::groups::is_group(result, result.src()[edge] as usize) {
388 return Ok(Inspected::said(format!(
389 "the edges of {} between two groups, counted: not one row of its tables",
390 graph.name
391 )));
392 }
393 let label = &result.edge_labels()[result.edge_label()[edge] as usize];
394 let row = result.edge_row(edge);
395 let end = |node: u32| {
396 let at = node as usize;
397 let ty = result.node_labels()[result.node_label()[at] as usize].key;
398 (
399 result.node_keys().get(at),
400 literal(result.node_keys().get(at), ty),
401 )
402 };
403 let (s_key, (s, s_shown)) = end(result.src()[edge]);
404 let (d_key, (d, d_shown)) = end(result.dst()[edge]);
405 let tables: Vec<_> = graph
406 .edge_tables
407 .iter()
408 .filter(|e| label.is_empty() || &e.name == label)
409 .collect();
410 if tables.is_empty() {
411 return Ok(Inspected::said(format!(
412 "the graph {} has no edge table '{label}'",
413 graph.name
414 )));
415 }
416 let mut first = None;
417 for e in tables {
418 let (source, destination) = (ident(&e.source), ident(&e.destination));
419 let table = table_name(ctx, &graph, &e.table);
420 let (from, to) = (name(&e.source), name(&e.destination));
421 let mut filter = source
422 .clone()
423 .eq(s.clone())
424 .and(destination.clone().eq(d.clone()));
425 let mut sql =
426 format!("SELECT * FROM {table} WHERE {from} = {s_shown} AND {to} = {d_shown}");
427 let either_way = row.is_none() && s_shown != d_shown;
429 if either_way {
430 filter = filter.or(source.eq(d.clone()).and(destination.eq(s.clone())));
431 sql = format!(
432 "SELECT * FROM {table} WHERE ({from} = {s_shown} AND {to} = {d_shown}) OR \
433 ({from} = {d_shown} AND {to} = {s_shown})"
434 );
435 }
436 let ends = Ends {
438 literals: [&s_shown, &d_shown],
439 keys: [s_key, d_key],
440 either_way,
441 };
442 let (numbers, (columns, rows)) = match between(ctx, run, &graph, e, &ends).await {
444 Some((numbers, found)) => (Some(numbers), found),
445 None => (
446 None,
447 read(ctx, &graph, &e.table, Some(filter), 0, MAX_ROWS + 1).await?,
448 ),
449 };
450 let mut found = Inspected {
451 table: Some(e.name.clone()),
452 sql: Some(sql),
453 columns,
454 rows,
455 row,
456 note: None,
457 indexed: numbers.is_some(),
458 };
459 if found.rows.len() > 1 {
460 let among = |row: u64| numbers.as_ref()?.iter().position(|&n| n == row);
463 let one = match row {
464 Some(row) => match among(row) {
465 Some(i) => Some((row, vec![found.rows[i].clone()])),
466 None => read_rows(ctx, &graph, &e.table, &[row])
467 .await?
468 .filter(|(_, rows)| !rows.is_empty())
469 .map(|(_, rows)| (row, rows)),
470 },
471 None => None,
472 };
473 match one {
474 Some((row, rows)) => {
475 found.rows = rows;
476 found.sql = Some(format!("SELECT * FROM {table} LIMIT 1 OFFSET {row}"));
477 }
478 None => {
479 let more = found.rows.len() > MAX_ROWS;
480 found.rows.truncate(MAX_ROWS);
481 found.note = Some(format!(
482 "{}{} rows of {} join these two nodes; the drawing does not say which \
483 this edge is",
484 if more { "more than " } else { "" },
485 found.rows.len(),
486 e.name
487 ));
488 }
489 }
490 }
491 if !found.rows.is_empty() {
492 return Ok(found);
493 }
494 first.get_or_insert(found);
495 }
496 let mut none = first.expect("there is a table");
497 none.note = Some(format!(
498 "no row of {} joins these two nodes: the edge is not the graph's (a query made it)",
499 none.table.as_deref().unwrap_or_default()
500 ));
501 Ok(none)
502}
503
504struct Ends<'a> {
506 literals: [&'a str; 2],
508 keys: [&'a str; 2],
510 either_way: bool,
512}
513
514impl Ends<'_> {
515 fn joins(&self, src: Option<&str>, dst: Option<&str>) -> bool {
517 let [s, d] = self.keys.map(Some);
518 (src, dst) == (s, d) || (self.either_way && (src, dst) == (d, s))
519 }
520}
521
522async fn between(
531 ctx: &SessionContext,
532 run: &dyn RunSql,
533 graph: &PropertyGraph,
534 e: &crate::graph::EdgeTable,
535 ends: &Ends<'_>,
536) -> Option<(Vec<u64>, (Vec<InspectedColumn>, Vec<Vec<Option<String>>>))> {
537 if graph.pair(None, None).ok()?.edges.name != e.name {
538 return None;
539 }
540 let [s, d] = ends.literals;
541 let (_, batches) = run
542 .run(
543 ctx,
544 &format!(
545 "SELECT src, dst, edge FROM induced_edges(\"{}\", nodes => [{s}, {d}])",
546 graph.name.replace('"', "\"\"")
547 ),
548 )
549 .await
550 .ok()?;
551 let mut rows = Vec::new();
554 for batch in &batches {
555 let number = cast(batch.column(2), &DataType::UInt64).ok()?;
556 let number = number.as_primitive::<UInt64Type>();
557 let shown = rows_of(std::slice::from_ref(&batch.project(&[0, 1]).ok()?)).ok()?;
558 for (i, ends_of) in shown.into_iter().enumerate() {
559 if number.is_valid(i) && ends.joins(ends_of[0].as_deref(), ends_of[1].as_deref()) {
560 let ends_of: [Option<String>; 2] = ends_of.try_into().ok()?;
561 rows.push((number.value(i), ends_of));
562 }
563 }
564 }
565 rows.sort_unstable_by_key(|(row, _)| *row);
566 rows.dedup_by_key(|(row, _)| *row);
567 rows.truncate(MAX_ROWS + 1);
568 if rows.is_empty() {
569 return None;
570 }
571 let frame = scan(ctx, graph, &e.table).await.ok()?;
574 let columns = columns_of(&frame);
575 let at = |name: &str| columns.iter().position(|c| c.name == name);
576 let (src, dst) = (at(&e.source)?, at(&e.destination)?);
577 let numbers: Vec<u64> = rows.iter().map(|(row, _)| *row).collect();
578 if columns.len() == 2 && src != dst {
579 let found = rows
580 .into_iter()
581 .map(|(_, [s, d])| if src == 0 { vec![s, d] } else { vec![d, s] })
582 .collect();
583 return Some((numbers, (columns, found)));
584 }
585 let found = rows_of(&take(ctx, frame, &numbers).await.ok()??).ok()?;
586 let all = found.len() == numbers.len()
588 && found
589 .iter()
590 .all(|row| ends.joins(row[src].as_deref(), row[dst].as_deref()));
591 all.then_some((numbers, (columns, found)))
592}
593
594pub async fn graph_neighbours(
601 ctx: &SessionContext,
602 sql: &dyn RunSql,
603 result: &GraphResult,
604 node: u32,
605) -> Result<Option<u64>> {
606 let at = node as usize;
607 let Some(graph) = result.graph() else {
608 return Ok(None);
609 };
610 if at >= result.n_nodes() {
611 return plan_err(format!("the drawing has no node {node}"));
612 }
613 if super::groups::is_group(result, at) {
615 return Ok(None);
616 }
617 let ty = result.node_labels()[result.node_label()[at] as usize].key;
618 let (_, key) = literal(result.node_keys().get(at), ty);
619 let (_, batches) = sql
620 .run(
621 ctx,
622 &format!(
623 "SELECT count(*) FROM hop(\"{}\", seeds => [{key}], steps => 1, direction => 'both')",
624 graph.replace('"', "\"\"")
625 ),
626 )
627 .await?;
628 for batch in &batches {
629 if batch.num_rows() > 0 {
630 let count = cast(batch.column(0), &DataType::UInt64)?;
631 let count = count.as_primitive::<UInt64Type>();
632 return Ok(count.is_valid(0).then(|| count.value(0)));
633 }
634 }
635 Ok(None)
636}