Skip to main content

shellfirm/wrap/
line.rs

1//! Keystroke → statement model for the PTY proxy.
2//!
3//! The wrapped program (psql, mysql, redis-cli, ...) owns the real line
4//! editor; shellfirm only sees the raw bytes the user types and the bytes the
5//! child echoes back. To decide what the program is about to execute when the
6//! user presses Enter, this module combines:
7//!
8//! * [`LineEditor`] — a model of the line being typed. It applies the common
9//!   readline/linenoise editing keys (Backspace/DEL, Ctrl-U, Ctrl-W, Ctrl-K,
10//!   Ctrl-A/E, Left/Right/Home/End, Delete, bracketed paste). Keys whose effect
11//!   it cannot know (Up/Down history recall, Tab completion, Ctrl-R search,
12//!   yank, Alt-sequences, unknown escape sequences) mark the line *uncertain*.
13//! * [`ScreenLine`] — a small terminal emulator of the child's output
14//!   (several rows, soft wraps, the alternate screen). The text the child
15//!   echoed after the prompt is compared with the model on every Enter; when
16//!   they disagree (history recall, Tab, keys typed into a pager, a prompt
17//!   redrawn after a `\prompt` answer) the echo wins and the model is checked
18//!   as a fallback. Keys typed while the child shows the alternate screen
19//!   (pager, editor) never reach the model. Lines typed at a no-echo prompt
20//!   (password) are dropped and never logged.
21//! * [`split_statements`] (see [`super::lexer`]) / [`Interceptor`] —
22//!   accumulates lines into statements with the client's own lexer rules,
23//!   recognises client meta-commands (`\i`, `source`, `.read`, `load()`,
24//!   `\!`, `delimiter`, `use`, dot-commands) and resyncs the pending buffer
25//!   whenever the child shows its primary prompt.
26//!
27//! Interception happens on **Enter** (CR `0x0D` or LF `0x0A`), the byte that
28//! makes the child act. The Enter byte is held back until the statement has
29//! been checked.
30
31use std::{
32    collections::HashMap,
33    sync::{Arc, Mutex, OnceLock},
34};
35
36use regex::Regex;
37
38pub use super::lexer::{
39    match_prompt, normalize_ws, split_statements, Dialect, MetaCommand, MetaKind, PromptKind,
40    Split, StreamSplitter,
41};
42pub use super::screen::ScreenLine;
43
44// ---------------------------------------------------------------------------
45// LineEditor
46// ---------------------------------------------------------------------------
47
48/// Escape-sequence parsing state for user input.
49#[derive(Debug, Clone, PartialEq, Eq)]
50enum KeyEsc {
51    None,
52    Esc,
53    Csi(Vec<u8>),
54    Ss3,
55}
56
57/// What a single input byte meant to the line editor model.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum KeyEvent {
60    /// The byte edited (or did not affect) the line; forward it unchanged.
61    Edit,
62    /// Enter (CR or LF) — the caller must check the statement before
63    /// forwarding the byte.
64    Enter,
65    /// Ctrl-C — the child discards its input; the model was reset.
66    Interrupt,
67    /// Ctrl-D on an empty line (EOF for most REPLs).
68    Eof,
69}
70
71/// Model of the line currently being edited by the user.
72#[derive(Debug, Clone)]
73#[allow(clippy::struct_excessive_bools)]
74pub struct LineEditor {
75    line: Vec<char>,
76    cursor: usize,
77    uncertain: bool,
78    esc: KeyEsc,
79    utf8: Vec<u8>,
80    in_paste: bool,
81    quoted_insert: bool,
82    touched: bool,
83}
84
85impl Default for LineEditor {
86    fn default() -> Self {
87        Self::new()
88    }
89}
90
91impl LineEditor {
92    #[must_use]
93    pub const fn new() -> Self {
94        Self {
95            line: Vec::new(),
96            cursor: 0,
97            uncertain: false,
98            esc: KeyEsc::None,
99            utf8: Vec::new(),
100            in_paste: false,
101            quoted_insert: false,
102            touched: false,
103        }
104    }
105
106    /// The modelled line text.
107    #[must_use]
108    pub fn text(&self) -> String {
109        self.line.iter().collect()
110    }
111
112    /// True when a key whose effect cannot be modelled was seen on this line
113    /// (history recall, Tab completion, reverse search, ...).
114    #[must_use]
115    pub const fn is_uncertain(&self) -> bool {
116        self.uncertain
117    }
118
119    /// True when no key has been pressed since the last reset.
120    #[must_use]
121    pub const fn is_fresh(&self) -> bool {
122        !self.touched
123    }
124
125    /// Reset to an empty, certain line.
126    pub fn clear(&mut self) {
127        *self = Self::new();
128    }
129
130    fn insert(&mut self, c: char) {
131        self.line.insert(self.cursor, c);
132        self.cursor += 1;
133    }
134
135    fn backspace(&mut self) {
136        if self.cursor > 0 {
137            self.cursor -= 1;
138            self.line.remove(self.cursor);
139        }
140    }
141
142    fn delete_at_cursor(&mut self) {
143        if self.cursor < self.line.len() {
144            self.line.remove(self.cursor);
145        }
146    }
147
148    fn kill_word_back(&mut self) {
149        // readline `unix-word-rubout`: whitespace, then non-whitespace.
150        while self.cursor > 0 && self.line[self.cursor - 1].is_whitespace() {
151            self.backspace();
152        }
153        while self.cursor > 0 && !self.line[self.cursor - 1].is_whitespace() {
154            self.backspace();
155        }
156    }
157
158    fn push_utf8(&mut self, byte: u8) {
159        self.utf8.push(byte);
160        match std::str::from_utf8(&self.utf8) {
161            Ok(s) => {
162                let chars: Vec<char> = s.chars().collect();
163                self.utf8.clear();
164                for c in chars {
165                    self.insert(c);
166                }
167            }
168            Err(e) if e.error_len().is_some() || self.utf8.len() >= 4 => {
169                self.utf8.clear();
170                self.insert(char::REPLACEMENT_CHARACTER);
171            }
172            Err(_) => {} // incomplete multi-byte sequence — wait for more
173        }
174    }
175
176    fn handle_csi(&mut self, params: &[u8], final_byte: u8) {
177        match (params, final_byte) {
178            (b"" | b"1", b'C') => self.cursor = (self.cursor + 1).min(self.line.len()),
179            (b"" | b"1", b'D') => self.cursor = self.cursor.saturating_sub(1),
180            (b"", b'H') | (b"1" | b"7", b'~') => self.cursor = 0,
181            (b"", b'F') | (b"4" | b"8", b'~') => self.cursor = self.line.len(),
182            (b"3", b'~') => self.delete_at_cursor(),
183            (b"200", b'~') => self.in_paste = true,
184            (b"201", b'~') => self.in_paste = false,
185            (b"2", b'~') => {} // Insert key: overwrite toggle is rare; ignore
186            // Up/Down (history), modified arrows (word moves), F-keys, ...
187            _ => self.uncertain = true,
188        }
189    }
190
191    /// Feed one input byte from the user's terminal.
192    pub fn feed(&mut self, byte: u8) -> KeyEvent {
193        self.touched = true;
194
195        if self.quoted_insert {
196            self.quoted_insert = false;
197            self.insert(char::from(byte));
198            return KeyEvent::Edit;
199        }
200
201        match std::mem::replace(&mut self.esc, KeyEsc::None) {
202            KeyEsc::None => {}
203            KeyEsc::Esc => {
204                match byte {
205                    b'[' => self.esc = KeyEsc::Csi(Vec::new()),
206                    b'O' => self.esc = KeyEsc::Ss3,
207                    0x1B => {
208                        self.uncertain = true;
209                        self.esc = KeyEsc::Esc;
210                    }
211                    // Alt-<key> (word moves, case changes, yank-pop, ...)
212                    _ => self.uncertain = true,
213                }
214                return KeyEvent::Edit;
215            }
216            KeyEsc::Csi(mut params) => {
217                if (0x40..=0x7E).contains(&byte) {
218                    self.handle_csi(&params, byte);
219                } else if params.len() < 32 {
220                    params.push(byte);
221                    self.esc = KeyEsc::Csi(params);
222                } else {
223                    self.uncertain = true;
224                }
225                return KeyEvent::Edit;
226            }
227            KeyEsc::Ss3 => {
228                match byte {
229                    b'C' => self.handle_csi(b"", b'C'),
230                    b'D' => self.handle_csi(b"", b'D'),
231                    b'H' => self.handle_csi(b"", b'H'),
232                    b'F' => self.handle_csi(b"", b'F'),
233                    _ => self.uncertain = true,
234                }
235                return KeyEvent::Edit;
236            }
237        }
238
239        if self.in_paste {
240            match byte {
241                0x1B => self.esc = KeyEsc::Esc,
242                b'\r' | b'\n' => self.insert('\n'),
243                b'\t' => self.insert('\t'),
244                0x00..=0x1F | 0x7F => {}
245                _ => self.push_utf8(byte),
246            }
247            return KeyEvent::Edit;
248        }
249
250        match byte {
251            b'\r' | b'\n' => return KeyEvent::Enter,
252            0x03 => {
253                self.clear();
254                return KeyEvent::Interrupt;
255            }
256            0x04 => {
257                if self.line.is_empty() {
258                    return KeyEvent::Eof;
259                }
260                self.delete_at_cursor();
261            }
262            0x01 => self.cursor = 0,
263            0x05 => self.cursor = self.line.len(),
264            0x02 => self.cursor = self.cursor.saturating_sub(1),
265            0x06 => self.cursor = (self.cursor + 1).min(self.line.len()),
266            0x08 | 0x7F => self.backspace(),
267            0x0B => self.line.truncate(self.cursor),
268            0x15 => {
269                self.line.drain(..self.cursor);
270                self.cursor = 0;
271            }
272            0x17 => self.kill_word_back(),
273            0x16 => self.quoted_insert = true,
274            0x1B => self.esc = KeyEsc::Esc,
275            0x0C | 0x1A | 0x00 => {} // Ctrl-L redraw, Ctrl-Z suspend, NUL
276            // Tab (completion), Ctrl-N/P (history), Ctrl-R/S (search),
277            // Ctrl-T (transpose), Ctrl-Y (yank), Ctrl-X prefix, Ctrl-_ (undo),
278            // and any other control byte.
279            _ if byte < 0x20 => self.uncertain = true,
280            _ => self.push_utf8(byte),
281        }
282        KeyEvent::Edit
283    }
284}
285
286// ---------------------------------------------------------------------------
287// Statement modes
288// ---------------------------------------------------------------------------
289
290/// How the wrapped program groups lines into statements.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum StatementMode {
293    /// Every line is a statement (redis-cli, shells, generic programs).
294    Line,
295    /// Statements end at a delimiter (SQL `;`).
296    Delimited {
297        delimiter: char,
298        /// The client lexer rules (quotes, comments, meta-commands).
299        dialect: Dialect,
300        /// The program executes a bracket-balanced line on Enter even without
301        /// the delimiter (mongosh / JavaScript shells).
302        enter_completes: bool,
303    },
304}
305
306/// Terminal mode of the child's side of the PTY at the moment Enter was
307/// pressed (only known for local programs).
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub struct TtyState {
310    /// Kernel echo is on.
311    pub echo: bool,
312    /// Canonical (cooked) line input.
313    pub icanon: bool,
314}
315
316impl TtyState {
317    /// Echo off but cooked input: a password / secret prompt (`getpass`).
318    #[must_use]
319    pub const fn is_secret_prompt(self) -> bool {
320        !self.echo && self.icanon
321    }
322}
323
324/// What must be checked before the held Enter byte is forwarded.
325#[derive(Debug, Clone, Default, PartialEq, Eq)]
326pub struct Submission {
327    /// Statements the program will execute on this Enter.
328    pub statements: Vec<String>,
329    /// Other readings of the line (the keystroke model when it disagrees
330    /// with the child's echo, the line without a suspicious pending buffer,
331    /// ...), checked when nothing above matched.
332    pub fallbacks: Vec<String>,
333    /// Text that was typed but never echoed by the child (could be a
334    /// secret). Checked like fallbacks, never logged verbatim.
335    pub unconfirmed: Vec<String>,
336    /// Client meta-commands that run files, shell commands or unseen SQL.
337    pub metas: Vec<MetaCommand>,
338    /// Whether the line text came from the child's echo.
339    pub from_echo: bool,
340    /// The line was typed at a no-echo prompt (password) and dropped.
341    pub secret: bool,
342    /// How many statements / client commands the line sends (each once;
343    /// the extra readings above are not counted).
344    pub count: usize,
345    /// The line makes the client open a new connection (psql `\c`, mysql
346    /// `connect` / `\r`, sqlcmd `:connect`): its temporary tables are gone.
347    pub reconnect: bool,
348}
349
350impl Submission {
351    #[must_use]
352    pub const fn is_empty(&self) -> bool {
353        self.statements.is_empty()
354            && self.fallbacks.is_empty()
355            && self.unconfirmed.is_empty()
356            && self.metas.is_empty()
357    }
358
359    /// A log-safe summary (unconfirmed input is redacted).
360    #[must_use]
361    pub fn log_summary(&self) -> String {
362        format!(
363            "statements={:?} fallbacks={:?} unconfirmed=[{}] metas={:?} from_echo={} secret={}",
364            self.statements,
365            self.fallbacks,
366            self.unconfirmed
367                .iter()
368                .map(|u| format!("<{} chars>", u.chars().count()))
369                .collect::<Vec<_>>()
370                .join(", "),
371            self.metas
372                .iter()
373                .map(|m| m.raw.as_str())
374                .collect::<Vec<_>>(),
375            self.from_echo,
376            self.secret
377        )
378    }
379}
380
381/// Screen facts needed for one keystroke.
382struct KeyView {
383    alt: bool,
384    alt_epoch: u64,
385    cursor: (u64, usize),
386    before_cursor: String,
387    anchor_row: Option<String>,
388}
389
390/// Where the user started typing the current line.
391#[derive(Debug, Clone)]
392struct Anchor {
393    row: u64,
394    col: usize,
395    prompt: String,
396    alt_epoch: u64,
397}
398
399/// mysql commands that run without a delimiter at the start of a line.
400const MYSQL_LINE_COMMANDS: &[&str] = &[
401    "use",
402    "connect",
403    "status",
404    "charset",
405    "warnings",
406    "nowarning",
407    "rehash",
408    "tee",
409    "notee",
410    "pager",
411    "nopager",
412    "prompt",
413    "quit",
414    "exit",
415    "help",
416    "clear",
417    "ego",
418    "go",
419    "print",
420    "edit",
421    "source",
422    "system",
423    "delimiter",
424    "resetconnection",
425    "query_attributes",
426    "ssl_session_data_print",
427];
428
429fn var_ref_re() -> &'static Regex {
430    static RE: OnceLock<Regex> = OnceLock::new();
431    RE.get_or_init(|| Regex::new(r#"(^|[^:]):(['"]?)([A-Za-z_][A-Za-z0-9_]*)(['"]?)"#).unwrap())
432}
433
434/// Arguments of a sqlite3 dot-command (`'...'` / `"..."` quoting).
435fn sqlite_args(arg: &str) -> Vec<String> {
436    let mut out = Vec::new();
437    let mut chars = arg.trim().chars().peekable();
438    while let Some(&c) = chars.peek() {
439        if c.is_whitespace() {
440            chars.next();
441            continue;
442        }
443        let mut word = String::new();
444        if c == '\'' || c == '"' {
445            chars.next();
446            for d in chars.by_ref() {
447                if d == c {
448                    break;
449                }
450                word.push(d);
451            }
452        } else {
453            while let Some(&d) = chars.peek() {
454                if d.is_whitespace() {
455                    break;
456                }
457                word.push(d);
458                chars.next();
459            }
460        }
461        out.push(word);
462    }
463    out
464}
465
466/// The shell command of an unquoted pipe argument of a sqlite3 dot-command:
467/// `.once |rm -rf x`, `.output |gzip > f`, `.read |cmd`, `.import |cmd t`.
468/// Option words (`-x`, `--csv`) before it are skipped. The command is the
469/// rest of the line (without the table name for `.import`, the last word).
470/// `None` when the first non-option argument is not an unquoted `|...`.
471fn unquoted_pipe(arg: &str, last_is_table: bool) -> Option<String> {
472    let mut rest = arg.trim_start();
473    while rest.starts_with('-') {
474        let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
475        rest = rest[end..].trim_start();
476    }
477    let cmd = rest.strip_prefix('|')?.trim();
478    let cmd = if last_is_table {
479        cmd.rsplit_once(char::is_whitespace)
480            .map_or(cmd, |(c, _)| c.trim_end())
481    } else {
482        cmd
483    };
484    (!cmd.is_empty()).then(|| cmd.to_string())
485}
486
487fn mongo_load_re() -> &'static Regex {
488    static RE: OnceLock<Regex> = OnceLock::new();
489    RE.get_or_init(|| Regex::new(r#"\bload\s*\(\s*(['"`])(.+?)['"`]\s*\)"#).unwrap())
490}
491
492/// A psql variable as the target of `TRUNCATE`, `DROP <object>` or `DELETE
493/// FROM` (`TRUNCATE :"t"`, `DROP TABLE IF EXISTS public.:t`); group 1 is
494/// the variable name.
495fn var_target_re() -> &'static Regex {
496    static RE: OnceLock<Regex> = OnceLock::new();
497    RE.get_or_init(|| {
498        Regex::new(
499            r#"(?i)^\s*(?:TRUNCATE(?:\s+TABLE)?(?:\s+ONLY)?|DROP\s+(?:MATERIALIZED\s+VIEW|FOREIGN\s+TABLE|[A-Z]+)(?:\s+IF\s+EXISTS)?|DELETE\s+FROM(?:\s+ONLY)?)\s+(?:[\w."]+\s*,\s*)*[\w."]*:['"]?([A-Za-z_][A-Za-z0-9_]*)"#,
500        )
501        .unwrap()
502    })
503}
504
505/// A sqlcmd line that is a client command, not T-SQL. sqlcmd reads its
506/// commands at the start of a line, whatever the batch holds.
507#[derive(Debug, Clone, PartialEq, Eq)]
508enum SqlCmdLine {
509    /// `GO [count]`: the batch so far runs.
510    Go,
511    /// `:exit(query)`: the batch runs, then `query`.
512    Exit(String),
513    /// `:reset`: the batch is discarded.
514    Reset,
515    /// Any other command: what it runs (`!!cmd`, `:!! cmd`, `:r file`,
516    /// `:ed`) and whether it opens a new connection (`:connect`).
517    Command {
518        meta: Option<MetaCommand>,
519        reconnect: bool,
520    },
521}
522
523fn sqlcmd_go_re() -> &'static Regex {
524    static RE: OnceLock<Regex> = OnceLock::new();
525    RE.get_or_init(|| Regex::new(r"(?i)^go(?:\s+\d+)?\s*;?$").unwrap())
526}
527
528/// sqlcmd commands that run nothing a check could see (`:setvar`, `:out`,
529/// `:on error`, ...).
530const SQLCMD_COMMANDS: &[&str] = &[
531    "setvar",
532    "listvar",
533    "out",
534    "error",
535    "perftrace",
536    "on",
537    "help",
538    "serverlist",
539    "list",
540    "xml",
541    "quit",
542];
543
544/// Read `line` as a sqlcmd command (`None`: it is T-SQL). The commands are
545/// case-insensitive; `!!` and `:!!` run an operating-system command, `:r`
546/// reads a file into the batch.
547fn sqlcmd_line(line: &str) -> Option<SqlCmdLine> {
548    let t = line.trim();
549    if sqlcmd_go_re().is_match(t) {
550        return Some(SqlCmdLine::Go);
551    }
552    let shell = |cmd: &str| {
553        let cmd = cmd.trim();
554        SqlCmdLine::Command {
555            meta: (!cmd.is_empty()).then(|| super::lexer::shell_meta(t.to_string(), cmd)),
556            reconnect: false,
557        }
558    };
559    if let Some(cmd) = t.strip_prefix("!!") {
560        return Some(shell(cmd));
561    }
562    let rest = t.strip_prefix(':')?;
563    if let Some(cmd) = rest.trim_start().strip_prefix("!!") {
564        return Some(shell(cmd));
565    }
566    let word_end = rest
567        .find(|c: char| !c.is_ascii_alphabetic())
568        .unwrap_or(rest.len());
569    let word = rest[..word_end].to_ascii_lowercase();
570    let arg = rest[word_end..].trim();
571    let command =
572        |meta: Option<MetaCommand>, reconnect: bool| Some(SqlCmdLine::Command { meta, reconnect });
573    match word.as_str() {
574        "r" => command(
575            Some(MetaCommand {
576                raw: t.to_string(),
577                kind: MetaKind::RunFile {
578                    path: super::lexer::unquote_arg(arg),
579                    relative: false,
580                },
581            }),
582            false,
583        ),
584        "ed" => command(Some(super::lexer::editor_meta(t.to_string())), false),
585        "connect" => command(None, true),
586        "reset" => Some(SqlCmdLine::Reset),
587        "exit" => {
588            let query = arg
589                .strip_prefix('(')
590                .and_then(|a| a.strip_suffix(')'))
591                .map(str::trim)
592                .unwrap_or_default();
593            Some(SqlCmdLine::Exit(query.to_string()))
594        }
595        w if SQLCMD_COMMANDS.contains(&w) => command(None, false),
596        _ => None,
597    }
598}
599
600/// Stateful keystroke interceptor for one wrap session.
601#[derive(Debug)]
602pub struct Interceptor {
603    editor: LineEditor,
604    pending: String,
605    mode: StatementMode,
606    delimiter: String,
607    screen: Arc<Mutex<ScreenLine>>,
608    anchor: Option<Anchor>,
609    last_prompt: Option<String>,
610    /// The anchor prompt went stale (the child redrew a new prompt): the
611    /// keystroke model may contain keys that never reached the line editor.
612    stale: bool,
613    vars: HashMap<String, String>,
614    /// A line typed but not echoed, kept for one more fallback check.
615    shadow: Option<String>,
616    tty: Option<TtyState>,
617    /// The child reads statements in non-canonical mode (has a line
618    /// editor), so a cooked-mode line is a side prompt (`\prompt`, ...).
619    has_line_editor: bool,
620    /// At least one line was confirmed by the child's echo.
621    echo_seen: bool,
622}
623
624impl Interceptor {
625    #[must_use]
626    pub fn new(mode: StatementMode) -> Self {
627        let delimiter = match mode {
628            StatementMode::Delimited { delimiter, .. } => delimiter.to_string(),
629            StatementMode::Line => "\n".to_string(),
630        };
631        Self {
632            editor: LineEditor::new(),
633            pending: String::new(),
634            mode,
635            delimiter,
636            screen: Arc::new(Mutex::new(ScreenLine::new())),
637            anchor: None,
638            last_prompt: None,
639            stale: false,
640            vars: HashMap::new(),
641            shadow: None,
642            tty: None,
643            has_line_editor: false,
644            echo_seen: false,
645        }
646    }
647
648    const fn dialect(&self) -> Option<Dialect> {
649        match self.mode {
650            StatementMode::Delimited { dialect, .. } => Some(dialect),
651            StatementMode::Line => None,
652        }
653    }
654
655    /// Shared handle to the echo tracker (for backends that read child
656    /// output on another thread).
657    #[must_use]
658    pub fn screen_handle(&self) -> Arc<Mutex<ScreenLine>> {
659        Arc::clone(&self.screen)
660    }
661
662    /// Feed child output to the echo tracker.
663    pub fn on_child_output(&self, bytes: &[u8]) {
664        if let Ok(mut s) = self.screen.lock() {
665            s.feed(bytes);
666        }
667    }
668
669    /// Tell the echo tracker the terminal size.
670    pub fn set_size(&self, cols: usize, rows: usize) {
671        if let Ok(mut s) = self.screen.lock() {
672            s.set_size(cols, rows);
673        }
674    }
675
676    /// Record the child's terminal mode (call before [`Self::take_submission`]).
677    pub const fn set_tty_state(&mut self, tty: Option<TtyState>) {
678        self.tty = tty;
679    }
680
681    /// Statement text accumulated from previous lines (not yet complete).
682    #[must_use]
683    pub fn pending(&self) -> &str {
684        &self.pending
685    }
686
687    /// The current statement delimiter (mysql `DELIMITER` changes it).
688    #[must_use]
689    pub fn delimiter(&self) -> &str {
690        &self.delimiter
691    }
692
693    /// The editor model (for diagnostics/tests).
694    #[must_use]
695    pub const fn editor(&self) -> &LineEditor {
696        &self.editor
697    }
698
699    /// The line needs the child's echo (history, Tab, a stale prompt).
700    #[must_use]
701    pub const fn needs_echo(&self) -> bool {
702        self.editor.is_uncertain() || self.stale
703    }
704
705    fn classify(&self, prompt: &str) -> Option<PromptKind> {
706        self.dialect()
707            .and_then(|d| match_prompt(d, prompt))
708            .filter(|(_, len)| *len == prompt.chars().count())
709            .map(|(k, _)| k)
710    }
711
712    fn reset_line(&mut self) {
713        self.editor.clear();
714        self.anchor = None;
715        self.stale = false;
716    }
717
718    /// Capture where typing starts; resync the pending buffer when the
719    /// child shows its primary prompt (its own buffer is empty then).
720    fn capture_anchor(&mut self, view: &KeyView) {
721        let prompt = view.before_cursor.clone();
722        if !self.pending.trim().is_empty() && self.classify(&prompt) == Some(PromptKind::Primary) {
723            tracing::debug!(
724                "[wrap] resync: the child shows its primary prompt; dropping {} pending char(s)",
725                self.pending.chars().count()
726            );
727            self.pending.clear();
728            self.shadow = None;
729        }
730        self.anchor = Some(Anchor {
731            row: view.cursor.0,
732            col: view.cursor.1,
733            prompt,
734            alt_epoch: view.alt_epoch,
735        });
736    }
737
738    fn key_view(&self) -> Option<KeyView> {
739        let s = self.screen.lock().ok()?;
740        Some(KeyView {
741            alt: s.in_alt_screen(),
742            alt_epoch: s.alt_epoch(),
743            cursor: s.cursor(),
744            before_cursor: s.text_before_cursor(),
745            anchor_row: self.anchor.as_ref().and_then(|a| s.row_text(a.row)),
746        })
747    }
748
749    /// Feed one byte typed by the user.
750    pub fn feed_key(&mut self, byte: u8) -> KeyEvent {
751        let Some(view) = self.key_view() else {
752            return self.editor.feed(byte);
753        };
754        if view.alt {
755            // A pager or editor owns the keyboard: nothing typed here reaches
756            // the client's line editor.
757            self.reset_line();
758            return KeyEvent::Edit;
759        }
760        if let Some(a) = &self.anchor {
761            if a.alt_epoch != view.alt_epoch {
762                // A pager/editor ran since the line started.
763                self.reset_line();
764            } else if !self.editor.is_fresh() {
765                let at_anchor = view
766                    .anchor_row
767                    .as_deref()
768                    .is_some_and(|t| t.starts_with(a.prompt.trim_end()));
769                let cursor_prompt = self.dialect().and_then(|d| {
770                    match_prompt(d, &view.before_cursor)
771                        .filter(|(_, len)| *len == view.before_cursor.chars().count())
772                });
773                if !at_anchor && cursor_prompt.is_some() {
774                    // The child drew a fresh prompt after keys were typed
775                    // (pager `q`, `\prompt` answer): those keys are gone.
776                    tracing::debug!("[wrap] resync: fresh prompt after typed keys");
777                    self.reset_line();
778                    self.stale = true;
779                }
780            }
781        }
782        if self.editor.is_fresh() && self.anchor.is_none() && !matches!(byte, b'\r' | b'\n') {
783            self.capture_anchor(&view);
784        }
785        let ev = self.editor.feed(byte);
786        if ev == KeyEvent::Interrupt {
787            self.pending.clear();
788            self.shadow = None;
789            self.anchor = None;
790            self.stale = false;
791        }
792        ev
793    }
794
795    /// The text the child echoed for the current line, and whether the
796    /// anchor prompt went stale.
797    #[allow(clippy::significant_drop_tightening)]
798    fn echoed_line(&self) -> Option<(String, bool)> {
799        let screen = self.screen.lock().ok()?;
800        let anchor = self.anchor.as_ref()?;
801        let prompt = anchor.prompt.trim_end();
802        let fix = |s: String| s.replace("^J", "\n").replace("^M", "\n");
803        if prompt.is_empty() {
804            return Some((fix(screen.text_from(anchor.row, anchor.col)), false));
805        }
806        // The latest row (since the anchor) that starts with the prompt:
807        // Tab listings and Ctrl-L redraw the prompt further down.
808        let first = screen.first_row();
809        let last = screen.last_row();
810        let plen = anchor.prompt.chars().count();
811        let mut r = last;
812        loop {
813            if let Some(t) = screen.row_text(r) {
814                if t.starts_with(prompt) && (r >= anchor.row || r + 50 >= last) {
815                    return Some((fix(screen.text_from(r, plen)), false));
816                }
817            }
818            if r == first || r + 60 < last {
819                break;
820            }
821            r -= 1;
822        }
823        // Stale anchor: look for any prompt the client is known to draw.
824        let d = self.dialect()?;
825        let mut r = last;
826        loop {
827            if let Some(t) = screen.row_text(r) {
828                if let Some((_, len)) = match_prompt(d, &format!("{t} ")) {
829                    return Some((fix(screen.text_from(r, len)), true));
830                }
831            }
832            if r == first || r + 20 < last {
833                break;
834            }
835            r -= 1;
836        }
837        None
838    }
839
840    /// True when the echo already shows the modelled line (no need to wait
841    /// for more child output).
842    #[must_use]
843    pub fn echo_confirms_model(&self) -> bool {
844        let model: String = self.editor.text().split_whitespace().collect();
845        if model.is_empty() {
846            return true;
847        }
848        self.echoed_line().is_some_and(|(e, stale)| {
849            let e: String = e.split_whitespace().collect();
850            !stale && e.contains(&model)
851        })
852    }
853
854    /// Decide what the line is: (`text`, `fallback`, `from_echo`, `unechoed`).
855    fn choose_line(&mut self) -> (String, Option<String>, bool, bool) {
856        let modelled = self.editor.text();
857        let m: String = modelled.split_whitespace().collect();
858        let uncertain = self.editor.is_uncertain();
859        match self.echoed_line() {
860            Some((echo, anchor_stale)) if !echo.trim().is_empty() => {
861                let e: String = echo.split_whitespace().collect();
862                let stale = anchor_stale || self.stale;
863                if e == m {
864                    self.echo_seen = true;
865                    (modelled, None, false, false)
866                } else if !uncertain && !stale && (e.contains(&m) || m.starts_with(&e)) {
867                    // Echo has extra decoration, or is still arriving.
868                    self.echo_seen |= e.contains(&m);
869                    (modelled, None, false, false)
870                } else {
871                    let fallback = (!m.is_empty()).then(|| normalize_ws(&modelled));
872                    (echo, fallback, true, false)
873                }
874            }
875            _ if m.is_empty() => (modelled, None, false, false),
876            // Typed but not echoed: a no-echo prompt, or a slow link.
877            _ => (modelled, None, false, self.echo_seen && !uncertain),
878        }
879    }
880
881    /// Called when Enter was pressed (and child output drained). Consumes the
882    /// current line and returns what must be checked.
883    pub fn take_submission(&mut self) -> Submission {
884        let mut sub = Submission::default();
885        if let Some(tty) = self.tty {
886            if tty.is_secret_prompt() {
887                // Password prompt: never checked, kept or logged.
888                self.reset_line();
889                sub.secret = true;
890                return sub;
891            }
892        }
893        let side_prompt = self.tty.is_some_and(|t| t.icanon) && self.has_line_editor;
894        if self.tty.is_some_and(|t| !t.icanon) {
895            self.has_line_editor = true;
896        }
897
898        let (line, fallback, from_echo, unechoed) = self.choose_line();
899        sub.from_echo = from_echo;
900        sub.fallbacks.extend(fallback);
901        self.last_prompt = self.anchor.take().map(|a| a.prompt);
902        self.editor.clear();
903        self.stale = false;
904        let shadow = self.shadow.take();
905
906        match self.mode {
907            StatementMode::Line => {
908                let stmts: Vec<String> = line
909                    .lines()
910                    .map(normalize_ws)
911                    .filter(|l| !l.is_empty())
912                    .collect();
913                sub.count = stmts.len();
914                if unechoed {
915                    sub.unconfirmed = stmts;
916                } else {
917                    sub.statements = stmts;
918                }
919            }
920            StatementMode::Delimited {
921                dialect,
922                enter_completes,
923                ..
924            } => {
925                if unechoed || side_prompt {
926                    // Not (provably) part of the query buffer: check it on
927                    // its own, keep the buffer as it is.
928                    let alone = self.split_alone(&line, dialect, enter_completes);
929                    sub.count = alone.statements.len() + alone.metas.len();
930                    if unechoed {
931                        self.shadow = Some(line.clone());
932                        sub.unconfirmed = alone.statements;
933                    } else {
934                        sub.fallbacks.extend(alone.statements);
935                    }
936                    sub.metas = alone.metas;
937                    return sub;
938                }
939                self.delimited(&line, dialect, enter_completes, true, &mut sub);
940                if let Some(prev) = shadow {
941                    let joined = format!("{prev}\n{line}");
942                    let alone = self.split_alone(&joined, dialect, enter_completes);
943                    sub.unconfirmed.extend(alone.statements);
944                }
945            }
946        }
947        sub
948    }
949
950    fn split_alone(&self, text: &str, dialect: Dialect, enter_completes: bool) -> Split {
951        let mut split = split_statements(text, &self.delimiter, dialect);
952        let rest = normalize_ws(&split.remainder);
953        if !rest.is_empty() && (enter_completes || !split.in_literal) {
954            split.statements.push(rest);
955        }
956        split
957    }
958
959    /// Client commands that are complete at the start of a line without a
960    /// delimiter (mysql `use db`, sqlite3 `.tables`). Returns true when the
961    /// line was such a command.
962    fn line_command(&mut self, line: &str, dialect: Dialect, sub: &mut Submission) -> bool {
963        let t = line.trim();
964        match dialect {
965            Dialect::MySql => {
966                let word = t
967                    .split_whitespace()
968                    .next()
969                    .unwrap_or("")
970                    .to_ascii_lowercase();
971                if !MYSQL_LINE_COMMANDS.contains(&word.as_str()) {
972                    return false;
973                }
974                let raw_arg = t[word.len()..].trim();
975                let arg = raw_arg
976                    .trim_end_matches(self.delimiter.as_str())
977                    .trim_end_matches(';')
978                    .trim();
979                let raw = t.to_string();
980                match word.as_str() {
981                    "delimiter" => {
982                        if let Some(d) = raw_arg.split_whitespace().next() {
983                            self.delimiter = d.to_string();
984                        }
985                    }
986                    "connect" => sub.reconnect = true,
987                    "source" => sub.metas.push(MetaCommand {
988                        raw,
989                        kind: MetaKind::RunFile {
990                            path: arg.to_string(),
991                            relative: false,
992                        },
993                    }),
994                    "system" => sub.metas.push(MetaCommand {
995                        raw,
996                        kind: MetaKind::Shell {
997                            command: arg.to_string(),
998                        },
999                    }),
1000                    "edit" => sub.metas.push(MetaCommand {
1001                        raw,
1002                        kind: MetaKind::Opaque {
1003                            id: "wrap:editor",
1004                            what: "This opens the query buffer in an editor; whatever you \
1005                                   write there runs without being checked."
1006                                .into(),
1007                        },
1008                    }),
1009                    _ => {}
1010                }
1011                true
1012            }
1013            Dialect::Sqlite if t.starts_with('.') => {
1014                let mut parts = t.splitn(2, char::is_whitespace);
1015                let cmd = parts.next().unwrap_or("");
1016                let arg = parts.next().unwrap_or("").trim();
1017                let raw = t.to_string();
1018                match cmd {
1019                    ".read" => {
1020                        let file = unquoted_pipe(arg, false).map_or_else(
1021                            || sqlite_args(arg).into_iter().next().unwrap_or_default(),
1022                            |c| format!("|{c}"),
1023                        );
1024                        let kind = file.strip_prefix('|').map_or_else(
1025                            || MetaKind::RunFile {
1026                                path: file.clone(),
1027                                relative: false,
1028                            },
1029                            |c| MetaKind::ShellToSql {
1030                                command: c.trim().to_string(),
1031                            },
1032                        );
1033                        sub.metas.push(MetaCommand { raw, kind });
1034                    }
1035                    ".once" | ".output" | ".import" => {
1036                        // `.once '|cmd'`, `.output '|cmd'` (query output is
1037                        // piped to a shell command), `.import '|cmd' table`
1038                        // (the command's output is imported).
1039                        // An unquoted `|cmd args...` runs the rest of the
1040                        // line (sqlite3 3.34+ joins the arguments).
1041                        let pipe = unquoted_pipe(arg, cmd == ".import").or_else(|| {
1042                            sqlite_args(arg)
1043                                .into_iter()
1044                                .filter(|a| !a.starts_with('-'))
1045                                .find_map(|a| a.strip_prefix('|').map(|c| c.trim().to_string()))
1046                        });
1047                        if let Some(command) = pipe.filter(|c| !c.is_empty()) {
1048                            sub.metas.push(MetaCommand {
1049                                raw,
1050                                kind: MetaKind::Shell { command },
1051                            });
1052                        }
1053                    }
1054                    ".shell" | ".system" if arg.is_empty() => {}
1055                    ".shell" | ".system" => sub.metas.push(MetaCommand {
1056                        raw,
1057                        kind: MetaKind::Shell {
1058                            command: arg.to_string(),
1059                        },
1060                    }),
1061                    _ => {}
1062                }
1063                true
1064            }
1065            _ => false,
1066        }
1067    }
1068
1069    /// Apply a sqlcmd command line (see [`sqlcmd_line`]) typed in a
1070    /// session: `GO` ends the batch, `!!` / `:r` / `:ed` are client
1071    /// commands checked on their own.
1072    fn sqlcmd_command(&mut self, cmd: SqlCmdLine, enter_completes: bool, sub: &mut Submission) {
1073        match cmd {
1074            SqlCmdLine::Go => self.end_sqlcmd_batch(enter_completes, sub),
1075            SqlCmdLine::Exit(query) => {
1076                self.end_sqlcmd_batch(enter_completes, sub);
1077                if !query.is_empty() {
1078                    let delimiter = self.delimiter.clone();
1079                    self.delimited(
1080                        &format!("{query}{delimiter}"),
1081                        Dialect::SqlServer,
1082                        enter_completes,
1083                        false,
1084                        sub,
1085                    );
1086                }
1087            }
1088            SqlCmdLine::Reset => self.pending.clear(),
1089            SqlCmdLine::Command { meta, reconnect } => {
1090                sub.reconnect |= reconnect;
1091                sub.metas.extend(meta);
1092                sub.count += 1;
1093            }
1094        }
1095    }
1096
1097    /// sqlcmd `GO`: what is pending in the batch runs now, with or without
1098    /// a `;`.
1099    fn end_sqlcmd_batch(&mut self, enter_completes: bool, sub: &mut Submission) {
1100        if !self.pending.trim().is_empty() {
1101            let delimiter = self.delimiter.clone();
1102            self.delimited(&delimiter, Dialect::SqlServer, enter_completes, false, sub);
1103        }
1104    }
1105
1106    /// Substitute psql `:var`, `:'var'`, `:"var"` references.
1107    fn substitute_vars(&self, stmt: &str) -> (String, Vec<String>) {
1108        let mut unknown = Vec::new();
1109        let out = var_ref_re()
1110            .replace_all(stmt, |c: &regex::Captures<'_>| {
1111                let name = &c[3];
1112                let (open, close) = (&c[2], &c[4]);
1113                if open != close {
1114                    return c[0].to_string();
1115                }
1116                self.vars.get(name).map_or_else(
1117                    || {
1118                        unknown.push(name.to_string());
1119                        c[0].to_string()
1120                    },
1121                    |v| match open {
1122                        "'" => format!("{}'{v}'", &c[1]),
1123                        "\"" => format!("{}\"{v}\"", &c[1]),
1124                        _ => format!("{}{v}", &c[1]),
1125                    },
1126                )
1127            })
1128            .to_string();
1129        (out, unknown)
1130    }
1131
1132    /// Add one line to the query buffer. `check_alone`: also check the line
1133    /// on its own when it continues a pending statement (typed input only;
1134    /// in a script file the buffer is known exactly).
1135    fn delimited(
1136        &mut self,
1137        line: &str,
1138        dialect: Dialect,
1139        enter_completes: bool,
1140        check_alone: bool,
1141        sub: &mut Submission,
1142    ) {
1143        if dialect == Dialect::SqlServer {
1144            if let Some(cmd) = sqlcmd_line(line) {
1145                self.sqlcmd_command(cmd, enter_completes, sub);
1146                return;
1147            }
1148        }
1149        let had_pending = !self.pending.trim().is_empty();
1150        if !had_pending && self.line_command(line, dialect, sub) {
1151            self.pending.clear();
1152            sub.count += 1;
1153            return;
1154        }
1155        // Does the child's own prompt confirm that its buffer is inside a
1156        // string/comment? Then the line really continues that literal.
1157        let prompt_in_literal = self.last_prompt.as_deref().and_then(|p| self.classify(p))
1158            == Some(PromptKind::InLiteral);
1159        let pending_in_literal =
1160            had_pending && split_statements(&self.pending, &self.delimiter, dialect).in_literal;
1161
1162        let combined = if had_pending {
1163            format!("{}\n{line}", self.pending)
1164        } else {
1165            line.to_string()
1166        };
1167        let split = split_statements(&combined, &self.delimiter, dialect);
1168        if let Some(d) = &split.delimiter {
1169            self.delimiter.clone_from(d);
1170        }
1171        for (k, v) in &split.vars {
1172            self.vars.insert(k.clone(), v.clone());
1173        }
1174        sub.reconnect |= split.reconnect;
1175        for m in &split.metas {
1176            sub.metas.push(self.expand_meta(m.clone(), dialect));
1177        }
1178        sub.count += split.metas.len();
1179        let mut statements = split.statements.clone();
1180        if enter_completes && split.remainder_balanced {
1181            let rest = normalize_ws(&split.remainder);
1182            if !rest.is_empty() {
1183                statements.push(rest);
1184            }
1185            self.pending.clear();
1186        } else if !split.remainder_has_code {
1187            // Only whitespace / comments: the client's query buffer stays
1188            // empty (a following `source` / `.read` line is a command).
1189            self.pending.clear();
1190        } else {
1191            self.pending = split.remainder;
1192        }
1193
1194        sub.count += statements.len();
1195        for stmt in statements {
1196            self.expand_statement(&stmt, dialect, sub);
1197        }
1198
1199        // One confusing statement must not hide the rest of the session:
1200        // unless the child's prompt confirms the open literal, also check
1201        // this line on its own.
1202        if check_alone && had_pending && !(prompt_in_literal && pending_in_literal) {
1203            let alone = self.split_alone(line, dialect, enter_completes);
1204            for s in alone.statements {
1205                let mut readings = vec![s.clone()];
1206                if dialect == Dialect::Postgres && s.contains(':') {
1207                    readings.push(normalize_ws(&self.substitute_vars(&s).0));
1208                }
1209                for r in readings {
1210                    if !sub.statements.contains(&r) && !sub.fallbacks.contains(&r) {
1211                        sub.fallbacks.push(r);
1212                    }
1213                }
1214            }
1215            for m in alone.metas {
1216                if !sub.metas.contains(&m) {
1217                    sub.metas.push(m);
1218                }
1219            }
1220        }
1221    }
1222
1223    /// psql interpolates variables in meta-command arguments: `\i :dir/x.sql`.
1224    fn expand_meta(&self, mut meta: MetaCommand, dialect: Dialect) -> MetaCommand {
1225        if dialect == Dialect::Postgres {
1226            if let MetaKind::RunFile { path, .. } = &mut meta.kind {
1227                if path.contains(':') {
1228                    let (expanded, _) = self.substitute_vars(path);
1229                    if expanded != *path {
1230                        // `:'dir'/x.sql`: the quotes only delimit the value.
1231                        *path = expanded.replace(['\'', '"'], "");
1232                    }
1233                }
1234            }
1235        }
1236        meta
1237    }
1238
1239    /// Add one complete statement (with psql variables substituted and
1240    /// mongosh `load()` calls recognised).
1241    fn expand_statement(&self, stmt: &str, dialect: Dialect, sub: &mut Submission) {
1242        if dialect == Dialect::Postgres && stmt.contains(':') {
1243            let (substituted, unknown) = self.substitute_vars(stmt);
1244            if substituted != stmt {
1245                sub.statements.push(normalize_ws(&substituted));
1246            }
1247            // `SELECT 'users' AS t \gset` then `TRUNCATE :"t"`: the table
1248            // is not known, so the statement is not provably harmless.
1249            if let Some(c) = var_target_re().captures(stmt) {
1250                if unknown.iter().any(|u| *u == c[1]) {
1251                    sub.metas.push(MetaCommand {
1252                        raw: stmt.to_string(),
1253                        kind: MetaKind::UnknownTarget {
1254                            what: format!(
1255                                "This runs `{}` on the object named by psql variable `{}`; \
1256                                 its value (set by `\\gset` or outside this session) is not \
1257                                 known to the wrap, so the target may be any table.",
1258                                stmt.split_whitespace().next().unwrap_or("").to_uppercase(),
1259                                &c[1]
1260                            ),
1261                        },
1262                    });
1263                }
1264            }
1265            let only_var = unknown.len() == 1
1266                && var_ref_re()
1267                    .find(stmt.trim())
1268                    .is_some_and(|m| m.as_str().trim() == stmt.trim());
1269            if only_var {
1270                sub.metas.push(MetaCommand {
1271                    raw: stmt.to_string(),
1272                    kind: MetaKind::Opaque {
1273                        id: "wrap:sql_variable",
1274                        what: format!(
1275                            "This runs the SQL stored in psql variable `{}`; its value is not \
1276                             known to the wrap.",
1277                            unknown[0]
1278                        ),
1279                    },
1280                });
1281            }
1282        }
1283        if dialect == Dialect::JavaScript {
1284            for c in mongo_load_re().captures_iter(stmt) {
1285                sub.metas.push(MetaCommand {
1286                    raw: c[0].to_string(),
1287                    kind: MetaKind::RunFile {
1288                        path: c[2].to_string(),
1289                        relative: false,
1290                    },
1291                });
1292            }
1293        }
1294        sub.statements.push(stmt.to_string());
1295    }
1296
1297    /// What a script file runs when the client reads it (`\i`, `source`,
1298    /// `\.`, `.read`, `load()`), following the same client model as typed
1299    /// input: mysql `DELIMITER` / `\d`, psql `\set` variables, line
1300    /// commands (`source`, `system`, `.read`, `.shell`) and backslash
1301    /// meta-commands. Nested includes come back as [`MetaKind::RunFile`]
1302    /// metas; the caller decides whether to follow them.
1303    ///
1304    /// See [`ScriptReader`] to read a large script line by line.
1305    #[must_use]
1306    pub fn split_script(dialect: Dialect, text: &str) -> Submission {
1307        let mut reader = ScriptReader::new(dialect);
1308        let mut sub = Submission::default();
1309        for line in text.lines() {
1310            reader.push_line(line, &mut sub);
1311        }
1312        reader.finish(&mut sub);
1313        sub
1314    }
1315
1316    /// The prompt captured for the most recently submitted line (used to
1317    /// repaint it after a discard the child does not redraw itself).
1318    #[must_use]
1319    pub fn last_prompt(&self) -> Option<&str> {
1320        self.last_prompt.as_deref()
1321    }
1322
1323    /// Forget the current line and pending statement (after a discard).
1324    pub fn discard(&mut self) {
1325        self.reset_line();
1326        self.pending.clear();
1327        self.shadow = None;
1328    }
1329}
1330
1331// ---------------------------------------------------------------------------
1332// Tests
1333// ---------------------------------------------------------------------------
1334
1335/// Streaming form of [`Interceptor::split_script`].
1336///
1337/// A script is read line by line in one linear pass (the lexer state
1338/// carries over between lines, pending text is never re-lexed), so files of
1339/// any size can be checked.
1340///
1341/// psql `COPY ... FROM stdin` data (up to `\.`) is skipped: it is data, and
1342/// a quote in it must not hide the statements after it.
1343#[derive(Debug)]
1344pub struct ScriptReader {
1345    ic: Interceptor,
1346    lexer: StreamSplitter,
1347    dialect: Dialect,
1348    in_copy_data: bool,
1349}
1350
1351fn copy_from_stdin_re() -> &'static Regex {
1352    static RE: OnceLock<Regex> = OnceLock::new();
1353    RE.get_or_init(|| Regex::new(r"(?i)^\s*COPY\b.*\bFROM\s+STDIN\b").unwrap())
1354}
1355
1356impl ScriptReader {
1357    #[must_use]
1358    pub fn new(dialect: Dialect) -> Self {
1359        Self {
1360            ic: Interceptor::new(StatementMode::Delimited {
1361                delimiter: ';',
1362                dialect,
1363                enter_completes: dialect == Dialect::JavaScript,
1364            }),
1365            lexer: StreamSplitter::new(";", dialect),
1366            dialect,
1367            in_copy_data: false,
1368        }
1369    }
1370
1371    /// Add one line of the script; what it completes is appended to `sub`.
1372    pub fn push_line(&mut self, line: &str, sub: &mut Submission) {
1373        let dialect = self.dialect;
1374        if dialect == Dialect::SqlServer {
1375            if let Some(cmd) = sqlcmd_line(line) {
1376                match cmd {
1377                    SqlCmdLine::Go => self.feed(";", sub),
1378                    SqlCmdLine::Exit(query) => {
1379                        self.feed(";", sub);
1380                        self.feed(&format!("{query};"), sub);
1381                    }
1382                    SqlCmdLine::Reset => self.lexer.clear(),
1383                    SqlCmdLine::Command { meta, reconnect } => {
1384                        sub.reconnect |= reconnect;
1385                        sub.metas.extend(meta);
1386                    }
1387                }
1388                return;
1389            }
1390        }
1391        if self.in_copy_data {
1392            if line.trim_end() == "\\." {
1393                self.in_copy_data = false;
1394            } else {
1395                // If the COPY itself failed, psql runs these lines as SQL:
1396                // check each one on its own (a quote in one row does not
1397                // carry over to the next).
1398                let split = split_statements(line, ";", dialect);
1399                sub.statements.extend(split.statements);
1400            }
1401            return;
1402        }
1403        if !self.lexer.has_pending() {
1404            if self.ic.line_command(line, dialect, sub) {
1405                self.lexer.clear();
1406                self.lexer.set_delimiter(&self.ic.delimiter);
1407                return;
1408            }
1409            // Comments left before this line are not part of a statement.
1410            self.lexer.clear();
1411        }
1412        self.lexer.feed(line);
1413        self.lexer.feed("\n");
1414        let mut split = self.lexer.take();
1415        if dialect == Dialect::JavaScript && split.remainder_balanced && self.lexer.has_pending() {
1416            // mongosh runs a complete line without `;`.
1417            self.lexer.flush();
1418            split.statements.extend(self.lexer.take().statements);
1419        }
1420        self.apply(split, sub);
1421    }
1422
1423    /// End of the script: a statement left without its delimiter still
1424    /// reaches the server (it stays in the query buffer).
1425    pub fn finish(&mut self, sub: &mut Submission) {
1426        if self.in_copy_data || !self.lexer.has_pending() {
1427            return;
1428        }
1429        let delimiter = self.ic.delimiter.clone();
1430        self.lexer.feed(&format!("\n{delimiter}"));
1431        let rest = normalize_ws(self.lexer.remainder());
1432        let mut split = self.lexer.take();
1433        if split.statements.is_empty() && !rest.is_empty() {
1434            split.statements.push(rest);
1435        }
1436        self.lexer.clear();
1437        self.apply(split, sub);
1438    }
1439
1440    /// Lex `text` as one more line of the script.
1441    fn feed(&mut self, text: &str, sub: &mut Submission) {
1442        self.lexer.feed(text);
1443        self.lexer.feed("\n");
1444        let split = self.lexer.take();
1445        self.apply(split, sub);
1446    }
1447
1448    fn apply(&mut self, split: Split, sub: &mut Submission) {
1449        let dialect = self.dialect;
1450        sub.reconnect |= split.reconnect;
1451        if let Some(d) = &split.delimiter {
1452            self.ic.delimiter.clone_from(d);
1453        }
1454        for (k, v) in split.vars {
1455            self.ic.vars.insert(k, v);
1456        }
1457        for m in split.metas {
1458            sub.metas.push(self.ic.expand_meta(m, dialect));
1459        }
1460        for stmt in split.statements {
1461            if dialect == Dialect::Postgres && copy_from_stdin_re().is_match(&stmt) {
1462                self.in_copy_data = true;
1463            }
1464            self.ic.expand_statement(&stmt, dialect, sub);
1465        }
1466    }
1467}
1468
1469#[cfg(test)]
1470mod tests {
1471    use super::*;
1472
1473    const SQL: StatementMode = StatementMode::Delimited {
1474        delimiter: ';',
1475        dialect: Dialect::Postgres,
1476        enter_completes: false,
1477    };
1478    const MONGO: StatementMode = StatementMode::Delimited {
1479        delimiter: ';',
1480        dialect: Dialect::JavaScript,
1481        enter_completes: true,
1482    };
1483
1484    /// Type `input` into the interceptor; return the submission for every Enter.
1485    fn type_all(ic: &mut Interceptor, input: &[u8]) -> Vec<Submission> {
1486        let mut subs = Vec::new();
1487        for &b in input {
1488            if ic.feed_key(b) == KeyEvent::Enter {
1489                subs.push(ic.take_submission());
1490            }
1491        }
1492        subs
1493    }
1494
1495    /// Type with a fake child that echoes every printable key and prints
1496    /// `prompt` after each Enter.
1497    fn type_echo(ic: &mut Interceptor, input: &[u8], prompt: &str) -> Vec<Submission> {
1498        let mut subs = Vec::new();
1499        for &b in input {
1500            if ic.feed_key(b) == KeyEvent::Enter {
1501                subs.push(ic.take_submission());
1502                ic.on_child_output(b"\r\n");
1503                ic.on_child_output(prompt.as_bytes());
1504            } else if b >= 0x20 && b != 0x7F {
1505                ic.on_child_output(&[b]);
1506            }
1507        }
1508        subs
1509    }
1510
1511    fn stmts(subs: &[Submission]) -> Vec<String> {
1512        subs.iter().flat_map(|s| s.statements.clone()).collect()
1513    }
1514
1515    fn everything(subs: &[Submission]) -> Vec<String> {
1516        subs.iter()
1517            .flat_map(|s| {
1518                s.statements
1519                    .iter()
1520                    .chain(&s.fallbacks)
1521                    .chain(&s.unconfirmed)
1522                    .cloned()
1523                    .collect::<Vec<_>>()
1524            })
1525            .collect()
1526    }
1527
1528    // -- LineEditor --
1529    #[test]
1530    fn cr_is_enter() {
1531        let mut ed = LineEditor::new();
1532        assert_eq!(ed.feed(b'a'), KeyEvent::Edit);
1533        assert_eq!(ed.feed(b'\r'), KeyEvent::Enter);
1534        assert_eq!(ed.feed(b'\n'), KeyEvent::Enter);
1535    }
1536
1537    #[test]
1538    fn backspace_and_del_edit_line() {
1539        let mut ed = LineEditor::new();
1540        for &b in b"DROP TABLX\x7fE us\x08\x08users" {
1541            ed.feed(b);
1542        }
1543        assert_eq!(ed.text(), "DROP TABLE users");
1544        assert!(!ed.is_uncertain());
1545    }
1546
1547    #[test]
1548    fn ctrl_u_kills_to_start() {
1549        let mut ed = LineEditor::new();
1550        for &b in b"SELECT 1\x15DROP TABLE x" {
1551            ed.feed(b);
1552        }
1553        assert_eq!(ed.text(), "DROP TABLE x");
1554    }
1555
1556    #[test]
1557    fn ctrl_w_kills_previous_word() {
1558        let mut ed = LineEditor::new();
1559        for &b in b"DROP TABLE foo  \x17users" {
1560            ed.feed(b);
1561        }
1562        assert_eq!(ed.text(), "DROP TABLE users");
1563    }
1564
1565    #[test]
1566    fn cursor_moves_and_inserts() {
1567        let mut ed = LineEditor::new();
1568        // "TABLE users", Home, "DROP ", End, ";"
1569        for &b in b"TABLE users\x1b[HDROP \x05;" {
1570            ed.feed(b);
1571        }
1572        assert_eq!(ed.text(), "DROP TABLE users;");
1573        // Left arrow twice then delete-at-cursor
1574        let mut ed = LineEditor::new();
1575        for &b in b"abcd\x1b[D\x1b[D\x1b[3~" {
1576            ed.feed(b);
1577        }
1578        assert_eq!(ed.text(), "abd");
1579        assert!(!ed.is_uncertain());
1580    }
1581
1582    #[test]
1583    fn ctrl_k_kills_to_end() {
1584        let mut ed = LineEditor::new();
1585        for &b in b"DROP TABLE users\x01\x06\x06\x06\x06\x0b" {
1586            ed.feed(b);
1587        }
1588        assert_eq!(ed.text(), "DROP");
1589    }
1590
1591    #[test]
1592    fn history_and_tab_mark_uncertain() {
1593        let mut ed = LineEditor::new();
1594        ed.feed(0x1B);
1595        ed.feed(b'[');
1596        ed.feed(b'A');
1597        assert!(ed.is_uncertain());
1598        let mut ed = LineEditor::new();
1599        ed.feed(b'D');
1600        ed.feed(b'\t');
1601        assert!(ed.is_uncertain());
1602        let mut ed = LineEditor::new();
1603        ed.feed(0x12); // Ctrl-R
1604        assert!(ed.is_uncertain());
1605        let mut ed = LineEditor::new();
1606        for &b in b"\x1bOA" {
1607            ed.feed(b);
1608        }
1609        assert!(ed.is_uncertain());
1610    }
1611
1612    #[test]
1613    fn ctrl_c_resets_and_ctrl_d_on_empty_is_eof() {
1614        let mut ed = LineEditor::new();
1615        ed.feed(b'x');
1616        assert_eq!(ed.feed(0x03), KeyEvent::Interrupt);
1617        assert_eq!(ed.text(), "");
1618        assert_eq!(ed.feed(0x04), KeyEvent::Eof);
1619        ed.feed(b'a');
1620        ed.feed(b'b');
1621        ed.feed(0x02); // left
1622        assert_eq!(ed.feed(0x04), KeyEvent::Edit); // delete-char
1623        assert_eq!(ed.text(), "a");
1624    }
1625
1626    #[test]
1627    fn bracketed_paste_keeps_newlines_literal() {
1628        let mut ed = LineEditor::new();
1629        let mut events = Vec::new();
1630        for &b in b"\x1b[200~DROP\rTABLE x;\x1b[201~" {
1631            events.push(ed.feed(b));
1632        }
1633        assert!(events.iter().all(|e| *e == KeyEvent::Edit));
1634        assert_eq!(ed.text(), "DROP\nTABLE x;");
1635        assert!(!ed.is_uncertain());
1636    }
1637
1638    #[test]
1639    fn utf8_input() {
1640        let mut ed = LineEditor::new();
1641        for &b in "שלום é".as_bytes() {
1642            ed.feed(b);
1643        }
1644        assert_eq!(ed.text(), "שלום é");
1645        ed.feed(0x7F);
1646        assert_eq!(ed.text(), "שלום ");
1647    }
1648
1649    // -- Interceptor --
1650
1651    #[test]
1652    fn sql_multiline_joined_with_space() {
1653        let mut ic = Interceptor::new(SQL);
1654        let subs = type_all(&mut ic, b"UPDATE users\rSET admin = true;\r");
1655        assert!(subs[0].statements.is_empty(), "first line is incomplete");
1656        assert_eq!(ic.pending(), "");
1657        assert_eq!(subs[1].statements, vec!["UPDATE users SET admin = true"]);
1658
1659        let subs = type_all(&mut ic, b"DROP\rTABLE users;\r");
1660        assert_eq!(stmts(&subs), vec!["DROP TABLE users"]);
1661    }
1662
1663    #[test]
1664    fn sql_backspace_typo() {
1665        let mut ic = Interceptor::new(SQL);
1666        let subs = type_all(&mut ic, b"DROP TABLX\x7fE users;\r");
1667        assert_eq!(stmts(&subs), vec!["DROP TABLE users"]);
1668    }
1669
1670    #[test]
1671    fn sql_lf_enter_also_works() {
1672        let mut ic = Interceptor::new(SQL);
1673        let subs = type_all(&mut ic, b"SELECT 1;\n");
1674        assert_eq!(stmts(&subs), vec!["SELECT 1"]);
1675    }
1676
1677    #[test]
1678    fn sql_meta_commands() {
1679        let mut ic = Interceptor::new(SQL);
1680        let subs = type_all(&mut ic, b"\\dt\r");
1681        assert!(subs[0].is_empty());
1682        let subs = type_all(&mut ic, b"DELETE FROM users\r\\r\rSELECT 1;\r");
1683        assert_eq!(stmts(&subs), vec!["SELECT 1"]);
1684        let subs = type_all(&mut ic, b"TRUNCATE TABLE orders\r\\g\r");
1685        assert_eq!(stmts(&subs), vec!["TRUNCATE TABLE orders"]);
1686        let subs = type_all(&mut ic, b"\\i cleanup.sql\r");
1687        assert!(matches!(subs[0].metas[0].kind, MetaKind::RunFile { .. }));
1688        assert_eq!(ic.pending(), "");
1689    }
1690
1691    #[test]
1692    fn sql_paste_two_statements_one_line() {
1693        let mut ic = Interceptor::new(SQL);
1694        let subs = type_all(&mut ic, b"SELECT count(*) FROM users; DELETE FROM users;\r");
1695        assert_eq!(
1696            stmts(&subs),
1697            vec!["SELECT count(*) FROM users", "DELETE FROM users"]
1698        );
1699    }
1700
1701    #[test]
1702    fn interrupt_clears_pending() {
1703        let mut ic = Interceptor::new(SQL);
1704        type_all(&mut ic, b"DROP\r");
1705        assert_eq!(ic.pending(), "DROP");
1706        assert_eq!(ic.feed_key(0x03), KeyEvent::Interrupt);
1707        assert_eq!(ic.pending(), "");
1708        let subs = type_all(&mut ic, b"TABLE x;\r");
1709        assert_eq!(stmts(&subs), vec!["TABLE x"]);
1710    }
1711
1712    #[test]
1713    fn line_mode_each_enter_is_statement() {
1714        let mut ic = Interceptor::new(StatementMode::Line);
1715        let subs = type_all(&mut ic, b"FLUSHALL\rget k\r\r");
1716        assert_eq!(subs[0].statements, vec!["FLUSHALL"]);
1717        assert_eq!(subs[1].statements, vec!["get k"]);
1718        assert!(subs[2].is_empty());
1719    }
1720
1721    #[test]
1722    fn line_mode_paste_with_newlines_splits_lines() {
1723        let mut ic = Interceptor::new(StatementMode::Line);
1724        let subs = type_all(&mut ic, b"\x1b[200~echo hi\nrm -rf /\x1b[201~\r");
1725        assert_eq!(subs[0].statements, vec!["echo hi", "rm -rf /"]);
1726    }
1727
1728    #[test]
1729    fn mongo_enter_completes_balanced_statement() {
1730        let mut ic = Interceptor::new(MONGO);
1731        let subs = type_all(&mut ic, b"db.dropDatabase()\r");
1732        assert_eq!(stmts(&subs), vec!["db.dropDatabase()"]);
1733        let subs = type_all(&mut ic, b"db.users.drop();\r");
1734        assert_eq!(stmts(&subs), vec!["db.users.drop()"]);
1735        let subs = type_all(&mut ic, b"db.users.deleteMany({\r})\r");
1736        assert!(subs[0].statements.is_empty());
1737        assert_eq!(subs[1].statements, vec!["db.users.deleteMany({ })"]);
1738        // regex literal with a bracket does not break balancing
1739        let subs = type_all(&mut ic, b"db.u.find({n: /^[(]/})\rdb.users.drop()\r");
1740        assert_eq!(
1741            stmts(&subs),
1742            vec!["db.u.find({n: /^[(]/})", "db.users.drop()"]
1743        );
1744        let subs = type_all(&mut ic, b"load('x.js')\r");
1745        assert!(matches!(subs[0].metas[0].kind, MetaKind::RunFile { .. }));
1746    }
1747
1748    #[test]
1749    fn uncertain_line_resyncs_from_echo() {
1750        let mut ic = Interceptor::new(SQL);
1751        ic.on_child_output(b"postgres=# ");
1752        for &b in b"\x1b[A" {
1753            assert_eq!(ic.feed_key(b), KeyEvent::Edit);
1754        }
1755        ic.on_child_output(b"DROP TABLE users;");
1756        assert_eq!(ic.feed_key(b'\r'), KeyEvent::Enter);
1757        let sub = ic.take_submission();
1758        assert!(sub.from_echo);
1759        assert_eq!(sub.statements, vec!["DROP TABLE users"]);
1760    }
1761
1762    #[test]
1763    fn multi_line_history_entry_resyncs_across_rows() {
1764        // psql stores a multi-line query as one history entry.
1765        let mut ic = Interceptor::new(SQL);
1766        ic.set_size(80, 24);
1767        ic.on_child_output(b"postgres=# ");
1768        for &b in b"\x1b[A" {
1769            ic.feed_key(b);
1770        }
1771        ic.on_child_output(b"UPDATE users\r\nSET admin = true;");
1772        ic.feed_key(b'\r');
1773        let sub = ic.take_submission();
1774        assert_eq!(sub.statements, vec!["UPDATE users SET admin = true"]);
1775        // readline shows embedded newlines as ^J on one row
1776        let mut ic = Interceptor::new(SQL);
1777        ic.on_child_output(b"postgres=# ");
1778        for &b in b"\x1b[A" {
1779            ic.feed_key(b);
1780        }
1781        ic.on_child_output(b"DELETE^JFROM users;");
1782        ic.feed_key(b'\r');
1783        assert_eq!(ic.take_submission().statements, vec!["DELETE FROM users"]);
1784    }
1785
1786    #[test]
1787    fn tab_completion_resyncs_from_echo() {
1788        let mut ic = Interceptor::new(SQL);
1789        ic.on_child_output(b"\r\npostgres=# ");
1790        for &b in b"DROP TA" {
1791            ic.feed_key(b);
1792            ic.on_child_output(&[b]);
1793        }
1794        ic.feed_key(b'\t');
1795        ic.on_child_output(b"BLE ");
1796        for &b in b"users;" {
1797            ic.feed_key(b);
1798            ic.on_child_output(&[b]);
1799        }
1800        ic.feed_key(b'\r');
1801        let sub = ic.take_submission();
1802        assert_eq!(sub.statements, vec!["DROP TABLE users"]);
1803        assert_eq!(sub.fallbacks, vec!["DROP TAusers;"]);
1804    }
1805
1806    #[test]
1807    fn tab_listing_uses_redrawn_prompt_row() {
1808        let mut ic = Interceptor::new(SQL);
1809        ic.on_child_output(b"postgres=# ");
1810        for &b in b"DROP TA" {
1811            ic.feed_key(b);
1812            ic.on_child_output(&[b]);
1813        }
1814        ic.feed_key(b'\t');
1815        ic.on_child_output(b"\r\nTABLE  TABLESPACE\r\npostgres=# DROP TABLE users;");
1816        ic.feed_key(b'\r');
1817        assert_eq!(ic.take_submission().statements, vec!["DROP TABLE users"]);
1818    }
1819
1820    #[test]
1821    fn uncertain_without_echo_falls_back_to_model() {
1822        let mut ic = Interceptor::new(StatementMode::Line);
1823        for &b in b"FLUSHALL\t" {
1824            ic.feed_key(b);
1825        }
1826        ic.feed_key(b'\r');
1827        let sub = ic.take_submission();
1828        assert!(!sub.from_echo);
1829        assert_eq!(sub.statements, vec!["FLUSHALL"]);
1830    }
1831
1832    #[test]
1833    fn pager_keys_in_alt_screen_are_ignored() {
1834        // `q` typed into less must not prefix the next statement.
1835        let mut ic = Interceptor::new(SQL);
1836        ic.on_child_output(b"postgres=# ");
1837        let subs = type_echo(&mut ic, b"SELECT * FROM big_table;\r", "");
1838        assert_eq!(stmts(&subs), vec!["SELECT * FROM big_table"]);
1839        ic.on_child_output(b"\x1b[?1049h  1 | row\r\n:");
1840        assert_eq!(ic.feed_key(b' '), KeyEvent::Edit);
1841        assert_eq!(ic.feed_key(b'q'), KeyEvent::Edit);
1842        ic.on_child_output(b"\x1b[?1049l\r\npostgres=# ");
1843        let subs = type_echo(&mut ic, b"TRUNCATE orders;\r", "postgres=# ");
1844        assert_eq!(stmts(&subs), vec!["TRUNCATE orders"]);
1845    }
1846
1847    #[test]
1848    fn pager_keys_without_alt_screen_resync_on_prompt() {
1849        // `less -X`: no alternate screen, the prompt is redrawn in place.
1850        let mut ic = Interceptor::new(SQL);
1851        ic.on_child_output(b"postgres=# ");
1852        type_echo(&mut ic, b"SELECT * FROM big_table;\r", "");
1853        ic.on_child_output(b"  1 | row\r\n:");
1854        ic.feed_key(b'q');
1855        ic.on_child_output(b"\r\x1b[Kpostgres=# ");
1856        let subs = type_echo(&mut ic, b"TRUNCATE orders;\r", "postgres=# ");
1857        assert!(everything(&subs).contains(&"TRUNCATE orders".to_string()));
1858        assert_eq!(subs[0].statements, vec!["TRUNCATE orders"]);
1859    }
1860
1861    #[test]
1862    fn password_prompt_is_dropped_and_not_kept() {
1863        let mut ic = Interceptor::new(SQL);
1864        ic.on_child_output(b"Password for user postgres: ");
1865        ic.set_tty_state(Some(TtyState {
1866            echo: false,
1867            icanon: true,
1868        }));
1869        let subs = type_all(&mut ic, b"S3cretPw\r");
1870        assert!(subs[0].secret);
1871        assert!(subs[0].is_empty());
1872        assert!(!subs[0].log_summary().contains("S3cret"));
1873        ic.set_tty_state(Some(TtyState {
1874            echo: false,
1875            icanon: false,
1876        }));
1877        ic.on_child_output(b"\r\npostgres=# ");
1878        let subs = type_echo(&mut ic, b"DROP TABLE users;\r", "postgres=# ");
1879        assert_eq!(stmts(&subs), vec!["DROP TABLE users"]);
1880    }
1881
1882    #[test]
1883    fn unechoed_line_is_checked_alone_and_redacted() {
1884        // Raw-mode client (mongosh passwordPrompt) that does not echo.
1885        let mut ic = Interceptor::new(SQL);
1886        ic.on_child_output(b"postgres=# ");
1887        type_echo(&mut ic, b"SELECT 1;\r", "Password: ");
1888        let subs = type_all(&mut ic, b"hunter2\r");
1889        assert_eq!(subs[0].unconfirmed, vec!["hunter2"]);
1890        assert!(subs[0].statements.is_empty());
1891        assert!(!subs[0].log_summary().contains("hunter2"));
1892        assert_eq!(ic.pending(), "");
1893    }
1894
1895    #[test]
1896    fn primary_prompt_resyncs_pending() {
1897        // psql `\prompt` answer, or any desync: the child shows `=#` again.
1898        let mut ic = Interceptor::new(SQL);
1899        ic.on_child_output(b"postgres=# ");
1900        type_echo(&mut ic, b"42\r", "postgres=# ");
1901        assert_eq!(ic.pending(), "42");
1902        let subs = type_echo(&mut ic, b"DELETE FROM users;\r", "postgres=# ");
1903        assert_eq!(subs[0].statements, vec!["DELETE FROM users"]);
1904        // a continuation prompt keeps the buffer
1905        let mut ic = Interceptor::new(SQL);
1906        ic.on_child_output(b"postgres=# ");
1907        type_echo(&mut ic, b"DROP\r", "postgres-# ");
1908        let subs = type_echo(&mut ic, b"TABLE users;\r", "postgres=# ");
1909        assert_eq!(subs[0].statements, vec!["DROP TABLE users"]);
1910    }
1911
1912    #[test]
1913    fn confusing_literal_never_disables_checking() {
1914        // Our lexer thinks a quote is open, the child does not (safety net).
1915        let mut ic = Interceptor::new(SQL);
1916        let subs = type_all(&mut ic, b"SELECT 'unterminated\rDROP TABLE users;\r");
1917        assert!(everything(&subs).contains(&"DROP TABLE users".to_string()));
1918    }
1919
1920    #[test]
1921    fn psql_dollar_quote_does_not_desync() {
1922        let mut ic = Interceptor::new(SQL);
1923        let subs = type_all(
1924            &mut ic,
1925            b"COMMENT ON TABLE users IS $$Don't touch$$;\rDROP TABLE users;\r",
1926        );
1927        assert_eq!(subs[1].statements, vec!["DROP TABLE users"]);
1928    }
1929
1930    #[test]
1931    fn psql_variables_are_substituted() {
1932        let mut ic = Interceptor::new(SQL);
1933        let subs = type_all(&mut ic, b"\\set cleanup 'DROP TABLE users'\r:cleanup;\r");
1934        assert!(stmts(&subs).contains(&"DROP TABLE users".to_string()));
1935        let subs = type_all(&mut ic, b":unknown_var;\r");
1936        assert!(matches!(
1937            subs[0].metas[0].kind,
1938            MetaKind::Opaque {
1939                id: "wrap:sql_variable",
1940                ..
1941            }
1942        ));
1943        let subs = type_all(&mut ic, b"SELECT now()::date;\r");
1944        assert!(subs[0].metas.is_empty());
1945    }
1946
1947    #[test]
1948    fn mysql_line_commands_and_delimiter() {
1949        let my = StatementMode::Delimited {
1950            delimiter: ';',
1951            dialect: Dialect::MySql,
1952            enter_completes: false,
1953        };
1954        let mut ic = Interceptor::new(my);
1955        let subs = type_all(&mut ic, b"use billing\rTRUNCATE invoices;\r");
1956        assert_eq!(stmts(&subs), vec!["TRUNCATE invoices"]);
1957        let subs = type_all(&mut ic, b"delimiter //\rDROP TABLE users//\r");
1958        assert_eq!(stmts(&subs), vec!["DROP TABLE users"]);
1959        assert_eq!(ic.delimiter(), "//");
1960        let subs = type_all(
1961            &mut ic,
1962            b"CREATE PROCEDURE p() BEGIN\rDELETE FROM a;\rEND//\r",
1963        );
1964        assert_eq!(
1965            stmts(&subs),
1966            vec!["CREATE PROCEDURE p() BEGIN DELETE FROM a; END"]
1967        );
1968        let subs = type_all(
1969            &mut ic,
1970            b"DELIMITER ;\rSELECT 1 # it's fine\r;\rDROP TABLE x;\r",
1971        );
1972        assert_eq!(stmts(&subs), vec!["SELECT 1", "DROP TABLE x"]);
1973        let subs = type_all(&mut ic, b"source /tmp/cleanup.sql\r");
1974        assert!(matches!(subs[0].metas[0].kind, MetaKind::RunFile { .. }));
1975        let subs = type_all(&mut ic, b"\\! rm -rf /data\r");
1976        assert!(matches!(subs[0].metas[0].kind, MetaKind::Shell { .. }));
1977    }
1978
1979    #[test]
1980    fn sqlite_dot_commands_are_line_commands() {
1981        let lite = StatementMode::Delimited {
1982            delimiter: ';',
1983            dialect: Dialect::Sqlite,
1984            enter_completes: false,
1985        };
1986        let mut ic = Interceptor::new(lite);
1987        let subs = type_all(&mut ic, b".tables\rDELETE FROM users;\r");
1988        assert_eq!(stmts(&subs), vec!["DELETE FROM users"]);
1989        let subs = type_all(&mut ic, b".read cleanup.sql\r.shell rm -rf /x\r");
1990        assert!(matches!(subs[0].metas[0].kind, MetaKind::RunFile { .. }));
1991        assert!(matches!(subs[1].metas[0].kind, MetaKind::Shell { .. }));
1992    }
1993
1994    #[test]
1995    fn sqlite_pipe_forms_run_shell_commands() {
1996        let lite = StatementMode::Delimited {
1997            delimiter: ';',
1998            dialect: Dialect::Sqlite,
1999            enter_completes: false,
2000        };
2001        let shell = |cmd: &str| MetaKind::Shell {
2002            command: cmd.to_string(),
2003        };
2004        for (line, want) in [
2005            (
2006                ".once '|rm -rf /home/dev/data'",
2007                shell("rm -rf /home/dev/data"),
2008            ),
2009            (".once -x '|rm -rf /x'", shell("rm -rf /x")),
2010            (".output \"|rm -rf /x\"", shell("rm -rf /x")),
2011            (".output |cat", shell("cat")),
2012            // Unquoted, the rest of the line is the command.
2013            (
2014                ".once |rm -rf /home/dev/data",
2015                shell("rm -rf /home/dev/data"),
2016            ),
2017            (".output |rm -rf /x", shell("rm -rf /x")),
2018            (".once -x |rm -rf /x", shell("rm -rf /x")),
2019            (".import |rm -rf /x t", shell("rm -rf /x")),
2020            (".import --csv |curl -s x t", shell("curl -s x")),
2021            (
2022                ".read |rm -rf /x",
2023                MetaKind::ShellToSql {
2024                    command: "rm -rf /x".into(),
2025                },
2026            ),
2027            (".import '|rm -rf /x' t", shell("rm -rf /x")),
2028            (".import --csv '|curl -s x' t", shell("curl -s x")),
2029            (
2030                ".read '|rm -rf /x'",
2031                MetaKind::ShellToSql {
2032                    command: "rm -rf /x".into(),
2033                },
2034            ),
2035        ] {
2036            let mut ic = Interceptor::new(lite);
2037            let subs = type_all(&mut ic, format!("{line}\r").as_bytes());
2038            assert_eq!(subs[0].metas.len(), 1, "{line}");
2039            assert_eq!(subs[0].metas[0].kind, want, "{line}");
2040        }
2041        for line in [".once out.txt", ".output stdout", ".import data.csv t"] {
2042            let mut ic = Interceptor::new(lite);
2043            let subs = type_all(&mut ic, format!("{line}\r").as_bytes());
2044            assert!(subs[0].metas.is_empty(), "{line}");
2045        }
2046    }
2047
2048    #[test]
2049    fn comment_line_leaves_the_buffer_empty() {
2050        // A `source` line after a comment line is a client command.
2051        let sub = Interceptor::split_script(Dialect::MySql, "-- cleanup\nsource /tmp/x.sql\n");
2052        assert!(
2053            matches!(
2054                sub.metas.first().map(|m| &m.kind),
2055                Some(MetaKind::RunFile { .. })
2056            ),
2057            "{sub:?}"
2058        );
2059        let sub = Interceptor::split_script(Dialect::Sqlite, "-- c\n.read /tmp/x.sql\n");
2060        assert!(matches!(
2061            sub.metas.first().map(|m| &m.kind),
2062            Some(MetaKind::RunFile { .. })
2063        ));
2064    }
2065
2066    #[test]
2067    fn script_reader_skips_copy_data_and_interpolates_include_paths() {
2068        let text = "COPY users (id, name) FROM stdin;\n1\tO'Brien\n2\tDROP TABLE users;\n\\.\nTRUNCATE orders;\n\\set d /home/dev\n\\i :d/cleanup.sql\n\\ir :'d'/x.sql\n";
2069        let sub = Interceptor::split_script(Dialect::Postgres, text);
2070        assert_eq!(
2071            sub.statements,
2072            vec![
2073                "COPY users (id, name) FROM stdin",
2074                "2 DROP TABLE users",
2075                "TRUNCATE orders"
2076            ]
2077        );
2078        assert_eq!(
2079            sub.metas[0].kind,
2080            MetaKind::RunFile {
2081                path: "/home/dev/cleanup.sql".into(),
2082                relative: false
2083            }
2084        );
2085        assert_eq!(
2086            sub.metas[1].kind,
2087            MetaKind::RunFile {
2088                path: "/home/dev/x.sql".into(),
2089                relative: true
2090            }
2091        );
2092    }
2093
2094    #[test]
2095    fn script_reader_is_linear_on_long_statements() {
2096        // One INSERT spread over 200k lines: lexed once, not re-lexed per
2097        // line (this took minutes with the quadratic splitter).
2098        let mut text = String::from("INSERT INTO t VALUES\n");
2099        for i in 0..200_000 {
2100            text.push_str(&format!("({i}, 'x'),\n"));
2101        }
2102        text.push_str("(0, 'y');\nDELETE FROM users;\n");
2103        let start = std::time::Instant::now();
2104        let sub = Interceptor::split_script(Dialect::Postgres, &text);
2105        assert_eq!(sub.statements.len(), 2);
2106        assert_eq!(sub.statements[1], "DELETE FROM users");
2107        assert!(start.elapsed().as_secs() < 20, "{:?}", start.elapsed());
2108    }
2109}