zippa-db 0.1.0

A fast, lightweight, cross-platform database client for PostgreSQL, MySQL, and SQLite.
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! The Import SQL Dump dialog.
//!
//! Opened from the session's sidebar, the File menu, or `Cmd`/`Ctrl`+`Shift`+`I`.
//! It runs in three states: a pre-flight where the user picks what a failure
//! should do, a running state with a progress bar, and a summary with the
//! errors that were collected.
//!
//! The view owns the import task and its abort handle, so cancelling from
//! inside the dialog or from the session's `Cmd`/`Ctrl`+`.` both reach it. The
//! work itself runs on [`runtime`](crate::db::runtime) against a single
//! dedicated connection; this view only reflects it.
//!
//! The dialog is `gpui_kit`'s [`Dialog`](gpui_kit::component::dialog::Dialog),
//! opened by the session, and this view is its body. It emits
//! [`ImportEvent::Dismissed`] when the user is done with it and
//! [`ImportEvent::Finished`] when a run ends, so the session can reload the
//! sidebar.

use std::path::PathBuf;
use std::sync::Arc;

use gpui_kit::base::TestSupportExt;
use gpui_kit::component::button::{Button, ButtonVariants};
use gpui_kit::component::progress::Progress;
use gpui_kit::component::radio::{Radio, RadioGroup};
use gpui_kit::component::{ActiveTheme, Disableable, Sizable, h_flex, v_flex};
use gpui_kit::prelude::*;
use gpui_kit::{ClipboardItem, Context, EventEmitter, SharedString, Window, actions, div};

use crate::db::import::{self, Preflight};
use crate::db::{
    Connection, Engine, ImportProgress, ImportRequest, ImportSummary, OnError, runtime,
};

actions!(zippa_db, [CloseImport]);

/// What the dialog tells its owner.
pub enum ImportEvent {
    /// The user is done with the dialog; the session takes it off screen.
    Dismissed,
    /// A run ended, whether it succeeded or failed; the sidebar is stale.
    Finished,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    Ready,
    Running,
    Done,
}

pub struct ImportView {
    connection: Arc<Connection>,
    path: PathBuf,
    name: SharedString,
    /// What the pre-flight read found; `None` until the background read lands.
    preflight: Option<Preflight>,
    on_error: OnError,
    state: State,
    progress: ImportProgress,
    summary: Option<ImportSummary>,
    failure: Option<String>,
    abort: Option<tokio::task::AbortHandle>,
    /// The dialog body's own focus, so `escape` reaches `CloseImport`.
    focus: gpui_kit::FocusHandle,
}

impl EventEmitter<ImportEvent> for ImportView {}

impl ImportView {
    pub fn new(
        connection: Arc<Connection>,
        path: PathBuf,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let name = path
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.display().to_string())
            .into();

        // Reading and decompressing the head of the dump is blocking I/O, so it
        // runs off the UI thread; the panel says it is checking until it lands.
        let engine = connection.config.engine;
        let task = cx.background_spawn({
            let path = path.clone();
            async move { import::preflight(&path, engine) }
        });
        cx.spawn(async move |this, cx| {
            let preflight = task.await;
            this.update(cx, |this, cx| {
                this.preflight = Some(preflight);
                cx.notify();
            })
            .ok();
        })
        .detach();

