sabiql 1.12.4

A fast, driver-less TUI for browsing and editing PostgreSQL databases
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
#![allow(
    clippy::disallowed_methods,
    reason = "the main loop is the time source: it reads the clock and injects `now` into reducers"
)]

use std::cell::RefCell;
use std::sync::Arc;
use std::time::{Duration, Instant};

use clap::Parser;
use color_eyre::eyre::Result;
use tokio::sync::mpsc;
use tokio::time::sleep_until;

mod panic_hooks;

#[cfg(test)]
mod tests;

#[cfg(test)]
#[path = "tests/render_snapshots/mod.rs"]
mod render_snapshots;

use sabiql_app::cmd::cache::TtlCache;
use sabiql_app::cmd::completion_engine::CompletionEngine;
use sabiql_app::cmd::effect::Effect;
use sabiql_app::cmd::render_schedule::next_animation_deadline;
use sabiql_app::cmd::runner::{
    ConnectionDeps, EffectRunner, ErDeps, QueryDeps, SettingsDeps, UtilityDeps,
};
use sabiql_app::model::app_state::AppState;
use sabiql_app::model::shared::db_capabilities::DbCapabilities;
use sabiql_app::model::shared::input_mode::InputMode;
use sabiql_app::ports::outbound::{
    ConnectionStore, ConnectionStoreError, DatabaseCapabilityProvider, DdlGenerator,
    PgServiceEntryReader, ServiceFileError, SettingsStore, SqlDialect,
};
use sabiql_app::services::AppServices;
use sabiql_app::update::action::Action;
use sabiql_app::update::input::handle_event;
use sabiql_app::update::reducer::reduce;
use sabiql_infra::adapters::{
    ArboardClipboard, FileConfigWriter, FileQueryHistoryStore, FsErLogWriter, NativeFolderOpener,
    PgServiceFileReader, PostgresAdapter, TomlConnectionStore, TomlSettingsStore,
};
use sabiql_infra::config::project_root::{find_project_root, get_project_name};
use sabiql_infra::export::DotExporter;
use sabiql_ui::adapters::TuiAdapter;
use sabiql_ui::tui::TuiRunner;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(clap::Subcommand, Debug)]
enum Command {
    #[cfg(feature = "self-update")]
    /// Update sabiql to the latest compatible version
    Update,
    #[cfg(not(feature = "self-update"))]
    /// Self-update is disabled in this build
    #[command(hide = true)]
    Update,
}

