fastshell 0.3.7

Lightweight Bash + Python runtime SDK for mobile AI agents
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
// Copyright (c) 2025 xiefujin <490021684@qq.com>
// Licensed under Apache-2.0, see LICENSE file for full license terms.

use crate::shell::{CommandOutput, Shell};

const SQLITE3_HELP_TEXT: &str = "\
sqlite3: SQLite command-line tool
Usage: sqlite3 [OPTIONS] DATABASE [SQL]
Options:
  -csv               Set output mode to CSV
  -header, -headers  Turn headers on
  -line              Line output mode
  -h, --help         Show this help message
Dot-commands:
  .tables   List tables
  .schema   Show CREATE statements
  .help     Show dot-command help
  .quit     Exit
";

impl Shell {
    pub fn cmd_sqlite3(&self, args: &[&str], stdin: Option<&str>) -> CommandOutput {
        if args.contains(&"-h") || args.contains(&"--help") {
            return CommandOutput::success(SQLITE3_HELP_TEXT.to_string());
        }
        let mut db_path: Option<String> = None;
        let mut sql: Option<String> = None;
        let mut dot_command: Option<String> = None;
        let mut csv_mode = false;
        let mut header_mode = false;

        let mut i = 0;
        while i < args.len() {
            match args[i] {
                "-csv" => csv_mode = true,
                "-header" | "-headers" => header_mode = true,
                "-line" | "-column" | "-list" | "-separator" => {} // accepted
                "--version" | "-version" => {
                    return CommandOutput::success(format!("{}\n", rusqlite::version()));
                }
                arg if !arg.starts_with('-') && !arg.starts_with('.') => {
                    if db_path.is_none() {
                        db_path = Some(arg.to_string());
                    } else {
                        // Accumulate SQL tokens (handles `sqlite3 db.sqlite SELECT * FROM users`)
                        match sql {
                            Some(ref mut s) => {
                                s.push(' ');
                                s.push_str(arg);
                            }
                            None => sql = Some(arg.to_string()),
                        }
                    }
                }
                arg if arg.starts_with('.') && dot_command.is_none() => {
                    // Dot commands take the rest of the line as arguments.
                    dot_command = Some(args[i..].join(" "));
                    break;
                }
                _ => crate::warn!("sqlite3: warning: unsupported option '{}'", args[i]),
            }
            i += 1;
        }

        let db_path = match db_path {
            Some(p) => p,
            None => {
                return CommandOutput::error(
                    "sqlite3: missing database path\nUsage: sqlite3 <database> [query]\n"
                        .to_string(),
                    1,
                )
            }
        };

        // `:memory:` is an in-memory DB, not a sandbox file.
        let abs_path = if db_path == ":memory:" {
            std::path::PathBuf::from(":memory:")
        } else {
            match self.vfs.resolve(&db_path, &self.cwd) {
                Ok(p) => p,
                Err(e) => return CommandOutput::error(format!("sqlite3: {}\n", e), 1),
            }
        };

        // Handle dot-commands
        if let Some(ref dc) = dot_command {
            return self.sqlite3_dot_command(&abs_path, dc);
        }

        // Handle direct SQL or stdin
        let sql_str = if let Some(ref s) = sql {
            s.clone()
        } else if let Some(stdin_data) = stdin {
            stdin_data.to_string()
        } else {
            // Try reading SQL from args if no stdin
            let remaining: Vec<&str> = args
                .iter()
                .skip_while(|a| !a.starts_with('-') || **a == db_path)
                .copied()
                .collect();
            if remaining.len() > 1 {
                remaining[1..].join(" ")
            } else {
                return CommandOutput::success(format!(
                    "SQLite version 3.45.3 (fastshell)\nEnter \".help\" for usage hints.\nConnected to {}\n",
                    db_path
                ));
            }
        };

        if sql_str.trim().is_empty() {
            return CommandOutput::success(String::new());
        }

        self.sqlite3_execute(&abs_path, &sql_str, csv_mode, header_mode)
    }

