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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! Headless UI tests: render the real views in a test window and check the
//! layout facts that are easy to break, such as controls being pushed out of
//! the window or a pane collapsing to zero height.
//!
//! One file per area, with the fixtures they share kept here: a test that
//! opens a session, types into a grid, or drives a dialog reaches for the same
//! few helpers whatever it is about.

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

use gpui_kit::component::scroll::ScrollbarMode;
use gpui_kit::component::table::ColumnSort;
use gpui_kit::component::{Root, Theme, ThemeMode, WindowExt};
use gpui_kit::test::TestWindowExt;
use gpui_kit::{
    App, AppContext as _, Bounds, Context, ElementId, Entity, InputEvent as _, Modifiers,
    MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, TestAppContext, Window,
    WindowHandle, point, px, size,
};
use uuid::Uuid;

use crate::app::Workspace;
use crate::settings::{self, Appearance, Settings};
use crate::ui::settings_window;
use crate::ui::welcome::WelcomeEvent;
use crate::workspace_state::{PanelState, SessionState, WorkspaceState};

use crate::db::export::Format;
use crate::db::query::QueryResult;
use crate::db::tests::TempDatabase;
use crate::db::{
    Connection, ConnectionConfig, DatabaseObject, Engine, ObjectKind, SafetyMode, TagColor, runtime,
};
use crate::ui::filter_bar::{FilterSpec, Operator};
use crate::ui::session::{CloseScope, Session};
use crate::ui::welcome::Welcome;

mod console;
mod editing;
mod explain;
mod export;
mod files;
mod filters;
mod import;
mod layout;
mod navigation;
mod paging;
mod preferences;
mod process_list;
mod query_digest;
mod quick_switcher;
mod row_panel;
mod rows;
mod running;
mod safety;
mod schema;
mod schema_search;
mod server_variables;
mod session;
mod sorting;
mod sqlite_maintenance;
mod value_dialog;
mod welcome;
mod workspace;

const WINDOW: (f32, f32) = (900., 600.);

/// `gpui_kit::component::init` with reduced motion on. GPUI times animations
/// on the wall clock, not the test scheduler's, and a dialog slides into
/// place: in a slow (unoptimized) build it can move between a click's
/// mouse-down and mouse-up, and the click misses its button. Reduced motion
/// draws every one-shot animation at its end state from the first frame.
fn init_ui(cx: &mut App) {
    gpui_kit::component::init(cx);
    cx.set_reduce_motion(true);
}

fn contains(window: Bounds<Pixels>, element: Bounds<Pixels>) -> bool {
    element.left() >= window.left()
        && element.right() <= window.right()
        && element.top() >= window.top()
        && element.bottom() <= window.bottom()
}

fn result_fixture() -> QueryResult {
    QueryResult {
        columns: vec!["id".into(), "name".into()],
        rows: vec![
            vec![Some("1".into()), Some("alpha".into())],
            vec![Some("2".into()), None],
        ],
        ..QueryResult::default()
    }
}

/// Build a session on a temporary SQLite database with the sidebar filled in.
fn session_with_objects(
    cx: &mut TestAppContext,
) -> (TempDatabase, gpui_kit::WindowHandle<Session>) {
    session_with_safety(cx, SafetyMode::default())
}

/// The same, on a connection that handles inline edits the way `safety` says.
fn session_with_safety(
    cx: &mut TestAppContext,
    safety: SafetyMode,
) -> (TempDatabase, gpui_kit::WindowHandle<Session>) {
    let database = runtime::block_on(TempDatabase::new());
    let config = ConnectionConfig {
        safety,
        ..database.config()
    };
    let connection = runtime::block_on(Connection::open(config, None))
        .expect("could not open the test database");

    cx.update(|cx| {
        init_ui(cx);
        crate::keymap::bind(cx);
    });
    let handle = {
        let connection = Arc::new(connection);
        cx.open_window(size(px(WINDOW.0), px(WINDOW.1)), |window, cx| {
            Session::new(connection, window, cx)
        })
    };

    handle
        .update(cx, |session, _, cx| {
            session.set_metadata_for_test(
                vec!["main".to_string()],
                vec![DatabaseObject {
                    schema: None,
                    name: "items".into(),
                    kind: ObjectKind::Table,
                }],
                cx,
            );
        })
        .unwrap();

    (database, handle)
}

