1use std::collections::HashMap;
14use std::io::Read;
15use std::path::{Path, PathBuf};
16use std::time::{Duration, Instant};
17
18use anyhow::{Context, Result};
19use clap::{Args, ValueEnum};
20use kglite::api::cypher::OutputFormat;
21use kglite::api::io::load_file;
22use kglite::api::param::kglite_value_to_json;
23use kglite::api::session::{execute_read, CsvImportPolicy, ExecuteOptions};
24use kglite::api::Value;
25
26use crate::code_tree_cli::DEFAULT_GRAPH;
27
28#[derive(Args, Debug)]
29pub struct QueryArgs {
30 pub query: String,
32 #[arg(short, long, default_value = DEFAULT_GRAPH)]
35 pub graph: PathBuf,
36 #[arg(long, value_parser = parse_timeout)]
39 pub timeout: Option<f64>,
40 #[arg(long, value_enum, default_value_t = QueryFormat::Human)]
42 pub format: QueryFormat,
43 #[arg(long)]
46 pub require_fresh: bool,
47 #[arg(long)]
54 pub parallel: bool,
55}
56
57const MAX_TIMEOUT_SECS: f64 = 1e9;
62
63fn check_timeout(seconds: f64) -> Result<f64, String> {
74 if !seconds.is_finite() || seconds <= 0.0 || seconds > MAX_TIMEOUT_SECS {
75 return Err(format!(
76 "timeout must be a positive, finite number of seconds \
77 (at most {MAX_TIMEOUT_SECS:.0}), got {seconds}"
78 ));
79 }
80 Ok(seconds)
81}
82
83fn parse_timeout(raw: &str) -> Result<f64, String> {
88 let seconds: f64 = raw
89 .parse()
90 .map_err(|_| format!("`{raw}` is not a number of seconds"))?;
91 check_timeout(seconds)
92}
93
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
97pub enum QueryFormat {
98 #[default]
100 Human,
101 Csv,
105 Json,
107}
108
109#[derive(Debug)]
114pub(crate) struct QueryOutput {
115 pub(crate) stdout: String,
116 pub(crate) rows: usize,
117 pub(crate) warning: Option<String>,
118}
119
120#[derive(Debug)]
123pub struct StaleGraph {
124 pub graph: PathBuf,
125 pub reason: String,
126}
127
128impl std::fmt::Display for StaleGraph {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 write!(
131 f,
132 "--require-fresh: refusing to query {} — {}",
133 self.graph.display(),
134 self.reason
135 )
136 }
137}
138
139impl std::error::Error for StaleGraph {}
140
141pub(crate) fn run(args: &QueryArgs) -> Result<()> {
142 let query = read_query(&args.query, std::io::stdin().lock())?;
143 let output = run_query(args, &query)?;
144 if let Some(warning) = &output.warning {
145 eprintln!("warning: {warning}");
146 }
147 print!("{}", output.stdout);
148 eprintln!("{} row(s)", output.rows);
149 Ok(())
150}
151
152pub(crate) fn read_query(spec: &str, mut stdin: impl Read) -> Result<String> {
154 if spec != "-" {
155 return Ok(spec.to_string());
156 }
157 let mut text = String::new();
158 stdin
159 .read_to_string(&mut text)
160 .context("could not read the query from stdin")?;
161 Ok(text)
162}
163
164pub(crate) fn run_query(args: &QueryArgs, query: &str) -> Result<QueryOutput> {
166 let graph_path = args.graph.as_path();
167 if !graph_path.exists() {
168 anyhow::bail!(
169 "graph artifact not found: {} — build one with `codingest build <dir>`",
170 graph_path.display()
171 );
172 }
173
174 let warning = freshness_warning(graph_path);
175 if let (Some(reason), true) = (warning.as_deref(), args.require_fresh) {
176 return Err(StaleGraph {
177 graph: graph_path.to_path_buf(),
178 reason: reason.to_string(),
179 }
180 .into());
181 }
182
183 let graph_text = graph_path.to_string_lossy().to_string();
184 let graph = load_file(&graph_text)
185 .with_context(|| format!("could not load graph artifact {}", graph_path.display()))?;
186
187 let params: HashMap<String, Value> = HashMap::new();
188 let mut opts = ExecuteOptions::eager(¶ms)
191 .with_csv_import(CsvImportPolicy::LocalFilesystem)
192 .with_parallel(args.parallel);
193 if let Some(seconds) = args.timeout {
194 let seconds = check_timeout(seconds).map_err(|message| anyhow::anyhow!("{message}"))?;
195 opts.deadline = Some(Instant::now() + Duration::from_secs_f64(seconds));
196 }
197 let outcome = execute_read(&graph, query, &opts).map_err(|e| anyhow::anyhow!("{e}"))?;
198
199 let effective = if outcome.output_format == OutputFormat::Csv {
203 QueryFormat::Csv
204 } else {
205 args.format
206 };
207 let result = &outcome.result;
208 let stdout = match effective {
209 QueryFormat::Human => render_human(&result.columns, &result.rows),
210 QueryFormat::Csv => result.to_csv(),
211 QueryFormat::Json => render_json(&result.columns, &result.rows),
212 };
213 Ok(QueryOutput {
214 stdout,
215 rows: result.rows.len(),
216 warning,
217 })
218}
219
220fn freshness_warning(graph_path: &Path) -> Option<String> {
228 match crate::code_tree_cli::status(graph_path) {
229 Ok(report) => {
230 if report["fresh"] == serde_json::Value::Bool(true) {
231 return None;
232 }
233 let state = report["status"].as_str().unwrap_or("unknown");
234 let reason = report["reason"].as_str().unwrap_or("no reason recorded");
235 Some(format!("graph is {state}: {reason}"))
236 }
237 Err(error) => Some(format!("freshness could not be verified: {error}")),
238 }
239}
240
241fn render_json(columns: &[String], rows: &[Vec<Value>]) -> String {
244 let payload = serde_json::json!({
245 "columns": columns,
246 "rows": rows
247 .iter()
248 .map(|row| row.iter().map(kglite_value_to_json).collect::<Vec<_>>())
249 .collect::<Vec<_>>(),
250 });
251 format!("{}\n", serde_json::to_string(&payload).expect("JSON value"))
252}
253
254fn render_human(columns: &[String], rows: &[Vec<Value>]) -> String {
256 let mut out = String::new();
257 out.push_str(&columns.join("\t"));
258 out.push('\n');
259 for row in rows {
260 let cells: Vec<String> = row.iter().map(render_cell).collect();
261 out.push_str(&cells.join("\t"));
262 out.push('\n');
263 }
264 out
265}
266
267fn render_cell(value: &Value) -> String {
270 match value {
271 Value::String(s) => s
272 .replace('\t', "\\t")
273 .replace('\n', "\\n")
274 .replace('\r', "\\r"),
275 other => kglite_value_to_json(other).to_string(),
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282 use crate::code_tree_cli::{build, BuildArgs, StatusFormat};
283 use std::fs;
284
285 struct Fixture {
286 _dir: tempfile::TempDir,
287 source: PathBuf,
288 graph: PathBuf,
289 }
290
291 fn fixture_with_source(source_text: &str) -> Fixture {
295 let dir = tempfile::tempdir().unwrap();
296 let source = dir.path().join("proj");
297 fs::create_dir(&source).unwrap();
298 fs::write(
299 source.join("Cargo.toml"),
300 "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
301 )
302 .unwrap();
303 fs::create_dir(source.join("src")).unwrap();
304 fs::write(source.join("src/lib.rs"), source_text).unwrap();
305 let graph = dir.path().join("demo.kgl");
306 build(&BuildArgs {
307 source: source.clone(),
308 output: Some(graph.clone()),
309 rev: None,
310 revs: vec![],
311 repo_root: None,
312 no_tests: false,
313 include_docs: false,
314 max_loc_per_file: None,
315 verbose: false,
316 embed_skills: false,
317 format: StatusFormat::Json,
318 })
319 .unwrap();
320 Fixture {
321 _dir: dir,
322 source,
323 graph,
324 }
325 }
326
327 fn fixture() -> Fixture {
328 fixture_with_source("pub fn alpha() {}\npub fn beta() { alpha(); }\n")
329 }
330
331 fn args(graph: &Path, format: QueryFormat) -> QueryArgs {
334 QueryArgs {
335 query: String::new(),
336 graph: graph.to_path_buf(),
337 timeout: None,
338 format,
339 require_fresh: false,
340 parallel: false,
341 }
342 }
343
344 #[test]
345 fn query_returns_rows_from_built_graph() {
346 let fx = fixture();
347 let out = run_query(
348 &args(&fx.graph, QueryFormat::Human),
349 "MATCH (f:Function) RETURN f.name, f.qualified_name ORDER BY f.name ASC",
350 )
351 .unwrap();
352 assert_eq!(
353 out.stdout,
354 "f.name\tf.qualified_name\n\
355 alpha\tcrate::src::alpha\n\
356 beta\tcrate::src::beta\n"
357 );
358 assert_eq!(out.rows, 2);
359 }
360
361 #[test]
362 fn query_renders_non_string_cells_as_json() {
363 let fx = fixture();
364 let counted = run_query(
365 &args(&fx.graph, QueryFormat::Human),
366 "MATCH (f:Function) RETURN count(f)",
367 )
368 .unwrap();
369 assert_eq!(counted.stdout, "count(f)\n2\n");
370 assert_eq!(counted.rows, 1);
371
372 let listed = run_query(
373 &args(&fx.graph, QueryFormat::Human),
374 "MATCH (f:File) RETURN f.path, labels(f)",
375 )
376 .unwrap();
377 assert_eq!(listed.stdout, "f.path\tlabels(f)\nsrc/lib.rs\t[\"File\"]\n");
378 assert_eq!(listed.rows, 1);
379 }
380
381 #[test]
382 fn render_cell_escapes_tsv_hostile_control_characters() {
383 assert_eq!(
384 render_cell(&Value::String("a\tb\nc\rd".to_string())),
385 "a\\tb\\nc\\rd"
386 );
387 assert_eq!(render_cell(&Value::Int64(-7)), "-7");
388 assert_eq!(render_cell(&Value::Null), "null");
389 }
390
391 #[test]
392 fn query_rejects_mutation_cypher() {
393 let fx = fixture();
394 let error = run_query(
395 &args(&fx.graph, QueryFormat::Human),
396 "CREATE (n:X {name: 'nope'})",
397 )
398 .unwrap_err()
399 .to_string();
400 assert!(
401 error.contains("execute_read called with a mutation query"),
402 "unexpected error: {error}"
403 );
404 }
405
406 #[test]
407 fn query_missing_graph_names_path_and_hint() {
408 let dir = tempfile::tempdir().unwrap();
409 let missing = dir.path().join("absent.kgl");
410 let error = run_query(
411 &args(&missing, QueryFormat::Human),
412 "MATCH (f:File) RETURN f.path",
413 )
414 .unwrap_err()
415 .to_string();
416 assert!(
417 error.contains(&missing.display().to_string()),
418 "error omits the path: {error}"
419 );
420 assert!(
421 error.contains("codingest build"),
422 "error omits the build hint: {error}"
423 );
424 }
425
426 #[test]
427 fn query_missing_parameter_errors_with_empty_candidates_for_map_and_where() {
428 let fx = fixture();
429 for (query, expected) in [
430 (
431 "MATCH (n:$label) RETURN n",
432 "Cypher execution error: Missing parameter: $label (used as a label or relationship type)",
433 ),
434 (
435 "MATCH (n:Absent {name: $missing}) RETURN n",
436 "Cypher execution error: Missing parameter: $missing",
437 ),
438 (
439 "MATCH (n:Absent) WHERE n.name = $missing RETURN n",
440 "Cypher execution error: Missing parameter: $missing",
441 ),
442 ] {
443 for _ in 0..2 {
444 let error = run_query(&args(&fx.graph, QueryFormat::Json), query)
445 .unwrap_err()
446 .to_string();
447 assert_eq!(error, expected, "{query}");
448 }
449 }
450 }
451
452 fn engine_result(graph_path: &Path, query: &str) -> kglite::api::cypher::CypherResult {
456 let graph = load_file(&graph_path.to_string_lossy()).unwrap();
457 let params: HashMap<String, Value> = HashMap::new();
458 let opts = ExecuteOptions::eager(¶ms);
459 execute_read(&graph, query, &opts).unwrap().result
460 }
461
462 #[test]
463 fn query_format_json_parses_and_matches() {
464 let fx = fixture();
465 let out = run_query(
466 &args(&fx.graph, QueryFormat::Json),
467 "MATCH (f:Function) RETURN f.name, f.qualified_name ORDER BY f.name ASC",
468 )
469 .unwrap();
470 assert!(out.stdout.ends_with('\n'));
471 assert_eq!(out.stdout.lines().count(), 1, "JSON must be one line");
472 let parsed: serde_json::Value = serde_json::from_str(&out.stdout).unwrap();
473 assert_eq!(
474 parsed,
475 serde_json::json!({
476 "columns": ["f.name", "f.qualified_name"],
477 "rows": [
478 ["alpha", "crate::src::alpha"],
479 ["beta", "crate::src::beta"],
480 ],
481 })
482 );
483 assert_eq!(out.rows, 2);
484 }
485
486 #[test]
487 fn query_format_json_projects_non_string_cells_naturally() {
488 let fx = fixture();
489 let out = run_query(
490 &args(&fx.graph, QueryFormat::Json),
491 "MATCH (f:File) RETURN f.path, labels(f)",
492 )
493 .unwrap();
494 let parsed: serde_json::Value = serde_json::from_str(&out.stdout).unwrap();
495 assert_eq!(
496 parsed["rows"],
497 serde_json::json!([["src/lib.rs", ["File"]]]),
498 );
499 }
500
501 #[test]
502 fn query_format_csv_equals_result_to_csv() {
503 let fx = fixture();
504 let query = "MATCH (f:Function) RETURN f.name, f.qualified_name ORDER BY f.name ASC";
505 let out = run_query(&args(&fx.graph, QueryFormat::Csv), query).unwrap();
506 let expected = engine_result(&fx.graph, query).to_csv();
507 assert_eq!(out.stdout, expected);
508 assert_eq!(
509 out.stdout,
510 "f.name,f.qualified_name\nalpha,crate::src::alpha\nbeta,crate::src::beta\n"
511 );
512 assert_eq!(out.rows, 2);
513 }
514
515 #[test]
516 fn query_json_and_csv_remain_complete_beyond_mcp_preview_limit() {
517 let expected_names = (0..247)
518 .map(|index| format!("row_{index:03}_{}", "x".repeat(72)))
519 .collect::<Vec<_>>();
520 let source = expected_names
521 .iter()
522 .map(|name| format!("pub fn {name}() {{}}\n"))
523 .collect::<String>();
524 let fx = fixture_with_source(&source);
525 let query = "MATCH (f:Function) RETURN f.name ORDER BY f.name ASC";
526
527 let json = run_query(&args(&fx.graph, QueryFormat::Json), query).unwrap();
528 assert_eq!(json.rows, 247);
529 assert!(json.stdout.len() > 16_384, "{} bytes", json.stdout.len());
530 let parsed: serde_json::Value = serde_json::from_str(&json.stdout).unwrap();
531 let expected_rows = expected_names
532 .iter()
533 .map(|name| serde_json::json!([name]))
534 .collect::<Vec<_>>();
535 assert_eq!(parsed["columns"], serde_json::json!(["f.name"]));
536 assert_eq!(parsed["rows"], serde_json::json!(expected_rows));
537
538 let csv = run_query(&args(&fx.graph, QueryFormat::Csv), query).unwrap();
539 assert_eq!(csv.rows, 247);
540 assert!(csv.stdout.len() > 16_384, "{} bytes", csv.stdout.len());
541 let expected_csv = format!("f.name\n{}\n", expected_names.join("\n"));
542 assert_eq!(csv.stdout, expected_csv);
543 }
544
545 #[test]
546 fn query_inline_format_csv_overrides_flag() {
547 let fx = fixture();
548 let query = "MATCH (f:Function) RETURN f.name, f.qualified_name \
551 ORDER BY f.name ASC FORMAT CSV";
552 for flag in [QueryFormat::Json, QueryFormat::Human] {
553 let out = run_query(&args(&fx.graph, flag), query).unwrap();
554 assert_eq!(
555 out.stdout,
556 "f.name,f.qualified_name\nalpha,crate::src::alpha\nbeta,crate::src::beta\n",
557 "--format {flag:?} survived an in-query FORMAT CSV"
558 );
559 }
560 }
561
562 #[test]
563 fn query_explain_renders_rows() {
564 let fx = fixture();
565 let out = run_query(
566 &args(&fx.graph, QueryFormat::Human),
567 "EXPLAIN MATCH (f:Function) RETURN f.name",
568 )
569 .unwrap();
570 assert!(out.rows > 0, "EXPLAIN produced no plan rows");
571 assert!(
572 out.stdout.lines().count() > 1,
573 "no rendered plan: {:?}",
574 out
575 );
576 }
577
578 const ROWS: &str = "MATCH (f:Function) RETURN f.name ORDER BY f.name ASC";
579 const EXPECTED: &str = "f.name\nalpha\nbeta\n";
580
581 #[test]
582 fn query_fresh_graph_has_no_warning() {
583 let fx = fixture();
584 let out = run_query(&args(&fx.graph, QueryFormat::Human), ROWS).unwrap();
585 assert_eq!(out.warning, None);
586 assert_eq!(out.stdout, EXPECTED);
587 }
588
589 #[test]
590 fn query_warns_on_stale_graph() {
591 let fx = fixture();
592 fs::write(fx.source.join("src/lib.rs"), "pub fn gamma() {}\n").unwrap();
593 let out = run_query(&args(&fx.graph, QueryFormat::Human), ROWS).unwrap();
594 assert_eq!(
595 out.warning.as_deref(),
596 Some("graph is stale: source changed since the graph was built")
597 );
598 assert_eq!(out.stdout, EXPECTED);
601 assert_eq!(out.rows, 2);
602 }
603
604 #[test]
605 fn query_missing_sidecar_warns_but_runs() {
606 let fx = fixture();
607 let sidecar = fx.graph.with_extension("kgl.meta.json");
608 assert!(sidecar.exists(), "fixture sidecar missing: {sidecar:?}");
609 fs::remove_file(&sidecar).unwrap();
610 let out = run_query(&args(&fx.graph, QueryFormat::Human), ROWS).unwrap();
611 assert_eq!(
612 out.warning.as_deref(),
613 Some("graph is missing: graph artifact or metadata sidecar is missing")
614 );
615 assert_eq!(out.stdout, EXPECTED);
616 }
617
618 #[test]
619 fn query_unverifiable_freshness_warns_but_runs() {
620 let fx = fixture();
621 fs::remove_dir_all(&fx.source).unwrap();
625 let out = run_query(&args(&fx.graph, QueryFormat::Human), ROWS).unwrap();
626 let warning = out.warning.expect("no warning for an unverifiable graph");
627 assert!(
628 warning.starts_with("freshness could not be verified: "),
629 "unexpected warning: {warning}"
630 );
631 assert_eq!(out.stdout, EXPECTED);
632 }
633
634 #[test]
635 fn query_require_fresh_errors_on_stale() {
636 let fx = fixture();
637 fs::write(fx.source.join("src/lib.rs"), "pub fn gamma() {}\n").unwrap();
638 let mut strict = args(&fx.graph, QueryFormat::Human);
639 strict.require_fresh = true;
640 let error = run_query(&strict, ROWS).unwrap_err();
641 let stale = error
642 .downcast_ref::<StaleGraph>()
643 .expect("--require-fresh did not produce a typed StaleGraph");
644 assert_eq!(stale.graph, fx.graph);
645 assert_eq!(
646 stale.reason,
647 "graph is stale: source changed since the graph was built"
648 );
649 assert_eq!(crate::exit_code_for(&error), 3);
650 }
651
652 #[test]
653 fn query_require_fresh_passes_on_fresh_graph() {
654 let fx = fixture();
655 let mut strict = args(&fx.graph, QueryFormat::Human);
656 strict.require_fresh = true;
657 let out = run_query(&strict, ROWS).unwrap();
658 assert_eq!(out.stdout, EXPECTED);
659 }
660
661 #[test]
662 fn exit_code_for_maps_stale_to_3_and_other_to_1() {
663 let stale: anyhow::Error = StaleGraph {
664 graph: PathBuf::from("/tmp/demo.kgl"),
665 reason: "source changed".to_string(),
666 }
667 .into();
668 assert_eq!(crate::exit_code_for(&stale), 3);
669 assert_eq!(crate::exit_code_for(&anyhow::anyhow!("bad cypher")), 1);
670 assert_eq!(
671 crate::exit_code_for(&std::io::Error::from(std::io::ErrorKind::NotFound).into()),
672 1
673 );
674 }
675
676 #[test]
677 fn parse_timeout_rejects_the_values_that_panic_duration() {
678 for raw in ["-1", "nan", "-0.5", "inf", "1e30", "0", "-0"] {
681 assert!(parse_timeout(raw).is_err(), "--timeout={raw} was accepted");
682 }
683 assert!(parse_timeout("banana").is_err());
684 assert_eq!(parse_timeout("0.000001"), Ok(0.000001));
685 assert_eq!(parse_timeout("30"), Ok(30.0));
686 assert_eq!(parse_timeout("1e9"), Ok(MAX_TIMEOUT_SECS));
687 }
688
689 #[test]
690 fn run_query_rejects_an_out_of_domain_timeout_without_panicking() {
691 let fx = fixture();
694 for seconds in [-1.0, f64::NAN, 0.0, 1e30, f64::INFINITY] {
695 let mut bad = args(&fx.graph, QueryFormat::Human);
696 bad.timeout = Some(seconds);
697 let error = run_query(&bad, ROWS).unwrap_err().to_string();
698 assert!(
699 error.contains("timeout must be a positive, finite number"),
700 "unexpected error for {seconds}: {error}"
701 );
702 }
703 }
704
705 #[test]
715 fn parallel_opt_in_is_wired_and_returns_the_same_rows() {
716 let fx = fixture();
717 let serial = run_query(&args(&fx.graph, QueryFormat::Human), ROWS).unwrap();
718 let mut parallel_args = args(&fx.graph, QueryFormat::Human);
719 parallel_args.parallel = true;
720 let parallel = run_query(¶llel_args, ROWS).unwrap();
721 assert_eq!(parallel.stdout, serial.stdout);
722 assert_eq!(parallel.rows, serial.rows);
723 assert_eq!(serial.rows, 2, "fixture lost its functions");
724 }
725
726 #[test]
727 fn query_reads_query_from_stdin_dash() {
728 let piped = "MATCH (f:File) RETURN f.path\n";
729 assert_eq!(read_query("-", piped.as_bytes()).unwrap(), piped);
730 assert_eq!(
731 read_query("MATCH (n) RETURN n", piped.as_bytes()).unwrap(),
732 "MATCH (n) RETURN n"
733 );
734 }
735}