mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Blanking of comments, text literals and quoted identifiers.
//!
//! Every textual comparison in this product runs over the output of this
//! module and never over the raw statement. Two measured defects in the
//! reference implementations come from comparing raw text: a legitimate query
//! carrying a reserved word inside a literal was refused, and a destructive
//! statement hidden behind a comment was admitted.
//!
//! # What is blanked
//!
//! Blanked regions are replaced byte for byte with spaces, so every offset in
//! the output still names the same position in the input and a refusal message
//! can point at the right place.
//!
//! Quoted identifiers are blanked too. They are names rather than literals, but
//! a name may legally contain a separator or a reserved word, and blanking is
//! what stops `` `a;b` `` from being read as two statements.
//!
//! # What is not blanked
//!
//! A conditional comment (`/*! ... */` or `/*M! ... */`) is executable on this
//! server, so its body is code and stays. Only the introducer and the closing
//! delimiter are blanked. Callers that must know a statement carried one ask
//! [`Stripped::has_conditional_comment`].
//!
//! # Why the same scan also feeds the parser
//!
//! [`expand_conditional_comments`] applies that one rule and nothing else, so
//! the parser is handed the statement the server will run. Leaving that to the
//! parser crate was measured to be wrong: it expands the introducer that starts
//! with an exclamation mark and drops the server-specific one as whitespace,
//! which took a file-reading call out of the tree the refusals walk.

use crate::error::{Failure, Result};

/// A statement with its comments, text literals and quoted identifiers blanked.
///
/// The text has exactly the same byte length as the input.
#[derive(Debug, Clone)]
pub struct Stripped {
    text: String,
    conditional_comment: bool,
    unterminated: Option<Unterminated>,
}

/// A quoted or commented region that never closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Unterminated {
    /// What kind of region was left open.
    pub kind: UnterminatedKind,
    /// The byte offset where the open region started.
    pub offset: usize,
}

/// The kinds of region that can be left open.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnterminatedKind {
    /// A `/* ... */` comment, conditional or not.
    BlockComment,
    /// A `'...'` or `"..."` literal.
    TextLiteral,
    /// A `` `...` `` identifier.
    QuotedIdentifier,
}

impl UnterminatedKind {
    /// The stable name used in a refusal message.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BlockComment => "block comment",
            Self::TextLiteral => "text literal",
            Self::QuotedIdentifier => "quoted identifier",
        }
    }

    /// The characters the region opens with.
    #[must_use]
    pub const fn opening_delimiter(self) -> &'static str {
        match self {
            Self::BlockComment => "/*",
            Self::TextLiteral => "'",
            Self::QuotedIdentifier => "`",
        }
    }
}

impl Stripped {
    /// The blanked text, byte-for-byte aligned with the input.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Whether the input carried a conditional comment, whose body is code.
    #[must_use]
    pub const fn has_conditional_comment(&self) -> bool {
        self.conditional_comment
    }

    /// The region left open, when the input ended inside one.
    #[must_use]
    pub const fn unterminated(&self) -> Option<Unterminated> {
        self.unterminated
    }

    /// Refuses a statement that ends inside a quote or a comment.
    ///
    /// An open region means the rest of the text was read as data rather than
    /// as code, so no later decision about it can be trusted.
    ///
    /// # Errors
    ///
    /// Returns a validation failure when a region was left open.
    pub fn refuse_if_unterminated(&self) -> Result<()> {
        match self.unterminated {
            None => Ok(()),
            Some(open) => Err(Failure::validation(
                "sql.unterminated_region",
                format!(
                    "the statement ends inside an unterminated {} that opens at byte {}",
                    open.kind.as_str(),
                    open.offset
                ),
            )
            // The delimiter and the offset, rather than the name of the kind,
            // because the catalogue substitutes this into prose a reader asked
            // for in their own language and a delimiter reads the same in all.
            .with_detail(
                "detail",
                format!("{} @ {}", open.kind.opening_delimiter(), open.offset),
            )
            .with_hint("close the quote or the comment before sending the statement")),
        }
    }
}

