diff --git a/Cargo.lock b/Cargo.lock index 2e2ad32..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", 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 d788de6..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}; @@ -156,10 +157,84 @@ 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, } +// 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 { + #[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, + #[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)] #[serde(rename_all = "camelCase")] pub struct SshConfig { @@ -223,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 @@ -841,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 d039313..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, 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/locales/bg.json b/crates/barsql-ui/locales/bg.json index 81d147e..e7bd05d 100644 --- a/crates/barsql-ui/locales/bg.json +++ b/crates/barsql-ui/locales/bg.json @@ -229,7 +229,9 @@ "pickSharedFolder": "Избери папка със SQL файлове", "openFolder": "Отвори папката", "removeFromConnection": "Премахни от тази връзка", - "moveQueryTo": "Премести в" + "moveQueryTo": "Премести в", + "filterSchemas": "Филтриране на схемите…", + "schemasFiltered": "Филтърът скрива всички схеми" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -805,5 +807,14 @@ "saveTo": "Запази в", "saveToFile": "Създава {{file}}", "deleteSharedDescription": "Изтрий {{file}} от диска? Свързаните табове остават отворени, но вече не се синхронизират." + }, + "schemaFilter": { + "title": "Филтриране на схемите", + "enabled": "Използвай филтъра", + "include": "Включване (regex)", + "exclude": "Изключване (regex)", + "hint": "Без значение от регистъра, съвпадение навсякъде в името. „Изключване“ има предимство.", + "invalid": "Невалиден регулярен израз: {{error}}", + "spaces": "Интервалите в началото или края се броят" } } diff --git a/crates/barsql-ui/locales/de.json b/crates/barsql-ui/locales/de.json index 6d539b5..3f8cdef 100644 --- a/crates/barsql-ui/locales/de.json +++ b/crates/barsql-ui/locales/de.json @@ -229,7 +229,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 Filter blendet alle Schemas aus" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -806,5 +808,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": "Filter verwenden", + "include": "Einschließen (Regex)", + "exclude": "Ausschließen (Regex)", + "hint": "Ohne Beachtung der Groß-/Kleinschreibung, Treffer irgendwo im Namen. Ausschließen hat Vorrang.", + "invalid": "Kein gültiger Regex: {{error}}", + "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 b638f85..621191e 100644 --- a/crates/barsql-ui/locales/en.json +++ b/crates/barsql-ui/locales/en.json @@ -251,7 +251,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 filter hides every schema" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -835,5 +837,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": "Use the filter", + "include": "Include (regex)", + "exclude": "Exclude (regex)", + "hint": "Ignores case and matches anywhere in the name. Exclude wins.", + "invalid": "Not a valid regex: {{error}}", + "spaces": "Leading or trailing spaces count" } } diff --git a/crates/barsql-ui/locales/es.json b/crates/barsql-ui/locales/es.json index 9f8885d..fe4f015 100644 --- a/crates/barsql-ui/locales/es.json +++ b/crates/barsql-ui/locales/es.json @@ -229,7 +229,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 oculta todos los esquemas" }, "systemViews": { "tableTabTitle": "{{view}}: {{name}}", @@ -815,5 +817,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": "Usar el filtro", + "include": "Incluir (regex)", + "exclude": "Excluir (regex)", + "hint": "Sin distinguir mayúsculas, coincide en cualquier parte del nombre. Excluir tiene prioridad.", + "invalid": "Regex no válida: {{error}}", + "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/lib.rs b/crates/barsql-ui/src/lib.rs index 972f8bb..d55af26 100644 --- a/crates/barsql-ui/src/lib.rs +++ b/crates/barsql-ui/src/lib.rs @@ -46,6 +46,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/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 new file mode 100644 index 0000000..d804d2a --- /dev/null +++ b/crates/barsql-ui/src/schema_filter_dialog.rs @@ -0,0 +1,211 @@ +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::prelude::FluentBuilder as _; +use gpui_kit::*; + +use crate::form; +use crate::i18n::{t, t_with}; +use crate::modal::{self, Modal}; +use crate::state; + +type OnSaved = Rc; + +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, +} + +impl SchemaFilterForm { + fn filter(&self, cx: &App) -> SchemaFilter { + SchemaFilter { + enabled: self.enabled, + include: self.include.read(cx).value().to_string(), + exclude: self.exclude.read(cx).value().to_string(), + ..self.connection.schema_filter.clone() + } + } + + // 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() { + 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), + 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, + 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(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, 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()) + .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, 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( + Button::new("schema-filter-save") + .large() + .debug_selector(|| "schema-filter-save".into()) + .primary() + .label(t(cx, "common.save")) + .disabled(saving || !self.valid()) + .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 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![ + 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 + }) + }); + if enabled { + focus_later(&include, window, cx); + } +} + +// 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 eed5fa6..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, @@ -85,6 +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 }, + // Filter schemas…, which the sidebar opens on the saved connection. + EditSchemaFilter, } // The table the active tab shows. Its row is marked. @@ -142,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. @@ -193,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), @@ -217,6 +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 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()) @@ -227,15 +234,48 @@ 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); } - if !same { + if !same || refiltered { self.schema_changed(cx); } } + // 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) { if self.active_table != table { self.active_table = table; @@ -267,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. @@ -340,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; @@ -349,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 { @@ -362,6 +407,14 @@ 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) { @@ -371,7 +424,7 @@ impl SchemaTree { 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| 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 { @@ -513,7 +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(); - 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| 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); @@ -1246,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. @@ -1619,12 +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) = (this.clone(), this.clone(), this.clone()); + 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")) @@ -1638,11 +1705,19 @@ 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)); }), ) + .item( + PopupMenuItem::new(t(cx, "sidebar.filterSchemas")) + .icon(Icon::new(Lucide::Funnel)) + .checked(filtered) + .on_click(move |_, _, cx| { + let _ = filter.update(cx, |_, cx| cx.emit(SchemaTreeEvent::EditSchemaFilter)); + }), + ) .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| { @@ -1854,6 +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 = self.filtered_out(cx); let connected = self.connected(cx); let body = if loading { form::loading_state(t(cx, "sidebar.loadingSchemasTables"), cx).into_any_element() @@ -1873,6 +1949,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.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 { @@ -1949,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 a88aa5d..9f7aae3 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,63 @@ fn searching_filters_tables_by_column_and_counts_them(cx: &mut TestAppContext) { settle(cx, |cx| ids(&tree, cx).is_empty()); } +#[gpui_kit::test] +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); + 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}"); + } +} + +#[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(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] 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 86e082c..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,6 +132,7 @@ impl Sidebar { title: title.clone(), run: false, }, + SchemaTreeEvent::EditSchemaFilter => return this.edit_schema_filter(window, cx), SchemaTreeEvent::TableChanged { connection_id, schema, table, change } => { SidebarEvent::TableChanged { connection_id: connection_id.clone(), @@ -378,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 9ac4717..a7ec849 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 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