#[tokio::main]
#[allow(
    clippy::print_stderr,
    reason = "CLI error output before TUI initialization"
)]
async fn main() -> Result<()> {
    dotenvy::dotenv().ok();
    panic_hooks::install_hooks()?;

    let args = Args::parse();
    if matches!(args.command, Some(Command::Update)) {
        #[cfg(feature = "self-update")]
        {
            return run_update();
        }
        #[cfg(not(feature = "self-update"))]
        {
            eprintln!("{}", self_update_disabled_message());
            std::process::exit(1);
        }
    }

    let project_root = find_project_root()?;
    let project_name = get_project_name(&project_root);

    let (action_tx, mut action_rx) = mpsc::channel::<Action>(256);

    let adapter = Arc::new(PostgresAdapter::new());
    let metadata_cache = TtlCache::new(300);
    let completion_engine = RefCell::new(CompletionEngine::new());
    let connection_store = TomlConnectionStore::new()?;
    let settings_store = TomlSettingsStore::new()?;
    let app_settings = settings_store.load().unwrap_or_default();
    let all_profiles = connection_store.load_all();
    let connection_store = Arc::new(connection_store);
    let settings_store = Arc::new(settings_store);

    let db_capabilities: DbCapabilities = adapter.capabilities().into();
    let pg_service_entry_reader: Arc<dyn PgServiceEntryReader> =
        Arc::new(PgServiceFileReader::new());

    let effect_runner = EffectRunner::new(
        Arc::clone(&adapter) as _,
        ConnectionDeps {
            dsn_builder: Arc::clone(&adapter) as _,
            connection_store: Arc::clone(&connection_store) as _,
            pg_service_entry_reader: Some(Arc::clone(&pg_service_entry_reader)),
        },
        QueryDeps {
            query_executor: Arc::clone(&adapter) as _,
            query_history_store: Arc::new(FileQueryHistoryStore::new()),
        },
        ErDeps {
            er_exporter: Arc::new(DotExporter::new()),
            config_writer: Arc::new(FileConfigWriter::new()),
            er_log_writer: Arc::new(FsErLogWriter),
        },
        UtilityDeps {
            clipboard: Arc::new(ArboardClipboard),
            folder_opener: Arc::new(NativeFolderOpener),
        },
        SettingsDeps {
            settings_store: Arc::clone(&settings_store) as _,
        },
        metadata_cache.clone(),
        action_tx.clone(),
    );

    let ddl_generator: Arc<dyn DdlGenerator> = adapter.clone();
    let sql_dialect: Arc<dyn SqlDialect> = adapter.clone();
    let services = AppServices {
        ddl_generator,
        sql_dialect,
        db_capabilities,
    };

    let mut state = AppState::new(project_name);
    state.ui.set_theme(app_settings.theme_id);
    state.settings.load_er_browser(app_settings.er_browser);

    match all_profiles {
        Ok(profiles) if profiles.is_empty() => {
            load_service_entries(&mut state, Some(&*pg_service_entry_reader));
            if state.service_entries().is_empty() {
                state.connection_setup.is_first_run = true;
                state.modal.set_mode(InputMode::ConnectionSetup);
            } else {
                state.modal.set_mode(InputMode::ConnectionSelector);
                state.ui.set_connection_list_selection(Some(0));
            }
        }
        Ok(mut profiles) => {
            profiles.sort_by(|a, b| {
                a.display_name()
                    .to_lowercase()
                    .cmp(&b.display_name().to_lowercase())
            });
            state.set_connections(profiles);
            load_service_entries(&mut state, Some(&*pg_service_entry_reader));

            state.modal.set_mode(InputMode::ConnectionSelector);
            state.ui.set_connection_list_selection(Some(0));
        }
        Err(ConnectionStoreError::VersionMismatch { found, expected }) => {
            eprintln!(
                "Error: Configuration file version mismatch (found v{}, expected v{}).\n\
                 Please delete {} and reconfigure.",
                found,
                expected,
                connection_store.storage_path().display()
            );
            std::process::exit(1);
        }
        Err(_) => {
            state.connection_setup.is_first_run = true;
            state.modal.set_mode(InputMode::ConnectionSetup);
        }
    }

    let mut tui = TuiRunner::new()?;
    tui.enter()?;

    let initial_size = tui.terminal().size()?;
    state.ui.terminal_width = initial_size.width;
    state.ui.terminal_height = initial_size.height;

    if state.session.dsn.is_some() && state.input_mode() == InputMode::Normal {
        process_action(
            Action::TryConnect,
            &mut state,
            &mut tui,
            &effect_runner,
            &completion_engine,
            &services,
        )
        .await?;
    }

    let cache_cleanup_interval = Duration::from_secs(150);
    let mut last_cache_cleanup = Instant::now();

    loop {
        let now = Instant::now();
        let deadline = next_animation_deadline(&state, now);

        tokio::select! {
            Some(event) = tui.next_event() => {
                let action = handle_event(event, &state, &services);
                if !action.is_none() {
                    drain_and_process_terminal_events(action, &mut state, &mut tui, &effect_runner, &completion_engine, &services).await?;
                }
            }
            Some(action) = action_rx.recv() => {
                process_action(action, &mut state, &mut tui, &effect_runner, &completion_engine, &services).await?;
            }
            // Animation deadline reached (spinner, cursor blink, message timeout)
            () = async {
                match deadline {
                    Some(d) => sleep_until(d.into()).await,
                    None => std::future::pending::<()>().await,
                }
            } => {
                process_action(Action::Render, &mut state, &mut tui, &effect_runner, &completion_engine, &services).await?;
            }
        }

        if let Some(debounce_until) = state.sql_modal.completion_debounce()
            && Instant::now() >= debounce_until
        {
            state.sql_modal.consume_completion_debounce();
            process_action(
                Action::CompletionTrigger,
                &mut state,
                &mut tui,
                &effect_runner,
                &completion_engine,
                &services,
            )
            .await?;
        }

        if last_cache_cleanup.elapsed() >= cache_cleanup_interval {
            metadata_cache.cleanup_expired().await;
            last_cache_cleanup = Instant::now();
        }

        if state.should_quit {
            break;
        }
    }

    tui.exit()?;
    Ok(())
}