/// Blanks comments, text literals and quoted identifiers.
///
/// Never fails: an unterminated region is blanked to the end of the input and
/// reported through [`Stripped::unterminated`], so a caller decides what to do.
///
/// # Examples
///
/// Blanked rather than removed, so every offset in the result still points at
/// the same character of the input. That is what lets a later stage report a
/// position the caller can find in the text they wrote:
///
/// ```
/// use mariadb_cli::sql::strip::strip;
///
/// let stripped = strip("SELECT 1 -- drop everything");
/// assert_eq!(stripped.text().len(), "SELECT 1 -- drop everything".len());
/// assert!(!stripped.text().contains("drop"));
/// ```
///
/// A keyword hidden inside a text literal is blanked too, which is the point:
/// classification runs over the result, so the literal cannot pose as code.
///
/// ```
/// use mariadb_cli::sql::strip::strip;
///
/// let stripped = strip("SELECT 'DELETE FROM pedidos'");
/// assert!(stripped.text().starts_with("SELECT "));
/// assert!(!stripped.text().contains("DELETE"));
/// ```
///
/// A region that never closes is reported rather than passed off as clean:
///
/// ```
/// use mariadb_cli::sql::strip::strip;
///
/// assert!(strip("SELECT 'aberta").unterminated().is_some());
/// assert!(strip("SELECT 'fechada'").unterminated().is_none());
/// ```
#[must_use]
pub fn strip(sql: &str) -> Stripped {
    let mut scanner = Scanner::new(sql, Mode::BlankEverything);
    scanner.run();
    scanner.finish()
}

/// The statement as the server will run it, with conditional comments expanded.
///
/// Only the introducer and the closing delimiter of a conditional comment are
/// blanked. Literals, names and plain comments are handed back byte for byte,
/// so the result parses like the input and every offset still names the same
/// position, which is what lets a parser complaint point at the caller's text.
///
/// # Why this is not left to the parser
///
/// The parser crate expands `/*! ... */` and drops `/*M! ... */` as whitespace.
/// This server runs both. A file-reading call written inside the second one was
/// therefore absent from the tree while present in the statement the server
/// executed, and every refusal that walks the tree was blind to it. Deciding
/// here what the server runs is what removes that difference of opinion.
///
/// # Examples
///
/// The body of both introducers survives, and the delimiters do not:
///
/// ```
/// use mariadb_cli::sql::strip::expand_conditional_comments;
///
/// let expanded = expand_conditional_comments("SELECT 1 /*M!100000 ,2 */");
/// assert!(expanded.contains(",2"));
/// assert!(!expanded.contains("/*"));
/// assert_eq!(expanded.len(), "SELECT 1 /*M!100000 ,2 */".len());
/// ```
///
/// A literal is data, so it is handed back exactly as it arrived:
///
/// ```
/// use mariadb_cli::sql::strip::expand_conditional_comments;
///
/// let text = "SELECT '/*M!100000 hidden */' AS note";
/// assert_eq!(expand_conditional_comments(text), text);
/// ```
#[must_use]
pub fn expand_conditional_comments(sql: &str) -> String {
    let mut scanner = Scanner::new(sql, Mode::ExpandConditional);
    scanner.run();
    scanner.finish().text
}

/// What the scan does with a region that is not a conditional delimiter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// Replace it with spaces, for textual comparison.
    BlankEverything,
    /// Hand it back unchanged, for parsing.
    ExpandConditional,
}

/// One left-to-right pass over the input.
struct Scanner<'a> {
    src: &'a str,
    bytes: &'a [u8],
    mode: Mode,
    /// The read position.
    pos: usize,
    /// The start of the run of bytes kept verbatim and not yet emitted.
    kept_from: usize,
    out: String,
    /// How many conditional comments are open around the read position.
    conditional_depth: usize,
    conditional_comment: bool,
    unterminated: Option<Unterminated>,
}

impl<'a> Scanner<'a> {
    fn new(src: &'a str, mode: Mode) -> Self {
        Self {
            src,
            bytes: src.as_bytes(),
            mode,
            pos: 0,
            kept_from: 0,
            out: String::with_capacity(src.len()),
            conditional_depth: 0,
            conditional_comment: false,
            unterminated: None,
        }
    }

