zippa-db 0.1.1

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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
//! `SessionPanel`: one dock panel wrapping a query editor+grid, a table view,
//! a structure view, or the console — the same [`TabContent`] the session
//! used to hold in a plain `Vec`, now a dock-managed panel with its own
//! title, toolbar and closing behavior.

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

use gpui_kit::assets::IconName;
use gpui_kit::base::TestSupportExt;
use gpui_kit::component::button::{Button, ButtonVariants};
use gpui_kit::component::dock::{BasePanel, Panel, PanelControl, PanelEvent, PanelId, TabGroup};
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
use gpui_kit::component::{
    ActiveTheme, Disableable, Icon, ResizableState, Sizable, h_flex, resizable_panel, v_flex,
    v_resizable,
};
use gpui_kit::prelude::*;
use gpui_kit::{
    App, Context, Entity, EventEmitter, FocusHandle, Focusable, MouseButton, MouseDownEvent,
    SharedString, WeakEntity, Window, div, px,
};

use crate::db::Connection;
use crate::db::DatabaseObject;
use crate::db::Engine;
use crate::db::Plan;
use crate::db::query::QueryResult;
use crate::db::runtime;
use crate::db::{PinnedConnection, ScriptMode, ScriptRun, TxnState};
use crate::ui::busy::busy_label;
use crate::ui::completion::SharedCatalog;
use crate::ui::console::ConsoleView;
use crate::ui::data_grid::{Copied, DataGrid};
use crate::ui::plan_view::PlanView;
use crate::ui::process_list::ProcessListView;
use crate::ui::query_digest::QueryDigestView;
use crate::ui::query_editor::{QueryEditor, QueryEditorEvent};
use crate::ui::schema_view::SchemaView;
use crate::ui::server_variables::ServerVariablesView;
use crate::ui::sql_file;
use crate::ui::sqlite_maintenance::SqliteMaintenanceView;
use crate::ui::table_view::TableView;
use crate::workspace_state::PanelState;

use super::tab::{ObjectViewMode, Status, TabContent};
use super::{CloseTab, NewTab};

/// Starting height of the result pane below the editor, as a share of the
/// window's height; the SQL is the point of a query tab, so the editor takes
/// the rest and the user drags from here. Per-panel: a split puts two query
/// panels on screen at once, and a single shared height would fight between
/// them.
const RESULTS_SHARE: f32 = 0.25;

/// Which tabs a close command takes along with the tab it was opened from.
///
/// The two "beside it" commands work along the strip the tab is shown in — a
/// session split into two groups has two strips, and a menu opened in one is
/// about that one. The two category commands clear the session instead: a
/// table tab is usually opened on the way somewhere rather than kept, so
/// "close the tables, keep my queries" is a command about the connection
/// rather than about one strip.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CloseScope {
    /// Every other tab in the same strip.
    Others,
    /// Every tab after this one in the same strip.
    ToTheRight,
    /// Every query tab in the session.
    QueryTabs,
    /// Every table tab in the session, its rows and its structure alike.
    TableTabs,
}

pub(crate) enum SessionPanelEvent {
    /// The user is working in this panel now.
    Focused,
    /// The panel left the dock, however it left.
    Removed,
    /// The tab's ✕, or a middle click on it.
    CloseRequested,
    /// A tab command that closes more than the tab it was opened from.
    CloseScopeRequested(CloseScope),
    /// The strip's + — a query tab beside this one.
    NewTabRequested,
    Run(String),
    RunScript(String),
    RunScriptIgnoringErrors(String),
    /// The status bar's Commit (`true`) or Roll Back (`false`), for the
    /// tab's open transaction.
    EndTransaction(bool),
    /// The user asked for a statement's plan.
    Explain {
        sql: String,
        analyze: bool,
    },
    OpenFile,
    Save,
}

pub(crate) struct SessionPanel {
    /// Stable identity for element ids and for tests: assigned in creation
    /// order and never reused, so a close button keeps its id when the user
    /// drags the tabs about.
    key: usize,
    title: SharedString,
    content: TabContent,
    focus: FocusHandle,
    /// The tab group displaying this panel, for bringing it forward. `None`
    /// until the dock has taken it.
    group: Option<WeakEntity<TabGroup>>,
    /// Editor above grid. One state per panel, not one per session: a split
    /// puts two query panels on screen at once, and a single
    /// `ResizableState` cannot drive two elements.
    panes: Entity<ResizableState>,
}

impl EventEmitter<SessionPanelEvent> for SessionPanel {}
impl EventEmitter<PanelEvent> for SessionPanel {}

