bashkit 0.10.0

Awesomely fast virtual sandbox with bash and file system
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
708
709
710
711
712
713
714
715
716
717
//! Dot-command dispatch.
//!
//! We support a deliberately small subset of `sqlite3` shell dot-commands —
//! the ones that actually make sense in a sandboxed, non-interactive context:
//!
//! | Command       | Semantics                                                |
//! |---------------|----------------------------------------------------------|
//! | `.help`       | List supported commands.                                 |
//! | `.quit`/`.exit` | End execution.                                         |
//! | `.tables`     | List tables in the main schema.                          |
//! | `.schema [t]` | Print CREATE TABLE statements (optional table filter).   |
//! | `.headers on|off` | Toggle column headers.                               |
//! | `.mode <m>`   | Switch output mode (list/csv/tabs/line/box/json/markdown/column). |
//! | `.separator <s>` | Set the field separator for list/csv modes.           |
//! | `.nullvalue <s>` | Set the placeholder for NULL values.                  |
//! | `.dump`       | Emit the schema + data as `INSERT` statements.           |
//! | `.read <path>`| Execute a script from the VFS.                           |
//! | `.indexes [t]`| List indexes (optionally filtered by table).             |
//!
//! Anything not in this table returns a `BadCommand` error so the user gets
//! actionable feedback rather than a silent no-op.

use std::path::PathBuf;

use turso_core::Value;

use super::engine::{Deadline, QueryLimits, SqliteEngine};
use super::formatter::{OutputMode, OutputOpts};
use super::parser::tokenize_dot;

/// Outcome of running a dot-command.
#[derive(Debug)]
pub(super) enum DotOutcome {
    /// Command produced output for the user.
    Stdout(String),
    /// Command modified `OutputOpts` in place; no stdout.
    Configured,
    /// Command requests early termination (`.quit`, `.exit`).
    Quit,
    /// Command requests evaluation of additional script text from a VFS path.
    /// The caller (builtin) executes it against the same engine.
    Read(PathBuf),
}

