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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/barsql-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
148 changes: 148 additions & 0 deletions crates/barsql-core/src/config.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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<String, Value>,
}

// 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<String, Value>,
}

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<String> {
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<Option<Regex>, 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<SchemaFilter>,
include: Option<Regex>,
exclude: Option<Regex>,
}

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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 })
);
}
}
4 changes: 3 additions & 1 deletion crates/barsql-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion crates/barsql-core/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '/';

Expand Down Expand Up @@ -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() {
Expand Down
13 changes: 12 additions & 1 deletion crates/barsql-ui/locales/bg.json
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,9 @@
"pickSharedFolder": "Избери папка със SQL файлове",
"openFolder": "Отвори папката",
"removeFromConnection": "Премахни от тази връзка",
"moveQueryTo": "Премести в"
"moveQueryTo": "Премести в",
"filterSchemas": "Филтриране на схемите…",
"schemasFiltered": "Филтърът скрива всички схеми"
},
"systemViews": {
"tableTabTitle": "{{view}}: {{name}}",
Expand Down Expand Up @@ -805,5 +807,14 @@
"saveTo": "Запази в",
"saveToFile": "Създава {{file}}",
"deleteSharedDescription": "Изтрий {{file}} от диска? Свързаните табове остават отворени, но вече не се синхронизират."
},
"schemaFilter": {
"title": "Филтриране на схемите",
"enabled": "Използвай филтъра",
"include": "Включване (regex)",
"exclude": "Изключване (regex)",
"hint": "Без значение от регистъра, съвпадение навсякъде в името. „Изключване“ има предимство.",
"invalid": "Невалиден регулярен израз: {{error}}",
"spaces": "Интервалите в началото или края се броят"
}
}
13 changes: 12 additions & 1 deletion crates/barsql-ui/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}}",
Expand Down Expand Up @@ -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"
}
}
13 changes: 12 additions & 1 deletion crates/barsql-ui/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}}",
Expand Down Expand Up @@ -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"
}
}
13 changes: 12 additions & 1 deletion crates/barsql-ui/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}}",
Expand Down Expand Up @@ -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"
}
}
Loading