    /// The byte at `index`, or zero past the end.
    ///
    /// Zero never appears in the delimiters this scanner matches, so it is a
    /// safe stand-in for the end of the input.
    fn at(&self, index: usize) -> u8 {
        self.bytes.get(index).copied().unwrap_or(0)
    }

    /// Emits every byte kept verbatim up to `upto`.
    fn flush_kept(&mut self, upto: usize) {
        if let Some(kept) = self.src.get(self.kept_from..upto) {
            self.out.push_str(kept);
        }
        self.kept_from = upto;
    }

    /// Replaces `from..to` with as many spaces as it has bytes.
    ///
    /// Region ends always land on a character boundary, because every
    /// delimiter this scanner matches is ASCII and a continuation byte of a
    /// multi-byte character never equals an ASCII byte.
    fn blank(&mut self, from: usize, to: usize) {
        self.flush_kept(from);
        for _ in from..to {
            self.out.push(' ');
        }
        self.kept_from = to;
        self.pos = to;
    }

    /// Passes over a region that is data or commentary rather than a delimiter.
    ///
    /// Which of the two scans is running decides what that means. The textual
    /// one replaces the region with spaces so a comparison cannot read data as
    /// code; the parsing one hands it back untouched, because a literal with
    /// its quotes removed is no longer a statement anybody can read.
    ///
    /// Both leave the byte length alone, so an offset means the same thing on
    /// either side.
    fn erase(&mut self, from: usize, to: usize) {
        match self.mode {
            Mode::BlankEverything => self.blank(from, to),
            Mode::ExpandConditional => self.pos = to,
        }
    }

    /// Records the first open region seen.
    fn mark_unterminated(&mut self, kind: UnterminatedKind, offset: usize) {
        if self.unterminated.is_none() {
            self.unterminated = Some(Unterminated { kind, offset });
        }
    }

    fn run(&mut self) {
        while self.pos < self.bytes.len() {
            let start = self.pos;
            match self.at(start) {
                // A closing delimiter of a conditional comment is punctuation,
                // never code, so it is blanked while its body is kept.
                b'*' if self.conditional_depth > 0 && self.at(start + 1) == b'/' => {
                    self.conditional_depth -= 1;
                    self.blank(start, start + 2);
                }
                b'-' if self.at(start + 1) == b'-' && starts_line_comment(self.at(start + 2)) => {
                    self.blank_to_end_of_line(start);
                }
                b'#' => self.blank_to_end_of_line(start),
                b'/' if self.at(start + 1) == b'*' => self.take_block_comment(start),
                b'\'' | b'"' => self.take_quoted(start, UnterminatedKind::TextLiteral),
                b'`' => self.take_quoted(start, UnterminatedKind::QuotedIdentifier),
                _ => self.pos = start + 1,
            }
        }
        if self.conditional_depth > 0 {
            self.mark_unterminated(UnterminatedKind::BlockComment, self.bytes.len());
        }
    }

    /// Passes over a `-- ` or `#` comment, keeping the line break that ends it.
    fn blank_to_end_of_line(&mut self, start: usize) {
        let end = self.src[start..]
            .find('\n')
            .map_or(self.bytes.len(), |offset| start + offset);
        self.erase(start, end);
    }

    /// Handles `/*`, which opens either an executable directive or a comment.
    fn take_block_comment(&mut self, start: usize) {
        if let Some(body_start) = conditional_body_start(self.bytes, start) {
            self.conditional_comment = true;
            self.conditional_depth += 1;
            self.blank(start, body_start);
            return;
        }
        self.blank_block_comment(start);
    }

    /// Blanks a plain `/* ... */` comment, honouring nesting.
    fn blank_block_comment(&mut self, start: usize) {
        let mut depth = 1_usize;
        let mut cursor = start + 2;
        while cursor < self.bytes.len() {
            if self.at(cursor) == b'/' && self.at(cursor + 1) == b'*' {
                depth += 1;
                cursor += 2;
            } else if self.at(cursor) == b'*' && self.at(cursor + 1) == b'/' {
                depth -= 1;
                cursor += 2;
                if depth == 0 {
                    self.erase(start, cursor);
                    return;
                }
            } else {
                cursor += 1;
            }
        }
        self.mark_unterminated(UnterminatedKind::BlockComment, start);
        self.erase(start, self.bytes.len());
    }