#[derive(Debug, thiserror::Error)]
pub(super) enum DotError {
    #[error("unknown dot-command: .{0}")]
    BadCommand(String),
    #[error("usage: .{0} {1}")]
    Usage(&'static str, &'static str),
    #[error("invalid value for .{cmd}: {value}")]
    InvalidValue { cmd: &'static str, value: String },
    #[error("sqlite engine error: {0}")]
    Engine(String),
    #[error("sqlite output exceeds byte cap ({0} > {1})")]
    OutputCap(usize, usize),
}

const HELP_TEXT: &str = concat!(
    ".help                   Show this message\n",
    ".quit / .exit           End execution\n",
    ".tables                 List tables\n",
    ".schema [TABLE]         Show CREATE statements\n",
    ".indexes [TABLE]        List indexes\n",
    ".headers on|off         Toggle column headers\n",
    ".mode MODE              Set output mode (list, csv, tabs, line, box,\n",
    "                        column, json, markdown)\n",
    ".separator SEP          Set output separator\n",
    ".nullvalue STR          Set NULL placeholder\n",
    ".dump                   Dump schema + data as SQL\n",
    ".read PATH              Execute SQL from a VFS file\n",
);

/// Dispatch a dot-command line.
///
/// `max_output_bytes` is the *remaining* output budget for the current
/// invocation. `.dump` enforces this cumulatively across schema and all
/// table rows so memory growth is bounded during construction, not only
/// after the full string is returned to the caller.
pub(super) fn dispatch(
    line: &str,
    engine: &SqliteEngine,
    opts: &mut OutputOpts,
    deadline: Deadline,
    limits: QueryLimits,
    max_output_bytes: usize,
) -> Result<DotOutcome, DotError> {
    let (name, args) = tokenize_dot(line);
    match name.as_str() {
        "help" | "h" | "?" => Ok(DotOutcome::Stdout(HELP_TEXT.to_string())),
        "quit" | "exit" => Ok(DotOutcome::Quit),
        "headers" | "header" => set_headers(args, opts).map(|_| DotOutcome::Configured),
        "mode" => set_mode(args, opts).map(|_| DotOutcome::Configured),
        "separator" | "sep" => set_separator(args, opts).map(|_| DotOutcome::Configured),
        "nullvalue" | "null" => set_null(args, opts).map(|_| DotOutcome::Configured),
        "tables" => tables(args, engine, opts, deadline, limits).map(DotOutcome::Stdout),
        "schema" => schema(args, engine, deadline, limits).map(DotOutcome::Stdout),
        "indexes" | "indices" => {
            indexes(args, engine, opts, deadline, limits).map(DotOutcome::Stdout)
        }
        "dump" => dump(engine, deadline, limits, max_output_bytes).map(DotOutcome::Stdout),
        "read" => {
            let path = args
                .into_iter()
                .next()
                .ok_or(DotError::Usage("read", "PATH"))?;
            Ok(DotOutcome::Read(PathBuf::from(path)))
        }
        other => Err(DotError::BadCommand(other.to_string())),
    }
}

fn set_headers(args: Vec<String>, opts: &mut OutputOpts) -> Result<(), DotError> {
    let v = args
        .into_iter()
        .next()
        .ok_or(DotError::Usage("headers", "on|off"))?;
    let lower = v.to_ascii_lowercase();
    opts.headers = match lower.as_str() {
        "on" | "1" | "true" | "yes" => true,
        "off" | "0" | "false" | "no" => false,
        _ => {
            return Err(DotError::InvalidValue {
                cmd: "headers",
                value: v,
            });
        }
    };
    Ok(())
}

fn set_mode(args: Vec<String>, opts: &mut OutputOpts) -> Result<(), DotError> {
    let v = args
        .into_iter()
        .next()
        .ok_or(DotError::Usage("mode", "MODE"))?;
    let mode = OutputMode::parse(&v).ok_or(DotError::InvalidValue {
        cmd: "mode",
        value: v.clone(),
    })?;
    opts.mode = mode;
    // sqlite3 also flips the separator for csv/tabs to a sensible default,
    // and switching back to list mode restores `|` only if the previous mode
    // had clobbered it (otherwise we keep whatever the user picked).
    match mode {
        OutputMode::Csv => opts.separator = ",".to_string(),
        OutputMode::Tabs => opts.separator = "\t".to_string(),
        OutputMode::List if opts.separator == "," || opts.separator == "\t" => {
            opts.separator = "|".to_string();
        }
        _ => {}
    }
    Ok(())
}

fn set_separator(args: Vec<String>, opts: &mut OutputOpts) -> Result<(), DotError> {
    let v = args
        .into_iter()
        .next()
        .ok_or(DotError::Usage("separator", "SEP"))?;
    opts.separator = decode_escapes(&v);
    Ok(())
}

fn set_null(args: Vec<String>, opts: &mut OutputOpts) -> Result<(), DotError> {
    let v = args.into_iter().next().unwrap_or_default();
    opts.null_text = v;
    Ok(())
}

/// Decode backslash escapes in a separator (e.g. `\t`, `\n`).
fn decode_escapes(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\\'
            && let Some(&next) = chars.peek()
        {
            chars.next();
            match next {
                't' => out.push('\t'),
                'n' => out.push('\n'),
                'r' => out.push('\r'),
                '0' => out.push('\0'),
                '\\' => out.push('\\'),
                other => {
                    out.push('\\');
                    out.push(other);
                }
            }
            continue;
        }
        out.push(c);
    }
    out
}

fn tables(
    args: Vec<String>,
    engine: &SqliteEngine,
    opts: &OutputOpts,
    deadline: Deadline,
    limits: QueryLimits,
) -> Result<String, DotError> {
    let pattern = args.into_iter().next();
    let sql = match pattern {
        Some(p) => format!(
            "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '{}' ORDER BY name",
            p.replace('\'', "''")
        ),
        None => "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name".to_string(),
    };
    let outcome = engine
        .execute(&sql, deadline, limits)
        .map_err(DotError::Engine)?;
    let mut names = Vec::new();
    for row in &outcome.rows {
        if let Some(Value::Text(t)) = row.first() {
            names.push(t.as_str().to_string());
        }
    }
    if names.is_empty() {
        return Ok(String::new());
    }
    // sqlite3 prints tables in a column-wrapped layout. We emit them one per
    // line for ergonomics inside scripts; pipe to `column` if you want grids.
    let _ = opts; // keep signature stable for future formatting toggles
    let mut out = names.join("\n");
    out.push('\n');
    Ok(out)
}