    fn sqlite3_dot_command(&self, db_path: &std::path::Path, cmd: &str) -> CommandOutput {
        let conn = match rusqlite::Connection::open(db_path) {
            Ok(c) => c,
            Err(e) => return CommandOutput::error(format!("sqlite3: {}\n", e), 1),
        };
        let mut parts = cmd.split_whitespace();
        let head = parts.next().unwrap_or("");
        let rest: Vec<&str> = parts.collect();

        match head {
            ".tables" | ".table" => {
                match conn
                    .prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
                {
                    Ok(mut stmt) => {
                        let mut output = String::new();
                        let rows = stmt.query_map([], |row| row.get::<_, String>(0));
                        match rows {
                            Ok(mapped) => {
                                for name in mapped.flatten() {
                                    output.push_str(&name);
                                    output.push(' ');
                                }
                                output.push('\n');
                                CommandOutput::success(output)
                            }
                            Err(e) => CommandOutput::error(format!("sqlite3: {}\n", e), 1),
                        }
                    }
                    Err(e) => CommandOutput::error(format!("sqlite3: {}\n", e), 1),
                }
            }
            ".schema" => {
                let (sql, params): (&str, Vec<String>) = if let Some(t) = rest.first() {
                    (
                        "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL AND name = ?1 ORDER BY type, name",
                        vec![t.to_string()],
                    )
                } else {
                    (
                        "SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY type, name",
                        Vec::new(),
                    )
                };
                match conn.prepare(sql) {
                    Ok(mut stmt) => {
                        let mut output = String::new();
                        let rows = stmt
                            .query_map(rusqlite::params_from_iter(params.iter()), |row| {
                                row.get::<_, String>(0)
                            });
                        match rows {
                            Ok(mapped) => {
                                for sql in mapped.flatten() {
                                    output.push_str(&sql);
                                    output.push_str(";\n");
                                }
                                CommandOutput::success(output)
                            }
                            Err(e) => CommandOutput::error(format!("sqlite3: {}\n", e), 1),
                        }
                    }
                    Err(e) => CommandOutput::error(format!("sqlite3: {}\n", e), 1),
                }
            }
            // `.mode` is accepted (output modes are selected via flags here).
            ".mode" => CommandOutput::success(String::new()),
            ".import" => {
                if rest.len() < 2 {
                    return CommandOutput::error(
                        "sqlite3: usage: .import FILE TABLE\n".to_string(),
                        1,
                    );
                }
                let (file, table) = (rest[0], rest[1]);
                let data = match self.vfs.read_to_string(file, &self.cwd) {
                    Ok(d) => d,
                    Err(e) => {
                        return CommandOutput::error(format!("sqlite3: {}: {}\n", file, e), 1)
                    }
                };
                let mut count = 0usize;
                for line in data.lines() {
                    if line.trim().is_empty() {
                        continue;
                    }
                    let vals: Vec<String> = line
                        .split(',')
                        .map(|v| format!("'{}'", v.trim().replace('\'', "''")))
                        .collect();
                    let sql = format!("INSERT INTO {} VALUES ({})", table, vals.join(","));
                    if conn.execute(&sql, []).is_ok() {
                        count += 1;
                    }
                }
                CommandOutput::success(format!("{} rows imported\n", count))
            }
            ".help" | ".h" => CommandOutput::success(
                ".tables          List tables\n\
                 .schema [TABLE]  Show CREATE statements\n\
                 .mode MODE       Accept output mode (no-op)\n\
                 .import F TABLE  Import a CSV file\n\
                 .help            Show this message\n\
                 .quit            Exit\n"
                    .to_string(),
            ),
            ".quit" | ".q" | ".exit" => CommandOutput::success(String::new()),
            ".dump" => {
                CommandOutput::error("sqlite3: .dump not fully implemented\n".to_string(), 1)
            }
            _ => CommandOutput::error(format!("sqlite3: unknown command: {}\n", cmd), 1),
        }
    }

