1use 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
55pub const MAX_SELECTED: usize = 1_000;
57pub const MAX_LISTED: usize = 20;
59
60const USAGE: &str = "usage: .find TEXT or .find WHERE condition";
61
62#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Query {
65 Text(String),
67 Where(String),
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Find {
74 pub query: Query,
75 pub sql_only: bool,
77}
78
79impl Find {
80 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 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#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct NotShown {
129 pub key: String,
131 pub hidden: bool,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Default)]
138pub struct Found {
139 pub text: String,
141 pub selected: Vec<u32>,
144 pub matches: usize,
146 pub not_shown: Vec<NotShown>,
148 pub not_shown_total: usize,
150 pub sql: Vec<String>,
152}
153
154struct Table {
156 name: String,
158 label: Option<String>,
160 key: String,
161 text: Option<String>,
163}
164
165impl Table {
166 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
193async 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
230struct Matches<'a> {
232 r: &'a GraphResult,
233 seen: Vec<bool>,
234 outside: HashSet<String>,
236 found: Found,
237}
238
239impl Matches<'_> {
240 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 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 let own = table
273 .label
274 .as_ref()
275 .and_then(|name| labels.iter().position(|l| &l.name == name));
276 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
291fn nodes(n: usize) -> String {
293 format!("{} node{}", thousands(n), if n == 1 { "" } else { "s" })
294}
295
296impl Found {
297 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
331pub 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 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 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 let mut exact = Vec::new();
418 let mut starts = Vec::new();
419 for (i, key) in r.node_keys().iter().enumerate() {
420 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 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
501fn 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 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}