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.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
288fn nodes(n: usize) -> String {
290 format!("{} node{}", thousands(n), if n == 1 { "" } else { "s" })
291}
292
293impl Found {
294 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
328pub 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 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 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 let mut exact = Vec::new();
415 let mut starts = Vec::new();
416 for (i, key) in r.node_keys().iter().enumerate() {
417 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 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
498fn 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 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}