diff --git a/Cargo.lock b/Cargo.lock index 143208cf07..0895ceb38c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6870,6 +6870,12 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.9" @@ -9133,6 +9139,7 @@ dependencies = [ "getrandom 0.4.3", "js-sys", "serde_core", + "sha1_smol", "wasm-bindgen", ] diff --git a/core/crates/storage/src/query_history/mod.rs b/core/crates/storage/src/query_history/mod.rs index 04615093a9..b03f8f2c9d 100644 --- a/core/crates/storage/src/query_history/mod.rs +++ b/core/crates/storage/src/query_history/mod.rs @@ -13,10 +13,12 @@ mod search_fold; mod status_filter; use std::path::{Path, PathBuf}; +use std::sync::Arc; use std::time::SystemTime; use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use sqlx::{AssertSqlSafe, ConnectOptions, Connection, Row, SqlitePool}; +use tokio::sync::watch; use uuid::Uuid; use crate::error::StorageError; @@ -63,6 +65,8 @@ pub(crate) enum Bind { pub struct QueryHistory { pool: SqlitePool, path: PathBuf, + // Shared by every handle `saved_queries` gives out, so a write through one reaches the others' followers. + saved_changes: Arc>, } impl QueryHistory { @@ -87,18 +91,19 @@ impl QueryHistory { crate::upgrade_copies::keep_database(&pool, &path, version).await?; } schema::migrate(&pool).await?; - Ok(Self { pool, path }) + Ok(Self { + pool, + path, + saved_changes: Arc::new(watch::channel(0).0), + }) } pub fn path(&self) -> &Path { &self.path } - /// The saved queries, which share this database. One file, one - /// migration chain, one open: what the user keeps and what they - /// ran are the same kind of thing in the same place. pub fn saved_queries(&self) -> crate::saved_queries::SavedQueries { - crate::saved_queries::SavedQueries::new(self.pool.clone(), self.path.clone()) + crate::saved_queries::SavedQueries::new(self.pool.clone(), self.path.clone(), self.saved_changes.clone()) } pub async fn record(&self, entry: NewEntry) -> Result { diff --git a/core/crates/storage/src/saved_queries/mod.rs b/core/crates/storage/src/saved_queries/mod.rs index 4a4a00737c..88dedfd222 100644 --- a/core/crates/storage/src/saved_queries/mod.rs +++ b/core/crates/storage/src/saved_queries/mod.rs @@ -1,9 +1,11 @@ mod new_saved_query; mod saved_query; +use std::sync::Arc; use std::time::SystemTime; -use sqlx::{Row, SqlitePool}; +use sqlx::{AssertSqlSafe, Connection, Row, SqlitePool}; +use tokio::sync::watch; use uuid::Uuid; use crate::error::StorageError; @@ -12,44 +14,38 @@ use crate::unix_time::{from_unix, to_unix}; pub use new_saved_query::NewSavedQuery; pub use saved_query::SavedQuery; -/// What a save did, so the caller can say which. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SaveOutcome { pub id: i64, - /// The name was already in use on this connection and its query - /// was overwritten. pub replaced: bool, } -/// The cap the query history puts on one entry, applied here too: a -/// saved query is the same kind of text and the same reasons apply. const MAX_QUERY_BYTES: usize = 1024 * 1024; -/// A name long enough to be unreadable in the list is a name nobody -/// meant to type. const MAX_NAME_CHARS: usize = 200; -/// The user's named queries. Cloning shares the pool with the query -/// history it lives beside. #[derive(Debug, Clone)] pub struct SavedQueries { pool: SqlitePool, // The database's file, whose upgrade copies a delete reaches too. path: std::path::PathBuf, + changes: Arc>, } impl SavedQueries { - pub(crate) fn new(pool: SqlitePool, path: std::path::PathBuf) -> Self { - Self { pool, path } + pub(crate) fn new(pool: SqlitePool, path: std::path::PathBuf, changes: Arc>) -> Self { + Self { pool, path, changes } + } + + pub fn changes(&self) -> watch::Receiver { + self.changes.subscribe() + } + + fn changed(&self) { + self.changes + .send_modify(|revision| *revision = revision.wrapping_add(1)); } - /// Keep `query` under its name, replacing whatever that name held - /// for this connection. - /// - /// Saving under a name already in use overwrites it, because that - /// is what the user is asking for: the same report, fixed. The - /// caller is expected to have confirmed the overwrite, which it - /// can see coming from `list`. pub async fn save(&self, query: NewSavedQuery) -> Result { let name = query.name.trim(); if name.is_empty() { @@ -68,14 +64,14 @@ impl SavedQueries { }); } let now = to_unix(SystemTime::now()); - // Asked before the write, because afterwards there is no way to - // tell an insert from an overwrite: only one connection is ever - // open on this pool, so nothing can slip in between. + // Hold the write lock across both statements, so concurrent saves agree on which inserted. + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; let replaced: bool = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM saved_queries WHERE connection_id = ? AND name = ?") .bind(query.connection_id.to_string()) .bind(name) - .fetch_one(&self.pool) + .fetch_one(&mut *transaction) .await? > 0; let id = sqlx::query( @@ -95,9 +91,11 @@ impl SavedQueries { .bind(&query.connection_name) .bind(now) .bind(now) - .fetch_one(&self.pool) + .fetch_one(&mut *transaction) .await? .try_get("id")?; + transaction.commit().await?; + self.changed(); Ok(SaveOutcome { id, replaced }) } @@ -137,15 +135,14 @@ impl SavedQueries { .bind(now) .fetch_optional(&self.pool) .await?; - Ok(match inserted { - Some(row) => Some(row.try_get("id")?), - None => None, - }) + let Some(row) = inserted else { + return Ok(None); + }; + let id = row.try_get("id")?; + self.changed(); + Ok(Some(id)) } - /// Everything saved against `connection`, or everything at all when - /// no connection is given. Ordered by name, because the user - /// looking for one knows what they called it. pub async fn list(&self, connection: Option) -> Result, StorageError> { let rows = match connection { Some(id) => { @@ -180,9 +177,6 @@ impl SavedQueries { row.map(row_to_saved_query).transpose() } - /// Give a saved query a different name. Fails when the connection - /// already has one under that name, which is the caller's cue to - /// say so rather than silently merge two queries into one. pub async fn rename(&self, id: i64, name: &str) -> Result<(), StorageError> { let name = name.trim(); if name.is_empty() { @@ -205,10 +199,11 @@ impl SavedQueries { _ => StorageError::Database(error), })? .rows_affected(); - match affected { - 0 => Err(StorageError::NotFound), - _ => Ok(()), + if affected == 0 { + return Err(StorageError::NotFound); } + self.changed(); + Ok(()) } pub async fn delete(&self, id: i64) -> Result<(), StorageError> { @@ -226,15 +221,13 @@ impl SavedQueries { .execute(&self.pool) .await? .rows_affected(); - match affected { - 0 => Err(StorageError::NotFound), - _ => Ok(()), + if affected == 0 { + return Err(StorageError::NotFound); } + self.changed(); + Ok(()) } - /// Drop everything saved against a connection, for when the - /// connection itself is removed. Its queries name tables only that - /// database has. pub async fn delete_for_connection(&self, connection: Uuid) -> Result { crate::query_history::trim_upgrade_copies( &self.path, @@ -250,6 +243,9 @@ impl SavedQueries { .execute(&self.pool) .await? .rows_affected(); + if affected > 0 { + self.changed(); + } Ok(affected as usize) } } @@ -356,6 +352,39 @@ mod tests { assert_eq!(all[0].query, "SELECT 2"); } + #[tokio::test] + async fn concurrent_new_saves_never_overwrite_the_winner() { + let root = tempfile::tempdir().expect("tempdir"); + let store = store(&root).await; + let connection = Uuid::new_v4(); + let (first, second) = tokio::join!( + store.save_if_new(new_query("daily", "SELECT 1", connection)), + store.save_if_new(new_query("daily", "SELECT 2", connection)), + ); + let first = first.expect("first save"); + let second = second.expect("second save"); + assert_ne!(first.is_some(), second.is_some()); + let saved = store.list(Some(connection)).await.expect("list"); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].query, if first.is_some() { "SELECT 1" } else { "SELECT 2" }); + } + + #[tokio::test] + async fn concurrent_saves_report_exactly_one_replacement_and_keep_the_id() { + let root = tempfile::tempdir().expect("tempdir"); + let store = store(&root).await; + let connection = Uuid::new_v4(); + let (first, second) = tokio::join!( + store.save(new_query("daily", "SELECT 1", connection)), + store.save(new_query("daily", "SELECT 2", connection)), + ); + let first = first.expect("first save"); + let second = second.expect("second save"); + assert_ne!(first.replaced, second.replaced); + assert_eq!(first.id, second.id); + assert_eq!(store.list(Some(connection)).await.expect("list").len(), 1); + } + #[tokio::test] async fn the_same_name_on_another_connection_is_another_query() { let root = tempfile::tempdir().expect("tempdir"); @@ -534,6 +563,67 @@ mod tests { assert_eq!(store.list(Some(staying)).await.expect("list").len(), 1); } + #[tokio::test] + async fn every_write_moves_the_revision_every_handle_follows() { + let root = tempfile::tempdir().expect("tempdir"); + let paths = StoragePaths::under(root.path(), "tablepro", "app.tablepro.TablePro"); + let history = QueryHistory::open(&paths).await.expect("open"); + let (writer, follower) = (history.saved_queries(), history.saved_queries()); + let mut changes = follower.changes(); + let connection = Uuid::new_v4(); + let mut moved = || { + let moved = changes.has_changed().expect("the sender lives"); + changes.mark_unchanged(); + moved + }; + + let saved = writer + .save(new_query("daily", "SELECT 1", connection)) + .await + .expect("save"); + assert!(moved(), "a save"); + writer + .save_if_new(new_query("weekly", "SELECT 2", connection)) + .await + .expect("save if new"); + assert!(moved(), "a save of a new name"); + writer.rename(saved.id, "nightly").await.expect("rename"); + assert!(moved(), "a rename"); + writer.delete(saved.id).await.expect("delete"); + assert!(moved(), "a delete"); + writer + .delete_for_connection(connection) + .await + .expect("delete for connection"); + assert!(moved(), "a connection's queries removed"); + } + + #[tokio::test] + async fn a_read_or_a_write_that_changed_nothing_leaves_the_revision() { + let root = tempfile::tempdir().expect("tempdir"); + let store = store(&root).await; + let connection = Uuid::new_v4(); + store + .save(new_query("daily", "SELECT 1", connection)) + .await + .expect("save"); + let changes = store.changes(); + + store.list(Some(connection)).await.expect("list"); + store + .save_if_new(new_query("daily", "SELECT 2", connection)) + .await + .expect("save if new"); + store.rename(404, "gone").await.expect_err("no such query"); + store.delete(404).await.expect_err("no such query"); + store + .delete_for_connection(Uuid::new_v4()) + .await + .expect("delete for a connection with none"); + + assert!(!changes.has_changed().expect("the sender lives")); + } + #[tokio::test] async fn a_save_carries_the_connections_current_name() { let root = tempfile::tempdir().expect("tempdir"); diff --git a/linux/about.toml b/linux/about.toml index 1e4cdb7d4a..eb8fb0dbb3 100644 --- a/linux/about.toml +++ b/linux/about.toml @@ -230,3 +230,10 @@ license = "Apache-2.0" [[sync_wrapper.clarify.files]] path = "LICENSE" checksum = "0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594" + +# cargo-about cannot identify the combined BSD and MIT license text. +[sha1_smol.clarify] +license = "BSD-3-Clause AND MIT" +[[sha1_smol.clarify.files]] +path = "LICENSE" +checksum = "282a21b0710441c364025461a447362daf18f5798a7b72ae2f801a2aa536da51" diff --git a/linux/build-aux/debian/copyright b/linux/build-aux/debian/copyright index 800d5c6bc2..ca9916a5d4 100644 --- a/linux/build-aux/debian/copyright +++ b/linux/build-aux/debian/copyright @@ -18754,6 +18754,72 @@ License: Apache-2.0 or Expat OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Files: vendor/sha1_smol-1.0.1/* +Copyright: 2018, the respective contributors, as shown by the AUTHORS file. + 2006-2009 Graydon Hoare + 2009-2013 Mozilla Foundation +License: BSD-3-Clause and Expat + BSD 3-Clause License + . + Copyright (c) 2018, the respective contributors, as shown by the AUTHORS file. + All rights reserved. + . + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + . + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + . + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + . + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + . + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + . + ----- + . + src/simd.rs is licensed under the MIT license: + . + Copyright (c) 2006-2009 Graydon Hoare + Copyright (c) 2009-2013 Mozilla Foundation + . + Permission is hereby granted, free of charge, to any + person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the + Software without restriction, including without + limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of + the Software, and to permit persons to whom the Software + is furnished to do so, subject to the following + conditions: + . + The above copyright notice and this permission notice + shall be included in all copies or substantial portions + of the Software. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF + ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT + SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + Files: vendor/sha3-0.12.0/* Copyright: 2020-2026 The RustCrypto Project Developers 2016-2023 Artyom Pavlov, Marek Kotewicz diff --git a/linux/changelog.d/4114.added.md b/linux/changelog.d/4114.added.md new file mode 100644 index 0000000000..0885e7d2fd --- /dev/null +++ b/linux/changelog.d/4114.added.md @@ -0,0 +1 @@ +The sidebar has a Favorites scope listing the saved queries of the connection in front. diff --git a/linux/crates/app/Cargo.toml b/linux/crates/app/Cargo.toml index 8a8fd21ecf..6600fedccc 100644 --- a/linux/crates/app/Cargo.toml +++ b/linux/crates/app/Cargo.toml @@ -100,7 +100,7 @@ tracing.workspace = true tracing-subscriber.workspace = true # Cells a value takes in the grid's monospace font. unicode-width.workspace = true -uuid.workspace = true +uuid = { workspace = true, features = ["v5"] } gettext-rs = { version = "0.8", features = ["gettext-system"] } # Counts grouped the way the user's locale groups digits. icu_decimal = { version = "2.3", features = ["alloc"] } diff --git a/linux/crates/app/src/services/saved_connection_editor.rs b/linux/crates/app/src/services/saved_connection_editor.rs index 9e057b1fb2..f2dab11097 100644 --- a/linux/crates/app/src/services/saved_connection_editor.rs +++ b/linux/crates/app/src/services/saved_connection_editor.rs @@ -262,24 +262,35 @@ impl SavedConnectionEditor { // A delete from another window purges a connection's queries once; any this import saves for // it afterwards are removed again here. - pub async fn save_imported_queries(&self, applied: &AppliedImport, store: &SavedQueries) -> QueryImportOutcome { + pub async fn save_imported_queries( + &self, + applied: &AppliedImport, + store: &SavedQueries, + ) -> Result { let outcome = save_queries(applied, store).await; - if let Ok(list) = self.list().await { - let mut gone: Vec = applied - .queries - .iter() - .map(|query| query.query.connection_id) - .filter(|id| !list.iter().any(|saved| saved.id == *id)) - .collect(); - gone.sort_unstable(); - gone.dedup(); - for id in gone { - if let Err(error) = store.delete_for_connection(id).await { - tracing::warn!(%error, "queries imported for a deleted connection are still saved"); - } + let list = self.list().await?; + let mut gone: Vec = applied + .queries + .iter() + .map(|query| query.query.connection_id) + .filter(|id| !list.iter().any(|saved| saved.id == *id)) + .collect(); + gone.sort_unstable(); + gone.dedup(); + let mut failure = None; + for &id in &gone { + if let Err(error) = store.delete_for_connection(id).await { + failure.get_or_insert(SavedConnectionError::Storage(error)); } } - outcome + if let Some(error) = failure { + return Err(error); + } + // Removed queries must not be reported as successfully imported. + if let Some(&id) = gone.first() { + return Err(SavedConnectionError::NotFound(id)); + } + Ok(outcome) } /// A pick of the group it is already in writes nothing. @@ -1454,4 +1465,100 @@ mod tests { assert_eq!(names, ["Prod", "Prod (Copy)", "Stage", "Test"]); assert_eq!(copy.order, 1); } + fn imported_query(id: Uuid) -> AppliedImport { + AppliedImport { + queries: vec![tablepro_foreign_import::review::ImportedQuery { + reference: "report".to_owned(), + query: tablepro_storage::saved_queries::NewSavedQuery { + name: "Report".to_owned(), + query: "SELECT 1".to_owned(), + connection_id: id, + connection_name: "Prod".to_owned(), + }, + }], + ..AppliedImport::default() + } + } + + async fn query_store(fixture: &Fixture) -> SavedQueries { + let paths = StoragePaths::under(fixture._root.path(), "tablepro-test", "app.tablepro.Test"); + tablepro_storage::QueryHistory::open(&paths) + .await + .expect("history") + .saved_queries() + } + + #[tokio::test] + async fn an_import_does_not_report_queries_removed_with_their_connection_as_added() { + let fixture = fixture().await; + let queries = query_store(&fixture).await; + let applied = imported_query(fixture.saved.id); + fixture + .store + .remove_blocking(fixture.saved.id) + .expect("connection removed"); + let result = fixture.editor.save_imported_queries(&applied, &queries).await; + assert!(matches!(result, Err(SavedConnectionError::NotFound(id)) if id == fixture.saved.id)); + assert!(queries.list(None).await.expect("queries").is_empty()); + } + + #[tokio::test] + async fn an_import_reports_a_connection_list_read_failure() { + let fixture = fixture().await; + let queries = query_store(&fixture).await; + let applied = imported_query(fixture.saved.id); + std::fs::remove_file(fixture.store.path()).expect("remove connection file"); + std::fs::create_dir(fixture.store.path()).expect("unreadable connection file"); + let paths = StoragePaths::under(fixture._root.path(), "tablepro-test", "app.tablepro.Test"); + let editor = SavedConnectionEditor::new(ConnectionStore::new(&paths), fixture.vault.clone(), paused_tasks()); + let result = editor.save_imported_queries(&applied, &queries).await; + assert!(matches!(result, Err(SavedConnectionError::Storage(_)))); + } + + #[tokio::test] + async fn an_import_reports_failure_to_remove_queries_of_a_deleted_connection() { + use tablepro_core::statement::{GuardedStatement, StatementBuilder}; + use tablepro_core::{ + CallOptions, ConnectEnvironment, ConnectOptions, ConnectTarget, DatabaseDriver, FileEndpoint, + ForeignKeyMode, TableRef, WorkspaceSettings, WriteBatch, WriteKind, + }; + use tokio_util::sync::CancellationToken; + + let fixture = fixture().await; + let queries = query_store(&fixture).await; + let paths = StoragePaths::under(fixture._root.path(), "tablepro-test", "app.tablepro.Test"); + let options = ConnectOptions { + target: ConnectTarget::File(FileEndpoint::open_existing(paths.history_database()).expect("history file")), + workspace_settings: WorkspaceSettings::workspace(false), + liveness: tablepro_core::LivenessPolicy::DESKTOP, + environment: ConnectEnvironment::new("test"), + }; + let mut trigger = StatementBuilder::new(); + trigger.push_sql("CREATE TRIGGER refuse_delete BEFORE DELETE ON saved_queries BEGIN SELECT RAISE(ABORT, 'test refuses delete'); END"); + let batch = WriteBatch::new( + WriteKind::SchemaChanges, + TableRef::unqualified("saved_queries"), + vec![GuardedStatement::unguarded(trigger.finish())], + ForeignKeyMode::Enforced, + ); + let connection = tablepro_driver_sqlite::SqliteDriver + .connect(options, CancellationToken::new()) + .await + .expect("connect"); + connection + .write_batch(&batch, CallOptions::new(None, CancellationToken::new())) + .await + .expect("trigger"); + connection.close().await.expect("close"); + fixture + .store + .remove_blocking(fixture.saved.id) + .expect("connection removed"); + let result = fixture + .editor + .save_imported_queries(&imported_query(fixture.saved.id), &queries) + .await; + assert!(matches!(result, Err(SavedConnectionError::Storage(_)))); + assert_eq!(queries.list(None).await.expect("queries").len(), 1); + } } diff --git a/linux/crates/app/src/ui/saved_queries_dialog/imp.rs b/linux/crates/app/src/ui/saved_queries_dialog/imp.rs index dfc972cb81..86e46f21e7 100644 --- a/linux/crates/app/src/ui/saved_queries_dialog/imp.rs +++ b/linux/crates/app/src/ui/saved_queries_dialog/imp.rs @@ -31,6 +31,7 @@ pub struct SavedQueriesDialog { pub retry_button: TemplateChild, pub(super) parts: OnceCell, + pub(super) changes: RefCell>, pub(super) snapshot: RefCell, pub(super) search_generation: Cell, pub(super) load_generation: Cell, @@ -54,6 +55,10 @@ impl ObjectSubclass for SavedQueriesDialog { } impl ObjectImpl for SavedQueriesDialog { + fn dispose(&self) { + self.changes.take(); + } + fn signals() -> &'static [Signal] { static SIGNALS: OnceLock> = OnceLock::new(); SIGNALS.get_or_init(|| { diff --git a/linux/crates/app/src/ui/saved_queries_dialog/mod.rs b/linux/crates/app/src/ui/saved_queries_dialog/mod.rs index e1b6a6eff8..404f3473c4 100644 --- a/linux/crates/app/src/ui/saved_queries_dialog/mod.rs +++ b/linux/crates/app/src/ui/saved_queries_dialog/mod.rs @@ -16,12 +16,12 @@ use gtk4::subclass::prelude::*; use gtk4::{gio, glib}; use libadwaita as adw; use libadwaita::prelude::*; -use tablepro_session::runtime::{TaskFailure, Tasks}; +use tablepro_session::runtime::{ProcessHold, TaskFailure, Tasks, WatchForwarder}; use tablepro_storage::{SavedQueries, StorageError}; use uuid::Uuid; use crate::i18n::{gettext, gettext_f}; -use crate::runtime::spawn_and_deliver; +use crate::runtime::{spawn_and_deliver, spawn_held}; use crate::ui::history_dialog::QueryDestination; use saved_query_listing::{Listing, matches}; use saved_query_object::SavedQueryObject; @@ -38,6 +38,7 @@ pub(crate) struct SavedQueriesDialogInit { // Its connection's queries are listed first. pub active_connection: Option, pub tasks: Tasks, + pub hold: Rc, } // What the last search matched. None shows every query. @@ -47,6 +48,8 @@ struct DialogParts { store: Option, active_connection: Option, tasks: Tasks, + hold: Rc, + selection: gtk::SingleSelection, items: gio::ListStore, matched: Matched, filter: gtk::CustomFilter, @@ -78,10 +81,18 @@ impl SavedQueriesDialog { let filtered = gtk::FilterListModel::new(Some(items.clone()), Some(filter.clone())); let sorted = gtk::SortListModel::new(Some(filtered), None::); sorted.set_section_sorter(Some(&by_group())); + let selection = gtk::SingleSelection::builder() + .model(&sorted) + .autoselect(false) + .can_unselect(true) + .build(); + let changes = init.store.as_ref().map(SavedQueries::changes); let _ = dialog.imp().parts.set(DialogParts { store: init.store, active_connection: init.active_connection, tasks: init.tasks, + hold: init.hold, + selection, items, matched, filter, @@ -89,8 +100,28 @@ impl SavedQueriesDialog { }); dialog.setup_list(); dialog.connect_controls(); - dialog.show_results(); - dialog.load(); + let loading = adw::StatusPage::builder() + .title(gettext("Loading Saved Queries")) + .paintable(&adw::SpinnerPaintable::new(Some(&dialog))) + .build(); + dialog.imp().stack.add_named(&loading, Some("loading")); + dialog.imp().stack.set_visible_child_name("loading"); + if let Some(changes) = changes { + let weak = dialog.downgrade(); + dialog.imp().changes.replace(Some(WatchForwarder::new( + changes, + move |_| { + if let Some(dialog) = weak.upgrade() { + dialog.load(); + } + }, + |future| { + glib::spawn_future_local(future); + }, + ))); + } else { + dialog.load_failed(); + } dialog } @@ -112,7 +143,7 @@ impl SavedQueriesDialog { return; }; let list_view = imp.list_view.get(); - list_view.set_model(Some(>k::NoSelection::new(Some(parts.sorted.clone())))); + list_view.set_model(Some(&parts.selection)); list_view.set_factory(Some(&self.row_factory())); list_view.set_header_factory(Some(&connection_header_factory())); let dialog = self.downgrade(); @@ -319,8 +350,6 @@ impl SavedQueriesDialog { self.change(StoreChange::Delete, move |store| async move { store.delete(id).await }); } - // The list is read again whether the change landed or not, so it - // shows what the store holds now. fn change(&self, change: StoreChange, work: impl FnOnce(SavedQueries) -> W + Send + 'static) where W: Future> + Send + 'static, @@ -331,31 +360,32 @@ impl SavedQueriesDialog { let Some(store) = parts.store.clone() else { return; }; + let (send, received) = tokio::sync::oneshot::channel(); + spawn_held(&parts.tasks, parts.hold.as_ref(), async move { + let _ = send.send(work(store).await); + }); let dialog = self.downgrade(); - drop(spawn_and_deliver( - &parts.tasks, - async move { work(store).await }, - move |done| { - let Some(dialog) = dialog.upgrade() else { - return; - }; - let failure = match done { - Ok(Ok(())) => None, - Ok(Err(error)) => { - tracing::warn!(%error, ?change, "a saved query change failed"); - Some(change.failure_text(Some(&error))) - } - Err(failure) => { - tracing::warn!(%failure, ?change, "a saved query change did not finish"); - Some(change.failure_text(None)) - } - }; - if let Some(message) = failure { - dialog.add_toast(&message); + glib::spawn_future_local(async move { + let done = received.await; + let Some(dialog) = dialog.upgrade() else { + return; + }; + let failure = match done { + Ok(Ok(())) => None, + Ok(Err(error)) => { + tracing::warn!(%error, ?change, "a saved query change failed"); + Some(change.failure_text(Some(&error))) } + Err(failure) => { + tracing::warn!(%failure, ?change, "a saved query change did not finish"); + Some(change.failure_text(None)) + } + }; + if let Some(message) = failure { + dialog.add_toast(&message); dialog.load(); - }, - )); + } + }); } fn load(&self) { @@ -402,6 +432,11 @@ impl SavedQueriesDialog { let Some(parts) = imp.parts.get() else { return; }; + let selected = parts + .selection + .selected_item() + .and_downcast::() + .and_then(|object| object.id()); let objects: Vec = listing .queries .into_iter() @@ -412,6 +447,19 @@ impl SavedQueriesDialog { imp.listed.set(true); // The ids the search matched may have changed with the list. self.search(); + if let Some(id) = selected { + let position = (0..parts.sorted.n_items()).find(|&position| { + parts + .sorted + .item(position) + .and_downcast::() + .and_then(|object| object.id()) + == Some(id) + }); + parts + .selection + .set_selected(position.unwrap_or(gtk::INVALID_LIST_POSITION)); + } self.show_results(); } @@ -475,8 +523,7 @@ impl SavedQueriesDialog { let Some(parts) = imp.parts.get() else { return; }; - // Only a read that lands takes the list off the error page. - if !imp.listed.get() && imp.stack.visible_child_name().as_deref() == Some("error") { + if !imp.listed.get() { return; } if parts.sorted.n_items() > 0 { diff --git a/linux/crates/app/src/ui/saved_queries_dialog/tests.rs b/linux/crates/app/src/ui/saved_queries_dialog/tests.rs index 74c27ce3d7..b883ce1e01 100644 --- a/linux/crates/app/src/ui/saved_queries_dialog/tests.rs +++ b/linux/crates/app/src/ui/saved_queries_dialog/tests.rs @@ -22,6 +22,7 @@ const WAIT: Duration = Duration::from_secs(30); struct Harness { runtime: AppRuntime, + hold: Rc, store: SavedQueries, root: tempfile::TempDir, } @@ -53,6 +54,7 @@ impl Harness { }); Self { runtime: test_runtime(), + hold: Rc::new(tablepro_session::runtime::CountingHold::new()), store, root, } @@ -63,6 +65,7 @@ impl Harness { store: Some(self.store.clone()), active_connection, tasks: self.runtime.tasks(), + hold: self.hold.clone(), }) } } @@ -335,6 +338,7 @@ fn deleting_a_query_takes_it_out_of_the_list() { let id = named(&dialog, "daily orders").id().expect("an id"); dialog.delete(id); + assert_eq!(harness.hold.live(), 1, "deletion holds the process"); wait_until(WAIT, || row_titles(&dialog) == ["stale carts"]).expect("the deleted query stayed in the list"); } @@ -347,6 +351,7 @@ fn renaming_a_query_lists_it_under_its_new_name() { let id = named(&dialog, "daily orders").id().expect("an id"); dialog.rename(id, "weekly orders".to_owned()); + assert_eq!(harness.hold.live(), 1, "rename holds the process"); wait_until(WAIT, || row_titles(&dialog) == ["weekly orders", "stale carts"]).expect("the new name"); } @@ -452,19 +457,19 @@ fn copying_a_query_says_so_inside_the_dialog() { } #[gtk4::test] -fn a_dialog_with_no_database_shows_the_empty_state_rather_than_failing() { +fn a_dialog_with_no_database_shows_an_error() { init(); let runtime = test_runtime(); let dialog = SavedQueriesDialog::new(SavedQueriesDialogInit { store: None, active_connection: None, tasks: runtime.tasks(), + hold: Rc::new(tablepro_session::runtime::CountingHold::new()), }); drain_main_context(); - assert_eq!(visible_page(&dialog).as_deref(), Some("empty")); - assert_eq!(dialog.imp().status_page.title(), "No Saved Queries"); + assert_eq!(visible_page(&dialog).as_deref(), Some("error")); assert!(row_titles(&dialog).is_empty()); } @@ -488,3 +493,101 @@ fn a_rename_failure_says_what_went_wrong() { fn every_row_menu_item_has_an_access_key_of_its_own() { assert_access_keys(&row_menu()); } + +#[gtk4::test] +fn a_change_keeps_the_process_until_it_lands_after_the_dialog_is_gone() { + let (harness, local, _) = seeded(); + let dialog = harness.dialog(Some(local)); + wait_until(WAIT, || row_titles(&dialog).len() == 2).expect("queries listed"); + let id = named(&dialog, "daily orders").id().expect("id"); + let (finish, finished) = tokio::sync::oneshot::channel(); + dialog.change(StoreChange::Rename, move |store| async move { + let _ = finished.await; + store.rename(id, "weekly orders").await + }); + assert_eq!(harness.hold.live(), 1); + drop(dialog); + drain_main_context(); + assert_eq!(harness.hold.live(), 1); + finish.send(()).expect("release write"); + wait_until(WAIT, || harness.hold.live() == 0).expect("write finished"); + let store = harness.store.clone(); + let read = harness.runtime.tasks().spawn_task(async move { store.get(id).await }); + let query = crate::test_support::finish_on_main(WAIT, read) + .expect("read finished") + .expect("task") + .expect("read") + .expect("query"); + assert_eq!(query.name, "weekly orders"); +} + +#[gtk4::test] +fn external_changes_reach_the_dialog_and_keep_selection_by_id() { + let (harness, local, _) = seeded(); + let dialog = harness.dialog(Some(local)); + wait_until(WAIT, || row_titles(&dialog).len() == 2).expect("queries listed"); + let id = named(&dialog, "daily orders").id().expect("id"); + dialog.imp().parts.get().expect("parts").selection.set_selected(0); + let store = harness.store.clone(); + let change = harness + .runtime + .tasks() + .spawn_task(async move { store.rename(id, "weekly orders").await }); + crate::test_support::finish_on_main(WAIT, change) + .expect("rename finished") + .expect("task") + .expect("rename"); + wait_until(WAIT, || row_titles(&dialog) == ["weekly orders", "stale carts"]).expect("external rename listed"); + let selected = dialog + .imp() + .parts + .get() + .expect("parts") + .selection + .selected_item() + .and_downcast::() + .and_then(|object| object.id()); + assert_eq!(selected, Some(id)); + let store = harness.store.clone(); + let change = harness + .runtime + .tasks() + .spawn_task(async move { store.delete(id).await }); + crate::test_support::finish_on_main(WAIT, change) + .expect("delete finished") + .expect("task") + .expect("delete"); + wait_until(WAIT, || row_titles(&dialog) == ["stale carts"]).expect("external deletion listed"); + assert!( + dialog + .imp() + .parts + .get() + .expect("parts") + .selection + .selected_item() + .is_none() + ); +} + +#[gtk4::test] +fn a_replaced_read_cannot_replace_the_current_list() { + let (harness, local, _) = seeded(); + let dialog = harness.dialog(Some(local)); + wait_until(WAIT, || row_titles(&dialog).len() == 2).expect("queries listed"); + let old = dialog.imp().load_generation.get(); + dialog.load(); + dialog.list_arrived(old, Ok(Ok(Listing::new(Vec::new(), Some(local))))); + assert_eq!(row_titles(&dialog).len(), 2); +} + +#[gtk4::test] +fn an_initial_read_never_claims_the_list_is_empty() { + let (harness, local, _) = seeded(); + let dialog = harness.dialog(Some(local)); + assert_eq!(visible_page(&dialog).as_deref(), Some("loading")); + dialog.apply_matches(Some(HashSet::new())); + assert_eq!(visible_page(&dialog).as_deref(), Some("loading")); + wait_until(WAIT, || row_titles(&dialog).len() == 2).expect("queries listed"); + assert_eq!(visible_page(&dialog).as_deref(), Some("list")); +} diff --git a/linux/crates/app/src/ui/session_window/import_from_app.rs b/linux/crates/app/src/ui/session_window/import_from_app.rs index 95d04e3d0d..a68fbaf1a3 100644 --- a/linux/crates/app/src/ui/session_window/import_from_app.rs +++ b/linux/crates/app/src/ui/session_window/import_from_app.rs @@ -67,7 +67,7 @@ impl SessionWindow { pub(super) fn imported_message( imported: &ImportedFromApp, - queries: Option, + queries: Option>, queries_available: bool, ) -> String { let connections = imported.applied.connections.len(); @@ -80,7 +80,7 @@ pub(super) fn imported_message( &[("n", &connections.to_string())], )); } - if let Some(queries) = queries { + if let Some(Ok(queries)) = &queries { if queries.added > 0 { parts.push(ngettext_f( "Added {n} saved query.", @@ -97,6 +97,14 @@ pub(super) fn imported_message( &[("n", &queries.failed.to_string())], )); } + } else if let Some(Err(error)) = queries { + tracing::warn!(%error, "saved query import could not finish"); + parts.push(match error { + SavedConnectionError::NotFound(_) => { + gettext("Saved query import was interrupted because a connection was deleted.") + } + _ => gettext("Saved query import could not finish. Some queries may have been saved."), + }); } else if !queries_available && !imported.applied.queries.is_empty() { parts.push(gettext( "Saved queries were not added: the query history is not available.", @@ -115,3 +123,34 @@ pub(super) fn imported_message( } parts.join(" ") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn query_cleanup_failures_are_visible_without_claiming_success() { + let imported = ImportedFromApp { + applied: Default::default(), + secrets_not_kept: 0, + }; + let message = imported_message( + &imported, + Some(Err(SavedConnectionError::Storage(StorageError::NotInitialised))), + true, + ); + assert_eq!( + message, + "Saved query import could not finish. Some queries may have been saved." + ); + let message = imported_message( + &imported, + Some(Err(SavedConnectionError::NotFound(uuid::Uuid::new_v4()))), + true, + ); + assert_eq!( + message, + "Saved query import was interrupted because a connection was deleted." + ); + } +} diff --git a/linux/crates/app/src/ui/session_window/resolve_file_identity.rs b/linux/crates/app/src/ui/session_window/resolve_file_identity.rs index 0f1315169d..3b32c21203 100644 --- a/linux/crates/app/src/ui/session_window/resolve_file_identity.rs +++ b/linux/crates/app/src/ui/session_window/resolve_file_identity.rs @@ -37,7 +37,8 @@ pub(crate) fn file_request( let endpoint = FileEndpoint::open_existing(path).map_err(DriverError::from)?; let mut request = ConnectRequest { metadata: ConnectionMetadata { - id: uuid::Uuid::new_v4(), + // Saved queries must remain attached when the same file is opened again. + id: uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, identity.uri.as_bytes()), name, driver_id: driver.id().to_owned(), }, @@ -100,6 +101,10 @@ mod tests { let request = file_request(&identity, &drivers, b"", false).expect("a request"); let read_only = file_request(&identity, &drivers, b"", true).expect("a read-only request"); + assert_eq!(request.metadata.id, read_only.metadata.id); + let other = FileIdentity::new(Some(PathBuf::from("/srv/other.db")), "file:///srv/other.db".to_owned()); + let other = file_request(&other, &drivers, b"", false).expect("other request"); + assert_ne!(request.metadata.id, other.metadata.id); assert_eq!(request.metadata.name, "app.db"); assert!(matches!(request.target, RequestTarget::File(_))); assert!(!request.workspace_settings.read_only); diff --git a/linux/crates/app/src/ui/workspace/imp.rs b/linux/crates/app/src/ui/workspace/imp.rs index 0b49c662f1..02cc65ce56 100644 --- a/linux/crates/app/src/ui/workspace/imp.rs +++ b/linux/crates/app/src/ui/workspace/imp.rs @@ -56,6 +56,8 @@ pub struct Workspace { pub(super) assistant_available: Cell, pub(super) key: OnceCell, + // File sessions and saved connections must use the editor save's identity. + pub(super) connection_id: OnceCell, pub(super) data_model: OnceCell, /// Which tab each of the session's pages shows, shared with the /// model, so the shell can tell whose a page is while the model is diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 6e4edd63b6..ca710b78be 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -546,6 +546,8 @@ pub(crate) enum WorkspaceInput { ShowHistory, ShowSavedQueries, ActiveTab(workspace_tabs::ActiveTabCommand), + ConfirmReplaceSavedQuery(tablepro_storage::saved_queries::NewSavedQuery), + ReplaceSavedQuery(tablepro_storage::saved_queries::NewSavedQuery), SaveQueryNamed { name: String, query: String, @@ -818,6 +820,7 @@ impl Workspace { let input = workspace.pump_inputs(); let _ = imp.sender.set(input.clone()); let _ = imp.key.set(key.clone()); + let _ = imp.connection_id.set(session.metadata().id); let context = session_slot(&context, &session); let storage = services.storage.clone(); let tasks = services.tasks.clone(); @@ -939,6 +942,10 @@ impl Workspace { self.imp().key.get().cloned() } + pub(crate) fn connection_id(&self) -> Option { + self.imp().connection_id.get().copied() + } + /// What the session's engine holds, which names the page with no /// tab open. pub(crate) fn data_model(&self) -> Option { @@ -1317,6 +1324,10 @@ impl WorkspaceModel { } } + #[expect( + clippy::too_many_lines, + reason = "Each workspace input dispatches to its own handler" + )] fn update(&mut self, msg: WorkspaceInput) { match msg { WorkspaceInput::HealthChanged(health) => self.refresh_health_banner(&health), @@ -1406,6 +1417,8 @@ impl WorkspaceModel { WorkspaceInput::ImportCsvRun(import) => self.on_import_csv_run(*import), WorkspaceInput::ActiveTab(command) => self.on_active_tab_command(command), WorkspaceInput::SaveQueryNamed { name, query } => self.on_save_query_named(name, query), + WorkspaceInput::ConfirmReplaceSavedQuery(query) => self.confirm_replace_saved_query(query), + WorkspaceInput::ReplaceSavedQuery(query) => self.save_named_query(query, true), WorkspaceInput::OpenHistoryQuery(text) => self.open_editor_tab(Some(text)), WorkspaceInput::ReplaceActiveTabQuery(text) => self.on_replace_active_tab_query(text), WorkspaceInput::RefreshPage => self.on_refresh_active_tab(), diff --git a/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs b/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs new file mode 100644 index 0000000000..6f7c41dbdf --- /dev/null +++ b/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs @@ -0,0 +1,270 @@ +use std::rc::Rc; + +use gtk4 as gtk; +use gtk4::prelude::*; +use gtk4::{gio, glib}; +use libadwaita as adw; +use tablepro_storage::saved_queries::SavedQuery; + +use crate::i18n::gettext; + +const LIST: &str = "list"; +const EMPTY: &str = "empty"; + +type Opened = Rc; + +#[derive(Clone)] +pub(crate) struct FavoritesPane { + stack: gtk::Stack, + store: gio::ListStore, + selection: gtk::SingleSelection, + error: adw::StatusPage, + retry: gtk::Button, + stale: adw::Banner, +} + +impl FavoritesPane { + pub(crate) fn new(opened: impl Fn(String) + 'static, retry: impl Fn() + 'static) -> Self { + let store = gio::ListStore::new::(); + let selection = gtk::SingleSelection::builder() + .model(&store) + .autoselect(false) + .can_unselect(true) + .build(); + let list = gtk::ListView::new(Some(selection.clone()), Some(factory())); + list.add_css_class("navigation-sidebar"); + list.set_single_click_activate(true); + list.update_property(&[gtk::accessible::Property::Label(&gettext("Favorites"))]); + let opened: Opened = Rc::new(opened); + let model = store.clone(); + list.connect_activate(move |_, position| { + if let Some(favorite) = favorite_at(&model, position) { + opened(favorite.query); + } + }); + let scrolled = gtk::ScrolledWindow::builder() + .hscrollbar_policy(gtk::PolicyType::Never) + .child(&list) + .build(); + let retry = Rc::new(retry); + let retry_button = gtk::Button::with_label(&gettext("Try Again")); + retry_button.set_halign(gtk::Align::Center); + retry_button.connect_clicked({ + let retry = retry.clone(); + move |_| retry() + }); + let error = adw::StatusPage::builder() + .title(gettext("Favorites Unavailable")) + .icon_name("dialog-warning-symbolic") + .child(&retry_button) + .build(); + error.add_css_class("compact"); + let stale = adw::Banner::builder() + .title(gettext("Favorites could not be refreshed.")) + .button_label(gettext("Try Again")) + .build(); + stale.connect_button_clicked(move |_| retry()); + let content = gtk::Box::new(gtk::Orientation::Vertical, 0); + content.append(&stale); + scrolled.set_vexpand(true); + content.append(&scrolled); + let empty = adw::StatusPage::builder() + .title(gettext("No Favorites")) + .icon_name("starred-symbolic") + .description(gettext("Save a query from the SQL editor to find it here.")) + .build(); + empty.add_css_class("compact"); + let stack = gtk::Stack::new(); + stack.add_named(&content, Some(LIST)); + stack.add_named(&error, Some("error")); + let loading = adw::StatusPage::builder() + .title(gettext("Loading Favorites")) + .child(&adw::Spinner::new()) + .build(); + loading.add_css_class("compact"); + stack.add_named(&loading, Some("loading")); + let disconnected = adw::StatusPage::builder() + .title(gettext("No Connection Selected")) + .description(gettext("Open a connection to see its saved queries.")) + .icon_name("starred-symbolic") + .build(); + disconnected.add_css_class("compact"); + stack.add_named(&disconnected, Some("disconnected")); + stack.add_named(&empty, Some(EMPTY)); + stack.set_visible_child_name(EMPTY); + Self { + stack, + store, + selection, + error, + retry: retry_button, + stale, + } + } + + pub(crate) fn widget(&self) -> gtk::Widget { + self.stack.clone().upcast() + } + + pub(crate) fn clear(&self) { + self.store.remove_all(); + self.stale.set_revealed(false); + } + + pub(crate) fn no_connection(&self) { + self.clear(); + self.stack.set_visible_child_name("disconnected"); + } + + pub(crate) fn loading(&self) { + self.stale.set_revealed(false); + if self.store.n_items() == 0 { + self.stack.set_visible_child_name("loading"); + } + } + + pub(crate) fn unavailable(&self) { + self.clear(); + self.error.set_description(Some(&gettext( + "The query history file could not be opened. Check the file and restart TablePro.", + ))); + self.retry.set_visible(false); + self.stack.set_visible_child_name("error"); + } + + pub(crate) fn failed(&self) { + if self.store.n_items() > 0 { + self.stale.set_revealed(true); + return; + } + self.error + .set_description(Some(&gettext("Saved queries could not be read. Try again."))); + self.retry.set_visible(true); + self.stack.set_visible_child_name("error"); + } + + pub(crate) fn show(&self, favorites: Vec) { + let selected = favorite_at(&self.store, self.selection.selected()).map(|saved| saved.id); + let selected_position = favorites.iter().position(|saved| Some(saved.id) == selected); + let items: Vec = favorites.into_iter().map(glib::BoxedAnyObject::new).collect(); + self.store.splice(0, self.store.n_items(), &items); + self.selection + .set_selected(selected_position.map_or(gtk::INVALID_LIST_POSITION, |position| position as u32)); + self.stale.set_revealed(false); + self.stack + .set_visible_child_name(if items.is_empty() { EMPTY } else { LIST }); + } + + #[cfg(test)] + pub(crate) fn names(&self) -> Vec { + (0..self.store.n_items()) + .filter_map(|position| favorite_at(&self.store, position)) + .map(|favorite| favorite.name) + .collect() + } +} + +fn favorite_at(store: &gio::ListStore, position: u32) -> Option { + let item = store.item(position).and_downcast::()?; + Some(item.borrow::().clone()) +} + +fn factory() -> gtk::SignalListItemFactory { + let factory = gtk::SignalListItemFactory::new(); + factory.connect_setup(|_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + let name = gtk::Label::builder() + .xalign(0.0) + .ellipsize(gtk::pango::EllipsizeMode::End) + .build(); + let summary = gtk::Label::builder() + .xalign(0.0) + .ellipsize(gtk::pango::EllipsizeMode::End) + .build(); + summary.add_css_class("caption"); + summary.add_css_class("dimmed"); + let row = gtk::Box::builder() + .orientation(gtk::Orientation::Vertical) + .spacing(2) + .margin_top(6) + .margin_bottom(6) + .build(); + row.append(&name); + row.append(&summary); + item.set_child(Some(&row)); + }); + factory.connect_bind(|_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + let (Some(object), Some(row)) = (item.item().and_downcast::(), item.child()) else { + return; + }; + let favorite = object.borrow::().clone(); + if let (Some(name), Some(summary)) = ( + row.first_child().and_downcast::(), + row.last_child().and_downcast::(), + ) { + name.set_label(&favorite.name); + summary.set_label(favorite.summary()); + } + item.set_accessible_label(&favorite.name); + }); + factory +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::SystemTime; + use uuid::Uuid; + + fn saved(id: i64, name: &str) -> SavedQuery { + SavedQuery { + id, + name: name.to_owned(), + query: "SELECT 1".to_owned(), + connection_id: Uuid::nil(), + connection_name: "Database".to_owned(), + created_at: SystemTime::UNIX_EPOCH, + updated_at: SystemTime::UNIX_EPOCH, + } + } + + #[gtk4::test] + fn favorites_keep_selection_by_id_after_rename_and_reorder() { + let pane = FavoritesPane::new(|_| {}, || {}); + pane.show(vec![saved(1, "One"), saved(2, "Two")]); + pane.selection.set_selected(1); + pane.show(vec![saved(2, "Renamed"), saved(1, "One")]); + assert_eq!(pane.selection.selected(), 0); + pane.show(vec![saved(1, "One")]); + assert_eq!(pane.selection.selected(), gtk::INVALID_LIST_POSITION); + } + + #[gtk4::test] + fn favorites_distinguish_loading_empty_unavailable_and_failed_refresh() { + let retried = Rc::new(std::cell::Cell::new(false)); + let retry = retried.clone(); + let pane = FavoritesPane::new(|_| {}, move || retry.set(true)); + pane.loading(); + assert_eq!(pane.stack.visible_child_name().as_deref(), Some("loading")); + pane.failed(); + assert_eq!(pane.stack.visible_child_name().as_deref(), Some("error")); + pane.retry.emit_clicked(); + assert!(retried.get()); + pane.show(vec![]); + assert_eq!(pane.stack.visible_child_name().as_deref(), Some(EMPTY)); + pane.show(vec![saved(1, "One")]); + pane.failed(); + assert!(pane.stale.is_revealed()); + assert_eq!(pane.names(), ["One"]); + pane.unavailable(); + assert!(!pane.retry.is_visible()); + assert!(pane.names().is_empty()); + pane.no_connection(); + assert_eq!(pane.stack.visible_child_name().as_deref(), Some("disconnected")); + } +} diff --git a/linux/crates/app/src/ui/workspace/sidebar/mod.rs b/linux/crates/app/src/ui/workspace/sidebar/mod.rs index 9c886343cf..92964f54ab 100644 --- a/linux/crates/app/src/ui/workspace/sidebar/mod.rs +++ b/linux/crates/app/src/ui/workspace/sidebar/mod.rs @@ -4,6 +4,7 @@ mod catalog_watch; mod connection_tree; +mod favorites_pane; mod key_listing; mod object_key; mod object_target; @@ -35,6 +36,7 @@ use tablepro_session::{ObjectListSnapshot, Session}; pub(super) use catalog_watch::{catalog_watch, reconnect_watch, spawn_local}; pub(crate) use connection_tree::{ConnectionTree, SessionRowState}; +pub(crate) use favorites_pane::FavoritesPane; pub(crate) use key_listing::{KeySidebar, KeysListed}; pub(super) use sidebar_affordances::SidebarAffordances; use sidebar_index::SidebarIndex; diff --git a/linux/crates/app/src/ui/workspace/status_pages.rs b/linux/crates/app/src/ui/workspace/status_pages.rs index ee669cee91..86cc7fc4d5 100644 --- a/linux/crates/app/src/ui/workspace/status_pages.rs +++ b/linux/crates/app/src/ui/workspace/status_pages.rs @@ -72,6 +72,7 @@ impl WorkspaceModel { store: self.history.store().map(|history| history.saved_queries()), active_connection: self.context.active.metadata().map(|metadata| metadata.id), tasks: self.tasks.clone(), + hold: self.context.hold.clone(), }); let input = self.input.clone(); dialog.connect_query_chosen(move |_, destination, text| { @@ -142,11 +143,40 @@ impl WorkspaceModel { return; }; let new_query = tablepro_storage::saved_queries::NewSavedQuery { - name: name.clone(), + name, query, connection_id: metadata.id, connection_name: metadata.name, }; + self.save_named_query(new_query, false); + } + + pub(super) fn confirm_replace_saved_query(&self, query: tablepro_storage::saved_queries::NewSavedQuery) { + let dialog = adw::AlertDialog::new( + Some(&crate::i18n::gettext_f( + "Replace “{name}”?", + &[("name", query.name.trim())], + )), + Some(&crate::i18n::gettext( + "A saved query already uses this name. Replacing it will overwrite its SQL.", + )), + ); + dialog.add_response("cancel", &crate::i18n::gettext("Cancel")); + dialog.add_response("replace", &crate::i18n::gettext("Replace")); + dialog.set_response_appearance("replace", adw::ResponseAppearance::Destructive); + dialog.set_default_response(Some("cancel")); + dialog.set_close_response("cancel"); + let input = self.input.clone(); + dialog.connect_response(None, move |_, response| { + if response == "replace" { + input.deliver(WorkspaceInput::ReplaceSavedQuery(query.clone())); + } + }); + dialog.present(self.dialog_parent().as_ref()); + } + + pub(super) fn save_named_query(&self, new_query: tablepro_storage::saved_queries::NewSavedQuery, replace: bool) { + let name = new_query.name.clone(); // The save lands even when the workspace is gone by then; only // its toast is dropped. A database still opening is waited for. let input = self.input.clone(); @@ -160,9 +190,21 @@ impl WorkspaceModel { }); return; }; - let message = match store.save(new_query).await { - Ok(outcome) if outcome.replaced => crate::i18n::gettext_f("Replaced “{name}”.", &[("name", &name)]), - Ok(_) => crate::i18n::gettext_f("Saved “{name}”.", &[("name", &name)]), + let saved = if replace { + store.save(new_query).await.map(|outcome| outcome.replaced) + } else { + match store.save_if_new(new_query.clone()).await { + Ok(Some(_)) => Ok(false), + Ok(None) => { + input.deliver(WorkspaceInput::ConfirmReplaceSavedQuery(new_query)); + return; + } + Err(error) => Err(error), + } + }; + let message = match saved { + Ok(true) => crate::i18n::gettext_f("Replaced “{name}”.", &[("name", &name)]), + Ok(false) => crate::i18n::gettext_f("Saved “{name}”.", &[("name", &name)]), Err(error) => { tracing::warn!(%error, "could not save the query"); crate::i18n::gettext("Could not save that query.") @@ -224,6 +266,95 @@ mod tests { ); } + #[gtk4::test] + fn replacing_a_saved_query_needs_confirmation_and_keeps_its_id() { + use crate::workspace::{answer, visible_alert}; + let test = TestWindow::connected("ConfirmSavedQuery"); + let availability = test.services.history().availability(); + wait_until(WAIT, || availability.borrow().is_ready()).expect("history ready"); + let save = |sql: &str| { + test.workspace() + .with_model(|model| model.on_save_query_named("Orders".to_owned(), sql.to_owned())); + wait_until(WAIT, || test.hold.live() == 0).expect("save complete"); + }; + let read = || { + let store = test.services.history().store().expect("history").saved_queries(); + let reading = test.services.tasks.spawn_task(async move { store.list(None).await }); + finish_on_main(WAIT, reading) + .expect("read complete") + .expect("task") + .expect("list") + .remove(0) + }; + save("SELECT 1"); + let original = read(); + save("SELECT 2"); + wait_until(WAIT, || visible_alert(&test.window).is_some()).expect("replace prompt"); + answer(&test.window, "cancel"); + assert_eq!(read().query, "SELECT 1"); + save("SELECT 3"); + wait_until(WAIT, || visible_alert(&test.window).is_some()).expect("replace prompt"); + answer(&test.window, "replace"); + wait_until(WAIT, || read().query == "SELECT 3").expect("replacement"); + assert_eq!(read().id, original.id); + } + + #[gtk4::test] + fn the_favorites_scope_lists_the_saved_queries_of_the_front_connection() { + use gtk4::subclass::prelude::ObjectSubclassIsExt; + let test = TestWindow::connected("FavoritesScope"); + let history = test.services.history(); + let availability = history.availability(); + wait_until(WAIT, || availability.borrow().is_ready()).expect("history ready"); + let shell = test.window.shell().expect("shell"); + let favorites = shell.imp().favorites.get().expect("favorites"); + shell.imp().scope_toggle.set_active_name(Some("favorites")); + test.workspace() + .with_model(|model| model.on_save_query_named("Orders".to_owned(), "SELECT 1".to_owned())); + wait_until(WAIT, || favorites.names() == ["Orders"]).expect("saved query listed"); + let store = history.store().expect("history").saved_queries(); + let work = test.services.tasks.spawn_task(async move { + let saved = store.list(None).await.expect("list"); + store.rename(saved[0].id, "Renamed").await.expect("rename"); + }); + finish_on_main(WAIT, work).expect("rename finished").expect("task"); + wait_until(WAIT, || favorites.names() == ["Renamed"]).expect("external rename listed"); + let store = history.store().expect("history").saved_queries(); + let work = test.services.tasks.spawn_task(async move { + let saved = store.list(None).await.expect("list"); + store.delete(saved[0].id).await.expect("delete"); + }); + finish_on_main(WAIT, work).expect("delete finished").expect("task"); + wait_until(WAIT, || favorites.names().is_empty()).expect("external deletion listed"); + } + + #[gtk4::test] + fn favorites_for_an_unsaved_file_survive_reopening_it() { + use gtk4::{gio, subclass::prelude::ObjectSubclassIsExt}; + let test = TestWindow::picker("FileFavorites"); + let root = tempfile::tempdir().expect("tempdir"); + let path = root.path().join("favorites.db"); + std::fs::write(&path, "").expect("database"); + let file = gio::File::for_path(path); + test.window.send(crate::ui::SessionWindowInput::OpenFile(file.clone())); + test.wait_for_page("workspace"); + let availability = test.services.history().availability(); + wait_until(WAIT, || availability.borrow().is_ready()).expect("history ready"); + let connection = test.workspace().connection_id(); + test.workspace() + .with_model(|model| model.on_save_query_named("File query".to_owned(), "SELECT 2".to_owned())); + wait_until(WAIT, || test.hold.live() == 0).expect("save finished"); + test.window.send(crate::ui::SessionWindowInput::Disconnect); + test.wait_for_page("picker"); + test.window.send(crate::ui::SessionWindowInput::OpenFile(file)); + test.wait_for_page("workspace"); + assert_eq!(test.workspace().connection_id(), connection); + let shell = test.window.shell().expect("shell"); + shell.imp().scope_toggle.set_active_name(Some("favorites")); + let favorites = shell.imp().favorites.get().expect("favorites"); + wait_until(WAIT, || favorites.names() == ["File query"]).expect("file query listed after reopen"); + } + #[gtk4::test] fn a_history_dialog_closed_by_hand_is_not_closed_again_on_disconnect() { use gtk4::glib; diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index 25eb2ae449..6fe5251925 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -28,9 +28,17 @@ use crate::ui::shell::{PRIMARY_MENU, TAB_OVERVIEW_MENU, app_menu, primary_menu_b /// names it. pub(super) const SHOW_SIDEBAR: &str = "show-sidebar"; +const TABLES: &str = "tables"; +const FAVORITES: &str = "favorites"; + /// The window action that shows and hides the assistant's column. pub(super) const SHOW_ASSISTANT: &str = "show-assistant"; +type FavoritesRead = Result< + Option, tablepro_storage::StorageError>>, + tablepro_session::runtime::TaskFailure, +>; + glib::wrapper! { pub struct WorkspaceShell(ObjectSubclass) @extends adw::Bin, gtk::Widget, @@ -86,7 +94,42 @@ impl WorkspaceShell { let imp = shell.imp(); imp.window.set(Some(window)); let tree = ConnectionTree::new(services.saved_connections.clone()); - imp.sidebar_slot.set_child(Some(&tree.widget())); + let sidebar = gtk::Stack::new(); + sidebar.add_named(&tree.widget(), Some(TABLES)); + let favorites = super::sidebar::FavoritesPane::new( + glib::clone!( + #[weak] + shell, + move |sql| shell.open_favorite(sql) + ), + glib::clone!( + #[weak] + shell, + move || shell.reload_favorites() + ), + ); + sidebar.add_named(&favorites.widget(), Some(FAVORITES)); + imp.sidebar_slot.set_child(Some(&sidebar)); + let _ = imp.sidebar_stack.set(sidebar); + let _ = imp.favorites.set(favorites); + let _ = imp.favorites_source.set((services.history(), services.tasks.clone())); + imp.favorites_availability + .replace(Some(tablepro_session::runtime::WatchForwarder::new( + services.history().availability(), + glib::clone!( + #[weak] + shell, + move |_| shell.follow_favorites() + ), + |future| { + glib::spawn_future_local(future); + }, + ))); + imp.scope_toggle.connect_active_name_notify(glib::clone!( + #[weak] + shell, + move |_| shell.on_scope_changed() + )); tree.follow_search(&imp.table_search); let _ = imp.tree.set(tree); crate::ui::picker::install_picker_actions(&shell, services.saved_connections.clone(), sender.clone()); @@ -532,8 +575,105 @@ impl WorkspaceShell { self.notify_front(); } - /// Show the front's banners and assistant, and name what follows its - /// data model after it. The expressions of `bind_front` do the rest. + fn on_scope_changed(&self) { + let imp = self.imp(); + let favorites = imp.scope_toggle.active_name().as_deref() == Some(FAVORITES); + if let Some(stack) = imp.sidebar_stack.get() { + stack.set_visible_child_name(if favorites { FAVORITES } else { TABLES }); + } + // The search reads connections and tables, which this scope does not list. + imp.table_search_toggle.set_visible(!favorites); + imp.refresh_tables_button.set_visible(!favorites); + if favorites { + imp.table_search_bar.set_search_mode(false); + imp.table_search_bar.set_key_capture_widget(None::<>k::Widget>); + } else { + imp.table_search_bar.set_key_capture_widget(Some(&*imp.sidebar_root)); + } + self.reload_favorites(); + } + + fn follow_favorites(&self) { + let imp = self.imp(); + if imp.favorites_watch.borrow().is_none() + && let Some((history, _)) = imp.favorites_source.get() + && let Some(history) = history.store() + { + imp.favorites_watch + .replace(Some(tablepro_session::runtime::WatchForwarder::new( + history.saved_queries().changes(), + glib::clone!( + #[weak(rename_to = shell)] + self, + move |_| shell.reload_favorites() + ), + |future| { + glib::spawn_future_local(future); + }, + ))); + } + self.reload_favorites(); + } + + pub(crate) fn reload_favorites(&self) { + let imp = self.imp(); + let generation = imp.favorites_generation.get().wrapping_add(1); + imp.favorites_generation.set(generation); + let connection = self.front().and_then(|front| front.connection_id()); + let (Some(pane), Some((history, tasks))) = (imp.favorites.get(), imp.favorites_source.get()) else { + return; + }; + if imp.favorites_connection.replace(connection) != connection { + pane.clear(); + } + if imp.scope_toggle.active_name().as_deref() != Some(FAVORITES) { + return; + } + let Some(connection) = connection else { + pane.no_connection(); + return; + }; + pane.loading(); + let ready = history.ready_store(); + crate::runtime::spawn_and_deliver( + tasks, + async move { + let history = ready.await?; + Some(history.saved_queries().list(Some(connection)).await) + }, + glib::clone!( + #[weak(rename_to = shell)] + self, + move |listed| shell.favorites_arrived(generation, connection, listed) + ), + ); + } + + fn favorites_arrived(&self, generation: u64, connection: Uuid, listed: FavoritesRead) { + if self.imp().favorites_generation.get() != generation + || self.front().and_then(|front| front.connection_id()) != Some(connection) + { + return; + } + let Some(pane) = self.imp().favorites.get() else { + return; + }; + match listed { + Ok(Some(Ok(favorites))) => pane.show(favorites), + Ok(None) => pane.unavailable(), + other => { + tracing::warn!(?other, "could not read favorites"); + pane.failed(); + } + } + } + + fn open_favorite(&self, sql: String) { + if let Some(sender) = self.front().and_then(|front| front.sender()) { + sender.deliver(super::WorkspaceInput::OpenHistoryQuery(sql)); + } + } + fn on_front_changed(&self) { let imp = self.imp(); if let Some(front) = self.front() { @@ -551,6 +691,7 @@ impl WorkspaceShell { } } self.describe_front(); + self.reload_favorites(); self.sync_assistant_column(); self.follow_front_for_new_tabs(); // A front with a tab selected says which row it shows itself. @@ -677,6 +818,10 @@ impl WorkspaceShell { /// names itself again from here on. pub(crate) fn shutdown(&self) { let imp = self.imp(); + imp.favorites_generation + .set(imp.favorites_generation.get().wrapping_add(1)); + imp.favorites_watch.take(); + imp.favorites_availability.take(); for watch in imp.watches.take() { watch.unwatch(); } @@ -805,6 +950,38 @@ mod tests { use crate::config::RESOURCE_BASE_PATH; use crate::test_support::assert_access_keys; + #[gtk4::test] + fn favorites_reject_old_reads_and_clear_rows_when_the_front_changes() { + use crate::ui::session_window::tests::TestWindow; + use tablepro_storage::saved_queries::SavedQuery; + let test = TestWindow::connected("FavoritesRequests"); + let shell = test.window.shell().expect("shell"); + shell.imp().scope_toggle.set_active_name(Some(FAVORITES)); + let connection = test.workspace().connection_id().expect("connection"); + let old = shell.imp().favorites_generation.get(); + shell.reload_favorites(); + let current = shell.imp().favorites_generation.get(); + let saved = SavedQuery { + id: 1, + name: "Current".to_owned(), + query: "SELECT 1".to_owned(), + connection_id: connection, + connection_name: "Database".to_owned(), + created_at: std::time::SystemTime::UNIX_EPOCH, + updated_at: std::time::SystemTime::UNIX_EPOCH, + }; + shell.favorites_arrived(current, connection, Ok(Some(Ok(vec![saved.clone()])))); + let pane = shell.imp().favorites.get().expect("pane"); + shell.favorites_arrived(old, connection, Ok(Some(Ok(vec![])))); + assert_eq!(pane.names(), ["Current"]); + shell.favorites_arrived(current, Uuid::new_v4(), Ok(Some(Ok(vec![])))); + assert_eq!(pane.names(), ["Current"]); + shell.set_front(None); + assert!(pane.names().is_empty()); + shell.favorites_arrived(current, connection, Ok(Some(Ok(vec![saved])))); + assert!(pane.names().is_empty()); + } + #[gtk4::test] fn the_tab_menu_and_the_main_menu_give_each_item_its_own_access_key() { crate::register_test_resources(); diff --git a/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs b/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs index 0b88179f47..f9bcdaad90 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell_imp.rs @@ -65,6 +65,8 @@ pub struct WorkspaceShell { #[template_child] pub sidebar_slot: TemplateChild, #[template_child] + pub scope_toggle: TemplateChild, + #[template_child] pub assistant_split: TemplateChild, #[template_child] pub assistant_stack: TemplateChild, @@ -114,6 +116,16 @@ pub struct WorkspaceShell { /// The saved connections, and the schemas and tables of each one open /// in the window. pub(super) tree: OnceCell, + pub(super) sidebar_stack: OnceCell, + pub(super) favorites: OnceCell, + pub(super) favorites_source: OnceCell<( + crate::services::history_service::HistoryService, + tablepro_session::runtime::Tasks, + )>, + pub(super) favorites_generation: Cell, + pub(super) favorites_connection: Cell>, + pub(super) favorites_watch: RefCell>, + pub(super) favorites_availability: RefCell>, /// The window the shell added its actions to. pub(super) window: glib::WeakRef, pub(super) sender: OnceCell>, diff --git a/linux/data/licenses/THIRD-PARTY-NOTICE.md b/linux/data/licenses/THIRD-PARTY-NOTICE.md index da91cefa2c..5388810773 100644 --- a/linux/data/licenses/THIRD-PARTY-NOTICE.md +++ b/linux/data/licenses/THIRD-PARTY-NOTICE.md @@ -2585,6 +2585,76 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI Used by: +- sha1_smol 1.0.1 + +~~~~text +BSD 3-Clause License + +Copyright (c) 2018, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----- + +src/simd.rs is licensed under the MIT license: + +Copyright (c) 2006-2009 Graydon Hoare +Copyright (c) 2009-2013 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +~~~~ + +### BSD 3-Clause "New" or "Revised" License + +Used by: + - subtle 2.6.1 ~~~~text @@ -4064,6 +4134,76 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI Used by: +- sha1_smol 1.0.1 + +~~~~text +BSD 3-Clause License + +Copyright (c) 2018, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----- + +src/simd.rs is licensed under the MIT license: + +Copyright (c) 2006-2009 Graydon Hoare +Copyright (c) 2009-2013 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +~~~~ + +### MIT License + +Used by: + - sqlx-core 0.9.0 - sqlx-macros-core 0.9.0 - sqlx-macros 0.9.0 diff --git a/linux/data/licenses/third-party.json b/linux/data/licenses/third-party.json index 62c678807d..cef205f7b9 100644 --- a/linux/data/licenses/third-party.json +++ b/linux/data/licenses/third-party.json @@ -108,6 +108,14 @@ { "crate": { "name": "aws-lc-sys", "version": "0.45.0" } } ] }, + { + "id": "BSD-3-Clause", + "name": "BSD 3-Clause \"New\" or \"Revised\" License", + "text": "BSD 3-Clause License\n\nCopyright (c) 2018, the respective contributors, as shown by the AUTHORS file.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n-----\n\nsrc/simd.rs is licensed under the MIT license:\n\nCopyright (c) 2006-2009 Graydon Hoare\nCopyright (c) 2009-2013 Mozilla Foundation\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n", + "used_by": [ + { "crate": { "name": "sha1_smol", "version": "1.0.1" } } + ] + }, { "id": "BSD-3-Clause", "name": "BSD 3-Clause \"New\" or \"Revised\" License", @@ -238,6 +246,14 @@ { "crate": { "name": "aws-lc-sys", "version": "0.45.0" } } ] }, + { + "id": "MIT", + "name": "MIT License", + "text": "BSD 3-Clause License\n\nCopyright (c) 2018, the respective contributors, as shown by the AUTHORS file.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n-----\n\nsrc/simd.rs is licensed under the MIT license:\n\nCopyright (c) 2006-2009 Graydon Hoare\nCopyright (c) 2009-2013 Mozilla Foundation\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n", + "used_by": [ + { "crate": { "name": "sha1_smol", "version": "1.0.1" } } + ] + }, { "id": "MIT", "name": "MIT License", @@ -3013,6 +3029,7 @@ { "name": "serde_with", "version": "3.23.0", "license": "MIT OR Apache-2.0" }, { "name": "serde_with_macros", "version": "3.23.0", "license": "MIT OR Apache-2.0" }, { "name": "sha1", "version": "0.11.0", "license": "MIT OR Apache-2.0" }, + { "name": "sha1_smol", "version": "1.0.1", "license": "BSD-3-Clause AND MIT" }, { "name": "sha2", "version": "0.10.9", "license": "MIT OR Apache-2.0" }, { "name": "sha2", "version": "0.11.0", "license": "MIT OR Apache-2.0" }, { "name": "sharded-slab", "version": "0.1.7", "license": "MIT" }, diff --git a/linux/data/resources/ui/workspace-shell.ui b/linux/data/resources/ui/workspace-shell.ui index 040ecb5aee..6f5948ee43 100644 --- a/linux/data/resources/ui/workspace-shell.ui +++ b/linux/data/resources/ui/workspace-shell.ui @@ -85,6 +85,28 @@ + + + tables + true + 12 + 12 + 6 + 6 + + + tables + Tables + + + + + favorites + Favorites + + + + diff --git a/linux/docs/storage.md b/linux/docs/storage.md index d21106bf82..3c9ab1f113 100644 --- a/linux/docs/storage.md +++ b/linux/docs/storage.md @@ -266,6 +266,27 @@ can tell whether a re-pinned entry falls in the pages already read. - `connections_with_history` lists each connection the history holds under the name of its latest run, so a renamed connection shows once. +### Following the saved queries + +`SavedQueries::changes` is a watch of a revision that every handle of one +database shares. A save, a save of a new name, a rename, a delete and a +connection's queries going move it on once they landed; a read, and a write +that changed nothing, leave it. The sidebar's Favorites and the Saved Queries +dialog read again on each revision, so a write from any window, an import or +a deleted connection reaches every list. Each list rejects replies from an +older read and keeps selection by saved-query id. Confirmed saves, renames +and deletions hold the process until the write finishes. + +The editor first inserts without replacement and asks for confirmation if the +name is taken. Confirmed replacement updates the same row id. The existence check +and write share a transaction, so simultaneous saves report which one +replaced the query. Renames update only the stored name and modification +time, leaving newer SQL and the connection identity intact. + +Unsaved database files use a UUID derived from their canonical URI, so queries +stay in the same scope after reopening the file. Queries saved by older builds +with a temporary file identity remain available in the Saved Queries dialog. + ### What goes into the history `HistoryService::record` is the one way in, for editor runs, saves and diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 23a2291ef9..3f0065ec44 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -621,6 +621,7 @@ crates/app/src/ui/workspace/saves.rs crates/app/src/ui/workspace/session_watches.rs crates/app/src/ui/workspace/sidebar/catalog_watch.rs crates/app/src/ui/workspace/sidebar/connection_tree.rs +crates/app/src/ui/workspace/sidebar/favorites_pane.rs crates/app/src/ui/workspace/sidebar/key_listing.rs crates/app/src/ui/workspace/sidebar/mod.rs crates/app/src/ui/workspace/sidebar/object_key.rs