tuible 0.0.2-alpha.1

A keyboard-driven database client for your terminal, built for both humans and AI agents.
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
use std::path::PathBuf;

use clap::{ArgAction, Args, Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(
    name = "tuible",
    version,
    about = "A keyboard-driven SQLite and DynamoDB client for humans and agents",
    long_about = "Browse SQLite or DynamoDB in an interactive terminal UI or run bounded, machine-readable one-shot commands. Connections open read-only unless write access is explicitly requested.",
    after_help = "Examples:\n  tuible\n  tuible profile work\n  tuible config --show\n  tuible demo --reset\n  tuible open app.sqlite\n  tuible query app.sqlite 'SELECT id, email FROM users LIMIT 10'\n  tuible dynamodb open --profile work --region eu-west-1\n  tuible dynamodb query users --key-condition 'pk = :pk' --values '{\":pk\":\"USER#42\"}' --profile work\n  tuible dynamodb get users '{\"pk\":\"USER#42\"}' --profile work"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Debug, Subcommand, PartialEq)]
pub enum Command {
    /// Launch the TUI against a bundled sample SQLite database.
    Demo {
        /// Recreate the sample database before launching.
        #[arg(long)]
        reset: bool,
    },
    /// Open a SQLite database in the TUI (read-only by default).
    Open {
        /// Path to an existing SQLite database.
        #[arg(value_name = "DATABASE")]
        database: PathBuf,
        /// Enable cell edits and write-capable SQL. Without this flag the database is enforced read-only.
        #[arg(long)]
        write: bool,
    },
    /// Open a saved connection profile from the XDG configuration file.
    Profile {
        /// Saved profile name.
        #[arg(value_name = "NAME")]
        name: String,
    },
    /// Print the XDG configuration path or the merged configuration.
    Config {
        /// Print the effective TOML configuration instead of only its path.
        #[arg(long)]
        show: bool,
    },
    /// List user tables as JSON.
    Tables {
        /// Path to an existing SQLite database.
        #[arg(value_name = "DATABASE")]
        database: PathBuf,
    },
    /// Describe a table as JSON.
    Schema {
        /// Path to an existing SQLite database.
        #[arg(value_name = "DATABASE")]
        database: PathBuf,
        /// Table to describe.
        #[arg(value_name = "TABLE")]
        table: String,
    },
    /// Run a read-only SQL statement and print bounded JSON output.
    Query {
        /// Path to an existing SQLite database.
        #[arg(value_name = "DATABASE")]
        database: PathBuf,
        /// One SQL statement to run.
        #[arg(value_name = "SQL", allow_hyphen_values = true)]
        sql: String,
        /// Stop reading after this many rows and set `truncated` in the JSON result.
        #[arg(long, default_value_t = 1_000, value_parser = positive_usize)]
        max_rows: usize,
    },
    /// Run SQL with write access and print JSON output.
    #[command(visible_alias = "exec")]
    Execute {
        /// Path to an existing SQLite database.
        #[arg(value_name = "DATABASE")]
        database: PathBuf,
        /// One SQL statement to run.
        #[arg(value_name = "SQL", allow_hyphen_values = true)]
        sql: String,
        /// Acknowledge that this command opens the database with write access.
        #[arg(long, action = ArgAction::SetTrue)]
        yes: bool,
        /// Maximum number of rows returned by statements with RETURNING.
        #[arg(long, default_value_t = 1_000, value_parser = positive_usize)]
        max_rows: usize,
    },
    /// Browse or operate on Amazon DynamoDB using the standard AWS credential chain.
    #[command(subcommand, visible_alias = "ddb")]
    Dynamodb(Box<DynamoCommand>),
}

#[derive(Debug, Clone, Args, PartialEq)]
pub struct DynamoConnectionArgs {
    /// AWS shared-config profile (supports SSO profiles after `aws sso login`).
    #[arg(long, env = "AWS_PROFILE")]
    pub profile: Option<String>,
    /// AWS region. Falls back to the standard AWS region provider chain.
    #[arg(long, env = "AWS_REGION")]
    pub region: Option<String>,
    /// Override the DynamoDB endpoint, for LocalStack, VPC proxies, or DynamoDB Local.
    #[arg(long)]
    pub endpoint_url: Option<String>,
    /// Use DynamoDB Local at http://localhost:8000 with disposable credentials.
    #[arg(long)]
    pub local: bool,
}

