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        let node = own.and_then(of).or_else(|| (0..labels.len()).find_map(of));
277        match node {
278            Some(i) => self.node(i),
279            None => {
280                if self.outside.insert(key.to_string()) {
281                    self.miss(key.to_string(), false);
282                }
283            }
284        }
285    }
286}
287
288/// `n` nodes, in words.
289fn nodes(n: usize) -> String {
290    format!("{} node{}", thousands(n), if n == 1 { "" } else { "s" })
291}
292
293impl Found {
294    /// What `.find` says of these matches.
295    fn say(&mut self, what: &str) {
296        let mut out = match (self.matches, self.selected.len()) {
297            (0, _) if self.not_shown_total == 0 => format!("No node matches {what}"),
298            (0, _) => format!("No node in the view matches {what}"),
299            (all, some) if some < all => format!(
300                "Selected the first {} of {} that match {what}",
301                thousands(some),
302                nodes(all)
303            ),
304            (all, _) => format!("Selected {}", nodes(all)),
305        };
306        if self.not_shown_total > 0 {
307            let named: Vec<String> = self
308                .not_shown
309                .iter()
310                .map(|n| match n.hidden {
311                    true => format!("{} (hidden)", n.key),
312                    false => n.key.clone(),
313                })
314                .collect();
315            let more = self.not_shown_total - named.len();
316            out.push_str(&format!("\nNot shown: {}", named.join(", ")));
317            if more > 0 {
318                out.push_str(&format!(" and {} more", thousands(more)));
319            }
320            if self.not_shown.iter().any(|n| n.hidden) {
321                out.push_str("\n.show ID shows a hidden node again");
322            }
323        }
324        self.text = out;
325    }
326}
327
328/// Run a `.find` line ([`Find::parse`]) on `session`: `sql` runs its
329/// statements on `ctx`. Nothing changes: the caller's view selects
330/// [`Found::selected`].
331///
332/// An error is a line that is not `.find`, a `WHERE` on a drawing with no
333/// table to ask, or a condition that no vertex table can answer.
334pub async fn find(
335    session: &Session,
336    ctx: &SessionContext,
337    sql: &dyn RunSql,
338    line: &str,
339) -> Result<Found> {
340    let Some(Find { query, sql_only }) = Find::parse(line)? else {
341        return plan_err(format!("'{}' is not .find; {USAGE}", line.trim()));
342    };
343    let r = session.result();
344    let tables = tables(ctx, r).await?;
345    let mut matches = Matches {
346        r,
347        seen: vec![false; r.n_nodes()],
348        outside: HashSet::new(),
349        found: Found::default(),
350    };
351    let what;
352    match &query {
353        Query::Text(text) => {
354            what = format!("'{text}'");
355            let needle = text.to_lowercase();
356            let key_of = |t: &Table| format!("lower(CAST({} AS VARCHAR))", ident(&t.key));
357            // The whole of a graph with no vertex table: the session has
358            // every node, and its keys are all there is to match.
359            let whole = r.provenance().rule.as_deref() == Some("graph");
360            let asked: Vec<&Table> = tables
361                .iter()
362                .flatten()
363                .filter(|t| !(whole && t.label.is_none()))
364                .collect();
365            let statements: Vec<String> = asked
366                .iter()
367                .map(|t| {
368                    let (key, lit) = (key_of(t), string(&needle));
369                    let prefix = format!("starts_with({key}, {lit})");
370                    let (label, rank) = match &t.text {
371                        Some(c) => (
372                            format!(" OR strpos(lower({}), {lit}) > 0", ident(c)),
373                            format!(
374                                "CASE WHEN {key} = {lit} THEN 0 WHEN {prefix} THEN 1 ELSE 2 END"
375                            ),
376                        ),
377                        None => (
378                            String::new(),
379                            format!("CASE WHEN {key} = {lit} THEN 0 ELSE 1 END"),
380                        ),
381                    };
382                    format!(
383                        "SELECT CAST({k} AS VARCHAR) AS {}, {rank} AS rank FROM {} \
384                         WHERE {prefix}{label} ORDER BY rank, {k}",
385                        t.out(),
386                        t.name,
387                        k = ident(&t.key),
388                    )
389                })
390                .collect();
391            if sql_only {
392                return Ok(said_sql(
393                    statements,
394                    ".find TEXT here matches the keys drawn",
395                ));
396            }
397            // By rank: the key itself, keys it starts, then label columns.
398            let mut ranked: [Vec<(usize, String)>; 3] = Default::default();
399            for (at, statement) in statements.iter().enumerate() {
400                let (_, batches) = sql.run(ctx, statement).await?;
401                for b in &batches {
402                    let ids = cast(b.column(0), &DataType::Utf8)?;
403                    let ids = ids.as_string::<i32>();
404                    let rank = cast(b.column(1), &DataType::Int64)?;
405                    let rank = rank.as_primitive::<Int64Type>();
406                    for i in (0..b.num_rows()).filter(|&i| ids.is_valid(i)) {
407                        let rank = rank.value(i).clamp(0, 2) as usize;
408                        ranked[rank].push((at, ids.value(i).to_string()));
409                    }
410                }
411            }
412            // The session's own keys, where no table was asked (or a node
413            // is of none of them).
414            let mut exact = Vec::new();
415            let mut starts = Vec::new();
416            for (i, key) in r.node_keys().iter().enumerate() {
417                // Keys are mostly numbers: lower-case only what has letters.
418                let hit = if key.is_ascii() {
419                    key.len() >= needle.len()
420                        && key.as_bytes()[..needle.len()].eq_ignore_ascii_case(needle.as_bytes())
421                } else {
422                    key.to_lowercase().starts_with(&needle)
423                };
424                if hit {
425                    let whole_key = key.len() == needle.len() || key.to_lowercase() == needle;
426                    if whole_key { &mut exact } else { &mut starts }.push(i as u32);
427                }
428            }
429            for (rank, own) in [(0, &exact), (1, &starts), (2, &Vec::new())] {
430                for (at, key) in &ranked[rank] {
431                    matches.row(asked[*at], key);
432                }
433                for &i in own {
434                    matches.node(i);
435                }
436            }
437            matches.found.sql = statements;
438        }
439        Query::Where(condition) => {
440            what = condition.clone();
441            let Some(tables) = &tables else {
442                return plan_err(
443                    "this drawing is not of a property graph, so there is no vertex table for a \
444                     condition; .find TEXT matches the keys drawn, or draw a graph's nodes \
445                     first: .graph NAME",
446                );
447            };
448            if tables.is_empty() {
449                return plan_err(
450                    "the graph that is drawn has several edge tables and no vertex table, so \
451                     there are no columns for a condition; .find TEXT matches the keys drawn",
452                );
453            }
454            let statements: Vec<String> = tables
455                .iter()
456                .map(|t| {
457                    format!(
458                        "SELECT CAST({k} AS VARCHAR) AS {} FROM {} WHERE ({condition}) ORDER BY {k}",
459                        t.out(),
460                        t.name,
461                        k = ident(&t.key),
462                    )
463                })
464                .collect();
465            if sql_only {
466                return Ok(said_sql(statements, ""));
467            }
468            // A condition is on one table's columns: with several vertex
469            // tables, those it cannot be asked of are left out.
470            let mut failed: Option<DataFusionError> = None;
471            let mut ran = Vec::new();
472            for (table, statement) in tables.iter().zip(statements) {
473                match sql.run(ctx, &statement).await {
474                    Ok((_, batches)) => {
475                        for b in &batches {
476                            let ids = cast(b.column(0), &DataType::Utf8)?;
477                            let ids = ids.as_string::<i32>();
478                            for i in (0..b.num_rows()).filter(|&i| ids.is_valid(i)) {
479                                matches.row(table, ids.value(i));
480                            }
481                        }
482                        ran.push(statement);
483                    }
484                    Err(e) => failed = failed.or(Some(e)),
485                }
486            }
487            match failed {
488                Some(e) if ran.is_empty() => return Err(e),
489                _ => matches.found.sql = ran,
490            }
491        }
492    }
493    let mut found = matches.found;
494    found.say(&what);
495    Ok(found)
496}
497
498/// `--sql`'s answer: the statements, or why there are none.
499fn said_sql(statements: Vec<String>, none: &str) -> Found {
500    let text = if statements.is_empty() {
501        format!("-- .find runs no SQL: {none}")
502    } else {
503        statements
504            .iter()
505            .map(|s| format!("{s};"))
506            .collect::<Vec<_>>()
507            .join("\n")
508    };
509    Found {
510        text,
511        sql: statements,
512        ..Found::default()
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    fn parsed(line: &str) -> Find {
521        Find::parse(line).unwrap().unwrap()
522    }
523
524    #[test]
525    fn find_lines_are_read() {
526        assert_eq!(
527            parsed(".find 33"),
528            Find {
529                query: Query::Text("33".into()),
530                sql_only: false
531            }
532        );
533        assert_eq!(
534            parsed("  .FIND  Mr Hi ;").query,
535            Query::Text("Mr Hi".into())
536        );
537        assert_eq!(
538            parsed(".find 'O''Neil'").query,
539            Query::Text("O'Neil".into())
540        );
541        assert_eq!(
542            parsed(".find WHERE club = 'Officer';").query,
543            Query::Where("club = 'Officer'".into())
544        );
545        assert_eq!(
546            parsed(".find where id > 3 --sql"),
547            Find {
548                query: Query::Where("id > 3".into()),
549                sql_only: true
550            }
551        );
552        // A text that starts with "where" is a text.
553        assert_eq!(
554            parsed(".find wherever").query,
555            Query::Text("wherever".into())
556        );
557        assert_eq!(parsed(".find 3 --sql").query, Query::Text("3".into()));
558    }
559
560    #[test]
561    fn other_lines_are_not_find() {
562        for line in [".finder", ".expand 3", "SELECT 1", ".graph karate", ""] {
563            assert_eq!(Find::parse(line).unwrap(), None, "{line}");
564        }
565        for line in [".find", ".find ;", ".find WHERE", ".find --sql"] {
566            let e = Find::parse(line).unwrap_err().to_string();
567            assert!(e.contains("usage: .find TEXT"), "{line}: {e}");
568        }
569    }
570}