Skip to main content

ursa_engine/graph/view/
session.rs

1//! The explore session (design §4, #440): the engine's side of exploring the
2//! graph that is drawn. A [`Session`] knows what is shown and turns each
3//! command into SQL and a [`GraphDelta`] for the view to apply.
4//!
5//! A session holds:
6//!
7//! - **the graph as it stands**, a [`GraphResult`]: the base that `.graph`
8//!   drew with every step so far applied. It carries the base property
9//!   graph's name, the `(label, key)` → index map ([`GraphResult::node`]) and
10//!   the shown set (a hidden node keeps its slot, with a flag);
11//! - **the history**, a list of [`Step`]s (the command, its SQL, its delta,
12//!   and through [`Step::inverse`] the delta that undoes it), and how many
13//!   of them are applied.
14//!
15//! The commands ([`Command`]), each one line of text:
16//!
17//! | command | what it does | its SQL |
18//! |---|---|---|
19//! | `.expand ID [in\|out\|both] [LIMIT n]` | adds the node's neighbours that are not shown, and the graph's edges among every node | `hop`, then `induced_edges` |
20//! | `.hide ID…` | hides nodes | none |
21//! | `.show ID…` or `.show all` | shows hidden nodes again | none |
22//! | `.undo`, `.redo` | steps the history | none |
23//! | `.graph history` | lists the steps | none |
24//!
25//! `--sql` on a command prints its SQL and changes nothing: no step, no
26//! delta. For `.expand` it prints both statements as a step would run them,
27//! and to do so it runs the first, a query, whose rows are the nodes the
28//! second names.
29//!
30//! # Expanding
31//!
32//! `.expand 33` runs two statements ([`Session::run`] gives them back in the
33//! step):
34//!
35//! 1. The neighbours to add: `hop` one step from the node (`both`
36//!    directions unless the command says `in` or `out`), without the nodes
37//!    that are shown, ordered by their degree in the graph (both directions,
38//!    highest first) and then by key, and cut at the limit
39//!    ([`EXPAND_LIMIT`], or `LIMIT n` up to [`MAX_EXPAND`]). The order is
40//!    total, so the same command always adds the same nodes, in the same
41//!    order. Expanding again adds the next ones.
42//! 2. The edges: `induced_edges` over every node of the session and the new
43//!    ones. An edge the session already has is left out: by its label and
44//!    its row in the edge table where both are known, else by the two nodes
45//!    it joins and its place among their parallel edges.
46//!
47//! The delta restores the neighbours that were hidden, appends the new nodes
48//! (in the order of statement 1) and then the new edges (in the order of
49//! statement 2, which is the edge table's). Hidden nodes are part of
50//! statement 2, so their edges to newer nodes are in the session when
51//! `.show` brings them back, with no query.
52//!
53//! # Undo
54//!
55//! Every op of a delta carries what its inverse needs, so `.undo` applies
56//! [`GraphDelta::invert`] of the last step and runs no SQL, and `.redo`
57//! applies the step's delta again. A new step drops the steps that were
58//! undone.
59
60use std::collections::{HashMap, HashSet};
61
62use datafusion::arrow::array::{Array, ArrayRef, AsArray, Int64Array, StringArray};
63use datafusion::arrow::compute::cast;
64use datafusion::arrow::datatypes::{DataType, Int64Type, UInt64Type};
65use datafusion::error::{DataFusionError, Result};
66use datafusion::prelude::SessionContext;
67use ursa_viz::model::{
68    EdgeBatch, GraphDelta, GraphResult, Key, KeyType, NodeBatch, Op, Provenance, NO_ROW,
69};
70
71use super::{plan_err, thousands, RunSql};
72use crate::graph::provenance as meta;
73
74/// How many neighbours `.expand` adds unless it says `LIMIT n`.
75pub const EXPAND_LIMIT: usize = 100;
76/// The most `LIMIT n` may ask for.
77pub const MAX_EXPAND: usize = 5_000;
78
79/// Which of a node's edges `.expand` follows.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum Direction {
82    In,
83    Out,
84    Both,
85}
86
87impl Direction {
88    /// As `hop`'s `direction` takes it.
89    pub fn name(self) -> &'static str {
90        match self {
91            Direction::In => "in",
92            Direction::Out => "out",
93            Direction::Both => "both",
94        }
95    }
96}
97
98/// An explore command, read from its line.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Command {
101    Expand {
102        id: String,
103        direction: Direction,
104        limit: usize,
105    },
106    Hide(Vec<String>),
107    /// The ids to show; none for `.show all`.
108    Show(Vec<String>),
109    Undo,
110    Redo,
111    History,
112}
113
114/// A command and whether it asked for its SQL alone (`--sql`).
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct Parsed {
117    pub command: Command,
118    pub sql_only: bool,
119    /// The line as the history shows it: trimmed, with no `;`.
120    pub text: String,
121}
122
123/// The words of a command: split at spaces, a quoted word (`'a b'`, `"a b"`)
124/// kept whole without its quotes, a doubled quote inside one being one.
125fn words(text: &str) -> Result<Vec<String>> {
126    let mut out = Vec::new();
127    let mut chars = text.chars().peekable();
128    while let Some(&c) = chars.peek() {
129        if c.is_whitespace() {
130            chars.next();
131            continue;
132        }
133        let mut word = String::new();
134        if c == '\'' || c == '"' {
135            chars.next();
136            loop {
137                match chars.next() {
138                    None => return plan_err(format!("a quote ({c}) is not closed in: {text}")),
139                    Some(x) if x == c => {
140                        if chars.peek() == Some(&c) {
141                            chars.next();
142                            word.push(c);
143                        } else {
144                            break;
145                        }
146                    }
147                    Some(x) => word.push(x),
148                }
149            }
150        } else {
151            while let Some(&x) = chars.peek() {
152                if x.is_whitespace() {
153                    break;
154                }
155                word.push(x);
156                chars.next();
157            }
158        }
159        out.push(word);
160    }
161    Ok(out)
162}
163
164impl Command {
165    /// The names of the explore commands, as typed: `.graph` is one only as
166    /// `.graph history`.
167    pub const NAMES: [&'static str; 5] = [".expand", ".hide", ".show", ".undo", ".redo"];
168
169    /// Read `line`. `Ok(None)` when it is not an explore command (`.graph
170    /// karate`, `.tables`); an error when it is one that cannot be read.
171    pub fn parse(line: &str) -> Result<Option<Parsed>> {
172        let text = line.trim().trim_end_matches(';').trim_end();
173        let (name, rest) = match text.find(char::is_whitespace) {
174            Some(at) => (&text[..at], text[at..].trim()),
175            None => (text, ""),
176        };
177        let name = name.to_ascii_lowercase();
178        if name == ".graph" {
179            if !rest
180                .split_whitespace()
181                .next()
182                .is_some_and(|w| w.eq_ignore_ascii_case("history"))
183            {
184                return Ok(None);
185            }
186        } else if !Self::NAMES.contains(&name.as_str()) {
187            return Ok(None);
188        }
189        let mut args = words(rest)?;
190        let before = args.len();
191        args.retain(|a| a != "--sql");
192        let sql_only = args.len() != before;
193        let command = match name.as_str() {
194            ".expand" => {
195                const USAGE: &str = "usage: .expand ID [in|out|both] [LIMIT n]";
196                let mut args = args.into_iter();
197                let Some(id) = args.next() else {
198                    return plan_err(USAGE);
199                };
200                let mut direction = None;
201                let mut limit = None;
202                while let Some(word) = args.next() {
203                    match word.to_ascii_lowercase().as_str() {
204                        "in" if direction.is_none() => direction = Some(Direction::In),
205                        "out" if direction.is_none() => direction = Some(Direction::Out),
206                        "both" if direction.is_none() => direction = Some(Direction::Both),
207                        "limit" if limit.is_none() => {
208                            let n = args.next().and_then(|n| n.parse::<usize>().ok());
209                            match n {
210                                Some(n) if (1..=MAX_EXPAND).contains(&n) => limit = Some(n),
211                                _ => {
212                                    return plan_err(format!(
213                                        "LIMIT takes a number of neighbours from 1 to {}; {USAGE}",
214                                        thousands(MAX_EXPAND)
215                                    ))
216                                }
217                            }
218                        }
219                        _ => {
220                            return plan_err(format!(
221                                "'{word}' is not part of .expand (one node at a time); {USAGE}"
222                            ))
223                        }
224                    }
225                }
226                Command::Expand {
227                    id,
228                    direction: direction.unwrap_or(Direction::Both),
229                    limit: limit.unwrap_or(EXPAND_LIMIT),
230                }
231            }
232            ".hide" => {
233                if args.is_empty() {
234                    return plan_err("usage: .hide ID…");
235                }
236                Command::Hide(args)
237            }
238            ".show" => {
239                if args.is_empty() {
240                    return plan_err("usage: .show ID… or .show all");
241                }
242                if args.len() == 1 && args[0].eq_ignore_ascii_case("all") {
243                    Command::Show(Vec::new())
244                } else {
245                    Command::Show(args)
246                }
247            }
248            ".undo" | ".redo" => {
249                if !args.is_empty() {
250                    return plan_err(format!("usage: {name}"));
251                }
252                if name == ".undo" {
253                    Command::Undo
254                } else {
255                    Command::Redo
256                }
257            }
258            _ => {
259                if args.len() != 1 {
260                    return plan_err("usage: .graph history");
261                }
262                Command::History
263            }
264        };
265        Ok(Some(Parsed {
266            command,
267            sql_only,
268            text: text.to_string(),
269        }))
270    }
271}
272
273/// One step of an exploration.
274#[derive(Debug, Clone, PartialEq)]
275pub struct Step {
276    /// The command, as typed.
277    pub command: String,
278    /// The statements it ran, in order; none for a step that reads nothing
279    /// (`.hide`, `.show`).
280    pub sql: Vec<String>,
281    /// What it changed.
282    pub delta: GraphDelta,
283    /// How many more nodes and edges were shown after it (fewer, when
284    /// negative).
285    pub nodes: i64,
286    pub edges: i64,
287}
288
289impl Step {
290    /// The delta that undoes the step.
291    pub fn inverse(&self) -> GraphDelta {
292        self.delta.invert()
293    }
294
295    /// `+16 nodes, +41 edges`.
296    pub fn summary(&self) -> String {
297        changed(self.nodes, self.edges)
298    }
299}
300
301/// `+16 nodes, +41 edges`; `-1 node, -3 edges`.
302fn changed(nodes: i64, edges: i64) -> String {
303    let part = |n: i64, one: &str| {
304        let sign = if n < 0 { '-' } else { '+' };
305        let s = if n.unsigned_abs() == 1 { "" } else { "s" };
306        format!("{sign}{} {one}{s}", thousands(n.unsigned_abs() as usize))
307    };
308    format!("{}, {}", part(nodes, "node"), part(edges, "edge"))
309}
310
311/// What a command did.
312#[derive(Debug, Clone, PartialEq)]
313pub struct Outcome {
314    /// What to print: one line for a command that changes the graph (what
315    /// changed, or why nothing did), the SQL for `--sql`, the steps for
316    /// `.graph history`. No newline at the end.
317    pub text: String,
318    /// The change for the view to apply, if there is one.
319    pub delta: Option<GraphDelta>,
320}
321
322impl Outcome {
323    fn said(text: impl Into<String>) -> Outcome {
324        Outcome {
325            text: text.into(),
326            delta: None,
327        }
328    }
329}
330
331/// Two nodes, whichever way an edge joins them. A drawing's edge with no row
332/// may be drawn against the way the graph stores it (a path's steps are).
333fn pair(a: u32, b: u32) -> (u32, u32) {
334    (a.min(b), a.max(b))
335}
336
337/// The session's edges, by what makes one the same edge: its label and row
338/// where the engine knew the row, else the two nodes it joins (and how many
339/// such edges join them).
340#[derive(Debug, Default)]
341struct EdgeIndex {
342    rows: HashSet<(u16, u64)>,
343    pairs: HashMap<(u32, u32), u32>,
344}
345
346impl EdgeIndex {
347    fn of(result: &GraphResult) -> EdgeIndex {
348        let mut index = EdgeIndex::default();
349        let (src, dst, label) = (result.src(), result.dst(), result.edge_label());
350        for i in 0..result.n_edges() {
351            index.add(src[i], dst[i], label[i], result.edge_row(i));
352        }
353        index
354    }
355
356    fn add(&mut self, src: u32, dst: u32, label: u16, row: Option<u64>) {
357        match row {
358            Some(row) => {
359                self.rows.insert((label, row));
360            }
361            None => *self.pairs.entry(pair(src, dst)).or_insert(0) += 1,
362        }
363    }
364
365    fn remove(&mut self, src: u32, dst: u32, label: u16, row: Option<u64>) {
366        match row {
367            Some(row) => {
368                self.rows.remove(&(label, row));
369            }
370            None => {
371                let pair = pair(src, dst);
372                if let Some(count) = self.pairs.get_mut(&pair) {
373                    *count -= 1;
374                    if *count == 0 {
375                        self.pairs.remove(&pair);
376                    }
377                }
378            }
379        }
380    }
381
382    /// Keep up with a delta the session applied.
383    fn track(&mut self, delta: &GraphDelta) {
384        let each = |batch: &EdgeBatch, f: &mut dyn FnMut(u32, u32, u16, Option<u64>)| {
385            for i in 0..batch.len() {
386                let row = batch
387                    .rows
388                    .as_ref()
389                    .map(|rows| rows[i])
390                    .filter(|&r| r != NO_ROW);
391                f(batch.src[i], batch.dst[i], batch.labels[i], row);
392            }
393        };
394        for op in &delta.ops {
395            match op {
396                Op::AddEdges(batch) => each(batch, &mut |s, d, l, r| self.add(s, d, l, r)),
397                Op::PopEdges(batch) => each(batch, &mut |s, d, l, r| self.remove(s, d, l, r)),
398                _ => {}
399            }
400        }
401    }
402}
403
404/// A column of node ids, as integers where it is one of integers.
405enum Ids {
406    Int(Int64Array),
407    Text(StringArray),
408}
409
410impl Ids {
411    fn of(array: &ArrayRef) -> Result<Ids> {
412        let integers = matches!(
413            array.data_type(),
414            DataType::Int8
415                | DataType::Int16
416                | DataType::Int32
417                | DataType::Int64
418                | DataType::UInt8
419                | DataType::UInt16
420                | DataType::UInt32
421        );
422        if integers {
423            let cast = cast(array, &DataType::Int64)?;
424            Ok(Ids::Int(cast.as_primitive::<Int64Type>().clone()))
425        } else {
426            let cast = cast(array, &DataType::Utf8)?;
427            Ok(Ids::Text(cast.as_string::<i32>().clone()))
428        }
429    }
430
431    /// Row `i`'s id as a key of type `ty`, if it is one (and not NULL).
432    fn key(&self, i: usize, ty: KeyType) -> Option<Key> {
433        match (self, ty) {
434            (Ids::Int(a), _) if a.is_null(i) => None,
435            (Ids::Text(a), _) if a.is_null(i) => None,
436            (Ids::Int(a), KeyType::Int) => Some(Key::Int(a.value(i))),
437            (Ids::Int(a), KeyType::Text) => Some(Key::Text(a.value(i).to_string())),
438            (Ids::Text(a), ty) => Key::parse(ty, a.value(i)).ok(),
439        }
440    }
441}
442
443/// `key` as a SQL literal.
444fn literal(out: &mut String, key: &str, ty: KeyType) {
445    match ty {
446        KeyType::Int => out.push_str(key),
447        KeyType::Text => {
448            out.push('\'');
449            out.push_str(&key.replace('\'', "''"));
450            out.push('\'');
451        }
452    }
453}
454
455fn model(e: ursa_viz::model::ModelError) -> DataFusionError {
456    DataFusionError::Plan(format!("the graph cannot be changed: {e}"))
457}
458
459/// The explore session of one drawing. See the [module](self).
460#[derive(Debug)]
461pub struct Session {
462    result: GraphResult,
463    steps: Vec<Step>,
464    /// How many of `steps` are applied; the rest were undone.
465    done: usize,
466    /// Made by the first `.expand`, and kept up after it.
467    edges: Option<EdgeIndex>,
468    /// Each node's degree in the property graph (both directions, every
469    /// edge counted), by slot, for the slots asked about so far
470    /// ([`Session::not_shown`]); [`NO_DEGREE`] for a node the graph has no
471    /// row for.
472    degrees: Vec<u32>,
473}
474
475/// The degree of a node the graph's `degree` has no row for.
476const NO_DEGREE: u32 = u32::MAX;
477/// Up to this many nodes' degrees are asked for by key; more, and the whole
478/// graph's are read.
479const DEGREES_BY_KEY: usize = 1_000;
480
481impl Session {
482    /// A session on what `.graph` drew.
483    pub fn new(base: GraphResult) -> Session {
484        Session {
485            result: base,
486            steps: Vec::new(),
487            done: 0,
488            edges: None,
489            degrees: Vec::new(),
490        }
491    }
492
493    /// The graph as it stands: the base with every applied step.
494    pub fn result(&self) -> &GraphResult {
495        &self.result
496    }
497
498    /// Every step, the undone ones included: `steps()[..applied()]` are in
499    /// the graph.
500    pub fn steps(&self) -> &[Step] {
501        &self.steps
502    }
503
504    /// How many steps are applied.
505    pub fn applied(&self) -> usize {
506        self.done
507    }
508
509    /// How many nodes and edges are shown.
510    pub fn shown(&self) -> (usize, usize) {
511        let r = &self.result;
512        let nodes = r.node_flags().iter().filter(|&&f| f == 0).count();
513        let edges = (0..r.n_edges()).filter(|&i| r.edge_is_shown(i)).count();
514        (nodes, edges)
515    }
516
517    /// The node `id` names: of the first label that has the key.
518    /// For each node slot, how many of the node's edges in the property
519    /// graph lead to something that is not shown: its degree in the graph
520    /// (both directions, every edge counted, as `degree` counts) less its
521    /// shown edges here. It is what a view's `+N` badge says, and 0 for a
522    /// hidden node and for one the graph does not have. Empty when the
523    /// drawing is not of a property graph.
524    ///
525    /// The graph's degrees are read once for each node (one `degree` query
526    /// for the nodes not asked about before: by key for up to
527    /// [`DEGREES_BY_KEY`] of them, else the whole graph's), and the shown
528    /// edges are counted each time.
529    pub async fn not_shown(&mut self, ctx: &SessionContext, sql: &dyn RunSql) -> Result<Vec<u32>> {
530        let Some(graph) = self.result.graph() else {
531            return Ok(Vec::new());
532        };
533        let n = self.result.n_nodes();
534        self.degrees.truncate(n);
535        let known = self.degrees.len();
536        if known < n {
537            let graph = format!("\"{}\"", graph.replace('"', "\"\""));
538            let mut query = format!("SELECT id, degree FROM degree({graph}, direction => 'both')");
539            let one_type = (known..n).all(|i| self.key_type(i) == self.key_type(known));
540            if n - known <= DEGREES_BY_KEY && one_type {
541                query.push_str(" WHERE id IN (");
542                for i in known..n {
543                    if i > known {
544                        query.push_str(", ");
545                    }
546                    literal(&mut query, self.result.node_keys().get(i), self.key_type(i));
547                }
548                query.push(')');
549            }
550            let (_, batches) = sql.run(ctx, &query).await?;
551            let r = &self.result;
552            let mut degrees = vec![NO_DEGREE; n - known];
553            for batch in &batches {
554                let ids = Ids::of(batch.column(0))?;
555                let degree = cast(batch.column(1), &DataType::UInt64)?;
556                let degree = degree.as_primitive::<UInt64Type>();
557                for i in 0..batch.num_rows() {
558                    let found = r.node_labels().iter().zip(0u16..).find_map(|(l, at)| {
559                        let key = ids.key(i, l.key)?;
560                        r.node(at, &key)
561                    });
562                    if let Some(at) = found.filter(|&at| at as usize >= known) {
563                        degrees[at as usize - known] =
564                            degree.value(i).min(u64::from(u32::MAX - 1)) as u32;
565                    }
566                }
567            }
568            self.degrees.extend(degrees);
569        }
570        let r = &self.result;
571        let mut shown = vec![0u32; n];
572        let (src, dst) = (r.src(), r.dst());
573        for e in 0..r.n_edges() {
574            if r.edge_is_shown(e) {
575                shown[src[e] as usize] += 1;
576                shown[dst[e] as usize] += 1;
577            }
578        }
579        Ok((0..n)
580            .map(|i| match self.degrees[i] {
581                NO_DEGREE => 0,
582                _ if r.node_is_removed(i) => 0,
583                degree => degree.saturating_sub(shown[i]),
584            })
585            .collect())
586    }
587
588    fn find(&self, id: &str) -> Option<u32> {
589        let r = &self.result;
590        r.node_labels().iter().zip(0u16..).find_map(|(label, l)| {
591            let key = Key::parse(label.key, id).ok()?;
592            r.node(l, &key)
593        })
594    }
595
596    fn resolve(&self, id: &str) -> Result<u32> {
597        match self.find(id) {
598            Some(node) => Ok(node),
599            None => plan_err(format!(
600                "no node '{id}' in the graph that is drawn; a node is named by its key, as the \
601                 graph view shows it"
602            )),
603        }
604    }
605
606    /// The key type of node `i`'s label.
607    fn key_type(&self, i: usize) -> KeyType {
608        self.result.node_labels()[self.result.node_label()[i] as usize].key
609    }
610
611    /// The keys of the session's nodes as a SQL list's items: the shown
612    /// ones, or all of them.
613    fn keys(&self, hidden_too: bool) -> String {
614        let r = &self.result;
615        let mut out = String::with_capacity(r.n_nodes() * 8);
616        for i in 0..r.n_nodes() {
617            if !hidden_too && r.node_is_removed(i) {
618                continue;
619            }
620            if !out.is_empty() {
621                out.push_str(", ");
622            }
623            literal(&mut out, r.node_keys().get(i), self.key_type(i));
624        }
625        out
626    }
627
628    /// Apply `delta` as a new step, dropping the steps that were undone.
629    fn step(&mut self, command: &str, sql: Vec<String>, delta: GraphDelta) -> Result<Outcome> {
630        let before = self.shown();
631        self.result.apply(&delta).map_err(model)?;
632        self.degrees.truncate(self.result.n_nodes());
633        if let Some(edges) = &mut self.edges {
634            edges.track(&delta);
635        }
636        let after = self.shown();
637        let step = Step {
638            command: command.to_string(),
639            sql,
640            delta: delta.clone(),
641            nodes: after.0 as i64 - before.0 as i64,
642            edges: after.1 as i64 - before.1 as i64,
643        };
644        let text = step.summary();
645        self.steps.truncate(self.done);
646        self.steps.push(step);
647        self.done += 1;
648        Ok(Outcome {
649            text,
650            delta: Some(delta),
651        })
652    }
653
654    /// Run one command: `.expand`, `.hide`, `.show`, `.undo`, `.redo` or
655    /// `.graph history`, as [`Command::parse`] reads it. `sql` runs the
656    /// statements of `.expand` on `ctx`.
657    ///
658    /// An error (a line that is not a command, an id that is not a node, SQL
659    /// that failed) changes nothing.
660    pub async fn run(
661        &mut self,
662        ctx: &SessionContext,
663        sql: &dyn RunSql,
664        line: &str,
665    ) -> Result<Outcome> {
666        let Some(parsed) = Command::parse(line)? else {
667            return plan_err(format!(
668                "'{}' is not an explore command; they are .expand, .hide, .show, .undo, .redo \
669                 and .graph history",
670                line.trim()
671            ));
672        };
673        let Parsed {
674            command,
675            sql_only,
676            text,
677        } = parsed;
678        match command {
679            Command::Expand {
680                id,
681                direction,
682                limit,
683            } => {
684                self.expand(ctx, sql, &text, &id, direction, limit, sql_only)
685                    .await
686            }
687            _ if sql_only => {
688                let name = text.split_whitespace().next().unwrap_or_default();
689                Ok(Outcome::said(format!(
690                    "-- {name} runs no SQL: it changes what is shown of the graph"
691                )))
692            }
693            Command::Hide(ids) => self.set_hidden(&text, &ids, true),
694            Command::Show(ids) => self.set_hidden(&text, &ids, false),
695            Command::Undo => self.undo(),
696            Command::Redo => self.redo(),
697            Command::History => Ok(Outcome::said(self.history())),
698        }
699    }
700
701    /// `.hide` (`hide`) or `.show`; no ids is every hidden node.
702    fn set_hidden(&mut self, command: &str, ids: &[String], hide: bool) -> Result<Outcome> {
703        let r = &self.result;
704        let mut nodes: Vec<u32> = if ids.is_empty() {
705            (0..r.n_nodes() as u32).collect()
706        } else {
707            let mut nodes = Vec::with_capacity(ids.len());
708            for id in ids {
709                nodes.push(self.resolve(id)?);
710            }
711            nodes
712        };
713        nodes.sort_unstable();
714        nodes.dedup();
715        nodes.retain(|&i| r.node_is_removed(i as usize) != hide);
716        if nodes.is_empty() {
717            let (state, named) = if hide {
718                ("hidden", ids.join(", "))
719            } else if ids.is_empty() {
720                return Ok(Outcome::said("Nothing changed: no node is hidden"));
721            } else {
722                ("shown", ids.join(", "))
723            };
724            let verb = if ids.len() == 1 { "is" } else { "are" };
725            return Ok(Outcome::said(format!(
726                "Nothing changed: {named} {verb} already {state}"
727            )));
728        }
729        let op = if hide {
730            Op::RemoveNodes(nodes)
731        } else {
732            Op::RestoreNodes(nodes)
733        };
734        self.step(command, Vec::new(), GraphDelta::new(vec![op]))
735    }
736
737    fn undo(&mut self) -> Result<Outcome> {
738        if self.done == 0 {
739            return Ok(Outcome::said("Nothing to undo"));
740        }
741        let step = &self.steps[self.done - 1];
742        let delta = step.inverse();
743        let text = format!(
744            "Undid {}: {}",
745            step.command,
746            changed(-step.nodes, -step.edges)
747        );
748        self.result.apply(&delta).map_err(model)?;
749        self.degrees.truncate(self.result.n_nodes());
750        if let Some(edges) = &mut self.edges {
751            edges.track(&delta);
752        }
753        self.done -= 1;
754        Ok(Outcome {
755            text,
756            delta: Some(delta),
757        })
758    }
759
760    fn redo(&mut self) -> Result<Outcome> {
761        let Some(step) = self.steps.get(self.done) else {
762            return Ok(Outcome::said("Nothing to redo"));
763        };
764        let delta = step.delta.clone();
765        let text = format!("Redid {}: {}", step.command, step.summary());
766        self.result.apply(&delta).map_err(model)?;
767        self.degrees.truncate(self.result.n_nodes());
768        if let Some(edges) = &mut self.edges {
769            edges.track(&delta);
770        }
771        self.done += 1;
772        Ok(Outcome {
773            text,
774            delta: Some(delta),
775        })
776    }
777
778    /// `.graph history`: what was drawn, then a line a step.
779    fn history(&self) -> String {
780        let r = &self.result;
781        let (nodes, edges) = self.shown();
782        let count = |n: usize, one: &str| {
783            let s = if n == 1 { "" } else { "s" };
784            format!("{} {one}{s}", thousands(n))
785        };
786        let mut out = match r.provenance().sql.as_deref() {
787            Some(sql) => format!("Explored from: {}", sql.replace('\n', " ")),
788            None => match r.graph() {
789                Some(graph) => format!("Explored from: the graph {graph}"),
790                None => "Explored from: a result".to_string(),
791            },
792        };
793        if self.steps.is_empty() {
794            out.push_str("\nNo steps yet: .expand ID adds a node's neighbours");
795        }
796        let width = self.steps.len().to_string().len();
797        let longest = self
798            .steps
799            .iter()
800            .map(|s| s.command.chars().count())
801            .max()
802            .unwrap_or(0);
803        for (i, step) in self.steps.iter().enumerate() {
804            let pad = " ".repeat(longest - step.command.chars().count());
805            let undone = if i < self.done { "" } else { "  (undone)" };
806            out.push_str(&format!(
807                "\n{:>width$}  {}{pad}  {}{undone}",
808                i + 1,
809                step.command,
810                step.summary()
811            ));
812        }
813        out.push_str(&format!(
814            "\nShown: {}, {}",
815            count(nodes, "node"),
816            count(edges, "edge")
817        ));
818        let hidden = r.n_nodes() - nodes;
819        if hidden > 0 {
820            out.push_str(&format!(" ({} hidden)", thousands(hidden)));
821        }
822        out
823    }
824
825    /// `.expand`: see the [module](self).
826    #[allow(clippy::too_many_arguments)]
827    async fn expand(
828        &mut self,
829        ctx: &SessionContext,
830        sql: &dyn RunSql,
831        command: &str,
832        id: &str,
833        direction: Direction,
834        limit: usize,
835        sql_only: bool,
836    ) -> Result<Outcome> {
837        let node = self.resolve(id)? as usize;
838        let Some(graph) = self.result.graph() else {
839            return plan_err(
840                "this drawing is not of a property graph, so there are no neighbours to add; \
841                 draw a graph's nodes first: .graph NAME, or .graph after a query on one \
842                 (hop, a path, an algorithm)",
843            );
844        };
845        if self.result.node_is_removed(node) {
846            return plan_err(format!("node {id} is hidden; .show {id} first"));
847        }
848        let graph = format!("\"{}\"", graph.replace('"', "\"\""));
849        let mut seed = String::new();
850        literal(
851            &mut seed,
852            self.result.node_keys().get(node),
853            self.key_type(node),
854        );
855
856        // 1. The neighbours that are not shown, the highest degree first.
857        let neighbours = format!(
858            "SELECT h.id, count(*) OVER () AS neighbours \
859             FROM hop({graph}, seeds => [{seed}], steps => 1, direction => '{}') AS h \
860             JOIN degree({graph}, direction => 'both') AS d ON d.id = h.id \
861             WHERE h.id NOT IN ({}) \
862             ORDER BY d.degree DESC, h.id LIMIT {limit}",
863            direction.name(),
864            self.keys(false),
865        );
866        let (schema, batches) = sql.run(ctx, &neighbours).await?;
867        let named = schema.field(0).metadata().get(meta::LABEL);
868        let r = &self.result;
869        // The label of a new node: the one the result says, or the node's.
870        let label = named
871            .and_then(|name| r.node_labels().iter().position(|l| &l.name == name))
872            .map_or(r.node_label()[node], |l| l as u16);
873        let key_type = r.node_labels()[label as usize].key;
874        let mut restored: Vec<u32> = Vec::new();
875        let mut added = NodeBatch::new();
876        let mut new: HashMap<Key, u32> = HashMap::new();
877        let mut not_shown = 0usize;
878        for batch in &batches {
879            let ids = Ids::of(batch.column(0))?;
880            let total = cast(batch.column(1), &DataType::UInt64)?;
881            let total = total.as_primitive::<UInt64Type>();
882            for i in 0..batch.num_rows() {
883                not_shown = not_shown.max(total.value(i) as usize);
884                let found = r.node_labels().iter().zip(0u16..).find_map(|(l, at)| {
885                    let key = ids.key(i, l.key)?;
886                    r.node(at, &key)
887                });
888                match found {
889                    Some(at) if r.node_is_removed(at as usize) => restored.push(at),
890                    Some(_) => {}
891                    None => {
892                        let Some(key) = ids.key(i, key_type) else {
893                            continue;
894                        };
895                        let at = (r.n_nodes() + added.len()) as u32;
896                        if new.insert(key.clone(), at).is_none() {
897                            added.push(label, &key);
898                        }
899                    }
900                }
901            }
902        }
903        restored.sort_unstable();
904        restored.dedup();
905
906        // 2. The graph's edges among every node of the session and the new.
907        let mut all = self.keys(true);
908        for key in added.keys.iter() {
909            if !all.is_empty() {
910                all.push_str(", ");
911            }
912            literal(&mut all, key, key_type);
913        }
914        let among = format!("SELECT src, dst, edge FROM induced_edges({graph}, nodes => [{all}])");
915        drop(all);
916        if sql_only {
917            return Ok(Outcome::said(format!("{neighbours};\n{among};")));
918        }
919        let (schema, batches) = sql.run(ctx, &among).await?;
920        let edges = self.edges.get_or_insert_with(|| EdgeIndex::of(r));
921        let edge_label = schema.field(2).metadata().get(meta::LABEL);
922        let at = edge_label.and_then(|name| r.edge_labels().iter().position(|l| l == name));
923        let new_label = match (edge_label, at) {
924            (Some(name), None) => Some(name.clone()),
925            _ => None,
926        };
927        let e_label = match (&new_label, at) {
928            (Some(_), _) => r.edge_labels().len() as u16,
929            (None, at) => at.unwrap_or(0) as u16,
930        };
931        let node_of = |ids: &Ids, i: usize| -> Option<u32> {
932            let found = r.node_labels().iter().zip(0u16..).find_map(|(l, at)| {
933                let key = ids.key(i, l.key)?;
934                r.node(at, &key)
935            });
936            found.or_else(|| new.get(&ids.key(i, key_type)?).copied())
937        };
938        let mut batch = EdgeBatch::new();
939        let mut rows = Vec::new();
940        // How many of each pair's edges with no row this pass has matched.
941        let mut matched: HashMap<(u32, u32), u32> = HashMap::new();
942        for b in &batches {
943            let (s, d) = (Ids::of(b.column(0))?, Ids::of(b.column(1))?);
944            let row = cast(b.column(2), &DataType::UInt64)?;
945            let row = row.as_primitive::<UInt64Type>();
946            for i in 0..b.num_rows() {
947                let (Some(s), Some(d)) = (node_of(&s, i), node_of(&d, i)) else {
948                    continue;
949                };
950                let row = row.is_valid(i).then(|| row.value(i));
951                if row.is_some_and(|row| edges.rows.contains(&(e_label, row))) {
952                    continue;
953                }
954                if let Some(&have) = edges.pairs.get(&pair(s, d)) {
955                    let used = matched.entry(pair(s, d)).or_insert(0);
956                    if *used < have {
957                        *used += 1;
958                        continue;
959                    }
960                }
961                batch.src.push(s);
962                batch.dst.push(d);
963                batch.labels.push(e_label);
964                rows.push(row.unwrap_or(NO_ROW));
965            }
966        }
967        batch.rows = Some(rows);
968
969        let mut ops = Vec::new();
970        if !restored.is_empty() {
971            ops.push(Op::RestoreNodes(restored));
972        }
973        let new_nodes = added.len();
974        if !added.is_empty() {
975            ops.push(Op::AddNodes(added));
976        }
977        if !batch.is_empty() {
978            if let Some(name) = new_label {
979                ops.push(Op::AddEdgeLabel(name));
980            }
981            ops.push(Op::AddEdges(batch));
982        }
983        if ops.is_empty() {
984            let whose = match direction {
985                Direction::Both => "neighbour",
986                Direction::In => "in-neighbour",
987                Direction::Out => "out-neighbour",
988            };
989            return Ok(Outcome::said(format!(
990                "Nothing changed: every {whose} of {id} is shown already, with the edges among \
991                 them"
992            )));
993        }
994        let statements = vec![neighbours, among];
995        let delta = GraphDelta::new(ops).with_provenance(Provenance {
996            sql: Some(statements.join(";\n")),
997            ..Provenance::default()
998        });
999        let mut outcome = self.step(command, statements, delta)?;
1000        let brought = new_nodes + outcome_restored(&outcome);
1001        if not_shown > brought {
1002            let more = not_shown - brought;
1003            let are = if more == 1 {
1004                "neighbour of {id} is"
1005            } else {
1006                "neighbours of {id} are"
1007            };
1008            outcome.text.push_str(&format!(
1009                " ({} more {} not shown: .expand {id} again adds the next)",
1010                thousands(more),
1011                are.replace("{id}", id)
1012            ));
1013        }
1014        Ok(outcome)
1015    }
1016}
1017
1018/// How many nodes an expansion's delta restored.
1019fn outcome_restored(outcome: &Outcome) -> usize {
1020    outcome.delta.as_ref().map_or(0, |delta| {
1021        delta
1022            .ops
1023            .iter()
1024            .map(|op| match op {
1025                Op::RestoreNodes(nodes) => nodes.len(),
1026                _ => 0,
1027            })
1028            .sum()
1029    })
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035
1036    fn parsed(line: &str) -> Command {
1037        Command::parse(line).unwrap().unwrap().command
1038    }
1039
1040    #[test]
1041    fn commands_are_read_from_their_lines() {
1042        assert_eq!(
1043            parsed(".expand 33"),
1044            Command::Expand {
1045                id: "33".into(),
1046                direction: Direction::Both,
1047                limit: EXPAND_LIMIT
1048            }
1049        );
1050        assert_eq!(
1051            parsed("  .EXPAND 'a b' In limit 7 ; "),
1052            Command::Expand {
1053                id: "a b".into(),
1054                direction: Direction::In,
1055                limit: 7
1056            }
1057        );
1058        assert_eq!(
1059            parsed(".hide 1 \"it's\" 'o''neil'"),
1060            Command::Hide(vec!["1".into(), "it's".into(), "o'neil".into()])
1061        );
1062        assert_eq!(parsed(".show ALL"), Command::Show(Vec::new()));
1063        assert_eq!(
1064            parsed(".show all 3"),
1065            Command::Show(vec!["all".into(), "3".into()])
1066        );
1067        assert_eq!(parsed(".undo;"), Command::Undo);
1068        assert_eq!(parsed(".redo"), Command::Redo);
1069        assert_eq!(parsed(".graph History"), Command::History);
1070        let sql = Command::parse(".expand 5 --sql out").unwrap().unwrap();
1071        assert!(sql.sql_only);
1072        assert_eq!(sql.text, ".expand 5 --sql out");
1073        assert_eq!(
1074            sql.command,
1075            Command::Expand {
1076                id: "5".into(),
1077                direction: Direction::Out,
1078                limit: EXPAND_LIMIT
1079            }
1080        );
1081    }
1082
1083    #[test]
1084    fn other_lines_are_not_explore_commands() {
1085        for line in [
1086            ".graph",
1087            ".graph karate",
1088            ".graph SELECT history FROM t",
1089            ".tables",
1090            "SELECT 1",
1091            "",
1092        ] {
1093            assert_eq!(Command::parse(line).unwrap(), None, "{line}");
1094        }
1095        for line in [
1096            ".expand",
1097            ".expand 1 2",
1098            ".expand 1 in out",
1099            ".expand 1 LIMIT",
1100            ".expand 1 LIMIT x",
1101            ".hide",
1102            ".hide 'open",
1103            ".redo 2",
1104        ] {
1105            assert!(Command::parse(line).is_err(), "{line}");
1106        }
1107    }
1108
1109    #[test]
1110    fn changes_are_signed_and_counted() {
1111        assert_eq!(changed(16, 41), "+16 nodes, +41 edges");
1112        assert_eq!(changed(-1, -1), "-1 node, -1 edge");
1113        assert_eq!(changed(0, 1200), "+0 nodes, +1,200 edges");
1114    }
1115}