querypie-cli 0.2.0

Query QueryPie databases from the terminal with webview authentication.
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
use std::fs;
use std::io::{self, IsTerminal, Read};
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use clap::{Args, Subcommand};
use clap_complete::Shell;

use super::{auth_cmd, data_cmd, session_cmd, Global};
use crate::formatting::{Options as FormatOptions, OutputFormat};

#[derive(Debug, Subcommand)]
pub(super) enum Command {
    #[command(about = "Log in, log out, and inspect authentication")]
    Auth {
        #[command(subcommand)]
        command: AuthCommand,
    },
    #[command(about = "Generate shell completions")]
    Completion {
        #[arg(value_enum)]
        shell: Shell,
    },
    #[command(about = "List and inspect QueryPie connections")]
    #[command(after_help = "EXAMPLES:\n  querypie connection list")]
    Connection {
        #[command(subcommand)]
        command: ConnectionCommand,
    },
    #[command(about = "List databases for a QueryPie connection")]
    #[command(after_help = "EXAMPLES:\n  querypie database list -c CONNECTION")]
    Database {
        #[command(subcommand)]
        command: DatabaseCommand,
    },
    #[command(about = "Run SQL through QueryPie")]
    #[command(after_help = "EXAMPLES:\n  querypie query -c CONNECTION 'select 1;'")]
    Query {
        #[command(flatten)]
        selection: DatabaseSelectionArgs,
        #[command(flatten)]
        args: QueryArgs,
    },
    #[command(about = "List schemas for a database")]
    #[command(after_help = "EXAMPLES:\n  querypie schema list -c CONNECTION -d DATABASE")]
    Schema {
        #[command(subcommand)]
        command: SchemaCommand,
    },
    #[command(about = "Manage cached QueryPie database sessions")]
    Session {
        #[command(subcommand)]
        command: SessionCommand,
    },
    #[command(about = "List and inspect tables")]
    #[command(
        after_help = "EXAMPLES:\n  querypie table ddl -c CONNECTION -d DATABASE TABLE\n  querypie table describe -c CONNECTION -d DATABASE TABLE\n  querypie table list -c CONNECTION -d DATABASE"
    )]
    Table {
        #[command(subcommand)]
        command: TableCommand,
    },
}

#[derive(Debug, Subcommand)]
pub(super) enum AuthCommand {
    #[command(about = "Open a webview and log in to QueryPie")]
    Login,
    #[command(about = "Log out and remove QueryPie webview session data")]
    Logout,
    #[command(hide = true)]
    ReadCookie,
    #[command(hide = true)]
    RefreshCookie,
    #[command(about = "Show current QueryPie authentication status")]
    Status,
}

#[derive(Debug, Subcommand)]
pub(super) enum ConnectionCommand {
    #[command(about = "List QueryPie connections")]
    List(OutputArgs),
}

#[derive(Debug, Subcommand)]
pub(super) enum DatabaseCommand {
    #[command(about = "List databases for the selected connection")]
    List {
        #[command(flatten)]
        selection: ConnectionSelectionArgs,
        #[command(flatten)]
        output: OutputArgs,
    },
}

#[derive(Debug, Subcommand)]
pub(super) enum SchemaCommand {
    #[command(about = "List schemas for the selected database")]
    List {
        #[command(flatten)]
        selection: DatabaseSelectionArgs,
        #[command(flatten)]
        output: OutputArgs,
    },
}

#[derive(Debug, Subcommand)]
pub(super) enum SessionCommand {
    #[command(about = "Clear cached QueryPie database sessions")]
    Clear {
        #[command(flatten)]
        selection: ConnectionArg,
    },
    #[command(about = "List cached QueryPie database sessions")]
    List(OutputArgs),
}

#[derive(Debug, Subcommand)]
pub(super) enum TableCommand {
    #[command(about = "Show DDL for a table")]
    Ddl {
        #[command(flatten)]
        selection: TableSelectionArgs,
        #[command(flatten)]
        output: OutputArgs,
        #[arg(add = clap_complete::ArgValueCompleter::new(super::completion::complete_tables))]
        table: String,
    },
    #[command(about = "Show QueryPie table structure")]
    Describe {
        #[command(flatten)]
        selection: TableSelectionArgs,
        #[command(flatten)]
        output: OutputArgs,
        #[arg(add = clap_complete::ArgValueCompleter::new(super::completion::complete_tables))]
        table: String,
    },
    #[command(about = "List tables for the selected schema")]
    List {
        #[command(flatten)]
        selection: TableSelectionArgs,
        #[command(flatten)]
        output: OutputArgs,
    },
}

