Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/agents/session.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,35 @@ The shape a change to the main pane has to fit (`session.rs`, with the
lands where no row takes it, and an object dragged while its database is
unknown carries nothing. The Pinned group exists only while something is
pinned, so pinning the first thing is the menu's.
- **The sidebar opens on the active schema and keeps the user's folds.** A
schema row starts open only when it is the schema the connection works in
(`Profile::explorer_opens_on`): `Profile::active_schema`, or, where
`Target::catalog_lists_databases` (MySQL, MariaDB, ClickHouse, whose
schema rows are databases), the row named like `Profile::active_database`.
Gated on that ability rather than matched by name everywhere, so a schema
sharing the database's name on another engine is not taken for it. When
neither names a listed row, the only schema there is opens. So a database
of many schemas is not a wall of open trees, and one of a single schema is
not a lone closed row. Every other schema starts closed, and every row
that is not a schema (Pinned, folders, Queries) open
(`explorer::root_folds`). Opening or closing a top-level row (a schema, a
folder, Pinned, Queries) is recorded from the tree's own `TreeEvent` (`Workspace::remember_fold`), keyboard, click and
`reveal_item` alike, in the profile's `folds`, row id to open, saved as
`[profiles.folds]` and left out when empty. A row it does not name gets the
default, so a schema created since stays closed and a new folder opens.
Every rebuild without a filter puts `folds` over what was kept, which is
how Collapse All and Expand All Schemas (the filter row's buttons and the
palette, no default chords) and Set as Active Schema show at once: Set as Active Schema
records the schema it picks as open and the one it leaves as it was, since
that one was open only for being active, and its rebuild opens the picked
row over what was kept, so it opens under a filter too. Nothing is recorded while the
filter has text: a filter opens every row it keeps so that matches show,
and those are not the user's folds. Clearing it rebuilds from `folds` and
the defaults; Collapse All Schemas clears it first, or nothing would close;
Expand All leaves it.
Category folds are kept across a refresh but not saved. Stale ids are left
in `folds`: harmless, and a dropped schema may come back. A duplicate takes
the folds with the folders.
- **A named buffer persists to its query file, an unnamed one to its own
`.scratch-{id}.sql`.** Edits stay in memory until Save, a connection switch,
opening another query, or normal quit/window close persists the buffers.
Expand Down
2 changes: 2 additions & 0 deletions src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ actions!(
ToggleStructure,
ToggleResultsFocus,
FocusSidebar,
CollapseAllSchemas,
ExpandAllSchemas,
OpenSidebarItem,
AcceptCompletion,
OpenSettings,
Expand Down
4 changes: 4 additions & 0 deletions src/connection_form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! This was a plain type at the crate root. It moved out whole; nothing changed
//! but its visibility.

use std::collections::BTreeMap;
use std::time::Instant;

use gpui::{App, AppContext, Context, Entity, SharedString, Subscription, Task, TextAlign, Window};
Expand Down Expand Up @@ -118,6 +119,7 @@ pub(crate) struct ConnectionForm {
pub(crate) last_url: SharedString,
/// What a duplicate takes from the connection it copies, given on save.
pub(crate) shortcuts: Shortcuts,
pub(crate) folds: BTreeMap<String, bool>,
_subscriptions: Vec<Subscription>,
}

Expand Down Expand Up @@ -402,6 +404,7 @@ impl ConnectionForm {
placeholders_for: None,
last_url: SharedString::default(),
shortcuts: Shortcuts::default(),
folds: BTreeMap::new(),
_subscriptions: subscriptions,
};
// The form is the whole window while it is open, and a window with
Expand Down Expand Up @@ -459,6 +462,7 @@ impl ConnectionForm {
form.color = profile.color;
form.mode = starting_mode(Some(profile.mode));
form.shortcuts = profile.shortcuts.duplicated();
form.folds = profile.folds.clone();
form.name.update(cx, |input, cx| {
input.set_value(name, window, cx);
});
Expand Down
6 changes: 6 additions & 0 deletions src/db/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,12 @@ impl Target {
abilities.switches_database && !abilities.catalog_lists_databases
}

/// Whether the catalog lists every database on the server, each as a
/// schema, as MySQL's does.
pub fn catalog_lists_databases(self) -> bool {
self.abilities().catalog_lists_databases
}

/// Whether the row count the catalog carries for a table is exact rather
/// than the statistics' estimate.
pub fn exact_row_estimates(self) -> bool {
Expand Down
100 changes: 98 additions & 2 deletions src/explorer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
collections::{HashMap, HashSet},
collections::{BTreeMap, HashMap, HashSet},
ops::Range,
};

Expand Down Expand Up @@ -52,6 +52,40 @@ pub fn is_schema_row(id: &str) -> bool {

const SCHEMA_ROW: &str = "schema-";

/// The row id of a schema.
pub fn schema_row(name: &str) -> String {
format!("{SCHEMA_ROW}{name}")
}

/// Whether each top-level row of an unfiltered sidebar opens: as `saved`
/// says where it names the row, and otherwise a schema only when it is
/// `within`, the one the connection works in (`Profile::explorer_opens_on`),
/// or, when `within` names none listed, the only schema there is. So a
/// database of many schemas opens on the one being worked in, and one of a
/// single schema is not a lone closed row. Any other row `saved` does not
/// name is left as built.
pub fn root_folds(
items: &[TreeItem],
saved: &BTreeMap<String, bool>,
within: Option<&str>,
) -> HashMap<String, bool> {
let schemas: Vec<&str> = items
.iter()
.filter_map(|item| item.id.strip_prefix(SCHEMA_ROW))
.collect();
let lone = schemas.len() == 1 && !schemas.iter().any(|schema| Some(*schema) == within);
items
.iter()
.filter_map(|item| {
let open = saved.get(item.id.as_ref()).copied().or_else(|| {
let schema = item.id.strip_prefix(SCHEMA_ROW)?;
Some(lone || within == Some(schema))
})?;
Some((item.id.to_string(), open))
})
.collect()
}

/// Whether each folder in `items` is open, by row id, to put back on a
/// rebuild with [`with_folds`].
pub fn folds(items: &[TreeItem]) -> HashMap<String, bool> {
Expand Down Expand Up @@ -271,7 +305,7 @@ pub fn tree(catalog: &Catalog, filter: &str) -> ExplorerTree {
.by_name()
.into_iter()
.filter_map(|(schema_index, schema)| {
let id = format!("{SCHEMA_ROW}{}", schema.name);
let id = schema_row(&schema.name);
let schema_matches = builder.name_matches(&id, &schema.name);
let mut groups = Vec::new();

Expand Down Expand Up @@ -1736,6 +1770,68 @@ mod tests {
assert!(!is_schema_row(&explorer.items[1].children[0].id));
}

#[test]
fn only_the_active_schema_opens_or_the_only_one_there_is() {
// Each root of a sidebar built afresh, as `root_folds` leaves it. Built
// expanded, so a schema it failed to close would show here as open.
let shown = |catalog: &Catalog, saved: &BTreeMap<String, bool>, active| {
let mut explorer = queries(&["daily".to_string()], "");
explorer.extend(tree(catalog, ""));
let folds = root_folds(&explorer.items, saved, active);
with_folds(explorer.items, &folds)
.iter()
.map(|item| (item.id.to_string(), item.is_expanded()))
.collect::<Vec<_>>()
};
let row = |id: &str, open| (id.to_string(), open);
let none = BTreeMap::new();
assert_eq!(
shown(&catalog(), &none, Some("analytics")),
[
row(QUERIES_GROUP, true),
row("schema-analytics", true),
row("schema-public", false)
]
);
for active in [Some("gone"), None] {
assert_eq!(
shown(&catalog(), &none, active),
[
row(QUERIES_GROUP, true),
row("schema-analytics", false),
row("schema-public", false)
],
"two schemas, neither active"
);
}

let saved = BTreeMap::from([
("schema-analytics".to_string(), false),
("schema-public".to_string(), true),
(QUERIES_GROUP.to_string(), false),
("schema-dropped".to_string(), true),
]);
assert_eq!(
shown(&catalog(), &saved, Some("analytics")),
[
row(QUERIES_GROUP, false),
row("schema-analytics", false),
row("schema-public", true)
],
"what the user left open or closed outranks the active schema"
);

let mut single = catalog();
single.schemas.truncate(1);
for within in [None, Some("gone")] {
assert_eq!(
shown(&single, &none, within),
[row(QUERIES_GROUP, true), row("schema-analytics", true)],
"the only schema, whatever names one not listed"
);
}
}

#[test]
fn a_change_to_the_saved_queries_keeps_what_was_folded_and_opened() {
let build = |names: &[String]| {
Expand Down
5 changes: 4 additions & 1 deletion src/icons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ use crate::db::Syntax;
/// The gpui-component widgets ask for their own paths — those are Lucide names
/// too, so they resolve here as well. Add a row when something asks for one;
/// an unlisted path simply draws nothing.
const ICONS: [(&str, &IconData); 80] = [
const ICONS: [(&str, &IconData); 81] = [
("icons/git-fork.svg", icondata_lu::LuGitFork),
("icons/chevron-down.svg", icondata_lu::LuChevronDown),
("icons/chevron-right.svg", icondata_lu::LuChevronRight),
("icons/chevron-left.svg", icondata_lu::LuChevronLeft),
("icons/chevron-up.svg", icondata_lu::LuChevronUp),
("icons/chevrons-up-down.svg", icondata_lu::LuChevronsUpDown),
("icons/chevrons-down-up.svg", icondata_lu::LuChevronsDownUp),
("icons/sort-ascending.svg", icondata_lu::LuArrowUpNarrowWide),
(
"icons/sort-descending.svg",
Expand Down Expand Up @@ -149,6 +150,8 @@ pub mod icon {
pub const FULL_ACCESS: &str = "icons/shield-alert.svg";
/// Folds the explorer column away, and brings it back.
pub const SIDEBAR: &str = "icons/panel-left.svg";
pub const COLLAPSE_ALL: &str = "icons/chevrons-down-up.svg";
pub const EXPAND_ALL: &str = "icons/chevrons-up-down.svg";
/// Folds the row panel beside a grid away, and brings it back.
pub const ROW_PANEL: &str = "icons/panel-right.svg";
/// Switches the row panel between reading a row and editing it.
Expand Down
32 changes: 17 additions & 15 deletions src/keybindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,21 @@ use gpui_component::input::ShowCompletions;
use crate::{
actions::{
AcceptCompletion, AddFilter, ApplyEdits, CancelQuery, ClearFilter, CloseTab,
CommandPalette, ConfirmDialog, CopyCell, CopyDiagnostics, CopyPlan, CopyResults, CopyRow,
CopyRows, CopySelection, CycleMode, DeleteRow, DiscardEdits, Disconnect, EditCell,
ExplainQuery, FocusSidebar, FollowForeignKey, FormatQuery, FuzzyOpen, GoToColumn,
HideColumn, ImportConnections, ImportRows, ImportRowsFromClipboard, Minimize, MoveTabLeft,
MoveTabRight, NewConnection, NewProject, NewQuery, NewRow, NextDialogButton, NextEdit,
NextPage, NextProfile, NextResult, NextTab, OpenLogsFolder, OpenSettings, OpenSidebarItem,
PaletteHistoryFilter, PaletteHistorySort, PaletteNext, PaletteNextScope, PalettePrevious,
PalettePreviousScope, PaletteRowActions, PaletteScopeLeft, PaletteScopeRight,
PreviousDialogButton, PreviousEdit, PreviousPage, PreviousProfile, PreviousResult,
PreviousTab, Quit, RefreshConnection, RefreshRelation, ResetConfirmations, ResetEditorZoom,
RunQuery, SaveQuery, SearchEverything, SelectDatabase, SelectTheme, SetDefault, SetEmpty,
SetMode, SetNull, ShowAllColumns, ShowEditor, ShowMessages, ShowReferences,
SortActiveColumn, SubmitConnection, SwitchConnection, TickDialogBox, ToggleComment,
ToggleNextJoin, TogglePinColumn, ToggleResultsFocus, ToggleRowEdit, ToggleRowPanel,
ToggleSidebar, ToggleStructure, ZoomEditorIn, ZoomEditorOut,
CollapseAllSchemas, CommandPalette, ConfirmDialog, CopyCell, CopyDiagnostics, CopyPlan,
CopyResults, CopyRow, CopyRows, CopySelection, CycleMode, DeleteRow, DiscardEdits,
Disconnect, EditCell, ExpandAllSchemas, ExplainQuery, FocusSidebar, FollowForeignKey,
FormatQuery, FuzzyOpen, GoToColumn, HideColumn, ImportConnections, ImportRows,
ImportRowsFromClipboard, Minimize, MoveTabLeft, MoveTabRight, NewConnection, NewProject,
NewQuery, NewRow, NextDialogButton, NextEdit, NextPage, NextProfile, NextResult, NextTab,
OpenLogsFolder, OpenSettings, OpenSidebarItem, PaletteHistoryFilter, PaletteHistorySort,
PaletteNext, PaletteNextScope, PalettePrevious, PalettePreviousScope, PaletteRowActions,
PaletteScopeLeft, PaletteScopeRight, PreviousDialogButton, PreviousEdit, PreviousPage,
PreviousProfile, PreviousResult, PreviousTab, Quit, RefreshConnection, RefreshRelation,
ResetConfirmations, ResetEditorZoom, RunQuery, SaveQuery, SearchEverything, SelectDatabase,
SelectTheme, SetDefault, SetEmpty, SetMode, SetNull, ShowAllColumns, ShowEditor,
ShowMessages, ShowReferences, SortActiveColumn, SubmitConnection, SwitchConnection,
TickDialogBox, ToggleComment, ToggleNextJoin, TogglePinColumn, ToggleResultsFocus,
ToggleRowEdit, ToggleRowPanel, ToggleSidebar, ToggleStructure, ZoomEditorIn, ZoomEditorOut,
},
db::ExplainMode,
export::RowsAs,
Expand Down Expand Up @@ -228,6 +228,8 @@ registry! {
("toggle_structure", "Toggle Data / Structure", None, ["secondary-shift-d"], ToggleStructure),
("toggle_results_focus", "Toggle Editor / Results Focus", None, ["secondary-k r"], ToggleResultsFocus),
("focus_sidebar", "Focus Sidebar", None, ["secondary-k e"], FocusSidebar),
("collapse_all_schemas", "Collapse All Schemas", None, [], CollapseAllSchemas),
("expand_all_schemas", "Expand All Schemas", None, [], ExpandAllSchemas),
("open_sidebar_item", "Sidebar: Open Selected", Some("Explorer"), ["enter"], OpenSidebarItem),
("quit", "Quit dbdelve", None, ["secondary-q"], Quit),
// AppKit only wires Window > Minimize through the application menu on
Expand Down
30 changes: 15 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,21 @@ use gpui_component::{
};

use actions::{
AddFilter, ApplyEdits, CancelQuery, ClearFilter, CloseTab, CommandPalette, CopyCell,
CopyDiagnostics, CopyPlan, CopyResults, CopyRow, CopyRows, CopySelection, CustomRowLimit,
CycleMode, DeleteRow, DiscardEdits, Disconnect, EditCell, ExplainQuery, FollowForeignKey,
FormatQuery, FuzzyOpen, GoToColumn, HideColumn, ImportConnections, ImportRows,
ImportRowsFromClipboard, LimitTarget, MenuImportRowsFromClipboard, Minimize, MoveTabLeft,
MoveTabRight, NewConnection, NewProject, NewQuery, NewRow, NextEdit, NextPage, NextProfile,
NextResult, NextTab, OpenLogsFolder, OpenReference, OpenSettings, PreviousEdit, PreviousPage,
PreviousProfile, PreviousResult, PreviousTab, Quit, RefreshConnection, RefreshRelation,
RemoveFilter, RequestWriteMode, ResetConfirmations, ResetEditorZoom, RunQuery, SaveQuery,
SearchEverything, SelectDatabase, SelectTheme, SetDefault, SetDefaultRowLimit, SetEmpty,
SetFilterColumn, SetFilterOperator, SetFilterRaw, SetMode, SetNull, SetQueryLimit, SetRowLimit,
ShowAllColumns, ShowEditor, ShowMessages, ShowReferences, SortActiveColumn, SortColumn,
SubmitConnection, SwitchConnection, ToggleComment, ToggleFilterJoin, ToggleNextJoin,
TogglePinColumn, ToggleRowEdit, ToggleRowPanel, ToggleSidebar, ToggleStructure, ZoomEditorIn,
ZoomEditorOut,
AddFilter, ApplyEdits, CancelQuery, ClearFilter, CloseTab, CollapseAllSchemas, CommandPalette,
CopyCell, CopyDiagnostics, CopyPlan, CopyResults, CopyRow, CopyRows, CopySelection,
CustomRowLimit, CycleMode, DeleteRow, DiscardEdits, Disconnect, EditCell, ExpandAllSchemas,
ExplainQuery, FollowForeignKey, FormatQuery, FuzzyOpen, GoToColumn, HideColumn,
ImportConnections, ImportRows, ImportRowsFromClipboard, LimitTarget,
MenuImportRowsFromClipboard, Minimize, MoveTabLeft, MoveTabRight, NewConnection, NewProject,
NewQuery, NewRow, NextEdit, NextPage, NextProfile, NextResult, NextTab, OpenLogsFolder,
OpenReference, OpenSettings, PreviousEdit, PreviousPage, PreviousProfile, PreviousResult,
PreviousTab, Quit, RefreshConnection, RefreshRelation, RemoveFilter, RequestWriteMode,
ResetConfirmations, ResetEditorZoom, RunQuery, SaveQuery, SearchEverything, SelectDatabase,
SelectTheme, SetDefault, SetDefaultRowLimit, SetEmpty, SetFilterColumn, SetFilterOperator,
SetFilterRaw, SetMode, SetNull, SetQueryLimit, SetRowLimit, ShowAllColumns, ShowEditor,
ShowMessages, ShowReferences, SortActiveColumn, SortColumn, SubmitConnection, SwitchConnection,
ToggleComment, ToggleFilterJoin, ToggleNextJoin, TogglePinColumn, ToggleRowEdit,
ToggleRowPanel, ToggleSidebar, ToggleStructure, ZoomEditorIn, ZoomEditorOut,
};
use completion::SchemaCompletions;
use connection_form::{ConnectionForm, default_profile_name};
Expand Down
24 changes: 24 additions & 0 deletions src/palette.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,8 @@ pub enum Command {
SetFont(FontSlot, String),
ToggleSidebar,
FocusSidebar,
CollapseAllSchemas,
ExpandAllSchemas,
ToggleResultsFocus,
ToggleRowPanel,
ToggleRowEdit,
Expand Down Expand Up @@ -4300,6 +4302,26 @@ fn command_items(workspace: &Workspace, profile: &Profile, cx: &App) -> Vec<Item
),
"focus_sidebar",
));
if matches!(&profile.catalog, CatalogState::Loaded(catalog, _) if !catalog.schemas.is_empty()) {
items.push(bound(
command(
"Expand all schemas",
icon::EXPAND_ALL,
Command::ExpandAllSchemas,
WINDOW,
),
"expand_all_schemas",
));
items.push(bound(
command(
"Collapse all schemas",
icon::COLLAPSE_ALL,
Command::CollapseAllSchemas,
WINDOW,
),
"collapse_all_schemas",
));
}
if session.active_results().is_some() || session.active_object().is_some() {
items.push(bound(
command(
Expand Down Expand Up @@ -4370,6 +4392,8 @@ fn beside_import(command: &Command) -> bool {
| Command::PickFont(_)
| Command::OpenSettings
| Command::ToggleSidebar
| Command::CollapseAllSchemas
| Command::ExpandAllSchemas
| Command::CycleMode
| Command::SetMode(_)
| Command::ResetConfirmations
Expand Down
Loading
Loading