impl SessionPanel {
    /// A query tab, already holding `sql`.
    pub(crate) fn query(
        key: usize,
        title: impl Into<SharedString>,
        sql: String,
        engine: Engine,
        catalog: SharedCatalog,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let editor = cx.new(|cx| QueryEditor::with_text(sql.clone(), engine, catalog, window, cx));
        cx.subscribe_in(&editor, window, Self::on_editor_event)
            .detach();

        let grid = cx.new(|cx| DataGrid::new(engine, window, cx));
        cx.subscribe_in(&grid, window, Self::on_grid_copied)
            .detach();

        Self {
            key,
            title: title.into(),
            content: TabContent::Query {
                editor,
                grid,
                status: Status::Idle,
                path: None,
                results: Vec::new(),
                result: 0,
                running: None,
                script: None,
                pinned: None,
                baseline: sql,
                plan: None,
                show_plan: false,
            },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// A table tab over an already-built [`TableView`].
    pub(crate) fn table(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<TableView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Table { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// A structure tab over an already-built [`SchemaView`].
    pub(crate) fn schema(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<SchemaView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Schema { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// The console tab over an already-built [`ConsoleView`]: one per
    /// session, the same as any other singleton tab, brought forward rather
    /// than duplicated.
    pub(crate) fn console(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<ConsoleView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Console { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// The process list tab over an already-built [`ProcessListView`]: one
    /// per session, the same as the console.
    pub(crate) fn processes(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<ProcessListView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Processes { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// The server variables tab over an already-built [`ServerVariablesView`]:
    /// one per session, the same as the console and the process list.
    pub(crate) fn variables(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<ServerVariablesView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Variables { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// The query digest tab over an already-built [`QueryDigestView`]: one
    /// per session, the same as the console, the process list, and the
    /// server variables.
    pub(crate) fn digest(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<QueryDigestView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Digest { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    /// The SQLite maintenance tab over an already-built
    /// [`SqliteMaintenanceView`]: one per session, like the other tools.
    pub(crate) fn maintenance(
        key: usize,
        title: impl Into<SharedString>,
        view: Entity<SqliteMaintenanceView>,
        cx: &mut Context<Self>,
    ) -> Self {
        Self {
            key,
            title: title.into(),
            content: TabContent::Maintenance { view },
            focus: cx.focus_handle(),
            group: None,
            panes: cx.new(|_| ResizableState::default()),
        }
    }

    fn on_editor_event(
        &mut self,
        _: &Entity<QueryEditor>,
        event: &QueryEditorEvent,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        match event {
            QueryEditorEvent::Run(sql) => cx.emit(SessionPanelEvent::Run(sql.clone())),
            QueryEditorEvent::RunScript(sql) => cx.emit(SessionPanelEvent::RunScript(sql.clone())),
            QueryEditorEvent::RunScriptIgnoringErrors(sql) => {
                cx.emit(SessionPanelEvent::RunScriptIgnoringErrors(sql.clone()))
            }
            QueryEditorEvent::Explain { sql, analyze } => cx.emit(SessionPanelEvent::Explain {
                sql: sql.clone(),
                analyze: *analyze,
            }),
            QueryEditorEvent::Open => cx.emit(SessionPanelEvent::OpenFile),
            QueryEditorEvent::Save => cx.emit(SessionPanelEvent::Save),
        }
    }

    /// A copy went to the clipboard; the status bar says what it was. This is
    /// the query tab's counterpart to the table view's footer notice.
    fn on_grid_copied(
        &mut self,
        _: &Entity<DataGrid>,
        event: &Copied,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.set_status(Status::Done(event.message.clone()));
        cx.notify();
    }

    #[cfg(test)]
    pub(crate) fn key(&self) -> usize {
        self.key
    }

    pub(crate) fn title(&self) -> SharedString {
        self.title.clone()
    }

    pub(crate) fn is_query(&self) -> bool {
        matches!(self.content, TabContent::Query { .. })
    }

    pub(crate) fn is_console(&self) -> bool {
        matches!(self.content, TabContent::Console { .. })
    }

    pub(crate) fn is_process_list(&self) -> bool {
        matches!(self.content, TabContent::Processes { .. })
    }

    pub(crate) fn is_server_variables(&self) -> bool {
        matches!(self.content, TabContent::Variables { .. })
    }

    pub(crate) fn is_query_digest(&self) -> bool {
        matches!(self.content, TabContent::Digest { .. })
    }

    pub(crate) fn is_maintenance(&self) -> bool {
        matches!(self.content, TabContent::Maintenance { .. })
    }

    /// The icon that tells this tab's kind apart at a glance.
    ///
    /// A table's data tab and its structure tab carry the same name, so the
    /// icon is what tells them apart; the query icon is the one the quick
    /// switcher already uses for an open query tab.
    pub(crate) fn icon(&self) -> IconName {
        match &self.content {
            TabContent::Query { .. } => IconName::SquareTerminal,
            TabContent::Table { .. } => IconName::Table,
            TabContent::Schema { .. } => IconName::ListTree,
            TabContent::Console { .. } => IconName::ScrollText,
            TabContent::Processes { .. } => IconName::Activity,
            TabContent::Variables { .. } => IconName::SlidersHorizontal,
            TabContent::Digest { .. } => IconName::Gauge,
            TabContent::Maintenance { .. } => IconName::Wrench,
        }
    }

    /// What this tab shows, in words.
    ///
    /// The icon is what tells a data tab from a structure one, but an icon
    /// names nothing to a screen reader, so the close button says the kind
    /// rather than leaving two identically named tabs to be guessed at.
    pub(crate) fn kind(&self) -> &'static str {
        match &self.content {
            TabContent::Query { .. } => "query",
            TabContent::Table { .. } => "table",
            TabContent::Schema { .. } => "table structure",
            TabContent::Console { .. } => "console",
            TabContent::Processes { .. } => "process list",
            TabContent::Variables { .. } => "server variables",
            TabContent::Digest { .. } => "query digest",
            TabContent::Maintenance { .. } => "database maintenance",
        }
    }

    /// The tab group displaying this panel, if the dock has taken it yet.
    pub(crate) fn group(&self) -> Option<WeakEntity<TabGroup>> {
        self.group.clone()
    }

    /// The commands a tab offers about itself and its neighbours.
    ///
    /// Shared by the tab's own right-click menu and the dock's `…` menu: both
    /// belong to one tab — the context menu hangs off its title element, and
    /// the `…` menu belongs to the group's displayed panel — so both offer the
    /// same commands about the same tab.
    ///
    /// Nothing here is disabled against how many tabs there are: the panel is
    /// drawn *by* its tab group, so reading the group to count them — the only
    /// place that knows — is a read of the group while it is being updated,
    /// which is a panic. A command with nothing to close does nothing instead,
    /// and the session's half of it decides that against the dock at the
    /// moment it runs.
    fn tab_menu(menu: PopupMenu, panel: WeakEntity<Self>) -> PopupMenu {
        let item = |label: &'static str, event: fn() -> SessionPanelEvent| {
            let panel = panel.clone();
            PopupMenuItem::new(label).on_click(move |_, _, cx| {
                if let Some(panel) = panel.upgrade() {
                    panel.update(cx, |_, cx| cx.emit(event()));
                }
            })
        };

        menu.item(item("Close", || SessionPanelEvent::CloseRequested))
            .separator()
            .item(item("Close Others", || {
                SessionPanelEvent::CloseScopeRequested(CloseScope::Others)
            }))
            .item(item("Close to the Right", || {
                SessionPanelEvent::CloseScopeRequested(CloseScope::ToTheRight)
            }))
            .separator()
            .item(item("Close All Table Tabs", || {
                SessionPanelEvent::CloseScopeRequested(CloseScope::TableTabs)
            }))
            .item(item("Close All Query Tabs", || {
                SessionPanelEvent::CloseScopeRequested(CloseScope::QueryTabs)
            }))
    }

    /// The table this tab shows, if it is a table or structure tab.
    pub(crate) fn object(&self, cx: &App) -> Option<DatabaseObject> {
        match &self.content {
            TabContent::Table { view } => Some(view.read(cx).object().clone()),
            TabContent::Schema { view } => Some(view.read(cx).object().clone()),
            TabContent::Query { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    /// Which view mode this tab is showing its object in, if it is showing one.
    pub(crate) fn mode(&self) -> Option<ObjectViewMode> {
        match &self.content {
            TabContent::Table { .. } => Some(ObjectViewMode::Data),
            TabContent::Schema { .. } => Some(ObjectViewMode::Schema),
            TabContent::Query { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    /// This tab as it would be restored: a query keeps its title, its buffer,
    /// and its file; a table or structure tab keeps the object it shows.
    pub(crate) fn snapshot(&self, cx: &App) -> PanelState {
        match &self.content {
            TabContent::Query { editor, path, .. } => PanelState::Query {
                title: self.title.to_string(),
                sql: editor.read(cx).sql(cx),
                file: path.clone(),
            },
            TabContent::Table { view } => PanelState::Table {
                object: view.read(cx).object().clone(),
                filters: view.read(cx).filters(cx),
            },
            TabContent::Schema { view } => PanelState::Schema {
                object: view.read(cx).object().clone(),
            },
            TabContent::Console { .. } => PanelState::Console,
            TabContent::Processes { .. } => PanelState::Processes,
            TabContent::Variables { .. } => PanelState::Variables,
            TabContent::Digest { .. } => PanelState::Digest,
            TabContent::Maintenance { .. } => PanelState::Maintenance,
        }
    }

    /// Whether a query tab's buffer has changed since it was opened or last
    /// saved. A table tab counts the edits staged in its grid; a structure tab
    /// its unapplied column edits.
    pub(crate) fn is_dirty(&self, cx: &App) -> bool {
        match &self.content {
            TabContent::Query {
                editor, baseline, ..
            } => &editor.read(cx).sql(cx) != baseline,
            TabContent::Table { view } => view.read(cx).has_staged_edits(cx),
            TabContent::Schema { view } => view.read(cx).is_dirty(cx),
            TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => false,
        }
    }

    /// Whether this tab holds changes that only exist on screen — staged
    /// rows in a table, a structure edit not yet applied — which re-reading
    /// it from a new connection throws away. A query buffer is not one: it
    /// survives a database switch.
    pub(crate) fn has_unapplied_changes(&self, cx: &App) -> bool {
        match &self.content {
            TabContent::Table { view } => view.read(cx).has_staged_edits(cx),
            TabContent::Schema { view } => view.read(cx).is_dirty(cx),
            _ => false,
        }
    }

    pub(crate) fn table_view(&self) -> Option<Entity<TableView>> {
        match &self.content {
            TabContent::Table { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn schema_view(&self) -> Option<Entity<SchemaView>> {
        match &self.content {
            TabContent::Schema { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Table { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn console_view(&self) -> Option<Entity<ConsoleView>> {
        match &self.content {
            TabContent::Console { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn process_list_view(&self) -> Option<Entity<ProcessListView>> {
        match &self.content {
            TabContent::Processes { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn server_variables_view(&self) -> Option<Entity<ServerVariablesView>> {
        match &self.content {
            TabContent::Variables { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn query_digest_view(&self) -> Option<Entity<QueryDigestView>> {
        match &self.content {
            TabContent::Digest { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn maintenance_view(&self) -> Option<Entity<SqliteMaintenanceView>> {
        match &self.content {
            TabContent::Maintenance { view } => Some(view.clone()),
            TabContent::Query { .. }
            | TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. } => None,
        }
    }

    pub(crate) fn editor(&self) -> Option<Entity<QueryEditor>> {
        match &self.content {
            TabContent::Query { editor, .. } => Some(editor.clone()),
            TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn grid(&self) -> Option<Entity<DataGrid>> {
        match &self.content {
            TabContent::Query { grid, .. } => Some(grid.clone()),
            TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => None,
        }
    }

    /// The editor and grid entities a run acts on.
    pub(crate) fn query_parts(&self) -> Option<(Entity<QueryEditor>, Entity<DataGrid>)> {
        match &self.content {
            TabContent::Query { editor, grid, .. } => Some((editor.clone(), grid.clone())),
            _ => None,
        }
    }

    /// The plan viewer this tab has, once it has read a plan.
    pub(crate) fn plan_view(&self) -> Option<Entity<PlanView>> {
        match &self.content {
            TabContent::Query { plan, .. } => plan.clone(),
            _ => None,
        }
    }

    /// Whether the pane is showing the plan rather than the result grid.
    pub(crate) fn showing_plan(&self) -> bool {
        matches!(
            &self.content,
            TabContent::Query {
                show_plan: true,
                ..
            }
        )
    }

    /// Show the plan pane or the result grid.
    pub(crate) fn set_show_plan(&mut self, show: bool, cx: &mut Context<Self>) {
        if let TabContent::Query { show_plan, .. } = &mut self.content {
            *show_plan = show;
            cx.notify();
        }
    }

    /// Put `plan` in this tab's viewer and show it, building the viewer the
    /// first time one is needed.
    pub(crate) fn set_plan(&mut self, plan: Plan, cx: &mut Context<Self>) {
        let summary = plan_summary(&plan);
        let TabContent::Query {
            plan: slot,
            show_plan,
            status,
            ..
        } = &mut self.content
        else {
            return;
        };

        let view = match slot {
            Some(view) => view.clone(),
            None => {
                let view = cx.new(PlanView::new);
                *slot = Some(view.clone());
                view
            }
        };
        view.update(cx, |view, cx| view.set_plan(plan, cx));
        *show_plan = true;
        *status = Status::Done(summary);
        cx.notify();
    }

    /// The plan viewer while it is the pane being shown, so whoever hands the
    /// tab its keyboard can put it on the plan instead of the editor.
    pub(crate) fn active_plan(&self) -> Option<Entity<PlanView>> {
        if !self.showing_plan() {
            return None;
        }
        self.plan_view()
    }

    /// The file a query tab is bound to, if any.
    pub(crate) fn file_path(&self) -> Option<PathBuf> {
        match &self.content {
            TabContent::Query { path, .. } => path.clone(),
            _ => None,
        }
    }

    pub(crate) fn file_name(&self) -> Option<String> {
        self.file_path()
            .as_ref()
            .and_then(|p| p.file_name())
            .and_then(|n| n.to_str())
            .map(|s| s.to_string())
    }

    #[cfg(test)]
    pub(crate) fn status_message(&self) -> String {
        match &self.content {
            TabContent::Query { status, .. } => status.message(),
            TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => String::new(),
        }
    }

    #[cfg(test)]
    pub(crate) fn is_running(&self) -> bool {
        matches!(
            &self.content,
            TabContent::Query {
                status: Status::Running,
                ..
            }
        )
    }

    /// How many results the last run left, and which one is showing.
    #[cfg(test)]
    pub(crate) fn results(&self) -> (usize, usize) {
        match &self.content {
            TabContent::Query {
                results, result, ..
            } => (results.len(), *result),
            TabContent::Table { .. }
            | TabContent::Schema { .. }
            | TabContent::Console { .. }
            | TabContent::Processes { .. }
            | TabContent::Variables { .. }
            | TabContent::Digest { .. }
            | TabContent::Maintenance { .. } => (0, 0),
        }
    }

    /// Say a run was cancelled, unless whatever cancelled it has already
    /// said more: the sender is dropped when the run is given up on, so this
    /// arrives after `cancel_running` has said what was rolled back.
    pub(crate) fn note_cancelled(&mut self) {
        if let TabContent::Query { status, .. } = &mut self.content
            && matches!(status, Status::Running)
        {
            *status = Status::Done("Cancelled".into());
        }
    }

    pub(crate) fn set_status(&mut self, status: Status) {
        if let TabContent::Query { status: slot, .. } = &mut self.content {
            *slot = status;
        }
    }

    pub(crate) fn set_running(&mut self, handle: Option<tokio::task::AbortHandle>) {
        if let TabContent::Query { running, .. } = &mut self.content {
            *running = handle;
        }
    }

    /// Whether a run is in flight, holding the abort handle a second send
    /// would otherwise overwrite — or a script is paused on a failure,
    /// holding its connection until it is answered.
    pub(crate) fn has_running_task(&self) -> bool {
        matches!(
            &self.content,
            TabContent::Query {
                running: Some(_),
                ..
            } | TabContent::Query {
                script: Some(_),
                ..
            }
        )
    }

    /// The connection this query tab runs on, checked out of `connection`'s
    /// pool on first use. `None` for a tab that is not a query tab.
    ///
    /// A pin left over from another connection — the session switched
    /// database — is let go and replaced.
    pub(crate) fn pin(&mut self, connection: &Arc<Connection>) -> Option<PinnedConnection> {
        let TabContent::Query { pinned, .. } = &mut self.content else {
            return None;
        };
        if pinned
            .as_ref()
            .is_none_or(|pin| !Arc::ptr_eq(pin.connection(), connection))
        {
            *pinned = Some(PinnedConnection::new(connection.clone()));
        }
        pinned.clone()
    }

    /// Whether this tab has a transaction open on its connection.
    pub(crate) fn transaction(&self) -> TxnState {
        match &self.content {
            TabContent::Query {
                pinned: Some(pin), ..
            } => pin.state(),
            _ => TxnState::Idle,
        }
    }

    /// Hold a script paused on a failure until the user answers.
    pub(crate) fn park_script(&mut self, run: Box<ScriptRun>) {
        if let TabContent::Query { script, .. } = &mut self.content {
            *script = Some(run);
        }
    }

    /// The paused script, taken to be answered — or `None` when it has
    /// already been answered, cancelled, or closed with its tab.
    pub(crate) fn take_script(&mut self) -> Option<Box<ScriptRun>> {
        match &mut self.content {
            TabContent::Query { script, .. } => script.take(),
            _ => None,
        }
    }

    /// Put a finished run's results in this tab.
    pub(crate) fn show_results(&mut self, results: Vec<QueryResult>, cx: &mut Context<Self>) {
        let TabContent::Query {
            grid,
            results: slot,
            result,
            show_plan,
            ..
        } = &mut self.content
        else {
            return;
        };

        let grid = grid.clone();
        *slot = results;
        *result = 0;
        // A new run is what the user asked to see, so the grid comes back even
        // if a plan was showing.
        *show_plan = false;

        let summary = self.result_summary();
        self.set_status(Status::Done(summary));

        // A statement that returned no rows at all — an `update`, say —
        // leaves the grid empty rather than showing the rows of the run
        // before it.
        let first = match &self.content {
            TabContent::Query { results, .. } => results.first().cloned(),
            _ => None,
        };
        match first {
            Some(result) => grid.update(cx, |grid, cx| grid.set_result(result, cx)),
            None => grid.update(cx, |grid, cx| grid.clear(cx)),
        }
        cx.notify();
    }

    /// Show another of the results the last run produced.
    pub(crate) fn show_result(&mut self, which: usize, cx: &mut Context<Self>) {
        let TabContent::Query {
            grid,
            results,
            result,
            ..
        } = &mut self.content
        else {
            return;
        };

        let Some(chosen) = results.get(which).cloned() else {
            return;
        };
        let grid = grid.clone();
        *result = which;

        grid.update(cx, |grid, cx| grid.set_result(chosen, cx));
        let summary = self.result_summary();
        self.set_status(Status::Done(summary));
        cx.notify();
    }

    /// What the status bar says about the run that just finished.
    fn result_summary(&self) -> String {
        let TabContent::Query {
            results, result, ..
        } = &self.content
        else {
            return String::new();
        };

        let Some(shown) = results.get(*result) else {
            return "Nothing to show".to_string();
        };

        if results.len() == 1 {
            return shown.summary();
        }

        let total: u128 = results
            .iter()
            .map(|result| result.elapsed.as_millis())
            .sum();
        format!(
            "{} statements in {total} ms · result {} of {}: {}",
            results.len(),
            result + 1,
            results.len(),
            shown.summary()
        )
    }

    /// Bind this query tab to `path`, naming the tab after the file.
    pub(crate) fn set_file(&mut self, path: PathBuf, cx: &mut Context<Self>) {
        let TabContent::Query { path: slot, .. } = &mut self.content else {
            return;
        };
        self.title = sql_file::label(&path).into();
        *slot = Some(path);
        cx.notify();
    }

    /// Mark `sql` as this query tab's clean state, as a save does.
    pub(crate) fn set_baseline(&mut self, sql: String) {
        if let TabContent::Query { baseline, .. } = &mut self.content {
            *baseline = sql;
        }
    }

    /// Stop the run in flight, if there is one. Answers whether there
    /// was something to cancel.
    pub(crate) fn cancel_running(&mut self, cx: &mut Context<Self>) -> bool {
        let open = self.transaction().is_open();
        let TabContent::Query {
            editor,
            running,
            status,
            pinned,
            ..
        } = &mut self.content
        else {
            return false;
        };

        if !matches!(status, Status::Running) {
            return false;
        }

        let editor = editor.clone();
        *status = Status::Done("Cancelled".into());
        if let Some(running) = running.take() {
            // A run on the tab's own connection (not a plan, which is read
            // from the pool) leaves it in a state nothing can vouch for, so
            // the tab lets it go: the server is asked to stop the statement,
            // and the connection closes once the run is dropped, rolling back
            // whatever was open. The next run checks out a fresh one.
            if pinned.as_ref().is_some_and(PinnedConnection::is_busy)
                && let Some(pin) = pinned.take()
            {
                pin.cancel();
                if open {
                    *status = Status::Done(
                        "Cancelled; the tab's open transaction was rolled back".into(),
                    );
                }
            }
            running.abort();
        }

        if let Some(run) = self.take_script() {
            let message = match run.mode() {
                ScriptMode::Transaction => "Cancelled; the script's transaction was rolled back",
                ScriptMode::Autocommit => "Cancelled; the statements before the error were applied",
            };
            self.set_status(Status::Done(message.into()));
            close_script(run);
        }
        editor.update(cx, |editor, cx| editor.set_running(false, cx));
        cx.notify();
        true
    }

    /// Stop the run in flight without touching the editor or status —
    /// the panel is on its way out of the dock, or its connection is closing,
    /// either way.
    ///
    /// The server is asked to stop the statement too: dropping the socket
    /// alone does not, and an `UPDATE` left running would still commit after
    /// the user had closed the tab it was started from.
    pub(crate) fn abort_running(&mut self) {
        if let TabContent::Query {
            running, pinned, ..
        } = &mut self.content
            && let Some(running) = running.take()
        {
            if pinned.as_ref().is_some_and(PinnedConnection::is_busy)
                && let Some(pin) = pinned.take()
            {
                pin.cancel();
            }
            running.abort();
        }
        if let Some(run) = self.take_script() {
            close_script(run);
        }
    }

    /// Point this tab at `connection`: a query tab clears its grid, a table
    /// or structure tab re-reads from the new connection.
    pub(crate) fn set_connection(&mut self, connection: Arc<Connection>, cx: &mut Context<Self>) {
        // A run still going belongs to the connection being left: stop it
        // (on the server too) and give the Run button back, or the tab would
        // say Idle while refusing every run until the old one ended — which a
        // statement on a dead socket may never do. A paused script goes the
        // same way.
        self.cancel_running(cx);
        if let Some(run) = self.take_script() {
            close_script(run);
            if let TabContent::Query { editor, .. } = &self.content {
                editor.update(cx, |editor, cx| editor.set_running(false, cx));
            }
        }
        match &mut self.content {
            TabContent::Query {
                grid,
                plan,
                show_plan,
                pinned,
                ..
            } => {
                // The tab's connection was to the database being left; the
                // next run checks one out of the new pool.
                *pinned = None;
                let grid = grid.clone();
                grid.update(cx, |grid, cx| grid.clear(cx));
                // A plan belongs to the connection it was read from.
                *plan = None;
                *show_plan = false;
                self.set_status(Status::Idle);
            }
            TabContent::Table { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
            TabContent::Schema { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
            TabContent::Console { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
            TabContent::Processes { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
            TabContent::Variables { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
            TabContent::Digest { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
            TabContent::Maintenance { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.set_connection(connection, cx));
            }
        }
    }

    /// Reread a table tab's rows, a console tab's log, a process list, the
    /// server variables, or the query digest. A query tab's buffer is the
    /// user's own SQL and is left alone; a structure tab has nothing to
    /// refresh this way.
    pub(crate) fn refresh(&mut self, cx: &mut Context<Self>) {
        match &self.content {
            TabContent::Table { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.refresh(cx));
            }
            TabContent::Console { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.refresh(cx));
            }
            TabContent::Processes { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.refresh(cx));
            }
            TabContent::Variables { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.refresh(cx));
            }
            TabContent::Digest { view } => {
                let view = view.clone();
                view.update(cx, |view, cx| view.refresh(cx));
            }
            // Nothing to re-read: it only shows what its buttons ran.
            TabContent::Query { .. }
            | TabContent::Schema { .. }
            | TabContent::Maintenance { .. } => {}
        }
    }

    /// Write a table tab's staged edits. `Cmd+S` on a query tab saves its
    /// buffer instead, handled by the session directly.
    pub(crate) fn commit(&mut self, cx: &mut Context<Self>) {
        if let TabContent::Table { view } = &self.content {
            let view = view.clone();
            view.update(cx, |view, cx| view.commit(cx));
        }
    }

    /// Bring `panel` forward in whatever group holds it, and put focus in it.
    ///
    /// A free function rather than a method taken through `panel.update(...)`:
    /// `TabGroup::select_tab` synchronously reads the group's panels back
    /// (`focus_active_panel` asks the displayed one whether it is still
    /// visible), and reading a panel entity while it is mid-`update` is a
    /// hard panic. Going through `panel.read(cx)` for everything here means
    /// the entity is never held exclusively while the dock reads it back.
    pub(crate) fn bring_forward(panel: &Entity<SessionPanel>, window: &mut Window, cx: &mut App) {
        let id = PanelId::from(panel.entity_id());
        if let Some(group) = panel.read(cx).group.as_ref().and_then(|g| g.upgrade()) {
            group.update(cx, |group, cx| {
                if let Some(ix) = group.panels().iter().position(|p| p.panel_id(cx) == id) {
                    group.select_tab(ix, window, cx);
                }
            });
        }
        // Covers the already-displayed case, where `select_tab` returns
        // early and never reaches `focus_active_panel`. The plan, when it is
        // what the tab shows, is where its keys are bound.
        match panel.read(cx).active_plan() {
            Some(plan) => plan.update(cx, |plan, cx| plan.focus(window, cx)),
            None => {
                let handle = panel.read(cx).focus_handle(cx);
                handle.focus(window, cx);
            }
        }
    }

    fn render_status_bar(&self, status: &Status, cx: &mut Context<Self>) -> impl IntoElement {
        let color = match status {
            Status::Error(_) => cx.theme().danger,
            _ => cx.theme().muted_foreground,
        };
        let message = status.message();
        let transaction = self.transaction();
        let running = matches!(status, Status::Running);

        h_flex()
            .px_3()
            .py_1()
            .flex_none()
            .gap_2()
            .justify_between()
            .border_t_1()
            .border_color(cx.theme().border)
            .bg(cx.theme().status_bar)
            // Errors can be long; cap the bar so it never eats the grid.
            .child(
                div()
                    .id("status")
                    .w_full()
                    .max_h(px(72.))
                    .overflow_y_scroll()
                    .text_xs()
                    .text_color(color)
                    .child(if matches!(status, Status::Running) {
                        busy_label(message, color).into_any_element()
                    } else {
                        message.into_any_element()
                    }),
            )
            .when(transaction.is_open(), |this| {
                this.child(self.render_transaction(transaction, running, cx))
            })
    }

    /// The open transaction, said in words beside the status — never by
    /// colour alone — with the two ways out of it.
    ///
    /// A failed transaction (Postgres) offers only Roll Back: the server
    /// refuses everything else, and a `COMMIT` there only rolls back anyway.
    fn render_transaction(
        &self,
        transaction: TxnState,
        running: bool,
        cx: &mut Context<Self>,
    ) -> impl IntoElement {
        let failed = transaction == TxnState::Failed;
        let (label, color) = if failed {
            ("Transaction failed: roll back", cx.theme().danger)
        } else {
            ("Transaction open", cx.theme().info)
        };

        h_flex()
            .flex_none()
            .gap_1()
            .child(
                div()
                    .id("transaction-state")
                    .text_xs()
                    .text_color(color)
                    .child(label)
                    .tooltip(|window, cx| {
                        gpui_kit::component::tooltip::Tooltip::new(
                            "Changes since BEGIN are not visible to the sidebar, table \
                             views, or other tabs until they are committed.",
                        )
                        .build(window, cx)
                    }),
            )
            .when(!failed, |this| {
                this.child(
                    Button::new("transaction-commit")
                        .xsmall()
                        .label("Commit")
                        .disabled(running)
                        .on_click(cx.listener(|_this, _, _window, cx| {
                            cx.emit(SessionPanelEvent::EndTransaction(true));
                        })),
                )
            })
            .child(
                Button::new("transaction-rollback")
                    .xsmall()
                    .label("Roll Back")
                    .disabled(running)
                    .on_click(cx.listener(|_this, _, _window, cx| {
                        cx.emit(SessionPanelEvent::EndTransaction(false));
                    })),
            )
    }

    /// The bar above the result area: one button per result the last run
    /// produced, and the Results/Plan switch once a plan has been read.
    fn render_view_bar(
        &self,
        results: usize,
        shown: usize,
        has_plan: bool,
        show_plan: bool,
        cx: &mut Context<Self>,
    ) -> impl IntoElement {
        h_flex()
            .flex_none()
            .px_2()
            .py_1()
            .gap_1()
            .border_b_1()
            .border_color(cx.theme().border)
            .bg(cx.theme().status_bar)
            .children((0..results).map(|index| {
                let button = Button::new(SharedString::from(format!("result-{index}")))
                    .xsmall()
                    .label(format!("Result {}", index + 1))
                    .disabled(show_plan)
                    .on_click(cx.listener(move |this, _, _window, cx| this.show_result(index, cx)));

                if index == shown && !show_plan {
                    button.primary()
                } else {
                    button.ghost()
                }
            }))
            .when(has_plan, |this| {
                this.child(
                    h_flex()
                        .flex_none()
                        .ml_auto()
                        .gap_1()
                        .child(
                            Button::new("show-results")
                                .xsmall()
                                .label("Results")
                                .when(show_plan, |this| this.ghost())
                                .when(!show_plan, |this| this.primary())
                                .on_click(cx.listener(|this, _, _window, cx| {
                                    this.set_show_plan(false, cx)
                                })),
                        )
                        .child(
                            Button::new("show-plan")
                                .xsmall()
                                .label("Plan")
                                .when(show_plan, |this| this.primary())
                                .when(!show_plan, |this| this.ghost())
                                .on_click(cx.listener(|this, _, window, cx| {
                                    this.set_show_plan(true, cx);
                                    if let Some(plan) = this.plan_view() {
                                        plan.update(cx, |plan, cx| plan.focus(window, cx));
                                    }
                                })),
                        ),
                )
            })
    }
}

/// The status bar's line after a plan comes back.
fn plan_summary(plan: &Plan) -> String {
    let milliseconds = plan.elapsed.as_millis();
    let analyzed = if plan.analyzed { " · analyzed" } else { "" };
    format!("Plan for 1 statement in {milliseconds} ms{analyzed}")
}

impl Focusable for SessionPanel {
    /// A query panel answers with its editor, so clicking its tab puts the
    /// caret where the user is about to type; the dock focuses this handle
    /// itself whenever it displays the panel.
    fn focus_handle(&self, cx: &App) -> FocusHandle {
        match &self.content {
            TabContent::Query { editor, .. } => editor.read(cx).focus_handle(cx),
            // A table panel answers with its grid, for the same reason: the
            // rows are what the keyboard is for, and the panel's own element
            // is above the contexts the grid's keys are bound on, so focus
            // left there would answer none of them.
            TabContent::Table { view } => view.read(cx).focus_handle(cx),
            TabContent::Schema { .. } => self.focus.clone(),
            // The rows are what the keyboard is for here too, the same
            // reason a table panel answers with its grid.
            TabContent::Console { view } => view.read(cx).focus_handle(cx),
            TabContent::Processes { view } => view.read(cx).focus_handle(cx),
            TabContent::Variables { view } => view.read(cx).focus_handle(cx),
            TabContent::Digest { view } => view.read(cx).focus_handle(cx),
            TabContent::Maintenance { view } => view.read(cx).focus_handle(cx),
        }
    }
}

impl BasePanel for SessionPanel {
    fn panel_name(&self) -> &'static str {
        "SessionPanel"
    }

    /// Permission for the dock's own Close, which never asks the session
    /// first; the ✕ goes through `DockArea::remove_panel`, which ignores
    /// this.
    fn closable(&self, cx: &App) -> bool {
        !self.is_dirty(cx)
    }

    fn set_active(&mut self, active: bool, _window: &mut Window, cx: &mut Context<Self>) {
        if active {
            cx.emit(SessionPanelEvent::Focused);
        }
    }

    fn on_added_to(
        &mut self,
        group: WeakEntity<TabGroup>,
        _window: &mut Window,
        _cx: &mut Context<Self>,
    ) {
        self.group = Some(group);
    }

    /// A tab that leaves takes its running query with it.
    fn on_removed(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
        self.abort_running();
        cx.emit(SessionPanelEvent::Removed);
    }
}

impl Panel for SessionPanel {
    fn title(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let dirty = self.is_dirty(cx);
        let label = if dirty {
            format!("\u{25cf} {}", self.title)
        } else {
            self.title.to_string()
        };
        let key = self.key;
        let title = self.title.clone();
        let kind = self.kind();
        let icon = self.icon();
        let transaction = self.transaction().is_open();

        h_flex()
            .id(("session-panel-title", key))
            .test_support()
            .gap_1()
            // Middle-click closes, the way it does in a browser. Capture
            // phase for the same reason the grid records its right-clicked
            // row that way: the ✕ button below would otherwise swallow the
            // press first.
            .capture_any_mouse_down(cx.listener(|_this, event: &MouseDownEvent, _window, cx| {
                if event.button == MouseButton::Middle {
                    cx.emit(SessionPanelEvent::CloseRequested);
                }
            }))
            // The title is the only part of a dock tab this app draws, so the
            // tab's right-click menu hangs off it. The same commands sit in
            // the `…` menu, which is reachable without a right click.
            .context_menu({
                let me = cx.weak_entity();
                move |menu, _, _| SessionPanel::tab_menu(menu, me.clone())
            })
            .child(
                Icon::new(icon)
                    .flex_none()
                    .text_color(cx.theme().muted_foreground),
            )
            .child(div().child(label))
            // A transaction left open in a tab out of sight is easy to
            // forget, and closing the tab would roll it back.
            .when(transaction, |this| {
                this.child(
                    div()
                        .id(("open-transaction", key))
                        .flex_none()
                        .size(px(6.))
                        .rounded_full()
                        .bg(cx.theme().info)
                        .tooltip(|window, cx| {
                            gpui_kit::component::tooltip::Tooltip::new("Open transaction")
                                .build(window, cx)
                        }),
                )
            })
            .child(
                Button::new(SharedString::from(format!("close-tab-{key}")))
                    .ghost()
                    .xsmall()
                    .icon(IconName::Close)
                    .accessibility_label(match (dirty, transaction) {
                        (true, true) => format!(
                            "Close the {kind} tab {title} (unsaved changes, open transaction)"
                        ),
                        (true, false) => format!("Close the {kind} tab {title} (unsaved changes)"),
                        (false, true) => format!("Close the {kind} tab {title} (open transaction)"),
                        (false, false) => format!("Close the {kind} tab {title}"),
                    })
                    .tooltip_with_action("Close tab", &CloseTab, Some("Session"))
                    .on_click(cx.listener(|_this, _, _window, cx| {
                        cx.emit(SessionPanelEvent::CloseRequested);
                    })),
            )
    }

    /// The `+` beside this panel's tabs, one per group, so a new tab lands
    /// in the group the user is looking at.
    fn toolbar_buttons(
        &mut self,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Option<Vec<Button>> {
        Some(vec![
            Button::new("new-tab")
                .ghost()
                .xsmall()
                .icon(IconName::Plus)
                .accessibility_label("New query tab")
                .tooltip_with_action("New query tab", &NewTab, Some("Session"))
                .on_click(cx.listener(|_this, _, _window, cx| {
                    cx.emit(SessionPanelEvent::NewTabRequested);
                })),
        ])
    }

    /// The `…` menu's own Close vanishes when this tab is dirty (see
    /// `closable`); say why rather than leaving it looking broken.
    fn dropdown_menu(
        &mut self,
        menu: PopupMenu,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) -> PopupMenu {
        let menu = if self.is_dirty(cx) {
            menu.item(PopupMenuItem::new("Close (unsaved changes)").disabled(true))
        } else {
            menu
        };

        // The `…` menu belongs to the group's displayed panel, so the tab
        // commands mean the same thing here as on the tab's own menu.
        Self::tab_menu(menu, cx.weak_entity())
    }

    /// The bodies carry their own footers and fill the pane.
    fn inner_padding(&self, _cx: &App) -> bool {
        false
    }

    fn zoom_control(&self, _cx: &App) -> Option<PanelControl> {
        Some(PanelControl::Toolbar)
    }
}

impl Render for SessionPanel {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        let key = self.key;
        let body = match &self.content {
            TabContent::Query {
                editor,
                grid,
                status,
                results,
                result,
                plan,
                show_plan,
                ..
            } => {
                let has_plan = plan.is_some();
                let showing_plan = *show_plan && has_plan;
                let content: gpui_kit::AnyElement = match (showing_plan, plan) {
                    (true, Some(plan)) => plan.clone().into_any_element(),
                    _ => grid.clone().into_any_element(),
                };

                v_flex()
                    .size_full()
                    .child(
                        div().flex_1().min_h_0().child(
                            v_resizable("session-panes")
                                .with_state(&self.panes)
                                .child(
                                    resizable_panel()
                                        .size_range(px(120.)..px(10_000.))
                                        .child(editor.clone()),
                                )
                                .child(
                                    resizable_panel()
                                        .size(window.viewport_size().height * RESULTS_SHARE)
                                        .size_range(px(80.)..px(10_000.))
                                        .child(
                                            v_flex()
                                                .size_full()
                                                // A script leaves one result per
                                                // statement, and a plan leaves the
                                                // switch; a lone result alone would
                                                // make the bar say nothing.
                                                .when(results.len() > 1 || has_plan, |this| {
                                                    this.child(self.render_view_bar(
                                                        results.len(),
                                                        *result,
                                                        has_plan,
                                                        showing_plan,
                                                        cx,
                                                    ))
                                                })
                                                .child(div().flex_1().min_h_0().child(content)),
                                        ),
                                ),
                        ),
                    )
                    .child(self.render_status_bar(status, cx))
                    .into_any_element()
            }
            // The table/structure view carries its own footer, so it fills
            // the pane.
            TabContent::Table { view } => view.clone().into_any_element(),
            TabContent::Schema { view } => view.clone().into_any_element(),
            TabContent::Console { view } => view.clone().into_any_element(),
            TabContent::Processes { view } => view.clone().into_any_element(),
            TabContent::Variables { view } => view.clone().into_any_element(),
            TabContent::Digest { view } => view.clone().into_any_element(),
            TabContent::Maintenance { view } => view.clone().into_any_element(),
        };

        div()
            .id(("session-panel", key))
            .test_support()
            .track_focus(&self.focus)
            .size_full()
            .child(body)
    }
}

/// Give up on a paused script on the database runtime, where its connection
/// has to be closed — closing it is what rolls an open transaction back.
pub(crate) fn close_script(run: Box<ScriptRun>) {
    // Nothing to wait for: the connection goes either way.
    drop(runtime::spawn(run.close()));
}