#[derive(Debug, Args)]
pub(super) struct QueryArgs {
    #[arg(
        short = 'f',
        long,
        value_name = "PATH",
        help = "Read SQL from a file",
        display_order = 5
    )]
    file: Option<PathBuf>,
    #[arg(
        long,
        default_value_t = 1000,
        value_parser = clap::value_parser!(i32).range(1..),
        help = "Maximum rows to fetch",
        display_order = 7
    )]
    limit: i32,
    #[command(flatten)]
    output: OutputArgs,
    #[arg(value_name = "SQL")]
    sql: Option<String>,
}

#[derive(Debug, Clone, Copy, Args)]
pub(super) struct OutputArgs {
    #[arg(long, help = "Do not truncate table output", display_order = 8)]
    pub(super) no_truncate: bool,
    #[arg(
        short = 'o',
        long,
        value_enum,
        default_value_t = OutputFormat::Text,
        help = "Output format",
        display_order = 9
    )]
    pub(super) output: OutputFormat,
}

#[derive(Debug, Clone, Args)]
pub(super) struct ConnectionArg {
    #[arg(
        short = 'c',
        long,
        value_name = "CONNECTION",
        help = "QueryPie connection name",
        add = clap_complete::ArgValueCompleter::new(super::completion::complete_connections),
        display_order = 2
    )]
    connection: Option<String>,
}

#[derive(Debug, Clone, Args)]
pub(super) struct ConnectionSelectionArgs {
    #[command(flatten)]
    connection: ConnectionArg,
    #[arg(
        long,
        value_name = "ENGINE",
        help = "Database engine name, such as mysql",
        add = clap_complete::ArgValueCompleter::new(super::completion::complete_engines),
        display_order = 4
    )]
    engine: Option<String>,
}

#[derive(Debug, Clone, Args)]
pub(super) struct DatabaseSelectionArgs {
    #[command(flatten)]
    connection: ConnectionSelectionArgs,
    #[arg(
        short = 'd',
        long = "db",
        value_name = "DATABASE",
        help = "Database name to use",
        add = clap_complete::ArgValueCompleter::new(super::completion::complete_databases),
        display_order = 3
    )]
    database: Option<String>,
}

#[derive(Debug, Clone, Args)]
pub(super) struct TableSelectionArgs {
    #[command(flatten)]
    database: DatabaseSelectionArgs,
    #[arg(
        long,
        value_name = "SCHEMA",
        help = "Schema name to use",
        add = clap_complete::ArgValueCompleter::new(super::completion::complete_schemas),
        display_order = 10
    )]
    schema: Option<String>,
}

impl Command {
    pub(super) fn run(self, global: &Global) -> Result<()> {
        match self {
            Command::Auth { command } => command.run(global),
            Command::Completion { .. } => Ok(()),
            Command::Connection { command } => command.run(global),
            Command::Database { command } => command.run(global),
            Command::Query { args, .. } => {
                let (sql, limit, output) = args.into_sql_limit_output()?;
                data_cmd::run_query(global, sql, limit, output)
            }
            Command::Schema { command } => command.run(global),
            Command::Session { command } => command.run(global),
            Command::Table { command } => command.run(global),
        }
    }

    pub(super) fn apply_selection(&self, global: &mut Global) {
        match self {
            Command::Auth { .. } | Command::Completion { .. } | Command::Connection { .. } => {}
            Command::Database { command } => command.apply_selection(global),
            Command::Query { selection, .. } => selection.apply_to(global),
            Command::Schema { command } => command.apply_selection(global),
            Command::Session { command } => command.apply_selection(global),
            Command::Table { command } => command.apply_selection(global),
        }
    }
}

impl ConnectionCommand {
    fn run(self, global: &Global) -> Result<()> {
        match self {
            ConnectionCommand::List(output) => data_cmd::list_connections(global, output),
        }
    }
}

impl DatabaseCommand {
    fn run(self, global: &Global) -> Result<()> {
        match self {
            DatabaseCommand::List { output, .. } => data_cmd::list_databases(global, output),
        }
    }

    fn apply_selection(&self, global: &mut Global) {
        match self {
            DatabaseCommand::List { selection, .. } => selection.apply_to(global),
        }
    }
}

