Skip to main content

sql_cli/sql/generators/
file_readers.rs

1use crate::data::advanced_csv_loader::AdvancedCsvLoader;
2use crate::data::datatable::{DataColumn, DataRow, DataTable, DataType, DataValue};
3use crate::data::stream_loader::{
4    collect_column_names, detect_delimiter_from_path, parse_delimiter_arg as parse_delim_byte,
5    parse_json_records, CsvReadOptions,
6};
7use crate::sql::generators::TableGenerator;
8use anyhow::{anyhow, Result};
9use regex::Regex;
10use serde_json::Value as JsonValue;
11use std::fs::File;
12use std::io::{BufRead, BufReader, Cursor, IsTerminal};
13use std::sync::{Arc, OnceLock};
14
15/// Hard cap on rows any file reader will return. Users who need more can raise
16/// it via a session setting (future work); for now this protects against
17/// accidentally pulling a multi-GB log into memory.
18const MAX_LINES_PER_FILE: usize = 1_000_000;
19
20/// Extract a string argument, erroring if the arg is missing/NULL/non-string.
21fn require_string(args: &[DataValue], idx: usize, name: &str) -> Result<String> {
22    match args.get(idx) {
23        Some(DataValue::String(s)) => Ok(s.clone()),
24        Some(DataValue::InternedString(s)) => Ok(s.as_str().to_string()),
25        Some(DataValue::Null) | None => Err(anyhow!("{} requires argument {}", name, idx + 1)),
26        Some(v) => Err(anyhow!(
27            "{} argument {} must be a string, got {:?}",
28            name,
29            idx + 1,
30            v
31        )),
32    }
33}
34
35/// Extract an optional string argument. Returns None for missing or NULL.
36fn optional_string(args: &[DataValue], idx: usize) -> Option<String> {
37    match args.get(idx) {
38        Some(DataValue::String(s)) => Some(s.clone()),
39        Some(DataValue::InternedString(s)) => Some(s.as_str().to_string()),
40        _ => None,
41    }
42}
43
44/// Parse a delimiter arg for READ_CSV, wrapping the shared parser's error
45/// with the function name for clearer messages.
46fn parse_delimiter_arg(s: &str, fn_name: &str) -> Result<u8> {
47    parse_delim_byte(s).map_err(|e| anyhow!("{}: {}", fn_name, e))
48}
49
50/// Open a file and stream its lines, applying an optional include-regex filter
51/// and the global truncation cap. Emits a stderr warning when truncation kicks in.
52///
53/// Returns (line_num, line) pairs where `line_num` is the original 1-based line
54/// number in the source file — so numbers are preserved through filtering.
55fn read_filtered_lines(path: &str, match_regex: Option<&Regex>) -> Result<Vec<(i64, String)>> {
56    let file = File::open(path).map_err(|e| anyhow!("Failed to open '{}': {}", path, e))?;
57    let reader = BufReader::new(file);
58
59    let mut out = Vec::new();
60    let mut truncated = false;
61
62    for (idx, line_result) in reader.lines().enumerate() {
63        let line = line_result.map_err(|e| anyhow!("Error reading '{}': {}", path, e))?;
64        let line_num = (idx + 1) as i64;
65
66        if let Some(re) = match_regex {
67            if !re.is_match(&line) {
68                continue;
69            }
70        }
71
72        if out.len() >= MAX_LINES_PER_FILE {
73            truncated = true;
74            break;
75        }
76        out.push((line_num, line));
77    }
78
79    if truncated {
80        eprintln!(
81            "WARNING: truncated to {} rows (max_lines_per_file cap) when reading '{}'",
82            MAX_LINES_PER_FILE, path
83        );
84    }
85
86    Ok(out)
87}
88
89/// Read lines from a file path, or from stdin if `path == "-"` (Unix convention).
90///
91/// Stdin reads are cached for the process — same buffer is reused across multiple
92/// reader invocations in the same query. The optional regex filter is applied to
93/// both sources uniformly.
94fn read_lines_from_path_or_stdin(
95    path: &str,
96    match_regex: Option<&Regex>,
97) -> Result<Vec<(i64, String)>> {
98    if path == "-" {
99        let cached = cached_stdin_lines()?;
100        return Ok(cached
101            .iter()
102            .filter(|(_, line)| match_regex.map_or(true, |re| re.is_match(line)))
103            .cloned()
104            .collect());
105    }
106    read_filtered_lines(path, match_regex)
107}
108
109/// READ_TEXT(path [, match_regex]) - Read a text file line by line.
110///
111/// Emits `(line_num, line)` rows. Optional `match_regex` filters source lines
112/// *before* materializing them, which is the primary fast path for large logs.
113pub struct ReadText;
114
115impl TableGenerator for ReadText {
116    fn name(&self) -> &str {
117        "READ_TEXT"
118    }
119
120    fn columns(&self) -> Vec<DataColumn> {
121        vec![DataColumn::new("line_num"), DataColumn::new("line")]
122    }
123
124    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
125        if args.is_empty() || args.len() > 2 {
126            return Err(anyhow!(
127                "READ_TEXT expects 1 or 2 arguments: (path [, match_regex])"
128            ));
129        }
130
131        let path = require_string(&args, 0, "READ_TEXT")?;
132        let match_regex = optional_string(&args, 1)
133            .map(|s| Regex::new(&s).map_err(|e| anyhow!("Invalid match_regex: {}", e)))
134            .transpose()?;
135
136        let lines = read_lines_from_path_or_stdin(&path, match_regex.as_ref())?;
137
138        let mut table = DataTable::new("read_text");
139        table.add_column(DataColumn::new("line_num"));
140        table.add_column(DataColumn::new("line"));
141
142        for (line_num, line) in lines {
143            table
144                .add_row(DataRow::new(vec![
145                    DataValue::Integer(line_num),
146                    DataValue::String(line),
147                ]))
148                .map_err(|e| anyhow!(e))?;
149        }
150
151        Ok(Arc::new(table))
152    }
153
154    fn description(&self) -> &str {
155        "Read a text file line-by-line. Pass '-' as path to read from stdin. Optional second arg is a regex that filters lines at read time."
156    }
157
158    fn arg_count(&self) -> usize {
159        2
160    }
161}
162
163/// GREP(path, pattern [, invert]) - Read only lines matching a regex.
164///
165/// Thin composable wrapper around READ_TEXT's filter path. Third argument
166/// (boolean or integer truthy value) inverts the match, matching `grep -v`.
167pub struct Grep;
168
169impl TableGenerator for Grep {
170    fn name(&self) -> &str {
171        "GREP"
172    }
173
174    fn columns(&self) -> Vec<DataColumn> {
175        vec![DataColumn::new("line_num"), DataColumn::new("line")]
176    }
177
178    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
179        if args.len() < 2 || args.len() > 3 {
180            return Err(anyhow!(
181                "GREP expects 2 or 3 arguments: (path, pattern [, invert])"
182            ));
183        }
184
185        let path = require_string(&args, 0, "GREP")?;
186        let pattern_str = require_string(&args, 1, "GREP")?;
187        let pattern =
188            Regex::new(&pattern_str).map_err(|e| anyhow!("Invalid GREP pattern: {}", e))?;
189
190        let invert = match args.get(2) {
191            Some(DataValue::Boolean(b)) => *b,
192            Some(DataValue::Integer(n)) => *n != 0,
193            Some(DataValue::Null) | None => false,
194            Some(v) => return Err(anyhow!("GREP invert flag must be boolean, got {:?}", v)),
195        };
196
197        // When not inverted we can push the filter down into the line reader for
198        // the fast path. When inverted we still iterate every line.
199        let lines = if invert {
200            let all = read_lines_from_path_or_stdin(&path, None)?;
201            all.into_iter()
202                .filter(|(_, line)| !pattern.is_match(line))
203                .collect::<Vec<_>>()
204        } else {
205            read_lines_from_path_or_stdin(&path, Some(&pattern))?
206        };
207
208        let mut table = DataTable::new("grep");
209        table.add_column(DataColumn::new("line_num"));
210        table.add_column(DataColumn::new("line"));
211
212        for (line_num, line) in lines {
213            table
214                .add_row(DataRow::new(vec![
215                    DataValue::Integer(line_num),
216                    DataValue::String(line),
217                ]))
218                .map_err(|e| anyhow!(e))?;
219        }
220
221        Ok(Arc::new(table))
222    }
223
224    fn description(&self) -> &str {
225        "Read only lines matching a regex (third arg inverts the match, like grep -v). Pass '-' as path to read from stdin."
226    }
227
228    fn arg_count(&self) -> usize {
229        3
230    }
231}
232
233/// READ_WORDS(path [, min_length [, case]]) - Read a text file and emit one row per word.
234///
235/// Emits `(word_num, word, line_num, word_pos)` rows where:
236///   - `word_num` is a global 1-based word counter across the whole file
237///   - `word` is the extracted token (punctuation stripped)
238///   - `line_num` is the original 1-based line number the word came from
239///   - `word_pos` is the 1-based position of the word within its line
240///
241/// Optional `min_length` (default 1) filters out short words.
242/// Optional `case` ('lower' or 'upper') normalises word casing.
243pub struct ReadWords;
244
245impl TableGenerator for ReadWords {
246    fn name(&self) -> &str {
247        "READ_WORDS"
248    }
249
250    fn columns(&self) -> Vec<DataColumn> {
251        vec![
252            DataColumn::new("word_num"),
253            DataColumn::new("word"),
254            DataColumn::new("line_num"),
255            DataColumn::new("word_pos"),
256        ]
257    }
258
259    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
260        if args.is_empty() || args.len() > 3 {
261            return Err(anyhow!(
262                "READ_WORDS expects 1 to 3 arguments: (path [, min_length [, case]])"
263            ));
264        }
265
266        let path = require_string(&args, 0, "READ_WORDS")?;
267
268        let min_length: usize = match args.get(1) {
269            Some(DataValue::Integer(n)) => {
270                if *n < 1 {
271                    return Err(anyhow!("READ_WORDS min_length must be >= 1"));
272                }
273                *n as usize
274            }
275            Some(DataValue::Float(f)) => *f as usize,
276            Some(DataValue::Null) | None => 1,
277            Some(v) => {
278                return Err(anyhow!(
279                    "READ_WORDS min_length must be an integer, got {:?}",
280                    v
281                ))
282            }
283        };
284
285        let case_option = optional_string(&args, 2);
286
287        let lines = read_lines_from_path_or_stdin(&path, None)?;
288
289        let mut table = DataTable::new("read_words");
290        table.add_column(DataColumn::new("word_num"));
291        table.add_column(DataColumn::new("word"));
292        table.add_column(DataColumn::new("line_num"));
293        table.add_column(DataColumn::new("word_pos"));
294
295        let mut word_num: i64 = 0;
296
297        for (line_num, line) in &lines {
298            let mut word_pos: i64 = 0;
299
300            for token in line.split(|c: char| !c.is_alphanumeric()) {
301                if token.is_empty() || token.len() < min_length {
302                    continue;
303                }
304
305                word_pos += 1;
306                word_num += 1;
307
308                let word = match case_option.as_deref() {
309                    Some("lower") | Some("lowercase") => token.to_lowercase(),
310                    Some("upper") | Some("uppercase") => token.to_uppercase(),
311                    _ => token.to_string(),
312                };
313
314                table
315                    .add_row(DataRow::new(vec![
316                        DataValue::Integer(word_num),
317                        DataValue::String(word),
318                        DataValue::Integer(*line_num),
319                        DataValue::Integer(word_pos),
320                    ]))
321                    .map_err(|e| anyhow!(e))?;
322            }
323        }
324
325        Ok(Arc::new(table))
326    }
327
328    fn description(&self) -> &str {
329        "Read a text file and emit one row per word, with optional min length and case normalisation"
330    }
331
332    fn arg_count(&self) -> usize {
333        3
334    }
335}
336
337/// READ_JSONL(path [, match_regex]) - Read newline-delimited JSON.
338///
339/// Each non-blank line is parsed as a self-contained JSON object. Schema is
340/// the union of object keys across the first 100 records, so heterogeneous
341/// log streams (later events introducing new fields) don't drop columns.
342/// Optional `match_regex` filters source lines *before* JSON parsing — the
343/// fast path for grepping large log files.
344pub struct ReadJsonl;
345
346impl TableGenerator for ReadJsonl {
347    fn name(&self) -> &str {
348        "READ_JSONL"
349    }
350
351    fn columns(&self) -> Vec<DataColumn> {
352        // Schema is dynamic; the actual columns are inferred at generate() time
353        // from the JSON keys in the file.
354        vec![DataColumn::new("(inferred from JSON keys)")]
355    }
356
357    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
358        if args.is_empty() || args.len() > 2 {
359            return Err(anyhow!(
360                "READ_JSONL expects 1 or 2 arguments: (path [, match_regex])"
361            ));
362        }
363
364        let path = require_string(&args, 0, "READ_JSONL")?;
365        let match_regex = optional_string(&args, 1)
366            .map(|s| Regex::new(&s).map_err(|e| anyhow!("Invalid match_regex: {}", e)))
367            .transpose()?;
368
369        let lines = read_lines_from_path_or_stdin(&path, match_regex.as_ref())?;
370
371        let mut records: Vec<JsonValue> = Vec::with_capacity(lines.len());
372        for (line_num, line) in &lines {
373            let trimmed = line.trim();
374            if trimmed.is_empty() {
375                continue;
376            }
377            let value: JsonValue = serde_json::from_str(trimmed)
378                .map_err(|e| anyhow!("READ_JSONL parse error at line {}: {}", line_num, e))?;
379            records.push(value);
380        }
381
382        let table = json_records_to_table(records, "read_jsonl", "READ_JSONL")?;
383        Ok(Arc::new(table))
384    }
385
386    fn description(&self) -> &str {
387        "Read newline-delimited JSON (one object per line). Pass '-' as path to read JSONL from stdin. Optional second arg is a regex that filters lines at read time."
388    }
389
390    fn arg_count(&self) -> usize {
391        2
392    }
393}
394
395/// READ_CSV(path [, delimiter]) - Read a delimited text file and emit one row per record.
396///
397/// Columns are inferred from the header row. Pass `-` as the path to read CSV
398/// from stdin (shares the same cached-once buffer with READ_STDIN / READ_JSONL).
399///
400/// Delimiter resolution:
401///   1. Explicit 2nd arg wins (single ASCII char or `\t` escape).
402///   2. Otherwise, `.tsv` → tab, `.psv` → pipe, everything else → comma.
403///   3. Stdin (`-`) with no explicit delimiter defaults to comma.
404///
405/// Type inference, string interning, and other optimisations are inherited
406/// from the main CSV loader so behaviour matches `sql-cli file.csv -q ...`.
407pub struct ReadCsv;
408
409impl TableGenerator for ReadCsv {
410    fn name(&self) -> &str {
411        "READ_CSV"
412    }
413
414    fn columns(&self) -> Vec<DataColumn> {
415        // Schema is inferred from the CSV header at generate() time.
416        vec![DataColumn::new("(inferred from CSV header)")]
417    }
418
419    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
420        if args.is_empty() || args.len() > 2 {
421            return Err(anyhow!(
422                "READ_CSV expects 1 or 2 arguments: (path [, delimiter])"
423            ));
424        }
425
426        let path = require_string(&args, 0, "READ_CSV")?;
427
428        // Resolve delimiter: explicit 2nd arg > extension auto-detect > comma.
429        // Stdin (`-`) skips the extension layer since there's no extension to read.
430        let delimiter = if let Some(s) = optional_string(&args, 1) {
431            parse_delimiter_arg(&s, "READ_CSV")?
432        } else if path == "-" {
433            b','
434        } else {
435            detect_delimiter_from_path(&path)
436        };
437
438        let opts = CsvReadOptions {
439            delimiter,
440            has_headers: true,
441        };
442
443        let mut loader = AdvancedCsvLoader::new();
444
445        let table = if path == "-" {
446            // Reconstruct a CSV byte stream from the cached stdin lines so other
447            // stdin readers in the same query keep seeing the same buffer.
448            let lines = cached_stdin_lines()?;
449            let mut buffer = String::with_capacity(lines.iter().map(|(_, l)| l.len() + 1).sum());
450            for (i, (_, line)) in lines.iter().enumerate() {
451                if i > 0 {
452                    buffer.push('\n');
453                }
454                buffer.push_str(line);
455            }
456            let cursor = Cursor::new(buffer.into_bytes());
457            loader
458                .load_csv_from_reader_with_opts(cursor, "read_csv", "<stdin>", &opts)
459                .map_err(|e| anyhow!("READ_CSV parse error reading stdin: {}", e))?
460        } else {
461            let file = File::open(&path)
462                .map_err(|e| anyhow!("READ_CSV failed to open '{}': {}", path, e))?;
463            loader
464                .load_csv_from_reader_with_opts(file, "read_csv", &path, &opts)
465                .map_err(|e| anyhow!("READ_CSV parse error reading '{}': {}", path, e))?
466        };
467
468        Ok(Arc::new(table))
469    }
470
471    fn description(&self) -> &str {
472        "Read a delimited text file (header row required). Pass '-' as path to read from stdin. \
473         Second arg overrides the delimiter; otherwise '.tsv' → tab, '.psv' → pipe, else comma."
474    }
475
476    fn arg_count(&self) -> usize {
477        2
478    }
479}
480
481fn json_value_to_string(value: &JsonValue) -> String {
482    match value {
483        JsonValue::Null => String::new(),
484        JsonValue::Bool(b) => b.to_string(),
485        JsonValue::Number(n) => n.to_string(),
486        JsonValue::String(s) => s.clone(),
487        JsonValue::Array(arr) => format!("{:?}", arr),
488        JsonValue::Object(obj) => format!("{:?}", obj),
489    }
490}
491
492/// Build a typed `DataTable` from a list of parsed JSON records (objects).
493///
494/// Columns are the ordered union of object keys across the first 100 records,
495/// so heterogeneous streams don't drop late-appearing fields. Types are
496/// inferred from the first 100 rows. Shared by READ_JSONL (one object per line)
497/// and READ_JSON (whole document / array). `func` names the calling function in
498/// error messages.
499fn json_records_to_table(
500    records: Vec<JsonValue>,
501    table_name: &str,
502    func: &str,
503) -> Result<DataTable> {
504    if records.is_empty() {
505        return Ok(DataTable::new(table_name));
506    }
507
508    let column_names = collect_column_names(&records, 100);
509    if column_names.is_empty() {
510        return Err(anyhow!(
511            "{}: no JSON objects found (records must be objects, not arrays/scalars)",
512            func
513        ));
514    }
515
516    // Stringify, infer types from the first 100 rows, then convert to typed
517    // DataValues — same pipeline the file-level JSON loader uses.
518    let mut string_rows: Vec<Vec<String>> = Vec::with_capacity(records.len());
519    for record in &records {
520        let obj = match record.as_object() {
521            Some(o) => o,
522            None => continue,
523        };
524        let mut row = Vec::with_capacity(column_names.len());
525        for col_name in &column_names {
526            let value = obj
527                .get(col_name)
528                .map(json_value_to_string)
529                .unwrap_or_default();
530            row.push(value);
531        }
532        string_rows.push(row);
533    }
534
535    let mut column_types: Vec<DataType> = vec![DataType::Null; column_names.len()];
536    let sample_size = string_rows.len().min(100);
537    for row in string_rows.iter().take(sample_size) {
538        for (col_idx, value) in row.iter().enumerate() {
539            if !value.is_empty() && value != "null" {
540                let inferred = DataType::infer_from_string(value);
541                column_types[col_idx] = column_types[col_idx].merge(&inferred);
542            }
543        }
544    }
545
546    let mut table = DataTable::new(table_name);
547    for (name, dtype) in column_names.iter().zip(column_types.iter()) {
548        let mut col = DataColumn::new(name);
549        col.data_type = dtype.clone();
550        table.add_column(col);
551    }
552
553    for string_row in &string_rows {
554        let mut values = Vec::with_capacity(string_row.len());
555        for (col_idx, value) in string_row.iter().enumerate() {
556            let dv = if value.is_empty() || value == "null" {
557                DataValue::Null
558            } else {
559                DataValue::from_string(value, &column_types[col_idx])
560            };
561            values.push(dv);
562        }
563        table
564            .add_row(DataRow::new(values))
565            .map_err(|e| anyhow!(e))?;
566    }
567
568    Ok(table)
569}
570
571/// READ_JSON(path) - Read a whole JSON document and emit one row per object.
572///
573/// Accepts either a JSON array of objects (`[{...}, {...}]`, possibly
574/// pretty-printed across many lines) or newline-delimited JSON (JSONL); the
575/// format is auto-detected. This is the multi-line counterpart to READ_JSONL,
576/// which requires exactly one object per line. Pass `-` as the path to read
577/// from stdin (shares the same cached-once buffer as the other stdin readers).
578pub struct ReadJson;
579
580impl TableGenerator for ReadJson {
581    fn name(&self) -> &str {
582        "READ_JSON"
583    }
584
585    fn columns(&self) -> Vec<DataColumn> {
586        // Schema is dynamic; the actual columns are inferred at generate() time
587        // from the JSON keys in the document.
588        vec![DataColumn::new("(inferred from JSON keys)")]
589    }
590
591    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
592        if args.len() != 1 {
593            return Err(anyhow!("READ_JSON expects 1 argument: (path)"));
594        }
595
596        let path = require_string(&args, 0, "READ_JSON")?;
597
598        let content = if path == "-" {
599            // Reconstruct the document from the cached stdin lines so other
600            // stdin readers in the same query keep seeing the same buffer.
601            let lines = cached_stdin_lines()?;
602            let mut buffer = String::with_capacity(lines.iter().map(|(_, l)| l.len() + 1).sum());
603            for (i, (_, line)) in lines.iter().enumerate() {
604                if i > 0 {
605                    buffer.push('\n');
606                }
607                buffer.push_str(line);
608            }
609            buffer
610        } else {
611            std::fs::read_to_string(&path)
612                .map_err(|e| anyhow!("READ_JSON failed to read '{}': {}", path, e))?
613        };
614
615        let records =
616            parse_json_records(&content).map_err(|e| anyhow!("READ_JSON parse error: {}", e))?;
617
618        let table = json_records_to_table(records, "read_json", "READ_JSON")?;
619        Ok(Arc::new(table))
620    }
621
622    fn description(&self) -> &str {
623        "Read a whole JSON document — a JSON array of objects (possibly pretty-printed) or newline-delimited JSON — and emit one row per object. Pass '-' as path to read from stdin. Unlike READ_JSONL, the input may span multiple lines per record."
624    }
625
626    fn arg_count(&self) -> usize {
627        1
628    }
629}
630
631/// READ_STDIN([match_regex]) - Read lines piped on standard input.
632///
633/// Emits `(line_num, line)` rows. Optional regex pre-filters lines before
634/// materialisation. Erroring on TTY input prevents the engine from blocking
635/// forever waiting on a keyboard when the user forgets the pipe.
636///
637/// Stdin is consumable, so it is read **once per process** and cached. This
638/// keeps the function composable: multiple `READ_STDIN()` references in the
639/// same query (CTEs, self-joins) see the same rows. The regex filter is
640/// applied per call against the cached buffer.
641pub struct ReadStdin;
642
643static STDIN_CACHE: OnceLock<Result<Vec<(i64, String)>, String>> = OnceLock::new();
644
645fn cached_stdin_lines() -> Result<&'static Vec<(i64, String)>> {
646    let cached = STDIN_CACHE.get_or_init(|| {
647        let stdin = std::io::stdin();
648        if stdin.is_terminal() {
649            return Err("READ_STDIN() requires data piped on stdin; got an interactive terminal. Try: cat file | sql-cli -q '...'".to_string());
650        }
651        let handle = stdin.lock();
652        let reader = BufReader::new(handle);
653        let mut out = Vec::new();
654        let mut truncated = false;
655        for (idx, line_result) in reader.lines().enumerate() {
656            let line = match line_result {
657                Ok(l) => l,
658                Err(e) => return Err(format!("Error reading stdin: {}", e)),
659            };
660            if out.len() >= MAX_LINES_PER_FILE {
661                truncated = true;
662                break;
663            }
664            out.push(((idx + 1) as i64, line));
665        }
666        if truncated {
667            eprintln!(
668                "WARNING: truncated to {} rows (max_lines_per_file cap) when reading stdin",
669                MAX_LINES_PER_FILE
670            );
671        }
672        Ok(out)
673    });
674    cached.as_ref().map_err(|e| anyhow!(e.clone()))
675}
676
677impl TableGenerator for ReadStdin {
678    fn name(&self) -> &str {
679        "READ_STDIN"
680    }
681
682    fn columns(&self) -> Vec<DataColumn> {
683        vec![DataColumn::new("line_num"), DataColumn::new("line")]
684    }
685
686    fn generate(&self, args: Vec<DataValue>) -> Result<Arc<DataTable>> {
687        if args.len() > 1 {
688            return Err(anyhow!(
689                "READ_STDIN expects 0 or 1 arguments: ([match_regex])"
690            ));
691        }
692
693        let match_regex = optional_string(&args, 0)
694            .map(|s| Regex::new(&s).map_err(|e| anyhow!("Invalid match_regex: {}", e)))
695            .transpose()?;
696
697        let lines = cached_stdin_lines()?;
698
699        let mut table = DataTable::new("read_stdin");
700        table.add_column(DataColumn::new("line_num"));
701        table.add_column(DataColumn::new("line"));
702
703        for (line_num, line) in lines {
704            if let Some(ref re) = match_regex {
705                if !re.is_match(line) {
706                    continue;
707                }
708            }
709            table
710                .add_row(DataRow::new(vec![
711                    DataValue::Integer(*line_num),
712                    DataValue::String(line.clone()),
713                ]))
714                .map_err(|e| anyhow!(e))?;
715        }
716
717        Ok(Arc::new(table))
718    }
719
720    fn description(&self) -> &str {
721        "Read lines piped on stdin (cached once per process). Optional regex filters lines at read time. Yields (line_num, line)."
722    }
723
724    fn arg_count(&self) -> usize {
725        1
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732    use std::io::Write;
733    use tempfile::NamedTempFile;
734
735    fn write_tmp(contents: &str) -> NamedTempFile {
736        let mut f = NamedTempFile::new().unwrap();
737        f.write_all(contents.as_bytes()).unwrap();
738        f
739    }
740
741    #[test]
742    fn test_read_text_returns_all_lines() {
743        let f = write_tmp("one\ntwo\nthree\n");
744        let table = ReadText
745            .generate(vec![DataValue::String(
746                f.path().to_string_lossy().to_string(),
747            )])
748            .unwrap();
749        assert_eq!(table.row_count(), 3);
750        assert_eq!(
751            table.get_value(0, 1).unwrap(),
752            &DataValue::String("one".to_string())
753        );
754        assert_eq!(table.get_value(2, 0).unwrap(), &DataValue::Integer(3));
755    }
756
757    #[test]
758    fn test_read_text_with_match_regex_filters_lines() {
759        let f = write_tmp("INFO boot\nERROR disk full\nINFO shutdown\nERROR oom\n");
760        let table = ReadText
761            .generate(vec![
762                DataValue::String(f.path().to_string_lossy().to_string()),
763                DataValue::String("ERROR".to_string()),
764            ])
765            .unwrap();
766        assert_eq!(table.row_count(), 2);
767        // Line numbers preserve original file positions (2 and 4), not 1 and 2.
768        assert_eq!(table.get_value(0, 0).unwrap(), &DataValue::Integer(2));
769        assert_eq!(table.get_value(1, 0).unwrap(), &DataValue::Integer(4));
770    }
771
772    #[test]
773    fn test_read_text_requires_path() {
774        assert!(ReadText.generate(vec![]).is_err());
775    }
776
777    #[test]
778    fn test_read_text_invalid_regex_errors_early() {
779        let f = write_tmp("hello\n");
780        let err = ReadText
781            .generate(vec![
782                DataValue::String(f.path().to_string_lossy().to_string()),
783                DataValue::String("(unclosed".to_string()),
784            ])
785            .unwrap_err();
786        assert!(err.to_string().contains("match_regex"));
787    }
788
789    #[test]
790    fn test_grep_matches_like_grep() {
791        let f = write_tmp("apple\nbanana\ncherry\napricot\n");
792        let table = Grep
793            .generate(vec![
794                DataValue::String(f.path().to_string_lossy().to_string()),
795                DataValue::String("^ap".to_string()),
796            ])
797            .unwrap();
798        assert_eq!(table.row_count(), 2);
799        assert_eq!(
800            table.get_value(0, 1).unwrap(),
801            &DataValue::String("apple".to_string())
802        );
803        assert_eq!(
804            table.get_value(1, 1).unwrap(),
805            &DataValue::String("apricot".to_string())
806        );
807    }
808
809    #[test]
810    fn test_grep_invert_like_grep_v() {
811        let f = write_tmp("apple\nbanana\ncherry\napricot\n");
812        let table = Grep
813            .generate(vec![
814                DataValue::String(f.path().to_string_lossy().to_string()),
815                DataValue::String("^ap".to_string()),
816                DataValue::Boolean(true),
817            ])
818            .unwrap();
819        assert_eq!(table.row_count(), 2);
820        assert_eq!(
821            table.get_value(0, 1).unwrap(),
822            &DataValue::String("banana".to_string())
823        );
824    }
825
826    // ---- ReadWords tests ----
827
828    #[test]
829    fn test_read_words_basic() {
830        let f = write_tmp("hello world\ngoodbye moon\n");
831        let table = ReadWords
832            .generate(vec![DataValue::String(
833                f.path().to_string_lossy().to_string(),
834            )])
835            .unwrap();
836        // 4 words total
837        assert_eq!(table.row_count(), 4);
838        // Columns: word_num, word, line_num, word_pos
839        // First word
840        assert_eq!(table.get_value(0, 0).unwrap(), &DataValue::Integer(1)); // word_num
841        assert_eq!(
842            table.get_value(0, 1).unwrap(),
843            &DataValue::String("hello".to_string())
844        );
845        assert_eq!(table.get_value(0, 2).unwrap(), &DataValue::Integer(1)); // line_num
846        assert_eq!(table.get_value(0, 3).unwrap(), &DataValue::Integer(1)); // word_pos
847                                                                            // Third word (first on line 2)
848        assert_eq!(table.get_value(2, 0).unwrap(), &DataValue::Integer(3));
849        assert_eq!(
850            table.get_value(2, 1).unwrap(),
851            &DataValue::String("goodbye".to_string())
852        );
853        assert_eq!(table.get_value(2, 2).unwrap(), &DataValue::Integer(2));
854        assert_eq!(table.get_value(2, 3).unwrap(), &DataValue::Integer(1));
855    }
856
857    #[test]
858    fn test_read_words_min_length() {
859        let f = write_tmp("I am a big dog\n");
860        let table = ReadWords
861            .generate(vec![
862                DataValue::String(f.path().to_string_lossy().to_string()),
863                DataValue::Integer(3),
864            ])
865            .unwrap();
866        // Only "big" and "dog" have length >= 3
867        assert_eq!(table.row_count(), 2);
868        assert_eq!(
869            table.get_value(0, 1).unwrap(),
870            &DataValue::String("big".to_string())
871        );
872        assert_eq!(
873            table.get_value(1, 1).unwrap(),
874            &DataValue::String("dog".to_string())
875        );
876    }
877
878    #[test]
879    fn test_read_words_case_lower() {
880        let f = write_tmp("Hello World\n");
881        let table = ReadWords
882            .generate(vec![
883                DataValue::String(f.path().to_string_lossy().to_string()),
884                DataValue::Integer(1),
885                DataValue::String("lower".to_string()),
886            ])
887            .unwrap();
888        assert_eq!(
889            table.get_value(0, 1).unwrap(),
890            &DataValue::String("hello".to_string())
891        );
892        assert_eq!(
893            table.get_value(1, 1).unwrap(),
894            &DataValue::String("world".to_string())
895        );
896    }
897
898    #[test]
899    fn test_read_words_strips_punctuation() {
900        let f = write_tmp("hello, world! foo-bar.\n");
901        let table = ReadWords
902            .generate(vec![DataValue::String(
903                f.path().to_string_lossy().to_string(),
904            )])
905            .unwrap();
906        let words: Vec<String> = (0..table.row_count())
907            .map(|i| match table.get_value(i, 1).unwrap() {
908                DataValue::String(s) => s.clone(),
909                _ => panic!("expected string"),
910            })
911            .collect();
912        assert_eq!(words, vec!["hello", "world", "foo", "bar"]);
913    }
914
915    #[test]
916    fn test_read_words_requires_path() {
917        assert!(ReadWords.generate(vec![]).is_err());
918    }
919
920    #[test]
921    fn test_read_words_empty_lines_skipped() {
922        let f = write_tmp("hello\n\n\nworld\n");
923        let table = ReadWords
924            .generate(vec![DataValue::String(
925                f.path().to_string_lossy().to_string(),
926            )])
927            .unwrap();
928        assert_eq!(table.row_count(), 2);
929        // word_num is contiguous
930        assert_eq!(table.get_value(0, 0).unwrap(), &DataValue::Integer(1));
931        assert_eq!(table.get_value(1, 0).unwrap(), &DataValue::Integer(2));
932        // line_num preserves original positions
933        assert_eq!(table.get_value(0, 2).unwrap(), &DataValue::Integer(1));
934        assert_eq!(table.get_value(1, 2).unwrap(), &DataValue::Integer(4));
935    }
936
937    // ---- ReadJsonl tests ----
938
939    fn col_index(table: &DataTable, name: &str) -> usize {
940        table
941            .columns
942            .iter()
943            .position(|c| c.name == name)
944            .unwrap_or_else(|| panic!("column '{}' not found", name))
945    }
946
947    #[test]
948    fn test_read_jsonl_basic() {
949        let f = write_tmp(
950            r#"{"id":1,"name":"alice","score":10}
951{"id":2,"name":"bob","score":20}
952{"id":3,"name":"carol","score":30}
953"#,
954        );
955        let table = ReadJsonl
956            .generate(vec![DataValue::String(
957                f.path().to_string_lossy().to_string(),
958            )])
959            .unwrap();
960        assert_eq!(table.row_count(), 3);
961        assert_eq!(table.column_count(), 3);
962
963        let id_col = col_index(&table, "id");
964        let name_col = col_index(&table, "name");
965        assert_eq!(table.get_value(0, id_col).unwrap(), &DataValue::Integer(1));
966        assert_eq!(
967            table.get_value(2, name_col).unwrap(),
968            &DataValue::String("carol".to_string())
969        );
970    }
971
972    #[test]
973    fn test_read_jsonl_heterogeneous_schema_unioned() {
974        // Later records introduce fields the first one didn't have. Schema
975        // should union them; missing values become Null.
976        let f = write_tmp(
977            r#"{"id":1,"name":"alice"}
978{"id":2,"name":"bob","extra":"hello"}
979{"id":3,"name":"carol","other":42}
980"#,
981        );
982        let table = ReadJsonl
983            .generate(vec![DataValue::String(
984                f.path().to_string_lossy().to_string(),
985            )])
986            .unwrap();
987        assert_eq!(table.row_count(), 3);
988        assert_eq!(table.column_count(), 4);
989        let extra = col_index(&table, "extra");
990        let other = col_index(&table, "other");
991        // Row 0 has neither extra nor other -> Null
992        assert_eq!(table.get_value(0, extra).unwrap(), &DataValue::Null);
993        assert_eq!(table.get_value(0, other).unwrap(), &DataValue::Null);
994        // Row 1 has extra="hello"
995        assert_eq!(
996            table.get_value(1, extra).unwrap(),
997            &DataValue::String("hello".to_string())
998        );
999        // Row 2 has other=42
1000        assert_eq!(table.get_value(2, other).unwrap(), &DataValue::Integer(42));
1001    }
1002
1003    #[test]
1004    fn test_read_jsonl_blank_lines_skipped() {
1005        let f = write_tmp(
1006            r#"{"id":1}
1007
1008{"id":2}
1009
1010"#,
1011        );
1012        let table = ReadJsonl
1013            .generate(vec![DataValue::String(
1014                f.path().to_string_lossy().to_string(),
1015            )])
1016            .unwrap();
1017        assert_eq!(table.row_count(), 2);
1018    }
1019
1020    #[test]
1021    fn test_read_jsonl_match_regex_pre_filters() {
1022        let f = write_tmp(
1023            r#"{"level":"INFO","msg":"boot"}
1024{"level":"ERROR","msg":"disk"}
1025{"level":"INFO","msg":"shutdown"}
1026{"level":"ERROR","msg":"oom"}
1027"#,
1028        );
1029        let table = ReadJsonl
1030            .generate(vec![
1031                DataValue::String(f.path().to_string_lossy().to_string()),
1032                DataValue::String("ERROR".to_string()),
1033            ])
1034            .unwrap();
1035        assert_eq!(table.row_count(), 2);
1036        let msg = col_index(&table, "msg");
1037        assert_eq!(
1038            table.get_value(0, msg).unwrap(),
1039            &DataValue::String("disk".to_string())
1040        );
1041    }
1042
1043    #[test]
1044    fn test_read_jsonl_invalid_line_errors_with_line_number() {
1045        let f = write_tmp(
1046            r#"{"id":1}
1047not json at all
1048{"id":3}
1049"#,
1050        );
1051        let err = ReadJsonl
1052            .generate(vec![DataValue::String(
1053                f.path().to_string_lossy().to_string(),
1054            )])
1055            .unwrap_err();
1056        let msg = err.to_string();
1057        assert!(
1058            msg.contains("line 2"),
1059            "error should cite line number: {}",
1060            msg
1061        );
1062    }
1063
1064    #[test]
1065    fn test_read_jsonl_requires_path() {
1066        assert!(ReadJsonl.generate(vec![]).is_err());
1067    }
1068
1069    #[test]
1070    fn test_read_jsonl_empty_file_returns_empty_table() {
1071        let f = write_tmp("");
1072        let table = ReadJsonl
1073            .generate(vec![DataValue::String(
1074                f.path().to_string_lossy().to_string(),
1075            )])
1076            .unwrap();
1077        assert_eq!(table.row_count(), 0);
1078    }
1079
1080    // ReadStdin: argument-validation only (stdin is process-global and we cannot
1081    // safely inject test data without refactoring to inject a Reader). The
1082    // happy-path is covered by manual smoke tests in commit messages and the
1083    // examples/ folder.
1084
1085    #[test]
1086    fn test_read_stdin_rejects_too_many_args() {
1087        let err = ReadStdin
1088            .generate(vec![
1089                DataValue::String("foo".to_string()),
1090                DataValue::String("bar".to_string()),
1091            ])
1092            .unwrap_err();
1093        assert!(
1094            err.to_string().contains("0 or 1 arguments"),
1095            "should mention arg count: {}",
1096            err
1097        );
1098    }
1099
1100    #[test]
1101    fn test_read_stdin_rejects_invalid_regex() {
1102        let err = ReadStdin
1103            .generate(vec![DataValue::String("[invalid(regex".to_string())])
1104            .unwrap_err();
1105        assert!(
1106            err.to_string().contains("Invalid match_regex"),
1107            "should mention regex: {}",
1108            err
1109        );
1110    }
1111
1112    // ---- ReadCsv tests ----
1113
1114    /// Helper to write a temp CSV-like file with a given extension and content.
1115    fn write_tmp_with_ext(ext: &str, contents: &str) -> tempfile::NamedTempFile {
1116        let f = tempfile::Builder::new()
1117            .suffix(&format!(".{}", ext))
1118            .tempfile()
1119            .unwrap();
1120        std::fs::write(f.path(), contents).unwrap();
1121        f
1122    }
1123
1124    #[test]
1125    fn test_read_csv_default_comma() {
1126        let f = write_tmp_with_ext("csv", "id,name\n1,alice\n2,bob\n");
1127        let table = ReadCsv
1128            .generate(vec![DataValue::String(
1129                f.path().to_string_lossy().to_string(),
1130            )])
1131            .unwrap();
1132        assert_eq!(table.column_count(), 2);
1133        assert_eq!(table.row_count(), 2);
1134        assert_eq!(table.columns[0].name, "id");
1135        assert_eq!(table.columns[1].name, "name");
1136    }
1137
1138    #[test]
1139    fn test_read_csv_psv_extension_auto_detects_pipe() {
1140        let f = write_tmp_with_ext("psv", "id|name|score\n1|alice|10\n2|bob|20\n");
1141        let table = ReadCsv
1142            .generate(vec![DataValue::String(
1143                f.path().to_string_lossy().to_string(),
1144            )])
1145            .unwrap();
1146        assert_eq!(table.column_count(), 3);
1147        assert_eq!(table.row_count(), 2);
1148        assert_eq!(table.columns[0].name, "id");
1149        assert_eq!(table.columns[2].name, "score");
1150        assert_eq!(
1151            table.metadata.get("delimiter").map(String::as_str),
1152            Some("|")
1153        );
1154    }
1155
1156    #[test]
1157    fn test_read_csv_tsv_extension_auto_detects_tab() {
1158        let f = write_tmp_with_ext("tsv", "id\tname\n1\talice\n2\tbob\n");
1159        let table = ReadCsv
1160            .generate(vec![DataValue::String(
1161                f.path().to_string_lossy().to_string(),
1162            )])
1163            .unwrap();
1164        assert_eq!(table.column_count(), 2);
1165        assert_eq!(table.row_count(), 2);
1166        assert_eq!(
1167            table.metadata.get("delimiter").map(String::as_str),
1168            Some("\\t")
1169        );
1170    }
1171
1172    #[test]
1173    fn test_read_csv_explicit_delimiter_overrides_extension() {
1174        // .psv extension would auto-detect pipe, but explicit comma wins.
1175        // Content is comma-delimited, so if extension auto-detect ran, it
1176        // would parse as a single column.
1177        let f = write_tmp_with_ext("psv", "id,name\n1,alice\n");
1178        let table = ReadCsv
1179            .generate(vec![
1180                DataValue::String(f.path().to_string_lossy().to_string()),
1181                DataValue::String(",".to_string()),
1182            ])
1183            .unwrap();
1184        assert_eq!(table.column_count(), 2);
1185    }
1186
1187    #[test]
1188    fn test_read_csv_explicit_pipe_on_unrecognised_extension() {
1189        let f = write_tmp_with_ext("dat", "a|b\n1|2\n");
1190        let table = ReadCsv
1191            .generate(vec![
1192                DataValue::String(f.path().to_string_lossy().to_string()),
1193                DataValue::String("|".to_string()),
1194            ])
1195            .unwrap();
1196        assert_eq!(table.column_count(), 2);
1197    }
1198
1199    #[test]
1200    fn test_read_csv_backslash_t_parses_as_tab() {
1201        let f = write_tmp_with_ext("dat", "a\tb\n1\t2\n");
1202        let table = ReadCsv
1203            .generate(vec![
1204                DataValue::String(f.path().to_string_lossy().to_string()),
1205                DataValue::String("\\t".to_string()),
1206            ])
1207            .unwrap();
1208        assert_eq!(table.column_count(), 2);
1209        assert_eq!(
1210            table.metadata.get("delimiter").map(String::as_str),
1211            Some("\\t")
1212        );
1213    }
1214
1215    #[test]
1216    fn test_read_csv_rejects_multi_char_delimiter() {
1217        let f = write_tmp_with_ext("dat", "a,b\n1,2\n");
1218        let err = ReadCsv
1219            .generate(vec![
1220                DataValue::String(f.path().to_string_lossy().to_string()),
1221                DataValue::String("||".to_string()),
1222            ])
1223            .unwrap_err();
1224        let msg = err.to_string();
1225        assert!(
1226            msg.contains("single ASCII character"),
1227            "should reject multi-char delimiter: {}",
1228            msg
1229        );
1230    }
1231
1232    #[test]
1233    fn test_read_csv_rejects_too_many_args() {
1234        let err = ReadCsv
1235            .generate(vec![
1236                DataValue::String("a".to_string()),
1237                DataValue::String("b".to_string()),
1238                DataValue::String("c".to_string()),
1239            ])
1240            .unwrap_err();
1241        assert!(err.to_string().contains("1 or 2 arguments"));
1242    }
1243
1244    #[test]
1245    fn test_read_csv_requires_path() {
1246        assert!(ReadCsv.generate(vec![]).is_err());
1247    }
1248
1249    // ---- ReadJson tests ----
1250
1251    #[test]
1252    fn test_read_json_array_of_objects() {
1253        // The case READ_JSONL can't handle: a pretty-printed multi-line array.
1254        let f = write_tmp(
1255            r#"[
1256  {"id": 1, "name": "alice"},
1257  {"id": 2, "name": "bob"}
1258]
1259"#,
1260        );
1261        let table = ReadJson
1262            .generate(vec![DataValue::String(
1263                f.path().to_string_lossy().to_string(),
1264            )])
1265            .unwrap();
1266        assert_eq!(table.row_count(), 2);
1267        assert_eq!(table.column_count(), 2);
1268        let id_col = col_index(&table, "id");
1269        let name_col = col_index(&table, "name");
1270        assert_eq!(table.get_value(0, id_col).unwrap(), &DataValue::Integer(1));
1271        assert_eq!(
1272            table.get_value(1, name_col).unwrap(),
1273            &DataValue::String("bob".to_string())
1274        );
1275    }
1276
1277    #[test]
1278    fn test_read_json_also_accepts_jsonl() {
1279        // Auto-detect: same loader handles one-object-per-line input too.
1280        let f = write_tmp("{\"id\":1}\n{\"id\":2}\n");
1281        let table = ReadJson
1282            .generate(vec![DataValue::String(
1283                f.path().to_string_lossy().to_string(),
1284            )])
1285            .unwrap();
1286        assert_eq!(table.row_count(), 2);
1287        let id_col = col_index(&table, "id");
1288        assert_eq!(table.get_value(1, id_col).unwrap(), &DataValue::Integer(2));
1289    }
1290
1291    #[test]
1292    fn test_read_json_heterogeneous_schema_unioned() {
1293        let f = write_tmp(
1294            r#"[
1295  {"id": 1, "name": "alice"},
1296  {"id": 2, "name": "bob", "extra": "hello"}
1297]"#,
1298        );
1299        let table = ReadJson
1300            .generate(vec![DataValue::String(
1301                f.path().to_string_lossy().to_string(),
1302            )])
1303            .unwrap();
1304        assert_eq!(table.column_count(), 3);
1305        let extra = col_index(&table, "extra");
1306        assert_eq!(table.get_value(0, extra).unwrap(), &DataValue::Null);
1307        assert_eq!(
1308            table.get_value(1, extra).unwrap(),
1309            &DataValue::String("hello".to_string())
1310        );
1311    }
1312
1313    #[test]
1314    fn test_read_json_empty_array_returns_empty_table() {
1315        let f = write_tmp("[]");
1316        let table = ReadJson
1317            .generate(vec![DataValue::String(
1318                f.path().to_string_lossy().to_string(),
1319            )])
1320            .unwrap();
1321        assert_eq!(table.row_count(), 0);
1322    }
1323
1324    #[test]
1325    fn test_read_json_rejects_too_many_args() {
1326        let err = ReadJson
1327            .generate(vec![
1328                DataValue::String("a".to_string()),
1329                DataValue::String("b".to_string()),
1330            ])
1331            .unwrap_err();
1332        assert!(err.to_string().contains("1 argument"));
1333    }
1334
1335    #[test]
1336    fn test_read_json_requires_path() {
1337        assert!(ReadJson.generate(vec![]).is_err());
1338    }
1339
1340    #[test]
1341    fn test_read_json_bad_path_errors() {
1342        let err = ReadJson
1343            .generate(vec![DataValue::String(
1344                "/no/such/file/here.json".to_string(),
1345            )])
1346            .unwrap_err();
1347        assert!(err.to_string().contains("READ_JSON failed to read"));
1348    }
1349}