/// Open a table tab on the seeded `items` table and hand back its view.
fn table_view(
    cx: &mut TestAppContext,
) -> (
    TempDatabase,
    gpui_kit::WindowHandle<Session>,
    gpui_kit::Entity<crate::ui::table_view::TableView>,
) {
    table_view_with_safety(cx, SafetyMode::default())
}

/// The same, on a connection that handles inline edits the way `safety` says.
fn table_view_with_safety(
    cx: &mut TestAppContext,
    safety: SafetyMode,
) -> (
    TempDatabase,
    gpui_kit::WindowHandle<Session>,
    gpui_kit::Entity<crate::ui::table_view::TableView>,
) {
    let (database, handle) = session_with_safety(cx, safety);

    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.click("object-items", cx);
    })
    .unwrap();

    let view = handle
        .update(cx, |session, _, cx| session.active_table_view(cx))
        .unwrap()
        .expect("clicking a table should open a table view");

    (database, handle, view)
}

/// Open a structure tab on the seeded `items` table and hand back its view.
fn schema_view(
    cx: &mut TestAppContext,
) -> (
    TempDatabase,
    gpui_kit::WindowHandle<Session>,
    gpui_kit::Entity<crate::ui::schema_view::SchemaView>,
) {
    let (database, handle) = session_with_objects(cx);

    let object = DatabaseObject {
        schema: None,
        name: "items".into(),
        kind: ObjectKind::Table,
    };
    handle
        .update(cx, |session, window, cx| {
            session.open_schema_for_test(&object, window, cx);
        })
        .unwrap();
    cx.run_until_parked();

    let view = handle
        .update(cx, |session, _, cx| session.active_schema_view(cx))
        .unwrap()
        .expect("opening a table's structure should open a schema view");

    (database, handle, view)
}

/// A directory the file dialogs can be pointed at, removed with the test.
struct ScratchDir {
    path: PathBuf,
}

impl ScratchDir {
    fn new() -> Self {
        let path = std::env::temp_dir().join(format!("zippa-db-files-{}", Uuid::new_v4()));
        std::fs::create_dir_all(&path).expect("could not create the scratch directory");
        Self { path }
    }

    /// Put a file in the directory and hand back its path.
    fn file(&self, name: &str, contents: &str) -> PathBuf {
        let path = self.path.join(name);
        std::fs::write(&path, contents).expect("could not write the scratch file");
        path
    }
}

impl Drop for ScratchDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

/// Draw the session and click a button in it by id.
fn click_in_session(cx: &mut TestAppContext, handle: WindowHandle<Session>, id: &'static str) {
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.click(id, cx);
    })
    .unwrap();
}

/// Draw the session and send it a keystroke; something inside it must already
/// hold focus for the keystroke to reach the Session key context.
fn press(cx: &mut TestAppContext, handle: WindowHandle<Session>, keystroke: &str) {
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.press(keystroke, cx);
    })
    .unwrap();
}

/// Four rows whose original, ascending, and descending orders all differ.
fn scores() -> QueryResult {
    QueryResult {
        columns: vec!["score".into(), "name".into()],
        rows: vec![
            vec![Some("10".into()), Some("ada".into())],
            vec![Some("9".into()), Some("grace".into())],
            vec![None, Some("unknown".into())],
            vec![Some("100".into()), Some("alan".into())],
        ],
        ..QueryResult::default()
    }
}

/// A workspace window, the way `main` opens one: the workspace inside a
/// `Root`, so the layer a dialog opens into is really there.
struct WorkspaceWindow {
    window: WindowHandle<Root>,
    view: Entity<Workspace>,
}

impl WorkspaceWindow {
    /// Reach the workspace itself, with the window the `Root` holds it in.
    fn update<R>(
        &self,
        cx: &mut TestAppContext,
        update: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> R,
    ) -> gpui_kit::Result<R> {
        self.window.update(cx, |_, window, cx| {
            self.view
                .update(cx, |workspace, cx| update(workspace, window, cx))
        })
    }
}

fn workspace(cx: &mut TestAppContext) -> WorkspaceWindow {
    workspace_from(cx, WorkspaceState::default())
}