    /// Blanks a region delimited by the byte at `start`.
    ///
    /// A doubled delimiter escapes itself everywhere. A backslash escapes the
    /// next byte inside a text literal but not inside a quoted identifier,
    /// which is how this server reads them.
    fn take_quoted(&mut self, start: usize, kind: UnterminatedKind) {
        let delimiter = self.at(start);
        let backslash_escapes = kind == UnterminatedKind::TextLiteral;
        let mut cursor = start + 1;
        while cursor < self.bytes.len() {
            let byte = self.at(cursor);
            // A backslash and a doubled delimiter both consume two bytes: the
            // marker and the byte it protects.
            let escaped = (backslash_escapes && byte == b'\\')
                || (byte == delimiter && self.at(cursor + 1) == delimiter);
            if escaped {
                cursor += 2;
            } else if byte == delimiter {
                self.erase(start, cursor + 1);
                return;
            } else {
                cursor += 1;
            }
        }
        self.mark_unterminated(kind, start);
        self.erase(start, self.bytes.len());
    }

    fn finish(mut self) -> Stripped {
        let end = self.bytes.len();
        self.flush_kept(end);
        Stripped {
            text: self.out,
            conditional_comment: self.conditional_comment,
            unterminated: self.unterminated,
        }
    }
}

/// Whether the byte after `--` turns it into a comment.
///
/// This server needs a space, a control character or the end of the input
/// after the two dashes, so `a--1` stays an expression.
const fn starts_line_comment(next: u8) -> bool {
    next == 0 || next == b' ' || next == b'\t' || next == b'\n' || next == b'\r'
}