async fn process_action(
    action: Action,
    state: &mut AppState,
    tui: &mut TuiRunner,
    effect_runner: &EffectRunner,
    completion_engine: &RefCell<CompletionEngine>,
    services: &AppServices,
) -> Result<()> {
    let now = Instant::now();
    let is_animation_tick = matches!(action, Action::Render);
    if is_animation_tick {
        state.clear_expired_timers(now);
    }
    let mut effects = reduce(state, action, now, services);
    if state.render_dirty {
        if !is_animation_tick {
            state.clear_expired_timers(now);
        }
        effects.push(Effect::Render);
    }
    flush_effects(
        effects,
        state,
        tui,
        effect_runner,
        completion_engine,
        services,
    )
    .await
}

async fn flush_effects(
    effects: Vec<Effect>,
    state: &mut AppState,
    tui: &mut TuiRunner,
    effect_runner: &EffectRunner,
    completion_engine: &RefCell<CompletionEngine>,
    services: &AppServices,
) -> Result<()> {
    let mut tui_adapter = TuiAdapter::new(tui);
    let mut pending = effect_runner
        .run(
            effects,
            &mut tui_adapter,
            state,
            completion_engine,
            services,
        )
        .await?;
    state.clear_dirty();

    let mut depth = 0;
    while !pending.is_empty() && depth < MAX_DEPTH {
        depth += 1;
        let mut next = Vec::new();
        for action in pending {
            let now = Instant::now();
            let mut effects = reduce(state, action, now, services);
            if state.render_dirty {
                state.clear_expired_timers(now);
                effects.push(Effect::Render);
            }
            let mut tui_adapter = TuiAdapter::new(tui);
            next.extend(
                effect_runner
                    .run(
                        effects,
                        &mut tui_adapter,
                        state,
                        completion_engine,
                        services,
                    )
                    .await?,
            );
            state.clear_dirty();
        }
        pending = next;
    }
    if depth >= MAX_DEPTH && !pending.is_empty() {
        dispatch_overflow_fallback(state, effect_runner.action_tx(), pending, Instant::now());
        // Render immediately: the main loop's next wakeup is the message expiry
        // itself, so without this draw the message would never become visible.
        let mut tui_adapter = TuiAdapter::new(tui);
        effect_runner
            .run(
                vec![Effect::Render],
                &mut tui_adapter,
                state,
                completion_engine,
                services,
            )
            .await?;
        state.clear_dirty();
    }
    Ok(())
}

const MAX_DEPTH: usize = 16;

/// Last-resort handling when DispatchActions recursion exceeds the depth
/// limit: re-queue through the action channel and surface the failure as a
/// UI error message (stderr would corrupt the TUI-owned screen).
fn dispatch_overflow_fallback(
    state: &mut AppState,
    action_tx: &mpsc::Sender<Action>,
    pending: Vec<Action>,
    now: Instant,
) {
    let deferred = pending.len();
    let mut dropped = 0usize;
    for action in pending {
        if action_tx.try_send(action).is_err() {
            dropped += 1;
        }
    }
    let message = if dropped > 0 {
        format!(
            "Internal error: action dispatch depth exceeded ({MAX_DEPTH}); {dropped} actions dropped"
        )
    } else {
        format!(
            "Internal error: action dispatch depth exceeded ({MAX_DEPTH}); {deferred} actions deferred"
        )
    };
    state.messages.set_error_at(message, now);
}