impl SchemaCommand {
    fn run(self, global: &Global) -> Result<()> {
        match self {
            SchemaCommand::List { output, .. } => data_cmd::list_schemas(global, output),
        }
    }

    fn apply_selection(&self, global: &mut Global) {
        match self {
            SchemaCommand::List { selection, .. } => selection.apply_to(global),
        }
    }
}

impl TableCommand {
    fn run(self, global: &Global) -> Result<()> {
        match self {
            TableCommand::Ddl { table, output, .. } => {
                data_cmd::show_table_ddl(global, table, output)
            }
            TableCommand::Describe { table, output, .. } => {
                data_cmd::describe_table(global, table, output)
            }
            TableCommand::List { output, .. } => data_cmd::list_tables(global, output),
        }
    }

    fn apply_selection(&self, global: &mut Global) {
        match self {
            TableCommand::Ddl { selection, .. }
            | TableCommand::Describe { selection, .. }
            | TableCommand::List { selection, .. } => selection.apply_to(global),
        }
    }
}

impl AuthCommand {
    fn run(self, global: &Global) -> Result<()> {
        match self {
            AuthCommand::Login => auth_cmd::auth_login(global),
            AuthCommand::Logout => auth_cmd::auth_logout(global),
            AuthCommand::ReadCookie => auth_cmd::auth_read_cookie(global),
            AuthCommand::RefreshCookie => auth_cmd::auth_refresh_cookie(global),
            AuthCommand::Status => auth_cmd::auth_status(global),
        }
    }
}

impl SessionCommand {
    fn run(self, global: &Global) -> Result<()> {
        match self {
            SessionCommand::Clear { .. } => session_cmd::clear_cached_sessions(global),
            SessionCommand::List(output) => session_cmd::list_cached_sessions(output),
        }
    }

    fn apply_selection(&self, global: &mut Global) {
        match self {
            SessionCommand::Clear { selection } => selection.apply_to(global),
            SessionCommand::List(_) => {}
        }
    }
}

impl ConnectionArg {
    fn apply_to(&self, global: &mut Global) {
        global.set_connection(&self.connection);
    }
}

impl ConnectionSelectionArgs {
    fn apply_to(&self, global: &mut Global) {
        self.connection.apply_to(global);
        global.set_engine(&self.engine);
    }
}

impl DatabaseSelectionArgs {
    fn apply_to(&self, global: &mut Global) {
        self.connection.apply_to(global);
        global.set_database(&self.database);
    }
}

impl TableSelectionArgs {
    fn apply_to(&self, global: &mut Global) {
        self.database.apply_to(global);
        global.set_schema(&self.schema);
    }
}

impl QueryArgs {
    fn into_sql_limit_output(self) -> Result<(String, i32, OutputArgs)> {
        let QueryArgs {
            sql,
            file,
            limit,
            output,
        } = self;
        let stdin_is_terminal = io::stdin().is_terminal();
        let sql = resolve_query_sql(sql, file, stdin_is_terminal, read_stdin, read_file)?;
        Ok((sql, limit, output))
    }
}

pub(super) fn fmt(output: OutputArgs) -> FormatOptions {
    FormatOptions {
        output: output.output,
        truncate: !output.no_truncate && !no_truncate_env(),
    }
}

const NO_SQL_ERROR: &str = "no SQL provided; pass SQL, use `query -`, or use `query --file <PATH>`";
const MULTIPLE_SQL_SOURCES_ERROR: &str =
    "provide exactly one SQL source; pass SQL, use `query -`, or use `query --file <PATH>`";

enum QuerySqlSource {
    Inline(String),
    Stdin,
    File(PathBuf),
}

fn resolve_query_sql(
    sql: Option<String>,
    file: Option<PathBuf>,
    stdin_is_terminal: bool,
    mut read_stdin: impl FnMut() -> Result<String>,
    mut read_file: impl FnMut(&Path) -> Result<String>,
) -> Result<String> {
    let sql = match query_sql_source(sql, file, stdin_is_terminal)? {
        QuerySqlSource::Inline(sql) => sql,
        QuerySqlSource::Stdin => read_stdin()?,
        QuerySqlSource::File(path) => read_file(&path)?,
    };

    validate_query_sql(sql)
}