fn schema(
    args: Vec<String>,
    engine: &SqliteEngine,
    deadline: Deadline,
    limits: QueryLimits,
) -> Result<String, DotError> {
    let pattern = args.into_iter().next();
    let sql = match pattern {
        Some(p) => format!(
            "SELECT sql FROM sqlite_master WHERE name LIKE '{}' AND sql IS NOT NULL ORDER BY name",
            p.replace('\'', "''")
        ),
        None => "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY name".to_string(),
    };
    let outcome = engine
        .execute(&sql, deadline, limits)
        .map_err(DotError::Engine)?;
    let mut out = String::new();
    for row in &outcome.rows {
        if let Some(Value::Text(t)) = row.first() {
            out.push_str(t.as_str());
            out.push_str(";\n");
        }
    }
    Ok(out)
}

fn indexes(
    args: Vec<String>,
    engine: &SqliteEngine,
    _opts: &OutputOpts,
    deadline: Deadline,
    limits: QueryLimits,
) -> Result<String, DotError> {
    let pattern = args.into_iter().next();
    let sql = match pattern {
        Some(p) => format!(
            "SELECT name FROM sqlite_master WHERE type='index' AND tbl_name LIKE '{}' ORDER BY name",
            p.replace('\'', "''")
        ),
        None => "SELECT name FROM sqlite_master WHERE type='index' ORDER BY name".to_string(),
    };
    let outcome = engine
        .execute(&sql, deadline, limits)
        .map_err(DotError::Engine)?;
    let mut out = String::new();
    for row in &outcome.rows {
        if let Some(Value::Text(t)) = row.first() {
            out.push_str(t.as_str());
            out.push('\n');
        }
    }
    Ok(out)
}

/// Append `chunk` to `buf`, returning `Err(OutputCap)` if doing so would
/// exceed `max`. This enforces the output budget *during* construction so
/// memory never grows beyond the cap even for large multi-table dumps.
/// THREAT[TM-DOS-091]: cumulative `.dump` output cap enforced here.
fn bounded_append(buf: &mut String, chunk: &str, max: usize) -> Result<(), DotError> {
    let next = buf.len().saturating_add(chunk.len());
    if next > max {
        return Err(DotError::OutputCap(next, max));
    }
    buf.push_str(chunk);
    Ok(())
}

/// Emit `BEGIN; <CREATE TABLE>...; <INSERT INTO ... VALUES (...)>; COMMIT;`.
/// This matches sqlite3's `.dump` for tables; views/triggers/indexes only get
/// their CREATE statement, no rows. Blob literals are emitted as `X'..'`.
///
/// `max_output_bytes` is the remaining output budget for the invocation.
/// The cap is applied cumulatively across schema lines and every row from
/// every table — construction stops as soon as the budget would be exceeded,
/// preventing unbounded memory growth from large multi-table databases.
fn dump(
    engine: &SqliteEngine,
    deadline: Deadline,
    limits: QueryLimits,
    max_output_bytes: usize,
) -> Result<String, DotError> {
    let mut out = String::new();
    bounded_append(
        &mut out,
        "PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n",
        max_output_bytes,
    )?;

    // Schema first.
    let schema_outcome = engine
        .execute(
            "SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY rowid",
            deadline,
            limits,
        )
        .map_err(DotError::Engine)?;
    for row in &schema_outcome.rows {
        if let Some(Value::Text(sql)) = row.get(2) {
            bounded_append(&mut out, sql.as_str(), max_output_bytes)?;
            bounded_append(&mut out, ";\n", max_output_bytes)?;
        }
    }

    // Then data, table by table.
    let tables_outcome = engine
        .execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
            deadline,
            limits,
        )
        .map_err(DotError::Engine)?;
    for row in &tables_outcome.rows {
        let Some(Value::Text(t)) = row.first() else {
            continue;
        };
        let name = t.as_str().to_string();
        let quoted = name.replace('"', "\"\"");
        let sql = format!("SELECT * FROM \"{quoted}\"");
        let data = engine
            .execute(&sql, deadline, limits)
            .map_err(DotError::Engine)?;
        for data_row in &data.rows {
            let values: Vec<String> = data_row.iter().map(format_sql_literal).collect();
            let line = format!("INSERT INTO \"{}\" VALUES({});\n", quoted, values.join(","));
            bounded_append(&mut out, &line, max_output_bytes)?;
        }
    }

    bounded_append(&mut out, "COMMIT;\n", max_output_bytes)?;
    Ok(out)
}