        Self {
            connection,
            path,
            name,
            preflight: None,
            on_error: OnError::default(),
            state: State::Ready,
            progress: ImportProgress::default(),
            summary: None,
            failure: None,
            abort: None,
            focus: cx.focus_handle(),
        }
    }

    /// Put the keyboard on the dialog body, where `escape` is handled.
    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
        self.focus.focus(window, cx);
    }

    /// The reason the import cannot start, if there is one.
    fn blocked_reason(&self) -> Option<String> {
        if let Some(error) = self
            .preflight
            .as_ref()
            .and_then(|preflight| preflight.error.clone())
        {
            return Some(error);
        }
        if self.connection.config.safety.is_read_only() {
            return Some(format!(
                "This connection is {} — importing would write to it.",
                self.connection.config.safety.label().to_lowercase()
            ));
        }
        None
    }

    /// Whether a run can start: the pre-flight has answered and nothing blocks
    /// it.
    fn can_start(&self) -> bool {
        self.preflight.is_some() && self.blocked_reason().is_none()
    }

    /// The database a run writes into, named on the button.
    fn target(&self) -> String {
        if self.connection.config.engine.is_file_based() {
            crate::db::file_name(self.connection.database())
        } else {
            self.connection.database().to_string()
        }
    }

    fn start(&mut self, cx: &mut Context<Self>) {
        if self.state != State::Ready || !self.can_start() {
            return;
        }

        let connection = self.connection.clone();
        let request = ImportRequest {
            path: self.path.clone(),
            on_error: self.on_error,
        };
        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
        let task = runtime::spawn(async move { connection.import_dump(request, sender).await });

        self.abort = task.abort_handle();
        self.state = State::Running;
        self.progress = ImportProgress::default();
        self.summary = None;
        self.failure = None;
        cx.notify();

        // Progress arrives on its own channel while the run is in flight.
        cx.spawn(async move |this, cx| {
            while let Some(update) = receiver.recv().await {
                this.update(cx, |this, cx| {
                    this.progress = update;
                    cx.notify();
                })
                .ok();
            }
        })
        .detach();

        cx.spawn(async move |this, cx| {
            let result = task.await;
            this.update(cx, |this, cx| this.finish(result, cx)).ok();
        })
        .detach();
    }

    fn finish(
        &mut self,
        result: Result<
            Result<ImportSummary, anyhow::Error>,
            tokio::sync::oneshot::error::RecvError,
        >,
        cx: &mut Context<Self>,
    ) {
        self.abort = None;
        self.state = State::Done;

        match result {
            Ok(Ok(summary)) => self.summary = Some(summary),
            Ok(Err(error)) => self.failure = Some(format!("{error:#}")),
            // The sender is dropped when the run is given up on.
            Err(_) => self.failure = Some("Cancelled".to_string()),
        }
        // Whatever the outcome, statements may already have been applied — a
        // stopped run keeps what ran, and so does a cancelled one — so the
        // schema and any open table are stale either way.
        cx.emit(ImportEvent::Finished);
        cx.notify();
    }

    /// Stop the run in flight, the way `Cmd`/`Ctrl`+`.` does.
    pub(crate) fn cancel(&mut self, _cx: &mut Context<Self>) {
        if let Some(abort) = self.abort.take() {
            abort.abort();
        }
    }

    fn close(&mut self, cx: &mut Context<Self>) {
        cx.emit(ImportEvent::Dismissed);
    }

    fn on_close(&mut self, _: &CloseImport, _window: &mut Window, cx: &mut Context<Self>) {
        self.close(cx);
    }

    fn copy_log(&self, cx: &mut Context<Self>) {
        cx.write_to_clipboard(ClipboardItem::new_string(self.log()));
    }

    /// The whole run as text, for the clipboard.
    fn log(&self) -> String {
        let size = self
            .summary
            .as_ref()
            .map(|summary| summary.total_bytes)
            .filter(|bytes| *bytes > 0)
            .unwrap_or_else(|| {
                self.preflight
                    .as_ref()
                    .map(|preflight| preflight.total_bytes)
                    .unwrap_or(0)
            });
        let mut text = format!("Import of {} ({})\n", self.path.display(), bytes(size));
        if let Some(failure) = &self.failure {
            text.push_str(&format!("Failed: {failure}\n"));
        }
        if let Some(summary) = &self.summary {
            text.push_str(&format!("{}\n", summary.summary()));
            if summary.dump_transaction {
                text.push_str("The dump carried its own transaction; the import managed it.\n");
            }
            for error in &summary.errors {
                text.push_str(&format!(
                    "line {}: {}\n  {}\n",
                    error.line, error.statement, error.message
                ));
            }
            if summary.dropped_errors > 0 {
                text.push_str(&format!(
                    "…and {} more errors not listed.\n",
                    summary.dropped_errors
                ));
            }
        }
        text
    }

    fn render_details(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let safety = self.connection.config.safety;
        v_flex()
            .gap_1()
            .child(
                h_flex()
                    .justify_between()
                    .child(div().text_sm().child(self.name.clone()))
                    .child(
                        div()
                            .text_xs()
                            .text_color(cx.theme().muted_foreground)
                            .child(match &self.preflight {
                                Some(preflight) => format!(
                                    "{} · {}",
                                    bytes(preflight.total_bytes),
                                    preflight.compression.label()
                                ),
                                None => "Checking the dump…".to_string(),
                            }),
                    ),
            )
            .child(
                div()
                    .text_xs()
                    .text_color(cx.theme().muted_foreground)
                    .child(format!(
                        "Into {} on {} · {}",
                        self.target(),
                        self.connection.config.engine.label(),
                        safety.label()
                    )),
            )
    }

    fn render_warnings(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let mismatch = self
            .preflight
            .as_ref()
            .and_then(|preflight| preflight.dialect_mismatch.clone());
        let destructive = self
            .preflight
            .as_ref()
            .map(|preflight| preflight.destructive)
            .unwrap_or(0);
        let fallback = self.connection.config.engine == Engine::MySql;

        v_flex()
            .gap_1()
            .when_some(mismatch, |this, warning| {
                this.child(warning_row(warning, cx.theme().warning))
            })
            .when(destructive > 0, |this| {
                this.child(warning_row(
                    format!(
                        "This dump contains {destructive} statement{} that drop or clear data.",
                        if destructive == 1 { "" } else { "s" }
                    ),
                    cx.theme().warning,
                ))
            })
            .when(fallback, |this| {
                this.child(warning_row(
                    "MySQL commits DDL itself, so rolling back is not possible; it falls back to stopping."
                        .to_string(),
                    cx.theme().muted_foreground,
                ))
            })
    }

    fn render_policy(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let engine = self.connection.config.engine;
        let selected = OnError::ALL
            .iter()
            .position(|policy| *policy == self.on_error)
            .unwrap_or(0);

        v_flex()
            .gap_1()
            .child(
                div()
                    .text_xs()
                    .text_color(cx.theme().muted_foreground)
                    .child("If a statement fails"),
            )
            .child(
                RadioGroup::new("import-policy")
                    .selected_index(Some(selected))
                    .on_change(cx.listener(|this, index, _window, cx| {
                        if let Some(policy) = OnError::ALL.get(*index) {
                            this.on_error = *policy;
                            cx.notify();
                        }
                    }))
                    .children(OnError::ALL.iter().enumerate().map(|(ix, policy)| {
                        Radio::new(SharedString::from(format!("import-policy-{ix}")))
                            .label(SharedString::from(policy.label()))
                            // MySQL cannot honour a rollback; the option stays
                            // visible but disabled, which is how the reason is
                            // discoverable without pretending it works.
                            .disabled(engine == Engine::MySql && *policy == OnError::Rollback)
                    })),
            )
            .child(
                div()
                    .text_xs()
                    .text_color(cx.theme().muted_foreground)
                    .child(self.on_error.description()),
            )
    }

    fn render_ready(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let blocked = self.blocked_reason();
        let can_start = self.can_start();
        // While the pre-flight is still reading, the button is off with a tooltip
        // that says why; a real block takes its place once it is known.
        let blocked_for_button = blocked.clone().or_else(|| {
            self.preflight
                .is_none()
                .then(|| "Checking the dump…".to_string())
        });

        v_flex()
            .flex_1()
            .gap_3()
            .child(self.render_details(cx))
            .when_some(blocked, |this, reason| {
                this.child(
                    div()
                        .text_sm()
                        .text_color(cx.theme().danger)
                        .child(format!("Cannot import: {reason}")),
                )
            })
            .child(self.render_warnings(cx))
            .child(self.render_policy(cx))
            .child(
                h_flex()
                    .gap_2()
                    .justify_end()
                    .child(
                        Button::new("import-cancel")
                            .ghost()
                            .small()
                            .label("Close")
                            .tooltip_with_action(
                                "Close the import dialog",
                                &CloseImport,
                                Some("ImportDialog"),
                            )
                            .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
                    )
                    .child(
                        Button::new("import-start")
                            .primary()
                            .small()
                            .label(format!("Import into {}", self.target()))
                            .disabled(!can_start)
                            .when_some(blocked_for_button, |button, reason| {
                                button.tooltip(SharedString::from(reason))
                            })
                            .on_click(cx.listener(|this, _, _, cx| this.start(cx))),
                    ),
            )
    }

    fn render_running(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let percent = self.progress.percent();

        v_flex()
            .flex_1()
            .gap_3()
            .child(self.render_details(cx))
            .child(
                Progress::new("import-progress")
                    .small()
                    .value(percent)
                    .accessibility_label(SharedString::from(format!(
                        "Import progress: {:.0}%",
                        percent
                    ))),
            )
            .child(
                // The bar alone says nothing to a screen reader or a
                // colour-blind reader, so the numbers are always spoken out.
                div()
                    .text_xs()
                    .text_color(cx.theme().muted_foreground)
                    .child(format!(
                        "{:.0}% · {} · {} · line {}",
                        percent,
                        plural(self.progress.statements, "statement"),
                        plural(self.progress.errors, "error"),
                        self.progress.line
                    )),
            )
            .child(
                h_flex().gap_2().justify_end().child(
                    Button::new("import-stop")
                        .outline()
                        .small()
                        .label("Cancel")
                        .on_click(cx.listener(|this, _, _, cx| this.cancel(cx))),
                ),
            )
    }

    fn render_done(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let failures = self
            .summary
            .as_ref()
            .map(|summary| summary.errors.len() + summary.dropped_errors as usize)
            .unwrap_or(0);

        v_flex()
            .flex_1()
            .gap_3()
            .child(self.render_details(cx))
            .child(
                div()
                    .text_sm()
                    .text_color(if self.failure.is_some() {
                        cx.theme().danger
                    } else if failures > 0 {
                        cx.theme().warning
                    } else {
                        cx.theme().success
                    })
                    .child(match (&self.failure, &self.summary) {
                        (Some(failure), _) => failure.clone(),
                        (None, Some(summary)) => summary.summary(),
                        (None, None) => "Done".to_string(),
                    }),
            )
            .when_some(self.render_errors(cx), |this, errors| this.child(errors))
            .when_some(self.notes(), |this, notes| {
                this.child(
                    div()
                        .text_xs()
                        .text_color(cx.theme().muted_foreground)
                        .child(notes),
                )
            })
            .child(
                h_flex()
                    .gap_2()
                    .justify_end()
                    .child(
                        Button::new("import-copy")
                            .ghost()
                            .small()
                            .label("Copy log")
                            .accessibility_label("Copy the import log to the clipboard")
                            .on_click(cx.listener(|this, _, _, cx| this.copy_log(cx))),
                    )
                    .child(
                        Button::new("import-close")
                            .primary()
                            .small()
                            .label("Close")
                            .tooltip_with_action(
                                "Close the import dialog",
                                &CloseImport,
                                Some("ImportDialog"),
                            )
                            .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
                    ),
            )
    }

    /// A line of small print for the ways a run's shape differed from what
    /// happened: a dump that carried its own transaction, or a rollback that
    /// had to become a stop.
    fn notes(&self) -> Option<String> {
        let summary = self.summary.as_ref()?;
        let mut notes = Vec::new();
        if summary.dump_transaction {
            notes.push(
                "The dump carried its own BEGIN/COMMIT; the import managed them.".to_string(),
            );
        }
        if summary.mysql_rollback_fallback {
            notes.push(
                "MySQL cannot roll a dump back, so the run stopped at the first error.".to_string(),
            );
        }
        (!notes.is_empty()).then(|| notes.join(" "))
    }

    fn render_errors(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
        let summary = self.summary.as_ref()?;
        if summary.errors.is_empty() {
            return None;
        }

        let rows = summary.errors.iter().map(|error| {
            v_flex()
                .gap_0p5()
                .child(
                    div()
                        .text_xs()
                        .text_color(cx.theme().danger)
                        .child(format!("Error at line {}: {}", error.line, error.message)),
                )
                .child(
                    div()
                        .text_xs()
                        .text_color(cx.theme().muted_foreground)
                        .truncate()
                        .child(error.statement.clone()),
                )
        });

        Some(
            div()
                .id("import-errors")
                .flex_1()
                .min_h_0()
                .overflow_y_scroll()
                .border_1()
                .border_color(cx.theme().border)
                .rounded(cx.theme().radius)
                .p_2()
                .child(v_flex().gap_2().children(rows)),
        )
    }
}