fn query_sql_source(
    sql: Option<String>,
    file: Option<PathBuf>,
    stdin_is_terminal: bool,
) -> Result<QuerySqlSource> {
    match (sql, file, stdin_is_terminal) {
        (Some(_), Some(_), _) => bail!(MULTIPLE_SQL_SOURCES_ERROR),
        (None, Some(path), _) if path == Path::new("-") => {
            bail!("`--file -` is not supported; use `query -` to read SQL from stdin")
        }
        (None, Some(path), _) => Ok(QuerySqlSource::File(path)),
        (Some(sql), None, _) if sql == "-" => Ok(QuerySqlSource::Stdin),
        (Some(sql), None, _) => Ok(QuerySqlSource::Inline(sql)),
        (None, None, false) => Ok(QuerySqlSource::Stdin),
        (None, None, true) => bail!(NO_SQL_ERROR),
    }
}

fn validate_query_sql(sql: String) -> Result<String> {
    if sql.trim().is_empty() {
        bail!("SQL is empty");
    }

    Ok(sql)
}

fn read_stdin() -> Result<String> {
    let mut sql = String::new();
    io::stdin()
        .read_to_string(&mut sql)
        .context("failed to read SQL from stdin")?;
    Ok(sql)
}

fn read_file(path: &Path) -> Result<String> {
    fs::read_to_string(path).with_context(|| format!("failed to read SQL from {}", path.display()))
}

fn no_truncate_env() -> bool {
    std::env::var("QUERYPIE_NO_TRUNCATE")
        .map(|value| {
            matches!(
                value.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes"
            )
        })
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;
    use crate::cli::Cli;

    fn resolve(
        sql: Option<&str>,
        file: Option<&str>,
        stdin_is_terminal: bool,
        stdin_sql: &str,
        file_sql: &str,
    ) -> Result<String> {
        resolve_query_sql(
            sql.map(str::to_owned),
            file.map(PathBuf::from),
            stdin_is_terminal,
            || Ok(stdin_sql.to_owned()),
            |_| Ok(file_sql.to_owned()),
        )
    }

    #[test]
    fn resolves_sql_sources() {
        let cases = [
            (
                "positional sql",
                Some("  select 1;\n"),
                None,
                true,
                "from stdin",
                "from file",
                "  select 1;\n",
            ),
            (
                "dash from stdin",
                Some("-"),
                None,
                true,
                "select from stdin;\n",
                "from file",
                "select from stdin;\n",
            ),
            (
                "piped stdin",
                None,
                None,
                false,
                "select from stdin;\n",
                "from file",
                "select from stdin;\n",
            ),
            (
                "file",
                None,
                Some("query.sql"),
                true,
                "from stdin",
                "  select from file;\n",
                "  select from file;\n",
            ),
        ];

        for (name, sql, file, stdin_is_terminal, stdin_sql, file_sql, expected) in cases {
            let actual = resolve(sql, file, stdin_is_terminal, stdin_sql, file_sql)
                .unwrap_or_else(|err| panic!("{name}: {err:#}"));

            assert_eq!(actual, expected, "{name}");
        }
    }

    #[test]
    fn rejects_invalid_sql_sources() {
        let cases = [
            (
                "file and positional sql",
                Some("select 1;"),
                Some("query.sql"),
                true,
                MULTIPLE_SQL_SOURCES_ERROR,
            ),
            ("empty sql", Some("   \n\t"), None, true, "SQL is empty"),
            ("file dash", None, Some("-"), true, "use `query -`"),
            ("missing sql", None, None, true, NO_SQL_ERROR),
        ];

        for (name, sql, file, stdin_is_terminal, expected) in cases {
            let err = resolve(sql, file, stdin_is_terminal, "from stdin", "from file")
                .expect_err(name)
                .to_string();

            assert!(
                err.contains(expected),
                "{name}: expected {err:?} to contain {expected:?}"
            );
        }
    }

    #[test]
    fn query_limit_starts_at_one() {
        for arg in ["--limit=-1", "--limit=0"] {
            let err = Cli::try_parse_from(["querypie", "query", arg, "select 1;"])
                .expect_err("limit below 1 should be rejected");
            assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
        }

        let cli = Cli::try_parse_from(["querypie", "query", "--limit", "1", "select 1;"])
            .expect("limit 1 should parse");

        let Command::Query { args, .. } = cli.command else {
            panic!("expected query command");
        };
        assert_eq!(args.limit, 1);
    }
}