/// A workspace window built from an injected state, the way `main` builds it
/// from the file — so no test ever reads the developer's own workspace.
fn workspace_from(cx: &mut TestAppContext, state: WorkspaceState) -> WorkspaceWindow {
    cx.update(|cx| {
        init_ui(cx);
        crate::keymap::bind(cx);
    });

    let state = std::cell::RefCell::new(Some(state));
    let view = std::cell::RefCell::new(None);
    let window = cx.open_window(size(px(WINDOW.0), px(WINDOW.1)), |window, cx| {
        let state = state.borrow_mut().take().expect("the state is taken once");
        let workspace = cx.new(|cx| Workspace::with_state_for_test(state, window, cx));
        *view.borrow_mut() = Some(workspace.clone());
        Root::new(workspace, window, cx)
    });
    // The crash dialog needs the root layer the window above just built.
    // `update_window` (not `update`) avoids borrowing the root view,
    // which the dialog itself needs to update.
    cx.update_window(window.into(), |_, window, cx| {
        Workspace::report_crash(window, cx)
    })
    .unwrap();
    let view = view.into_inner().expect("the workspace is built above");

    WorkspaceWindow { window, view }
}

/// A workspace restored from `state`, with `connections` saved in a scratch
/// config directory so the reconnect can find them. The directory must outlive
/// the workspace, so it is handed back.
fn restored_workspace(
    cx: &mut TestAppContext,
    state: WorkspaceState,
    connections: Vec<ConnectionConfig>,
) -> (ScratchDir, WorkspaceWindow) {
    let dir = ScratchDir::new();
    crate::db::store::set_config_dir_for_test(dir.path.clone());
    crate::db::store::save(&connections).expect("could not save the test connections");
    let handle = workspace_from(cx, state);
    (dir, handle)
}

/// Open a connection to a database of its own from the active tab, the way
/// the connection manager does when its Connect button succeeds.
fn connect(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> TempDatabase {
    connect_with_safety(cx, handle, SafetyMode::default())
}

/// The same, on a connection whose write mode is `safety`.
fn connect_with_safety(
    cx: &mut TestAppContext,
    handle: &WorkspaceWindow,
    safety: SafetyMode,
) -> TempDatabase {
    let database = runtime::block_on(TempDatabase::new());
    let config = ConnectionConfig {
        safety,
        ..database.config()
    };
    connect_config(cx, handle, config);
    database
}

/// The same, on a connection named `name`, which is what a user gives one so
/// its tab does not read as its database alone.
fn connect_named(cx: &mut TestAppContext, handle: &WorkspaceWindow, name: &str) -> TempDatabase {
    let database = runtime::block_on(TempDatabase::new());
    let config = ConnectionConfig {
        name: name.to_string(),
        ..database.config()
    };
    connect_config(cx, handle, config);
    database
}

/// Connect the active connection-manager tab with `config`.
fn connect_config(cx: &mut TestAppContext, handle: &WorkspaceWindow, config: ConnectionConfig) {
    let connection = Arc::new(
        runtime::block_on(Connection::open(config, None))
            .expect("could not open the test database"),
    );

    let welcome = handle
        .update(cx, |workspace, _, _| workspace.active_welcome_for_test())
        .unwrap()
        .expect("the active tab should be showing the connection manager");

    welcome.update(cx, |_, cx| cx.emit(WelcomeEvent::Connected(connection)));
    cx.run_until_parked();
}

/// Open a session inside a workspace, which is where the `Root` an
/// `AlertDialog` needs lives.
fn workspace_session(cx: &mut TestAppContext) -> (TempDatabase, WorkspaceWindow, Entity<Session>) {
    workspace_session_with_safety(cx, SafetyMode::default())
}

/// The same, on a connection that handles writes the way `safety` says.
fn workspace_session_with_safety(
    cx: &mut TestAppContext,
    safety: SafetyMode,
) -> (TempDatabase, WorkspaceWindow, Entity<Session>) {
    let handle = workspace(cx);
    let database = connect_with_safety(cx, &handle, safety);

    let session = handle
        .update(cx, |workspace, _, _| workspace.active_session_for_test())
        .unwrap()
        .expect("the active tab should be a session");
    cx.run_until_parked();

    (database, handle, session)
}

/// Put `sql` in a workspace session's editor and hand it the keyboard.
fn prepare_workspace_editor(
    cx: &mut TestAppContext,
    handle: &WorkspaceWindow,
    session: &Entity<Session>,
    sql: &str,
) {
    let session = session.clone();
    let sql = sql.to_string();
    cx.update_window(handle.window.into(), |_, window, cx| {
        session.update(cx, |session, cx| {
            session.prepare_active_editor_for_test(&sql, window, cx);
        });
    })
    .unwrap();
}

/// Close a workspace session's tab by index, the way its ✕ does.
fn close_workspace_tab(
    cx: &mut TestAppContext,
    handle: &WorkspaceWindow,
    session: &Entity<Session>,
    index: usize,
) {
    let session = session.clone();
    cx.update_window(handle.window.into(), |_, window, cx| {
        session.update(cx, |session, cx| {
            session.close_tab_for_test(index, window, cx);
        });
    })
    .unwrap();
    cx.run_until_parked();
}

fn press_workspace(cx: &mut TestAppContext, handle: &WorkspaceWindow, keystroke: &str) {
    cx.update_window(handle.window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.press(keystroke, cx);
    })
    .unwrap();
    cx.run_until_parked();
}

