From 130186edf54e60c9ef8fe78c7392b74fb95159da Mon Sep 17 00:00:00 2001 From: victormasson Date: Mon, 30 Nov 2026 12:01:55 +0100 Subject: [PATCH 1/2] feat: Filters the schemas the tree lists with include and exclude regexes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Filter schemas… in the schema tree's options menu opens a dialog with an on/off switch, an include regex and an exclude regex. Patterns ignore case and match anywhere in the name unless anchored, | means or, an empty include keeps every schema and exclude wins. A pattern that doesn't compile shows its error and can't be saved. The filter is saved on the connection (schemaFilter in connections.json), for all its databases, and saving it refreshes the tree. Switching it off keeps the patterns. When it hides every schema, the tree says so. --- Cargo.lock | 1 + crates/barsql-core/src/config.rs | 21 ++ crates/barsql-core/src/lib.rs | 2 +- crates/barsql-ui/Cargo.toml | 1 + crates/barsql-ui/locales/bg.json | 13 +- crates/barsql-ui/locales/de.json | 13 +- crates/barsql-ui/locales/en.json | 13 +- crates/barsql-ui/locales/es.json | 13 +- crates/barsql-ui/src/lib.rs | 1 + crates/barsql-ui/src/schema_filter_dialog.rs | 220 +++++++++++++++++++ crates/barsql-ui/src/schema_tree.rs | 51 ++++- crates/barsql-ui/src/schema_tree/tests.rs | 20 +- crates/barsql-ui/src/sidebar.rs | 1 + guide/schema.md | 1 + 14 files changed, 360 insertions(+), 11 deletions(-) create mode 100644 crates/barsql-ui/src/schema_filter_dialog.rs diff --git a/Cargo.lock b/Cargo.lock index 2e2ad32..63400fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -789,6 +789,7 @@ dependencies = [ "jiff", "lsp-types", "objc2 0.6.5", + "regex", "rfd", "serde", "serde_json", diff --git a/crates/barsql-core/src/config.rs b/crates/barsql-core/src/config.rs index d788de6..16935bb 100644 --- a/crates/barsql-core/src/config.rs +++ b/crates/barsql-core/src/config.rs @@ -156,10 +156,31 @@ pub struct ConnectionConfig { pub ssh: SshConfig, #[serde(default, skip_serializing_if = "ExtensionsConfig::is_empty")] pub extensions: ExtensionsConfig, + #[serde(default, skip_serializing_if = "SchemaFilter::is_empty")] + pub schema_filter: SchemaFilter, #[serde(flatten)] pub extra: Map, } +// The schemas the schema tree lists. Each pattern is a case-insensitive regex found anywhere in the name: an empty +// include keeps every schema, and exclude wins. Switching it off keeps the patterns. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SchemaFilter { + #[serde(default, skip_serializing_if = "is_false")] + pub enabled: bool, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub include: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub exclude: String, +} + +impl SchemaFilter { + fn is_empty(&self) -> bool { + *self == Self::default() + } +} + #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SshConfig { diff --git a/crates/barsql-core/src/lib.rs b/crates/barsql-core/src/lib.rs index d039313..3478e27 100644 --- a/crates/barsql-core/src/lib.rs +++ b/crates/barsql-core/src/lib.rs @@ -11,7 +11,7 @@ pub mod shared; pub mod structure; pub use capabilities::Capabilities; -pub use config::{ConfigError, ConnectionConfig, DriverType, ExtensionFile, ExtensionsConfig, SshConfig}; +pub use config::{ConfigError, ConnectionConfig, DriverType, ExtensionFile, ExtensionsConfig, SchemaFilter, SshConfig}; pub use dialect::SqlDialect; pub use query::{ ExtensionFailure, HistoryEntry, MessageLevel, QueryError, ResultSummary, Row, RowDelete, RowUpdate, SavedQuery, diff --git a/crates/barsql-ui/Cargo.toml b/crates/barsql-ui/Cargo.toml index 2d89d43..478d88e 100644 --- a/crates/barsql-ui/Cargo.toml +++ b/crates/barsql-ui/Cargo.toml @@ -19,6 +19,7 @@ gpui-kit.workspace = true jiff.workspace = true image = { version = "0.25", default-features = false, features = ["png"], optional = true } lsp-types.workspace = true +regex.workspace = true rfd.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/barsql-ui/locales/bg.json b/crates/barsql-ui/locales/bg.json index 0e4262c..36d8123 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -228,7 +228,9 @@ "pickSharedFolder": "Избери папка със SQL файлове", "openFolder": "Отвори папката", "removeFromConnection": "Премахни от тази връзка", - "moveQueryTo": "Премести в" + "moveQueryTo": "Премести в", + "filterSchemas": "Филтриране на схемите…", + "schemasFiltered": "Филтърът на схемите скрива всички схеми. Променете го в „Опции за схемата“." }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -701,5 +703,14 @@ "saveTo": "Запази в", "saveToFile": "Създава {{file}}", "deleteSharedDescription": "Изтрий {{file}} от диска? Свързаните табове остават отворени, но вече не се синхронизират." + }, + "schemaFilter": { + "title": "Филтриране на схемите", + "enabled": "Филтриране на показаните схеми", + "include": "Включване (регулярен израз)", + "exclude": "Изключване (регулярен израз)", + "hint": "| означава „или“: ^test.*|-\\d$ запазва имена, които започват с test или завършват с тире и цифра. Без значение от регистъра, съвпадение навсякъде в името, освен ако е закотвено с ^ или $. Празно „Включване“ запазва всички схеми. „Изключване“ има предимство.", + "invalid": "Невалиден регулярен израз: {{error}}", + "failed": "Филтърът на схемите не можа да бъде запазен" } } diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index 863c529..4c69f20 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -228,7 +228,9 @@ "pickSharedFolder": "Ordner mit SQL-Dateien auswählen", "openFolder": "Ordner öffnen", "removeFromConnection": "Aus dieser Verbindung entfernen", - "moveQueryTo": "Verschieben nach" + "moveQueryTo": "Verschieben nach", + "filterSchemas": "Schemas filtern…", + "schemasFiltered": "Der Schemafilter blendet alle Schemas aus. Ändern Sie ihn in den Schema-Optionen." }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -702,5 +704,14 @@ "saveTo": "Speichern in", "saveToFile": "Erstellt {{file}}", "deleteSharedDescription": "{{file}} von der Festplatte löschen? Verknüpfte Editor-Tabs bleiben offen, sind aber nicht mehr synchronisiert." + }, + "schemaFilter": { + "title": "Schemas filtern", + "enabled": "Aufgelistete Schemas filtern", + "include": "Einschließen (Regex)", + "exclude": "Ausschließen (Regex)", + "hint": "| bedeutet „oder“: ^test.*|-\\d$ behält Namen, die mit test beginnen oder mit Bindestrich und Ziffer enden. Ohne Beachtung der Groß-/Kleinschreibung, Treffer irgendwo im Namen, außer mit ^ oder $ verankert. Ein leeres Einschließen behält alle Schemas. Ausschließen hat Vorrang.", + "invalid": "Kein gültiger Regex: {{error}}", + "failed": "Der Schemafilter konnte nicht gespeichert werden" } } diff --git a/crates/barsql-ui/locales/en.json b/crates/barsql-ui/locales/en.json index b6f061e..735cb84 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -250,7 +250,9 @@ "pickSharedFolder": "Select a folder of SQL files", "openFolder": "Open folder", "removeFromConnection": "Remove from this connection", - "moveQueryTo": "Move to" + "moveQueryTo": "Move to", + "filterSchemas": "Filter schemas…", + "schemasFiltered": "The schema filter hides every schema. Change it in Schema options." }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -731,5 +733,14 @@ "saveTo": "Save to", "saveToFile": "Creates {{file}}", "deleteSharedDescription": "Delete {{file}} from disk? Editor tabs linked to it stay open but are no longer synced." + }, + "schemaFilter": { + "title": "Filter schemas", + "enabled": "Filter the schemas listed", + "include": "Include (regex)", + "exclude": "Exclude (regex)", + "hint": "Use | for “or”: ^test.*|-\\d$ keeps names that start with test or end with a dash and a digit. Case-insensitive, matched anywhere in the name unless anchored with ^ or $. Leave Include empty to keep every schema. Exclude wins.", + "invalid": "Not a valid regex: {{error}}", + "failed": "Could not save the schema filter" } } diff --git a/crates/barsql-ui/locales/es.json b/crates/barsql-ui/locales/es.json index b1b329a..4319398 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -228,7 +228,9 @@ "pickSharedFolder": "Elige una carpeta de archivos SQL", "openFolder": "Abrir carpeta", "removeFromConnection": "Quitar de esta conexión", - "moveQueryTo": "Mover a" + "moveQueryTo": "Mover a", + "filterSchemas": "Filtrar esquemas…", + "schemasFiltered": "El filtro de esquemas oculta todos los esquemas. Cámbialo en Opciones del esquema." }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -711,5 +713,14 @@ "saveTo": "Guardar en", "saveToFile": "Crea {{file}}", "deleteSharedDescription": "¿Eliminar {{file}} del disco? Las pestañas del editor vinculadas siguen abiertas, pero dejan de sincronizarse." + }, + "schemaFilter": { + "title": "Filtrar esquemas", + "enabled": "Filtrar los esquemas listados", + "include": "Incluir (regex)", + "exclude": "Excluir (regex)", + "hint": "| significa «o»: ^test.*|-\\d$ mantiene los nombres que empiezan por test o terminan en guion y dígito. Sin distinguir mayúsculas, coincide en cualquier parte del nombre salvo que se ancle con ^ o $. Deja Incluir vacío para mantener todos los esquemas. Excluir tiene prioridad.", + "invalid": "Regex no válida: {{error}}", + "failed": "No se pudo guardar el filtro de esquemas" } } diff --git a/crates/barsql-ui/src/lib.rs b/crates/barsql-ui/src/lib.rs index 9cff278..753ccec 100644 --- a/crates/barsql-ui/src/lib.rs +++ b/crates/barsql-ui/src/lib.rs @@ -44,6 +44,7 @@ mod scenarios; mod schema; mod schema_actions; mod schema_diff_view; +mod schema_filter_dialog; mod schema_objects; mod schema_tree; mod screenshots; diff --git a/crates/barsql-ui/src/schema_filter_dialog.rs b/crates/barsql-ui/src/schema_filter_dialog.rs new file mode 100644 index 0000000..ec1d149 --- /dev/null +++ b/crates/barsql-ui/src/schema_filter_dialog.rs @@ -0,0 +1,220 @@ +use std::rc::Rc; + +use barsql_core::{ConnectionConfig, SchemaFilter}; +use gpui_kit::component::button::{Button, ButtonVariants}; +use gpui_kit::component::input::{InputEvent, InputState}; +use gpui_kit::component::{Disableable, Sizable, WindowExt, v_flex}; +use gpui_kit::*; +use regex::{Regex, RegexBuilder}; + +use crate::form; +use crate::i18n::{t, t_with}; +use crate::modal::{self, Modal}; +use crate::{state, toast}; + +type OnSaved = Rc; + +// An empty pattern is no pattern. The form trims what it saves. +fn pattern(text: &str) -> Result, regex::Error> { + if text.is_empty() { + return Ok(None); + } + RegexBuilder::new(text).case_insensitive(true).build().map(Some) +} + +// Whether the schema tree lists a schema. A pattern that doesn't compile keeps everything, as the dialog won't save one. +pub(crate) fn keeps(filter: &SchemaFilter) -> impl Fn(&str) -> bool + use<> { + let compiled = |text: &str| if filter.enabled { pattern(text).ok().flatten() } else { None }; + let (include, exclude) = (compiled(&filter.include), compiled(&filter.exclude)); + move |name| include.as_ref().is_none_or(|r| r.is_match(name)) && exclude.as_ref().is_none_or(|r| !r.is_match(name)) +} + +pub(crate) struct SchemaFilterForm { + connection: ConnectionConfig, + enabled: bool, + include: Entity, + exclude: Entity, + saving: bool, + on_saved: OnSaved, + _subscriptions: Vec, +} + +impl SchemaFilterForm { + fn filter(&self, cx: &App) -> SchemaFilter { + SchemaFilter { + enabled: self.enabled, + include: self.include.read(cx).value().trim().to_string(), + exclude: self.exclude.read(cx).value().trim().to_string(), + } + } + + fn error(input: &Entity, cx: &App) -> Option { + let error = pattern(input.read(cx).value().trim()).err()?; + // The regex crate's message spans several lines, with the pattern drawn above a caret. + let reason = error.to_string().lines().last().unwrap_or_default().trim_start_matches("error: ").to_string(); + Some(t_with(cx, "schemaFilter.invalid", &[("error", &reason)])) + } + + fn valid(&self, cx: &App) -> bool { + Self::error(&self.include, cx).is_none() && Self::error(&self.exclude, cx).is_none() + } + + fn save(&mut self, window: &mut Window, cx: &mut Context) { + if self.saving || !self.valid(cx) { + return; + } + let config = ConnectionConfig { schema_filter: self.filter(cx), ..self.connection.clone() }; + self.saving = true; + cx.notify(); + let bar = state::bar(cx); + let task = state::spawn(cx, async move { bar.save_connection(config).await }); + let on_saved = self.on_saved.clone(); + cx.spawn_in(window, async move |this, cx| { + let result = task.await; + let _ = this.update_in(cx, |this, window, cx| { + this.saving = false; + match result { + Some(Ok(_)) => { + window.close_dialog(cx); + on_saved(window, cx); + } + Some(Err(error)) => toast::error_in(t(cx, "schemaFilter.failed"), error.message, cx), + None => {} + } + cx.notify(); + }); + }) + .detach(); + } + + fn field(&self, id: &'static str, label: &str, input: &Entity, window: &Window, cx: &App) -> Div { + let control = v_flex() + .gap(rems(0.462)) + .child( + div().debug_selector(move || id.into()).child(form::input(input, window, cx).disabled(!self.enabled)), + ) + .children(Self::error(input, cx).map(|error| form::error(error, cx))); + form::group(t(cx, label), control, cx) + } +} + +impl Render for SchemaFilterForm { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let enabled = self.enabled; + let toggle = form::checkbox("schema-filter-enabled", enabled, t(cx, "schemaFilter.enabled"), false, cx) + .debug_selector(|| "schema-filter-enabled".into()) + .on_click(cx.listener(move |form, _, _, cx| { + form.enabled = !enabled; + cx.notify(); + })); + let body = modal::body() + .child(toggle) + .child(self.field("schema-filter-include", "schemaFilter.include", &self.include, window, cx)) + .child(self.field("schema-filter-exclude", "schemaFilter.exclude", &self.exclude, window, cx)) + .child(form::hint(t(cx, "schemaFilter.hint"), cx)); + modal::scroll_content().child(modal::scroll_body(body)).child( + modal::footer(cx) + .child( + Button::new("schema-filter-cancel") + .large() + .label(t(cx, "common.cancel")) + .on_click(|_, window, cx| window.close_dialog(cx)), + ) + .child( + Button::new("schema-filter-save") + .large() + .debug_selector(|| "schema-filter-save".into()) + .primary() + .label(t(cx, "common.save")) + .disabled(self.saving || !self.valid(cx)) + .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))), + ), + ) + } +} + +// `connection` is the saved connection, whose filter is edited. +pub fn open( + connection: ConnectionConfig, + window: &mut Window, + cx: &mut App, + on_saved: impl Fn(&mut Window, &mut App) + 'static, +) { + let form = cx.new(|cx| { + let filter = &connection.schema_filter; + // The examples are regexes, the same in every language. + let mut input = |value: &str, example: &'static str, cx: &mut Context| { + let value = value.to_string(); + cx.new(|cx| InputState::new(window, cx).placeholder(example).default_value(value)) + }; + let include = input(&filter.include, r"^test.*|-\d$", cx); + let exclude = input(&filter.exclude, r"^pg_|_old$", cx); + let changed = |cx: &mut Context, input: &Entity| { + cx.subscribe(input, |_, _, event: &InputEvent, cx| { + if matches!(event, InputEvent::Change) { + cx.notify(); + } + }) + }; + let _subscriptions = vec![changed(cx, &include), changed(cx, &exclude)]; + SchemaFilterForm { + enabled: filter.enabled, + connection, + include, + exclude, + saving: false, + on_saved: Rc::new(on_saved), + _subscriptions, + } + }); + window.open_dialog(cx, move |dialog, window, cx| { + let entry = form.clone(); + Modal::new("schema-filter", t(cx, "schemaFilter.title")) + .size(modal::Size::Sm) + .build(dialog, form.clone(), window, cx) + .on_ok(move |_, window, cx| { + entry.update(cx, |form, cx| form.save(window, cx)); + false + }) + }); +} + +#[cfg(test)] +mod tests { + use super::{SchemaFilter, keeps, pattern}; + + fn filter(enabled: bool, include: &str, exclude: &str) -> SchemaFilter { + SchemaFilter { enabled, include: include.into(), exclude: exclude.into() } + } + + #[test] + fn keeps_what_include_finds_unless_exclude_does() { + let keep = keeps(&filter(true, "^app|sales", "_old$")); + assert!(keep("App_core")); + assert!(keep("eu_sales")); + assert!(!keep("app_old")); + assert!(!keep("public")); + } + + #[test] + fn the_dialogs_example_is_an_or() { + let keep = keeps(&filter(true, r"^test.*|-\d$", "")); + assert!(keep("Test_orders")); + assert!(keep("shop-2")); + assert!(!keep("shop-v")); + assert!(!keep("my_test")); + } + + #[test] + fn empty_include_keeps_all_and_off_ignores_patterns() { + assert!(keeps(&filter(true, "", "^pg_"))("public")); + assert!(!keeps(&filter(true, "", "^pg_"))("PG_toast")); + assert!(keeps(&filter(false, "^app", "^pg_"))("pg_toast")); + } + + #[test] + fn a_broken_pattern_keeps_everything() { + assert!(pattern("(").is_err()); + assert!(keeps(&filter(true, "(", "["))("public")); + } +} diff --git a/crates/barsql-ui/src/schema_tree.rs b/crates/barsql-ui/src/schema_tree.rs index 56e3949..b5908ad 100644 --- a/crates/barsql-ui/src/schema_tree.rs +++ b/crates/barsql-ui/src/schema_tree.rs @@ -33,7 +33,7 @@ use crate::spinner::Spinner; use crate::state::{self, set_setting_json, setting_json}; use crate::toast; use crate::tokens::{ICON_SM, ICON_XS, RADIUS, RADIUS_SM, TEXT_2XS, TEXT_BASE, TEXT_SM, TEXT_XS, TINT}; -use crate::{form, hover_card}; +use crate::{form, hover_card, schema_filter_dialog}; // How far a table's Browse button sits from the end of its row. const BROWSE_INSET: Rems = rems(0.308); @@ -82,6 +82,8 @@ pub enum SchemaTreeEvent { Connected(String), // A dialog changed a table, so its open table views need to follow. TableChanged { connection_id: String, schema: String, table: String, change: TableChange }, + // The saved connection changed, like its schema filter, so the connection list reloads. + ConnectionSaved, } // The table the active tab shows. Its row is marked. @@ -211,6 +213,8 @@ impl SchemaTree { pub fn set_connection(&mut self, connection: Option, cx: &mut Context) { let same = self.connection.as_ref().map(|c| &c.id) == connection.as_ref().map(|c| &c.id); + let filter = |c: &Option| c.as_ref().map(|c| c.schema_filter.clone()); + let refiltered = filter(&self.connection) != filter(&connection); self.only_schema = connection .as_ref() .filter(|c| c.shows_all_databases()) @@ -225,11 +229,19 @@ impl SchemaTree { if let Some(conn) = self.connection.clone().filter(|c| state::bar(cx).is_connected(&c.id)) { self.load(&conn, false, cx); } - if !same { + if !same || refiltered { self.schema_changed(cx); } } + // The schemas the tree lists: the connection's filter keeps them, and a picked MySQL or ClickHouse database + // lists only its own. + fn keeps(&self) -> impl Fn(&str) -> bool + use<> { + let filter = self.connection.as_ref().map(|c| schema_filter_dialog::keeps(&c.schema_filter)); + let only = self.only_schema.clone(); + move |name| filter.as_ref().is_none_or(|keep| keep(name)) && only.as_ref().is_none_or(|only| only == name) + } + pub fn set_active_table(&mut self, table: Option, cx: &mut Context) { if self.active_table != table { self.active_table = table; @@ -362,10 +374,11 @@ impl SchemaTree { let Some(data) = schema::get(cx, &conn.id) else { return }; let Some(schemas) = data.schemas() else { return }; let searching = !self.needle.is_empty(); + let keep = self.keeps(); let mut tables_to_load = Vec::new(); let mut columns_to_load = Vec::new(); let mut sizes_to_load = Vec::new(); - for sch in schemas.iter().filter(|s| self.only_schema.as_ref().is_none_or(|only| *only == s.name)) { + for sch in schemas.iter().filter(|s| keep(&s.name)) { let key = format!("{}:{}", conn.id, sch.name); let open = self.expanded_schemas.get(&key) == Some(&true); let Some(tables) = data.tables(&sch.name) else { @@ -507,7 +520,8 @@ impl SchemaTree { let Some(data) = schema::get(cx, &conn.id) else { return rows }; let Some(schemas) = data.schemas() else { return rows }; let needle = self.needle.as_str(); - for sch in schemas.iter().filter(|s| self.only_schema.as_ref().is_none_or(|only| *only == s.name)) { + let keep = self.keeps(); + for sch in schemas.iter().filter(|s| keep(&s.name)) { let key = format!("{}:{}", conn.id, sch.name); let all = data.tables(&sch.name).unwrap_or_default(); let loading = data.tables_loading(&sch.name); @@ -1593,9 +1607,10 @@ impl SchemaTree { let (open, writable) = (self.has_open(), self.writable()); let driver = self.connection.as_ref().map(|c| c.driver.clone()).unwrap_or_default(); let server_views = views(&driver, ViewScope::Server).next().is_some(); + let filtered = self.connection.as_ref().is_some_and(|c| c.schema_filter.enabled); let button = form::options_button("schema-options", t(cx, "sidebar.schemaOptions")).disabled(!enabled); form::sidebar_menu(button, move |menu, window, cx| { - let (collapse, import, views_for) = (this.clone(), this.clone(), this.clone()); + let (collapse, import, views_for, filter) = (this.clone(), this.clone(), this.clone(), this.clone()); let driver = driver.clone(); menu.item( PopupMenuItem::new(t(cx, "sidebar.collapseAll")) @@ -1614,6 +1629,14 @@ impl SchemaTree { let _ = import.update(cx, |tree, cx| tree.import_default(window, cx)); }), ) + .item( + PopupMenuItem::new(t(cx, "sidebar.filterSchemas")) + .icon(Icon::new(Lucide::Funnel)) + .checked(filtered) + .on_click(move |_, window, cx| { + let _ = filter.update(cx, |tree, cx| tree.edit_schema_filter(window, cx)); + }), + ) .when(server_views, |menu| { let label = t(cx, "sidebar.serverViews"); menu.submenu_with_icon(Some(Icon::new(Lucide::Activity)), label, window, cx, move |menu, _, cx| { @@ -1623,6 +1646,21 @@ impl SchemaTree { }) } + // Saved on the connection itself, for each of its databases. + fn edit_schema_filter(&mut self, window: &mut Window, cx: &mut Context) { + let Some(base) = self.connection.as_ref().map(|c| barsql_core::scope::base_id(&c.id).to_string()) else { + return; + }; + let Some(saved) = state::bar(cx).list_connections().into_iter().find(|c| c.id == base) else { return }; + let this = cx.entity().downgrade(); + schema_filter_dialog::open(saved, window, cx, move |_, cx| { + let _ = this.update(cx, |tree, cx| { + cx.emit(SchemaTreeEvent::ConnectionSaved); + tree.refresh(cx); + }); + }); + } + // A failed connect names the connection and offers Connect again, in place of the Not connected page. A schema // that failed to load keeps what the tree has under the card. fn error_card(&self, conn: &ConnectionConfig, connected: bool, cx: &mut Context) -> Option
{ @@ -1825,6 +1863,7 @@ impl Render for SchemaTree { let data = schema::get(cx, &conn.id); let loading = data.is_some_and(|d| d.loading()); let schemas_empty = data.and_then(|d| d.schemas()).is_some_and(<[_]>::is_empty); + let all_filtered = data.and_then(|d| d.schemas()).is_some() && self.rows.is_empty() && self.needle.is_empty(); let connected = self.connected(cx); let body = if loading { form::loading_state(t(cx, "sidebar.loadingSchemasTables"), cx).into_any_element() @@ -1844,6 +1883,8 @@ impl Render for SchemaTree { } } else if schemas_empty && self.error.is_none() { self.message(None, t(cx, "sidebar.noSchemasRefresh"), cx).into_any_element() + } else if all_filtered && self.error.is_none() { + self.message(Some(Lucide::Funnel), t(cx, "sidebar.schemasFiltered"), cx).into_any_element() } else if self.rows.is_empty() && !self.needle.is_empty() { self.message(None, t(cx, "sidebar.noMatches"), cx).into_any_element() } else { diff --git a/crates/barsql-ui/src/schema_tree/tests.rs b/crates/barsql-ui/src/schema_tree/tests.rs index 0b2e13f..4168e10 100644 --- a/crates/barsql-ui/src/schema_tree/tests.rs +++ b/crates/barsql-ui/src/schema_tree/tests.rs @@ -1,7 +1,7 @@ use std::cell::RefCell; use std::rc::Rc; -use barsql_core::{ColumnInfo, DriverType, ObjectKind, SqlDialect}; +use barsql_core::{ColumnInfo, ConnectionConfig, DriverType, ObjectKind, SchemaFilter, SqlDialect}; use gpui_kit::assets::IconName as Lucide; use gpui_kit::test::TestWindowExt as _; use gpui_kit::{Entity, Modifiers, MouseButton, MouseDownEvent, TestAppContext, VisualTestContext}; @@ -253,6 +253,24 @@ fn searching_filters_tables_by_column_and_counts_them(cx: &mut TestAppContext) { settle(cx, |cx| ids(&tree, cx).is_empty()); } +#[gpui_kit::test] +fn the_schema_filter_hides_schemas_until_it_is_switched_off(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tree, cx) = open(&env, cx); + connect(&tree, cx); + let schema_filter = SchemaFilter { enabled: true, include: String::new(), exclude: "^MAIN$".into() }; + let filtered = ConnectionConfig { schema_filter, ..env.connection.clone() }; + tree.update(cx, |tree, cx| tree.set_connection(Some(filtered.clone()), cx)); + settle(cx, |cx| ids(&tree, cx).is_empty()); + + let off = ConnectionConfig { + schema_filter: SchemaFilter { enabled: false, ..filtered.schema_filter.clone() }, + ..filtered + }; + tree.update(cx, |tree, cx| tree.set_connection(Some(off), cx)); + settle(cx, has(&tree, "s:main")); +} + #[gpui_kit::test] fn refresh_reloads_and_forgets_loaded_groups(cx: &mut TestAppContext) { let env = Env::new(cx); diff --git a/crates/barsql-ui/src/sidebar.rs b/crates/barsql-ui/src/sidebar.rs index 6ea4786..c28d246 100644 --- a/crates/barsql-ui/src/sidebar.rs +++ b/crates/barsql-ui/src/sidebar.rs @@ -126,6 +126,7 @@ impl Sidebar { title: title.clone(), run: false, }, + SchemaTreeEvent::ConnectionSaved => return this.reload_connections(cx), SchemaTreeEvent::TableChanged { connection_id, schema, table, change } => { SidebarEvent::TableChanged { connection_id: connection_id.clone(), diff --git a/guide/schema.md b/guide/schema.md index 9ac4717..91c785a 100644 --- a/guide/schema.md +++ b/guide/schema.md @@ -7,6 +7,7 @@ - Tables show their size on disk from the catalog's own figures (PostgreSQL, MySQL / MariaDB, SQL Server and ClickHouse): PostgreSQL's and MySQL 8's are estimates as of their last statistics update, which MySQL 8 caches for up to a day, and **Refresh** reads them again - Columns show an icon for their type, and gold primary-key and blue foreign-key icons, as the grid and ER diagram do. Hover one for its full type, foreign-key target, default, whether it's generated, and the values an enum allows - Search tables and columns instantly, with the matches highlighted +- **Filter schemas…** in the tree's options menu hides schemas by name, with an include and an exclude regex. They ignore case and match anywhere in the name unless anchored, `|` means or (`^test.*|-\d$`), an empty include keeps every schema, and exclude wins. The filter is saved with the connection, for all its databases, and switching it off keeps the patterns - Arrow keys move through the tree, `→` / `←` expand and collapse, and `Enter` expands a row or inserts a column's name - **Click** a column to insert its name at the cursor - The 👁 button on a table (or **Browse data**) opens its rows in the grid, editable when it has a primary key From 9822b65fc4502bde6004764b61ad6e1163d0397d Mon Sep 17 00:00:00 2001 From: Bare7a Date: Tue, 1 Dec 2026 11:44:34 +0200 Subject: [PATCH 2/2] Hardens the schema filter and extends it to the database lists --- Cargo.lock | 2 +- crates/barsql-core/Cargo.toml | 1 + crates/barsql-core/src/config.rs | 131 +++++++++++++- crates/barsql-core/src/lib.rs | 4 +- crates/barsql-core/src/scope.rs | 7 +- crates/barsql-ui/Cargo.toml | 1 - crates/barsql-ui/locales/bg.json | 12 +- crates/barsql-ui/locales/de.json | 8 +- crates/barsql-ui/locales/en.json | 8 +- crates/barsql-ui/locales/es.json | 8 +- crates/barsql-ui/src/database_pane.rs | 54 +++++- crates/barsql-ui/src/query_tab.rs | 7 +- crates/barsql-ui/src/scenarios/driver.rs | 8 + crates/barsql-ui/src/scenarios/import.rs | 4 +- crates/barsql-ui/src/scenarios/schema.rs | 62 ++++++- crates/barsql-ui/src/schema.rs | 18 ++ crates/barsql-ui/src/schema_filter_dialog.rs | 171 +++++++++---------- crates/barsql-ui/src/schema_tree.rs | 139 +++++++++------ crates/barsql-ui/src/schema_tree/tests.rs | 57 ++++++- crates/barsql-ui/src/sidebar.rs | 14 +- guide/schema.md | 2 +- 21 files changed, 532 insertions(+), 186 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 63400fa..f7bd401 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -691,6 +691,7 @@ dependencies = [ "dirs 7.0.0", "hex", "jiff", + "regex", "serde", "serde_json", "sha2 0.11.2", @@ -789,7 +790,6 @@ dependencies = [ "jiff", "lsp-types", "objc2 0.6.5", - "regex", "rfd", "serde", "serde_json", diff --git a/crates/barsql-core/Cargo.toml b/crates/barsql-core/Cargo.toml index 404d065..3500887 100644 --- a/crates/barsql-core/Cargo.toml +++ b/crates/barsql-core/Cargo.toml @@ -9,6 +9,7 @@ publish.workspace = true dirs.workspace = true hex.workspace = true jiff.workspace = true +regex.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true diff --git a/crates/barsql-core/src/config.rs b/crates/barsql-core/src/config.rs index 16935bb..1548939 100644 --- a/crates/barsql-core/src/config.rs +++ b/crates/barsql-core/src/config.rs @@ -1,5 +1,6 @@ use std::fmt; +use regex::{Regex, RegexBuilder}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; @@ -162,8 +163,7 @@ pub struct ConnectionConfig { pub extra: Map, } -// The schemas the schema tree lists. Each pattern is a case-insensitive regex found anywhere in the name: an empty -// include keeps every schema, and exclude wins. Switching it off keeps the patterns. +// Case-insensitive regexes for the schemas the tree lists; exclude wins. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SchemaFilter { @@ -173,12 +173,66 @@ pub struct SchemaFilter { pub include: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub exclude: String, + #[serde(flatten)] + pub extra: Map, } impl SchemaFilter { fn is_empty(&self) -> bool { *self == Self::default() } + + fn normalize(&mut self) { + for text in [&mut self.include, &mut self.exclude] { + if text.trim().is_empty() { + text.clear(); + } + } + } + + // A pattern that doesn't compile keeps everything; the dialog won't switch one on. + pub fn matcher(&self) -> SchemaMatcher { + let compiled = |text: &str| if self.enabled { pattern(text).ok().flatten() } else { None }; + let (include, exclude) = (compiled(&self.include), compiled(&self.exclude)); + SchemaMatcher { filter: Some(self.clone()), include, exclude } + } + + // The last line of the regex crate's message, which draws the pattern above it. + pub fn pattern_error(text: &str) -> Option { + let error = pattern(text).err()?.to_string(); + Some(error.lines().last().unwrap_or_default().trim_start_matches("error: ").to_string()) + } +} + +// Spaces count in a regex, so only a blank pattern is none. +fn pattern(text: &str) -> Result, regex::Error> { + if text.trim().is_empty() { + return Ok(None); + } + RegexBuilder::new(text).case_insensitive(true).build().map(Some) +} + +#[derive(Default)] +pub struct SchemaMatcher { + filter: Option, + include: Option, + exclude: Option, +} + +impl SchemaMatcher { + // Recompiles only for another filter, and says whether it did. + pub fn set(&mut self, filter: Option<&SchemaFilter>) -> bool { + if self.filter.as_ref() == filter { + return false; + } + *self = filter.map(SchemaFilter::matcher).unwrap_or_default(); + true + } + + pub fn keeps(&self, name: &str) -> bool { + self.include.as_ref().is_none_or(|r| r.is_match(name)) + && self.exclude.as_ref().is_none_or(|r| !r.is_match(name)) + } } #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] @@ -244,6 +298,7 @@ impl ConnectionConfig { self.take_url_token(); self.ssh.normalize(); self.extensions.normalize(); + self.schema_filter.normalize(); } // Turso's dashboard hands out URLs with `?authToken=…`. The token goes in its own field, so the URL can be @@ -862,4 +917,76 @@ mod tests { // The fingerprint before url and authToken existed. assert_eq!(cfg.fingerprint(), hex::encode(Sha256::digest(b"postgres|h|0|||||||false|false||0|||||||false"))); } + + fn matcher(enabled: bool, include: &str, exclude: &str) -> SchemaMatcher { + SchemaFilter { enabled, include: include.into(), exclude: exclude.into(), ..Default::default() }.matcher() + } + + #[test] + fn a_schema_filter_keeps_what_include_finds_unless_exclude_does() { + let filter = matcher(true, "^app|sales", "_old$"); + assert!(filter.keeps("App_core")); + assert!(filter.keeps("eu_sales")); + assert!(!filter.keeps("app_old")); + assert!(!filter.keeps("public")); + } + + #[test] + fn the_schema_filters_example_is_an_or() { + let filter = matcher(true, r"^test.*|-\d$", ""); + assert!(filter.keeps("Test_orders")); + assert!(filter.keeps("shop-2")); + assert!(!filter.keeps("shop-v")); + assert!(!filter.keeps("my_test")); + } + + #[test] + fn a_blank_include_keeps_all_and_a_filter_off_ignores_its_patterns() { + assert!(matcher(true, "", "^pg_").keeps("public")); + assert!(matcher(true, " ", "^pg_").keeps("public")); + assert!(!matcher(true, "", "^pg_").keeps("PG_toast")); + assert!(matcher(false, "^app", "^pg_").keeps("pg_toast")); + } + + #[test] + fn a_broken_pattern_says_why_and_keeps_everything() { + assert_eq!(SchemaFilter::pattern_error("(").as_deref(), Some("unclosed group")); + assert_eq!(SchemaFilter::pattern_error("^app"), None); + assert!(matcher(true, "(", "[").keeps("public")); + } + + #[test] + fn spaces_count_in_a_schema_pattern() { + let trailing = matcher(true, "", " $"); + assert!(trailing.keeps("public")); + assert!(!trailing.keeps("archive ")); + assert_eq!(SchemaFilter::pattern_error(r"prod\ "), None); + let filter = SchemaFilter { include: " ".into(), exclude: " $".into(), ..Default::default() }; + let mut cfg = ConnectionConfig { schema_filter: filter, ..pg() }; + cfg.normalize(); + assert_eq!((cfg.schema_filter.include.as_str(), cfg.schema_filter.exclude.as_str()), ("", " $")); + } + + #[test] + fn a_matcher_compiles_again_only_for_another_filter() { + let mut matcher = SchemaMatcher::default(); + let filter = SchemaFilter { enabled: true, exclude: "^pg_".into(), ..Default::default() }; + assert!(matcher.set(Some(&filter))); + assert!(!matcher.set(Some(&filter.clone()))); + assert!(!matcher.keeps("pg_toast")); + assert!(matcher.set(None)); + assert!(matcher.keeps("pg_toast")); + } + + #[test] + fn the_schema_filter_stays_out_of_the_file_until_set_and_keeps_unknown_fields() { + assert!(serde_json::to_value(pg()).unwrap().get("schemaFilter").is_none()); + let json = r#"{"driver":"postgres","schemaFilter":{"enabled":true,"exclude":"^pg_","later":1}}"#; + let cfg: ConnectionConfig = serde_json::from_str(json).unwrap(); + assert!(cfg.schema_filter.enabled && cfg.schema_filter.exclude == "^pg_"); + assert_eq!( + serde_json::to_value(&cfg).unwrap()["schemaFilter"], + serde_json::json!({ "enabled": true, "exclude": "^pg_", "later": 1 }) + ); + } } diff --git a/crates/barsql-core/src/lib.rs b/crates/barsql-core/src/lib.rs index 3478e27..dff2306 100644 --- a/crates/barsql-core/src/lib.rs +++ b/crates/barsql-core/src/lib.rs @@ -11,7 +11,9 @@ pub mod shared; pub mod structure; pub use capabilities::Capabilities; -pub use config::{ConfigError, ConnectionConfig, DriverType, ExtensionFile, ExtensionsConfig, SchemaFilter, SshConfig}; +pub use config::{ + ConfigError, ConnectionConfig, DriverType, ExtensionFile, ExtensionsConfig, SchemaFilter, SchemaMatcher, SshConfig, +}; pub use dialect::SqlDialect; pub use query::{ ExtensionFailure, HistoryEntry, MessageLevel, QueryError, ResultSummary, Row, RowDelete, RowUpdate, SavedQuery, diff --git a/crates/barsql-core/src/scope.rs b/crates/barsql-core/src/scope.rs index 28ea8ad..d65bf8d 100644 --- a/crates/barsql-core/src/scope.rs +++ b/crates/barsql-core/src/scope.rs @@ -2,7 +2,7 @@ // database swapped. The connection's own database keeps the base id, so its tabs, history and tree state stay put. use crate::capabilities::DefaultSchema; -use crate::config::ConnectionConfig; +use crate::config::{ConnectionConfig, SchemaFilter}; pub const SEPARATOR: char = '/'; @@ -52,6 +52,11 @@ impl ConnectionConfig { } } + // The schema filter, for the database lists of an engine whose databases are its schemas. + pub fn database_filter(&self) -> Option<&SchemaFilter> { + (self.driver.capabilities().default_schema == DefaultSchema::Database).then_some(&self.schema_filter) + } + // Called on the saved connection. Its own database gives the connection back unchanged. pub fn in_database(&self, database: &str) -> ConnectionConfig { if database == self.default_database() { diff --git a/crates/barsql-ui/Cargo.toml b/crates/barsql-ui/Cargo.toml index 478d88e..2d89d43 100644 --- a/crates/barsql-ui/Cargo.toml +++ b/crates/barsql-ui/Cargo.toml @@ -19,7 +19,6 @@ gpui-kit.workspace = true jiff.workspace = true image = { version = "0.25", default-features = false, features = ["png"], optional = true } lsp-types.workspace = true -regex.workspace = true rfd.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/barsql-ui/locales/bg.json b/crates/barsql-ui/locales/bg.json index a23fe68..e7bd05d 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -231,7 +231,7 @@ "removeFromConnection": "Премахни от тази връзка", "moveQueryTo": "Премести в", "filterSchemas": "Филтриране на схемите…", - "schemasFiltered": "Филтърът на схемите скрива всички схеми. Променете го в „Опции за схемата“." + "schemasFiltered": "Филтърът скрива всички схеми" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -810,11 +810,11 @@ }, "schemaFilter": { "title": "Филтриране на схемите", - "enabled": "Филтриране на показаните схеми", - "include": "Включване (регулярен израз)", - "exclude": "Изключване (регулярен израз)", - "hint": "| означава „или“: ^test.*|-\\d$ запазва имена, които започват с test или завършват с тире и цифра. Без значение от регистъра, съвпадение навсякъде в името, освен ако е закотвено с ^ или $. Празно „Включване“ запазва всички схеми. „Изключване“ има предимство.", + "enabled": "Използвай филтъра", + "include": "Включване (regex)", + "exclude": "Изключване (regex)", + "hint": "Без значение от регистъра, съвпадение навсякъде в името. „Изключване“ има предимство.", "invalid": "Невалиден регулярен израз: {{error}}", - "failed": "Филтърът на схемите не можа да бъде запазен" + "spaces": "Интервалите в началото или края се броят" } } diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index bd3a0db..3f8cdef 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -231,7 +231,7 @@ "removeFromConnection": "Aus dieser Verbindung entfernen", "moveQueryTo": "Verschieben nach", "filterSchemas": "Schemas filtern…", - "schemasFiltered": "Der Schemafilter blendet alle Schemas aus. Ändern Sie ihn in den Schema-Optionen." + "schemasFiltered": "Der Filter blendet alle Schemas aus" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -811,11 +811,11 @@ }, "schemaFilter": { "title": "Schemas filtern", - "enabled": "Aufgelistete Schemas filtern", + "enabled": "Filter verwenden", "include": "Einschließen (Regex)", "exclude": "Ausschließen (Regex)", - "hint": "| bedeutet „oder“: ^test.*|-\\d$ behält Namen, die mit test beginnen oder mit Bindestrich und Ziffer enden. Ohne Beachtung der Groß-/Kleinschreibung, Treffer irgendwo im Namen, außer mit ^ oder $ verankert. Ein leeres Einschließen behält alle Schemas. Ausschließen hat Vorrang.", + "hint": "Ohne Beachtung der Groß-/Kleinschreibung, Treffer irgendwo im Namen. Ausschließen hat Vorrang.", "invalid": "Kein gültiger Regex: {{error}}", - "failed": "Der Schemafilter konnte nicht gespeichert werden" + "spaces": "Leerzeichen am Anfang oder Ende zählen mit" } } diff --git a/crates/barsql-ui/locales/en.json b/crates/barsql-ui/locales/en.json index b5fc855..621191e 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -253,7 +253,7 @@ "removeFromConnection": "Remove from this connection", "moveQueryTo": "Move to", "filterSchemas": "Filter schemas…", - "schemasFiltered": "The schema filter hides every schema. Change it in Schema options." + "schemasFiltered": "The filter hides every schema" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -840,11 +840,11 @@ }, "schemaFilter": { "title": "Filter schemas", - "enabled": "Filter the schemas listed", + "enabled": "Use the filter", "include": "Include (regex)", "exclude": "Exclude (regex)", - "hint": "Use | for “or”: ^test.*|-\\d$ keeps names that start with test or end with a dash and a digit. Case-insensitive, matched anywhere in the name unless anchored with ^ or $. Leave Include empty to keep every schema. Exclude wins.", + "hint": "Ignores case and matches anywhere in the name. Exclude wins.", "invalid": "Not a valid regex: {{error}}", - "failed": "Could not save the schema filter" + "spaces": "Leading or trailing spaces count" } } diff --git a/crates/barsql-ui/locales/es.json b/crates/barsql-ui/locales/es.json index 552fe51..fe4f015 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -231,7 +231,7 @@ "removeFromConnection": "Quitar de esta conexión", "moveQueryTo": "Mover a", "filterSchemas": "Filtrar esquemas…", - "schemasFiltered": "El filtro de esquemas oculta todos los esquemas. Cámbialo en Opciones del esquema." + "schemasFiltered": "El filtro oculta todos los esquemas" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -820,11 +820,11 @@ }, "schemaFilter": { "title": "Filtrar esquemas", - "enabled": "Filtrar los esquemas listados", + "enabled": "Usar el filtro", "include": "Incluir (regex)", "exclude": "Excluir (regex)", - "hint": "| significa «o»: ^test.*|-\\d$ mantiene los nombres que empiezan por test o terminan en guion y dígito. Sin distinguir mayúsculas, coincide en cualquier parte del nombre salvo que se ancle con ^ o $. Deja Incluir vacío para mantener todos los esquemas. Excluir tiene prioridad.", + "hint": "Sin distinguir mayúsculas, coincide en cualquier parte del nombre. Excluir tiene prioridad.", "invalid": "Regex no válida: {{error}}", - "failed": "No se pudo guardar el filtro de esquemas" + "spaces": "Los espacios al principio o al final cuentan" } } diff --git a/crates/barsql-ui/src/database_pane.rs b/crates/barsql-ui/src/database_pane.rs index 8024f37..b23ac3c 100644 --- a/crates/barsql-ui/src/database_pane.rs +++ b/crates/barsql-ui/src/database_pane.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet}; use std::ops::Range; use std::rc::Rc; -use barsql_core::{ConnectionConfig, DatabaseInfo}; +use barsql_core::{ConnectionConfig, DatabaseInfo, SchemaMatcher}; use gpui_kit::assets::IconName as Lucide; use gpui_kit::base::ElementExt as _; use gpui_kit::component::button::{Button, ButtonVariants}; @@ -110,6 +110,7 @@ pub struct DatabasePane { needle: String, collapsed: bool, show_system: bool, + schema_matcher: SchemaMatcher, rows: f32, next_load: u64, nav: ListNav, @@ -149,6 +150,7 @@ impl DatabasePane { needle: String::new(), collapsed: setting_bool(cx, COLLAPSED_KEY, false), show_system: setting_bool(cx, SYSTEM_KEY, false), + schema_matcher: SchemaMatcher::default(), rows: ROWS.0, next_load: 0, nav: ListNav::with_scroll(UniformListScrollHandle::new(), cx), @@ -161,6 +163,8 @@ impl DatabasePane { let key = |c: &Option| c.as_ref().map(|c| (c.id.clone(), c.fingerprint())); let same = key(&self.connection) == key(&connection); let moved = shown != self.shown; + // Databases are schemas on MySQL and ClickHouse, so the schema filter hides them here too. + self.schema_matcher.set(connection.as_ref().and_then(ConnectionConfig::database_filter)); self.connection = connection; self.shown = shown; if !same { @@ -307,7 +311,12 @@ impl DatabasePane { .detach(); } - // The connection's own database and the one shown stay, even when they're system ones. + // The connection's own database and the one shown stay, even when they're system ones or filtered out. + fn kept(&self, db: &DatabaseInfo, own: &str) -> bool { + let listed = (self.show_system || !db.system) && self.schema_matcher.keeps(&db.name); + listed || db.name == own || db.name == self.shown + } + fn visible(&self) -> Vec { let (Listed::Ready(all), Some(base)) = (&self.listed, &self.connection) else { return Vec::new() }; let own = base.default_database(); @@ -315,7 +324,7 @@ impl DatabasePane { let pinned = self.pinned(); let mut shown: Vec = all .iter() - .filter(|db| self.show_system || !db.system || db.name == own || db.name == self.shown) + .filter(|db| self.kept(db, &own)) .filter(|db| needle.is_empty() || db.name.to_lowercase().contains(&needle)) .cloned() .collect(); @@ -324,7 +333,8 @@ impl DatabasePane { } fn filtered(&self) -> bool { - matches!(&self.listed, Listed::Ready(all) if all.iter().filter(|db| !db.system).count() > FILTER_AFTER) + let Listed::Ready(all) = &self.listed else { return false }; + all.iter().filter(|db| !db.system && self.schema_matcher.keeps(&db.name)).count() > FILTER_AFTER } fn step(&mut self, step: isize, cx: &mut Context) { @@ -645,8 +655,9 @@ impl DatabasePane { impl Render for DatabasePane { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let shown: Rc<[DatabaseInfo]> = self.visible().into(); + let own = self.connection.as_ref().map(ConnectionConfig::default_database).unwrap_or_default(); let count = match &self.listed { - Listed::Ready(all) => Some(all.iter().filter(|db| self.show_system || !db.system).count()), + Listed::Ready(all) => Some(all.iter().filter(|db| self.kept(db, &own)).count()), _ => None, }; let filter = (!self.collapsed && self.filtered()).then(|| { @@ -667,7 +678,7 @@ impl Render for DatabasePane { #[cfg(test)] mod tests { - use barsql_core::{ConnectionConfig, DatabaseInfo, DriverType}; + use barsql_core::{ConnectionConfig, DatabaseInfo, DriverType, SchemaFilter}; use gpui_kit::{TestAppContext, VisualTestContext}; use super::DatabasePane; @@ -715,6 +726,37 @@ mod tests { }); } + #[gpui_kit::test] + fn the_schema_filter_hides_databases_only_where_they_are_schemas(cx: &mut TestAppContext) { + let _env = Env::new(cx); + let window = cx.add_window(DatabasePane::new); + let pane = window.root(cx).unwrap(); + let cx = VisualTestContext::from_window(window.into(), cx).into_mut(); + let mysql = ConnectionConfig { + id: "server".into(), + driver: DriverType::MySql, + database: "app".into(), + show_all_databases: true, + schema_filter: SchemaFilter { enabled: true, exclude: "^log".into(), ..Default::default() }, + ..Default::default() + }; + let listed = || { + vec![db("app", true, false), db("logs", true, false), db("log_old", true, false), db("sales", true, false)] + }; + let names = |cx: &mut VisualTestContext| pane.read_with(cx, |pane, _| pane.listed()); + pane.update(cx, |pane, cx| { + pane.set_connection(Some(mysql.clone()), "logs".into(), cx); + pane.show_list(listed(), cx); + }); + assert_eq!(names(cx), ["app", "logs", "sales"], "the shown database stays"); + let postgres = ConnectionConfig { driver: DriverType::Postgres, ..mysql }; + pane.update(cx, |pane, cx| { + pane.set_connection(Some(postgres), "logs".into(), cx); + pane.show_list(listed(), cx); + }); + assert_eq!(names(cx), ["app", "logs", "log_old", "sales"], "Postgres databases aren't its schemas"); + } + #[gpui_kit::test] fn the_database_the_tree_shows_scrolls_into_view(cx: &mut TestAppContext) { let _env = Env::new(cx); diff --git a/crates/barsql-ui/src/query_tab.rs b/crates/barsql-ui/src/query_tab.rs index fdc214e..16178fd 100644 --- a/crates/barsql-ui/src/query_tab.rs +++ b/crates/barsql-ui/src/query_tab.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use barsql_app::{BuilderRef, EditorTab, RunEvent, TablePlace}; -use barsql_core::{ConnectionConfig, DatabaseInfo, SavedQuery, scope}; +use barsql_core::{ConnectionConfig, DatabaseInfo, SavedQuery, SchemaFilter, scope}; use barsql_sql::design; use barsql_sql::lang::{self, TxnControl, detect_transaction_control}; use barsql_sql::params::{find_params, param_names, substitute}; @@ -517,6 +517,7 @@ impl QueryTab { database_pane::ensure_listed(&base, cx); } let movable = self.movable(cx); + let filter = self.connection.database_filter().cloned(); let tab = cx.entity().downgrade(); let picker = Button::new("tab-database") .debug_selector(|| "tab-database".into()) @@ -529,7 +530,9 @@ impl QueryTab { let key = if listed.is_some() { "connection.noDatabases" } else { "connection.loadingDatabases" }; return menu.item(PopupMenuItem::new(t(cx, key)).disabled(true)); }; - for db in listed.iter().filter(|db| !db.system || db.name == current) { + // Compiled as the menu opens, with the Databases list's rule. + let matcher = filter.as_ref().map(SchemaFilter::matcher).unwrap_or_default(); + for db in listed.iter().filter(|db| (!db.system && matcher.keeps(&db.name)) || db.name == current) { let (tab, name) = (tab.clone(), db.name.clone()); menu = menu.item( PopupMenuItem::new(db.name.clone()) diff --git a/crates/barsql-ui/src/scenarios/driver.rs b/crates/barsql-ui/src/scenarios/driver.rs index 4cba7f9..f48724e 100644 --- a/crates/barsql-ui/src/scenarios/driver.rs +++ b/crates/barsql-ui/src/scenarios/driver.rs @@ -492,6 +492,14 @@ impl Driver<'_> { self.pause(); } + // Counts up from the menu's last item, for menus whose first items are disabled in some states. + pub fn menu_pick_from_end(&mut self, selector: &'static str, ups: usize) { + self.click(selector); + self.cx.update(|window, cx| window.draw(cx).clear(cx)); + self.keys(&format!("{}enter", "up ".repeat(ups + 1))); + self.pause(); + } + // As `context_submenu`, for a button's menu ending in the submenu. Up reaches it past items that may be disabled. #[cfg(feature = "e2e")] pub fn menu_last_submenu(&mut self, selector: &'static str, pick: usize) { diff --git a/crates/barsql-ui/src/scenarios/import.rs b/crates/barsql-ui/src/scenarios/import.rs index 8c35874..a7998ea 100644 --- a/crates/barsql-ui/src/scenarios/import.rs +++ b/crates/barsql-ui/src/scenarios/import.rs @@ -45,9 +45,9 @@ fn import(app: &mut Driver) -> (i64, i64) { shown(app).result.expect("an import result") } -// Import data, from the schema tree's options menu. +// Second from the end on SQLite, so Collapse all turning on as the schema loads can't shift it. fn toolbar_import(app: &mut Driver) { - app.menu_pick("schema-options", 1); + app.menu_pick_from_end("schema-options", 1); } #[gpui_kit::test] diff --git a/crates/barsql-ui/src/scenarios/schema.rs b/crates/barsql-ui/src/scenarios/schema.rs index 84b42f7..686ac71 100644 --- a/crates/barsql-ui/src/scenarios/schema.rs +++ b/crates/barsql-ui/src/scenarios/schema.rs @@ -1,4 +1,4 @@ -use barsql_core::Value; +use barsql_core::{SchemaFilter, Value}; use gpui_kit::component::scroll::Scrollbar; use gpui_kit::{Entity, Modifiers, TestAppContext, point, px}; @@ -19,6 +19,8 @@ const COLUMN_INSERT: usize = 0; const COLUMN_RENAME: usize = 2; const COLUMN_DROP: usize = 3; const OBJECT_DROP: usize = 3; +// Last in the schema options menu on SQLite, where Collapse all above it comes and goes. +const FILTER_SCHEMAS_FROM_END: usize = 0; fn tree(app: &mut Driver) -> Entity { let sidebar = app.sidebar(); @@ -73,6 +75,64 @@ fn the_schema_search_filters_tables_and_says_when_nothing_matches(cx: &mut TestA assert!(has(&mut app, "t:main.e2e_keep") && has(&mut app, "t:main.e2e_other")); } +fn generation(app: &mut Driver) -> u64 { + let id = app.connection.id.clone(); + let generation = app.cx.update(|_, cx| crate::schema::get(cx, &id).map(|entry| entry.generation())); + generation.expect("the schema is cached") +} + +fn saved_filter(app: &mut Driver) -> SchemaFilter { + let saved = app.env.bar.list_connections().into_iter().find(|c| c.id == app.connection.id); + saved.expect("the connection is saved").schema_filter +} + +fn toggle_schema_filter(app: &mut Driver, include: Option<&str>, exclude: Option<&str>) { + app.menu_pick_from_end("schema-options", FILTER_SCHEMAS_FROM_END); + app.click("schema-filter-enabled"); + for (selector, pattern) in [("schema-filter-include", include), ("schema-filter-exclude", exclude)] { + if let Some(pattern) = pattern { + app.click(selector); + app.type_text(pattern); + } + } +} + +fn save_schema_filter(app: &mut Driver) { + app.click("schema-filter-save"); + app.settle_dialog_closed(); +} + +#[gpui_kit::test] +fn a_saved_schema_filter_hides_schemas_without_reloading_them(cx: &mut TestAppContext) { + let mut app = prepared(cx, "CREATE TABLE e2e_kept (id INTEGER)"); + let loaded = generation(&mut app); + toggle_schema_filter(&mut app, None, Some("^main$")); + save_schema_filter(&mut app); + listed_row(&mut app, "s:main", false); + assert_eq!(generation(&mut app), loaded, "the tree keeps what it loaded"); + let tree = tree(&mut app); + assert!(app.cx.update(|_, cx| tree.read(cx).says_all_filtered(cx)), "the empty tree says why"); + + toggle_schema_filter(&mut app, None, None); + save_schema_filter(&mut app); + listed_row(&mut app, "t:main.e2e_kept", true); + let filter = saved_filter(&mut app); + assert_eq!((filter.enabled, filter.exclude.as_str()), (false, "^main$"), "switching it off keeps the pattern"); +} + +#[gpui_kit::test] +fn a_filter_switched_off_saves_with_a_broken_pattern(cx: &mut TestAppContext) { + let mut app = prepared(cx, "CREATE TABLE e2e_kept (id INTEGER)"); + toggle_schema_filter(&mut app, Some("("), None); + app.click("schema-filter-save"); + assert!(app.dialog_open() && saved_filter(&mut app) == SchemaFilter::default(), "it can't save switched on"); + app.click("schema-filter-enabled"); + save_schema_filter(&mut app); + let filter = saved_filter(&mut app); + assert_eq!((filter.enabled, filter.include.as_str()), (false, "(")); + listed_row(&mut app, "t:main.e2e_kept", true); +} + #[gpui_kit::test] fn select_in_new_tab_opens_the_tables_rows(cx: &mut TestAppContext) { let mut app = prepared( diff --git a/crates/barsql-ui/src/schema.rs b/crates/barsql-ui/src/schema.rs index fbb9300..b8d6bc4 100644 --- a/crates/barsql-ui/src/schema.rs +++ b/crates/barsql-ui/src/schema.rs @@ -98,6 +98,10 @@ impl ConnectionSchema { self.tables_loading.contains(schema) } + pub fn failed_schemas(&self) -> impl Iterator { + self.tables_failed.iter().map(String::as_str) + } + pub fn size(&self, schema: &str, table: &str) -> Option { self.sizes.get(schema)?.done()?.get(table).copied() } @@ -123,6 +127,11 @@ impl ConnectionSchema { matches!(self.references.get(&column_cache_key(schema, table)), Some(Load::Running(_))) } + #[cfg(test)] + pub fn generation(&self) -> u64 { + self.generation + } + fn next_load(&mut self) -> u64 { self.next_load += 1; self.next_load @@ -244,6 +253,15 @@ pub fn forget(connection_id: &str, cx: &mut App) { *entry = ConnectionSchema { generation: entry.generation + 1, ..Default::default() }; } +// A schema beside SQLite's lone `main`, whose tables failed to load. +#[cfg(test)] +pub fn add_failed_schema(connection_id: &str, name: &str, cx: &mut App) { + let entry = entry(cx, connection_id); + entry.schemas.get_or_insert_default().push(SchemaInfo { name: name.into() }); + entry.tables_failed.insert(name.into()); + entry.error = Some(format!("{name} failed")); +} + pub fn loaded_ids(cx: &App) -> Vec { let Some(schemas) = cx.try_global::() else { return Vec::new() }; schemas.connections.iter().filter(|(_, entry)| entry.schemas.is_some()).map(|(id, _)| id.clone()).collect() diff --git a/crates/barsql-ui/src/schema_filter_dialog.rs b/crates/barsql-ui/src/schema_filter_dialog.rs index ec1d149..d804d2a 100644 --- a/crates/barsql-ui/src/schema_filter_dialog.rs +++ b/crates/barsql-ui/src/schema_filter_dialog.rs @@ -4,36 +4,25 @@ use barsql_core::{ConnectionConfig, SchemaFilter}; use gpui_kit::component::button::{Button, ButtonVariants}; use gpui_kit::component::input::{InputEvent, InputState}; use gpui_kit::component::{Disableable, Sizable, WindowExt, v_flex}; +use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; -use regex::{Regex, RegexBuilder}; use crate::form; use crate::i18n::{t, t_with}; use crate::modal::{self, Modal}; -use crate::{state, toast}; +use crate::state; type OnSaved = Rc; -// An empty pattern is no pattern. The form trims what it saves. -fn pattern(text: &str) -> Result, regex::Error> { - if text.is_empty() { - return Ok(None); - } - RegexBuilder::new(text).case_insensitive(true).build().map(Some) -} - -// Whether the schema tree lists a schema. A pattern that doesn't compile keeps everything, as the dialog won't save one. -pub(crate) fn keeps(filter: &SchemaFilter) -> impl Fn(&str) -> bool + use<> { - let compiled = |text: &str| if filter.enabled { pattern(text).ok().flatten() } else { None }; - let (include, exclude) = (compiled(&filter.include), compiled(&filter.exclude)); - move |name| include.as_ref().is_none_or(|r| r.is_match(name)) && exclude.as_ref().is_none_or(|r| !r.is_match(name)) -} - pub(crate) struct SchemaFilterForm { connection: ConnectionConfig, enabled: bool, include: Entity, exclude: Entity, + // Kept as each pattern changes, since a large regex takes milliseconds to compile. + include_error: Option, + exclude_error: Option, + error: Option, saving: bool, on_saved: OnSaved, _subscriptions: Vec, @@ -43,81 +32,100 @@ impl SchemaFilterForm { fn filter(&self, cx: &App) -> SchemaFilter { SchemaFilter { enabled: self.enabled, - include: self.include.read(cx).value().trim().to_string(), - exclude: self.exclude.read(cx).value().trim().to_string(), + include: self.include.read(cx).value().to_string(), + exclude: self.exclude.read(cx).value().to_string(), + ..self.connection.schema_filter.clone() } } - fn error(input: &Entity, cx: &App) -> Option { - let error = pattern(input.read(cx).value().trim()).err()?; - // The regex crate's message spans several lines, with the pattern drawn above a caret. - let reason = error.to_string().lines().last().unwrap_or_default().trim_start_matches("error: ").to_string(); - Some(t_with(cx, "schemaFilter.invalid", &[("error", &reason)])) - } - - fn valid(&self, cx: &App) -> bool { - Self::error(&self.include, cx).is_none() && Self::error(&self.exclude, cx).is_none() + // A filter that's off doesn't use its patterns, so they don't stop it saving. + fn valid(&self) -> bool { + !self.enabled || (self.include_error.is_none() && self.exclude_error.is_none()) } fn save(&mut self, window: &mut Window, cx: &mut Context) { - if self.saving || !self.valid(cx) { + if self.saving || !self.valid() { return; } let config = ConnectionConfig { schema_filter: self.filter(cx), ..self.connection.clone() }; self.saving = true; + self.error = None; cx.notify(); let bar = state::bar(cx); let task = state::spawn(cx, async move { bar.save_connection(config).await }); let on_saved = self.on_saved.clone(); cx.spawn_in(window, async move |this, cx| { let result = task.await; + let saved = matches!(result, Some(Ok(_))); let _ = this.update_in(cx, |this, window, cx| { this.saving = false; match result { - Some(Ok(_)) => { - window.close_dialog(cx); - on_saved(window, cx); - } - Some(Err(error)) => toast::error_in(t(cx, "schemaFilter.failed"), error.message, cx), + Some(Ok(_)) => window.close_dialog(cx), + Some(Err(error)) => this.error = Some(error.message.into()), None => {} } cx.notify(); }); + // Also when a click closed the dialog during the save and the form is gone. + if saved { + let _ = cx.update(|window, cx| on_saved(window, cx)); + } }) .detach(); } - fn field(&self, id: &'static str, label: &str, input: &Entity, window: &Window, cx: &App) -> Div { + fn field( + &self, + id: &'static str, + label: &str, + input: &Entity, + error: Option<&String>, + window: &Window, + cx: &App, + ) -> Div { + let error = error + .filter(|_| self.enabled) + .map(|reason| t_with(cx, "schemaFilter.invalid", &[("error", reason.as_str())])); + let text = input.read(cx).value(); + let spaced = self.enabled && error.is_none() && !text.trim().is_empty() && text.trim().len() != text.len(); + let input = form::input(input, window, cx).disabled(!self.enabled || self.saving); let control = v_flex() .gap(rems(0.462)) - .child( - div().debug_selector(move || id.into()).child(form::input(input, window, cx).disabled(!self.enabled)), - ) - .children(Self::error(input, cx).map(|error| form::error(error, cx))); + .child(div().debug_selector(move || id.into()).child(input)) + .children(error.map(|error| form::error(error, cx))) + .when(spaced, |el| el.child(form::hint(t(cx, "schemaFilter.spaces"), cx))); form::group(t(cx, label), control, cx) } } impl Render for SchemaFilterForm { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let enabled = self.enabled; - let toggle = form::checkbox("schema-filter-enabled", enabled, t(cx, "schemaFilter.enabled"), false, cx) + let (enabled, saving) = (self.enabled, self.saving); + let toggle = form::checkbox("schema-filter-enabled", enabled, t(cx, "schemaFilter.enabled"), saving, cx) .debug_selector(|| "schema-filter-enabled".into()) - .on_click(cx.listener(move |form, _, _, cx| { - form.enabled = !enabled; - cx.notify(); - })); + .when(!saving, |el| { + el.on_click(cx.listener(|form, _, window, cx| { + form.enabled = !form.enabled; + if form.enabled { + focus_later(&form.include, window, cx); + } + cx.notify(); + })) + }); + let (include, exclude) = (self.include_error.as_ref(), self.exclude_error.as_ref()); let body = modal::body() .child(toggle) - .child(self.field("schema-filter-include", "schemaFilter.include", &self.include, window, cx)) - .child(self.field("schema-filter-exclude", "schemaFilter.exclude", &self.exclude, window, cx)) - .child(form::hint(t(cx, "schemaFilter.hint"), cx)); + .child(self.field("schema-filter-include", "schemaFilter.include", &self.include, include, window, cx)) + .child(self.field("schema-filter-exclude", "schemaFilter.exclude", &self.exclude, exclude, window, cx)) + .child(form::hint(t(cx, "schemaFilter.hint"), cx)) + .children(self.error.clone().map(|error| form::error(error, cx))); modal::scroll_content().child(modal::scroll_body(body)).child( modal::footer(cx) .child( Button::new("schema-filter-cancel") .large() .label(t(cx, "common.cancel")) + .disabled(saving) .on_click(|_, window, cx| window.close_dialog(cx)), ) .child( @@ -126,7 +134,7 @@ impl Render for SchemaFilterForm { .debug_selector(|| "schema-filter-save".into()) .primary() .label(t(cx, "common.save")) - .disabled(self.saving || !self.valid(cx)) + .disabled(saving || !self.valid()) .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))), ), ) @@ -149,72 +157,55 @@ pub fn open( }; let include = input(&filter.include, r"^test.*|-\d$", cx); let exclude = input(&filter.exclude, r"^pg_|_old$", cx); - let changed = |cx: &mut Context, input: &Entity| { - cx.subscribe(input, |_, _, event: &InputEvent, cx| { + let watch = |cx: &mut Context, + input: &Entity, + set: fn(&mut SchemaFilterForm, Option)| { + cx.subscribe(input, move |form, input, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { + set(form, SchemaFilter::pattern_error(&input.read(cx).value())); cx.notify(); } }) }; - let _subscriptions = vec![changed(cx, &include), changed(cx, &exclude)]; + let _subscriptions = vec![ + watch(cx, &include, |form, error| form.include_error = error), + watch(cx, &exclude, |form, error| form.exclude_error = error), + ]; SchemaFilterForm { enabled: filter.enabled, + include_error: SchemaFilter::pattern_error(&filter.include), + exclude_error: SchemaFilter::pattern_error(&filter.exclude), connection, include, exclude, + error: None, saving: false, on_saved: Rc::new(on_saved), _subscriptions, } }); + let (enabled, include) = (form.read(cx).enabled, form.read(cx).include.clone()); window.open_dialog(cx, move |dialog, window, cx| { + let saving = form.read(cx).saving; let entry = form.clone(); Modal::new("schema-filter", t(cx, "schemaFilter.title")) .size(modal::Size::Sm) + .closable(!saving) .build(dialog, form.clone(), window, cx) + .keyboard(!saving) + .overlay_closable(!saving) .on_ok(move |_, window, cx| { entry.update(cx, |form, cx| form.save(window, cx)); false }) }); -} - -#[cfg(test)] -mod tests { - use super::{SchemaFilter, keeps, pattern}; - - fn filter(enabled: bool, include: &str, exclude: &str) -> SchemaFilter { - SchemaFilter { enabled, include: include.into(), exclude: exclude.into() } - } - - #[test] - fn keeps_what_include_finds_unless_exclude_does() { - let keep = keeps(&filter(true, "^app|sales", "_old$")); - assert!(keep("App_core")); - assert!(keep("eu_sales")); - assert!(!keep("app_old")); - assert!(!keep("public")); - } - - #[test] - fn the_dialogs_example_is_an_or() { - let keep = keeps(&filter(true, r"^test.*|-\d$", "")); - assert!(keep("Test_orders")); - assert!(keep("shop-2")); - assert!(!keep("shop-v")); - assert!(!keep("my_test")); - } - - #[test] - fn empty_include_keeps_all_and_off_ignores_patterns() { - assert!(keeps(&filter(true, "", "^pg_"))("public")); - assert!(!keeps(&filter(true, "", "^pg_"))("PG_toast")); - assert!(keeps(&filter(false, "^app", "^pg_"))("pg_toast")); + if enabled { + focus_later(&include, window, cx); } +} - #[test] - fn a_broken_pattern_keeps_everything() { - assert!(pattern("(").is_err()); - assert!(keeps(&filter(true, "(", "["))("public")); - } +// Deferred, so it lands after the dialog takes focus. +fn focus_later(input: &Entity, window: &mut Window, cx: &mut App) { + let input = input.clone(); + window.defer(cx, move |window, cx| input.update(cx, |input, cx| input.focus(window, cx))); } diff --git a/crates/barsql-ui/src/schema_tree.rs b/crates/barsql-ui/src/schema_tree.rs index 1268192..4e70d01 100644 --- a/crates/barsql-ui/src/schema_tree.rs +++ b/crates/barsql-ui/src/schema_tree.rs @@ -3,7 +3,9 @@ use std::ops::Range; use std::time::Duration; use barsql_core::capabilities::DefaultSchema; -use barsql_core::{ColumnInfo, ConnectionConfig, DriverType, ObjectKind, ObjectRef, SqlDialect, TableInfo}; +use barsql_core::{ + ColumnInfo, ConnectionConfig, DriverType, ObjectKind, ObjectRef, SchemaMatcher, SqlDialect, TableInfo, +}; use barsql_sql::alter::ConstraintKind; use barsql_sql::dml::preview_select; use barsql_sql::lang::quoting::build_qualified_table; @@ -24,7 +26,7 @@ use crate::form::{LargeButton as _, ToolButton as _}; use crate::i18n::{I18n, bytes, count, t, t_count, t_with}; use crate::list_nav::{self, BarClearance, LIST_INSET}; use crate::query_builder::TableDrag; -use crate::schema::{self, Schemas}; +use crate::schema::{self, ConnectionSchema, Schemas}; use crate::schema_actions::{self, Applied, Change}; use crate::schema_objects::{ Badge, Group, ObjectRow, constraint_rows, group_key, index_rows, routine_rows, routines_key, trigger_rows, @@ -34,7 +36,7 @@ use crate::spinner::Spinner; use crate::state::{self, set_setting_json, setting_json}; use crate::toast; use crate::tokens::{ICON_SM, ICON_XS, RADIUS, RADIUS_SM, TEXT_2XS, TEXT_BASE, TEXT_SM, TEXT_XS, TINT}; -use crate::{form, hover_card, schema_filter_dialog}; +use crate::{form, hover_card}; // How far a table's Browse button sits from the end of its row. const BROWSE_INSET: Rems = rems(0.308); @@ -85,8 +87,8 @@ pub enum SchemaTreeEvent { Connected(String), // A dialog changed a table, so its open table views need to follow. TableChanged { connection_id: String, schema: String, table: String, change: TableChange }, - // The saved connection changed, like its schema filter, so the connection list reloads. - ConnectionSaved, + // Filter schemas…, which the sidebar opens on the saved connection. + EditSchemaFilter, } // The table the active tab shows. Its row is marked. @@ -144,6 +146,7 @@ pub struct SchemaTree { connection: Option, // A MySQL or ClickHouse database picked from the Databases list: only its row shows. only_schema: Option, + schema_matcher: SchemaMatcher, search: Entity, needle: String, // Keyed `connection:schema` and `connection:schema:table`, and persisted. @@ -195,6 +198,7 @@ impl SchemaTree { Self { connection: None, only_schema: None, + schema_matcher: SchemaMatcher::default(), search, needle: String::new(), expanded_schemas: setting_json(cx, SCHEMA_EXPANDED_KEY), @@ -219,8 +223,7 @@ impl SchemaTree { pub fn set_connection(&mut self, connection: Option, cx: &mut Context) { let same = self.connection.as_ref().map(|c| &c.id) == connection.as_ref().map(|c| &c.id); - let filter = |c: &Option| c.as_ref().map(|c| c.schema_filter.clone()); - let refiltered = filter(&self.connection) != filter(&connection); + let refiltered = self.schema_matcher.set(connection.as_ref().map(|c| &c.schema_filter)); self.only_schema = connection .as_ref() .filter(|c| c.shows_all_databases()) @@ -231,6 +234,11 @@ impl SchemaTree { self.error = None; self.connecting = false; } + // The cache's error may come from a schema the filter now hides; schema_changed puts it back if not. + let cached = self.connection.as_ref().and_then(|c| schema::get(cx, &c.id)).and_then(|d| d.error()); + if refiltered && self.error.as_deref() == cached { + self.error = None; + } // A live connection loads its schema on first view, even if it connected after the tree showed it. if let Some(conn) = self.connection.clone().filter(|c| state::bar(cx).is_connected(&c.id)) { self.load(&conn, false, cx); @@ -240,12 +248,32 @@ impl SchemaTree { } } - // The schemas the tree lists: the connection's filter keeps them, and a picked MySQL or ClickHouse database - // lists only its own. - fn keeps(&self) -> impl Fn(&str) -> bool + use<> { - let filter = self.connection.as_ref().map(|c| schema_filter_dialog::keeps(&c.schema_filter)); - let only = self.only_schema.clone(); - move |name| filter.as_ref().is_none_or(|keep| keep(name)) && only.as_ref().is_none_or(|only| only == name) + // A picked MySQL or ClickHouse database lists only its own, which the Databases list already filtered. + fn keeps(&self, name: &str) -> bool { + match &self.only_schema { + Some(only) => only == name, + None => self.schema_matcher.keeps(name), + } + } + + fn picked(&self, name: &str) -> bool { + self.only_schema.as_ref().is_none_or(|only| only == name) + } + + // Hidden by the filter rather than by a pick. + fn filtered(&self, name: &str) -> bool { + self.picked(name) && !self.keeps(name) + } + + // The filter, not a picked database the list lacks, hides every schema. + fn filtered_out(&self, cx: &App) -> bool { + // Any row means a schema is kept, which spares a scan of every schema on each frame. + if !self.rows.is_empty() { + return false; + } + let Some(conn) = self.connection.as_ref().filter(|c| c.schema_filter.enabled) else { return false }; + let Some(schemas) = schema::get(cx, &conn.id).and_then(|d| d.schemas()) else { return false }; + schemas.iter().any(|s| self.picked(&s.name)) && !schemas.iter().any(|s| self.keeps(&s.name)) } pub fn set_active_table(&mut self, table: Option, cx: &mut Context) { @@ -279,13 +307,18 @@ impl SchemaTree { } } - // Toolbar import, into the connection's first schema, or the one database shown. + // Toolbar import, into the first schema the tree lists, or the one database shown. pub fn import_default(&mut self, window: &mut Window, cx: &mut Context) { + let schema = self.import_schema(cx); + self.import(schema.unwrap_or_default(), None, window, cx); + } + + fn import_schema(&self, cx: &App) -> Option { let first = self.connection.as_ref().and_then(|c| { - schema::get(cx, &c.id).and_then(|d| d.schemas()).and_then(|s| s.first()).map(|s| s.name.clone()) + let schemas = schema::get(cx, &c.id).and_then(|d| d.schemas())?; + schemas.iter().find(|s| self.keeps(&s.name)).map(|s| s.name.clone()) }); - let schema = self.only_schema.clone().or(first); - self.import(schema.unwrap_or_default(), None, window, cx); + self.only_schema.clone().or(first) } // A finished import reloads the schema. @@ -352,8 +385,8 @@ impl SchemaTree { if let Some(conn) = self.connection.clone() && let Some(data) = schema::get(cx, &conn.id) { - if let Some(error) = data.error() { - self.error = Some(error.to_string()); + if let Some(error) = self.shown_error(data) { + self.error = Some(error); } if self.expand_on_load && data.schemas().is_some() && !data.loading() { self.expand_on_load = false; @@ -361,7 +394,7 @@ impl SchemaTree { .schemas() .unwrap_or_default() .iter() - .filter(|s| data.tables(&s.name).is_some()) + .filter(|s| data.tables(&s.name).is_some() && self.keeps(&s.name)) .map(|s| format!("{}:{}", conn.id, s.name)) .collect(); for key in loaded { @@ -374,17 +407,24 @@ impl SchemaTree { self.rebuild(cx); } + // A failed table load in a schema the filter hides isn't shown. + fn shown_error(&self, data: &ConnectionSchema) -> Option { + let error = data.error()?; + let mut failed = data.failed_schemas().peekable(); + let hidden = data.schemas().is_some() && failed.peek().is_some() && failed.all(|name| self.filtered(name)); + (!hidden).then(|| error.to_string()) + } + // Loads tables of open schemas and columns of open tables. A search loads every schema's tables, plus the // columns of tables whose names don't match. fn hydrate(&mut self, conn: &ConnectionConfig, cx: &mut Context) { let Some(data) = schema::get(cx, &conn.id) else { return }; let Some(schemas) = data.schemas() else { return }; let searching = !self.needle.is_empty(); - let keep = self.keeps(); let mut tables_to_load = Vec::new(); let mut columns_to_load = Vec::new(); let mut sizes_to_load = Vec::new(); - for sch in schemas.iter().filter(|s| keep(&s.name)) { + for sch in schemas.iter().filter(|s| self.keeps(&s.name)) { let key = format!("{}:{}", conn.id, sch.name); let open = self.expanded_schemas.get(&key) == Some(&true); let Some(tables) = data.tables(&sch.name) else { @@ -526,8 +566,7 @@ impl SchemaTree { let Some(data) = schema::get(cx, &conn.id) else { return rows }; let Some(schemas) = data.schemas() else { return rows }; let needle = self.needle.as_str(); - let keep = self.keeps(); - for sch in schemas.iter().filter(|s| keep(&s.name)) { + for sch in schemas.iter().filter(|s| self.keeps(&s.name)) { let key = format!("{}:{}", conn.id, sch.name); let all = data.tables(&sch.name).unwrap_or_default(); let loading = data.tables_loading(&sch.name); @@ -1260,13 +1299,22 @@ impl SchemaTree { self.rebuild(cx); } - // Includes tables hidden under a closed schema. - fn has_open(&self) -> bool { + // Includes tables hidden under a closed schema, but none in a schema the filter hides. + fn has_open(&self, cx: &App) -> bool { let Some(conn) = &self.connection else { return false }; let prefix = format!("{}:", conn.id); + let schemas = schema::get(cx, &conn.id).and_then(|d| d.schemas()).unwrap_or_default(); + let hidden: HashSet = + schemas.iter().filter(|s| self.filtered(&s.name)).map(|s| format!("{prefix}{}", s.name)).collect(); + // A schema's own key, or one of its tables' and groups' keys after a `:`. + let shown = |key: &str| { + key.starts_with(&prefix) + && !hidden.contains(key) + && !key.match_indices(':').any(|(at, _)| at >= prefix.len() && hidden.contains(&key[..at])) + }; let schemas_and_tables = self.expanded_schemas.iter().chain(&self.expanded_tables); - schemas_and_tables.filter(|(_, open)| **open).any(|(key, _)| key.starts_with(&prefix)) - || self.expanded_groups.iter().any(|key| key.starts_with(&prefix)) + schemas_and_tables.filter(|(_, open)| **open).any(|(key, _)| shown(key)) + || self.expanded_groups.iter().any(|key| shown(key)) } // With no cursor yet, Down starts at the top and Up at the bottom. @@ -1633,13 +1681,17 @@ impl SchemaTree { fn options_menu(&self, enabled: bool, cx: &mut Context) -> impl IntoElement + use<> { let this = cx.entity().downgrade(); - let (open, writable) = (self.has_open(), self.writable()); + let writable = self.writable(); let driver = self.connection.as_ref().map(|c| c.driver.clone()).unwrap_or_default(); let server_views = views(&driver, ViewScope::Server).next().is_some(); let filtered = self.connection.as_ref().is_some_and(|c| c.schema_filter.enabled); let button = form::options_button("schema-options", t(cx, "sidebar.schemaOptions")).disabled(!enabled); form::sidebar_menu(button, move |menu, window, cx| { let (collapse, import, views_for, filter) = (this.clone(), this.clone(), this.clone(), this.clone()); + let (open, hidden) = this.upgrade().map_or((false, false), |tree| { + let tree = tree.read(cx); + (tree.has_open(cx), tree.filtered_out(cx)) + }); let driver = driver.clone(); menu.item( PopupMenuItem::new(t(cx, "sidebar.collapseAll")) @@ -1653,7 +1705,7 @@ impl SchemaTree { .item( PopupMenuItem::new(t(cx, "sidebar.importData")) .icon(Icon::new(Lucide::Upload)) - .disabled(!writable) + .disabled(!writable || hidden) .on_click(move |_, window, cx| { let _ = import.update(cx, |tree, cx| tree.import_default(window, cx)); }), @@ -1662,8 +1714,8 @@ impl SchemaTree { PopupMenuItem::new(t(cx, "sidebar.filterSchemas")) .icon(Icon::new(Lucide::Funnel)) .checked(filtered) - .on_click(move |_, window, cx| { - let _ = filter.update(cx, |tree, cx| tree.edit_schema_filter(window, cx)); + .on_click(move |_, _, cx| { + let _ = filter.update(cx, |_, cx| cx.emit(SchemaTreeEvent::EditSchemaFilter)); }), ) .when(server_views, |menu| { @@ -1675,21 +1727,6 @@ impl SchemaTree { }) } - // Saved on the connection itself, for each of its databases. - fn edit_schema_filter(&mut self, window: &mut Window, cx: &mut Context) { - let Some(base) = self.connection.as_ref().map(|c| barsql_core::scope::base_id(&c.id).to_string()) else { - return; - }; - let Some(saved) = state::bar(cx).list_connections().into_iter().find(|c| c.id == base) else { return }; - let this = cx.entity().downgrade(); - schema_filter_dialog::open(saved, window, cx, move |_, cx| { - let _ = this.update(cx, |tree, cx| { - cx.emit(SchemaTreeEvent::ConnectionSaved); - tree.refresh(cx); - }); - }); - } - // A failed connect names the connection and offers Connect again, in place of the Not connected page. A schema // that failed to load keeps what the tree has under the card. fn error_card(&self, conn: &ConnectionConfig, connected: bool, cx: &mut Context) -> Option
{ @@ -1892,7 +1929,7 @@ impl Render for SchemaTree { let data = schema::get(cx, &conn.id); let loading = data.is_some_and(|d| d.loading()); let schemas_empty = data.and_then(|d| d.schemas()).is_some_and(<[_]>::is_empty); - let all_filtered = data.and_then(|d| d.schemas()).is_some() && self.rows.is_empty() && self.needle.is_empty(); + let all_filtered = self.filtered_out(cx); let connected = self.connected(cx); let body = if loading { form::loading_state(t(cx, "sidebar.loadingSchemasTables"), cx).into_any_element() @@ -1912,7 +1949,7 @@ impl Render for SchemaTree { } } else if schemas_empty && self.error.is_none() { self.message(None, t(cx, "sidebar.noSchemasRefresh"), cx).into_any_element() - } else if all_filtered && self.error.is_none() { + } else if all_filtered { self.message(Some(Lucide::Funnel), t(cx, "sidebar.schemasFiltered"), cx).into_any_element() } else if self.rows.is_empty() && !self.needle.is_empty() { self.message(None, t(cx, "sidebar.noMatches"), cx).into_any_element() @@ -1990,6 +2027,10 @@ impl SchemaTree { self.rows.is_empty() && !self.needle.is_empty() } + pub(crate) fn says_all_filtered(&self, cx: &App) -> bool { + self.filtered_out(cx) + } + #[cfg(feature = "e2e")] pub(crate) fn reveal(&mut self, id: &str, cx: &mut Context) { let connection = self.connection.as_ref(); diff --git a/crates/barsql-ui/src/schema_tree/tests.rs b/crates/barsql-ui/src/schema_tree/tests.rs index fa10de1..9f7aae3 100644 --- a/crates/barsql-ui/src/schema_tree/tests.rs +++ b/crates/barsql-ui/src/schema_tree/tests.rs @@ -254,21 +254,60 @@ fn searching_filters_tables_by_column_and_counts_them(cx: &mut TestAppContext) { } #[gpui_kit::test] -fn the_schema_filter_hides_schemas_until_it_is_switched_off(cx: &mut TestAppContext) { +fn only_a_filter_that_empties_the_tree_says_so(cx: &mut TestAppContext) { let env = Env::new(cx); let (tree, cx) = open(&env, cx); connect(&tree, cx); - let schema_filter = SchemaFilter { enabled: true, include: String::new(), exclude: "^MAIN$".into() }; - let filtered = ConnectionConfig { schema_filter, ..env.connection.clone() }; - tree.update(cx, |tree, cx| tree.set_connection(Some(filtered.clone()), cx)); + assert!(cx.update(|_, cx| tree.read(cx).has_open(cx)), "main opens as it loads"); + let excluding = |pattern: &str| ConnectionConfig { + schema_filter: SchemaFilter { enabled: true, exclude: pattern.into(), ..Default::default() }, + ..env.connection.clone() + }; + tree.update(cx, |tree, cx| tree.set_connection(Some(excluding("^MAIN$")), cx)); settle(cx, |cx| ids(&tree, cx).is_empty()); + tree.update(cx, |tree, cx| tree.set_needle("orders".into(), cx)); + cx.update(|_, cx| { + let tree = tree.read(cx); + assert!(tree.says_all_filtered(cx), "a search doesn't hide why the tree is empty"); + assert!(!tree.has_open(cx), "a hidden schema leaves Collapse all nothing to do"); + }); + tree.update(cx, |tree, cx| tree.set_needle(String::new(), cx)); + + // A picked MySQL database shows whatever the filter says, and one the list lacks isn't the filter's doing. + for (picked, shown) in [("main", true), ("unlisted", false)] { + tree.update(cx, |tree, cx| { + tree.only_schema = Some(picked.into()); + tree.rebuild(cx); + }); + assert_eq!(ids(&tree, cx).contains(&"s:main".to_string()), shown, "{picked}"); + assert!(!cx.update(|_, cx| tree.read(cx).says_all_filtered(cx)), "{picked}"); + } +} - let off = ConnectionConfig { - schema_filter: SchemaFilter { enabled: false, ..filtered.schema_filter.clone() }, - ..filtered +#[gpui_kit::test] +fn the_filter_takes_a_hidden_schemas_load_error_and_import_with_it(cx: &mut TestAppContext) { + let env = Env::new(cx); + let (tree, cx) = open(&env, cx); + connect(&tree, cx); + let id = env.connection.id.clone(); + cx.update(|_, cx| crate::schema::add_failed_schema(&id, "audit", cx)); + settle(cx, |cx| cx.update(|_, cx| tree.read(cx).error.is_some())); + let excluding = |pattern: &str| ConnectionConfig { + schema_filter: SchemaFilter { enabled: true, exclude: pattern.into(), ..Default::default() }, + ..env.connection.clone() }; - tree.update(cx, |tree, cx| tree.set_connection(Some(off), cx)); - settle(cx, has(&tree, "s:main")); + tree.update(cx, |tree, cx| tree.set_connection(Some(excluding("^audit$")), cx)); + cx.update(|_, cx| { + let tree = tree.read(cx); + assert_eq!(tree.error, None, "audit's failure goes with audit"); + assert_eq!(tree.import_schema(cx).as_deref(), Some("main")); + }); + tree.update(cx, |tree, cx| tree.set_connection(Some(excluding("^main$")), cx)); + cx.update(|_, cx| { + let tree = tree.read(cx); + assert!(tree.error.is_some(), "audit shows again, and so does its failure"); + assert_eq!(tree.import_schema(cx).as_deref(), Some("audit")); + }); } #[gpui_kit::test] diff --git a/crates/barsql-ui/src/sidebar.rs b/crates/barsql-ui/src/sidebar.rs index 1ffd674..1ae00b2 100644 --- a/crates/barsql-ui/src/sidebar.rs +++ b/crates/barsql-ui/src/sidebar.rs @@ -22,6 +22,7 @@ use crate::i18n::t; use crate::saved_panel::{SavedEvent, SavedPanel}; use crate::schema; use crate::schema_actions::{Applied, Change}; +use crate::schema_filter_dialog; use crate::schema_tree::{ActiveTable, SchemaTree, SchemaTreeEvent, TableChange}; use crate::state; use crate::tokens::{DOT, ICON_SM, ICON_XS, RADIUS, STRIP, TEXT_BASE, TEXT_SM, TOP_BAR}; @@ -98,7 +99,7 @@ impl Sidebar { let saved = cx.new(|cx| SavedPanel::new(window, cx)); let history = cx.new(|cx| HistoryPanel::new(window, cx)); let subscriptions = vec![ - cx.subscribe(&schema_tree, |this, _, event: &SchemaTreeEvent, cx| { + cx.subscribe_in(&schema_tree, window, |this, _, event: &SchemaTreeEvent, window, cx| { let event = match event { SchemaTreeEvent::Insert(text) => SidebarEvent::Insert(text.clone()), SchemaTreeEvent::Connected(id) => { @@ -131,7 +132,7 @@ impl Sidebar { title: title.clone(), run: false, }, - SchemaTreeEvent::ConnectionSaved => return this.reload_connections(cx), + SchemaTreeEvent::EditSchemaFilter => return this.edit_schema_filter(window, cx), SchemaTreeEvent::TableChanged { connection_id, schema, table, change } => { SidebarEvent::TableChanged { connection_id: connection_id.clone(), @@ -379,6 +380,15 @@ impl Sidebar { }) } + // Saved on the connection itself, for each of its databases. + fn edit_schema_filter(&mut self, window: &mut Window, cx: &mut Context) { + let Some(base) = self.selected_base().cloned() else { return }; + let this = cx.entity().downgrade(); + schema_filter_dialog::open(base, window, cx, move |_, cx| { + let _ = this.update(cx, |sidebar, cx| sidebar.reload_connections(cx)); + }); + } + // SQLite files opened from the OS or dropped on the window become a prefilled new connection. pub fn open_sqlite(&mut self, file_path: String, name: String, window: &mut Window, cx: &mut Context) { let config = ConnectionConfig { diff --git a/guide/schema.md b/guide/schema.md index 91c785a..a7ec849 100644 --- a/guide/schema.md +++ b/guide/schema.md @@ -7,7 +7,7 @@ - Tables show their size on disk from the catalog's own figures (PostgreSQL, MySQL / MariaDB, SQL Server and ClickHouse): PostgreSQL's and MySQL 8's are estimates as of their last statistics update, which MySQL 8 caches for up to a day, and **Refresh** reads them again - Columns show an icon for their type, and gold primary-key and blue foreign-key icons, as the grid and ER diagram do. Hover one for its full type, foreign-key target, default, whether it's generated, and the values an enum allows - Search tables and columns instantly, with the matches highlighted -- **Filter schemas…** in the tree's options menu hides schemas by name, with an include and an exclude regex. They ignore case and match anywhere in the name unless anchored, `|` means or (`^test.*|-\d$`), an empty include keeps every schema, and exclude wins. The filter is saved with the connection, for all its databases, and switching it off keeps the patterns +- **Filter schemas…** in the tree's options menu hides schemas by name with include and exclude regexes, saved with the connection. On MySQL / MariaDB and ClickHouse it filters the database lists too - Arrow keys move through the tree, `→` / `←` expand and collapse, and `Enter` expands a row or inserts a column's name - **Click** a column to insert its name at the cursor - The 👁 button on a table (or **Browse data**) opens its rows in the grid, editable when it has a primary key