#[derive(Debug, Subcommand, PartialEq)]
pub enum DynamoCommand {
    /// Open DynamoDB in the interactive TUI (read-only by default).
    Open {
        #[command(flatten)]
        connection: DynamoConnectionArgs,
        /// Allow PartiQL writes. Inline item editing remains disabled.
        #[arg(long)]
        write: bool,
    },
    /// List DynamoDB tables as JSON.
    Tables {
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Describe keys, indexes, size, and status for a table.
    #[command(visible_alias = "schema")]
    Describe {
        /// DynamoDB table name.
        #[arg(value_name = "TABLE")]
        table: String,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Scan one bounded page, returning natural and lossless DynamoDB JSON.
    Scan {
        /// DynamoDB table name.
        #[arg(value_name = "TABLE")]
        table: String,
        /// Optional filter expression applied after scanning.
        #[arg(long, value_name = "EXPRESSION")]
        filter: Option<String>,
        /// Projection expression limiting returned attributes.
        #[arg(long, value_name = "EXPRESSION")]
        projection: Option<String>,
        /// JSON expression values, or @file.
        #[arg(long, value_name = "JSON")]
        values: Option<String>,
        /// JSON expression names, or @file.
        #[arg(long, value_name = "JSON")]
        names: Option<String>,
        /// Resume from `last_evaluated_key`, or use the typed key with --typed-json.
        #[arg(long, value_name = "JSON")]
        start_key: Option<String>,
        /// Maximum evaluated items for this request (DynamoDB may return fewer).
        #[arg(long, default_value_t = 100, value_parser = positive_usize)]
        limit: usize,
        /// Use strongly consistent reads.
        #[arg(long)]
        consistent_read: bool,
        /// Interpret expression values and start keys as AWS DynamoDB JSON.
        #[arg(long)]
        typed_json: bool,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Run a PartiQL statement. SELECT is read-only; writes require --yes.
    #[command(visible_alias = "sql")]
    Partiql {
        /// One DynamoDB PartiQL statement.
        #[arg(value_name = "STATEMENT", allow_hyphen_values = true)]
        statement: String,
        /// Positional PartiQL parameters as a JSON array, or @file.
        #[arg(long, value_name = "JSON")]
        parameters: Option<String>,
        /// Interpret parameters as AWS DynamoDB JSON values.
        #[arg(long)]
        typed_json: bool,
        /// Maximum SELECT items to return before marking the result truncated.
        #[arg(long, default_value_t = 1_000, value_parser = positive_usize)]
        max_rows: usize,
        /// Resume a previous PartiQL response from its `next_token`.
        #[arg(long)]
        next_token: Option<String>,
        /// Acknowledge that this statement may write data.
        #[arg(long, action = ArgAction::SetTrue)]
        yes: bool,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Get one item in both natural and lossless DynamoDB JSON.
    Get {
        /// DynamoDB table name.
        #[arg(value_name = "TABLE")]
        table: String,
        /// Plain JSON key, DynamoDB JSON with --typed-json, or @path/to/key.json.
        #[arg(value_name = "KEY")]
        key: String,
        /// Projection expression limiting returned attributes.
        #[arg(long, value_name = "EXPRESSION")]
        projection: Option<String>,
        /// JSON expression names used by the projection, or @file.
        #[arg(long, value_name = "JSON")]
        names: Option<String>,
        /// Use strongly consistent reads.
        #[arg(long)]
        consistent_read: bool,
        /// Interpret keys/items as AWS DynamoDB JSON (`{"pk":{"S":"value"}}`).
        #[arg(long)]
        typed_json: bool,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Query one bounded page, returning natural and lossless DynamoDB JSON.
    Query {
        /// DynamoDB table name.
        #[arg(value_name = "TABLE")]
        table: String,
        /// DynamoDB key condition expression, such as `pk = :pk AND begins_with(sk, :sk)`.
        #[arg(long, value_name = "EXPRESSION")]
        key_condition: String,
        /// Global or local secondary index name.
        #[arg(long)]
        index: Option<String>,
        /// Optional post-query filter expression.
        #[arg(long, value_name = "EXPRESSION")]
        filter: Option<String>,
        /// Projection expression limiting returned attributes.
        #[arg(long, value_name = "EXPRESSION")]
        projection: Option<String>,
        /// JSON expression values, for example '{":pk":"USER#42"}', or @file.
        #[arg(long, value_name = "JSON")]
        values: Option<String>,
        /// JSON expression names, for example '{"#status":"status"}', or @file.
        #[arg(long, value_name = "JSON")]
        names: Option<String>,
        /// Resume from `last_evaluated_key`, or use the typed key with --typed-json.
        #[arg(long, value_name = "JSON")]
        start_key: Option<String>,
        /// Maximum evaluated items for this request (DynamoDB may return fewer).
        #[arg(long, default_value_t = 100, value_parser = positive_usize)]
        limit: usize,
        /// Use strongly consistent reads (not supported on global secondary indexes).
        #[arg(long)]
        consistent_read: bool,
        /// Interpret expression values as AWS DynamoDB JSON.
        #[arg(long)]
        typed_json: bool,
        /// Return sort-key results in descending order.
        #[arg(long)]
        descending: bool,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Put a complete item from plain JSON or DynamoDB JSON.
    Put {
        /// DynamoDB table name.
        #[arg(value_name = "TABLE")]
        table: String,
        /// Plain JSON item, DynamoDB JSON with --typed-json, or @path/to/item.json.
        #[arg(value_name = "ITEM")]
        item: String,
        /// Optional condition expression, such as `attribute_not_exists(pk)`.
        #[arg(long, value_name = "EXPRESSION")]
        condition: Option<String>,
        /// JSON condition expression values, or @file.
        #[arg(long, value_name = "JSON")]
        values: Option<String>,
        /// JSON condition expression names, or @file.
        #[arg(long, value_name = "JSON")]
        names: Option<String>,
        /// Interpret the item as AWS DynamoDB JSON.
        #[arg(long)]
        typed_json: bool,
        /// Acknowledge that the item will be written.
        #[arg(long, action = ArgAction::SetTrue)]
        yes: bool,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
    /// Delete one item by key.
    Delete {
        /// DynamoDB table name.
        #[arg(value_name = "TABLE")]
        table: String,
        /// Plain JSON key, DynamoDB JSON with --typed-json, or @path/to/key.json.
        #[arg(value_name = "KEY")]
        key: String,
        /// Optional condition expression.
        #[arg(long, value_name = "EXPRESSION")]
        condition: Option<String>,
        /// JSON condition expression values, or @file.
        #[arg(long, value_name = "JSON")]
        values: Option<String>,
        /// JSON condition expression names, or @file.
        #[arg(long, value_name = "JSON")]
        names: Option<String>,
        /// Interpret the key as AWS DynamoDB JSON.
        #[arg(long)]
        typed_json: bool,
        /// Acknowledge that the item will be deleted.
        #[arg(long, action = ArgAction::SetTrue)]
        yes: bool,
        #[command(flatten)]
        connection: DynamoConnectionArgs,
    },
}

fn positive_usize(value: &str) -> Result<usize, String> {
    match value.parse() {
        Ok(value) if value > 0 => Ok(value),
        _ => Err("must be a positive integer".to_string()),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::unwrap_used)]

    use super::*;

    #[test]
    fn parses_demo_subcommand() {
        let cli = Cli::try_parse_from(["tuible", "demo"]).unwrap();
        assert_eq!(cli.command, Some(Command::Demo { reset: false }));
    }

    #[test]
    fn parses_read_only_open_by_default() {
        let cli = Cli::try_parse_from(["tuible", "open", "data.sqlite"]).unwrap();
        assert_eq!(
            cli.command,
            Some(Command::Open {
                database: PathBuf::from("data.sqlite"),
                write: false
            })
        );
    }

    #[test]
    fn execute_accepts_explicit_confirmation() {
        let cli = Cli::try_parse_from([
            "tuible",
            "execute",
            "data.sqlite",
            "DELETE FROM events",
            "--yes",
        ])
        .unwrap();
        assert_eq!(
            cli.command,
            Some(Command::Execute {
                database: PathBuf::from("data.sqlite"),
                sql: "DELETE FROM events".into(),
                yes: true,
                max_rows: 1_000,
            })
        );
    }

    #[test]
    fn defaults_to_no_subcommand() {
        let cli = Cli::try_parse_from(["tuible"]).unwrap();
        assert_eq!(cli.command, None);
    }

    #[test]
    fn parses_saved_connection_profile() {
        let cli = Cli::try_parse_from(["tuible", "profile", "work"]).unwrap();

        assert_eq!(
            cli.command,
            Some(Command::Profile {
                name: "work".to_string()
            })
        );
    }

    #[test]
    fn parses_dynamodb_query_with_aws_profile() {
        let cli = Cli::try_parse_from([
            "tuible",
            "dynamodb",
            "query",
            "users",
            "--key-condition",
            "pk = :pk",
            "--values",
            r#"{":pk":"USER#42"}"#,
            "--profile",
            "work",
            "--region",
            "eu-west-1",
        ])
        .unwrap();

        let Some(Command::Dynamodb(command)) = cli.command else {
            panic!("expected DynamoDB query");
        };
        let DynamoCommand::Query {
            table,
            key_condition,
            connection,
            ..
        } = *command
        else {
            panic!("expected DynamoDB query");
        };
        assert_eq!(table, "users");
        assert_eq!(key_condition, "pk = :pk");
        assert_eq!(connection.profile.as_deref(), Some("work"));
        assert_eq!(connection.region.as_deref(), Some("eu-west-1"));
    }
}