fn click_workspace(cx: &mut TestAppContext, handle: &WorkspaceWindow, id: impl Into<ElementId>) {
    let id = id.into();
    cx.update_window(handle.window.into(), move |_, window, cx| {
        window.draw(cx).clear(cx);
        window.click(id, cx);
    })
    .unwrap();
    cx.run_until_parked();
}

fn workspace_dialog_open(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> bool {
    cx.update_window(handle.window.into(), |_, window, cx| {
        window.has_active_dialog(cx)
    })
    .unwrap()
}

fn titles(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> Vec<String> {
    handle
        .update(cx, |workspace, _, cx| workspace.tab_titles_for_test(cx))
        .unwrap()
}

fn labels(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> Vec<String> {
    handle
        .update(cx, |workspace, _, cx| workspace.tab_labels_for_test(cx))
        .unwrap()
}

fn active(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> usize {
    handle
        .update(cx, |workspace, _, _| workspace.active_for_test())
        .unwrap()
}

fn click(cx: &mut TestAppContext, handle: &WorkspaceWindow, id: &'static str) {
    cx.update_window(handle.window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.click(id, cx);
    })
    .unwrap();
}

/// Reopen the test database and count the rows in `items`, the way the test
/// above checks that refresh did not run an INSERT sitting in a query tab.
async fn other_count(database: &TempDatabase) -> i64 {
    let connection = Connection::open(database.config(), None)
        .await
        .expect("could not reopen the test database");
    let result = connection
        .run_query("select count(*) as n from items")
        .await
        .expect("could not count the rows");
    connection.close().await;
    result.rows[0][0]
        .as_ref()
        .expect("count(*) should not be null")
        .parse()
        .expect("count(*) should be a number")
}

/// Stage `value` in a cell of the open table view's grid.
///
/// The selection and the editor are two separate frames on purpose: focus
/// moves when a frame is drawn, so doing both at once would leave the table
/// holding the focus and blur the editor straight back out again.
fn stage_cell(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
    row: usize,
    col: usize,
    value: &str,
) {
    let grid = view.read_with(cx, |view, _| view.grid_for_test());
    // Editing starts from a click in the grid, which focuses it and selects
    // the cell.
    grid.downgrade()
        .update_in(cx, |grid, window, cx| {
            grid.focus_for_test(window, cx);
            grid.select_cell_for_test(row, col, cx);
        })
        .unwrap();
    cx.run_until_parked();

    // A double click on the selected cell opens the editor over it.
    grid.downgrade()
        .update_in(cx, |grid, window, cx| {
            grid.begin_edit_for_test(row, col, window, cx);
            grid.set_editor_value_for_test(value, window, cx);
        })
        .unwrap();
    cx.run_until_parked();
}

/// Put the focus back on the grid itself, the way clicking out of a cell
/// editor and back onto the table does.
fn focus_grid(cx: &mut TestAppContext, view: &gpui_kit::Entity<crate::ui::table_view::TableView>) {
    let grid = view.read_with(cx, |view, _| view.grid_for_test());
    grid.downgrade()
        .update_in(cx, |grid, window, cx| {
            grid.commit_editor(cx);
            grid.focus_for_test(window, cx);
        })
        .unwrap();
}

/// The `id` column of the `items` row with this name, read through a second
/// connection.
async fn id_of(database: &TempDatabase, name: &str) -> Option<String> {
    let connection = Connection::open(database.config(), None)
        .await
        .expect("could not reopen the test database");
    let result = connection
        .run_query(&format!(
            "select id from items where name = {}",
            crate::db::quote_literal(name)
        ))
        .await
        .expect("could not read the row");
    connection.close().await;
    result.rows.first().and_then(|row| row[0].clone())
}

/// The `name` column of `items` for a row, read through a second connection.
async fn name_of(database: &TempDatabase, id: i64) -> Option<String> {
    let connection = Connection::open(database.config(), None)
        .await
        .expect("could not reopen the test database");
    let result = connection
        .run_query(&format!("select name from items where id = {id}"))
        .await
        .expect("could not read the row");
    connection.close().await;
    result.rows[0][0].clone()
}

/// Run a statement through a second connection, the way another client would.
fn run_external(database: &TempDatabase, sql: &str) {
    runtime::block_on(async {
        let connection = Connection::open(database.config(), None)
            .await
            .expect("could not open a second connection to the test database");
        connection
            .run_query(sql)
            .await
            .expect("the statement failed");
        connection.close().await;
    });
}

/// Open a table tab on a table the seed data does not have, created here.
fn table_view_on(
    cx: &mut TestAppContext,
    name: &'static str,
    create: &str,
) -> (
    TempDatabase,
    gpui_kit::WindowHandle<Session>,
    gpui_kit::Entity<crate::ui::table_view::TableView>,
) {
    let (database, handle) = session_with_objects(cx);
    run_external(&database, create);

    handle
        .update(cx, |session, _, cx| {
            session.set_metadata_for_test(
                vec!["main".to_string()],
                vec![DatabaseObject {
                    schema: None,
                    name: name.into(),
                    kind: ObjectKind::Table,
                }],
                cx,
            );
        })
        .unwrap();

    let id = gpui_kit::SharedString::from(format!("object-{name}"));
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.click(id, cx);
    })
    .unwrap();

    let view = handle
        .update(cx, |session, _, cx| session.active_table_view(cx))
        .unwrap()
        .expect("clicking a table should open a table view");

    (database, handle, view)
}

/// Select a cell the way clicking one does, with the grid holding the focus.
fn select_cell(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
    row: usize,
    col: usize,
) {
    let grid = view.read_with(cx, |view, _| view.grid_for_test());
    grid.downgrade()
        .update_in(cx, |grid, window, cx| {
            grid.focus_for_test(window, cx);
            grid.select_cell_for_test(row, col, cx);
        })
        .unwrap();
    cx.run_until_parked();
}

/// The row the grid is highlighting, and the cell the selection sits on.
fn selection(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
) -> (Option<usize>, Option<(usize, usize)>) {
    view.read_with(cx, |view, cx| {
        view.grid_for_test().read(cx).selection_for_test(cx)
    })
}

/// The rows picked out for a row command, in display order.
fn picked(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
) -> Vec<usize> {
    view.read_with(cx, |view, cx| {
        view.grid_for_test().read(cx).rows_selected_for_test(cx)
    })
}

/// Whether the grid itself holds the keyboard, rather than a cell editor or a
/// checkbox that was clicked.
fn grid_focused(
    cx: &mut TestAppContext,
    handle: WindowHandle<Session>,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
) -> bool {
    let grid = view.read_with(cx, |view, _| view.grid_for_test());
    cx.update_window(handle.into(), |_, window, cx| {
        grid.read(cx).is_focused_for_test(window, cx)
    })
    .unwrap()
}

/// What the app last put on the clipboard.
fn clipboard(cx: &mut TestAppContext) -> Option<String> {
    cx.update(|cx| cx.read_from_clipboard().and_then(|item| item.text()))
}

/// Click the pick box beside `row_ix`, the way a user checks a row out.
fn pick_row(cx: &mut TestAppContext, handle: WindowHandle<Session>, row_ix: usize) {
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.click(("pick", row_ix), cx);
    })
    .unwrap();
}

