Skip to main content

ursa_engine/graph/view/
find.rs

1//! `.find` (design §6 "Search and focus", #445): the nodes of the graph that
2//! is drawn that match a text or a condition, for the view to select and fit.
3//!
4//! | command | what matches |
5//! |---|---|
6//! | `.find TEXT` | a node whose key starts with TEXT, then one whose label column (the vertex table's first text column that is not its key) contains TEXT; letter case is ignored |
7//! | `.find WHERE condition` | a row of the vertex table the condition holds for, the condition being SQL on the table's columns |
8//!
9//! The matches that are shown in the view are the selection ([`Found::selected`]):
10//! a key that is TEXT itself first, then the keys that start with it, then
11//! the label matches, each in the table's key order (the view's own order
12//! where no table is asked); at most [`MAX_SELECTED`], with the true count
13//! beside them. The matches the view does not show (a hidden node
14//! of the session, or a node of the graph that was never drawn) are counted
15//! and the first [`MAX_LISTED`] named ([`Found::not_shown`]).
16//!
17//! `.find` reads the session ([`Session::result`]) and changes nothing: it is
18//! no step of the exploration, so `.undo` does not see it. `--sql` at the end
19//! prints its SQL and selects nothing.
20//!
21//! # Its SQL
22//!
23//! One statement for each vertex table of the drawing's property graph:
24//!
25//! ```sql
26//! -- .find 33
27//! SELECT CAST("id" AS VARCHAR) AS node, CASE … END AS rank FROM members
28//! WHERE starts_with(lower(CAST("id" AS VARCHAR)), '33') OR strpos(lower("club"), '33') > 0
29//! ORDER BY rank, "id"
30//! -- .find WHERE club = 'Officer'
31//! SELECT CAST("id" AS VARCHAR) AS node FROM members WHERE (club = 'Officer') ORDER BY "id"
32//! ```
33//!
34//! A graph with no vertex table has its `<graph>.nodes` (the edges' ends,
35//! `id`) in the table's place. Two cases run no SQL: a drawing that is of no
36//! property graph, and `.find TEXT` on the whole of a graph with no vertex
37//! table (`.graph NAME`), where every node is in the session already. Both
38//! match the session's keys, and neither can take a `WHERE`.
39
40use std::collections::HashSet;
41
42use datafusion::arrow::array::{Array, AsArray};
43use datafusion::arrow::compute::cast;
44use datafusion::arrow::datatypes::{DataType, Int64Type};
45use datafusion::common::TableReference;
46use datafusion::error::{DataFusionError, Result};
47use datafusion::prelude::SessionContext;
48use ursa_viz::model::{GraphResult, Key};
49
50use super::session::Session;
51use super::{plan_err, thousands, RunSql};
52use crate::graph::registry_of;
53use crate::graph::schema::{ID, NODES};
54
55/// The most nodes `.find` selects; it says how many matched.
56pub const MAX_SELECTED: usize = 1_000;
57/// The most matches outside the view that `.find` names; it counts the rest.
58pub const MAX_LISTED: usize = 20;
59
60const USAGE: &str = "usage: .find TEXT or .find WHERE condition";
61
62/// What `.find` looks for.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Query {
65    /// Keys that start with the text, then label columns that contain it.
66    Text(String),
67    /// A SQL condition on the vertex table's columns.
68    Where(String),
69}
70
71/// A `.find` line, read.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Find {
74    pub query: Query,
75    /// `--sql`: print the SQL and select nothing.
76    pub sql_only: bool,
77}
78
79impl Find {
80    /// Read `line`. `Ok(None)` when it is not `.find`; an error when it is
81    /// one with nothing to look for.
82    pub fn parse(line: &str) -> Result<Option<Find>> {
83        let text = line.trim().trim_end_matches(';').trim_end();
84        let (name, rest) = match text.find(char::is_whitespace) {
85            Some(at) => (&text[..at], text[at..].trim()),
86            None => (text, ""),
87        };
88        if !name.eq_ignore_ascii_case(".find") {
89            return Ok(None);
90        }
91        let (rest, sql_only) = match rest.strip_suffix("--sql") {
92            Some(before) if before.is_empty() || before.ends_with(char::is_whitespace) => {
93                (before.trim_end(), true)
94            }
95            _ => (rest, false),
96        };
97        let is_where = rest
98            .get(..5)
99            .is_some_and(|w| w.eq_ignore_ascii_case("where"))
100            && rest[5..].chars().next().is_none_or(char::is_whitespace);
101        let query = if is_where {
102            let condition = rest[5..].trim();
103            if condition.is_empty() {
104                return plan_err(format!(
105                    "WHERE takes a condition on the vertex table's columns: .find WHERE club = \
106                     'Officer'; {USAGE}"
107                ));
108            }
109            Query::Where(condition.to_string())
110        } else {
111            // 'a b' and "a b" are the text without the quotes.
112            let unquoted = ['\'', '"'].iter().find_map(|&q| {
113                let inner = rest.strip_prefix(q)?.strip_suffix(q)?;
114                (rest.len() >= 2).then(|| inner.replace(&format!("{q}{q}"), &q.to_string()))
115            });
116            let text = unquoted.unwrap_or_else(|| rest.to_string());
117            if text.is_empty() {
118                return plan_err(USAGE);
119            }
120            Query::Text(text)
121        };
122        Ok(Some(Find { query, sql_only }))
123    }
124}
125
126/// A match the view does not show.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct NotShown {
129    /// The node's key, as the shell prints it.
130    pub key: String,
131    /// Whether it is a hidden node of the session, which `.show` brings
132    /// back; otherwise it is a node of the graph that was never drawn.
133    pub hidden: bool,
134}
135
136/// What `.find` found.
137#[derive(Debug, Clone, PartialEq, Eq, Default)]
138pub struct Found {
139    /// What to print. No newline at the end.
140    pub text: String,
141    /// The matches the view shows, as its node indexes, the best first: at
142    /// most [`MAX_SELECTED`]. The view selects them and fits them.
143    pub selected: Vec<u32>,
144    /// How many matches the view shows: more than `selected` past the cap.
145    pub matches: usize,
146    /// The first [`MAX_LISTED`] matches the view does not show.
147    pub not_shown: Vec<NotShown>,
148    /// How many matches the view does not show.
149    pub not_shown_total: usize,
150    /// The statements run (or, for `--sql`, that would be).
151    pub sql: Vec<String>,
152}
153
154/// A table `.find` reads: a vertex table, or a graph's `nodes`.
155struct Table {
156    /// As SQL names it.
157    name: String,
158    /// The vertex table's element name: the label of its nodes.
159    label: Option<String>,
160    key: String,
161    /// The label column: the first text column that is not the key.
162    text: Option<String>,
163}
164
165impl Table {
166    /// What the statement calls the key as text: not the key's own name,
167    /// which `ORDER BY` must still mean the column by (10 after 9).
168    fn out(&self) -> &'static str {
169        if self.key.eq_ignore_ascii_case("node") {
170            "node_key"
171        } else {
172            "node"
173        }
174    }
175}
176
177fn ident(name: &str) -> String {
178    format!("\"{}\"", name.replace('"', "\"\""))
179}
180
181fn string(text: &str) -> String {
182    format!("'{}'", text.replace('\'', "''"))
183}
184
185fn is_text(ty: &DataType) -> bool {
186    match ty {
187        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => true,
188        DataType::Dictionary(_, values) => is_text(values),
189        _ => false,
190    }
191}
192
193/// The tables of the drawing's graph: its vertex tables, or its `nodes`.
194/// None when the drawing is of no graph the session has.
195async fn tables(ctx: &SessionContext, r: &GraphResult) -> Result<Option<Vec<Table>>> {
196    let Some(graph) = r.graph().and_then(|name| registry_of(ctx).get(name)) else {
197        return Ok(None);
198    };
199    let mut out = Vec::new();
200    for v in &graph.vertex_tables {
201        let schema = ctx
202            .table(v.table.clone())
203            .await?
204            .schema()
205            .as_arrow()
206            .clone();
207        let text = schema
208            .fields()
209            .iter()
210            .find(|f| f.name() != &v.key && is_text(f.data_type()))
211            .map(|f| f.name().clone());
212        out.push(Table {
213            name: v.table.to_quoted_string(),
214            label: Some(v.name.clone()),
215            key: v.key.clone(),
216            text,
217        });
218    }
219    if out.is_empty() && graph.default_pair().is_some() {
220        out.push(Table {
221            name: TableReference::partial(graph.name.as_str(), NODES).to_quoted_string(),
222            label: None,
223            key: ID.to_string(),
224            text: None,
225        });
226    }
227    Ok(Some(out))
228}
229
230/// The matches as they are gathered: each node of the session once.
231struct Matches<'a> {
232    r: &'a GraphResult,
233    seen: Vec<bool>,
234    /// Keys outside the session that matched already.
235    outside: HashSet<String>,
236    found: Found,
237}
238
239impl Matches<'_> {
240    /// Session node `i` matched.
241    fn node(&mut self, i: u32) {
242        if std::mem::replace(&mut self.seen[i as usize], true) {
243            return;
244        }
245        if self.r.node_is_removed(i as usize) {
246            self.miss(self.r.node_keys().get(i as usize).to_string(), true);
247        } else {
248            self.found.matches += 1;
249            if self.found.selected.len() < MAX_SELECTED {
250                self.found.selected.push(i);
251            }
252        }
253    }
254
255    fn miss(&mut self, key: String, hidden: bool) {
256        self.found.not_shown_total += 1;
257        if self.found.not_shown.len() < MAX_LISTED {
258            self.found.not_shown.push(NotShown { key, hidden });
259        }
260    }
261
262    /// A row of `table` matched: the node with this key, in the session or
263    /// not.
264    fn row(&mut self, table: &Table, key: &str) {
265        let labels = self.r.node_labels();
266        let of = |l: usize| {
267            let key = Key::parse(labels[l].key, key).ok()?;
268            self.r.node(l as u16, &key)
269        };
270        // The table's own label first; a drawing may name its nodes' label
271        // otherwise (or not at all), so then any.
272        let own = table
273            .label
274            .as_ref()
275            .and_then(|name| labels.iter().position(|l| &l.name == name));
276        // (A grouped drawing's groups are no table's rows.)
277        let node = own
278            .and_then(of)
279            .or_else(|| (super::groups::own_labels(self.r)..labels.len()).find_map(of));
280        match node {
281            Some(i) => self.node(i),
282            None => {
283                if self.outside.insert(key.to_string()) {
284                    self.miss(key.to_string(), false);
285                }
286            }
287        }
288    }
289}
290
291/// `n` nodes, in words.
292fn nodes(n: usize) -> String {
293    format!("{} node{}", thousands(n), if n == 1 { "" } else { "s" })
294}
295
296impl Found {
297    /// What `.find` says of these matches.
298    fn say(&mut self, what: &str) {
299        let mut out = match (self.matches, self.selected.len()) {
300            (0, _) if self.not_shown_total == 0 => format!("No node matches {what}"),
301            (0, _) => format!("No node in the view matches {what}"),
302            (all, some) if some < all => format!(
303                "Selected the first {} of {} that match {what}",
304                thousands(some),
305                nodes(all)
306            ),
307            (all, _) => format!("Selected {}", nodes(all)),
308        };
309        if self.not_shown_total > 0 {
310            let named: Vec<String> = self
311                .not_shown
312                .iter()
313                .map(|n| match n.hidden {
314                    true => format!("{} (hidden)", n.key),
315                    false => n.key.clone(),
316                })
317                .collect();
318            let more = self.not_shown_total - named.len();
319            out.push_str(&format!("\nNot shown: {}", named.join(", ")));
320            if more > 0 {
321                out.push_str(&format!(" and {} more", thousands(more)));
322            }
323            if self.not_shown.iter().any(|n| n.hidden) {
324                out.push_str("\n.show ID shows a hidden node again");
325            }
326        }
327        self.text = out;
328    }
329}
330
331/// Run a `.find` line ([`Find::parse`]) on `session`: `sql` runs its
332/// statements on `ctx`. Nothing changes: the caller's view selects
333/// [`Found::selected`].
334///
335/// An error is a line that is not `.find`, a `WHERE` on a drawing with no
336/// table to ask, or a condition that no vertex table can answer.
337pub async fn find(
338    session: &Session,
339    ctx: &SessionContext,
340    sql: &dyn RunSql,
341    line: &str,
342) -> Result<Found> {
343    let Some(Find { query, sql_only }) = Find::parse(line)? else {
344        return plan_err(format!("'{}' is not .find; {USAGE}", line.trim()));
345    };
346    let r = session.result();
347    let tables = tables(ctx, r).await?;
348    let mut matches = Matches {
349        r,
350        seen: vec![false; r.n_nodes()],
351        outside: HashSet::new(),
352        found: Found::default(),
353    };
354    let what;
355    match &query {
356        Query::Text(text) => {
357            what = format!("'{text}'");
358            let needle = text.to_lowercase();
359            let key_of = |t: &Table| format!("lower(CAST({} AS VARCHAR))", ident(&t.key));
360            // The whole of a graph with no vertex table: the session has
361            // every node, and its keys are all there is to match.
362            let whole = r.provenance().rule.as_deref() == Some("graph");
363            let asked: Vec<&Table> = tables
364                .iter()
365                .flatten()
366                .filter(|t| !(whole && t.label.is_none()))
367                .collect();
368            let statements: Vec<String> = asked
369                .iter()
370                .map(|t| {
371                    let (key, lit) = (key_of(t), string(&needle));
372                    let prefix = format!("starts_with({key}, {lit})");
373                    let (label, rank) = match &t.text {
374                        Some(c) => (
375                            format!(" OR strpos(lower({}), {lit}) > 0", ident(c)),
376                            format!(
377                                "CASE WHEN {key} = {lit} THEN 0 WHEN {prefix} THEN 1 ELSE 2 END"
378                            ),
379                        ),
380                        None => (
381                            String::new(),
382                            format!("CASE WHEN {key} = {lit} THEN 0 ELSE 1 END"),
383                        ),
384                    };
385                    format!(
386                        "SELECT CAST({k} AS VARCHAR) AS {}, {rank} AS rank FROM {} \
387                         WHERE {prefix}{label} ORDER BY rank, {k}",
388                        t.out(),
389                        t.name,
390                        k = ident(&t.key),
391                    )
392                })
393                .collect();
394            if sql_only {
395                return Ok(said_sql(
396                    statements,
397                    ".find TEXT here matches the keys drawn",
398                ));
399            }
400            // By rank: the key itself, keys it starts, then label columns.
401            let mut ranked: [Vec<(usize, String)>; 3] = Default::default();
402            for (at, statement) in statements.iter().enumerate() {
403                let (_, batches) = sql.run(ctx, statement).await?;
404                for b in &batches {
405                    let ids = cast(b.column(0), &DataType::Utf8)?;
406                    let ids = ids.as_string::<i32>();
407                    let rank = cast(b.column(1), &DataType::Int64)?;
408                    let rank = rank.as_primitive::<Int64Type>();
409                    for i in (0..b.num_rows()).filter(|&i| ids.is_valid(i)) {
410                        let rank = rank.value(i).clamp(0, 2) as usize;
411                        ranked[rank].push((at, ids.value(i).to_string()));
412                    }
413                }
414            }
415            // The session's own keys, where no table was asked (or a node
416            // is of none of them).
417            let mut exact = Vec::new();
418            let mut starts = Vec::new();
419            for (i, key) in r.node_keys().iter().enumerate() {
420                // Keys are mostly numbers: lower-case only what has letters.
421                let hit = if key.is_ascii() {
422                    key.len() >= needle.len()
423                        && key.as_bytes()[..needle.len()].eq_ignore_ascii_case(needle.as_bytes())
424                } else {
425                    key.to_lowercase().starts_with(&needle)
426                };
427                if hit {
428                    let whole_key = key.len() == needle.len() || key.to_lowercase() == needle;
429                    if whole_key { &mut exact } else { &mut starts }.push(i as u32);
430                }
431            }
432            for (rank, own) in [(0, &exact), (1, &starts), (2, &Vec::new())] {
433                for (at, key) in &ranked[rank] {
434                    matches.row(asked[*at], key);
435                }
436                for &i in own {
437                    matches.node(i);
438                }
439            }
440            matches.found.sql = statements;
441        }
442        Query::Where(condition) => {
443            what = condition.clone();
444            let Some(tables) = &tables else {
445                return plan_err(
446                    "this drawing is not of a property graph, so there is no vertex table for a \
447                     condition; .find TEXT matches the keys drawn, or draw a graph's nodes \
448                     first: .graph NAME",
449                );
450            };
451            if tables.is_empty() {
452                return plan_err(
453                    "the graph that is drawn has several edge tables and no vertex table, so \
454                     there are no columns for a condition; .find TEXT matches the keys drawn",
455                );
456            }
457            let statements: Vec<String> = tables
458                .iter()
459                .map(|t| {
460                    format!(
461                        "SELECT CAST({k} AS VARCHAR) AS {} FROM {} WHERE ({condition}) ORDER BY {k}",
462                        t.out(),
463                        t.name,
464                        k = ident(&t.key),
465                    )
466                })
467                .collect();
468            if sql_only {
469                return Ok(said_sql(statements, ""));
470            }
471            // A condition is on one table's columns: with several vertex
472            // tables, those it cannot be asked of are left out.
473            let mut failed: Option<DataFusionError> = None;
474            let mut ran = Vec::new();
475            for (table, statement) in tables.iter().zip(statements) {
476                match sql.run(ctx, &statement).await {
477                    Ok((_, batches)) => {
478                        for b in &batches {
479                            let ids = cast(b.column(0), &DataType::Utf8)?;
480                            let ids = ids.as_string::<i32>();
481                            for i in (0..b.num_rows()).filter(|&i| ids.is_valid(i)) {
482                                matches.row(table, ids.value(i));
483                            }
484                        }
485                        ran.push(statement);
486                    }
487                    Err(e) => failed = failed.or(Some(e)),
488                }
489            }
490            match failed {
491                Some(e) if ran.is_empty() => return Err(e),
492                _ => matches.found.sql = ran,
493            }
494        }
495    }
496    let mut found = matches.found;
497    found.say(&what);
498    Ok(found)
499}
500
501/// `--sql`'s answer: the statements, or why there are none.
502fn said_sql(statements: Vec<String>, none: &str) -> Found {
503    let text = if statements.is_empty() {
504        format!("-- .find runs no SQL: {none}")
505    } else {
506        statements
507            .iter()
508            .map(|s| format!("{s};"))
509            .collect::<Vec<_>>()
510            .join("\n")
511    };
512    Found {
513        text,
514        sql: statements,
515        ..Found::default()
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522
523    fn parsed(line: &str) -> Find {
524        Find::parse(line).unwrap().unwrap()
525    }
526
527    #[test]
528    fn find_lines_are_read() {
529        assert_eq!(
530            parsed(".find 33"),
531            Find {
532                query: Query::Text("33".into()),
533                sql_only: false
534            }
535        );
536        assert_eq!(
537            parsed("  .FIND  Mr Hi ;").query,
538            Query::Text("Mr Hi".into())
539        );
540        assert_eq!(
541            parsed(".find 'O''Neil'").query,
542            Query::Text("O'Neil".into())
543        );
544        assert_eq!(
545            parsed(".find WHERE club = 'Officer';").query,
546            Query::Where("club = 'Officer'".into())
547        );
548        assert_eq!(
549            parsed(".find where id > 3 --sql"),
550            Find {
551                query: Query::Where("id > 3".into()),
552                sql_only: true
553            }
554        );
555        // A text that starts with "where" is a text.
556        assert_eq!(
557            parsed(".find wherever").query,
558            Query::Text("wherever".into())
559        );
560        assert_eq!(parsed(".find 3 --sql").query, Query::Text("3".into()));
561    }
562
563    #[test]
564    fn other_lines_are_not_find() {
565        for line in [".finder", ".expand 3", "SELECT 1", ".graph karate", ""] {
566            assert_eq!(Find::parse(line).unwrap(), None, "{line}");
567        }
568        for line in [".find", ".find ;", ".find WHERE", ".find --sql"] {
569            let e = Find::parse(line).unwrap_err().to_string();
570            assert!(e.contains("usage: .find TEXT"), "{line}: {e}");
571        }
572    }
573}