const MAX_DRAIN: usize = 32;

async fn drain_and_process_terminal_events(
    first_action: Action,
    state: &mut AppState,
    tui: &mut TuiRunner,
    effect_runner: &EffectRunner,
    completion_engine: &RefCell<CompletionEngine>,
    services: &AppServices,
) -> Result<()> {
    if !first_action.is_scroll() {
        return process_action(
            first_action,
            state,
            tui,
            effect_runner,
            completion_engine,
            services,
        )
        .await;
    }

    let now = Instant::now();
    let mut effects = reduce(state, first_action, now, services);
    if !effects.is_empty() {
        if state.render_dirty {
            state.clear_expired_timers(now);
            effects.push(Effect::Render);
        }
        return flush_effects(
            effects,
            state,
            tui,
            effect_runner,
            completion_engine,
            services,
        )
        .await;
    }

    let mut drained = 0;
    while drained < MAX_DRAIN {
        let Some(event) = tui.try_next_event() else {
            break;
        };
        drained += 1;
        let action = handle_event(event, state, services);
        if action.is_none() {
            continue;
        }

        if action.is_scroll() {
            let now = Instant::now();
            let mut effects = reduce(state, action, now, services);
            if !effects.is_empty() {
                if state.render_dirty {
                    state.clear_expired_timers(now);
                    effects.push(Effect::Render);
                }
                flush_effects(
                    effects,
                    state,
                    tui,
                    effect_runner,
                    completion_engine,
                    services,
                )
                .await?;
                break;
            }
        } else {
            if state.render_dirty {
                state.clear_dirty();
                process_action(
                    Action::Render,
                    state,
                    tui,
                    effect_runner,
                    completion_engine,
                    services,
                )
                .await?;
            }
            process_action(
                action,
                state,
                tui,
                effect_runner,
                completion_engine,
                services,
            )
            .await?;
            if state.should_quit {
                return Ok(());
            }
        }
    }

    if state.render_dirty {
        state.clear_dirty();
        process_action(
            Action::Render,
            state,
            tui,
            effect_runner,
            completion_engine,
            services,
        )
        .await?;
    }

    Ok(())
}

fn load_service_entries(state: &mut AppState, reader: Option<&dyn PgServiceEntryReader>) {
    let Some(reader) = reader else {
        return;
    };

    match reader.read_services() {
        Ok((services, path)) if !services.is_empty() => {
            state.set_service_entries(services);
            state.runtime.service_file_path = Some(path);
        }
        Ok(_) | Err(ServiceFileError::NotFound(_)) => {}
        Err(e) => {
            state.messages.set_error_at(e.to_string(), Instant::now());
        }
    }
}

#[cfg(feature = "self-update")]
#[allow(clippy::print_stdout, reason = "CLI subcommand output, TUI not active")]
fn run_update() -> Result<()> {
    let current = env!("CARGO_PKG_VERSION");
    println!("Current version: v{current}");
    println!("Checking for updates...");

    let status = self_update::backends::github::Update::configure()
        .repo_owner("riii111")
        .repo_name("sabiql")
        .bin_name("sabiql")
        .show_download_progress(true)
        .no_confirm(true)
        .current_version(current)
        .build()?
        .update()?;

    if status.updated() {
        println!("Updated successfully: v{} -> {}", current, status.version());
    } else {
        println!("Already up to date (v{current}).");
    }

    Ok(())
}

#[cfg(not(feature = "self-update"))]
fn self_update_disabled_message() -> String {
    format!(
        "Self-update is not available in this build (v{}).\n\
         If installed via Homebrew: brew upgrade sabiql\n\
         If installed via cargo:    cargo install sabiql",
        env!("CARGO_PKG_VERSION")
    )
}