    fn sqlite3_execute(
        &self,
        db_path: &std::path::Path,
        sql: &str,
        csv_mode: bool,
        header_mode: bool,
    ) -> CommandOutput {
        let conn = match rusqlite::Connection::open(db_path) {
            Ok(c) => c,
            Err(e) => return CommandOutput::error(format!("sqlite3: {}\n", e), 1),
        };

        let mut output = String::new();
        let mut stderr = String::new();

        let statements: Vec<&str> = sql
            .split(';')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();

        for stmt_str in &statements {
            let sql_upper = stmt_str.trim().to_uppercase();

            if sql_upper.starts_with("SELECT")
                || sql_upper.starts_with("PRAGMA")
                || sql_upper.starts_with("EXPLAIN")
                || sql_upper.starts_with("WITH")
            {
                match conn.prepare(stmt_str) {
                    Ok(mut stmt) => {
                        let col_count = stmt.column_count();
                        let col_names: Vec<String> = (0..col_count)
                            .map(|i| stmt.column_name(i).unwrap_or("?").to_string())
                            .collect();

                        if header_mode && !col_names.is_empty() {
                            if csv_mode {
                                output.push_str(&col_names.join(","));
                            } else {
                                output.push_str(&col_names.join("|"));
                            }
                            output.push('\n');
                        }

                        let rows = stmt.query_map([], |row| {
                            let mut vals = Vec::new();
                            for i in 0..col_count {
                                let val: String = match row.get_ref(i) {
                                    Ok(rusqlite::types::ValueRef::Null) => String::new(),
                                    Ok(rusqlite::types::ValueRef::Integer(n)) => n.to_string(),
                                    Ok(rusqlite::types::ValueRef::Real(f)) => f.to_string(),
                                    Ok(rusqlite::types::ValueRef::Text(t)) => {
                                        String::from_utf8_lossy(t).to_string()
                                    }
                                    Ok(rusqlite::types::ValueRef::Blob(b)) => {
                                        format!(
                                            "x'{}'",
                                            b.iter()
                                                .map(|byte| format!("{:02x}", byte))
                                                .collect::<String>()
                                        )
                                    }
                                    Err(_) => "ERROR".to_string(),
                                };
                                vals.push(val);
                            }
                            Ok(vals)
                        });

                        match rows {
                            Ok(mapped) => {
                                for row in mapped.flatten() {
                                    if csv_mode {
                                        output.push_str(&row.join(","));
                                    } else {
                                        output.push_str(&row.join("|"));
                                    }
                                    output.push('\n');
                                }
                            }
                            Err(e) => {
                                stderr.push_str(&format!("sqlite3: {}\n", e));
                            }
                        }
                    }
                    Err(e) => {
                        stderr.push_str(&format!("sqlite3: {}\n", e));
                    }
                }
            } else {
                match conn.execute_batch(stmt_str) {
                    Ok(_) => {}
                    Err(e) => {
                        stderr.push_str(&format!("sqlite3: {}\n", e));
                    }
                }
            }
        }

        if stderr.is_empty() {
            CommandOutput::success(output)
        } else {
            let had_output = !output.is_empty();
            CommandOutput {
                stdout: output,
                stderr,
                exit_code: if had_output { 0 } else { 1 },
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vfs::Vfs;
    use std::fs;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static COUNTER: AtomicUsize = AtomicUsize::new(0);

    fn setup() -> Shell {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("fs_sqlite3_test_{}_{}", std::process::id(), n));
        let _ = fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir).unwrap();
        Shell::new(vfs)
    }

    #[test]
    fn test_sqlite3_create_and_select() {
        let shell = setup();
        shell.cmd_sqlite3(
            &[
                "test.db",
                "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
            ],
            None,
        );
        shell.cmd_sqlite3(&["test.db", "INSERT INTO users VALUES (1, 'Alice')"], None);
        shell.cmd_sqlite3(&["test.db", "INSERT INTO users VALUES (2, 'Bob')"], None);

        let out = shell.cmd_sqlite3(&["test.db", "SELECT * FROM users ORDER BY id"], None);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("Alice"));
        assert!(out.stdout.contains("Bob"));
        assert!(out.stdout.contains("1"));
        assert!(out.stdout.contains("2"));
    }