/// Where the executable body of a conditional comment starts.
///
/// Returns `None` when the comment opening at `start` is a plain comment. The
/// introducer is `/*!` or `/*M!`, optionally followed by the version digits
/// that decide whether this server runs the body.
fn conditional_body_start(bytes: &[u8], start: usize) -> Option<usize> {
    let read = |index: usize| bytes.get(index).copied().unwrap_or(0);
    let mut cursor = match read(start + 2) {
        b'!' => start + 3,
        b'M' | b'm' if read(start + 3) == b'!' => start + 4,
        _ => return None,
    };
    while read(cursor).is_ascii_digit() {
        cursor += 1;
    }
    Some(cursor)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn text_of(sql: &str) -> String {
        strip(sql).text().to_string()
    }

    /// Every offset in the output still names the same input position, which
    /// is what lets a refusal point at the right byte.
    #[test]
    fn the_blanked_text_keeps_the_byte_length_of_the_input() {
        for sql in [
            "SELECT 1",
            "SELECT 'olá' -- acento\nFROM t",
            "SELECT /* ácido */ `coluna` FROM t",
            "SELECT '\u{1f600}' FROM t",
            "SELECT # fim",
        ] {
            assert_eq!(text_of(sql).len(), sql.len(), "input {sql:?}");
        }
    }

    #[test]
    fn a_reserved_word_inside_a_literal_disappears_from_the_text() {
        let stripped = text_of("SELECT 'DROP TABLE users' FROM t");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
        assert!(stripped.contains("SELECT"));
        assert!(stripped.contains("FROM t"));
    }

    #[test]
    fn a_doubled_quote_does_not_end_the_literal() {
        let stripped = text_of("SELECT 'it''s DROP' , 1");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
        assert!(stripped.contains(", 1"));
    }

    #[test]
    fn a_backslash_escaped_quote_does_not_end_the_literal() {
        let stripped = text_of("SELECT 'a\\' DROP' , 1");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
        assert!(stripped.contains(", 1"));
    }

    #[test]
    fn a_double_quoted_literal_is_blanked_like_a_single_quoted_one() {
        let stripped = text_of("SELECT \"DROP TABLE\" , 1");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
    }

    /// A backslash is an ordinary byte inside a quoted identifier, so the
    /// closing backtick still closes it.
    #[test]
    fn a_backslash_does_not_escape_inside_a_quoted_identifier() {
        let stripped = text_of("SELECT `a\\` , 1");
        assert!(stripped.contains(", 1"), "got {stripped:?}");
        assert!(strip("SELECT `a\\` , 1").unterminated().is_none());
    }

    #[test]
    fn a_separator_inside_a_quoted_identifier_disappears_from_the_text() {
        let stripped = text_of("SELECT * FROM `a;b`");
        assert!(!stripped.contains(';'), "got {stripped:?}");
    }

    #[test]
    fn a_line_comment_needs_a_space_after_the_two_dashes() {
        assert!(text_of("SELECT 1-- DROP").contains("SELECT 1"));
        assert!(!text_of("SELECT 1-- DROP").contains("DROP"));
        assert!(
            text_of("SELECT 1--2").contains("--2"),
            "without a space the dashes are an operator"
        );
    }

    #[test]
    fn a_hash_comment_runs_to_the_end_of_the_line() {
        let stripped = text_of("SELECT 1 # DROP TABLE t\nFROM u");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
        assert!(stripped.contains("FROM u"));
    }

    #[test]
    fn a_block_comment_is_blanked_and_may_nest() {
        let stripped = text_of("SELECT /* a /* b */ DROP */ 1");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
        assert!(stripped.contains("SELECT"));
        assert!(stripped.contains('1'));
    }

    #[test]
    fn a_comment_placed_mid_statement_does_not_hide_the_rest() {
        let stripped = text_of("DELETE /* looks harmless */ FROM users");
        assert!(stripped.contains("DELETE"));
        assert!(stripped.contains("FROM users"));
    }

    #[test]
    fn a_conditional_comment_is_kept_as_code() {
        let stripped = text_of("SELECT /*!40001 SQL_NO_CACHE */ 1");
        assert!(
            stripped.contains("SQL_NO_CACHE"),
            "the body is executable, got {stripped:?}"
        );
        assert!(!stripped.contains("/*"), "the introducer is punctuation");
        assert!(!stripped.contains("*/"), "the terminator is punctuation");
        assert!(strip("SELECT /*!40001 SQL_NO_CACHE */ 1").has_conditional_comment());
    }

    #[test]
    fn a_server_specific_conditional_comment_is_kept_as_code() {
        let stripped = text_of("SELECT /*M!100301 DROP */ 1");
        assert!(stripped.contains("DROP"), "got {stripped:?}");
        assert!(strip("SELECT /*M!100301 DROP */ 1").has_conditional_comment());
    }

    #[test]
    fn a_literal_inside_a_conditional_comment_is_still_blanked() {
        let stripped = text_of("SELECT /*! 'DROP' */ 1");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
    }

    #[test]
    fn a_conditional_comment_inside_a_plain_comment_stays_commented_out() {
        let stripped = text_of("SELECT /* /*!40001 DROP */ */ 1");
        assert!(!stripped.contains("DROP"), "got {stripped:?}");
        assert!(!strip("SELECT /* /*!40001 DROP */ */ 1").has_conditional_comment());
    }

    #[test]
    fn a_comment_marker_inside_a_literal_does_not_open_a_comment() {
        let stripped = text_of("SELECT '/*' , 1 , '*/'");
        assert!(stripped.contains(", 1 ,"), "got {stripped:?}");
    }

    #[test]
    fn a_quote_inside_a_comment_does_not_open_a_literal() {
        let stripped = text_of("SELECT /* it's here */ 1 , 2");
        assert!(stripped.contains("1 , 2"), "got {stripped:?}");
    }

    #[test]
    fn an_unterminated_literal_is_reported_and_refused() {
        let stripped = strip("SELECT 'never closed");
        let open = stripped.unterminated().expect("open region");
        assert_eq!(open.kind, UnterminatedKind::TextLiteral);
        assert_eq!(open.offset, 7);
        assert!(stripped.refuse_if_unterminated().is_err());
    }

    #[test]
    fn an_unterminated_block_comment_is_reported_and_refused() {
        let stripped = strip("SELECT 1 /* never closed");
        let open = stripped.unterminated().expect("open region");
        assert_eq!(open.kind, UnterminatedKind::BlockComment);
        assert!(stripped.refuse_if_unterminated().is_err());
    }

    #[test]
    fn an_unterminated_quoted_identifier_is_reported() {
        let stripped = strip("SELECT * FROM `never closed");
        let open = stripped.unterminated().expect("open region");
        assert_eq!(open.kind, UnterminatedKind::QuotedIdentifier);
    }

    #[test]
    fn a_closed_statement_reports_no_open_region() {
        assert!(strip("SELECT 'a' , `b` /* c */ -- d\n")
            .refuse_if_unterminated()
            .is_ok());
    }

    #[test]
    fn an_empty_input_produces_an_empty_text() {
        assert_eq!(text_of(""), "");
    }

    /// The parsing scan keeps every offset, so a parser complaint still points
    /// at the byte the caller wrote.
    #[test]
    fn expanding_a_conditional_comment_keeps_the_byte_length() {
        for sql in [
            "SELECT 1",
            "SELECT /*!40001 SQL_NO_CACHE */ 1",
            "SELECT /*M!100301 SQL_NO_CACHE */ 1",
            "SELECT 'olá' /*M! ,2 */ FROM t",
            "SELECT /* plain */ 1 -- tail\n",
        ] {
            assert_eq!(
                expand_conditional_comments(sql).len(),
                sql.len(),
                "input {sql:?}"
            );
        }
    }

    /// Both introducers this server honours are expanded, and the version
    /// digits go with the introducer they belong to.
    ///
    /// The parser crate expands only the first of the two, which is what let a
    /// file-reading call written inside the second one reach the server while
    /// staying out of the tree every refusal walks.
    #[test]
    fn both_conditional_introducers_leave_their_body_as_code() {
        for sql in [
            "SELECT 1 /*!100000 ,2 */",
            "SELECT 1 /*M!100000 ,2 */",
            "SELECT 1 /*m!100000 ,2 */",
            "SELECT 1 /*M! ,2 */",
        ] {
            let expanded = expand_conditional_comments(sql);
            assert!(expanded.contains(",2"), "input {sql:?} gave {expanded:?}");
            assert!(!expanded.contains("/*"), "input {sql:?}");
            assert!(!expanded.contains("*/"), "input {sql:?}");
            assert!(!expanded.contains('!'), "input {sql:?}");
            assert!(
                !expanded.contains("100000"),
                "the version gate is punctuation, not code: {expanded:?}"
            );
        }
    }

    /// Data reaches the parser exactly as it arrived, because a literal with
    /// its quotes replaced by spaces is no longer a statement anybody can read.
    #[test]
    fn the_parsing_scan_hands_back_data_and_commentary_untouched() {
        for sql in [
            "SELECT '/*M!100000 hidden */' AS note",
            "SELECT `/*M!100000`",
            "SELECT 1 /* /*M!100000 hidden */",
            "SELECT 1 -- /*M!100000 hidden\n",
            "SELECT 1 # /*M!100000 hidden",
        ] {
            assert_eq!(expand_conditional_comments(sql), sql, "input {sql:?}");
        }
    }

    /// The two scans answer different questions and must not be swapped.
    ///
    /// The textual one exists so a comparison cannot read data as code, and the
    /// parsing one exists so the tree is the statement the server will run.
    #[test]
    fn the_two_scans_agree_on_the_conditional_body_and_on_nothing_else() {
        let sql = "SELECT 'x' /*M!100000 ,LOAD_FILE(1) */";
        let blanked = text_of(sql);
        let expanded = expand_conditional_comments(sql);

        assert!(blanked.contains("LOAD_FILE"), "got {blanked:?}");
        assert!(expanded.contains("LOAD_FILE"), "got {expanded:?}");
        assert!(
            !blanked.contains('x'),
            "the literal is data to a comparison"
        );
        assert!(expanded.contains("'x'"), "the literal is code to a parser");
    }
}