/// Export the open table, answering the save dialog with `path`.
fn export_table(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
    format: Format,
    path: &std::path::Path,
) {
    view.update(cx, |view, cx| view.export(format, cx));
    cx.simulate_new_path_selection({
        let path = path.to_path_buf();
        move |_directory| Some(path)
    });
    cx.run_until_parked();
}

/// The same, for the rows picked out in the grid.
fn export_picked_rows(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
    format: Format,
    path: &std::path::Path,
) {
    view.update(cx, |view, cx| view.export_picked(format, cx));
    cx.simulate_new_path_selection({
        let path = path.to_path_buf();
        move |_directory| Some(path)
    });
    cx.run_until_parked();
}

/// Shift-click `row_ix`'s pick box, which takes everything between it and the
/// last row picked.
fn pick_through(cx: &mut TestAppContext, handle: WindowHandle<Session>, row_ix: usize) {
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        let position = window.find(("pick", row_ix)).bounds().center();
        let modifiers = Modifiers {
            shift: true,
            ..Default::default()
        };

        window.dispatch_event(
            MouseDownEvent {
                button: MouseButton::Left,
                position,
                modifiers,
                click_count: 1,
                first_mouse: false,
            }
            .to_platform_input(),
            cx,
        );
        window.dispatch_event(
            MouseUpEvent {
                button: MouseButton::Left,
                position,
                modifiers,
                click_count: 1,
            }
            .to_platform_input(),
            cx,
        );
    })
    .unwrap();
}