    #[test]
    fn test_sqlite3_dot_tables() {
        let shell = setup();
        shell.cmd_sqlite3(&["test.db", "CREATE TABLE users (id INTEGER)"], None);
        shell.cmd_sqlite3(&["test.db", "CREATE TABLE posts (id INTEGER)"], None);

        let out = shell.cmd_sqlite3(&["test.db", ".tables"], None);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("users"));
        assert!(out.stdout.contains("posts"));
    }

    #[test]
    fn test_sqlite3_dot_schema() {
        let shell = setup();
        shell.cmd_sqlite3(&["test.db", "CREATE TABLE t (a TEXT, b INTEGER)"], None);

        let out = shell.cmd_sqlite3(&["test.db", ".schema"], None);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.to_uppercase().contains("CREATE TABLE"));
    }

    #[test]
    fn test_sqlite3_dot_help() {
        let shell = setup();
        let out = shell.cmd_sqlite3(&["test.db", ".help"], None);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains(".tables"));
    }

    #[test]
    fn test_sqlite3_missing_db() {
        let shell = setup();
        let out = shell.cmd_sqlite3(&[], None);
        assert_ne!(out.exit_code, 0);
        assert!(out.stderr.contains("missing database path"));
    }

    #[test]
    fn test_sqlite3_csv_mode() {
        let shell = setup();
        shell.cmd_sqlite3(&["test.db", "CREATE TABLE t (x, y)"], None);
        shell.cmd_sqlite3(&["test.db", "INSERT INTO t VALUES ('a', 'b')"], None);

        let out = shell.cmd_sqlite3(&["-csv", "test.db", "SELECT * FROM t"], None);
        assert_eq!(out.exit_code, 0);
        assert_eq!(out.stdout.trim(), "a,b");
    }

    #[test]
    fn test_sqlite3_header_mode() {
        let shell = setup();
        shell.cmd_sqlite3(&["test.db", "CREATE TABLE t (col_a, col_b)"], None);
        shell.cmd_sqlite3(&["test.db", "INSERT INTO t VALUES ('x', 'y')"], None);

        let out = shell.cmd_sqlite3(&["-header", "test.db", "SELECT * FROM t"], None);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("col_a"));
        assert!(out.stdout.contains("col_b"));
    }

    #[test]
    fn test_sqlite3_pipe_sql() {
        let shell = setup();
        // Use stdin to pass SQL
        let out = shell.cmd_sqlite3(
            &["test.db"],
            Some("CREATE TABLE x (n INTEGER); INSERT INTO x VALUES (42); SELECT * FROM x"),
        );
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("42"));
    }

    #[test]
    fn test_sqlite3_multiple_statements() {
        let shell = setup();
        let out = shell.cmd_sqlite3(&["test.db", "CREATE TABLE m (v TEXT); INSERT INTO m VALUES ('hello'); INSERT INTO m VALUES ('world'); SELECT * FROM m"], None);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("hello"));
        assert!(out.stdout.contains("world"));
    }

    #[test]
    fn test_sqlite3_update_and_delete() {
        let shell = setup();
        shell.cmd_sqlite3(&["test.db", "CREATE TABLE d (id, val)"], None);
        shell.cmd_sqlite3(&["test.db", "INSERT INTO d VALUES (1, 'old')"], None);
        shell.cmd_sqlite3(&["test.db", "UPDATE d SET val='new' WHERE id=1"], None);

        let out = shell.cmd_sqlite3(&["test.db", "SELECT val FROM d WHERE id=1"], None);
        assert!(out.stdout.contains("new"));
        assert!(!out.stdout.contains("old"));

        shell.cmd_sqlite3(&["test.db", "DELETE FROM d WHERE id=1"], None);
        let out = shell.cmd_sqlite3(&["test.db", "SELECT count(*) FROM d"], None);
        assert!(out.stdout.contains("0"));
    }

    #[test]
    fn test_sqlite3_help() {
        let mut shell = setup();
        let out = shell.execute("sqlite3", &["-h"], None);
        assert_eq!(out.exit_code, 0);
        assert!(!out.stdout.is_empty());
    }

    #[test]
    fn test_sqlite3_help_long() {
        let mut shell = setup();
        let out = shell.execute("sqlite3", &["--help"], None);
        assert_eq!(out.exit_code, 0);
        assert!(!out.stdout.is_empty());
    }
}