easysql 0.1.0

getting to the sql prompt, quick and easy - saved connections, their passwords and their tunnels in one CLI + TUI
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
//! The toolbox - bare `esql`. Four tabs (Connections / Passwords / Tunnels /
//! Settings) and a set of wizards that stand in for the things nobody
//! remembers: a `~/.pg_service.conf` block, a `~/.pgpass` line, a `[clientX]`
//! group, and `ssh -L port:host:port bastion`.
//!
//! Opening a connection runs *suspended*: we drop out of the alternate screen,
//! hand the real terminal to psql/mysql/sqlite3 so it owns its own prompt,
//! pager and readline, then restore the UI when you `\q`. Tunnels are spawned
//! detached and tracked, so they don't need that.

use crate::creds::{self, Cred};
use crate::engines::{self, Conn, Engine};
use crate::history;
use crate::reach::{self, Reach};
use crate::settings::{self, ConnOrder, Settings};
use crate::tunnels;
use anyhow::Result;
use crossterm::{
    event::{self, Event, KeyEventKind},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::widgets::{ListState, Padding};
use std::collections::HashMap;
use std::io::{self, Stdout};
use std::process::{Command, ExitStatus};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::{Duration, Instant};

type Term = Terminal<CrosstermBackend<Stdout>>;

mod confirm;
mod detail;
mod filter;
mod input;
mod picker;
mod probe;
mod prompt;
mod render;
mod widgets;
mod wizard;

use confirm::Confirm;
use detail::render_detail;
use picker::Picker;
use prompt::{Action, Kind, Prompt, render_prompt};
use render::ui;
use widgets::{centered, empty, titled, wrapped_line_count};

/// The tabs. Order here is the left-to-right / Tab-cycle order.
#[derive(Clone, Copy, PartialEq)]
pub(super) enum View {
    Connections,
    Passwords,
    Tunnels,
    Settings,
}

const VIEWS: [View; 4] = [
    View::Connections,
    View::Passwords,
    View::Tunnels,
    View::Settings,
];

// The bottom bar is a terse reminder of this view's actions only; `?` opens the
// full cheat-sheet (navigation keys and the real command behind each action), so
// the bar stays short instead of restating everything and overflowing.
const CONN_HINTS: &str = "↵ open · c new · e edit · d del · p password · t tunnel · y yank · Y url · r refresh · / find · ? help";
const PASS_HINTS: &str = "c new · d forget · r refresh · / find · ? help";
const TUNNELS_HINTS: &str = "d kill · r refresh · / find · ? help";
const SETTINGS_HINTS: &str = "↵ change · d back to default · r reload · ? help";

/// How long a status message stays on screen before the hints return.
const STATUS_TTL: Duration = Duration::from_millis(1500);

/// An external command the event loop must run *suspended* (outside the TUI) so
/// it can own the terminal - which here is only ever a database client.
pub(super) struct PendingRun {
    pub(super) argv: Vec<String>,
    pub(super) label: String,
    /// The connection, when this run is an interactive session. Carried whole
    /// rather than by name because a failed open is diagnosed against it.
    pub(super) connect: Option<Conn>,
}

pub(super) struct App {
    pub(super) view: View,
    pub(super) conns: Vec<Conn>,
    pub(super) creds: Vec<Cred>,
    pub(super) tunnels: Vec<tunnels::Tunnel>,
    pub(super) conn_state: ListState,
    pub(super) cred_state: ListState,
    pub(super) tunnel_state: ListState,
    pub(super) prompt: Option<Prompt>,
    pub(super) picker: Option<Picker>,
    pub(super) confirm: Option<Confirm>,
    pub(super) status: String,
    /// When `status` was set; it stops showing after `STATUS_TTL` so an old
    /// message never sits there looking like it is still current.
    pub(super) status_at: Option<Instant>,
    pub(super) show_help: bool,
    pub(super) should_quit: bool,
    /// What `/` is filtering the current list by. Empty means "show all".
    pub(super) query: String,
    /// True while the query is being typed, so keys go into it instead of
    /// triggering actions.
    pub(super) searching: bool,
    /// When you last opened each connection, and how often.
    pub(super) history: history::History,
    /// Last known state of each server's port, keyed by `Conn::key`.
    pub(super) reach: HashMap<String, Reach>,
    /// Which probe round we are showing; answers from an older one are dropped.
    pub(super) reach_gen: u64,
    pub(super) reach_tx: Sender<reach::Msg>,
    pub(super) reach_rx: Receiver<reach::Msg>,
    /// Whether each engine's client is on PATH, worked out once per refresh
    /// rather than per row per frame.
    pub(super) installed: [bool; 4],
    /// The choices that are yours rather than the clients'.
    pub(super) settings: Settings,
    pub(super) settings_state: ListState,
}

impl App {
    /// An app with no data loaded - the base for both `new()` and the tests
    /// (which set the lists directly, so they never touch a real config).
    pub(super) fn empty() -> Self {
        let (tx, rx) = channel();
        App {
            view: View::Connections,
            conns: Vec::new(),
            creds: Vec::new(),
            tunnels: Vec::new(),
            conn_state: ListState::default().with_selected(Some(0)),
            cred_state: ListState::default().with_selected(Some(0)),
            tunnel_state: ListState::default().with_selected(Some(0)),
            prompt: None,
            picker: None,
            confirm: None,
            status: String::new(),
            status_at: None,
            show_help: false,
            should_quit: false,
            query: String::new(),
            searching: false,
            history: history::History::default(),
            reach: HashMap::new(),
            reach_gen: 0,
            reach_tx: tx,
            reach_rx: rx,
            installed: [true; 4],
            settings: Settings::default(),
            // Selected from the start: the detail panel beside a list that has
            // never been touched would otherwise read "nothing selected", which
            // looks like an empty tab rather than one you have not moved in.
            settings_state: ListState::default().with_selected(Some(0)),
        }
    }

    /// Set the transient status line. It fades on its own after `STATUS_TTL`.
    pub(super) fn set_status(&mut self, msg: impl Into<String>) {
        self.status = msg.into();
        self.status_at = Some(Instant::now());
    }

    /// The status message while it is still fresh; `None` once it has expired.
    pub(super) fn live_status(&self) -> Option<&str> {
        let at = self.status_at?;
        (at.elapsed() < STATUS_TTL && !self.status.is_empty()).then_some(self.status.as_str())
    }

    pub(super) fn new() -> Self {
        let mut app = Self::empty();
        app.settings = settings::load();
        app.history = history::load();
        app.refresh_all();
        app.start_probes();
        app
    }

    // --- data loading -----------------------------------------------------

    pub(super) fn refresh_all(&mut self) {
        self.refresh_conns();
        self.refresh_creds();
        self.refresh_tunnels();
    }

    pub(super) fn refresh_conns(&mut self) {
        self.conns = engines::list();
        self.sort_conns();
        for e in engines::ENGINES {
            self.installed[e.idx()] = engines::client_installed(e, &self.settings);
        }
        let n = self.conn_rows().len();
        Self::clamp(&mut self.conn_state, n);
    }

    /// Most recently opened first, then everything you have never opened,
    /// alphabetically. The database you were in ten minutes ago is the one you
    /// are most likely reaching for, and it should not be a scroll away - unless
    /// you asked for plain alphabetical in Settings.
    pub(super) fn sort_conns(&mut self) {
        match self.settings.conn_order {
            ConnOrder::Recent => {
                let history = &self.history;
                self.conns.sort_by_key(|c| history.rank(&c.key()));
            }
            ConnOrder::Alpha => self
                .conns
                .sort_by(|a, b| (a.engine.idx(), &a.name).cmp(&(b.engine.idx(), &b.name))),
        }
    }

    pub(super) fn refresh_creds(&mut self) {
        self.creds = creds::list();
        let n = self.cred_rows().len();
        Self::clamp(&mut self.cred_state, n);
    }

    /// The local port of a live forward whose far end is exactly this
    /// connection's host and port, if one is open. This is what stops easysql
    /// offering to dig a tunnel it has already dug.
    pub(super) fn tunnel_carrying(&self, c: &Conn) -> Option<String> {
        let port = c.port_or_default();
        self.tunnels.iter().find_map(|t| {
            let (open, target, onward) = t.ports()?;
            let same_host = target.eq_ignore_ascii_case(&c.host)
                || crate::sshhosts::is_same_machine(&t.host, &c.host)
                    && matches!(target, "127.0.0.1" | "localhost");
            (t.kind == 'L' && same_host && onward == port).then(|| open.to_string())
        })
    }

    pub(super) fn refresh_tunnels(&mut self) {
        self.tunnels = tunnels::list();
        let n = self.tunnel_rows().len();
        Self::clamp(&mut self.tunnel_state, n);
    }

    /// Is there a saved password that answers for this connection? Only asked
    /// of the engines whose client reads a password file of its own: SQLite has
    /// nothing to unlock, and sqlcmd prompts for itself.
    pub(super) fn has_password(&self, c: &Conn) -> bool {
        c.engine.stores_password() && self.creds.iter().any(|cred| cred.covers(c))
    }

    // --- reachability -----------------------------------------------------

    /// Start a fresh round of port probes. Older rounds are invalidated by the
    /// generation bump, so a slow answer from the last round cannot repaint a
    /// server we have since re-probed.
    pub(super) fn start_probes(&mut self) {
        self.reach_gen += 1;
        // Turned off in Settings: forget what we knew rather than leave dots
        // that stop being true the moment anything moves.
        if !self.settings.probe {
            self.reach.clear();
            return;
        }
        let targets: Vec<reach::Target> = self
            .conns
            .iter()
            // A SQLite file has no port and nothing to ask.
            .filter(|c| c.engine.networked())
            .map(|c| reach::Target {
                key: c.key(),
                host: if c.host.is_empty() {
                    "localhost".to_string()
                } else {
                    c.host.clone()
                },
                port: c.port_or_default().parse().unwrap_or(0),
            })
            .filter(|t| t.port != 0)
            .collect();
        for t in &targets {
            self.reach.insert(t.key.clone(), Reach::Probing);
        }
        reach::probe_all(
            targets,
            self.reach_gen,
            self.reach_tx.clone(),
            self.settings.probe_timeout,
        );
    }

    /// Take whatever the probe threads have reported since the last frame.
    pub(super) fn drain_probes(&mut self) -> bool {
        let mut changed = false;
        while let Ok(msg) = self.reach_rx.try_recv() {
            if msg.generation != self.reach_gen {
                continue; // an answer to a question we no longer ask
            }
            self.reach.insert(msg.key, msg.reach);
            changed = true;
        }
        changed
    }

    /// True while any probe is still outstanding, so the event loop knows to
    /// keep waking up instead of blocking on a keypress.
    pub(super) fn probing(&self) -> bool {
        self.reach.values().any(|r| *r == Reach::Probing)
    }

    // --- filtering --------------------------------------------------------

    /// Indices into `conns` that survive the current query.
    pub(super) fn conn_rows(&self) -> Vec<usize> {
        self.conns
            .iter()
            .enumerate()
            .filter(|(_, c)| {
                let target = c.target();
                filter::matches(&self.query, &[&c.name, &target, c.engine.label()])
            })
            .map(|(i, _)| i)
            .collect()
    }

    pub(super) fn cred_rows(&self) -> Vec<usize> {
        self.creds
            .iter()
            .enumerate()
            .filter(|(_, c)| filter::matches(&self.query, &[&c.describe()]))
            .map(|(i, _)| i)
            .collect()
    }

    pub(super) fn tunnel_rows(&self) -> Vec<usize> {
        self.tunnels
            .iter()
            .enumerate()
            .filter(|(_, t)| filter::matches(&self.query, &[&t.describe()]))
            .map(|(i, _)| i)
            .collect()
    }

    /// The settings the current query keeps. Every one is always relevant, so
    /// this filters the same way the other tabs do rather than specially.
    pub(super) fn settings_rows(&self) -> Vec<settings::Row> {
        self.settings
            .rows()
            .into_iter()
            .filter(|r| filter::matches(&self.query, &[r.label, r.key, &r.value, r.help]))
            .collect()
    }

    pub(super) fn selected_setting(&self) -> Option<settings::Row> {
        let i = self.settings_state.selected()?;
        self.settings_rows().into_iter().nth(i)
    }

    /// How many rows the current view is showing, after filtering.
    pub(super) fn row_count(&self) -> usize {
        match self.view {
            View::Connections => self.conn_rows().len(),
            View::Passwords => self.cred_rows().len(),
            View::Tunnels => self.tunnel_rows().len(),
            View::Settings => self.settings_rows().len(),
        }
    }

    /// Jump to another view the way a finished action does. The filter belongs
    /// to the list it was typed over, so it does not come along - and a tunnel
    /// made from a filtered Connections list would otherwise land on a Tunnels
    /// tab that hides it.
    pub(super) fn goto_view(&mut self, view: View) {
        self.view = view;
        if !self.query.is_empty() || self.searching {
            self.query.clear();
            self.searching = false;
            self.requery();
        }
    }

    /// Put the cursor on the tunnel with this pid: the one you just made is the
    /// one you are looking for, and on a busy list it is not row one.
    pub(super) fn select_tunnel(&mut self, pid: u32) {
        let at = self
            .tunnel_rows()
            .iter()
            .position(|&r| self.tunnels[r].pid == pid);
        if let Some(i) = at {
            self.tunnel_state.select(Some(i));
        }
    }

    /// The same for a connection, after adding or renaming one.
    pub(super) fn select_conn(&mut self, key: &str) {
        let at = self
            .conn_rows()
            .iter()
            .position(|&r| self.conns[r].key() == key);
        if let Some(i) = at {
            self.conn_state.select(Some(i));
        }
    }

    /// Re-clamp every list after the query changed, and put the selection back
    /// at the top so the first match is the one under the cursor.
    pub(super) fn requery(&mut self) {
        self.conn_state.select(Some(0));
        self.cred_state.select(Some(0));
        self.tunnel_state.select(Some(0));
        self.settings_state.select(Some(0));
        let n = self.conn_rows().len();
        Self::clamp(&mut self.conn_state, n);
        let n = self.cred_rows().len();
        Self::clamp(&mut self.cred_state, n);
        let n = self.tunnel_rows().len();
        Self::clamp(&mut self.tunnel_state, n);
        let n = self.settings_rows().len();
        Self::clamp(&mut self.settings_state, n);
    }

    /// Keep a list's selection in range (and set/clear it as the list fills/empties).
    pub(super) fn clamp(state: &mut ListState, len: usize) {
        if len == 0 {
            state.select(None);
        } else {
            let sel = state.selected().unwrap_or(0).min(len - 1);
            state.select(Some(sel));
        }
    }

    // A selection indexes the *filtered* rows, so every lookup goes through the
    // row list; indexing the raw vec would pick the wrong entry the moment `/`
    // hides anything.
    pub(super) fn selected_conn(&self) -> Option<&Conn> {
        let row = *self.conn_rows().get(self.conn_state.selected()?)?;
        self.conns.get(row)
    }

    pub(super) fn selected_cred(&self) -> Option<&Cred> {
        let row = *self.cred_rows().get(self.cred_state.selected()?)?;
        self.creds.get(row)
    }

    pub(super) fn selected_tunnel(&self) -> Option<&tunnels::Tunnel> {
        let row = *self.tunnel_rows().get(self.tunnel_state.selected()?)?;
        self.tunnels.get(row)
    }

    // --- input ------------------------------------------------------------

    pub(super) fn cycle_view(&mut self, delta: i32) {
        let i = VIEWS.iter().position(|v| *v == self.view).unwrap_or(0) as i32;
        let n = (i + delta).rem_euclid(VIEWS.len() as i32) as usize;
        self.view = VIEWS[n];
        // A `/` filter belongs to the list you typed it over; carrying it into
        // the next tab would silently hide rows you never searched.
        if !self.query.is_empty() || self.searching {
            self.query.clear();
            self.searching = false;
            self.requery();
        }
    }

    pub(super) fn move_sel(&mut self, delta: i32) {
        let len = self.row_count();
        match self.view {
            View::Connections => Self::move_state(&mut self.conn_state, len, delta),
            View::Passwords => Self::move_state(&mut self.cred_state, len, delta),
            View::Tunnels => Self::move_state(&mut self.tunnel_state, len, delta),
            View::Settings => Self::move_state(&mut self.settings_state, len, delta),
        }
    }

    pub(super) fn move_state(state: &mut ListState, len: usize, delta: i32) {
        if len == 0 {
            return;
        }
        let cur = state.selected().unwrap_or(0) as i32;
        let next = (cur + delta).rem_euclid(len as i32) as usize;
        state.select(Some(next));
    }
}

// ==========================================================================
// Terminal lifecycle + event loop
// ==========================================================================

/// Entry point for bare `esql`.
pub fn run() -> Result<()> {
    install_panic_hook();
    let mut terminal = setup()?;
    let mut app = App::new();
    let res = event_loop(&mut terminal, &mut app);
    teardown(&mut terminal)?;
    res
}

fn event_loop(terminal: &mut Term, app: &mut App) -> Result<()> {
    while !app.should_quit {
        terminal.draw(|f| ui(f, app))?;

        // While a status message is showing, or port probes are still landing,
        // we wake up periodically so the screen can catch up on its own;
        // otherwise block until the user actually presses a key, so an idle TUI
        // costs nothing.
        let timeout = if app.live_status().is_some() || app.probing() {
            Duration::from_millis(200)
        } else {
            Duration::from_secs(3600)
        };
        if !event::poll(timeout)? {
            app.drain_probes();
            continue; // nothing pressed: redraw so the stale status drops off
        }
        app.drain_probes();

        let Event::Key(key) = event::read()? else {
            continue;
        };
        // crossterm emits Press+Release on some platforms; act on Press only.
        if key.kind != KeyEventKind::Press {
            continue;
        }

        if let Some(run) = app.on_key(key) {
            let status = run_suspended(terminal, &run.argv)?;

            if let Some(conn) = run.connect.clone() {
                match status {
                    // A session you actually got into is what makes a connection
                    // "recent"; a failed one leaves the ordering alone.
                    Some(s) if s.success() => {
                        history::record(&conn.key());
                        app.history = history::load();
                    }
                    // The client printed why and then we redrew over it. Ask the
                    // server the same question non-interactively and offer the
                    // fix in a modal instead of a status that flashes past.
                    Some(_) => app.offer_fix(&conn),
                    None => {}
                }
            }

            let msg = match status {
                Some(s) if s.success() => format!("{}", run.label),
                Some(s) => format!("{} failed (exit {})", run.label, s.code().unwrap_or(-1)),
                None => format!("{}: could not run '{}'", run.label, run.argv[0]),
            };
            app.set_status(msg);
            app.refresh_all();
        }
    }
    Ok(())
}

/// Leave the TUI, run an interactive command with the real terminal, then
/// restore the TUI. This is what lets psql own its prompt, its pager and its
/// readline instead of us pretending to be a database client.
fn run_suspended(terminal: &mut Term, argv: &[String]) -> Result<Option<ExitStatus>> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    // ratatui hides the cursor while drawing and leaving the alt-screen does not
    // restore it, so without this the client runs with an invisible cursor and
    // you cannot see where you are typing.
    terminal.show_cursor()?;

    let status = Command::new(&argv[0]).args(&argv[1..]).status().ok();

    enable_raw_mode()?;
    execute!(terminal.backend_mut(), EnterAlternateScreen)?;
    terminal.hide_cursor()?;
    terminal.clear()?;
    Ok(status)
}

fn setup() -> Result<Term> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    Ok(Terminal::new(CrosstermBackend::new(stdout))?)
}

fn teardown(terminal: &mut Term) -> Result<()> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    Ok(())
}

/// Make sure a panic doesn't leave the user's terminal in raw/alt-screen mode.
fn install_panic_hook() {
    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = disable_raw_mode();
        let _ = execute!(io::stdout(), LeaveAlternateScreen);
        hook(info);
    }));
}