impl Render for ImportView {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        v_flex()
            .id("import-dialog")
            .test_support()
            .size_full()
            .gap_3()
            .track_focus(&self.focus)
            .key_context("ImportDialog")
            .on_action(cx.listener(Self::on_close))
            .child(match self.state {
                State::Ready => self.render_ready(cx).into_any_element(),
                State::Running => self.render_running(cx).into_any_element(),
                State::Done => self.render_done(cx).into_any_element(),
            })
    }
}

/// A dim warning line, in words rather than colour alone.
fn warning_row(message: String, color: gpui_kit::Hsla) -> impl IntoElement {
    div().text_xs().text_color(color).child(message)
}

/// `"1 statement"` / `"3 statements"`.
fn plural(count: u64, noun: &str) -> String {
    if count == 1 {
        format!("{count} {noun}")
    } else {
        format!("{count} {noun}s")
    }
}

/// A file size, in units a person reads.
fn bytes(bytes: u64) -> String {
    const UNITS: [&str; 4] = ["B", "KB", "MB", "GB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit + 1 < UNITS.len() {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

#[cfg(test)]
impl ImportView {
    pub(crate) fn is_ready_for_test(&self) -> bool {
        self.state == State::Ready
    }

    pub(crate) fn is_done_for_test(&self) -> bool {
        self.state == State::Done
    }

    pub(crate) fn blocked_reason_for_test(&self) -> Option<String> {
        self.blocked_reason()
    }

    pub(crate) fn set_on_error_for_test(&mut self, policy: OnError, cx: &mut Context<Self>) {
        self.on_error = policy;
        cx.notify();
    }

    pub(crate) fn start_for_test(&mut self, cx: &mut Context<Self>) {
        self.start(cx);
    }

    pub(crate) fn summary_for_test(&self) -> Option<ImportSummary> {
        self.summary.clone()
    }

    pub(crate) fn copy_log_for_test(&self, cx: &mut Context<Self>) {
        self.copy_log(cx);
    }

    pub(crate) fn dismiss_for_test(&mut self, cx: &mut Context<Self>) {
        self.close(cx);
    }
}