/// Drag from one row's pick box to another's, the way a run of rows is swept.
fn sweep_rows(cx: &mut TestAppContext, handle: WindowHandle<Session>, from: usize, to: usize) {
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        let from = window.find(("pick", from)).bounds().center();
        let to = window.find(("pick", to)).bounds().center();
        window.drag(from, to, cx);
    })
    .unwrap();
}

/// Click a row away from its pick box — on its first cell — with `modifiers`.
fn click_row(
    cx: &mut TestAppContext,
    handle: WindowHandle<Session>,
    row_ix: usize,
    modifiers: Modifiers,
) {
    cx.update_window(handle.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        let position = window.find(("row", row_ix)).bounds().center();

        window.dispatch_event(
            MouseDownEvent {
                button: MouseButton::Left,
                position,
                modifiers,
                click_count: 1,
                first_mouse: false,
            }
            .to_platform_input(),
            cx,
        );
        window.dispatch_event(
            MouseUpEvent {
                button: MouseButton::Left,
                position,
                modifiers,
                click_count: 1,
            }
            .to_platform_input(),
            cx,
        );
    })
    .unwrap();
}

// The real right-click path — pointer over a cell, menu opens, item chosen —
// was checked by hand against a running grid and by a throwaway test: the
// assertions passed, but `PopupMenu` keeps itself alive through the
// subscription its own context menu registers, so every such test ends in the
// harness's leaked-entity panic. The menu's own logic is covered through
// `request_delete_for_test` and `discard_draft_for_test`, which call exactly
// what the items call. A tab's menu takes the same two steps: the throwaway
// test confirmed that a right click on a tab's title opens it and that its
// items run, and `Session::close_scope_for_test` calls what they call.