fn format_sql_literal(v: &Value) -> String {
    match v {
        Value::Null => "NULL".to_string(),
        Value::Numeric(_) => format!("{v}"),
        Value::Text(t) => {
            let escaped = t.as_str().replace('\'', "''");
            format!("'{escaped}'")
        }
        Value::Blob(b) => {
            let mut hex = String::with_capacity(b.len() * 2 + 3);
            hex.push_str("X'");
            for byte in b {
                use std::fmt::Write as _;
                let _ = write!(hex, "{byte:02X}");
            }
            hex.push('\'');
            hex
        }
    }
}

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

    fn opts() -> OutputOpts {
        OutputOpts::default()
    }

    fn mk_engine() -> SqliteEngine {
        SqliteEngine::open_pure_memory().expect("open in-mem")
    }

    fn no_deadline() -> Deadline {
        // Tests run instantly; an "unlimited" deadline is the only sensible
        // choice so a slow CI host doesn't flake.
        Deadline::new(std::time::Duration::ZERO)
    }

    fn unlimited_limits() -> QueryLimits {
        QueryLimits {
            max_rows: usize::MAX,
            max_value_bytes: usize::MAX,
            max_result_bytes: usize::MAX,
        }
    }

    fn dispatch_t(
        line: &str,
        engine: &SqliteEngine,
        opts: &mut OutputOpts,
    ) -> Result<DotOutcome, DotError> {
        dispatch(
            line,
            engine,
            opts,
            no_deadline(),
            unlimited_limits(),
            usize::MAX,
        )
    }

    #[test]
    fn help_returns_text() {
        let engine = mk_engine();
        let mut o = opts();
        let r = dispatch_t(".help", &engine, &mut o).unwrap();
        match r {
            DotOutcome::Stdout(s) => assert!(s.contains(".tables")),
            _ => panic!("expected stdout"),
        }
    }

    #[test]
    fn unknown_command_errors() {
        let engine = mk_engine();
        let mut o = opts();
        let err = dispatch_t(".doesnotexist", &engine, &mut o).unwrap_err();
        assert!(matches!(err, DotError::BadCommand(_)));
    }

    #[test]
    fn headers_toggle() {
        let engine = mk_engine();
        let mut o = opts();
        dispatch_t(".headers on", &engine, &mut o).unwrap();
        assert!(o.headers);
        dispatch_t(".headers off", &engine, &mut o).unwrap();
        assert!(!o.headers);
    }

    #[test]
    fn headers_invalid() {
        let engine = mk_engine();
        let mut o = opts();
        let err = dispatch_t(".headers maybe", &engine, &mut o).unwrap_err();
        assert!(matches!(err, DotError::InvalidValue { cmd: "headers", .. }));
    }

    #[test]
    fn headers_missing_arg() {
        let engine = mk_engine();
        let mut o = opts();
        let err = dispatch_t(".headers", &engine, &mut o).unwrap_err();
        assert!(matches!(err, DotError::Usage("headers", _)));
    }

    #[test]
    fn mode_changes_separator_for_csv() {
        let engine = mk_engine();
        let mut o = opts();
        dispatch_t(".mode csv", &engine, &mut o).unwrap();
        assert_eq!(o.separator, ",");
        dispatch_t(".mode tabs", &engine, &mut o).unwrap();
        assert_eq!(o.separator, "\t");
        dispatch_t(".mode list", &engine, &mut o).unwrap();
        assert_eq!(o.separator, "|");
    }

    #[test]
    fn mode_invalid() {
        let engine = mk_engine();
        let mut o = opts();
        let err = dispatch_t(".mode bogus", &engine, &mut o).unwrap_err();
        assert!(matches!(err, DotError::InvalidValue { cmd: "mode", .. }));
    }

    #[test]
    fn separator_decodes_escapes() {
        let engine = mk_engine();
        let mut o = opts();
        dispatch_t(".separator '\\t'", &engine, &mut o).unwrap();
        assert_eq!(o.separator, "\t");
        dispatch_t(".separator '\\n'", &engine, &mut o).unwrap();
        assert_eq!(o.separator, "\n");
    }

    #[test]
    fn nullvalue_sets_placeholder() {
        let engine = mk_engine();
        let mut o = opts();
        dispatch_t(".nullvalue NIL", &engine, &mut o).unwrap();
        assert_eq!(o.null_text, "NIL");
        // Empty arg → empty placeholder
        dispatch_t(".nullvalue", &engine, &mut o).unwrap();
        assert_eq!(o.null_text, "");
    }

    #[test]
    fn tables_lists_existing() {
        let engine = mk_engine();
        engine
            .execute("CREATE TABLE foo(a)", no_deadline(), unlimited_limits())
            .unwrap();
        engine
            .execute("CREATE TABLE bar(b)", no_deadline(), unlimited_limits())
            .unwrap();
        let mut o = opts();
        let DotOutcome::Stdout(s) = dispatch_t(".tables", &engine, &mut o).unwrap() else {
            panic!("expected stdout");
        };
        assert!(s.contains("foo"));
        assert!(s.contains("bar"));
    }

    #[test]
    fn tables_with_pattern() {
        let engine = mk_engine();
        engine
            .execute("CREATE TABLE foo(a)", no_deadline(), unlimited_limits())
            .unwrap();
        engine
            .execute("CREATE TABLE bar(b)", no_deadline(), unlimited_limits())
            .unwrap();
        let mut o = opts();
        let DotOutcome::Stdout(s) = dispatch_t(".tables foo", &engine, &mut o).unwrap() else {
            panic!("expected stdout");
        };
        assert!(s.contains("foo"));
        assert!(!s.contains("bar"));
    }

    #[test]
    fn tables_empty_db() {
        let engine = mk_engine();
        let mut o = opts();
        let DotOutcome::Stdout(s) = dispatch_t(".tables", &engine, &mut o).unwrap() else {
            panic!("expected stdout");
        };
        assert_eq!(s, "");
    }

    #[test]
    fn schema_returns_create() {
        let engine = mk_engine();
        engine
            .execute(
                "CREATE TABLE foo(a INTEGER, b TEXT)",
                no_deadline(),
                unlimited_limits(),
            )
            .unwrap();
        let mut o = opts();
        let DotOutcome::Stdout(s) = dispatch_t(".schema", &engine, &mut o).unwrap() else {
            panic!("expected stdout");
        };
        assert!(s.contains("CREATE TABLE foo"));
    }

    #[test]
    fn dump_round_trips() {
        let engine = mk_engine();
        engine
            .execute(
                "CREATE TABLE t(x INTEGER, y TEXT)",
                no_deadline(),
                unlimited_limits(),
            )
            .unwrap();
        engine
            .execute(
                "INSERT INTO t VALUES (1, 'hello'), (2, 'O''Brien')",
                no_deadline(),
                unlimited_limits(),
            )
            .unwrap();
        let mut o = opts();
        let DotOutcome::Stdout(s) = dispatch_t(".dump", &engine, &mut o).unwrap() else {
            panic!("expected stdout");
        };
        assert!(s.contains("BEGIN TRANSACTION;"));
        assert!(s.contains("CREATE TABLE t"));
        assert!(s.contains("INSERT INTO \"t\" VALUES(1,'hello')"));
        assert!(s.contains("'O''Brien'"));
        assert!(s.contains("COMMIT;"));
    }

    /// `.dump` must stop and return an error when the cumulative output would
    /// exceed the configured output cap, preventing unbounded memory growth
    /// across many tables (DeepSec issue #1869).
    #[test]
    fn dump_respects_output_cap() {
        let engine = mk_engine();
        // Two tables with several rows of text data.
        engine
            .execute("CREATE TABLE a(v TEXT)", no_deadline(), unlimited_limits())
            .unwrap();
        engine
            .execute("CREATE TABLE b(v TEXT)", no_deadline(), unlimited_limits())
            .unwrap();
        for i in 0..10 {
            engine
                .execute(
                    &format!(
                        "INSERT INTO a VALUES ('row-{i:04}-padding-aaaaaaaaaaaaaaaaaaaaaaaaa')"
                    ),
                    no_deadline(),
                    unlimited_limits(),
                )
                .unwrap();
            engine
                .execute(
                    &format!(
                        "INSERT INTO b VALUES ('row-{i:04}-padding-bbbbbbbbbbbbbbbbbbbbbbbbb')"
                    ),
                    no_deadline(),
                    unlimited_limits(),
                )
                .unwrap();
        }

        // A tiny cap that the dump cannot fit into, ensuring the cap fires
        // mid-construction rather than only after the full string is built.
        let tiny_cap: usize = 100;
        let mut o = opts();
        let err = dispatch(
            ".dump",
            &engine,
            &mut o,
            no_deadline(),
            unlimited_limits(),
            tiny_cap,
        )
        .unwrap_err();

        assert!(
            matches!(err, DotError::OutputCap(_, _)),
            "expected OutputCap, got: {err}"
        );
        // Error message must not contain debug shapes — plain text only.
        let msg = err.to_string();
        assert!(
            !msg.contains("{:?}"), // debug-ok: testing that debug shapes are absent from error output
            "debug shape leaked into error: {msg}"
        );
        assert!(
            msg.len() <= 1024,
            "error message too long ({} bytes)",
            msg.len()
        );
    }

    /// `.dump` on an empty database still produces the PRAGMA/BEGIN/COMMIT
    /// boilerplate even with a very tight cap that fits it.
    #[test]
    fn dump_empty_db_under_cap() {
        let engine = mk_engine();
        let mut o = opts();
        // "PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\nCOMMIT;\n" is ~50 bytes.
        let DotOutcome::Stdout(s) = dispatch(
            ".dump",
            &engine,
            &mut o,
            no_deadline(),
            unlimited_limits(),
            4096,
        )
        .unwrap() else {
            panic!("expected stdout");
        };
        assert!(s.starts_with("PRAGMA foreign_keys=OFF;"));
        assert!(s.ends_with("COMMIT;\n"));
    }

    #[test]
    fn read_returns_path() {
        let engine = mk_engine();
        let mut o = opts();
        let DotOutcome::Read(p) = dispatch_t(".read /tmp/x.sql", &engine, &mut o).unwrap() else {
            panic!("expected read");
        };
        assert_eq!(p.to_string_lossy(), "/tmp/x.sql");
    }

    #[test]
    fn read_without_path_errors() {
        let engine = mk_engine();
        let mut o = opts();
        let err = dispatch_t(".read", &engine, &mut o).unwrap_err();
        assert!(matches!(err, DotError::Usage("read", _)));
    }

    #[test]
    fn quit_signals_quit() {
        let engine = mk_engine();
        let mut o = opts();
        let r = dispatch_t(".quit", &engine, &mut o).unwrap();
        assert!(matches!(r, DotOutcome::Quit));
        let r = dispatch_t(".exit", &engine, &mut o).unwrap();
        assert!(matches!(r, DotOutcome::Quit));
    }
}