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//! | `.expand group:N` | in a drawing grouped by `GROUP BY`: opens group N, adding its members and the graph's edges among the members of the open groups | `induced_edges` |
21//! | `.collapse group:N` | closes group N: its members are hidden | none |
22//! | `.hide ID…` | hides nodes | none |
23//! | `.show ID…` or `.show all` | shows hidden nodes again | none |
24//! | `.undo`, `.redo` | steps the history | none |
25//! | `.graph history` | lists the steps | none |
26//!
27//! `--sql` on a command prints its SQL and changes nothing: no step, no
28//! delta. For `.expand` it prints both statements as a step would run them,
29//! and to do so it runs the first, a query, whose rows are the nodes the
30//! second names.
31//!
32//! # Expanding
33//!
34//! `.expand 33` runs two statements ([`Session::run`] gives them back in the
35//! step):
36//!
37//! 1. The neighbours to add: `hop` one step from the node (`both`
38//!    directions unless the command says `in` or `out`), without the nodes
39//!    that are shown, ordered by their degree in the graph (both directions,
40//!    highest first) and then by key, and cut at the limit
41//!    ([`EXPAND_LIMIT`], or `LIMIT n` up to [`MAX_EXPAND`]). The order is
42//!    total, so the same command always adds the same nodes, in the same
43//!    order. Expanding again adds the next ones.
44//! 2. The edges: `induced_edges` over every node of the session and the new
45//!    ones. An edge the session already has is left out: by its label and
46//!    its row in the edge table where both are known, else by the two nodes
47//!    it joins and its place among their parallel edges.
48//!
49//! The delta restores the neighbours that were hidden, appends the new nodes
50//! (in the order of statement 1) and then the new edges (in the order of
51//! statement 2, which is the edge table's). Hidden nodes are part of
52//! statement 2, so their edges to newer nodes are in the session when
53//! `.show` brings them back, with no query.
54//!
55//! # Groups
56//!
57//! A drawing made with `GROUP BY` ([`super::groups`], #499) has a node for
58//! each group and none of the groups' members; a session on it
59//! ([`Session::grouped`]) knows which nodes each group has. `.expand
60//! group:3` opens the group keyed 3, in one statement: `induced_edges` over
61//! its members and the members of the groups already open. The delta adds
62//! the members (in the drawing's node order, each with its group's value in
63//! the column the result is grouped by and its place in the group's disc in `group x` and
64//! `group y`: [`super::groups::disc_layout`] of the group's members and the
65//! edges among them) and then the edges the session does not have. The
66//! group's own node stays, with the edges to the other groups: a view
67//! draws the members in its disc. `.collapse group:3` hides the members,
68//! and opening the group again shows them, with no query. `.undo` of the
69//! step that opened a group takes its members and their edges away again.
70//! In such a session `.expand` opens groups only.
71//!
72//! # Undo
73//!
74//! Every op of a delta carries what its inverse needs, so `.undo` applies
75//! [`GraphDelta::invert`] of the last step and runs no SQL, and `.redo`
76//! applies the step's delta again. A new step drops the steps that were
77//! undone.
78
79use std::collections::{HashMap, HashSet};
80
81use datafusion::arrow::array::RecordBatch;
82use datafusion::arrow::array::{Array, ArrayRef, AsArray, Int64Array, StringArray};
83use datafusion::arrow::compute::cast;
84use datafusion::arrow::datatypes::SchemaRef;
85use datafusion::arrow::datatypes::{DataType, Int64Type, UInt64Type};
86use datafusion::error::{DataFusionError, Result};
87use datafusion::prelude::SessionContext;
88use ursa_viz::model::{
89    BatchValues, EdgeBatch, GraphDelta, GraphResult, Key, KeyType, NodeBatch, Op, Provenance,
90    Strings, Values, NO_ROW,
91};
92
93use super::groups::{self, Grouping};
94use super::{plan_err, thousands, RunSql};
95use crate::graph::provenance as meta;
96
97/// How many neighbours `.expand` adds unless it says `LIMIT n`.
98pub const EXPAND_LIMIT: usize = 100;
99/// The most `LIMIT n` may ask for.
100pub const MAX_EXPAND: usize = 5_000;
101
102/// Which of a node's edges `.expand` follows.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum Direction {
105    In,
106    Out,
107    Both,
108}
109
110impl Direction {
111    /// As `hop`'s `direction` takes it.
112    pub fn name(self) -> &'static str {
113        match self {
114            Direction::In => "in",
115            Direction::Out => "out",
116            Direction::Both => "both",
117        }
118    }
119}
120
121/// An explore command, read from its line.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub enum Command {
124    Expand {
125        id: String,
126        direction: Direction,
127        limit: usize,
128    },
129    /// `.collapse group:N`: the group to close.
130    Collapse(String),
131    Hide(Vec<String>),
132    /// The ids to show; none for `.show all`.
133    Show(Vec<String>),
134    Undo,
135    Redo,
136    History,
137}
138
139/// A command and whether it asked for its SQL alone (`--sql`).
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Parsed {
142    pub command: Command,
143    pub sql_only: bool,
144    /// The line as the history shows it: trimmed, with no `;`.
145    pub text: String,
146}
147
148/// The words of a command: split at spaces, a quoted word (`'a b'`, `"a b"`)
149/// kept whole without its quotes, a doubled quote inside one being one.
150fn words(text: &str) -> Result<Vec<String>> {
151    let mut out = Vec::new();
152    let mut chars = text.chars().peekable();
153    while let Some(&c) = chars.peek() {
154        if c.is_whitespace() {
155            chars.next();
156            continue;
157        }
158        let mut word = String::new();
159        if c == '\'' || c == '"' {
160            chars.next();
161            loop {
162                match chars.next() {
163                    None => return plan_err(format!("a quote ({c}) is not closed in: {text}")),
164                    Some(x) if x == c => {
165                        if chars.peek() == Some(&c) {
166                            chars.next();
167                            word.push(c);
168                        } else {
169                            break;
170                        }
171                    }
172                    Some(x) => word.push(x),
173                }
174            }
175        } else {
176            while let Some(&x) = chars.peek() {
177                if x.is_whitespace() {
178                    break;
179                }
180                word.push(x);
181                chars.next();
182            }
183        }
184        out.push(word);
185    }
186    Ok(out)
187}
188
189impl Command {
190    /// The names of the explore commands, as typed: `.graph` is one only as
191    /// `.graph history`.
192    pub const NAMES: [&'static str; 6] =
193        [".expand", ".collapse", ".hide", ".show", ".undo", ".redo"];
194
195    /// Read `line`. `Ok(None)` when it is not an explore command (`.graph
196    /// karate`, `.tables`); an error when it is one that cannot be read.
197    pub fn parse(line: &str) -> Result<Option<Parsed>> {
198        let text = line.trim().trim_end_matches(';').trim_end();
199        let (name, rest) = match text.find(char::is_whitespace) {
200            Some(at) => (&text[..at], text[at..].trim()),
201            None => (text, ""),
202        };
203        let name = name.to_ascii_lowercase();
204        if name == ".graph" {
205            if !rest
206                .split_whitespace()
207                .next()
208                .is_some_and(|w| w.eq_ignore_ascii_case("history"))
209            {
210                return Ok(None);
211            }
212        } else if !Self::NAMES.contains(&name.as_str()) {
213            return Ok(None);
214        }
215        let mut args = words(rest)?;
216        let before = args.len();
217        args.retain(|a| a != "--sql");
218        let sql_only = args.len() != before;
219        let command = match name.as_str() {
220            ".expand" => {
221                const USAGE: &str = "usage: .expand ID [in|out|both] [LIMIT n]";
222                let mut args = args.into_iter();
223                let Some(id) = args.next() else {
224                    return plan_err(USAGE);
225                };
226                let mut direction = None;
227                let mut limit = None;
228                while let Some(word) = args.next() {
229                    match word.to_ascii_lowercase().as_str() {
230                        "in" if direction.is_none() => direction = Some(Direction::In),
231                        "out" if direction.is_none() => direction = Some(Direction::Out),
232                        "both" if direction.is_none() => direction = Some(Direction::Both),
233                        "limit" if limit.is_none() => {
234                            let n = args.next().and_then(|n| n.parse::<usize>().ok());
235                            match n {
236                                Some(n) if (1..=MAX_EXPAND).contains(&n) => limit = Some(n),
237                                _ => {
238                                    return plan_err(format!(
239                                        "LIMIT takes a number of neighbours from 1 to {}; {USAGE}",
240                                        thousands(MAX_EXPAND)
241                                    ))
242                                }
243                            }
244                        }
245                        _ => {
246                            return plan_err(format!(
247                                "'{word}' is not part of .expand (one node at a time); {USAGE}"
248                            ))
249                        }
250                    }
251                }
252                Command::Expand {
253                    id,
254                    direction: direction.unwrap_or(Direction::Both),
255                    limit: limit.unwrap_or(EXPAND_LIMIT),
256                }
257            }
258            ".collapse" => {
259                if args.len() != 1 {
260                    return plan_err("usage: .collapse group:N");
261                }
262                Command::Collapse(args.remove(0))
263            }
264            ".hide" => {
265                if args.is_empty() {
266                    return plan_err("usage: .hide ID…");
267                }
268                Command::Hide(args)
269            }
270            ".show" => {
271                if args.is_empty() {
272                    return plan_err("usage: .show ID… or .show all");
273                }
274                if args.len() == 1 && args[0].eq_ignore_ascii_case("all") {
275                    Command::Show(Vec::new())
276                } else {
277                    Command::Show(args)
278                }
279            }
280            ".undo" | ".redo" => {
281                if !args.is_empty() {
282                    return plan_err(format!("usage: {name}"));
283                }
284                if name == ".undo" {
285                    Command::Undo
286                } else {
287                    Command::Redo
288                }
289            }
290            _ => {
291                if args.len() != 1 {
292                    return plan_err("usage: .graph history");
293                }
294                Command::History
295            }
296        };
297        Ok(Some(Parsed {
298            command,
299            sql_only,
300            text: text.to_string(),
301        }))
302    }
303}
304
305/// One step of an exploration.
306#[derive(Debug, Clone, PartialEq)]
307pub struct Step {
308    /// The command, as typed.
309    pub command: String,
310    /// The statements it ran, in order; none for a step that reads nothing
311    /// (`.hide`, `.show`).
312    pub sql: Vec<String>,
313    /// What it changed.
314    pub delta: GraphDelta,
315    /// How many more nodes and edges were shown after it (fewer, when
316    /// negative).
317    pub nodes: i64,
318    pub edges: i64,
319}
320
321impl Step {
322    /// The delta that undoes the step.
323    pub fn inverse(&self) -> GraphDelta {
324        self.delta.invert()
325    }
326
327    /// `+16 nodes, +41 edges`.
328    pub fn summary(&self) -> String {
329        changed(self.nodes, self.edges)
330    }
331}
332
333/// `+16 nodes, +41 edges`; `-1 node, -3 edges`.
334fn changed(nodes: i64, edges: i64) -> String {
335    let part = |n: i64, one: &str| {
336        let sign = if n < 0 { '-' } else { '+' };
337        let s = if n.unsigned_abs() == 1 { "" } else { "s" };
338        format!("{sign}{} {one}{s}", thousands(n.unsigned_abs() as usize))
339    };
340    format!("{}, {}", part(nodes, "node"), part(edges, "edge"))
341}
342
343/// What a command did.
344#[derive(Debug, Clone, PartialEq)]
345pub struct Outcome {
346    /// What to print: one line for a command that changes the graph (what
347    /// changed, or why nothing did), the SQL for `--sql`, the steps for
348    /// `.graph history`. No newline at the end.
349    pub text: String,
350    /// The change for the view to apply, if there is one.
351    pub delta: Option<GraphDelta>,
352}
353
354impl Outcome {
355    fn said(text: impl Into<String>) -> Outcome {
356        Outcome {
357            text: text.into(),
358            delta: None,
359        }
360    }
361}
362
363/// Two nodes, whichever way an edge joins them. A drawing's edge with no row
364/// may be drawn against the way the graph stores it (a path's steps are).
365fn pair(a: u32, b: u32) -> (u32, u32) {
366    (a.min(b), a.max(b))
367}
368
369/// The session's edges, by what makes one the same edge: its label and row
370/// where the engine knew the row, else the two nodes it joins (and how many
371/// such edges join them).
372#[derive(Debug, Default)]
373struct EdgeIndex {
374    rows: HashSet<(u16, u64)>,
375    pairs: HashMap<(u32, u32), u32>,
376}
377
378impl EdgeIndex {
379    fn of(result: &GraphResult) -> EdgeIndex {
380        let mut index = EdgeIndex::default();
381        let (src, dst, label) = (result.src(), result.dst(), result.edge_label());
382        for i in 0..result.n_edges() {
383            index.add(src[i], dst[i], label[i], result.edge_row(i));
384        }
385        index
386    }
387
388    fn add(&mut self, src: u32, dst: u32, label: u16, row: Option<u64>) {
389        match row {
390            Some(row) => {
391                self.rows.insert((label, row));
392            }
393            None => *self.pairs.entry(pair(src, dst)).or_insert(0) += 1,
394        }
395    }
396
397    fn remove(&mut self, src: u32, dst: u32, label: u16, row: Option<u64>) {
398        match row {
399            Some(row) => {
400                self.rows.remove(&(label, row));
401            }
402            None => {
403                let pair = pair(src, dst);
404                if let Some(count) = self.pairs.get_mut(&pair) {
405                    *count -= 1;
406                    if *count == 0 {
407                        self.pairs.remove(&pair);
408                    }
409                }
410            }
411        }
412    }
413
414    /// Keep up with a delta the session applied.
415    fn track(&mut self, delta: &GraphDelta) {
416        let each = |batch: &EdgeBatch, f: &mut dyn FnMut(u32, u32, u16, Option<u64>)| {
417            for i in 0..batch.len() {
418                let row = batch
419                    .rows
420                    .as_ref()
421                    .map(|rows| rows[i])
422                    .filter(|&r| r != NO_ROW);
423                f(batch.src[i], batch.dst[i], batch.labels[i], row);
424            }
425        };
426        for op in &delta.ops {
427            match op {
428                Op::AddEdges(batch) => each(batch, &mut |s, d, l, r| self.add(s, d, l, r)),
429                Op::PopEdges(batch) => each(batch, &mut |s, d, l, r| self.remove(s, d, l, r)),
430                _ => {}
431            }
432        }
433    }
434}
435
436/// A column of node ids, as integers where it is one of integers.
437enum Ids {
438    Int(Int64Array),
439    Text(StringArray),
440}
441
442impl Ids {
443    fn of(array: &ArrayRef) -> Result<Ids> {
444        let integers = matches!(
445            array.data_type(),
446            DataType::Int8
447                | DataType::Int16
448                | DataType::Int32
449                | DataType::Int64
450                | DataType::UInt8
451                | DataType::UInt16
452                | DataType::UInt32
453        );
454        if integers {
455            let cast = cast(array, &DataType::Int64)?;
456            Ok(Ids::Int(cast.as_primitive::<Int64Type>().clone()))
457        } else {
458            let cast = cast(array, &DataType::Utf8)?;
459            Ok(Ids::Text(cast.as_string::<i32>().clone()))
460        }
461    }
462
463    /// Row `i`'s id as a key of type `ty`, if it is one (and not NULL).
464    fn key(&self, i: usize, ty: KeyType) -> Option<Key> {
465        match (self, ty) {
466            (Ids::Int(a), _) if a.is_null(i) => None,
467            (Ids::Text(a), _) if a.is_null(i) => None,
468            (Ids::Int(a), KeyType::Int) => Some(Key::Int(a.value(i))),
469            (Ids::Int(a), KeyType::Text) => Some(Key::Text(a.value(i).to_string())),
470            (Ids::Text(a), ty) => Key::parse(ty, a.value(i)).ok(),
471        }
472    }
473}
474
475/// `key` as a SQL literal.
476fn literal(out: &mut String, key: &str, ty: KeyType) {
477    match ty {
478        KeyType::Int => out.push_str(key),
479        KeyType::Text => {
480            out.push('\'');
481            out.push_str(&key.replace('\'', "''"));
482            out.push('\'');
483        }
484    }
485}
486
487fn model(e: ursa_viz::model::ModelError) -> DataFusionError {
488    DataFusionError::Plan(format!("the graph cannot be changed: {e}"))
489}
490
491/// The explore session of one drawing. See the [module](self).
492#[derive(Debug)]
493pub struct Session {
494    result: GraphResult,
495    steps: Vec<Step>,
496    /// How many of `steps` are applied; the rest were undone.
497    done: usize,
498    /// Made by the first `.expand`, and kept up after it.
499    edges: Option<EdgeIndex>,
500    /// Each node's degree in the property graph (both directions, every
501    /// edge counted), by slot, for the slots asked about so far
502    /// ([`Session::not_shown`]); [`NO_DEGREE`] for a node the graph has no
503    /// row for.
504    degrees: Vec<u32>,
505    /// Of a drawing made with `GROUP BY`: which nodes each group has.
506    groups: Option<Grouping>,
507}
508
509/// The degree of a node the graph's `degree` has no row for.
510const NO_DEGREE: u32 = u32::MAX;
511/// Up to this many nodes' degrees are asked for by key; more, and the whole
512/// graph's are read.
513const DEGREES_BY_KEY: usize = 1_000;
514
515impl Session {
516    /// A session on what `.graph` drew.
517    pub fn new(base: GraphResult) -> Session {
518        Session {
519            result: base,
520            steps: Vec::new(),
521            done: 0,
522            edges: None,
523            degrees: Vec::new(),
524            groups: None,
525        }
526    }
527
528    /// A session on what `.graph … GROUP BY` drew: `base` is the grouped
529    /// result and `groups` its groups' members (`GraphView::groups`), which
530    /// `.expand group:N` opens.
531    pub fn grouped(base: GraphResult, groups: Grouping) -> Session {
532        Session {
533            groups: Some(groups),
534            ..Session::new(base)
535        }
536    }
537
538    /// The groups of a session on a grouped drawing.
539    pub fn grouping(&self) -> Option<&Grouping> {
540        self.groups.as_ref()
541    }
542
543    /// The graph as it stands: the base with every applied step.
544    pub fn result(&self) -> &GraphResult {
545        &self.result
546    }
547
548    /// Every step, the undone ones included: `steps()[..applied()]` are in
549    /// the graph.
550    pub fn steps(&self) -> &[Step] {
551        &self.steps
552    }
553
554    /// How many steps are applied.
555    pub fn applied(&self) -> usize {
556        self.done
557    }
558
559    /// How many nodes and edges are shown.
560    pub fn shown(&self) -> (usize, usize) {
561        let r = &self.result;
562        let nodes = r.node_flags().iter().filter(|&&f| f == 0).count();
563        let edges = (0..r.n_edges()).filter(|&i| r.edge_is_shown(i)).count();
564        (nodes, edges)
565    }
566
567    /// The node `id` names: of the first label that has the key.
568    /// For each node slot, how many of the node's edges in the property
569    /// graph lead to something that is not shown: its degree in the graph
570    /// (both directions, every edge counted, as `degree` counts) less its
571    /// shown edges here. It is what a view's `+N` badge says, and 0 for a
572    /// hidden node and for one the graph does not have. Empty when the
573    /// drawing is not of a property graph.
574    ///
575    /// The graph's degrees are read once for each node (one `degree` query
576    /// for the nodes not asked about before: by key for up to
577    /// [`DEGREES_BY_KEY`] of them, else the whole graph's), and the shown
578    /// edges are counted each time.
579    pub async fn not_shown(&mut self, ctx: &SessionContext, sql: &dyn RunSql) -> Result<Vec<u32>> {
580        // A group is no node of the graph: it has no degree there.
581        if self.groups.is_some() {
582            return Ok(Vec::new());
583        }
584        let Some(graph) = self.result.graph() else {
585            return Ok(Vec::new());
586        };
587        let n = self.result.n_nodes();
588        self.degrees.truncate(n);
589        let known = self.degrees.len();
590        if known < n {
591            let graph = format!("\"{}\"", graph.replace('"', "\"\""));
592            let mut query = format!("SELECT id, degree FROM degree({graph}, direction => 'both')");
593            let one_type = (known..n).all(|i| self.key_type(i) == self.key_type(known));
594            if n - known <= DEGREES_BY_KEY && one_type {
595                query.push_str(" WHERE id IN (");
596                for i in known..n {
597                    if i > known {
598                        query.push_str(", ");
599                    }
600                    literal(&mut query, self.result.node_keys().get(i), self.key_type(i));
601                }
602                query.push(')');
603            }
604            let (_, batches) = sql.run(ctx, &query).await?;
605            let r = &self.result;
606            let mut degrees = vec![NO_DEGREE; n - known];
607            for batch in &batches {
608                let ids = Ids::of(batch.column(0))?;
609                let degree = cast(batch.column(1), &DataType::UInt64)?;
610                let degree = degree.as_primitive::<UInt64Type>();
611                for i in 0..batch.num_rows() {
612                    let found = r.node_labels().iter().zip(0u16..).find_map(|(l, at)| {
613                        let key = ids.key(i, l.key)?;
614                        r.node(at, &key)
615                    });
616                    if let Some(at) = found.filter(|&at| at as usize >= known) {
617                        degrees[at as usize - known] =
618                            degree.value(i).min(u64::from(u32::MAX - 1)) as u32;
619                    }
620                }
621            }
622            self.degrees.extend(degrees);
623        }
624        let r = &self.result;
625        let mut shown = vec![0u32; n];
626        let (src, dst) = (r.src(), r.dst());
627        for e in 0..r.n_edges() {
628            if r.edge_is_shown(e) {
629                shown[src[e] as usize] += 1;
630                shown[dst[e] as usize] += 1;
631            }
632        }
633        Ok((0..n)
634            .map(|i| match self.degrees[i] {
635                NO_DEGREE => 0,
636                _ if r.node_is_removed(i) => 0,
637                degree => degree.saturating_sub(shown[i]),
638            })
639            .collect())
640    }
641
642    fn find(&self, id: &str) -> Option<u32> {
643        let r = &self.result;
644        // In a grouped drawing `group:3` is a group, and any other id a
645        // member of an open one.
646        let skip = if self.groups.is_some() {
647            if let Some(group) = group_id(id) {
648                return group.and_then(|g| r.node(0, &Key::Int(g)));
649            }
650            1
651        } else {
652            0
653        };
654        r.node_labels()
655            .iter()
656            .zip(0u16..)
657            .skip(skip)
658            .find_map(|(label, l)| {
659                let key = Key::parse(label.key, id).ok()?;
660                r.node(l, &key)
661            })
662    }
663
664    fn resolve(&self, id: &str) -> Result<u32> {
665        match self.find(id) {
666            Some(node) => Ok(node),
667            None => plan_err(format!(
668                "no node '{id}' in the graph that is drawn; a node is named by its key, as the \
669                 graph view shows it"
670            )),
671        }
672    }
673
674    /// The key type of node `i`'s label.
675    fn key_type(&self, i: usize) -> KeyType {
676        self.result.node_labels()[self.result.node_label()[i] as usize].key
677    }
678
679    /// The keys of the session's nodes as a SQL list's items: the shown
680    /// ones, or all of them.
681    fn keys(&self, hidden_too: bool) -> String {
682        let r = &self.result;
683        let mut out = String::with_capacity(r.n_nodes() * 8);
684        for i in 0..r.n_nodes() {
685            if !hidden_too && r.node_is_removed(i) {
686                continue;
687            }
688            if !out.is_empty() {
689                out.push_str(", ");
690            }
691            literal(&mut out, r.node_keys().get(i), self.key_type(i));
692        }
693        out
694    }
695
696    /// Apply `delta` as a new step, dropping the steps that were undone.
697    fn step(&mut self, command: &str, sql: Vec<String>, delta: GraphDelta) -> Result<Outcome> {
698        let before = self.shown();
699        self.result.apply(&delta).map_err(model)?;
700        self.degrees.truncate(self.result.n_nodes());
701        if let Some(edges) = &mut self.edges {
702            edges.track(&delta);
703        }
704        let after = self.shown();
705        let step = Step {
706            command: command.to_string(),
707            sql,
708            delta: delta.clone(),
709            nodes: after.0 as i64 - before.0 as i64,
710            edges: after.1 as i64 - before.1 as i64,
711        };
712        let text = step.summary();
713        self.steps.truncate(self.done);
714        self.steps.push(step);
715        self.done += 1;
716        Ok(Outcome {
717            text,
718            delta: Some(delta),
719        })
720    }
721
722    /// Run one command: `.expand`, `.hide`, `.show`, `.undo`, `.redo` or
723    /// `.graph history`, as [`Command::parse`] reads it. `sql` runs the
724    /// statements of `.expand` on `ctx`.
725    ///
726    /// An error (a line that is not a command, an id that is not a node, SQL
727    /// that failed) changes nothing.
728    pub async fn run(
729        &mut self,
730        ctx: &SessionContext,
731        sql: &dyn RunSql,
732        line: &str,
733    ) -> Result<Outcome> {
734        let Some(parsed) = Command::parse(line)? else {
735            return plan_err(format!(
736                "'{}' is not an explore command; they are .expand, .collapse, .hide, .show, \
737                 .undo, .redo and .graph history",
738                line.trim()
739            ));
740        };
741        let Parsed {
742            command,
743            sql_only,
744            text,
745        } = parsed;
746        match command {
747            Command::Expand {
748                id,
749                direction,
750                limit,
751            } => {
752                if self.groups.is_some() {
753                    return self.open(ctx, sql, &text, &id, sql_only).await;
754                }
755                self.expand(ctx, sql, &text, &id, direction, limit, sql_only)
756                    .await
757            }
758            _ if sql_only => {
759                let name = text.split_whitespace().next().unwrap_or_default();
760                Ok(Outcome::said(format!(
761                    "-- {name} runs no SQL: it changes what is shown of the graph"
762                )))
763            }
764            Command::Collapse(id) => self.collapse(&text, &id),
765            Command::Hide(ids) => self.set_hidden(&text, &ids, true),
766            Command::Show(ids) => self.set_hidden(&text, &ids, false),
767            Command::Undo => self.undo(),
768            Command::Redo => self.redo(),
769            Command::History => Ok(Outcome::said(self.history())),
770        }
771    }
772
773    /// `.hide` (`hide`) or `.show`; no ids is every hidden node.
774    fn set_hidden(&mut self, command: &str, ids: &[String], hide: bool) -> Result<Outcome> {
775        let r = &self.result;
776        let mut nodes: Vec<u32> = if ids.is_empty() {
777            (0..r.n_nodes() as u32).collect()
778        } else {
779            let mut nodes = Vec::with_capacity(ids.len());
780            for id in ids {
781                nodes.push(self.resolve(id)?);
782            }
783            nodes
784        };
785        nodes.sort_unstable();
786        nodes.dedup();
787        nodes.retain(|&i| r.node_is_removed(i as usize) != hide);
788        if nodes.is_empty() {
789            let (state, named) = if hide {
790                ("hidden", ids.join(", "))
791            } else if ids.is_empty() {
792                return Ok(Outcome::said("Nothing changed: no node is hidden"));
793            } else {
794                ("shown", ids.join(", "))
795            };
796            let verb = if ids.len() == 1 { "is" } else { "are" };
797            return Ok(Outcome::said(format!(
798                "Nothing changed: {named} {verb} already {state}"
799            )));
800        }
801        let op = if hide {
802            Op::RemoveNodes(nodes)
803        } else {
804            Op::RestoreNodes(nodes)
805        };
806        self.step(command, Vec::new(), GraphDelta::new(vec![op]))
807    }
808
809    fn undo(&mut self) -> Result<Outcome> {
810        if self.done == 0 {
811            return Ok(Outcome::said("Nothing to undo"));
812        }
813        let step = &self.steps[self.done - 1];
814        let delta = step.inverse();
815        let text = format!(
816            "Undid {}: {}",
817            step.command,
818            changed(-step.nodes, -step.edges)
819        );
820        self.result.apply(&delta).map_err(model)?;
821        self.degrees.truncate(self.result.n_nodes());
822        if let Some(edges) = &mut self.edges {
823            edges.track(&delta);
824        }
825        self.done -= 1;
826        Ok(Outcome {
827            text,
828            delta: Some(delta),
829        })
830    }
831
832    fn redo(&mut self) -> Result<Outcome> {
833        let Some(step) = self.steps.get(self.done) else {
834            return Ok(Outcome::said("Nothing to redo"));
835        };
836        let delta = step.delta.clone();
837        let text = format!("Redid {}: {}", step.command, step.summary());
838        self.result.apply(&delta).map_err(model)?;
839        self.degrees.truncate(self.result.n_nodes());
840        if let Some(edges) = &mut self.edges {
841            edges.track(&delta);
842        }
843        self.done += 1;
844        Ok(Outcome {
845            text,
846            delta: Some(delta),
847        })
848    }
849
850    /// `.graph history`: what was drawn, then a line a step.
851    fn history(&self) -> String {
852        let r = &self.result;
853        let (nodes, edges) = self.shown();
854        let count = |n: usize, one: &str| {
855            let s = if n == 1 { "" } else { "s" };
856            format!("{} {one}{s}", thousands(n))
857        };
858        let mut out = match r.provenance().sql.as_deref() {
859            Some(sql) => format!("Explored from: {}", sql.replace('\n', " ")),
860            None => match r.graph() {
861                Some(graph) => format!("Explored from: the graph {graph}"),
862                None => "Explored from: a result".to_string(),
863            },
864        };
865        if self.steps.is_empty() {
866            out.push_str("\nNo steps yet: .expand ID adds a node's neighbours");
867        }
868        let width = self.steps.len().to_string().len();
869        let longest = self
870            .steps
871            .iter()
872            .map(|s| s.command.chars().count())
873            .max()
874            .unwrap_or(0);
875        for (i, step) in self.steps.iter().enumerate() {
876            let pad = " ".repeat(longest - step.command.chars().count());
877            let undone = if i < self.done { "" } else { "  (undone)" };
878            out.push_str(&format!(
879                "\n{:>width$}  {}{pad}  {}{undone}",
880                i + 1,
881                step.command,
882                step.summary()
883            ));
884        }
885        out.push_str(&format!(
886            "\nShown: {}, {}",
887            count(nodes, "node"),
888            count(edges, "edge")
889        ));
890        let hidden = r.n_nodes() - nodes;
891        if hidden > 0 {
892            out.push_str(&format!(" ({} hidden)", thousands(hidden)));
893        }
894        out
895    }
896
897    /// `.expand`: see the [module](self).
898    #[allow(clippy::too_many_arguments)]
899    async fn expand(
900        &mut self,
901        ctx: &SessionContext,
902        sql: &dyn RunSql,
903        command: &str,
904        id: &str,
905        direction: Direction,
906        limit: usize,
907        sql_only: bool,
908    ) -> Result<Outcome> {
909        let node = self.resolve(id)? as usize;
910        let Some(graph) = self.result.graph() else {
911            return plan_err(
912                "this drawing is not of a property graph, so there are no neighbours to add; \
913                 draw a graph's nodes first: .graph NAME, or .graph after a query on one \
914                 (hop, a path, an algorithm)",
915            );
916        };
917        if self.result.node_is_removed(node) {
918            return plan_err(format!("node {id} is hidden; .show {id} first"));
919        }
920        let graph = format!("\"{}\"", graph.replace('"', "\"\""));
921        let mut seed = String::new();
922        literal(
923            &mut seed,
924            self.result.node_keys().get(node),
925            self.key_type(node),
926        );
927
928        // 1. The neighbours that are not shown, the highest degree first.
929        let neighbours = format!(
930            "SELECT h.id, count(*) OVER () AS neighbours \
931             FROM hop({graph}, seeds => [{seed}], steps => 1, direction => '{}') AS h \
932             JOIN degree({graph}, direction => 'both') AS d ON d.id = h.id \
933             WHERE h.id NOT IN ({}) \
934             ORDER BY d.degree DESC, h.id LIMIT {limit}",
935            direction.name(),
936            self.keys(false),
937        );
938        let (schema, batches) = sql.run(ctx, &neighbours).await?;
939        let named = schema.field(0).metadata().get(meta::LABEL);
940        let r = &self.result;
941        // The label of a new node: the one the result says, or the node's.
942        let label = named
943            .and_then(|name| r.node_labels().iter().position(|l| &l.name == name))
944            .map_or(r.node_label()[node], |l| l as u16);
945        let key_type = r.node_labels()[label as usize].key;
946        let mut restored: Vec<u32> = Vec::new();
947        let mut added = NodeBatch::new();
948        let mut new: HashMap<Key, u32> = HashMap::new();
949        let mut not_shown = 0usize;
950        for batch in &batches {
951            let ids = Ids::of(batch.column(0))?;
952            let total = cast(batch.column(1), &DataType::UInt64)?;
953            let total = total.as_primitive::<UInt64Type>();
954            for i in 0..batch.num_rows() {
955                not_shown = not_shown.max(total.value(i) as usize);
956                let found = r.node_labels().iter().zip(0u16..).find_map(|(l, at)| {
957                    let key = ids.key(i, l.key)?;
958                    r.node(at, &key)
959                });
960                match found {
961                    Some(at) if r.node_is_removed(at as usize) => restored.push(at),
962                    Some(_) => {}
963                    None => {
964                        let Some(key) = ids.key(i, key_type) else {
965                            continue;
966                        };
967                        let at = (r.n_nodes() + added.len()) as u32;
968                        if new.insert(key.clone(), at).is_none() {
969                            added.push(label, &key);
970                        }
971                    }
972                }
973            }
974        }
975        restored.sort_unstable();
976        restored.dedup();
977
978        // 2. The graph's edges among every node of the session and the new.
979        let mut all = self.keys(true);
980        for key in added.keys.iter() {
981            if !all.is_empty() {
982                all.push_str(", ");
983            }
984            literal(&mut all, key, key_type);
985        }
986        let among = format!("SELECT src, dst, edge FROM induced_edges({graph}, nodes => [{all}])");
987        drop(all);
988        if sql_only {
989            return Ok(Outcome::said(format!("{neighbours};\n{among};")));
990        }
991        let (schema, batches) = sql.run(ctx, &among).await?;
992        let edges = self.edges.get_or_insert_with(|| EdgeIndex::of(r));
993        let node_of = |ids: &Ids, i: usize| -> Option<u32> {
994            let found = r.node_labels().iter().zip(0u16..).find_map(|(l, at)| {
995                let key = ids.key(i, l.key)?;
996                r.node(at, &key)
997            });
998            found.or_else(|| new.get(&ids.key(i, key_type)?).copied())
999        };
1000        let (batch, new_label) = new_edges(edges, r, &schema, &batches, node_of, |_, _| {})?;
1001
1002        let mut ops = Vec::new();
1003        if !restored.is_empty() {
1004            ops.push(Op::RestoreNodes(restored));
1005        }
1006        let new_nodes = added.len();
1007        if !added.is_empty() {
1008            ops.push(Op::AddNodes(added));
1009        }
1010        if !batch.is_empty() {
1011            if let Some(name) = new_label {
1012                ops.push(Op::AddEdgeLabel(name));
1013            }
1014            ops.push(Op::AddEdges(batch));
1015        }
1016        if ops.is_empty() {
1017            let whose = match direction {
1018                Direction::Both => "neighbour",
1019                Direction::In => "in-neighbour",
1020                Direction::Out => "out-neighbour",
1021            };
1022            return Ok(Outcome::said(format!(
1023                "Nothing changed: every {whose} of {id} is shown already, with the edges among \
1024                 them"
1025            )));
1026        }
1027        let statements = vec![neighbours, among];
1028        let delta = GraphDelta::new(ops).with_provenance(Provenance {
1029            sql: Some(statements.join(";\n")),
1030            ..Provenance::default()
1031        });
1032        let mut outcome = self.step(command, statements, delta)?;
1033        let brought = new_nodes + outcome_restored(&outcome);
1034        if not_shown > brought {
1035            let more = not_shown - brought;
1036            let are = if more == 1 {
1037                "neighbour of {id} is"
1038            } else {
1039                "neighbours of {id} are"
1040            };
1041            outcome.text.push_str(&format!(
1042                " ({} more {} not shown: .expand {id} again adds the next)",
1043                thousands(more),
1044                are.replace("{id}", id)
1045            ));
1046        }
1047        Ok(outcome)
1048    }
1049
1050    /// The group `id` names in a grouped session (`group:3`), as its key
1051    /// and its node.
1052    fn group(&self, command: &str, id: &str) -> Result<usize> {
1053        let Some(groups) = &self.groups else {
1054            return plan_err(format!(
1055                "{command} closes a group of a grouped drawing, and this one is not grouped; \
1056                 draw one with .graph NAME GROUP BY column"
1057            ));
1058        };
1059        match group_id(id) {
1060            Some(Some(g)) if (g as usize) < groups.len() => Ok(g as usize),
1061            Some(_) => plan_err(format!(
1062                "no group '{id}' in the graph that is drawn; its groups are group:0 to group:{}",
1063                groups.len() - 1
1064            )),
1065            None => plan_err(format!(
1066                "this drawing is grouped by {}, and {command} takes one of its groups, as \
1067                 {command} group:0 (group:0 to group:{}); a group's key is in its tooltip",
1068                groups.by(),
1069                groups.len() - 1
1070            )),
1071        }
1072    }
1073
1074    /// Each node's group in a grouped session, by slot: a group's own, and
1075    /// a member's.
1076    fn group_codes(&self) -> &[u32] {
1077        let r = &self.result;
1078        let column = r.encodings().group_by.as_deref();
1079        match column
1080            .and_then(|name| r.node_column(name))
1081            .map(|c| &c.values)
1082        {
1083            Some(Values::Dict { codes, .. }) => codes,
1084            _ => &[],
1085        }
1086    }
1087
1088    /// `.expand group:N` in a grouped session: see the [module](self).
1089    async fn open(
1090        &mut self,
1091        ctx: &SessionContext,
1092        sql: &dyn RunSql,
1093        command: &str,
1094        id: &str,
1095        sql_only: bool,
1096    ) -> Result<Outcome> {
1097        let g = self.group(".expand", id)?;
1098        let groups = self.groups.as_ref().expect("a grouped session");
1099        let r = &self.result;
1100        if r.node_is_removed(g) {
1101            return plan_err(format!("group {g} is hidden; .show group:{g} first"));
1102        }
1103        let members = groups.members(g);
1104        if members.len() > groups::MAX_OPEN {
1105            return plan_err(format!(
1106                "group {g} has {} members, and a group of more than {} is not opened in place; \
1107                 draw it on its own: .graph SELECT … WHERE … on its members",
1108                thousands(members.len()),
1109                thousands(groups::MAX_OPEN)
1110            ));
1111        }
1112        // The group's members: the node each is, here already or new, and
1113        // its place among them.
1114        let n_groups = groups.len();
1115        let mut restored: Vec<u32> = Vec::new();
1116        let mut added = NodeBatch::new();
1117        let mut new: HashMap<(u16, Key), u32> = HashMap::new();
1118        let mut place: HashMap<u32, u32> = HashMap::with_capacity(members.len());
1119        let mut added_at: Vec<u32> = Vec::new();
1120        for (local, &v) in members.iter().enumerate() {
1121            let label = groups.label(v);
1122            let Ok(key) = Key::parse(r.node_labels()[label as usize].key, groups.key(v)) else {
1123                continue;
1124            };
1125            let slot = match r.node(label, &key) {
1126                Some(at) => {
1127                    if r.node_is_removed(at as usize) {
1128                        restored.push(at);
1129                    }
1130                    at
1131                }
1132                None => {
1133                    let at = (r.n_nodes() + added.len()) as u32;
1134                    added.push(label, &key);
1135                    added_at.push(local as u32);
1136                    new.insert((label, key), at);
1137                    at
1138                }
1139            };
1140            place.insert(slot, local as u32);
1141        }
1142        if restored.is_empty() && added.is_empty() {
1143            return Ok(Outcome::said(format!(
1144                "Nothing changed: group {g} is open already; .collapse group:{g} closes it"
1145            )));
1146        }
1147        if added.is_empty() {
1148            // Closed by .collapse: its members and their edges are here.
1149            if sql_only {
1150                return Ok(Outcome::said(format!(
1151                    "-- .expand group:{g} runs no SQL: the group's members are in the session"
1152                )));
1153            }
1154            return self.step(
1155                command,
1156                Vec::new(),
1157                GraphDelta::new(vec![Op::RestoreNodes(restored)]),
1158            );
1159        }
1160        let Some(graph) = r.graph() else {
1161            return plan_err(
1162                "opening a group reads the edges among its members from a property graph, and \
1163                 this drawing is of rows that name none; group a graph (.graph NAME GROUP BY \
1164                 column), or say which graph the ids are of (ON graph)",
1165            );
1166        };
1167        let graph = format!("\"{}\"", graph.replace('"', "\"\""));
1168
1169        // The graph's edges among the members of every open group and this
1170        // one's.
1171        let mut all = String::with_capacity((r.n_nodes() - n_groups + added.len()) * 8);
1172        for i in n_groups..r.n_nodes() {
1173            if !all.is_empty() {
1174                all.push_str(", ");
1175            }
1176            literal(&mut all, r.node_keys().get(i), self.key_type(i));
1177        }
1178        for (key, &label) in added.keys.iter().zip(&added.labels) {
1179            if !all.is_empty() {
1180                all.push_str(", ");
1181            }
1182            literal(&mut all, key, r.node_labels()[label as usize].key);
1183        }
1184        let max_edges = crate::options::graph_max_edges(ctx.state().config());
1185        let among = format!(
1186            "SELECT src, dst, edge FROM induced_edges({graph}, nodes => [{all}]) LIMIT {}",
1187            max_edges.saturating_add(1)
1188        );
1189        drop(all);
1190        if sql_only {
1191            return Ok(Outcome::said(format!("{among};")));
1192        }
1193        let (schema, batches) = sql.run(ctx, &among).await?;
1194        let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
1195        if rows > max_edges {
1196            return plan_err(format!(
1197                "there are more than {} edges among the members of the open groups, the most \
1198                 the graph view draws; close a group (.collapse group:N), or raise the limit: {}",
1199                thousands(max_edges),
1200                super::raise_max_edges(rows)
1201            ));
1202        }
1203        let edges = self.edges.get_or_insert_with(|| EdgeIndex::of(r));
1204        // A member's id is a key of a vertex table, never of `group`.
1205        let node_of = |ids: &Ids, i: usize| -> Option<u32> {
1206            r.node_labels()
1207                .iter()
1208                .zip(0u16..)
1209                .skip(1)
1210                .find_map(|(l, at)| {
1211                    let key = ids.key(i, l.key)?;
1212                    r.node(at, &key).or_else(|| new.get(&(at, key)).copied())
1213                })
1214        };
1215        // The edges among this group's members, for their places in its disc.
1216        let (mut inner_src, mut inner_dst) = (Vec::new(), Vec::new());
1217        let (batch, new_label) = new_edges(edges, r, &schema, &batches, node_of, |s, d| {
1218            if let (Some(&a), Some(&b)) = (place.get(&s), place.get(&d)) {
1219                inner_src.push(a);
1220                inner_dst.push(b);
1221            }
1222        })?;
1223        drop(batches);
1224        let (x, y) = groups::disc_layout(members.len(), inner_src, inner_dst);
1225        let count = added.len();
1226        let added = added
1227            .with_column(
1228                r.encodings().group_by.clone().unwrap_or_default(),
1229                BatchValues::Dict {
1230                    new_values: Strings::new(),
1231                    codes: vec![g as u32; count],
1232                },
1233            )
1234            .with_column(
1235                groups::X,
1236                BatchValues::F32(added_at.iter().map(|&i| x[i as usize]).collect()),
1237            )
1238            .with_column(
1239                groups::Y,
1240                BatchValues::F32(added_at.iter().map(|&i| y[i as usize]).collect()),
1241            );
1242
1243        let mut ops = Vec::new();
1244        if !restored.is_empty() {
1245            ops.push(Op::RestoreNodes(restored));
1246        }
1247        ops.push(Op::AddNodes(added));
1248        if !batch.is_empty() {
1249            if let Some(name) = new_label {
1250                ops.push(Op::AddEdgeLabel(name));
1251            }
1252            ops.push(Op::AddEdges(batch));
1253        }
1254        let statements = vec![among];
1255        let delta = GraphDelta::new(ops).with_provenance(Provenance {
1256            sql: Some(statements.join(";\n")),
1257            ..Provenance::default()
1258        });
1259        self.step(command, statements, delta)
1260    }
1261
1262    /// `.collapse group:N`: hide the members of group N that are shown.
1263    fn collapse(&mut self, command: &str, id: &str) -> Result<Outcome> {
1264        let g = self.group(".collapse", id)?;
1265        let groups = self.groups.as_ref().expect("a grouped session");
1266        let r = &self.result;
1267        let codes = self.group_codes();
1268        let nodes: Vec<u32> = (groups.len()..r.n_nodes())
1269            .filter(|&i| codes.get(i) == Some(&(g as u32)) && !r.node_is_removed(i))
1270            .map(|i| i as u32)
1271            .collect();
1272        if nodes.is_empty() {
1273            return Ok(Outcome::said(format!(
1274                "Nothing changed: group {g} is not open; .expand group:{g} opens it"
1275            )));
1276        }
1277        self.step(
1278            command,
1279            Vec::new(),
1280            GraphDelta::new(vec![Op::RemoveNodes(nodes)]),
1281        )
1282    }
1283}
1284
1285/// `id` as a group's: `Some(Some(3))` for `group:3`, `Some(None)` for
1286/// `group:` and something that is no number, `None` for any other id.
1287fn group_id(id: &str) -> Option<Option<i64>> {
1288    let (label, key) = id.split_once(':')?;
1289    if !label.eq_ignore_ascii_case(groups::GROUP) {
1290        return None;
1291    }
1292    Some(key.parse::<i64>().ok().filter(|&g| g >= 0))
1293}
1294
1295/// The rows of an `induced_edges` result (`src`, `dst`, `edge`) that the
1296/// session does not have (`edges` is its index, of `r`'s), as a batch to
1297/// add, and the name of its edge label if the result has none of that name
1298/// yet (the batch's edges are then of the label after `r`'s last).
1299/// `node_of` says which node an id is, if any; `seen` is told each row's
1300/// two nodes, whether or not the session has the edge.
1301fn new_edges(
1302    edges: &EdgeIndex,
1303    r: &GraphResult,
1304    schema: &SchemaRef,
1305    batches: &[RecordBatch],
1306    node_of: impl Fn(&Ids, usize) -> Option<u32>,
1307    mut seen: impl FnMut(u32, u32),
1308) -> Result<(EdgeBatch, Option<String>)> {
1309    let edge_label = schema.field(2).metadata().get(meta::LABEL);
1310    let at = edge_label.and_then(|name| r.edge_labels().iter().position(|l| l == name));
1311    let new_label = match (edge_label, at) {
1312        (Some(name), None) => Some(name.clone()),
1313        _ => None,
1314    };
1315    let e_label = match (&new_label, at) {
1316        (Some(_), _) => r.edge_labels().len() as u16,
1317        (None, at) => at.unwrap_or(0) as u16,
1318    };
1319    let mut batch = EdgeBatch::new();
1320    let mut rows = Vec::new();
1321    // How many of each pair's edges with no row this pass has matched.
1322    let mut matched: HashMap<(u32, u32), u32> = HashMap::new();
1323    for b in batches {
1324        let (s, d) = (Ids::of(b.column(0))?, Ids::of(b.column(1))?);
1325        let row = cast(b.column(2), &DataType::UInt64)?;
1326        let row = row.as_primitive::<UInt64Type>();
1327        for i in 0..b.num_rows() {
1328            let (Some(s), Some(d)) = (node_of(&s, i), node_of(&d, i)) else {
1329                continue;
1330            };
1331            seen(s, d);
1332            let row = row.is_valid(i).then(|| row.value(i));
1333            if row.is_some_and(|row| edges.rows.contains(&(e_label, row))) {
1334                continue;
1335            }
1336            if let Some(&have) = edges.pairs.get(&pair(s, d)) {
1337                let used = matched.entry(pair(s, d)).or_insert(0);
1338                if *used < have {
1339                    *used += 1;
1340                    continue;
1341                }
1342            }
1343            batch.src.push(s);
1344            batch.dst.push(d);
1345            batch.labels.push(e_label);
1346            rows.push(row.unwrap_or(NO_ROW));
1347        }
1348    }
1349    batch.rows = Some(rows);
1350    Ok((batch, new_label))
1351}
1352
1353/// How many nodes an expansion's delta restored.
1354fn outcome_restored(outcome: &Outcome) -> usize {
1355    outcome.delta.as_ref().map_or(0, |delta| {
1356        delta
1357            .ops
1358            .iter()
1359            .map(|op| match op {
1360                Op::RestoreNodes(nodes) => nodes.len(),
1361                _ => 0,
1362            })
1363            .sum()
1364    })
1365}
1366
1367#[cfg(test)]
1368mod tests {
1369    use super::*;
1370
1371    fn parsed(line: &str) -> Command {
1372        Command::parse(line).unwrap().unwrap().command
1373    }
1374
1375    #[test]
1376    fn commands_are_read_from_their_lines() {
1377        assert_eq!(
1378            parsed(".expand 33"),
1379            Command::Expand {
1380                id: "33".into(),
1381                direction: Direction::Both,
1382                limit: EXPAND_LIMIT
1383            }
1384        );
1385        assert_eq!(
1386            parsed("  .EXPAND 'a b' In limit 7 ; "),
1387            Command::Expand {
1388                id: "a b".into(),
1389                direction: Direction::In,
1390                limit: 7
1391            }
1392        );
1393        assert_eq!(
1394            parsed(".hide 1 \"it's\" 'o''neil'"),
1395            Command::Hide(vec!["1".into(), "it's".into(), "o'neil".into()])
1396        );
1397        assert_eq!(parsed(".show ALL"), Command::Show(Vec::new()));
1398        assert_eq!(
1399            parsed(".show all 3"),
1400            Command::Show(vec!["all".into(), "3".into()])
1401        );
1402        assert_eq!(parsed(".undo;"), Command::Undo);
1403        assert_eq!(parsed(".redo"), Command::Redo);
1404        assert_eq!(parsed(".graph History"), Command::History);
1405        let sql = Command::parse(".expand 5 --sql out").unwrap().unwrap();
1406        assert!(sql.sql_only);
1407        assert_eq!(sql.text, ".expand 5 --sql out");
1408        assert_eq!(
1409            sql.command,
1410            Command::Expand {
1411                id: "5".into(),
1412                direction: Direction::Out,
1413                limit: EXPAND_LIMIT
1414            }
1415        );
1416    }
1417
1418    #[test]
1419    fn other_lines_are_not_explore_commands() {
1420        for line in [
1421            ".graph",
1422            ".graph karate",
1423            ".graph SELECT history FROM t",
1424            ".tables",
1425            "SELECT 1",
1426            "",
1427        ] {
1428            assert_eq!(Command::parse(line).unwrap(), None, "{line}");
1429        }
1430        for line in [
1431            ".expand",
1432            ".expand 1 2",
1433            ".expand 1 in out",
1434            ".expand 1 LIMIT",
1435            ".expand 1 LIMIT x",
1436            ".hide",
1437            ".hide 'open",
1438            ".redo 2",
1439        ] {
1440            assert!(Command::parse(line).is_err(), "{line}");
1441        }
1442    }
1443
1444    #[test]
1445    fn changes_are_signed_and_counted() {
1446        assert_eq!(changed(16, 41), "+16 nodes, +41 edges");
1447        assert_eq!(changed(-1, -1), "-1 node, -1 edge");
1448        assert_eq!(changed(0, 1200), "+0 nodes, +1,200 edges");
1449    }
1450}