/// Put one saved SQLite connection in the manager's list.
fn saved_connection(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> (TempDatabase, Uuid) {
    let database = runtime::block_on(TempDatabase::new());
    let config = database.config();
    let id = config.id;

    let welcome = handle
        .update(cx, |workspace, _, _| workspace.active_welcome_for_test())
        .unwrap()
        .expect("the active tab should be showing the connection manager");
    welcome.update(cx, |welcome, cx| {
        welcome.set_connections_for_test(vec![config], cx)
    });

    (database, id)
}

/// Add a filter to the open table view, the way filling in a line of the bar
/// does, and wait for the page it re-reads.
fn add_filter(
    cx: &mut TestAppContext,
    view: &gpui_kit::Entity<crate::ui::table_view::TableView>,
    column: &str,
    operator: Operator,
    value: &str,
) {
    let filters = view.read_with(cx, |view, _| view.filters_for_test());
    let (column, value) = (column.to_string(), value.to_string());
    filters
        .downgrade()
        .update_in(cx, |filters, window, cx| {
            filters.add_filter_for_test(&column, operator, &value, window, cx);
        })
        .unwrap();
    cx.run_until_parked();
}

/// What the grid asked to be shown in the value dialog.
fn pending_value(cx: &mut TestAppContext) -> crate::ui::value_dialog::ValueRequest {
    cx.update(|cx| crate::ui::value_dialog::pending(cx))
        .expect("no value is waiting to be shown")
}

/// Open a table tab inside a workspace, which is what builds the dialog.
fn workspace_table(
    cx: &mut TestAppContext,
) -> (
    TempDatabase,
    WorkspaceWindow,
    gpui_kit::Entity<crate::ui::table_view::TableView>,
) {
    let handle = workspace(cx);
    let database = connect(cx, &handle);

    let session = handle
        .update(cx, |workspace, _, _| workspace.active_session_for_test())
        .unwrap()
        .expect("the active tab should be a session");
    cx.run_until_parked();

    cx.update_window(handle.window.into(), |_, window, cx| {
        window.render_frame(cx);
        window.click("object-items", cx);
    })
    .unwrap();
    cx.run_until_parked();

    let view = session
        .read_with(cx, |session, cx| session.active_table_view(cx))
        .expect("clicking a table should open a table view");

    (database, handle, view)
}

/// Draw the workspace, which is what picks the value up and builds the dialog.
fn draw_workspace(cx: &mut TestAppContext, handle: &WorkspaceWindow) {
    cx.update_window(handle.window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
    })
    .unwrap();
    cx.run_until_parked();
}

/// The quick switcher over `session`, built the way opening it does but without
/// the dialog around it, so a test can choose an item and see what it did.
fn switcher_view(
    cx: &mut TestAppContext,
    handle: &WorkspaceWindow,
    session: &Entity<Session>,
) -> Entity<crate::ui::quick_switcher::QuickSwitcherView> {
    let session = session.clone();
    cx.update_window(handle.window.into(), |_, window, cx| {
        cx.new(|cx| crate::ui::quick_switcher::QuickSwitcherView::new(session, window, cx))
    })
    .unwrap()
}

/// Put `sql` in the active editor and the caret at `cursor`.
fn prepare_editor(
    cx: &mut TestAppContext,
    handle: WindowHandle<Session>,
    sql: &str,
    cursor: usize,
) {
    handle
        .update(cx, |session, window, cx| {
            session.prepare_active_editor_for_test(sql, window, cx);
            if let Some(editor) = session.active_editor_for_test(cx) {
                editor.update(cx, |editor, cx| editor.set_cursor_for_test(cursor, cx));
            }
        })
        .unwrap();
}

/// Open the editor on a new connection, and wait for it to draw.
fn new_connection_editor(cx: &mut TestAppContext, handle: &WorkspaceWindow) -> Entity<Welcome> {
    let welcome = handle
        .update(cx, |workspace, _, _| workspace.active_welcome_for_test())
        .unwrap()
        .expect("the active tab should be showing the connection manager");
    cx.update_window(handle.window.into(), |_, window, cx| {
        welcome.update(cx, |welcome, cx| {
            welcome.new_connection_for_test(window, cx)
        });
    })
    .unwrap();
    draw_workspace(cx, handle);
    welcome
}

/// Pick `engine` in the open editor and fill its database field in.
fn fill_editor(
    cx: &mut TestAppContext,
    handle: &WorkspaceWindow,
    welcome: &Entity<Welcome>,
    engine: Engine,
    database: &str,
) {
    cx.update_window(handle.window.into(), |_, window, cx| {
        welcome.update(cx, |welcome, cx| {
            welcome.with_editor_for_test(cx, |editor, cx| {
                editor.fill_for_test(engine, database, window, cx)
            })
        });
    })
    .unwrap();
}

fn editor_status(cx: &mut TestAppContext, welcome: &Entity<Welcome>) -> String {
    welcome.update(cx, |welcome, cx| {
        welcome.with_editor_for_test(cx, |editor, _| editor.status_for_test())
    })
}