From f02b24c727fb3e53fd4d0e74c879bab2616194fa Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 15:21:33 +0700 Subject: [PATCH 1/5] feat(core): whole-store reads and writes for the Mac's saved queries, favourites, table folders and history --- core/crates/ffi/src/favourites.rs | 4 +- core/crates/ffi/src/history.rs | 6 +- core/crates/ffi/src/host_stores.rs | 561 ++++++ core/crates/ffi/src/lib.rs | 7 + core/crates/ffi/src/saved_queries.rs | 6 +- core/crates/ffi/src/table_folders.rs | 4 +- core/crates/ffi/tests/host_stores.rs | 264 +++ core/crates/storage/src/favourites.rs | 5 + core/crates/storage/src/favourites_batch.rs | 436 +++++ core/crates/storage/src/lib.rs | 14 +- .../storage/src/query_history/host_entries.rs | 124 ++ .../src/query_history/host_entries_tests.rs | 76 + core/crates/storage/src/query_history/mod.rs | 1 + .../crates/storage/src/saved_queries/batch.rs | 280 +++ .../storage/src/saved_queries/batch_tests.rs | 205 ++ .../storage/src/saved_queries/deletion.rs | 4 +- core/crates/storage/src/saved_queries/mod.rs | 2 + .../crates/storage/src/table_folders/batch.rs | 372 ++++ core/crates/storage/src/table_folders/mod.rs | 3 + .../Generated/tablepro_ffi.cs | 1686 +++++++++++++++++ 20 files changed, 4045 insertions(+), 15 deletions(-) create mode 100644 core/crates/ffi/src/host_stores.rs create mode 100644 core/crates/ffi/tests/host_stores.rs create mode 100644 core/crates/storage/src/favourites_batch.rs create mode 100644 core/crates/storage/src/query_history/host_entries.rs create mode 100644 core/crates/storage/src/query_history/host_entries_tests.rs create mode 100644 core/crates/storage/src/saved_queries/batch.rs create mode 100644 core/crates/storage/src/saved_queries/batch_tests.rs create mode 100644 core/crates/storage/src/table_folders/batch.rs diff --git a/core/crates/ffi/src/favourites.rs b/core/crates/ffi/src/favourites.rs index 10ce2d26b8..68b7594845 100644 --- a/core/crates/ffi/src/favourites.rs +++ b/core/crates/ffi/src/favourites.rs @@ -11,8 +11,8 @@ use crate::runtime::on_runtime; // The tables and databases a user marked, per connection, in the query history's database (core ADR 0017). #[derive(uniffi::Object)] pub struct FavouriteStore { - favourites: Favourites, - tasks: Tasks, + pub(crate) favourites: Favourites, + pub(crate) tasks: Tasks, } // A table by its database and schema, None where the engine has neither. diff --git a/core/crates/ffi/src/history.rs b/core/crates/ffi/src/history.rs index 2f17ae0167..1719119562 100644 --- a/core/crates/ffi/src/history.rs +++ b/core/crates/ffi/src/history.rs @@ -22,8 +22,8 @@ use crate::table_folders::TableFolderStore; #[derive(uniffi::Object)] pub struct QueryHistoryStore { - history: QueryHistory, - tasks: Tasks, + pub(crate) history: QueryHistory, + pub(crate) tasks: Tasks, } // A run as the editor saw it end. Times are milliseconds from the Unix epoch; the store keeps whole seconds. @@ -320,7 +320,7 @@ impl From for Outcome { } // A time past what the clock holds lands on the epoch rather than panicking. -fn from_millis(millis: i64) -> SystemTime { +pub(crate) fn from_millis(millis: i64) -> SystemTime { from_epoch(Duration::from_millis(millis.unsigned_abs()), millis < 0) } diff --git a/core/crates/ffi/src/host_stores.rs b/core/crates/ffi/src/host_stores.rs new file mode 100644 index 0000000000..1d48cc5dac --- /dev/null +++ b/core/crates/ffi/src/host_stores.rs @@ -0,0 +1,561 @@ +// Whole-store reads and writes for a host that keeps a store of its own beside the core's while it moves in, each +// record under its own id (core ADR 0010, slices 3 and 9). A write names the digest it was based on where it +// replaces a whole store, so a change the host never read is refused rather than lost. + +use tablepro_storage::query_history::{NewEntry, Outcome}; +use tablepro_storage::saved_queries::SavedQuery; +use tablepro_storage::{ + DatabaseEnvironment, FavouriteDatabase, FavouriteDigests, FavouriteTable, FavouriteWrite, SavedQueryFolder, + SavedQuerySettlement, SavedQueryWrite, TableFolder, TableFolderItem, TableFolderWrite, TableRef, +}; + +use crate::error::CoreError; +use crate::favourites::{DatabaseEnvironmentTag, FavouriteStore}; +use crate::history::{HistoryOutcomeTag, QueryHistoryStore, from_millis, millis}; +use crate::library::{parse_id, parse_ids}; +use crate::runtime::on_runtime; +use crate::saved_queries::SavedQueryStore; +use crate::table_folders::{TableFolderRecord, TableFolderStore, TableRefRecord}; + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryRecord { + pub id: String, + pub name: String, + pub sql: String, + pub keyword: Option, + // None for a query in every connection. + pub connection_id: Option, + pub connection_name: String, + pub folder_id: Option, + pub order: i64, + pub created_at_ms: i64, + pub updated_at_ms: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryFolderRecord { + pub id: String, + pub name: String, + pub connection_id: Option, + pub parent_id: Option, + pub order: i64, + pub created_at_ms: i64, + pub updated_at_ms: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryStoreContents { + pub queries: Vec, + pub folders: Vec, + pub digest: String, +} + +// Removing a folder changes no other record; the write carries the queries and folders it moved. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryRecordWrite { + pub queries: Vec, + pub folders: Vec, + pub removed_queries: Vec, + pub removed_folders: Vec, +} + +// The ids whose name or keyword the store changed to settle a collision (core ADR 0052): edits of this device's own. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryWriteOutcome { + pub settled_queries: Vec, + pub settled_folders: Vec, + pub digest: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteTableRecord { + pub connection_id: String, + pub database: Option, + pub schema: Option, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteDatabaseRecord { + pub connection_id: String, + pub database: String, + pub environment: DatabaseEnvironmentTag, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteDatabaseKey { + pub connection_id: String, + pub database: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteStoreContents { + pub tables: Vec, + pub databases: Vec, + pub digests: FavouriteDigestsRecord, +} + +// One per kind, since a host may keep the tables and the databases in two stores. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteDigestsRecord { + pub tables: String, + pub databases: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteRecordWrite { + pub tables: Vec, + pub databases: Vec, + pub removed_tables: Vec, + pub removed_databases: Vec, +} + +// A table of any connection. An empty database or schema for an engine that has none. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TableKeyRecord { + pub connection_id: String, + pub table: TableRefRecord, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TablePlacementRecord { + pub connection_id: String, + pub table: TableRefRecord, + pub folder_id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TableFolderStoreContents { + pub folders: Vec, + pub items: Vec, + pub digest: String, +} + +// Removing a folder changes no item; the write names the items it takes out. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TableFolderRecordWrite { + pub folders: Vec, + pub items: Vec, + pub removed_folders: Vec, + pub removed_items: Vec, +} + +// A run another store kept, under its own record id. Times are milliseconds from the Unix epoch; the store keeps +// whole seconds. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct HistoryEntryRecord { + pub record_id: String, + pub sql: String, + pub driver_id: String, + pub connection_id: String, + pub connection_name: String, + pub executed_at_ms: i64, + pub duration_ms: Option, + pub rows_affected: Option, + pub outcome: HistoryOutcomeTag, +} + +#[uniffi::export] +impl SavedQueryStore { + // Every connection's queries and folders, in record id order. + pub async fn contents(&self) -> Result { + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { + let contents = queries.contents().await?; + Ok(SavedQueryStoreContents { + queries: contents.queries.into_iter().map(SavedQueryRecord::from).collect(), + folders: contents.folders.into_iter().map(SavedQueryFolderRecord::from).collect(), + digest: contents.digest, + }) + }) + .await + } + + // In one commit; each record keeps its id, times and place as given. + pub async fn write_records(&self, write: SavedQueryRecordWrite) -> Result { + let write = SavedQueryWrite { + queries: write + .queries + .into_iter() + .map(SavedQuery::try_from) + .collect::>()?, + folders: write + .folders + .into_iter() + .map(SavedQueryFolder::try_from) + .collect::>()?, + removed_queries: parse_ids(&write.removed_queries)?, + removed_folders: parse_ids(&write.removed_folders)?, + }; + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { Ok(queries.write(&write).await?.into()) }).await + } + + // The store comes to hold exactly these. Refused with storage.import_outdated, writing nothing, when + // `expected_digest` is not the digest of what the store holds; None replaces whatever it holds. + pub async fn replace_records( + &self, + expected_digest: Option, + queries: Vec, + folders: Vec, + ) -> Result { + let queries: Vec = queries + .into_iter() + .map(SavedQuery::try_from) + .collect::>()?; + let folders: Vec = folders + .into_iter() + .map(SavedQueryFolder::try_from) + .collect::>()?; + let store = self.queries.clone(); + on_runtime(&self.tasks, async move { + Ok(store + .replace(expected_digest.as_deref(), &queries, &folders) + .await? + .into()) + }) + .await + } +} + +#[uniffi::export] +impl FavouriteStore { + pub async fn contents(&self) -> Result { + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + let contents = favourites.contents().await?; + Ok(FavouriteStoreContents { + tables: contents.tables.into_iter().map(FavouriteTableRecord::from).collect(), + databases: contents + .databases + .into_iter() + .map(FavouriteDatabaseRecord::from) + .collect(), + digests: contents.digests.into(), + }) + }) + .await + } + + // In one commit. Returns the digests after it. + pub async fn write_records(&self, write: FavouriteRecordWrite) -> Result { + let write = FavouriteWrite { + tables: tables(write.tables)?, + databases: databases(write.databases)?, + removed_tables: tables(write.removed_tables)?, + removed_databases: write + .removed_databases + .into_iter() + .map(|key| Ok((parse_id(&key.connection_id)?, key.database))) + .collect::>()?, + }; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { Ok(favourites.write(&write).await?.into()) }).await + } + + // The store comes to hold exactly these tables; its databases stay. As `SavedQueryStore::replace_records`, against + // the tables' digest. + pub async fn replace_tables( + &self, + expected_digest: Option, + held: Vec, + ) -> Result { + let held = tables(held)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + Ok(favourites + .replace_tables(expected_digest.as_deref(), &held) + .await? + .into()) + }) + .await + } + + // As `replace_tables`, for the databases. + pub async fn replace_databases( + &self, + expected_digest: Option, + held: Vec, + ) -> Result { + let held = databases(held)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + Ok(favourites + .replace_databases(expected_digest.as_deref(), &held) + .await? + .into()) + }) + .await + } +} + +#[uniffi::export] +impl TableFolderStore { + pub async fn contents(&self) -> Result { + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { + let contents = folders.contents().await?; + Ok(TableFolderStoreContents { + folders: contents.folders.iter().map(TableFolderRecord::from).collect(), + items: contents.items.into_iter().map(TablePlacementRecord::from).collect(), + digest: contents.digest, + }) + }) + .await + } + + // In one commit. Returns the digest after it. + pub async fn write_records(&self, write: TableFolderRecordWrite) -> Result { + let write = TableFolderWrite { + folders: table_folders(write.folders)?, + items: placements(write.items)?, + removed_folders: parse_ids(&write.removed_folders)?, + removed_items: write + .removed_items + .into_iter() + .map(|key| table_ref(&key.connection_id, key.table)) + .collect::>()?, + }; + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { Ok(folders.write(&write).await?) }).await + } + + // As `SavedQueryStore::replace_records`. + pub async fn replace_records( + &self, + expected_digest: Option, + folders_held: Vec, + items_held: Vec, + ) -> Result { + let held_folders = table_folders(folders_held)?; + let held_items = placements(items_held)?; + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { + Ok(folders + .replace(expected_digest.as_deref(), &held_folders, &held_items) + .await?) + }) + .await + } +} + +#[uniffi::export] +impl QueryHistoryStore { + // In one commit. An entry the store already holds keeps its row. Returns how many were new. + pub async fn put_entries(&self, entries: Vec) -> Result { + let entries: Vec = entries.into_iter().map(NewEntry::try_from).collect::>()?; + let history = self.history.clone(); + on_runtime(&self.tasks, async move { Ok(history.put(&entries).await?) }).await + } + + // Every entry's record id, oldest row first. + pub async fn record_ids(&self) -> Result, CoreError> { + let history = self.history.clone(); + on_runtime(&self.tasks, async move { + Ok(history + .record_ids() + .await? + .into_iter() + .map(|id| id.to_string()) + .collect()) + }) + .await + } + + // By record id. Returns how many were there. + pub async fn remove_entries(&self, record_ids: Vec) -> Result { + let ids = parse_ids(&record_ids)?; + let history = self.history.clone(); + on_runtime(&self.tasks, async move { Ok(history.remove(&ids).await?) }).await + } +} + +impl From for SavedQueryRecord { + fn from(query: SavedQuery) -> Self { + Self { + id: query.id.to_string(), + name: query.name, + sql: query.query, + keyword: query.keyword, + connection_id: query.connection_id.map(|id| id.to_string()), + connection_name: query.connection_name, + folder_id: query.folder_id.map(|id| id.to_string()), + order: query.order, + created_at_ms: millis(query.created_at), + updated_at_ms: millis(query.updated_at), + } + } +} + +impl TryFrom for SavedQuery { + type Error = CoreError; + + fn try_from(record: SavedQueryRecord) -> Result { + Ok(Self { + id: parse_id(&record.id)?, + name: record.name, + query: record.sql, + keyword: record.keyword, + connection_id: record.connection_id.as_deref().map(parse_id).transpose()?, + connection_name: record.connection_name, + folder_id: record.folder_id.as_deref().map(parse_id).transpose()?, + order: record.order, + created_at: from_millis(record.created_at_ms), + updated_at: from_millis(record.updated_at_ms), + }) + } +} + +impl From for SavedQueryFolderRecord { + fn from(folder: SavedQueryFolder) -> Self { + Self { + id: folder.id.to_string(), + name: folder.name, + connection_id: folder.connection_id.map(|id| id.to_string()), + parent_id: folder.parent_id.map(|id| id.to_string()), + order: folder.order, + created_at_ms: millis(folder.created_at), + updated_at_ms: millis(folder.updated_at), + } + } +} + +impl TryFrom for SavedQueryFolder { + type Error = CoreError; + + fn try_from(record: SavedQueryFolderRecord) -> Result { + Ok(Self { + id: parse_id(&record.id)?, + connection_id: record.connection_id.as_deref().map(parse_id).transpose()?, + name: record.name, + parent_id: record.parent_id.as_deref().map(parse_id).transpose()?, + order: record.order, + created_at: from_millis(record.created_at_ms), + updated_at: from_millis(record.updated_at_ms), + }) + } +} + +impl From for SavedQueryWriteOutcome { + fn from(settlement: SavedQuerySettlement) -> Self { + Self { + settled_queries: settlement.queries.iter().map(ToString::to_string).collect(), + settled_folders: settlement.folders.iter().map(ToString::to_string).collect(), + digest: settlement.digest, + } + } +} + +impl From for FavouriteDigestsRecord { + fn from(digests: FavouriteDigests) -> Self { + Self { + tables: digests.tables, + databases: digests.databases, + } + } +} + +impl From for FavouriteTableRecord { + fn from(table: FavouriteTable) -> Self { + Self { + connection_id: table.connection_id.to_string(), + database: table.database, + schema: table.schema, + name: table.name, + } + } +} + +impl From for FavouriteDatabaseRecord { + fn from(database: FavouriteDatabase) -> Self { + Self { + connection_id: database.connection_id.to_string(), + database: database.database, + environment: database.environment.into(), + } + } +} + +fn tables(records: Vec) -> Result, CoreError> { + records + .into_iter() + .map(|record| { + Ok(FavouriteTable { + connection_id: parse_id(&record.connection_id)?, + database: record.database.filter(|database| !database.is_empty()), + schema: record.schema.filter(|schema| !schema.is_empty()), + name: record.name, + }) + }) + .collect() +} + +fn databases(records: Vec) -> Result, CoreError> { + records + .into_iter() + .map(|record| { + Ok(FavouriteDatabase { + connection_id: parse_id(&record.connection_id)?, + database: record.database, + environment: DatabaseEnvironment::from(record.environment), + }) + }) + .collect() +} + +impl From for TablePlacementRecord { + fn from(item: TableFolderItem) -> Self { + Self { + connection_id: item.table.connection_id.to_string(), + table: TableRefRecord { + database: item.table.database, + schema: item.table.schema, + name: item.table.name, + }, + folder_id: item.folder_id.to_string(), + } + } +} + +fn table_ref(connection_id: &str, table: TableRefRecord) -> Result { + Ok(TableRef { + connection_id: parse_id(connection_id)?, + database: table.database, + schema: table.schema, + name: table.name, + }) +} + +fn table_folders(records: Vec) -> Result, CoreError> { + records.into_iter().map(TableFolder::try_from).collect() +} + +fn placements(records: Vec) -> Result, CoreError> { + records + .into_iter() + .map(|record| { + Ok(TableFolderItem { + table: table_ref(&record.connection_id, record.table)?, + folder_id: parse_id(&record.folder_id)?, + }) + }) + .collect() +} + +impl TryFrom for NewEntry { + type Error = CoreError; + + fn try_from(record: HistoryEntryRecord) -> Result { + Ok(Self { + record_id: parse_id(&record.record_id)?, + query: record.sql, + driver_id: record.driver_id, + connection_id: parse_id(&record.connection_id)?, + connection_name: record.connection_name, + executed_at: from_millis(record.executed_at_ms), + duration_ms: record.duration_ms, + rows_affected: record.rows_affected, + outcome: Outcome::from(record.outcome), + }) + } +} diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 07f3aa017d..8fba5d8965 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -26,6 +26,7 @@ mod foreign_import; mod history; mod host; mod host_key; +mod host_stores; mod import; mod key_read; mod keymap; @@ -101,6 +102,12 @@ pub use history::{ QueryHistoryStore, }; pub use host::{HostConfig, HostSecretError, HostSecretStore, HostSecrets, SecretItemTag, SecretKindTag}; +pub use host_stores::{ + FavouriteDatabaseKey, FavouriteDatabaseRecord, FavouriteDigestsRecord, FavouriteRecordWrite, + FavouriteStoreContents, FavouriteTableRecord, HistoryEntryRecord, SavedQueryFolderRecord, SavedQueryRecord, + SavedQueryRecordWrite, SavedQueryStoreContents, SavedQueryWriteOutcome, TableFolderRecordWrite, + TableFolderStoreContents, TableKeyRecord, TablePlacementRecord, +}; pub use import::{ CsvDelimiterTag, CsvImport, CsvImportCheck, CsvImportOutcome, CsvPreview, CsvReadOptions, CsvRowFault, ImportColumnInfo, LineSpan, diff --git a/core/crates/ffi/src/saved_queries.rs b/core/crates/ffi/src/saved_queries.rs index 34f4d61db2..ff85d02e91 100644 --- a/core/crates/ffi/src/saved_queries.rs +++ b/core/crates/ffi/src/saved_queries.rs @@ -13,9 +13,9 @@ use crate::runtime::on_runtime; // named by its record id, UUID text. #[derive(uniffi::Object)] pub struct SavedQueryStore { - queries: SavedQueries, - folders: SavedQueryFolders, - tasks: Tasks, + pub(crate) queries: SavedQueries, + pub(crate) folders: SavedQueryFolders, + pub(crate) tasks: Tasks, } #[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] diff --git a/core/crates/ffi/src/table_folders.rs b/core/crates/ffi/src/table_folders.rs index 212ce1fd73..76523603e5 100644 --- a/core/crates/ffi/src/table_folders.rs +++ b/core/crates/ffi/src/table_folders.rs @@ -11,8 +11,8 @@ use crate::runtime::on_runtime; // history's database. A table sits in at most one folder. #[derive(uniffi::Object)] pub struct TableFolderStore { - folders: TableFolders, - tasks: Tasks, + pub(crate) folders: TableFolders, + pub(crate) tasks: Tasks, } // An empty database or schema for an engine that has none. diff --git a/core/crates/ffi/tests/host_stores.rs b/core/crates/ffi/tests/host_stores.rs new file mode 100644 index 0000000000..c8cba2c946 --- /dev/null +++ b/core/crates/ffi/tests/host_stores.rs @@ -0,0 +1,264 @@ +#![expect( + clippy::unwrap_used, + reason = "the setup helpers fail a test the way the test functions themselves do" +)] + +use std::path::Path; +use std::sync::Arc; + +use secrecy::SecretString; +use tablepro_ffi::{ + Core, DatabaseEnvironmentTag, FavouriteDatabaseKey, FavouriteDatabaseRecord, FavouriteRecordWrite, + FavouriteTableRecord, HistoryEntryRecord, HistoryOutcomeTag, HostConfig, HostSecretError, HostSecrets, + SavedQueryFolderRecord, SavedQueryRecord, SavedQueryRecordWrite, SecretItemTag, SecretKindTag, TableFolderRecord, + TableFolderRecordWrite, TableKeyRecord, TablePlacementRecord, TableRefRecord, +}; + +struct NoSecrets; + +impl HostSecrets for NoSecrets { + fn load(&self, _: String, _: SecretKindTag) -> Result, HostSecretError> { + Ok(None) + } + + fn store(&self, _: String, _: SecretKindTag, _: SecretString, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn relabel(&self, _: String, _: SecretKindTag, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete(&self, _: String, _: SecretKindTag) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete_connection(&self, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn load_item(&self, _: SecretItemTag) -> Result, HostSecretError> { + Ok(None) + } + + fn store_item(&self, _: SecretItemTag, _: SecretString) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete_item(&self, _: SecretItemTag) -> Result<(), HostSecretError> { + Ok(()) + } +} + +const SHOP: &str = "6F0B6A4E-3A52-4C2F-9D1E-0C6A2B7F9E11"; +const FOLDER: &str = "1C2D3E4F-5A6B-4C7D-8E9F-A0B1C2D3E4F5"; +const QUERY: &str = "9A8B7C6D-5E4F-4A3B-8C2D-1E0F9A8B7C6D"; +const RUN: &str = "0D1E2F3A-4B5C-4D6E-9F7A-8B9C0D1E2F3A"; + +fn started(dir: &Path) -> Arc { + Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: Some(dir.display().to_string()), + }, + Box::new(NoSecrets), + ) + .unwrap() +} + +fn saved_query(name: &str) -> SavedQueryRecord { + SavedQueryRecord { + id: QUERY.to_owned(), + name: name.to_owned(), + sql: "SELECT 1".to_owned(), + keyword: Some("one".to_owned()), + connection_id: Some(SHOP.to_owned()), + connection_name: "shop".to_owned(), + folder_id: Some(FOLDER.to_owned()), + order: 4, + created_at_ms: 1_700_000_000_123, + updated_at_ms: 1_700_000_000_456, + } +} + +#[tokio::test] +async fn a_mac_store_moves_in_with_its_ids_times_and_places() { + let dir = tempfile::tempdir().unwrap(); + let store = started(dir.path()).history().await.unwrap().saved_queries(); + let folder = SavedQueryFolderRecord { + id: FOLDER.to_owned(), + name: "Reports".to_owned(), + connection_id: None, + parent_id: None, + order: 1, + created_at_ms: 1_700_000_000_000, + updated_at_ms: 1_700_000_000_000, + }; + + let outcome = store + .replace_records(None, vec![saved_query("Daily")], vec![folder.clone()]) + .await + .unwrap(); + + let contents = store.contents().await.unwrap(); + assert!(outcome.settled_queries.is_empty()); + assert_eq!(outcome.digest, contents.digest); + let held = &contents.queries[0]; + assert_eq!(held.id.to_uppercase(), QUERY); + assert_eq!( + held.folder_id.as_deref().map(str::to_uppercase).as_deref(), + Some(FOLDER) + ); + assert_eq!( + (held.order, held.created_at_ms, held.updated_at_ms), + (4, 1_700_000_000_123, 1_700_000_000_456) + ); + assert_eq!(contents.folders[0].name, folder.name); +} + +#[tokio::test] +async fn a_write_based_on_an_older_read_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let store = started(dir.path()).history().await.unwrap().saved_queries(); + let read = store.contents().await.unwrap(); + store + .write_records(SavedQueryRecordWrite { + queries: vec![saved_query("Daily")], + folders: Vec::new(), + removed_queries: Vec::new(), + removed_folders: Vec::new(), + }) + .await + .unwrap(); + + let refused = store + .replace_records(Some(read.digest), Vec::new(), Vec::new()) + .await + .unwrap_err(); + + assert_eq!(refused.code(), "storage.import_outdated"); + assert_eq!(store.contents().await.unwrap().queries.len(), 1); +} + +#[tokio::test] +async fn favourites_and_table_folders_of_every_connection_read_and_write_whole() { + let dir = tempfile::tempdir().unwrap(); + let history = started(dir.path()).history().await.unwrap(); + let favourites = history.favourites(); + let table = FavouriteTableRecord { + connection_id: SHOP.to_owned(), + database: Some("shop".to_owned()), + schema: None, + name: "orders".to_owned(), + }; + favourites + .write_records(FavouriteRecordWrite { + tables: vec![table.clone()], + databases: vec![FavouriteDatabaseRecord { + connection_id: SHOP.to_owned(), + database: "shop".to_owned(), + environment: DatabaseEnvironmentTag::Production, + }], + removed_tables: Vec::new(), + removed_databases: Vec::new(), + }) + .await + .unwrap(); + favourites + .write_records(FavouriteRecordWrite { + tables: Vec::new(), + databases: Vec::new(), + removed_tables: Vec::new(), + removed_databases: vec![FavouriteDatabaseKey { + connection_id: SHOP.to_owned(), + database: "shop".to_owned(), + }], + }) + .await + .unwrap(); + let marked = favourites.contents().await.unwrap(); + assert_eq!(marked.tables.len(), 1); + assert_eq!(marked.tables[0].name, table.name); + assert!(marked.databases.is_empty()); + let stale = favourites + .replace_databases(Some(marked.digests.tables.clone()), Vec::new()) + .await + .unwrap_err(); + assert_eq!(stale.code(), "storage.import_outdated"); + let cleared = favourites + .replace_tables(Some(marked.digests.tables), Vec::new()) + .await + .unwrap(); + assert_eq!(cleared.databases, marked.digests.databases); + assert!(favourites.contents().await.unwrap().tables.is_empty()); + + let folders = history.table_folders(); + let reference = TableRefRecord { + database: "shop".to_owned(), + schema: String::new(), + name: "orders".to_owned(), + }; + folders + .write_records(TableFolderRecordWrite { + folders: vec![TableFolderRecord { + id: FOLDER.to_owned(), + connection_id: SHOP.to_owned(), + database: "shop".to_owned(), + schema: String::new(), + name: "Billing".to_owned(), + created_at_ms: 1_700_000_000_000, + updated_at_ms: 1_700_000_000_001, + }], + items: vec![TablePlacementRecord { + connection_id: SHOP.to_owned(), + table: reference.clone(), + folder_id: FOLDER.to_owned(), + }], + removed_folders: Vec::new(), + removed_items: Vec::new(), + }) + .await + .unwrap(); + let filed = folders.contents().await.unwrap(); + assert_eq!(filed.folders[0].updated_at_ms, 1_700_000_000_001); + assert_eq!(filed.items[0].table, reference); + folders + .write_records(TableFolderRecordWrite { + folders: Vec::new(), + items: Vec::new(), + removed_folders: vec![FOLDER.to_owned()], + removed_items: vec![TableKeyRecord { + connection_id: SHOP.to_owned(), + table: reference, + }], + }) + .await + .unwrap(); + let emptied = folders.contents().await.unwrap(); + assert!(emptied.folders.is_empty() && emptied.items.is_empty()); +} + +#[tokio::test] +async fn history_entries_move_in_under_their_record_ids() { + let dir = tempfile::tempdir().unwrap(); + let history = started(dir.path()).history().await.unwrap(); + let run = HistoryEntryRecord { + record_id: RUN.to_owned(), + sql: "SELECT 1".to_owned(), + driver_id: "MySQL".to_owned(), + connection_id: SHOP.to_owned(), + connection_name: "shop".to_owned(), + executed_at_ms: 1_700_000_000_000, + duration_ms: Some(5), + rows_affected: Some(1), + outcome: HistoryOutcomeTag::Succeeded, + }; + + let added = history.put_entries(vec![run.clone(), run]).await.unwrap(); + + assert_eq!(added, 1); + let ids = history.record_ids().await.unwrap(); + assert_eq!(ids.iter().map(|id| id.to_uppercase()).collect::>(), [RUN]); + assert_eq!(history.remove_entries(ids).await.unwrap(), 1); + assert!(history.record_ids().await.unwrap().is_empty()); +} diff --git a/core/crates/storage/src/favourites.rs b/core/crates/storage/src/favourites.rs index 66f7ea86e8..164d58761e 100644 --- a/core/crates/storage/src/favourites.rs +++ b/core/crates/storage/src/favourites.rs @@ -9,6 +9,11 @@ use crate::error::StorageError; use crate::journal::{JournalEntry, RecordKind, RecordRef, Signals}; use crate::unix_time::to_unix; +#[path = "favourites_batch.rs"] +mod batch; + +pub use batch::{FavouriteContents, FavouriteDigests, FavouriteWrite}; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DatabaseEnvironment { Development, diff --git a/core/crates/storage/src/favourites_batch.rs b/core/crates/storage/src/favourites_batch.rs new file mode 100644 index 0000000000..c07077150e --- /dev/null +++ b/core/crates/storage/src/favourites_batch.rs @@ -0,0 +1,436 @@ +// Writes a host makes whole: every favourite it holds, or the ones one of its edits marked and cleared. The Mac's +// store writes through these while it moves into the core (core ADR 0010, slice 9). + +use std::collections::HashSet; +use std::time::SystemTime; + +use sha2::{Digest, Sha256}; +use sqlx::{AssertSqlSafe, Connection, Row, SqliteConnection}; +use uuid::Uuid; + +use crate::StorageError; +use crate::journal::{JournalEntry, RecordKind, RecordRef}; +use crate::query_history::{Bind, CopyDelete, trim_upgrade_copies}; +use crate::unix_time::to_unix; + +use super::{DatabaseEnvironment, FavouriteDatabase, FavouriteTable, Favourites, database_record}; + +// Every connection's favourites, with a digest of each kind a later write can name to say what it was based on. Each +// kind has its own, since the Mac keeps the tables and the databases in two stores. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FavouriteContents { + pub tables: Vec, + pub databases: Vec, + pub digests: FavouriteDigests, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FavouriteDigests { + pub tables: String, + pub databases: String, +} + +// Favourites marked, databases filed under the environment given, and favourites cleared by their key. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FavouriteWrite { + pub tables: Vec, + pub databases: Vec, + pub removed_tables: Vec, + // A database by its connection and name. + pub removed_databases: Vec<(Uuid, String)>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + Tables, + Databases, +} + +impl Favourites { + pub async fn contents(&self) -> Result { + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin().await?; + let contents = read_contents(&mut transaction).await?; + transaction.commit().await?; + Ok(contents) + } + + // Returns the digests after the write. + pub async fn write(&self, write: &FavouriteWrite) -> Result { + self.commit(None, write).await + } + + // The store comes to hold exactly these tables, its databases untouched. Refused with `ImportOutdated`, writing + // nothing, when `expected` is not the digest of the tables the store holds. + pub async fn replace_tables( + &self, + expected: Option<&str>, + tables: &[FavouriteTable], + ) -> Result { + let write = FavouriteWrite { + tables: tables.to_vec(), + ..FavouriteWrite::default() + }; + self.commit(Some((Kind::Tables, expected)), &write).await + } + + // As `replace_tables`, for the databases. + pub async fn replace_databases( + &self, + expected: Option<&str>, + databases: &[FavouriteDatabase], + ) -> Result { + let write = FavouriteWrite { + databases: databases.to_vec(), + ..FavouriteWrite::default() + }; + self.commit(Some((Kind::Databases, expected)), &write).await + } + + async fn commit( + &self, + replace: Option<(Kind, Option<&str>)>, + write: &FavouriteWrite, + ) -> Result { + if write.tables.iter().any(|table| table.name.is_empty()) + || write.databases.iter().any(|database| database.database.is_empty()) + { + return Err(StorageError::EmptyName); + } + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; + let (removed_tables, removed_databases) = match replace { + Some((kind, expected)) => { + let held = read_contents(&mut transaction).await?; + let digest = match kind { + Kind::Tables => &held.digests.tables, + Kind::Databases => &held.digests.databases, + }; + if expected.is_some_and(|expected| expected != digest) { + return Err(StorageError::ImportOutdated); + } + match kind { + Kind::Tables => { + let kept: HashSet<(Uuid, String, String, String)> = write.tables.iter().map(key).collect(); + let gone = held.tables.into_iter().filter(|table| !kept.contains(&key(table))); + (gone.collect(), Vec::new()) + } + Kind::Databases => { + let kept: HashSet<(Uuid, &str)> = write + .databases + .iter() + .map(|database| (database.connection_id, database.database.as_str())) + .collect(); + let gone = held + .databases + .into_iter() + .filter(|database| !kept.contains(&(database.connection_id, database.database.as_str()))) + .map(|database| (database.connection_id, database.database)); + (Vec::new(), gone.collect()) + } + } + } + None => (write.removed_tables.clone(), write.removed_databases.clone()), + }; + trim_upgrade_copies(&self.path, ©_deletes(&removed_tables, &removed_databases)).await?; + let (gone_tables, gone_databases) = remove(&mut transaction, &removed_tables, &removed_databases).await?; + let (marked_tables, marked_databases) = mark(&mut transaction, write).await?; + let digests = read_contents(&mut transaction).await?.digests; + transaction.commit().await?; + let entries: Vec = [ + JournalEntry::new(RecordKind::FavouriteTable) + .wrote(marked_tables) + .deleted(gone_tables), + JournalEntry::new(RecordKind::FavouriteDatabase) + .wrote(marked_databases) + .deleted(gone_databases), + ] + .into_iter() + .filter(|entry| !entry.is_empty()) + .collect(); + if !entries.is_empty() { + self.signals.changed(&entries); + } + Ok(digests) + } +} + +type Changed = (Vec, Vec); + +async fn remove( + database: &mut SqliteConnection, + tables: &[FavouriteTable], + databases: &[(Uuid, String)], +) -> Result { + let mut gone_tables = Vec::new(); + for table in tables { + let removed = sqlx::query( + "DELETE FROM favourite_tables WHERE connection_id = ? AND database = ? AND schema = ? AND name = ?", + ) + .bind(table.connection_id.to_string()) + .bind(table.database.as_deref().unwrap_or_default()) + .bind(table.schema.as_deref().unwrap_or_default()) + .bind(&table.name) + .execute(&mut *database) + .await? + .rows_affected(); + if removed > 0 { + gone_tables.push(table.record()); + } + } + let mut gone_databases = Vec::new(); + for (connection_id, name) in databases { + let removed = sqlx::query("DELETE FROM favourite_databases WHERE connection_id = ? AND database = ?") + .bind(connection_id.to_string()) + .bind(name) + .execute(&mut *database) + .await? + .rows_affected(); + if removed > 0 { + gone_databases.push(database_record(*connection_id, name)); + } + } + Ok((gone_tables, gone_databases)) +} + +async fn mark(database: &mut SqliteConnection, write: &FavouriteWrite) -> Result { + let now = to_unix(SystemTime::now()); + let mut marked_tables = Vec::new(); + for table in &write.tables { + let added = sqlx::query( + "INSERT INTO favourite_tables (connection_id, database, schema, name, created_at) \ + VALUES (?, ?, ?, ?, ?) ON CONFLICT (connection_id, database, schema, name) DO NOTHING", + ) + .bind(table.connection_id.to_string()) + .bind(table.database.as_deref().unwrap_or_default()) + .bind(table.schema.as_deref().unwrap_or_default()) + .bind(&table.name) + .bind(now) + .execute(&mut *database) + .await? + .rows_affected(); + if added > 0 { + marked_tables.push(table.record()); + } + } + let mut marked_databases = Vec::new(); + for favourite in &write.databases { + let changed = sqlx::query( + "INSERT INTO favourite_databases (connection_id, database, environment, created_at) \ + VALUES (?, ?, ?, ?) \ + ON CONFLICT (connection_id, database) DO UPDATE SET environment = excluded.environment \ + WHERE favourite_databases.environment <> excluded.environment", + ) + .bind(favourite.connection_id.to_string()) + .bind(&favourite.database) + .bind(favourite.environment.as_str()) + .bind(now) + .execute(&mut *database) + .await? + .rows_affected(); + if changed > 0 { + marked_databases.push(database_record(favourite.connection_id, &favourite.database)); + } + } + Ok((marked_tables, marked_databases)) +} + +// As the table's primary key holds it: an absent database or schema is empty. +fn key(table: &FavouriteTable) -> (Uuid, String, String, String) { + ( + table.connection_id, + table.database.clone().unwrap_or_default(), + table.schema.clone().unwrap_or_default(), + table.name.clone(), + ) +} + +fn copy_deletes(tables: &[FavouriteTable], databases: &[(Uuid, String)]) -> Vec { + let tables = tables.iter().map(|table| CopyDelete { + table: "favourite_tables", + sql: "DELETE FROM main.favourite_tables WHERE connection_id = ? AND database = ? AND schema = ? AND name = ?" + .to_owned(), + binds: vec![ + Bind::Text(table.connection_id.to_string()), + Bind::Text(table.database.clone().unwrap_or_default()), + Bind::Text(table.schema.clone().unwrap_or_default()), + Bind::Text(table.name.clone()), + ], + }); + let databases = databases.iter().map(|(connection_id, database)| CopyDelete { + table: "favourite_databases", + sql: "DELETE FROM main.favourite_databases WHERE connection_id = ? AND database = ?".to_owned(), + binds: vec![Bind::Text(connection_id.to_string()), Bind::Text(database.clone())], + }); + tables.chain(databases).collect() +} + +async fn read_contents(database: &mut SqliteConnection) -> Result { + let tables = sqlx::query( + "SELECT connection_id, database, schema, name FROM favourite_tables \ + ORDER BY connection_id, database, schema, name", + ) + .fetch_all(&mut *database) + .await? + .into_iter() + .map(|row| { + let (database, schema): (String, String) = (row.try_get("database")?, row.try_get("schema")?); + Ok(FavouriteTable { + connection_id: uuid(&row.try_get::("connection_id")?)?, + database: Some(database).filter(|text| !text.is_empty()), + schema: Some(schema).filter(|text| !text.is_empty()), + name: row.try_get("name")?, + }) + }) + .collect::, StorageError>>()?; + let databases = sqlx::query( + "SELECT connection_id, database, environment FROM favourite_databases ORDER BY connection_id, database", + ) + .fetch_all(&mut *database) + .await? + .into_iter() + .map(|row| { + let environment: String = row.try_get("environment")?; + Ok(FavouriteDatabase { + connection_id: uuid(&row.try_get::("connection_id")?)?, + database: row.try_get("database")?, + environment: DatabaseEnvironment::parse(&environment) + .ok_or_else(|| StorageError::Schema(format!("unknown database environment: {environment}")))?, + }) + }) + .collect::, StorageError>>()?; + let digests = digests(&tables, &databases)?; + Ok(FavouriteContents { + tables, + databases, + digests, + }) +} + +fn uuid(text: &str) -> Result { + Uuid::parse_str(text).map_err(|_| StorageError::Schema("a favourite's connection_id is not a UUID".to_owned())) +} + +fn digests(tables: &[FavouriteTable], databases: &[FavouriteDatabase]) -> Result { + let tables: Vec<_> = tables.iter().map(key).collect(); + let databases: Vec<_> = databases + .iter() + .map(|database| { + ( + database.connection_id, + &database.database, + database.environment.as_str(), + ) + }) + .collect(); + Ok(FavouriteDigests { + tables: hex::encode(Sha256::digest(serde_json::to_vec(&tables)?)), + databases: hex::encode(Sha256::digest(serde_json::to_vec(&databases)?)), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{QueryHistory, StoragePaths}; + + async fn favourites(root: &tempfile::TempDir) -> Favourites { + QueryHistory::open(&StoragePaths::under(root.path(), "tablepro", "app.tablepro.TablePro")) + .await + .expect("open") + .favourites() + } + + fn table(connection_id: Uuid, schema: Option<&str>, name: &str) -> FavouriteTable { + FavouriteTable { + connection_id, + database: Some("shop".to_owned()), + schema: schema.map(str::to_owned), + name: name.to_owned(), + } + } + + #[tokio::test] + async fn a_write_marks_and_clears_by_key_across_connections() { + let root = tempfile::tempdir().expect("tempdir"); + let store = favourites(&root).await; + let (one, two) = (Uuid::new_v4(), Uuid::new_v4()); + let orders = table(one, Some("public"), "orders"); + let users = table(two, None, "users"); + let marked = FavouriteDatabase { + connection_id: two, + database: "shop".to_owned(), + environment: DatabaseEnvironment::Production, + }; + store + .write(&FavouriteWrite { + tables: vec![orders.clone(), users.clone()], + databases: vec![marked.clone()], + ..FavouriteWrite::default() + }) + .await + .expect("write"); + + let digests = store + .write(&FavouriteWrite { + removed_tables: vec![orders], + ..FavouriteWrite::default() + }) + .await + .expect("clear"); + + let contents = store.contents().await.expect("contents"); + assert_eq!(contents.tables, vec![users]); + assert_eq!(contents.databases, vec![marked]); + assert_eq!(contents.digests, digests); + } + + #[tokio::test] + async fn a_replace_of_tables_on_an_older_read_writes_nothing_and_a_current_one_keeps_the_databases() { + let root = tempfile::tempdir().expect("tempdir"); + let store = favourites(&root).await; + let connection = Uuid::new_v4(); + let first = table(connection, None, "first"); + let second = table(connection, None, "second"); + store + .write(&FavouriteWrite { + tables: vec![first.clone()], + ..FavouriteWrite::default() + }) + .await + .expect("write"); + let read = store.contents().await.expect("contents"); + store + .write(&FavouriteWrite { + tables: vec![second.clone()], + ..FavouriteWrite::default() + }) + .await + .expect("write"); + + let marked = FavouriteDatabase { + connection_id: connection, + database: "shop".to_owned(), + environment: DatabaseEnvironment::Testing, + }; + store + .write(&FavouriteWrite { + databases: vec![marked.clone()], + ..FavouriteWrite::default() + }) + .await + .expect("write a database"); + + let refused = store.replace_tables(Some(&read.digests.tables), &[]).await; + let current = store.contents().await.expect("contents").digests; + store + .replace_tables(Some(¤t.tables), std::slice::from_ref(&second)) + .await + .expect("replace"); + + assert!(matches!(refused, Err(StorageError::ImportOutdated))); + let contents = store.contents().await.expect("contents"); + assert_eq!(contents.tables, vec![second]); + assert_eq!(contents.databases, vec![marked]); + } +} diff --git a/core/crates/storage/src/lib.rs b/core/crates/storage/src/lib.rs index e87b8ced69..3bd16751d6 100644 --- a/core/crates/storage/src/lib.rs +++ b/core/crates/storage/src/lib.rs @@ -52,7 +52,10 @@ pub use credentials::{ pub use document_problem::{DocumentProblem, DocumentProblemKind}; pub use drafts::{DraftId, DraftScope, DraftStore}; pub use error::StorageError; -pub use favourites::{DatabaseEnvironment, FavouriteDatabase, FavouriteTable, Favourites}; +pub use favourites::{ + DatabaseEnvironment, FavouriteContents, FavouriteDatabase, FavouriteDigests, FavouriteTable, FavouriteWrite, + Favourites, +}; pub use group_name_error::GroupNameError; pub use group_tree::GroupTree; pub use journal::{ChangeJournal, JournalEntry, RecordKind, RecordRef}; @@ -60,8 +63,13 @@ pub use library_icon::{LibraryIcon, SymbolName}; pub use name_rules::shown as shown_name; pub use paths::StoragePaths; pub use query_history::QueryHistory; -pub use saved_queries::{SavedQueries, SavedQueriesSnapshot, SavedQueryFolder, SavedQueryFolders}; +pub use saved_queries::{ + SavedQueries, SavedQueriesSnapshot, SavedQueryContents, SavedQueryFolder, SavedQueryFolders, SavedQuerySettlement, + SavedQueryWrite, +}; pub use store_identity::{StoreContinuity, StoreIdentity}; -pub use table_folders::{TableFolder, TableFolderItem, TableFolders, TableRef, TableScope}; +pub use table_folders::{ + TableFolder, TableFolderContents, TableFolderItem, TableFolderWrite, TableFolders, TableRef, TableScope, +}; pub use tag_name_error::TagNameError; pub use team_library::{TeamLibraryItem, TeamLibraryKind, TeamLibraryOwner, TeamLibraryStore, TeamLibraryTeam}; diff --git a/core/crates/storage/src/query_history/host_entries.rs b/core/crates/storage/src/query_history/host_entries.rs new file mode 100644 index 0000000000..5967329b14 --- /dev/null +++ b/core/crates/storage/src/query_history/host_entries.rs @@ -0,0 +1,124 @@ +// Entries a host keeps in a store of its own and copies here under their ids: the Mac records each run in its +// history and here, until its history reads from the core (core ADR 0010, slice 3). + +use std::collections::HashSet; + +use sqlx::{AssertSqlSafe, Connection}; +use uuid::Uuid; + +use super::search_fold::fold; +use super::{ + Bind, CopyDelete, IDS_PER_STATEMENT, MAX_QUERY_BYTES, NewEntry, Outcome, QueryHistory, trim_upgrade_copies, +}; +use crate::error::StorageError; +use crate::unix_time::to_unix; + +impl QueryHistory { + // In one transaction. An entry this store already holds keeps its row, as `record` keeps it. Returns how many + // were new. + pub async fn put(&self, entries: &[NewEntry]) -> Result { + if let Some(entry) = entries.iter().find(|entry| entry.query.len() > MAX_QUERY_BYTES) { + return Err(StorageError::TooLarge { + got: entry.query.len(), + limit: MAX_QUERY_BYTES, + }); + } + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; + let mut inserted = Vec::new(); + let mut seen = HashSet::new(); + for entry in entries.iter().filter(|entry| seen.insert(entry.record_id)) { + let (success, cancelled, error) = match &entry.outcome { + Outcome::Success => (1_i64, 0_i64, None), + Outcome::Error(message) => (0, 0, Some(message.as_str())), + Outcome::Cancelled => (0, 1, None), + }; + let added = sqlx::query( + "INSERT INTO history (record_id, query, query_folded, driver_id, connection_id, connection_name, \ + executed_at, duration_ms, rows_affected, success, cancelled, error) \ + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (record_id) DO NOTHING", + ) + .bind(entry.record_id.to_string()) + .bind(&entry.query) + .bind(fold(&entry.query)) + .bind(&entry.driver_id) + .bind(entry.connection_id.to_string()) + .bind(&entry.connection_name) + .bind(to_unix(entry.executed_at)) + .bind(entry.duration_ms) + .bind(entry.rows_affected) + .bind(success) + .bind(cancelled) + .bind(error) + .execute(&mut *transaction) + .await? + .rows_affected(); + if added > 0 { + inserted.push(entry.record_id); + } + } + transaction.commit().await?; + let count = inserted.len() as u64; + self.history_changed(inserted, []); + Ok(count) + } + + // Every entry's record id, so a host can tell which of its own the store lacks or holds past. + pub async fn record_ids(&self) -> Result, StorageError> { + let texts: Vec = sqlx::query_scalar("SELECT record_id FROM history ORDER BY id") + .fetch_all(&self.pool) + .await?; + texts + .iter() + .map(|text| { + Uuid::parse_str(text).map_err(|_| StorageError::Schema("a history record_id is not a UUID".to_owned())) + }) + .collect() + } + + // By record id, from the upgrade copies too. Returns how many were there. + pub async fn remove(&self, record_ids: &[Uuid]) -> Result { + if record_ids.is_empty() { + return Ok(0); + } + let copies: Vec = record_ids + .chunks(IDS_PER_STATEMENT) + .map(|chunk| CopyDelete { + table: "history", + sql: format!( + "DELETE FROM main.history WHERE record_id IN ({})", + vec!["?"; chunk.len()].join(",") + ), + binds: chunk.iter().map(|id| Bind::Text(id.to_string())).collect(), + }) + .collect(); + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; + trim_upgrade_copies(&self.path, &copies).await?; + let mut removed = Vec::new(); + for chunk in record_ids.chunks(IDS_PER_STATEMENT) { + let sql = format!( + "DELETE FROM history WHERE record_id IN ({}) RETURNING record_id", + vec!["?"; chunk.len()].join(",") + ); + let mut statement = sqlx::query_scalar::<_, String>(AssertSqlSafe(sql)); + for id in chunk { + statement = statement.bind(id.to_string()); + } + removed.extend(statement.fetch_all(&mut *transaction).await?); + } + if !removed.is_empty() { + sqlx::query("INSERT INTO history_search(history_search) VALUES('optimize')") + .execute(&mut *transaction) + .await?; + } + transaction.commit().await?; + let count = removed.len() as u64; + self.history_changed([], super::record_ids(removed)); + Ok(count) + } +} + +#[cfg(test)] +#[path = "host_entries_tests.rs"] +mod tests; diff --git a/core/crates/storage/src/query_history/host_entries_tests.rs b/core/crates/storage/src/query_history/host_entries_tests.rs new file mode 100644 index 0000000000..bc1c1bbdc5 --- /dev/null +++ b/core/crates/storage/src/query_history/host_entries_tests.rs @@ -0,0 +1,76 @@ +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use uuid::Uuid; + +use super::super::{HistoryPageRequest, HistoryQuery, NewEntry, Outcome, QueryHistory}; +use crate::StoragePaths; +use crate::journal::recording::Recording; +use crate::journal::{RecordKind, RecordRef}; + +async fn history(root: &tempfile::TempDir) -> QueryHistory { + QueryHistory::open(&StoragePaths::under(root.path(), "tablepro", "app.tablepro.TablePro")) + .await + .expect("open") +} + +fn entry(query: &str, seconds: u64) -> NewEntry { + NewEntry { + record_id: Uuid::new_v4(), + query: query.to_owned(), + driver_id: "MySQL".to_owned(), + connection_id: Uuid::new_v4(), + connection_name: "shop".to_owned(), + executed_at: SystemTime::UNIX_EPOCH + Duration::from_secs(seconds), + duration_ms: Some(12), + rows_affected: Some(3), + outcome: Outcome::Error("syntax".to_owned()), + } +} + +#[tokio::test] +async fn put_keeps_each_entrys_id_and_an_entry_put_again_keeps_its_row() { + let root = tempfile::tempdir().expect("tempdir"); + let history = history(&root).await; + let first = entry("SELECT 1", 1_700_000_000); + let second = entry("SELECT 2", 1_700_000_100); + + let added = history.put(&[first.clone(), second.clone()]).await.expect("put"); + let again = history.put(std::slice::from_ref(&first)).await.expect("put again"); + + assert_eq!((added, again), (2, 0)); + let mut ids = history.record_ids().await.expect("ids"); + ids.sort(); + let mut expected = vec![first.record_id, second.record_id]; + expected.sort(); + assert_eq!(ids, expected); + let page = history + .search_page(&HistoryQuery::from_input("select 1"), HistoryPageRequest::first(10)) + .await + .expect("search"); + let found = page.entries.first().expect("an entry"); + assert_eq!(found.record_id, first.record_id); + assert_eq!(found.connection_name, "shop"); + assert_eq!(found.error.as_deref(), Some("syntax")); + assert!(!found.success); +} + +#[tokio::test] +async fn remove_takes_entries_by_record_id_and_the_journal_hears_them() { + let root = tempfile::tempdir().expect("tempdir"); + let history = history(&root).await; + let kept = entry("SELECT kept", 1_700_000_000); + let gone = entry("SELECT gone", 1_700_000_100); + history.put(&[kept.clone(), gone.clone()]).await.expect("put"); + let journal = Arc::new(Recording::default()); + history.set_journal(Some(journal.clone())); + + let removed = history.remove(&[gone.record_id, Uuid::new_v4()]).await.expect("remove"); + + assert_eq!(removed, 1); + assert_eq!(history.record_ids().await.expect("ids"), vec![kept.record_id]); + let entries = journal.take_entries().concat(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].kind, RecordKind::HistoryEntry); + assert_eq!(entries[0].deleted, vec![RecordRef::Id(gone.record_id)]); +} diff --git a/core/crates/storage/src/query_history/mod.rs b/core/crates/storage/src/query_history/mod.rs index f0f43929a6..6a79f9a2f5 100644 --- a/core/crates/storage/src/query_history/mod.rs +++ b/core/crates/storage/src/query_history/mod.rs @@ -9,6 +9,7 @@ mod history_connection; mod history_cursor; mod history_page; mod history_query; +mod host_entries; #[cfg(test)] mod identity_tests; mod new_entry; diff --git a/core/crates/storage/src/saved_queries/batch.rs b/core/crates/storage/src/saved_queries/batch.rs new file mode 100644 index 0000000000..40d79695c7 --- /dev/null +++ b/core/crates/storage/src/saved_queries/batch.rs @@ -0,0 +1,280 @@ +// Writes a host makes whole: every record it holds, or the records one of its edits wrote and removed, each under +// its own id. The Mac's store writes through these while it moves into the core (core ADR 0010, slice 3). + +use std::collections::HashSet; +use std::time::SystemTime; + +use sha2::{Digest, Sha256}; +use sqlx::{AssertSqlSafe, Connection, Row, SqliteConnection}; +use uuid::Uuid; + +use crate::StorageError; +use crate::journal::JournalEntry; +use crate::query_history::trim_upgrade_copies; +use crate::unix_time::to_unix_millis; + +use super::deletion::{delete_folder_rows, rowid_deletes}; +use super::folders::{SavedQueryFolder, folders, row_to_folder}; +use super::put::{put_folders, put_queries}; +use super::{SavedQueries, SavedQuery, queries, row_to_saved_query}; + +const IDS_PER_STATEMENT: usize = 500; + +// Every query and folder, with a digest a later write can name to say what it was based on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SavedQueryContents { + pub queries: Vec, + pub folders: Vec, + pub digest: String, +} + +// Records written over any this store holds under their ids, and records removed by id. A removal changes no +// other row: the folders and queries a removed folder held stay as the write gives them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SavedQueryWrite { + pub queries: Vec, + pub folders: Vec, + pub removed_queries: Vec, + pub removed_folders: Vec, +} + +// The ids whose name or keyword the store changed to settle a collision (core ADR 0052), and the digest after. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SavedQuerySettlement { + pub queries: Vec, + pub folders: Vec, + pub digest: String, +} + +impl SavedQueries { + pub async fn contents(&self) -> Result { + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin().await?; + let contents = read_contents(&mut transaction).await?; + transaction.commit().await?; + Ok(contents) + } + + pub async fn write(&self, write: &SavedQueryWrite) -> Result { + self.commit(None, write).await + } + + // The store comes to hold exactly these records. Refused with `ImportOutdated`, writing nothing, when + // `expected` is not the digest of what the store holds, so a change the caller never read survives. + pub async fn replace( + &self, + expected: Option<&str>, + queries: &[SavedQuery], + folders: &[SavedQueryFolder], + ) -> Result { + let kept_queries: HashSet = queries.iter().map(|query| query.id).collect(); + let kept_folders: HashSet = folders.iter().map(|folder| folder.id).collect(); + let replace = Replace { + expected, + kept_queries, + kept_folders, + }; + let write = SavedQueryWrite { + queries: queries.to_vec(), + folders: folders.to_vec(), + removed_queries: Vec::new(), + removed_folders: Vec::new(), + }; + self.commit(Some(replace), &write).await + } + + async fn commit( + &self, + replace: Option>, + write: &SavedQueryWrite, + ) -> Result { + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; + let (removed_queries, removed_folders) = match &replace { + Some(replace) => { + let held = read_contents(&mut transaction).await?; + if replace.expected.is_some_and(|expected| expected != held.digest) { + return Err(StorageError::ImportOutdated); + } + let gone_queries = held + .queries + .iter() + .map(|query| query.id) + .filter(|id| !replace.kept_queries.contains(id)) + .collect(); + let gone_folders = held + .folders + .iter() + .map(|folder| folder.id) + .filter(|id| !replace.kept_folders.contains(id)) + .collect(); + (gone_queries, gone_folders) + } + None => (write.removed_queries.clone(), write.removed_folders.clone()), + }; + let removed_queries = remove_rows(&mut transaction, &self.path, "saved_queries", &removed_queries).await?; + let removed_folders = + remove_rows(&mut transaction, &self.path, "saved_query_folders", &removed_folders).await?; + let now = SystemTime::now(); + let settled_folders = match write.folders.is_empty() { + true => Vec::new(), + false => put_folders(&mut transaction, &write.folders, now).await?, + }; + let settled_queries = match write.queries.is_empty() { + true => Vec::new(), + false => put_queries(&mut transaction, &write.queries, now).await?, + }; + let digest = read_contents(&mut transaction).await?.digest; + transaction.commit().await?; + let entries: Vec = [ + queries( + write + .queries + .iter() + .map(|query| query.id) + .chain(settled_queries.iter().copied()), + removed_queries, + ), + folders( + write + .folders + .iter() + .map(|folder| folder.id) + .chain(settled_folders.iter().copied()), + removed_folders, + ), + ] + .into_iter() + .filter(|entry| !entry.is_empty()) + .collect(); + if !entries.is_empty() { + self.signals.changed(&entries); + } + Ok(SavedQuerySettlement { + queries: settled_queries, + folders: settled_folders, + digest, + }) + } +} + +struct Replace<'a> { + expected: Option<&'a str>, + kept_queries: HashSet, + kept_folders: HashSet, +} + +async fn read_contents(database: &mut SqliteConnection) -> Result { + let queries = sqlx::query(concat!("SELECT ", columns!(), " FROM saved_queries ORDER BY record_id")) + .fetch_all(&mut *database) + .await? + .iter() + .map(row_to_saved_query) + .collect::, _>>()?; + let folders = sqlx::query(concat!( + "SELECT ", + folder_columns!(), + " FROM saved_query_folders ORDER BY record_id" + )) + .fetch_all(&mut *database) + .await? + .iter() + .map(row_to_folder) + .collect::, _>>()?; + let digest = digest(&queries, &folders)?; + Ok(SavedQueryContents { + queries, + folders, + digest, + }) +} + +// Over every stored value in record id order, so two reads of the same rows give the same digest. +fn digest(queries: &[SavedQuery], folders: &[SavedQueryFolder]) -> Result { + let queries: Vec<_> = queries + .iter() + .map(|query| { + ( + query.id, + &query.name, + &query.query, + query.connection_id, + &query.connection_name, + &query.keyword, + query.folder_id, + query.order, + to_unix_millis(query.created_at), + to_unix_millis(query.updated_at), + ) + }) + .collect(); + let folders: Vec<_> = folders + .iter() + .map(|folder| { + ( + folder.id, + &folder.name, + folder.connection_id, + folder.parent_id, + folder.order, + to_unix_millis(folder.created_at), + to_unix_millis(folder.updated_at), + ) + }) + .collect(); + let bytes = serde_json::to_vec(&(queries, folders))?; + Ok(hex::encode(Sha256::digest(&bytes))) +} + +// Removes the rows these ids name, from the upgrade copies too, and returns the ids that were there. +async fn remove_rows( + database: &mut SqliteConnection, + path: &std::path::Path, + table: &'static str, + ids: &[Uuid], +) -> Result, StorageError> { + let mut rowids = Vec::new(); + let mut removed = Vec::new(); + for chunk in ids.chunks(IDS_PER_STATEMENT) { + let sql = format!( + "SELECT id, record_id FROM {table} WHERE record_id IN ({})", + vec!["?"; chunk.len()].join(",") + ); + let mut statement = sqlx::query(AssertSqlSafe(sql)); + for id in chunk { + statement = statement.bind(id.to_string()); + } + for row in statement.fetch_all(&mut *database).await? { + rowids.push(row.try_get::("id")?); + removed.push(super::ordering::record_id(&row.try_get::("record_id")?)?); + } + } + if rowids.is_empty() { + return Ok(removed); + } + trim_upgrade_copies(path, &rowid_deletes(table, &rowids)).await?; + match table { + "saved_query_folders" => delete_folder_rows(database, &rowids).await?, + _ => delete_query_rows(database, &rowids).await?, + } + Ok(removed) +} + +async fn delete_query_rows(database: &mut SqliteConnection, ids: &[i64]) -> Result<(), StorageError> { + for chunk in ids.chunks(IDS_PER_STATEMENT) { + let sql = format!( + "DELETE FROM saved_queries WHERE id IN ({})", + vec!["?"; chunk.len()].join(",") + ); + let mut statement = sqlx::query(AssertSqlSafe(sql)); + for id in chunk { + statement = statement.bind(id); + } + statement.execute(&mut *database).await?; + } + Ok(()) +} + +#[cfg(test)] +#[path = "batch_tests.rs"] +mod tests; diff --git a/core/crates/storage/src/saved_queries/batch_tests.rs b/core/crates/storage/src/saved_queries/batch_tests.rs new file mode 100644 index 0000000000..a5f700c1b4 --- /dev/null +++ b/core/crates/storage/src/saved_queries/batch_tests.rs @@ -0,0 +1,205 @@ +use std::sync::Arc; +use std::time::Duration; + +use super::*; +use crate::journal::recording::Recording; +use crate::journal::{RecordKind, RecordRef}; +use crate::{QueryHistory, StoragePaths}; + +async fn history(root: &tempfile::TempDir) -> QueryHistory { + QueryHistory::open(&StoragePaths::under(root.path(), "tablepro", "app.tablepro.TablePro")) + .await + .expect("open") +} + +fn at(millis: u64) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_millis(millis) +} + +fn query(name: &str, connection: Option, folder: Option, created_at: SystemTime) -> SavedQuery { + SavedQuery { + id: Uuid::new_v4(), + name: name.to_owned(), + query: format!("SELECT '{name}'"), + connection_id: connection, + connection_name: "local".to_owned(), + keyword: None, + folder_id: folder, + order: 3, + created_at, + updated_at: created_at + Duration::from_millis(5), + } +} + +fn folder(name: &str, parent: Option, created_at: SystemTime) -> SavedQueryFolder { + SavedQueryFolder { + id: Uuid::new_v4(), + connection_id: None, + name: name.to_owned(), + parent_id: parent, + order: 2, + created_at, + updated_at: created_at, + } +} + +#[tokio::test] +async fn a_write_keeps_every_id_and_value_and_two_reads_give_one_digest() { + let root = tempfile::tempdir().expect("tempdir"); + let store = history(&root).await.saved_queries(); + let shelf = folder("Reports", None, at(1_700_000_000_001)); + let mut daily = query("Daily", Some(Uuid::new_v4()), Some(shelf.id), at(1_700_000_000_123)); + daily.keyword = Some("dl".to_owned()); + + let settled = store + .write(&SavedQueryWrite { + queries: vec![daily.clone()], + folders: vec![shelf.clone()], + ..SavedQueryWrite::default() + }) + .await + .expect("write"); + + let contents = store.contents().await.expect("contents"); + assert!(settled.queries.is_empty() && settled.folders.is_empty()); + assert_eq!(contents.queries, vec![daily]); + assert_eq!(contents.folders, vec![shelf]); + assert_eq!(settled.digest, contents.digest); + assert_eq!(store.contents().await.expect("contents").digest, contents.digest); +} + +#[tokio::test] +async fn removing_a_folder_changes_no_other_row() { + let root = tempfile::tempdir().expect("tempdir"); + let store = history(&root).await.saved_queries(); + let outer = folder("Outer", None, at(1_000)); + let inner = folder("Inner", Some(outer.id), at(2_000)); + let filed = query("Filed", None, Some(outer.id), at(3_000)); + store + .write(&SavedQueryWrite { + queries: vec![filed.clone()], + folders: vec![outer.clone(), inner.clone()], + ..SavedQueryWrite::default() + }) + .await + .expect("write"); + + store + .write(&SavedQueryWrite { + removed_folders: vec![outer.id], + ..SavedQueryWrite::default() + }) + .await + .expect("remove"); + + let contents = store.contents().await.expect("contents"); + assert_eq!(contents.folders, vec![inner]); + assert_eq!(contents.queries, vec![filed]); +} + +#[tokio::test] +async fn a_replace_leaves_only_what_it_names_and_the_journal_hears_each_id() { + let root = tempfile::tempdir().expect("tempdir"); + let history = history(&root).await; + let store = history.saved_queries(); + let kept = query("Kept", None, None, at(1_000)); + let dropped = query("Dropped", None, None, at(2_000)); + let old_folder = folder("Old", None, at(3_000)); + store + .write(&SavedQueryWrite { + queries: vec![kept.clone(), dropped.clone()], + folders: vec![old_folder.clone()], + ..SavedQueryWrite::default() + }) + .await + .expect("write"); + let journal = Arc::new(Recording::default()); + history.set_journal(Some(journal.clone())); + let read = store.contents().await.expect("contents"); + + store + .replace(Some(&read.digest), std::slice::from_ref(&kept), &[]) + .await + .expect("replace"); + + let contents = store.contents().await.expect("contents"); + assert_eq!(contents.queries, vec![kept.clone()]); + assert!(contents.folders.is_empty()); + let entries = journal.take_entries().concat(); + let query_entry = entries + .iter() + .find(|entry| entry.kind == RecordKind::SavedQuery) + .expect("queries"); + assert_eq!(query_entry.written, vec![RecordRef::Id(kept.id)]); + assert_eq!(query_entry.deleted, vec![RecordRef::Id(dropped.id)]); + let folder_entry = entries + .iter() + .find(|entry| entry.kind == RecordKind::SavedQueryFolder) + .expect("folders"); + assert_eq!(folder_entry.deleted, vec![RecordRef::Id(old_folder.id)]); +} + +#[tokio::test] +async fn a_replace_based_on_an_older_read_writes_nothing() { + let root = tempfile::tempdir().expect("tempdir"); + let store = history(&root).await.saved_queries(); + let first = query("First", None, None, at(1_000)); + store + .write(&SavedQueryWrite { + queries: vec![first.clone()], + ..SavedQueryWrite::default() + }) + .await + .expect("write"); + let read = store.contents().await.expect("contents"); + let later = query("Later", None, None, at(2_000)); + store + .write(&SavedQueryWrite { + queries: vec![later.clone()], + ..SavedQueryWrite::default() + }) + .await + .expect("write"); + + let refused = store + .replace(Some(&read.digest), std::slice::from_ref(&first), &[]) + .await; + + assert!(matches!(refused, Err(StorageError::ImportOutdated))); + let mut names: Vec = store + .contents() + .await + .expect("contents") + .queries + .into_iter() + .map(|query| query.name) + .collect(); + names.sort(); + assert_eq!(names, ["First", "Later"]); +} + +#[tokio::test] +async fn two_queries_of_one_name_settle_on_the_later_one_and_report_it() { + let root = tempfile::tempdir().expect("tempdir"); + let store = history(&root).await.saved_queries(); + let connection = Some(Uuid::new_v4()); + let older = query("Report", connection, None, at(1_000)); + let newer = query("Report", connection, None, at(2_000)); + + let settled = store + .replace(None, &[older.clone(), newer.clone()], &[]) + .await + .expect("replace"); + + assert_eq!(settled.queries, vec![newer.id]); + let contents = store.contents().await.expect("contents"); + let name_of = |id: Uuid| { + contents + .queries + .iter() + .find(|query| query.id == id) + .map(|query| query.name.clone()) + }; + assert_eq!(name_of(older.id).as_deref(), Some("Report")); + assert_eq!(name_of(newer.id).as_deref(), Some("Report (2)")); +} diff --git a/core/crates/storage/src/saved_queries/deletion.rs b/core/crates/storage/src/saved_queries/deletion.rs index 7061aaebfd..10fdf79d71 100644 --- a/core/crates/storage/src/saved_queries/deletion.rs +++ b/core/crates/storage/src/saved_queries/deletion.rs @@ -267,7 +267,7 @@ async fn unfile_queries( Ok(unfiled) } -fn rowid_deletes(table: &'static str, ids: &[i64]) -> Vec { +pub(super) fn rowid_deletes(table: &'static str, ids: &[i64]) -> Vec { ids.chunks(IDS_PER_STATEMENT) .map(|chunk| CopyDelete { table, @@ -280,7 +280,7 @@ fn rowid_deletes(table: &'static str, ids: &[i64]) -> Vec { .collect() } -async fn delete_folder_rows(database: &mut SqliteConnection, ids: &[i64]) -> Result<(), StorageError> { +pub(super) async fn delete_folder_rows(database: &mut SqliteConnection, ids: &[i64]) -> Result<(), StorageError> { for chunk in ids.chunks(IDS_PER_STATEMENT) { let sql = format!( "DELETE FROM saved_query_folders WHERE id IN ({})", diff --git a/core/crates/storage/src/saved_queries/mod.rs b/core/crates/storage/src/saved_queries/mod.rs index d2c0b96be3..bab4413079 100644 --- a/core/crates/storage/src/saved_queries/mod.rs +++ b/core/crates/storage/src/saved_queries/mod.rs @@ -11,6 +11,7 @@ macro_rules! folder_columns { }; } +mod batch; mod deletion; mod folders; mod new_saved_query; @@ -34,6 +35,7 @@ use crate::journal::{JournalEntry, RecordKind, RecordRef, Signals}; use crate::stored_id::{optional_uuid_column, uuid_column}; use crate::unix_time::{from_unix_millis, to_unix_millis}; +pub use batch::{SavedQueryContents, SavedQuerySettlement, SavedQueryWrite}; pub use folders::{SavedQueryFolder, SavedQueryFolders}; pub use new_saved_query::NewSavedQuery; pub(crate) use put::free_name; diff --git a/core/crates/storage/src/table_folders/batch.rs b/core/crates/storage/src/table_folders/batch.rs new file mode 100644 index 0000000000..29f501f396 --- /dev/null +++ b/core/crates/storage/src/table_folders/batch.rs @@ -0,0 +1,372 @@ +// Writes a host makes whole: every folder and item it holds, or the ones one of its edits wrote and removed. The +// Mac's store writes through these while it moves into the core (core ADR 0010, slice 9). + +use std::collections::HashSet; + +use sha2::{Digest, Sha256}; +use sqlx::{AssertSqlSafe, Connection, Row, SqliteConnection}; +use uuid::Uuid; + +use crate::StorageError; +use crate::journal::{JournalEntry, RecordKind, RecordRef}; +use crate::query_history::{Bind, CopyDelete, trim_upgrade_copies}; + +use super::{TableFolder, TableFolderItem, TableFolders, TableRef, checked_name, folder_from_row, uuid_column}; + +// Every folder and item of every connection, with a digest a later write can name to say what it was based on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TableFolderContents { + pub folders: Vec, + pub items: Vec, + pub digest: String, +} + +// Folders and items written over any this store holds under their keys, and ones removed. Removing a folder +// changes no item: the write names the items it takes out. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TableFolderWrite { + pub folders: Vec, + pub items: Vec, + pub removed_folders: Vec, + pub removed_items: Vec, +} + +impl TableFolders { + pub async fn contents(&self) -> Result { + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin().await?; + let contents = read_contents(&mut transaction).await?; + transaction.commit().await?; + Ok(contents) + } + + // Returns the digest after the write. + pub async fn write(&self, write: &TableFolderWrite) -> Result { + self.commit(None, write).await + } + + // The store comes to hold exactly these. Refused with `ImportOutdated`, writing nothing, when `expected` is not + // the digest of what the store holds. + pub async fn replace( + &self, + expected: Option<&str>, + folders: &[TableFolder], + items: &[TableFolderItem], + ) -> Result { + let write = TableFolderWrite { + folders: folders.to_vec(), + items: items.to_vec(), + removed_folders: Vec::new(), + removed_items: Vec::new(), + }; + self.commit(Some(expected), &write).await + } + + async fn commit(&self, replace: Option>, write: &TableFolderWrite) -> Result { + for folder in &write.folders { + checked_name(&folder.name)?; + } + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; + let (removed_folders, removed_items) = match replace { + Some(expected) => { + let held = read_contents(&mut transaction).await?; + if expected.is_some_and(|expected| expected != held.digest) { + return Err(StorageError::ImportOutdated); + } + let kept_folders: HashSet = write.folders.iter().map(|folder| folder.id).collect(); + let kept_items: HashSet<&TableRef> = write.items.iter().map(|item| &item.table).collect(); + let folders: Vec = held + .folders + .iter() + .map(|folder| folder.id) + .filter(|id| !kept_folders.contains(id)) + .collect(); + let items: Vec = held + .items + .into_iter() + .map(|item| item.table) + .filter(|table| !kept_items.contains(table)) + .collect(); + (folders, items) + } + None => (write.removed_folders.clone(), write.removed_items.clone()), + }; + trim_upgrade_copies(&self.path, ©_deletes(&removed_folders, &removed_items)).await?; + let (gone_folders, gone_items) = remove(&mut transaction, &removed_folders, &removed_items).await?; + let (wrote_folders, wrote_items) = put(&mut transaction, write).await?; + let digest = read_contents(&mut transaction).await?.digest; + transaction.commit().await?; + self.tell( + JournalEntry::new(RecordKind::TableFolder) + .wrote(wrote_folders) + .deleted(gone_folders), + Some( + JournalEntry::new(RecordKind::TableFolderItem) + .wrote(wrote_items) + .deleted(gone_items), + ), + ); + Ok(digest) + } +} + +type Changed = (Vec, Vec); + +async fn remove( + database: &mut SqliteConnection, + folders: &[Uuid], + items: &[TableRef], +) -> Result { + let mut gone_folders = Vec::new(); + for id in folders { + let removed = sqlx::query("DELETE FROM table_folders WHERE id = ?") + .bind(id.to_string()) + .execute(&mut *database) + .await? + .rows_affected(); + if removed > 0 { + gone_folders.push(RecordRef::Id(*id)); + } + } + let mut gone_items = Vec::new(); + for table in items { + let removed = sqlx::query( + "DELETE FROM table_folder_items WHERE connection_id = ? AND database = ? AND schema = ? AND name = ?", + ) + .bind(table.connection_id.to_string()) + .bind(&table.database) + .bind(&table.schema) + .bind(&table.name) + .execute(&mut *database) + .await? + .rows_affected(); + if removed > 0 { + gone_items.push(RecordRef::Table(table.clone())); + } + } + Ok((gone_folders, gone_items)) +} + +async fn put(database: &mut SqliteConnection, write: &TableFolderWrite) -> Result { + let mut wrote_folders = Vec::new(); + for folder in &write.folders { + let changed = sqlx::query( + "INSERT INTO table_folders (id, connection_id, database, schema, name, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET connection_id = excluded.connection_id, \ + database = excluded.database, schema = excluded.schema, name = excluded.name, \ + created_at = excluded.created_at, updated_at = excluded.updated_at \ + WHERE (connection_id, database, schema, name, created_at, updated_at) IS NOT \ + (excluded.connection_id, excluded.database, excluded.schema, excluded.name, excluded.created_at, \ + excluded.updated_at)", + ) + .bind(folder.id.to_string()) + .bind(folder.scope.connection_id.to_string()) + .bind(&folder.scope.database) + .bind(&folder.scope.schema) + .bind(&folder.name) + .bind(folder.created_at_ms) + .bind(folder.updated_at_ms) + .execute(&mut *database) + .await? + .rows_affected(); + if changed > 0 { + wrote_folders.push(RecordRef::Id(folder.id)); + } + } + let mut wrote_items = Vec::new(); + for item in &write.items { + let changed = sqlx::query( + "INSERT INTO table_folder_items (connection_id, database, schema, name, folder_id) \ + VALUES (?, ?, ?, ?, ?) ON CONFLICT (connection_id, database, schema, name) \ + DO UPDATE SET folder_id = excluded.folder_id WHERE folder_id IS NOT excluded.folder_id", + ) + .bind(item.table.connection_id.to_string()) + .bind(&item.table.database) + .bind(&item.table.schema) + .bind(&item.table.name) + .bind(item.folder_id.to_string()) + .execute(&mut *database) + .await? + .rows_affected(); + if changed > 0 { + wrote_items.push(RecordRef::Table(item.table.clone())); + } + } + Ok((wrote_folders, wrote_items)) +} + +fn copy_deletes(folders: &[Uuid], items: &[TableRef]) -> Vec { + let folders = folders.iter().map(|id| CopyDelete { + table: "table_folders", + sql: "DELETE FROM main.table_folders WHERE id = ?".to_owned(), + binds: vec![Bind::Text(id.to_string())], + }); + let items = items.iter().map(|table| CopyDelete { + table: "table_folder_items", + sql: "DELETE FROM main.table_folder_items WHERE connection_id = ? AND database = ? AND schema = ? AND name = ?" + .to_owned(), + binds: vec![ + Bind::Text(table.connection_id.to_string()), + Bind::Text(table.database.clone()), + Bind::Text(table.schema.clone()), + Bind::Text(table.name.clone()), + ], + }); + folders.chain(items).collect() +} + +async fn read_contents(database: &mut SqliteConnection) -> Result { + let folders = sqlx::query( + "SELECT id, connection_id, database, schema, name, created_at, updated_at FROM table_folders ORDER BY id", + ) + .fetch_all(&mut *database) + .await? + .into_iter() + .map(folder_from_row) + .collect::, _>>()?; + let items = sqlx::query( + "SELECT connection_id, database, schema, name, folder_id FROM table_folder_items \ + ORDER BY connection_id, database, schema, name", + ) + .fetch_all(&mut *database) + .await? + .into_iter() + .map(|row| { + Ok(TableFolderItem { + table: TableRef { + connection_id: uuid_column(&row, "connection_id")?, + database: row.try_get("database")?, + schema: row.try_get("schema")?, + name: row.try_get("name")?, + }, + folder_id: uuid_column(&row, "folder_id")?, + }) + }) + .collect::, StorageError>>()?; + let digest = digest(&folders, &items)?; + Ok(TableFolderContents { folders, items, digest }) +} + +fn digest(folders: &[TableFolder], items: &[TableFolderItem]) -> Result { + let folders: Vec<_> = folders + .iter() + .map(|folder| { + ( + folder.id, + folder.scope.connection_id, + &folder.scope.database, + &folder.scope.schema, + &folder.name, + folder.created_at_ms, + folder.updated_at_ms, + ) + }) + .collect(); + let items: Vec<_> = items + .iter() + .map(|item| { + ( + item.table.connection_id, + &item.table.database, + &item.table.schema, + &item.table.name, + item.folder_id, + ) + }) + .collect(); + let bytes = serde_json::to_vec(&(folders, items))?; + Ok(hex::encode(Sha256::digest(&bytes))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{QueryHistory, StoragePaths, TableScope}; + + async fn folders(root: &tempfile::TempDir) -> TableFolders { + QueryHistory::open(&StoragePaths::under(root.path(), "tablepro", "app.tablepro.TablePro")) + .await + .expect("open") + .table_folders() + } + + fn folder(connection_id: Uuid, name: &str) -> TableFolder { + TableFolder { + id: Uuid::new_v4(), + scope: TableScope { + connection_id, + database: "shop".to_owned(), + schema: String::new(), + }, + name: name.to_owned(), + created_at_ms: 1_700_000_000_123, + updated_at_ms: 1_700_000_000_456, + } + } + + fn filed(folder: &TableFolder, name: &str) -> TableFolderItem { + TableFolderItem { + table: TableRef { + connection_id: folder.scope.connection_id, + database: folder.scope.database.clone(), + schema: folder.scope.schema.clone(), + name: name.to_owned(), + }, + folder_id: folder.id, + } + } + + #[tokio::test] + async fn a_write_keeps_ids_and_times_and_removing_a_folder_leaves_its_items_to_the_write() { + let root = tempfile::tempdir().expect("tempdir"); + let store = folders(&root).await; + let shelf = folder(Uuid::new_v4(), "Billing"); + let item = filed(&shelf, "invoices"); + store + .write(&TableFolderWrite { + folders: vec![shelf.clone()], + items: vec![item.clone()], + ..TableFolderWrite::default() + }) + .await + .expect("write"); + assert_eq!(store.contents().await.expect("contents").folders, vec![shelf.clone()]); + + let digest = store + .write(&TableFolderWrite { + removed_folders: vec![shelf.id], + ..TableFolderWrite::default() + }) + .await + .expect("remove"); + + let contents = store.contents().await.expect("contents"); + assert!(contents.folders.is_empty()); + assert_eq!(contents.items, vec![item]); + assert_eq!(contents.digest, digest); + } + + #[tokio::test] + async fn a_replace_on_an_older_read_writes_nothing() { + let root = tempfile::tempdir().expect("tempdir"); + let store = folders(&root).await; + let connection = Uuid::new_v4(); + let first = folder(connection, "First"); + let read = store.contents().await.expect("contents"); + store + .write(&TableFolderWrite { + folders: vec![first.clone()], + ..TableFolderWrite::default() + }) + .await + .expect("write"); + + let refused = store.replace(Some(&read.digest), &[], &[]).await; + let current = store.contents().await.expect("contents").digest; + store.replace(Some(¤t), &[], &[]).await.expect("replace"); + + assert!(matches!(refused, Err(StorageError::ImportOutdated))); + assert!(store.contents().await.expect("contents").folders.is_empty()); + } +} diff --git a/core/crates/storage/src/table_folders/mod.rs b/core/crates/storage/src/table_folders/mod.rs index a33d3a64fa..cfc74ff435 100644 --- a/core/crates/storage/src/table_folders/mod.rs +++ b/core/crates/storage/src/table_folders/mod.rs @@ -7,9 +7,12 @@ use crate::error::StorageError; use crate::journal::{JournalEntry, RecordKind, RecordRef, Signals}; use crate::query_history::{Bind, CopyDelete, trim_upgrade_copies}; +mod batch; #[cfg(test)] mod tests; +pub use batch::{TableFolderContents, TableFolderWrite}; + /// A table as a connection's catalog names it. An engine without databases or schemas leaves that /// part empty. #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 3d93b49de8..851cf97778 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1800,6 +1800,32 @@ public struct UniffiVTableCallbackInterfaceCloudKitTransport + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2842,6 +2868,50 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_favouritestore_tables(ulong @ptr,RustBuffer @connectionId ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_favouritestore_contents(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_favouritestore_replace_databases(ulong @ptr,RustBuffer @expectedDigest,RustBuffer @held + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_favouritestore_replace_tables(ulong @ptr,RustBuffer @expectedDigest,RustBuffer @held + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_favouritestore_write_records(ulong @ptr,RustBuffer @write + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3095,6 +3165,39 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_table_folders(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_put_entries(ulong @ptr,RustBuffer @entries + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_record_ids(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_remove_entries(ulong @ptr,RustBuffer @recordIds + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4206,6 +4309,39 @@ public static extern void uniffi_tablepro_ffi_fn_free_savedquerystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_contents(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_replace_records(ulong @ptr,RustBuffer @expectedDigest,RustBuffer @queries,RustBuffer @folders + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_write_records(ulong @ptr,RustBuffer @write + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -5669,6 +5805,39 @@ public static extern void uniffi_tablepro_ffi_fn_free_tablefolderstore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_contents(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_replace_records(ulong @ptr,RustBuffer @expectedDigest,RustBuffer @foldersHeld,RustBuffer @itemsHeld + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_write_records(ulong @ptr,RustBuffer @write + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -7759,6 +7928,50 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_favouritestore_tables( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_contents( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_replace_databases( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_replace_tables( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_write_records( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -7968,6 +8181,39 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_table_folders( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_put_entries( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_record_ids( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_remove_entries( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -8859,6 +9105,39 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_queryrun_result_set( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_contents( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_replace_records( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_write_records( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -10179,6 +10458,39 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_syncservice_upload_again( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_contents( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_replace_records( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_write_records( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -11224,6 +11536,30 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_tables` checksum `53725`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_contents(); + if (checksum != 43991) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_contents` checksum `43991`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_replace_databases(); + if (checksum != 31786) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_replace_databases` checksum `31786`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_replace_tables(); + if (checksum != 1900) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_replace_tables` checksum `1900`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_write_records(); + if (checksum != 15974) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_write_records` checksum `15974`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_app(); if (checksum != 35608) { @@ -11338,6 +11674,24 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_table_folders` checksum `54603`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_put_entries(); + if (checksum != 32732) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_put_entries` checksum `32732`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_record_ids(); + if (checksum != 20012) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_record_ids` checksum `20012`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_remove_entries(); + if (checksum != 6327) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_remove_entries` checksum `6327`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_columns(); if (checksum != 53368) { @@ -11824,6 +12178,24 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_result_set` checksum `63812`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_contents(); + if (checksum != 63971) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_contents` checksum `63971`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_replace_records(); + if (checksum != 2325) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_replace_records` checksum `2325`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_write_records(); + if (checksum != 21766) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_write_records` checksum `21766`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_create_folder(); if (checksum != 44813) { @@ -12544,6 +12916,24 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_upload_again` checksum `50600`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_contents(); + if (checksum != 26846) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_contents` checksum `26846`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_replace_records(); + if (checksum != 22235) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_replace_records` checksum `22235`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_write_records(); + if (checksum != 52151) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_write_records` checksum `52151`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_create(); if (checksum != 55602) { @@ -17715,6 +18105,14 @@ internal interface IFavouriteStore { Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment); /// Task Tables(string @connectionId); + /// + Task Contents(); + /// + Task ReplaceDatabases(string? @expectedDigest, FavouriteDatabaseRecord[] @held); + /// + Task ReplaceTables(string? @expectedDigest, FavouriteTableRecord[] @held); + /// + Task WriteRecords(FavouriteRecordWrite @write); } internal class FavouriteStore : IFavouriteStore, IDisposable { protected ulong pointer; @@ -17921,6 +18319,94 @@ public async Task Tables(string @connectionId) { ); } + /// + public async Task Contents() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_contents(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeFavouriteStoreContents.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ReplaceDatabases(string? @expectedDigest, FavouriteDatabaseRecord[] @held) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_replace_databases(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@expectedDigest), FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.Lower(@held)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeFavouriteDigestsRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ReplaceTables(string? @expectedDigest, FavouriteTableRecord[] @held) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_replace_tables(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@expectedDigest), FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Lower(@held)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeFavouriteDigestsRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task WriteRecords(FavouriteRecordWrite @write) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_write_records(thisPtr, FfiConverterTypeFavouriteRecordWrite.INSTANCE.Lower(@write)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeFavouriteDigestsRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + } @@ -18906,6 +19392,12 @@ internal interface IQueryHistoryStore { /// Task SetPinned(long @id, bool @pinned); TableFolderStore TableFolders(); + /// + Task PutEntries(HistoryEntryRecord[] @entries); + /// + Task RecordIds(); + /// + Task RemoveEntries(string[] @recordIds); } internal class QueryHistoryStore : IQueryHistoryStore, IDisposable { protected ulong pointer; @@ -19158,6 +19650,72 @@ public TableFolderStore TableFolders() { } + /// + public async Task PutEntries(HistoryEntryRecord[] @entries) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_put_entries(thisPtr, FfiConverterSequenceTypeHistoryEntryRecord.INSTANCE.Lower(@entries)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RecordIds() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_record_ids(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceString.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RemoveEntries(string[] @recordIds) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_remove_entries(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@recordIds)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + } @@ -19873,6 +20431,12 @@ public override void Write(RowSave value, BigEndianStream stream) { internal interface ISavedQueryStore { + /// + Task Contents(); + /// + Task ReplaceRecords(string? @expectedDigest, SavedQueryRecord[] @queries, SavedQueryFolderRecord[] @folders); + /// + Task WriteRecords(SavedQueryRecordWrite @write); /// Task CreateFolder(string? @connectionId, string @name, string? @parentId); /// @@ -19987,6 +20551,72 @@ internal T CallWithPointer(Func func) } + /// + public async Task Contents() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_contents(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSavedQueryStoreContents.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ReplaceRecords(string? @expectedDigest, SavedQueryRecord[] @queries, SavedQueryFolderRecord[] @folders) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_replace_records(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@expectedDigest), FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.Lower(@queries), FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.Lower(@folders)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSavedQueryWriteOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task WriteRecords(SavedQueryRecordWrite @write) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_write_records(thisPtr, FfiConverterTypeSavedQueryRecordWrite.INSTANCE.Lower(@write)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSavedQueryWriteOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task CreateFolder(string? @connectionId, string @name, string? @parentId) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -21796,6 +22426,12 @@ public override void Write(TableEditor value, BigEndianStream stream) { internal interface ITableFolderStore { + /// + Task Contents(); + /// + Task ReplaceRecords(string? @expectedDigest, TableFolderRecord[] @foldersHeld, TablePlacementRecord[] @itemsHeld); + /// + Task WriteRecords(TableFolderRecordWrite @write); /// Task Create(string @connectionId, string @database, string @schema, string @name); /// @@ -21902,6 +22538,72 @@ internal T CallWithPointer(Func func) } + /// + public async Task Contents() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_tablefolderstore_contents(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeTableFolderStoreContents.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ReplaceRecords(string? @expectedDigest, TableFolderRecord[] @foldersHeld, TablePlacementRecord[] @itemsHeld) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_tablefolderstore_replace_records(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@expectedDigest), FfiConverterSequenceTypeTableFolderRecord.INSTANCE.Lower(@foldersHeld), FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.Lower(@itemsHeld)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterString.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task WriteRecords(TableFolderRecordWrite @write) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_tablefolderstore_write_records(thisPtr, FfiConverterTypeTableFolderRecordWrite.INSTANCE.Lower(@write)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterString.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task Create(string @connectionId, string @database, string @schema, string @name) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -24814,6 +25516,172 @@ public override void Write(FavouriteDatabaseInfo value, BigEndianStream stream) +internal record FavouriteDatabaseKey ( + string ConnectionId, + string Database +) { +} + +class FfiConverterTypeFavouriteDatabaseKey: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteDatabaseKey INSTANCE = new FfiConverterTypeFavouriteDatabaseKey(); + + public override FavouriteDatabaseKey Read(BigEndianStream stream) { + return new FavouriteDatabaseKey( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + Database: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteDatabaseKey value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterString.INSTANCE.AllocationSize(value.Database); + } + + public override void Write(FavouriteDatabaseKey value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterString.INSTANCE.Write(value.Database, stream); + } +} + + + +internal record FavouriteDatabaseRecord ( + string ConnectionId, + string Database, + DatabaseEnvironmentTag Environment +) { +} + +class FfiConverterTypeFavouriteDatabaseRecord: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteDatabaseRecord INSTANCE = new FfiConverterTypeFavouriteDatabaseRecord(); + + public override FavouriteDatabaseRecord Read(BigEndianStream stream) { + return new FavouriteDatabaseRecord( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + Database: FfiConverterString.INSTANCE.Read(stream), + Environment: FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteDatabaseRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterString.INSTANCE.AllocationSize(value.Database) + + FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.AllocationSize(value.Environment); + } + + public override void Write(FavouriteDatabaseRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterString.INSTANCE.Write(value.Database, stream); + FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Write(value.Environment, stream); + } +} + + + +internal record FavouriteDigestsRecord ( + string Tables, + string Databases +) { +} + +class FfiConverterTypeFavouriteDigestsRecord: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteDigestsRecord INSTANCE = new FfiConverterTypeFavouriteDigestsRecord(); + + public override FavouriteDigestsRecord Read(BigEndianStream stream) { + return new FavouriteDigestsRecord( + Tables: FfiConverterString.INSTANCE.Read(stream), + Databases: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteDigestsRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Tables) + + FfiConverterString.INSTANCE.AllocationSize(value.Databases); + } + + public override void Write(FavouriteDigestsRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Tables, stream); + FfiConverterString.INSTANCE.Write(value.Databases, stream); + } +} + + + +internal record FavouriteRecordWrite ( + FavouriteTableRecord[] Tables, + FavouriteDatabaseRecord[] Databases, + FavouriteTableRecord[] RemovedTables, + FavouriteDatabaseKey[] RemovedDatabases +) { +} + +class FfiConverterTypeFavouriteRecordWrite: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteRecordWrite INSTANCE = new FfiConverterTypeFavouriteRecordWrite(); + + public override FavouriteRecordWrite Read(BigEndianStream stream) { + return new FavouriteRecordWrite( + Tables: FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Read(stream), + Databases: FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.Read(stream), + RemovedTables: FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Read(stream), + RemovedDatabases: FfiConverterSequenceTypeFavouriteDatabaseKey.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteRecordWrite value) { + return 0 + + FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.AllocationSize(value.Tables) + + FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.AllocationSize(value.Databases) + + FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.AllocationSize(value.RemovedTables) + + FfiConverterSequenceTypeFavouriteDatabaseKey.INSTANCE.AllocationSize(value.RemovedDatabases); + } + + public override void Write(FavouriteRecordWrite value, BigEndianStream stream) { + FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Write(value.Tables, stream); + FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.Write(value.Databases, stream); + FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Write(value.RemovedTables, stream); + FfiConverterSequenceTypeFavouriteDatabaseKey.INSTANCE.Write(value.RemovedDatabases, stream); + } +} + + + +internal record FavouriteStoreContents ( + FavouriteTableRecord[] Tables, + FavouriteDatabaseRecord[] Databases, + FavouriteDigestsRecord Digests +) { +} + +class FfiConverterTypeFavouriteStoreContents: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteStoreContents INSTANCE = new FfiConverterTypeFavouriteStoreContents(); + + public override FavouriteStoreContents Read(BigEndianStream stream) { + return new FavouriteStoreContents( + Tables: FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Read(stream), + Databases: FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.Read(stream), + Digests: FfiConverterTypeFavouriteDigestsRecord.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteStoreContents value) { + return 0 + + FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.AllocationSize(value.Tables) + + FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.AllocationSize(value.Databases) + + FfiConverterTypeFavouriteDigestsRecord.INSTANCE.AllocationSize(value.Digests); + } + + public override void Write(FavouriteStoreContents value, BigEndianStream stream) { + FfiConverterSequenceTypeFavouriteTableRecord.INSTANCE.Write(value.Tables, stream); + FfiConverterSequenceTypeFavouriteDatabaseRecord.INSTANCE.Write(value.Databases, stream); + FfiConverterTypeFavouriteDigestsRecord.INSTANCE.Write(value.Digests, stream); + } +} + + + internal record FavouriteTableInfo ( string? Database, string? Schema, @@ -24848,6 +25716,44 @@ public override void Write(FavouriteTableInfo value, BigEndianStream stream) { +internal record FavouriteTableRecord ( + string ConnectionId, + string? Database, + string? Schema, + string Name +) { +} + +class FfiConverterTypeFavouriteTableRecord: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteTableRecord INSTANCE = new FfiConverterTypeFavouriteTableRecord(); + + public override FavouriteTableRecord Read(BigEndianStream stream) { + return new FavouriteTableRecord( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + Database: FfiConverterOptionalString.INSTANCE.Read(stream), + Schema: FfiConverterOptionalString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteTableRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Database) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Schema) + + FfiConverterString.INSTANCE.AllocationSize(value.Name); + } + + public override void Write(FavouriteTableRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Database, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Schema, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + } +} + + + internal record FileOpenRequest ( string Path, string? DriverId, @@ -25652,6 +26558,64 @@ public override void Write(HistoryEntryInfo value, BigEndianStream stream) { +internal record HistoryEntryRecord ( + string RecordId, + string Sql, + string DriverId, + string ConnectionId, + string ConnectionName, + long ExecutedAtMs, + long? DurationMs, + long? RowsAffected, + HistoryOutcomeTag Outcome +) { +} + +class FfiConverterTypeHistoryEntryRecord: FfiConverterRustBuffer { + public static FfiConverterTypeHistoryEntryRecord INSTANCE = new FfiConverterTypeHistoryEntryRecord(); + + public override HistoryEntryRecord Read(BigEndianStream stream) { + return new HistoryEntryRecord( + RecordId: FfiConverterString.INSTANCE.Read(stream), + Sql: FfiConverterString.INSTANCE.Read(stream), + DriverId: FfiConverterString.INSTANCE.Read(stream), + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + ConnectionName: FfiConverterString.INSTANCE.Read(stream), + ExecutedAtMs: FfiConverterInt64.INSTANCE.Read(stream), + DurationMs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + RowsAffected: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Outcome: FfiConverterTypeHistoryOutcomeTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(HistoryEntryRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.RecordId) + + FfiConverterString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterString.INSTANCE.AllocationSize(value.DriverId) + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionName) + + FfiConverterInt64.INSTANCE.AllocationSize(value.ExecutedAtMs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.DurationMs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.RowsAffected) + + FfiConverterTypeHistoryOutcomeTag.INSTANCE.AllocationSize(value.Outcome); + } + + public override void Write(HistoryEntryRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.RecordId, stream); + FfiConverterString.INSTANCE.Write(value.Sql, stream); + FfiConverterString.INSTANCE.Write(value.DriverId, stream); + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterString.INSTANCE.Write(value.ConnectionName, stream); + FfiConverterInt64.INSTANCE.Write(value.ExecutedAtMs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.DurationMs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.RowsAffected, stream); + FfiConverterTypeHistoryOutcomeTag.INSTANCE.Write(value.Outcome, stream); + } +} + + + internal record HistoryPageInfo ( HistoryEntryInfo[] Entries, HistoryCursorArg? Next @@ -27670,6 +28634,56 @@ public override void Write(SavedQueryFolderInfo value, BigEndianStream stream) { +internal record SavedQueryFolderRecord ( + string Id, + string Name, + string? ConnectionId, + string? ParentId, + long Order, + long CreatedAtMs, + long UpdatedAtMs +) { +} + +class FfiConverterTypeSavedQueryFolderRecord: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryFolderRecord INSTANCE = new FfiConverterTypeSavedQueryFolderRecord(); + + public override SavedQueryFolderRecord Read(BigEndianStream stream) { + return new SavedQueryFolderRecord( + Id: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + ConnectionId: FfiConverterOptionalString.INSTANCE.Read(stream), + ParentId: FfiConverterOptionalString.INSTANCE.Read(stream), + Order: FfiConverterInt64.INSTANCE.Read(stream), + CreatedAtMs: FfiConverterInt64.INSTANCE.Read(stream), + UpdatedAtMs: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryFolderRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ParentId) + + FfiConverterInt64.INSTANCE.AllocationSize(value.Order) + + FfiConverterInt64.INSTANCE.AllocationSize(value.CreatedAtMs) + + FfiConverterInt64.INSTANCE.AllocationSize(value.UpdatedAtMs); + } + + public override void Write(SavedQueryFolderRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ParentId, stream); + FfiConverterInt64.INSTANCE.Write(value.Order, stream); + FfiConverterInt64.INSTANCE.Write(value.CreatedAtMs, stream); + FfiConverterInt64.INSTANCE.Write(value.UpdatedAtMs, stream); + } +} + + + internal record SavedQueryInfo ( string Id, string Name, @@ -27724,6 +28738,174 @@ public override void Write(SavedQueryInfo value, BigEndianStream stream) { +internal record SavedQueryRecord ( + string Id, + string Name, + string Sql, + string? Keyword, + string? ConnectionId, + string ConnectionName, + string? FolderId, + long Order, + long CreatedAtMs, + long UpdatedAtMs +) { +} + +class FfiConverterTypeSavedQueryRecord: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryRecord INSTANCE = new FfiConverterTypeSavedQueryRecord(); + + public override SavedQueryRecord Read(BigEndianStream stream) { + return new SavedQueryRecord( + Id: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + Sql: FfiConverterString.INSTANCE.Read(stream), + Keyword: FfiConverterOptionalString.INSTANCE.Read(stream), + ConnectionId: FfiConverterOptionalString.INSTANCE.Read(stream), + ConnectionName: FfiConverterString.INSTANCE.Read(stream), + FolderId: FfiConverterOptionalString.INSTANCE.Read(stream), + Order: FfiConverterInt64.INSTANCE.Read(stream), + CreatedAtMs: FfiConverterInt64.INSTANCE.Read(stream), + UpdatedAtMs: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Keyword) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionName) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.FolderId) + + FfiConverterInt64.INSTANCE.AllocationSize(value.Order) + + FfiConverterInt64.INSTANCE.AllocationSize(value.CreatedAtMs) + + FfiConverterInt64.INSTANCE.AllocationSize(value.UpdatedAtMs); + } + + public override void Write(SavedQueryRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.Sql, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Keyword, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterString.INSTANCE.Write(value.ConnectionName, stream); + FfiConverterOptionalString.INSTANCE.Write(value.FolderId, stream); + FfiConverterInt64.INSTANCE.Write(value.Order, stream); + FfiConverterInt64.INSTANCE.Write(value.CreatedAtMs, stream); + FfiConverterInt64.INSTANCE.Write(value.UpdatedAtMs, stream); + } +} + + + +internal record SavedQueryRecordWrite ( + SavedQueryRecord[] Queries, + SavedQueryFolderRecord[] Folders, + string[] RemovedQueries, + string[] RemovedFolders +) { +} + +class FfiConverterTypeSavedQueryRecordWrite: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryRecordWrite INSTANCE = new FfiConverterTypeSavedQueryRecordWrite(); + + public override SavedQueryRecordWrite Read(BigEndianStream stream) { + return new SavedQueryRecordWrite( + Queries: FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.Read(stream), + Folders: FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.Read(stream), + RemovedQueries: FfiConverterSequenceString.INSTANCE.Read(stream), + RemovedFolders: FfiConverterSequenceString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryRecordWrite value) { + return 0 + + FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.AllocationSize(value.Queries) + + FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.AllocationSize(value.Folders) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.RemovedQueries) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.RemovedFolders); + } + + public override void Write(SavedQueryRecordWrite value, BigEndianStream stream) { + FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.Write(value.Queries, stream); + FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.Write(value.Folders, stream); + FfiConverterSequenceString.INSTANCE.Write(value.RemovedQueries, stream); + FfiConverterSequenceString.INSTANCE.Write(value.RemovedFolders, stream); + } +} + + + +internal record SavedQueryStoreContents ( + SavedQueryRecord[] Queries, + SavedQueryFolderRecord[] Folders, + string Digest +) { +} + +class FfiConverterTypeSavedQueryStoreContents: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryStoreContents INSTANCE = new FfiConverterTypeSavedQueryStoreContents(); + + public override SavedQueryStoreContents Read(BigEndianStream stream) { + return new SavedQueryStoreContents( + Queries: FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.Read(stream), + Folders: FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.Read(stream), + Digest: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryStoreContents value) { + return 0 + + FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.AllocationSize(value.Queries) + + FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.AllocationSize(value.Folders) + + FfiConverterString.INSTANCE.AllocationSize(value.Digest); + } + + public override void Write(SavedQueryStoreContents value, BigEndianStream stream) { + FfiConverterSequenceTypeSavedQueryRecord.INSTANCE.Write(value.Queries, stream); + FfiConverterSequenceTypeSavedQueryFolderRecord.INSTANCE.Write(value.Folders, stream); + FfiConverterString.INSTANCE.Write(value.Digest, stream); + } +} + + + +internal record SavedQueryWriteOutcome ( + string[] SettledQueries, + string[] SettledFolders, + string Digest +) { +} + +class FfiConverterTypeSavedQueryWriteOutcome: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryWriteOutcome INSTANCE = new FfiConverterTypeSavedQueryWriteOutcome(); + + public override SavedQueryWriteOutcome Read(BigEndianStream stream) { + return new SavedQueryWriteOutcome( + SettledQueries: FfiConverterSequenceString.INSTANCE.Read(stream), + SettledFolders: FfiConverterSequenceString.INSTANCE.Read(stream), + Digest: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryWriteOutcome value) { + return 0 + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.SettledQueries) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.SettledFolders) + + FfiConverterString.INSTANCE.AllocationSize(value.Digest); + } + + public override void Write(SavedQueryWriteOutcome value, BigEndianStream stream) { + FfiConverterSequenceString.INSTANCE.Write(value.SettledQueries, stream); + FfiConverterSequenceString.INSTANCE.Write(value.SettledFolders, stream); + FfiConverterString.INSTANCE.Write(value.Digest, stream); + } +} + + + internal record SchemaEntry ( string Name, bool IsDefault, @@ -29300,6 +30482,78 @@ public override void Write(TableFolderRecord value, BigEndianStream stream) { +internal record TableFolderRecordWrite ( + TableFolderRecord[] Folders, + TablePlacementRecord[] Items, + string[] RemovedFolders, + TableKeyRecord[] RemovedItems +) { +} + +class FfiConverterTypeTableFolderRecordWrite: FfiConverterRustBuffer { + public static FfiConverterTypeTableFolderRecordWrite INSTANCE = new FfiConverterTypeTableFolderRecordWrite(); + + public override TableFolderRecordWrite Read(BigEndianStream stream) { + return new TableFolderRecordWrite( + Folders: FfiConverterSequenceTypeTableFolderRecord.INSTANCE.Read(stream), + Items: FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.Read(stream), + RemovedFolders: FfiConverterSequenceString.INSTANCE.Read(stream), + RemovedItems: FfiConverterSequenceTypeTableKeyRecord.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TableFolderRecordWrite value) { + return 0 + + FfiConverterSequenceTypeTableFolderRecord.INSTANCE.AllocationSize(value.Folders) + + FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.AllocationSize(value.Items) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.RemovedFolders) + + FfiConverterSequenceTypeTableKeyRecord.INSTANCE.AllocationSize(value.RemovedItems); + } + + public override void Write(TableFolderRecordWrite value, BigEndianStream stream) { + FfiConverterSequenceTypeTableFolderRecord.INSTANCE.Write(value.Folders, stream); + FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.Write(value.Items, stream); + FfiConverterSequenceString.INSTANCE.Write(value.RemovedFolders, stream); + FfiConverterSequenceTypeTableKeyRecord.INSTANCE.Write(value.RemovedItems, stream); + } +} + + + +internal record TableFolderStoreContents ( + TableFolderRecord[] Folders, + TablePlacementRecord[] Items, + string Digest +) { +} + +class FfiConverterTypeTableFolderStoreContents: FfiConverterRustBuffer { + public static FfiConverterTypeTableFolderStoreContents INSTANCE = new FfiConverterTypeTableFolderStoreContents(); + + public override TableFolderStoreContents Read(BigEndianStream stream) { + return new TableFolderStoreContents( + Folders: FfiConverterSequenceTypeTableFolderRecord.INSTANCE.Read(stream), + Items: FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.Read(stream), + Digest: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TableFolderStoreContents value) { + return 0 + + FfiConverterSequenceTypeTableFolderRecord.INSTANCE.AllocationSize(value.Folders) + + FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.AllocationSize(value.Items) + + FfiConverterString.INSTANCE.AllocationSize(value.Digest); + } + + public override void Write(TableFolderStoreContents value, BigEndianStream stream) { + FfiConverterSequenceTypeTableFolderRecord.INSTANCE.Write(value.Folders, stream); + FfiConverterSequenceTypeTablePlacementRecord.INSTANCE.Write(value.Items, stream); + FfiConverterString.INSTANCE.Write(value.Digest, stream); + } +} + + + internal record TableInfoRecord ( RowEstimate Rows, string? Comment, @@ -29342,6 +30596,36 @@ public override void Write(TableInfoRecord value, BigEndianStream stream) { +internal record TableKeyRecord ( + string ConnectionId, + TableRefRecord Table +) { +} + +class FfiConverterTypeTableKeyRecord: FfiConverterRustBuffer { + public static FfiConverterTypeTableKeyRecord INSTANCE = new FfiConverterTypeTableKeyRecord(); + + public override TableKeyRecord Read(BigEndianStream stream) { + return new TableKeyRecord( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + Table: FfiConverterTypeTableRefRecord.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TableKeyRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterTypeTableRefRecord.INSTANCE.AllocationSize(value.Table); + } + + public override void Write(TableKeyRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterTypeTableRefRecord.INSTANCE.Write(value.Table, stream); + } +} + + + /// /// A table, named the way the server qualifies it. No schema means the /// engine has none, or the connection's default one. @@ -29376,6 +30660,40 @@ public override void Write(TableName value, BigEndianStream stream) { +internal record TablePlacementRecord ( + string ConnectionId, + TableRefRecord Table, + string FolderId +) { +} + +class FfiConverterTypeTablePlacementRecord: FfiConverterRustBuffer { + public static FfiConverterTypeTablePlacementRecord INSTANCE = new FfiConverterTypeTablePlacementRecord(); + + public override TablePlacementRecord Read(BigEndianStream stream) { + return new TablePlacementRecord( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + Table: FfiConverterTypeTableRefRecord.INSTANCE.Read(stream), + FolderId: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TablePlacementRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterTypeTableRefRecord.INSTANCE.AllocationSize(value.Table) + + FfiConverterString.INSTANCE.AllocationSize(value.FolderId); + } + + public override void Write(TablePlacementRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterTypeTableRefRecord.INSTANCE.Write(value.Table, stream); + FfiConverterString.INSTANCE.Write(value.FolderId, stream); + } +} + + + internal record TableRefRecord ( string Database, string Schema, @@ -44186,6 +45504,98 @@ public override void Write(FavouriteDatabaseInfo[] value, BigEndianStream stream +class FfiConverterSequenceTypeFavouriteDatabaseKey: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteDatabaseKey INSTANCE = new FfiConverterSequenceTypeFavouriteDatabaseKey(); + + public override FavouriteDatabaseKey[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new FavouriteDatabaseKey[length]; + var readFn = FfiConverterTypeFavouriteDatabaseKey.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(FavouriteDatabaseKey[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeFavouriteDatabaseKey.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(FavouriteDatabaseKey[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeFavouriteDatabaseKey.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeFavouriteDatabaseRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteDatabaseRecord INSTANCE = new FfiConverterSequenceTypeFavouriteDatabaseRecord(); + + public override FavouriteDatabaseRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new FavouriteDatabaseRecord[length]; + var readFn = FfiConverterTypeFavouriteDatabaseRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(FavouriteDatabaseRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeFavouriteDatabaseRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(FavouriteDatabaseRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeFavouriteDatabaseRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeFavouriteTableInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeFavouriteTableInfo INSTANCE = new FfiConverterSequenceTypeFavouriteTableInfo(); @@ -44232,6 +45642,52 @@ public override void Write(FavouriteTableInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeFavouriteTableRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteTableRecord INSTANCE = new FfiConverterSequenceTypeFavouriteTableRecord(); + + public override FavouriteTableRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new FavouriteTableRecord[length]; + var readFn = FfiConverterTypeFavouriteTableRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(FavouriteTableRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeFavouriteTableRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(FavouriteTableRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeFavouriteTableRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeFilterColumn: FfiConverterRustBuffer { public static FfiConverterSequenceTypeFilterColumn INSTANCE = new FfiConverterSequenceTypeFilterColumn(); @@ -44692,6 +46148,52 @@ public override void Write(HistoryEntryInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeHistoryEntryRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeHistoryEntryRecord INSTANCE = new FfiConverterSequenceTypeHistoryEntryRecord(); + + public override HistoryEntryRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new HistoryEntryRecord[length]; + var readFn = FfiConverterTypeHistoryEntryRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(HistoryEntryRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeHistoryEntryRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(HistoryEntryRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeHistoryEntryRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeImportColumnInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeImportColumnInfo INSTANCE = new FfiConverterSequenceTypeImportColumnInfo(); @@ -45704,6 +47206,52 @@ public override void Write(SavedQueryFolderInfo[] value, BigEndianStream stream) +class FfiConverterSequenceTypeSavedQueryFolderRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeSavedQueryFolderRecord INSTANCE = new FfiConverterSequenceTypeSavedQueryFolderRecord(); + + public override SavedQueryFolderRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new SavedQueryFolderRecord[length]; + var readFn = FfiConverterTypeSavedQueryFolderRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(SavedQueryFolderRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeSavedQueryFolderRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(SavedQueryFolderRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeSavedQueryFolderRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeSavedQueryInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeSavedQueryInfo INSTANCE = new FfiConverterSequenceTypeSavedQueryInfo(); @@ -45750,6 +47298,52 @@ public override void Write(SavedQueryInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeSavedQueryRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeSavedQueryRecord INSTANCE = new FfiConverterSequenceTypeSavedQueryRecord(); + + public override SavedQueryRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new SavedQueryRecord[length]; + var readFn = FfiConverterTypeSavedQueryRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(SavedQueryRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeSavedQueryRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(SavedQueryRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeSavedQueryRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeSchemaEntry: FfiConverterRustBuffer { public static FfiConverterSequenceTypeSchemaEntry INSTANCE = new FfiConverterSequenceTypeSchemaEntry(); @@ -46486,6 +48080,52 @@ public override void Write(TableFolderRecord[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeTableKeyRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeTableKeyRecord INSTANCE = new FfiConverterSequenceTypeTableKeyRecord(); + + public override TableKeyRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new TableKeyRecord[length]; + var readFn = FfiConverterTypeTableKeyRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(TableKeyRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeTableKeyRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(TableKeyRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeTableKeyRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeTableName: FfiConverterRustBuffer { public static FfiConverterSequenceTypeTableName INSTANCE = new FfiConverterSequenceTypeTableName(); @@ -46532,6 +48172,52 @@ public override void Write(TableName[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeTablePlacementRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeTablePlacementRecord INSTANCE = new FfiConverterSequenceTypeTablePlacementRecord(); + + public override TablePlacementRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new TablePlacementRecord[length]; + var readFn = FfiConverterTypeTablePlacementRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(TablePlacementRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeTablePlacementRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(TablePlacementRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeTablePlacementRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeTableRefRecord: FfiConverterRustBuffer { public static FfiConverterSequenceTypeTableRefRecord INSTANCE = new FfiConverterSequenceTypeTableRefRecord(); From 372ad690b0465204920ecb338f76d8c22b2d8287 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 16:17:34 +0700 Subject: [PATCH 2/5] fix(core): history delete by connection, and the store digest checked before validation --- core/crates/ffi/src/host_stores.rs | 21 ++++++-- core/crates/ffi/tests/host_stores.rs | 11 +++- core/crates/storage/src/favourites_batch.rs | 11 ++-- .../crates/storage/src/table_folders/batch.rs | 7 +-- .../Generated/tablepro_ffi.cs | 54 +++++++++++++++++++ 5 files changed, 91 insertions(+), 13 deletions(-) diff --git a/core/crates/ffi/src/host_stores.rs b/core/crates/ffi/src/host_stores.rs index 1d48cc5dac..b50902fd53 100644 --- a/core/crates/ffi/src/host_stores.rs +++ b/core/crates/ffi/src/host_stores.rs @@ -1,6 +1,6 @@ -// Whole-store reads and writes for a host that keeps a store of its own beside the core's while it moves in, each -// record under its own id (core ADR 0010, slices 3 and 9). A write names the digest it was based on where it -// replaces a whole store, so a change the host never read is refused rather than lost. +// Whole-store reads and writes for an app that keeps these records itself, or moves them in from a store of its own: +// the Mac and iOS apps, each record under its own id (core ADR 0010, slices 3 and 9). A write names the digest it was +// based on where it replaces a whole store, so a change the app never read is refused rather than lost. use tablepro_storage::query_history::{NewEntry, Outcome}; use tablepro_storage::saved_queries::SavedQuery; @@ -341,7 +341,10 @@ impl TableFolderStore { #[uniffi::export] impl QueryHistoryStore { - // In one commit. An entry the store already holds keeps its row. Returns how many were new. + // Runs the app recorded itself, with their outcome and error text, or moved in from its own store, in one commit. + // An entry the store already holds keeps its row. The engines' rules for statements that carry a secret live in + // their drivers, which an Apple build does not link, so the app passes only runs it keeps. Returns how many were + // new. pub async fn put_entries(&self, entries: Vec) -> Result { let entries: Vec = entries.into_iter().map(NewEntry::try_from).collect::>()?; let history = self.history.clone(); @@ -362,6 +365,16 @@ impl QueryHistoryStore { .await } + // Every run of the connection, pinned ones included, for a connection deleted with its history. + pub async fn delete_for_connection(&self, connection_id: String) -> Result { + let connection = parse_id(&connection_id)?; + let history = self.history.clone(); + on_runtime(&self.tasks, async move { + Ok(history.delete_for_connection(connection).await?) + }) + .await + } + // By record id. Returns how many were there. pub async fn remove_entries(&self, record_ids: Vec) -> Result { let ids = parse_ids(&record_ids)?; diff --git a/core/crates/ffi/tests/host_stores.rs b/core/crates/ffi/tests/host_stores.rs index c8cba2c946..dfc70d198b 100644 --- a/core/crates/ffi/tests/host_stores.rs +++ b/core/crates/ffi/tests/host_stores.rs @@ -254,11 +254,20 @@ async fn history_entries_move_in_under_their_record_ids() { outcome: HistoryOutcomeTag::Succeeded, }; - let added = history.put_entries(vec![run.clone(), run]).await.unwrap(); + let added = history.put_entries(vec![run.clone(), run.clone()]).await.unwrap(); assert_eq!(added, 1); let ids = history.record_ids().await.unwrap(); assert_eq!(ids.iter().map(|id| id.to_uppercase()).collect::>(), [RUN]); assert_eq!(history.remove_entries(ids).await.unwrap(), 1); assert!(history.record_ids().await.unwrap().is_empty()); + + let other = HistoryEntryRecord { + record_id: QUERY.to_owned(), + connection_id: FOLDER.to_owned(), + ..run.clone() + }; + history.put_entries(vec![run, other]).await.unwrap(); + assert_eq!(history.delete_for_connection(SHOP.to_owned()).await.unwrap(), 1); + assert_eq!(history.record_ids().await.unwrap().len(), 1); } diff --git a/core/crates/storage/src/favourites_batch.rs b/core/crates/storage/src/favourites_batch.rs index c07077150e..cde358123e 100644 --- a/core/crates/storage/src/favourites_batch.rs +++ b/core/crates/storage/src/favourites_batch.rs @@ -92,11 +92,6 @@ impl Favourites { replace: Option<(Kind, Option<&str>)>, write: &FavouriteWrite, ) -> Result { - if write.tables.iter().any(|table| table.name.is_empty()) - || write.databases.iter().any(|database| database.database.is_empty()) - { - return Err(StorageError::EmptyName); - } let mut connection = self.pool.acquire().await?; let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; let (removed_tables, removed_databases) = match replace { @@ -132,6 +127,12 @@ impl Favourites { } None => (write.removed_tables.clone(), write.removed_databases.clone()), }; + // After the digest check, so a store that moved is refused as outdated whatever the write holds. + if write.tables.iter().any(|table| table.name.is_empty()) + || write.databases.iter().any(|database| database.database.is_empty()) + { + return Err(StorageError::EmptyName); + } trim_upgrade_copies(&self.path, ©_deletes(&removed_tables, &removed_databases)).await?; let (gone_tables, gone_databases) = remove(&mut transaction, &removed_tables, &removed_databases).await?; let (marked_tables, marked_databases) = mark(&mut transaction, write).await?; diff --git a/core/crates/storage/src/table_folders/batch.rs b/core/crates/storage/src/table_folders/batch.rs index 29f501f396..64d06fdd49 100644 --- a/core/crates/storage/src/table_folders/batch.rs +++ b/core/crates/storage/src/table_folders/batch.rs @@ -63,9 +63,6 @@ impl TableFolders { } async fn commit(&self, replace: Option>, write: &TableFolderWrite) -> Result { - for folder in &write.folders { - checked_name(&folder.name)?; - } let mut connection = self.pool.acquire().await?; let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; let (removed_folders, removed_items) = match replace { @@ -92,6 +89,10 @@ impl TableFolders { } None => (write.removed_folders.clone(), write.removed_items.clone()), }; + // After the digest check, so a store that moved is refused as outdated whatever the write holds. + for folder in &write.folders { + checked_name(&folder.name)?; + } trim_upgrade_copies(&self.path, ©_deletes(&removed_folders, &removed_items)).await?; let (gone_folders, gone_items) = remove(&mut transaction, &removed_folders, &removed_items).await?; let (wrote_folders, wrote_items) = put(&mut transaction, write).await?; diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 851cf97778..692f7eb012 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1843,6 +1843,8 @@ public struct UniffiVTableCallbackInterfaceCloudKitTransport + + @@ -3165,6 +3167,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_table_folders(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_delete_for_connection(ulong @ptr,RustBuffer @connectionId + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -8181,6 +8194,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_table_folders( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete_for_connection( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -11674,6 +11698,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_table_folders` checksum `54603`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete_for_connection(); + if (checksum != 38619) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete_for_connection` checksum `38619`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_put_entries(); if (checksum != 32732) { @@ -19393,6 +19423,8 @@ internal interface IQueryHistoryStore { Task SetPinned(long @id, bool @pinned); TableFolderStore TableFolders(); /// + Task DeleteForConnection(string @connectionId); + /// Task PutEntries(HistoryEntryRecord[] @entries); /// Task RecordIds(); @@ -19650,6 +19682,28 @@ public TableFolderStore TableFolders() { } + /// + public async Task DeleteForConnection(string @connectionId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_delete_for_connection(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task PutEntries(HistoryEntryRecord[] @entries) { return await _UniFFIAsync.UniffiRustCallAsync( From 276cab666865d3ba17d0955267b5cac31c84e9b0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Thu, 26 Nov 2026 17:19:39 +0700 Subject: [PATCH 3/5] feat(macos): saved queries, favourites, table folders and history copied into the core's history.db --- .claude/rules/data-sync-storage.md | 10 +- .../Infrastructure/PostLaunchWork.swift | 7 + .../CoreMirror/CoreHistoryDatabase.swift | 98 +++++ .../Core/Storage/CoreMirror/CoreMirror.swift | 326 ++++++++++++++ .../CoreMirror/FavoriteCoreAdapters.swift | 401 ++++++++++++++++++ .../CoreMirror/QueryHistoryCoreMirror.swift | 183 ++++++++ .../CoreMirror/SavedQueryCoreAdapter.swift | 275 ++++++++++++ .../Storage/FavoriteDatabasesStorage.swift | 28 +- .../Core/Storage/FavoriteTablesStorage.swift | 35 +- .../Core/Storage/QueryHistoryManager.swift | 71 +++- .../QueryHistoryStorage+CoreMirror.swift | 137 ++++++ .../Core/Storage/QueryHistoryStorage.swift | 3 + .../Core/Storage/SQLFavoriteManager.swift | 77 +++- .../SQLFavoriteStorage+CoreMirror.swift | 143 +++++++ .../Core/Storage/TableFolderStorage.swift | 53 ++- .../TablePro/Core/Sync/SyncCoordinator.swift | 18 +- .../CoreMirror/CoreMirrorFixture.swift | 31 ++ .../CoreMirror/FavoriteCoreMirrorTests.swift | 148 +++++++ .../QueryHistoryCoreMirrorTests.swift | 109 +++++ .../SavedQueryCoreMirrorTests.swift | 239 +++++++++++ .../scripts/probes/check-history-downgrade.sh | 134 ++++++ 21 files changed, 2476 insertions(+), 50 deletions(-) create mode 100644 apple/TablePro/Core/Storage/CoreMirror/CoreHistoryDatabase.swift create mode 100644 apple/TablePro/Core/Storage/CoreMirror/CoreMirror.swift create mode 100644 apple/TablePro/Core/Storage/CoreMirror/FavoriteCoreAdapters.swift create mode 100644 apple/TablePro/Core/Storage/CoreMirror/QueryHistoryCoreMirror.swift create mode 100644 apple/TablePro/Core/Storage/CoreMirror/SavedQueryCoreAdapter.swift create mode 100644 apple/TablePro/Core/Storage/QueryHistoryStorage+CoreMirror.swift create mode 100644 apple/TablePro/Core/Storage/SQLFavoriteStorage+CoreMirror.swift create mode 100644 apple/TableProTests/Core/Storage/CoreMirror/CoreMirrorFixture.swift create mode 100644 apple/TableProTests/Core/Storage/CoreMirror/FavoriteCoreMirrorTests.swift create mode 100644 apple/TableProTests/Core/Storage/CoreMirror/QueryHistoryCoreMirrorTests.swift create mode 100644 apple/TableProTests/Core/Storage/CoreMirror/SavedQueryCoreMirrorTests.swift create mode 100755 apple/scripts/probes/check-history-downgrade.sh diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index 5c70f1c241..445313ffdd 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -165,14 +165,20 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Appearance mode (Auto, Light, Dark) | UserDefaults, device-local, never synced | `AppSettingsStorage` through `AppSettingsManager.appearanceMode` | | Light and dark theme ids (iCloud-synced, category `appearance`) | UserDefaults | `AppearanceSettings` through `AppSettingsManager` | | User themes (iCloud-synced, one `AppSettings` record `theme.` each) | JSON, one file per theme | `ThemeCatalog` (sync rules: `.claude/rules/theme.md`, Sync) | -| Query history | SQLite FTS5 | `QueryHistoryStorage` | +| Query history | SQLite FTS5 `query_history.db`, which the History pane, Insights and the plan and Rewind snapshots read; each run, deletion, clear and retention pass also reaches the core's history under the run's id, and a deletion or clear reports a failure while the core still holds what went | `QueryHistoryStorage`, copied by `QueryHistoryCoreMirror` | +| Saved queries and their folders (iCloud-synced) | SQLite `sql_favorites.db`, which this build and the previous stable read; each write also reaches the core's copy | `SQLFavoriteStorage` through `SQLFavoriteManager`, copied by `CoreMirror` | +| The core's copy of the saved queries and folders, the favourite tables and databases, the table folders and the history (core ADR 0010, slices 3 and 9), each under the Mac's id. A launch takes in what changed in the Swift stores, the previous stable's edits included, and a write that reached only the core goes back to them. A collision the core settles (ADR 0052) is written back and marked dirty | SQLite `Core/state/history.db` in the support directory | the core's `tablepro-storage` through `CoreHistoryDatabase` | +| What a Swift store and the core's copy held when they last agreed, a digest per record, so a push tells which side changed each one. A record either side changed goes to the other, the Swift store's version when both did; one the core refused keeps its last agreement and goes again | UserDefaults `com.TablePro.coreMirror.savedQueries`, `.favoriteTables`, `.favoriteDatabases`, `.tableFolders`, device-local, never synced | `CoreMirror` | +| The runs `query_history.db` and the core's history both held when they last agreed, so a run leaves the core only when it left the Mac's store after that. In the same file, so a damaged one set aside takes it along and the core keeps its runs; the previous stable never touches it | Table `core_mirror` in `query_history.db` | `QueryHistoryCoreMirror` | | Query tab edit history: up to 50 versions per tab, kept 30 days or the shorter Query History window, after the tab closes too; purged with the connection and by Clear History | SQLite `query_tab_versions.db`, device-local, never synced | `QueryTabVersionStorage` | | Tab state | JSON | `TabPersistenceCoordinator`, `TabDiskActor` | | Filter defaults and presets | UserDefaults | `FilterSettingsStorage`, `FilterPresetStorage` | | Per-table filters | JSON, one file per table | `FilterSettingsStorage` | | Generate Rows settings per table | UserDefaults, device-local | `RowGenerationSettingsStore` | | Row inspector field heights, per column name | UserDefaults, device-local | `InspectorFieldHeightStore` | -| Favorite tables (iCloud-synced) | UserDefaults | `FavoriteTablesStorage` | +| Favorite tables (iCloud-synced) | UserDefaults; each change also reaches the core's copy | `FavoriteTablesStorage` | +| Favorite databases and their environment (iCloud-synced) | UserDefaults `com.TablePro.favoriteDatabases`; each change also reaches the core's copy | `FavoriteDatabasesStorage` | +| Table folders and what they hold (iCloud-synced) | UserDefaults, one document per connection under `com.TablePro.tableFolders.`; each change also reaches the core's copy | `TableFolderStorage` | | Team library read cache, per server and account: each team's pull cursor and items (synced with tablepro-cloud's `/v2`, never iCloud). Unsent edits stay in memory only; the library 0.88 and earlier kept, with its unsent edits, is read once for the tablepro.app sign-in the core restores, behind the UserDefaults flag `com.TablePro.teamLibrary.earlierLibraryConsidered`, then deleted; its edits are uploaded once (`TeamLibrarySync` has the rules) | JSON, one file per team in `TeamLibraryCache//`; 0.88 and earlier: `TeamLibrary/` and `team_library.json` | `TeamLibraryStorage` through `TeamLibrarySync` | | TablePro account: the device, the entitlement, the chosen server, a company server's license and entitlement keys | `Account/account.json` in Application Support, device-local, never synced | the core's `tablepro-account` through `AccountServices` | | The account's refresh token: tablepro.app's in the item earlier builds read, each company server's in its own | Keychain `com.TablePro.account.refreshToken`, and one item per company server, device-only | the core through `KeychainHostSecrets` | diff --git a/apple/TablePro/Core/Services/Infrastructure/PostLaunchWork.swift b/apple/TablePro/Core/Services/Infrastructure/PostLaunchWork.swift index fd1bb6268e..70b560c129 100644 --- a/apple/TablePro/Core/Services/Infrastructure/PostLaunchWork.swift +++ b/apple/TablePro/Core/Services/Infrastructure/PostLaunchWork.swift @@ -29,6 +29,13 @@ internal enum PostLaunchWork { Task { await PluginManager.shared.sweepPluginSignatures() } Task { await QueryHistoryManager.shared.performStartupCleanup() } + // The core's history.db takes in what the stores the previous stable reads hold (core ADR 0010, slices 3 and 9). + Task { + await SQLFavoriteManager.shared.pushToCore() + await FavoriteTablesStorage.shared.coreMirror?.push() + await FavoriteDatabasesStorage.shared.coreMirror?.push() + await TableFolderStorage.shared.coreMirror?.push() + } let supportDirectory = AppStorageEnvironment.shared.supportDirectory Task.detached(priority: .utility) { RetiredTableLoadHistory.remove(in: supportDirectory) } SignInPrompt.live.presentIfNeeded() diff --git a/apple/TablePro/Core/Storage/CoreMirror/CoreHistoryDatabase.swift b/apple/TablePro/Core/Storage/CoreMirror/CoreHistoryDatabase.swift new file mode 100644 index 0000000000..6341c4d6d3 --- /dev/null +++ b/apple/TablePro/Core/Storage/CoreMirror/CoreHistoryDatabase.swift @@ -0,0 +1,98 @@ +// +// CoreHistoryDatabase.swift +// TablePro +// + +import Foundation +import os +import TableProFFI +import TableProLogRedaction + +// The core's history.db (core ADR 0060): the saved queries and their folders, the favourite tables and databases, +// the table folders and the history, in one file under `TablePro/Core/`. Opened on first use; a failed open is +// tried again on the next call. +internal actor CoreHistoryDatabase { + internal static let shared = CoreHistoryDatabase( + folder: AppStorageEnvironment.shared.supportDirectory.appendingPathComponent("Core", isDirectory: true) + ) + + private static let logger = Logger(subsystem: "com.TablePro", category: "CoreHistoryDatabase") + + nonisolated internal let folder: URL + private let clientVersion: String + private var core: Core? + private var store: QueryHistoryStore? + + internal init(folder: URL, clientVersion: String = CoreHistoryDatabase.appVersion) { + self.folder = folder + self.clientVersion = clientVersion + } + + nonisolated internal static var appVersion: String { + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" + } + + internal func history() async throws -> QueryHistoryStore { + if let store { return store } + do { + // Private as the core keeps its own folders, since history.db holds the SQL a person ran. + try FileManager.default.createDirectory( + at: folder, + withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700] + ) + let core = try self.core ?? Core( + config: HostConfig(clientVersion: clientVersion, storageDir: folder.path), + secrets: NoHistorySecrets() + ) + self.core = core + let opened = try await core.history() + store = opened + return opened + } catch { + Self.logger.error("The core's history store did not open: \(LogRedaction.publicDescription(of: error), privacy: .public)") + throw error + } + } + + internal func savedQueries() async throws -> SavedQueryStore { + try await history().savedQueries() + } + + internal func favourites() async throws -> FavouriteStore { + try await history().favourites() + } + + internal func tableFolders() async throws -> TableFolderStore { + try await history().tableFolders() + } +} + +// A whole-store write the core refused because the store moved since it was read (storage.import_outdated). +internal func refusingOutdated(_ work: () async throws -> Void) async throws { + do { + try await work() + } catch CoreError.Failed(let info) where info.code == "storage.import_outdated" { + throw CoreMirrorError.outdated + } +} + +// Nothing in history.db is a secret, and this core is opened for that file alone. +private final class NoHistorySecrets: HostSecrets, Sendable { + func load(connectionId: String, kind: SecretKindTag) throws -> String? { nil } + + func store(connectionId: String, kind: SecretKindTag, secret: String, label: String) throws { + throw HostSecretError.Unavailable(detail: "the history store keeps no secrets") + } + + func relabel(connectionId: String, kind: SecretKindTag, label: String) throws {} + func delete(connectionId: String, kind: SecretKindTag) throws {} + func deleteConnection(connectionId: String) throws {} + func loadItem(item: SecretItemTag) throws -> String? { nil } + + func storeItem(item: SecretItemTag, secret: String) throws { + throw HostSecretError.Unavailable(detail: "the history store keeps no secrets") + } + + func deleteItem(item: SecretItemTag) throws {} +} diff --git a/apple/TablePro/Core/Storage/CoreMirror/CoreMirror.swift b/apple/TablePro/Core/Storage/CoreMirror/CoreMirror.swift new file mode 100644 index 0000000000..8abf9e5bc7 --- /dev/null +++ b/apple/TablePro/Core/Storage/CoreMirror/CoreMirror.swift @@ -0,0 +1,326 @@ +// +// CoreMirror.swift +// TablePro +// + +import CryptoKit +import Foundation +import os +import TableProLogRedaction + +// A Swift store the previous stable reads, and the core's copy of it in history.db, each record under its own id +// (core ADR 0010, slices 3 and 9). The Swift store stays what this build reads and writes first; every write +// reaches the core after it, and a push compares both sides record by record with what they held when they last +// agreed, so a change on either side, the previous stable's included, goes to the other. +internal protocol CoreMirrorAdapter: Sendable { + associatedtype Key: Hashable & Sendable & Encodable + associatedtype Value: Equatable & Sendable & Encodable + + var name: String { get } + func key(of value: Value) -> Key + // Nil when the Swift store cannot be read: nothing goes to the core then. + func readLegacy() async -> CoreMirrorLegacyRead? + func readCore() async throws -> CoreMirrorCoreRead + func writeCore(puts: [Value], removals: [Key]) async throws + // Whole, refused with `CoreMirrorError.outdated` when the core no longer holds what `expected` names. + func replaceCore(expected: String, values: [Value]) async throws + // Only when every key touched still holds what `expected` gives (absent where it has none), checked in the same + // step as the write, so an edit made since the read is never written over; false writes nothing. + func applyToLegacy(puts: [Value], removals: [Key], expected: [Key: Value]) async -> Bool + // Values the core changed to settle a collision: this Mac's own edits, which sync like any other. + func announce(settled: [Value]) async +} + +internal struct CoreMirrorLegacyRead: Sendable { + let values: [Value] + // False while the store holds less than it should: a damaged file set aside and waiting for a refill, or a + // document that does not read. A record missing from it is then not taken for a deletion. + let allowsRemovals: Bool +} + +internal struct CoreMirrorCoreRead: Sendable { + let values: [Value] + let digest: String +} + +internal enum CoreMirrorError: Error { + case outdated +} + +internal actor CoreMirror { + private typealias Side = [String: (key: Adapter.Key, value: Adapter.Value)] + + private static var logger: Logger { Logger(subsystem: "com.TablePro", category: "CoreMirror") } + + nonisolated internal let adapter: Adapter + private let defaults: UserDefaults + private var tail: Task? + // A push asked for and not started yet already covers every write before it starts. + private var waiting = false + + internal init(adapter: Adapter, defaults: UserDefaults) { + self.adapter = adapter + self.defaults = defaults + } + + nonisolated internal var baseKey: String { + "com.TablePro.coreMirror.\(adapter.name)" + } + + nonisolated internal func schedulePush() { + Task { await self.requestPush() } + } + + private func requestPush() async { + guard !waiting else { return } + await push() + } + + // Runs after every push asked for before it, so a write is never compared against an older one's result. False + // when the core could not be read or refused the write, so the two may still differ. + @discardableResult + internal func push() async -> Bool { + waiting = true + let previous = tail + let run = Task { [self] in + _ = await previous?.value + return await pushOnce() + } + tail = run + return await run.value + } + + // Each record's key, encoded, with the digest of the value both sides held when they last agreed. Nil before the + // first push. + internal var base: [String: String]? { + guard let data = defaults.data(forKey: baseKey) else { return nil } + return try? JSONDecoder().decode([String: String].self, from: data) + } + + private func save(_ base: [String: String]) { + guard let data = try? JSONEncoder().encode(base) else { return } + defaults.set(data, forKey: baseKey) + } + + private func pushOnce() async -> Bool { + waiting = false + guard let legacy = await adapter.readLegacy() else { return false } + let core: CoreMirrorCoreRead + do { + core = try await adapter.readCore() + } catch { + log("the core could not be read", error) + return false + } + let mine = side(legacy.values) + let theirs = side(core.values) + guard let base else { + return await moveIn(legacy, mine: mine, core: core, theirs: theirs) + } + var toCore: [Adapter.Value] = [] + var coreRemovals: [Adapter.Key] = [] + var toLegacy: [Adapter.Value] = [] + var legacyRemovals: [Adapter.Key] = [] + for code in Set(mine.keys).union(theirs.keys).union(base.keys) { + let held = mine[code] + let copy = theirs[code] + let legacyChanged = (held != nil || legacy.allowsRemovals) && digest(held?.value) != base[code] + let coreChanged = digest(copy?.value) != base[code] + // A record both sides changed takes the Swift store's version, which the person last saw. + if legacyChanged { + if let held, held.value != copy?.value { + toCore.append(held.value) + } else if held == nil, let copy { + coreRemovals.append(copy.key) + } + } else if coreChanged { + if let copy, copy.value != held?.value { + toLegacy.append(copy.value) + } else if copy == nil, let held { + legacyRemovals.append(held.key) + } + } + } + let refused: Set + do { + refused = try await send(puts: toCore, removals: coreRemovals) + } catch { + log("the core refused the write", error) + return false + } + var current = mine + if !toLegacy.isEmpty || !legacyRemovals.isEmpty { + let unchanged = expected(mine, toLegacy, legacyRemovals) + if await adapter.applyToLegacy(puts: toLegacy, removals: legacyRemovals, expected: unchanged) { + apply(toLegacy, legacyRemovals, to: ¤t) + } else { + Self.logger.notice("\(self.adapter.name, privacy: .public): the store changed during the push; the next one takes it") + } + } + return await settle(written: toCore, refused: refused, base: base, current: current, before: theirs) + && refused.isEmpty + } + + // The first push: the core comes to hold exactly the Swift store, refused when the core moved since the read. + private func moveIn( + _ legacy: CoreMirrorLegacyRead, + mine: Side, + core: CoreMirrorCoreRead, + theirs: Side + ) async -> Bool { + var refused: Set = [] + do { + try await moveWhole(legacy, core: core) + } catch CoreMirrorError.outdated { + Self.logger.notice("\(self.adapter.name, privacy: .public): the core changed during the first push; the next one tries again") + return false + } catch { + // A record the core refuses fails the whole write, which then goes one record at a time. The core + // matched the read when it refused, so removing what the read saw removes nothing newer. A store that + // holds less than it should removes nothing. + let puts = legacy.values.filter { theirs[code(of: $0)]?.value != $0 } + let removals = legacy.allowsRemovals ? theirs.filter { mine[$0.key] == nil }.map(\.value.key) : [] + do { + refused = try await send(puts: puts, removals: removals) + } catch { + log("the core refused the first push", error) + return false + } + } + return await settle(written: legacy.values, refused: refused, base: [:], current: mine, before: theirs) + && refused.isEmpty + } + + private func moveWhole(_ legacy: CoreMirrorLegacyRead, core: CoreMirrorCoreRead) async throws { + guard legacy.allowsRemovals else { throw CoreMirrorPartialStore() } + try await adapter.replaceCore(expected: core.digest, values: legacy.values) + } + + // Returns the encoded keys the core refused; their older copy may still be there, so none reads as a settlement. + private func send(puts: [Adapter.Value], removals: [Adapter.Key]) async throws -> Set { + guard !puts.isEmpty || !removals.isEmpty else { return [] } + do { + try await adapter.writeCore(puts: puts, removals: removals) + return [] + } catch { + // One record the core refuses, such as a blank name, keeps the others out of a single write. Removals go + // first, so a name or keyword a removed record held is free for the record that takes it. + if !removals.isEmpty { + try await adapter.writeCore(puts: [], removals: removals) + } + var refused: Set = [] + for value in puts { + do { + try await adapter.writeCore(puts: [value], removals: []) + } catch { + refused.insert(code(of: value)) + } + } + if !refused.isEmpty { + Self.logger.error("\(self.adapter.name, privacy: .public): the core refused \(refused.count, privacy: .public) records") + } + return refused + } + } + + // A record the core holds differently after a write, one the write carried or one both sides held alike before + // it, is the core's settlement of a collision, which the Swift store takes and syncs as its own edit. A key both + // sides now hold alike is agreed; any other keeps its last agreement, so the next push looks at it again. + private func settle( + written: [Adapter.Value], + refused: Set, + base: [String: String], + current: Side, + before: Side + ) async -> Bool { + let after: CoreMirrorCoreRead + do { + after = try await adapter.readCore() + } catch { + log("the core could not be read back", error) + return false + } + let held = side(after.values) + var current = current + let carried = Set(written.map(code(of:))) + let settled: [Adapter.Value] = held.compactMap { encoded, copy in + guard !refused.contains(encoded), let mine = current[encoded], copy.value != mine.value else { return nil } + guard carried.contains(encoded) || before[encoded]?.value == mine.value else { return nil } + return copy.value + } + if !settled.isEmpty { + if await adapter.applyToLegacy(puts: settled, removals: [], expected: expected(current, settled, [])) { + apply(settled, [], to: ¤t) + await adapter.announce(settled: settled) + } else { + Self.logger.notice("\(self.adapter.name, privacy: .public): the store changed during the push; the next one takes it") + } + } + var next: [String: String] = [:] + for code in Set(current.keys).union(held.keys).union(base.keys) { + let mine = current[code]?.value + let theirs = held[code]?.value + if !refused.contains(code), mine == theirs { + if let agreed = digest(mine) { + next[code] = agreed + } + } else if let previous = base[code] { + next[code] = previous + } + } + save(next) + return true + } + + private func side(_ values: [Adapter.Value]) -> Side { + var side: Side = [:] + for value in values { + side[code(of: value)] = (adapter.key(of: value), value) + } + return side + } + + private func apply(_ puts: [Adapter.Value], _ removals: [Adapter.Key], to side: inout Side) { + for key in removals { + side[Self.encoded(key)] = nil + } + for value in puts { + side[code(of: value)] = (adapter.key(of: value), value) + } + } + + // What the read held for each key a write back touches. + private func expected(_ side: Side, _ puts: [Adapter.Value], _ removals: [Adapter.Key]) -> [Adapter.Key: Adapter.Value] { + var expected: [Adapter.Key: Adapter.Value] = [:] + for key in puts.map(adapter.key(of:)) + removals { + expected[key] = side[Self.encoded(key)]?.value + } + return expected + } + + private func code(of value: Adapter.Value) -> String { + Self.encoded(adapter.key(of: value)) + } + + private func digest(_ value: Adapter.Value?) -> String? { + guard let value else { return nil } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + guard let data = try? encoder.encode(value) else { return nil } + return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + + private static func encoded(_ key: Adapter.Key) -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + guard let data = try? encoder.encode(key) else { return "" } + return String(bytes: data, encoding: .utf8) ?? "" + } + + private func log(_ what: String, _ error: any Error) { + Self.logger.error("\(self.adapter.name, privacy: .public): \(what, privacy: .public): \(LogRedaction.publicDescription(of: error), privacy: .public)") + } +} + +// A store that holds less than it should never replaces the core's whole copy. +private struct CoreMirrorPartialStore: Error {} diff --git a/apple/TablePro/Core/Storage/CoreMirror/FavoriteCoreAdapters.swift b/apple/TablePro/Core/Storage/CoreMirror/FavoriteCoreAdapters.swift new file mode 100644 index 0000000000..493b59e8c1 --- /dev/null +++ b/apple/TablePro/Core/Storage/CoreMirror/FavoriteCoreAdapters.swift @@ -0,0 +1,401 @@ +// +// FavoriteCoreAdapters.swift +// TablePro +// + +import Foundation +import TableProFFI + +// The favourite tables in UserDefaults and the core's (core ADR 0010, slice 9). A table is its own key. +internal final class FavoriteTablesCoreAdapter: CoreMirrorAdapter, @unchecked Sendable { + private weak var store: FavoriteTablesStorage? + private let database: CoreHistoryDatabase + + init(store: FavoriteTablesStorage, database: CoreHistoryDatabase) { + self.store = store + self.database = database + } + + var name: String { "favoriteTables" } + + func key(of value: FavoriteTablesStorage.FavoriteEntry) -> FavoriteTablesStorage.FavoriteEntry { + value + } + + func readLegacy() async -> CoreMirrorLegacyRead? { + guard let store else { return nil } + return CoreMirrorLegacyRead(values: Array(store.loadFavorites()), allowsRemovals: store.storedFavoritesRead) + } + + func readCore() async throws -> CoreMirrorCoreRead { + let contents = try await database.favourites().contents() + let values = contents.tables.compactMap { record -> FavoriteTablesStorage.FavoriteEntry? in + guard let connectionId = UUID(uuidString: record.connectionId) else { return nil } + return FavoriteTablesStorage.FavoriteEntry( + connectionId: connectionId, + database: record.database, + schema: record.schema, + name: record.name + ) + } + return CoreMirrorCoreRead(values: values, digest: contents.digests.tables) + } + + func writeCore(puts: [FavoriteTablesStorage.FavoriteEntry], removals: [FavoriteTablesStorage.FavoriteEntry]) async throws { + _ = try await database.favourites().writeRecords(write: FavouriteRecordWrite( + tables: puts.map(Self.record), + databases: [], + removedTables: removals.map(Self.record), + removedDatabases: [] + )) + } + + func replaceCore(expected: String, values: [FavoriteTablesStorage.FavoriteEntry]) async throws { + let store = try await database.favourites() + try await refusingOutdated { + _ = try await store.replaceTables(expectedDigest: expected, held: values.map(Self.record)) + } + } + + func applyToLegacy( + puts: [FavoriteTablesStorage.FavoriteEntry], + removals: [FavoriteTablesStorage.FavoriteEntry], + expected: [FavoriteTablesStorage.FavoriteEntry: FavoriteTablesStorage.FavoriteEntry] + ) async -> Bool { + guard let store else { return false } + // Every write to these favourites runs on the main actor, so the check and the write see the same set. + return await MainActor.run { + // A document that does not decode is never written over: what it holds is only unread. + guard store.storedFavoritesRead else { return false } + let held = store.loadFavorites() + guard (puts + removals).allSatisfy({ held.contains($0) == (expected[$0] != nil) }) else { return false } + store.applyCoreFavorites(puts: puts, removals: removals) + return true + } + } + + func announce(settled: [FavoriteTablesStorage.FavoriteEntry]) async {} + + private static func record(_ entry: FavoriteTablesStorage.FavoriteEntry) -> FavouriteTableRecord { + FavouriteTableRecord( + connectionId: entry.connectionId.uuidString, + database: entry.database, + schema: entry.schema, + name: entry.name + ) + } +} + +// The favourite databases in UserDefaults and the core's, keyed by connection and database. +internal final class FavoriteDatabasesCoreAdapter: CoreMirrorAdapter, @unchecked Sendable { + private weak var store: FavoriteDatabasesStorage? + private let database: CoreHistoryDatabase + + init(store: FavoriteDatabasesStorage, database: CoreHistoryDatabase) { + self.store = store + self.database = database + } + + var name: String { "favoriteDatabases" } + + func key(of value: FavoriteDatabaseEntry) -> String { + value.id + } + + func readLegacy() async -> CoreMirrorLegacyRead? { + guard let store else { return nil } + return await MainActor.run { + CoreMirrorLegacyRead(values: Array(store.loadFavorites()), allowsRemovals: store.storedFavoritesRead) + } + } + + func readCore() async throws -> CoreMirrorCoreRead { + let contents = try await database.favourites().contents() + let values = contents.databases.compactMap { record -> FavoriteDatabaseEntry? in + guard let connectionId = UUID(uuidString: record.connectionId) else { return nil } + return FavoriteDatabaseEntry( + connectionId: connectionId, + database: record.database, + environment: Self.environment(record.environment) + ) + } + return CoreMirrorCoreRead(values: values, digest: contents.digests.databases) + } + + func writeCore(puts: [FavoriteDatabaseEntry], removals: [String]) async throws { + let removed = removals.compactMap(Self.key(from:)) + _ = try await database.favourites().writeRecords(write: FavouriteRecordWrite( + tables: [], + databases: puts.map(Self.record), + removedTables: [], + removedDatabases: removed + )) + } + + func replaceCore(expected: String, values: [FavoriteDatabaseEntry]) async throws { + let store = try await database.favourites() + try await refusingOutdated { + _ = try await store.replaceDatabases(expectedDigest: expected, held: values.map(Self.record)) + } + } + + func applyToLegacy( + puts: [FavoriteDatabaseEntry], + removals: [String], + expected: [String: FavoriteDatabaseEntry] + ) async -> Bool { + guard let store else { return false } + return await MainActor.run { + guard store.storedFavoritesRead else { return false } + let held = Dictionary(store.loadFavorites().map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + guard (puts.map(\.id) + removals).allSatisfy({ held[$0] == expected[$0] }) else { return false } + store.applyCoreFavorites(puts: puts, removals: removals) + return true + } + } + + func announce(settled: [FavoriteDatabaseEntry]) async {} + + private static func record(_ entry: FavoriteDatabaseEntry) -> FavouriteDatabaseRecord { + FavouriteDatabaseRecord( + connectionId: entry.connectionId.uuidString, + database: entry.database, + environment: tag(entry.environment) + ) + } + + // The entry's id is its connection, then U+0001, then the database name. + private static func key(from id: String) -> FavouriteDatabaseKey? { + guard let separator = id.firstIndex(of: "\u{1}") else { return nil } + return FavouriteDatabaseKey( + connectionId: String(id[.. DatabaseEnvironmentTag { + switch environment { + case .development: .development + case .testing: .testing + case .production: .production + case .unassigned: .unassigned + } + } + + private static func environment(_ tag: DatabaseEnvironmentTag) -> FavoriteDatabaseEnvironment { + switch tag { + case .development: .development + case .testing: .testing + case .production: .production + case .unassigned: .unassigned + } + } +} + +internal enum TableFolderMirrorKey: Hashable, Sendable, Encodable { + case folder(UUID) + case item(TableFolderItemKey) +} + +// A folder's times in whole milliseconds, the precision the core and a CloudKit date keep. +internal enum TableFolderMirrorValue: Equatable, Sendable, Encodable { + case folder(Folder) + case item(TableFolderItem) + + internal struct Folder: Equatable, Sendable, Encodable { + let id: UUID + let scope: DatabaseScope + let name: String + let createdAtMs: Int64 + let updatedAtMs: Int64 + } +} + +// The table folders in UserDefaults, one document per connection, and the core's (core ADR 0010, slice 9). +internal final class TableFolderCoreAdapter: CoreMirrorAdapter, @unchecked Sendable { + private weak var store: TableFolderStorage? + private let database: CoreHistoryDatabase + + init(store: TableFolderStorage, database: CoreHistoryDatabase) { + self.store = store + self.database = database + } + + var name: String { "tableFolders" } + + func readLegacy() async -> CoreMirrorLegacyRead? { + guard let store else { return nil } + return await MainActor.run { () -> CoreMirrorLegacyRead in + let values = Self.values(store.allFolders(), store.allItems()) + // A document that does not read stands for folders this build cannot see, which the core keeps. + return CoreMirrorLegacyRead(values: values, allowsRemovals: !store.hasUnreadableDocumentsAfterReadingAll) + } + } + + func key(of value: TableFolderMirrorValue) -> TableFolderMirrorKey { + Self.key(of: value) + } + + private static func key(of value: TableFolderMirrorValue) -> TableFolderMirrorKey { + switch value { + case .folder(let folder): .folder(folder.id) + case .item(let item): .item(item.key) + } + } + + private static func values(_ folders: [TableFolder], _ items: [TableFolderItem]) -> [TableFolderMirrorValue] { + let folders = folders.map { folder in + TableFolderMirrorValue.folder(.init( + id: folder.id, + scope: folder.scope, + name: folder.name, + createdAtMs: CoreMirrorTime.milliseconds(folder.createdAt), + updatedAtMs: CoreMirrorTime.milliseconds(folder.updatedAt) + )) + } + return folders + items.map(TableFolderMirrorValue.item) + } + + func readCore() async throws -> CoreMirrorCoreRead { + let contents = try await database.tableFolders().contents() + let folders = contents.folders.compactMap { record -> TableFolderMirrorValue? in + guard let id = UUID(uuidString: record.id), let connectionId = UUID(uuidString: record.connectionId) else { + return nil + } + return .folder(.init( + id: id, + scope: Self.scope(connectionId, record.database, record.schema), + name: record.name, + createdAtMs: record.createdAtMs, + updatedAtMs: record.updatedAtMs + )) + } + let items = contents.items.compactMap { record -> TableFolderMirrorValue? in + guard let connectionId = UUID(uuidString: record.connectionId), + let folderId = UUID(uuidString: record.folderId) else { return nil } + return .item(TableFolderItem( + scope: Self.scope(connectionId, record.table.database, record.table.schema), + name: record.table.name, + folderId: folderId + )) + } + return CoreMirrorCoreRead(values: folders + items, digest: contents.digest) + } + + func writeCore(puts: [TableFolderMirrorValue], removals: [TableFolderMirrorKey]) async throws { + let (folders, items) = Self.records(puts) + var removedFolders: [String] = [] + var removedItems: [TableKeyRecord] = [] + for key in removals { + switch key { + case .folder(let id): + removedFolders.append(id.uuidString) + case .item(let item): + removedItems.append(TableKeyRecord( + connectionId: item.scope.connectionId.uuidString, + table: Self.table(item.scope, item.name) + )) + } + } + _ = try await database.tableFolders().writeRecords(write: TableFolderRecordWrite( + folders: folders, + items: items, + removedFolders: removedFolders, + removedItems: removedItems + )) + } + + func replaceCore(expected: String, values: [TableFolderMirrorValue]) async throws { + let (folders, items) = Self.records(values) + let store = try await database.tableFolders() + try await refusingOutdated { + _ = try await store.replaceRecords(expectedDigest: expected, foldersHeld: folders, itemsHeld: items) + } + } + + func applyToLegacy( + puts: [TableFolderMirrorValue], + removals: [TableFolderMirrorKey], + expected: [TableFolderMirrorKey: TableFolderMirrorValue] + ) async -> Bool { + var folders: [TableFolder] = [] + var items: [TableFolderItem] = [] + for value in puts { + switch value { + case .folder(let folder): + folders.append(TableFolder( + id: folder.id, + scope: folder.scope, + name: folder.name, + createdAt: CoreMirrorTime.date(folder.createdAtMs), + updatedAt: CoreMirrorTime.date(folder.updatedAtMs) + )) + case .item(let item): + items.append(item) + } + } + var removedFolders: Set = [] + var removedItems: Set = [] + for key in removals { + switch key { + case .folder(let id): removedFolders.insert(id) + case .item(let item): removedItems.insert(item) + } + } + let touched = puts.map(key(of:)) + removals + guard let store else { return false } + return await MainActor.run { [folders, items, removedFolders, removedItems] in + // The store refuses to write a document that does not read, so nothing would land. + guard !store.hasUnreadableDocumentsAfterReadingAll else { return false } + let held = Dictionary( + Self.values(store.allFolders(), store.allItems()).map { (Self.key(of: $0), $0) }, + uniquingKeysWith: { first, _ in first } + ) + guard touched.allSatisfy({ held[$0] == expected[$0] }) else { return false } + store.applyCoreRecords( + folders: folders, + items: items, + removedFolderIds: removedFolders, + removedItemKeys: removedItems + ) + return true + } + } + + func announce(settled: [TableFolderMirrorValue]) async {} + + // The core names a database or schema an engine lacks by the empty string; the Mac by none. + private static func scope(_ connectionId: UUID, _ database: String, _ schema: String) -> DatabaseScope { + DatabaseScope(connectionId: connectionId, database: database, schema: schema.isEmpty ? nil : schema) + } + + private static func table(_ scope: DatabaseScope, _ name: String) -> TableRefRecord { + TableRefRecord(database: scope.database, schema: scope.schema ?? "", name: name) + } + + private static func records(_ values: [TableFolderMirrorValue]) -> ([TableFolderRecord], [TablePlacementRecord]) { + var folders: [TableFolderRecord] = [] + var items: [TablePlacementRecord] = [] + for value in values { + switch value { + case .folder(let folder): + folders.append(TableFolderRecord( + id: folder.id.uuidString, + connectionId: folder.scope.connectionId.uuidString, + database: folder.scope.database, + schema: folder.scope.schema ?? "", + name: folder.name, + createdAtMs: folder.createdAtMs, + updatedAtMs: folder.updatedAtMs + )) + case .item(let item): + items.append(TablePlacementRecord( + connectionId: item.scope.connectionId.uuidString, + table: table(item.scope, item.name), + folderId: item.folderId.uuidString + )) + } + } + return (folders, items) + } +} diff --git a/apple/TablePro/Core/Storage/CoreMirror/QueryHistoryCoreMirror.swift b/apple/TablePro/Core/Storage/CoreMirror/QueryHistoryCoreMirror.swift new file mode 100644 index 0000000000..e42784c3bb --- /dev/null +++ b/apple/TablePro/Core/Storage/CoreMirror/QueryHistoryCoreMirror.swift @@ -0,0 +1,183 @@ +// +// QueryHistoryCoreMirror.swift +// TablePro +// + +import Foundation +import os +import TableProFFI +import TableProLogRedaction + +// The history in `query_history.db` and the core's, entry for entry under the Mac's ids (core ADR 0052, History). +// The Mac's store keeps what only this device needs (the database, the source, plan and Rewind snapshots, the +// insights), so it stays what the History pane reads; the core holds the fields that sync. Each run goes to both. A +// run leaves the core only when it left the Mac's store after both held it: deleted, cleared, dropped by retention, +// or deleted by the previous stable after a downgrade. +internal actor QueryHistoryCoreMirror { + private static let logger = Logger(subsystem: "com.TablePro", category: "QueryHistoryCoreMirror") + private static let entriesPerWrite = 500 + + private let storage: QueryHistoryStorage + private let database: CoreHistoryDatabase + private let connectionNames: @Sendable (Set) async -> [UUID: String] + private var tail: Task? + private var cleanupRunsSeen = 0 + + internal init( + storage: QueryHistoryStorage, + database: CoreHistoryDatabase, + connectionNames: @escaping @Sendable (Set) async -> [UUID: String] + ) { + self.storage = storage + self.database = database + self.connectionNames = connectionNames + } + + nonisolated internal func schedulePush() { + Task { await self.push() } + } + + nonisolated internal func scheduleRecorded(_ id: UUID) { + Task { await self.recorded(id) } + } + + // A retention pass the record ran drops runs here too. + internal func recorded(_ id: UUID) async { + _ = await serialized { [self] in await recordedOnce(id) } + } + + private func recordedOnce(_ id: UUID) async -> Bool { + do { + let rows = await storage.coreRows(ids: [id]) + if try await put(rows).contains(id) { + await storage.updateCoreMirrorBase(adding: [id], removing: []) + } + } catch { + Self.logger.error("A run did not reach the core's history: \(LogRedaction.publicDescription(of: error), privacy: .public)") + } + guard await storage.cleanupRuns != cleanupRunsSeen else { return true } + return await pushOnce() + } + + // False when the core may still hold a run the Mac's store no longer has, or lack one it has. + @discardableResult + internal func push() async -> Bool { + await serialized { [self] in await pushOnce() } + } + + // The runs the Mac's store just dropped leave the core too, whatever the last agreement says. + internal func dropped(_ ids: Set) async -> Bool { + await serialized { [self] in await droppedOnce(ids) } + } + + private func droppedOnce(_ ids: Set) async -> Bool { + do { + let store = try await database.history() + let gone = ids.map(\.uuidString) + for start in stride(from: 0, to: gone.count, by: Self.entriesPerWrite) { + _ = try await store.removeEntries(recordIds: Array(gone[start.. Bool { + await serialized { [self] in await clearedOnce(connectionId: connectionId) } + } + + private func clearedOnce(connectionId: UUID?) async -> Bool { + do { + let store = try await database.history() + if let connectionId { + _ = try await store.deleteForConnection(connectionId: connectionId.uuidString) + } else { + try await store.clear() + } + } catch { + Self.logger.error("The core's history was not cleared: \(LogRedaction.publicDescription(of: error), privacy: .public)") + return false + } + return await pushOnce() + } + + private func serialized(_ work: @escaping @Sendable () async -> Bool) async -> Bool { + let previous = tail + let run = Task { () -> Bool in + await previous?.value + return await work() + } + tail = Task { _ = await run.value } + return await run.value + } + + private func pushOnce() async -> Bool { + cleanupRunsSeen = await storage.cleanupRuns + guard let mine = await storage.entryIds(), let base = await storage.coreMirrorBase() else { return false } + do { + let store = try await database.history() + let held = Set(try await store.recordIds().compactMap(UUID.init(uuidString:))) + let missing = Array(mine.subtracting(held)) + var written: Set = [] + for start in stride(from: 0, to: missing.count, by: Self.entriesPerWrite) { + let chunk = Array(missing[start.. Set { + guard !rows.isEmpty else { return [] } + let names = await connectionNames(Set(rows.map(\.connectionId))) + let entries = rows.map { row in + HistoryEntryRecord( + recordId: row.id.uuidString, + sql: row.query, + driverId: row.databaseType, + connectionId: row.connectionId.uuidString, + connectionName: names[row.connectionId] ?? "", + executedAtMs: CoreMirrorTime.milliseconds(row.executedAt), + durationMs: CoreMirrorTime.milliseconds(seconds: row.executionTime), + rowsAffected: Int64(row.rowCount), + outcome: row.wasSuccessful ? .succeeded : .failed(message: row.errorMessage ?? "") + ) + } + let store = try await database.history() + do { + _ = try await store.putEntries(entries: entries) + return Set(rows.map(\.id)) + } catch { + // One run the core refuses, such as one past its size cap, keeps the others out of a single write. + var taken: Set = [] + for (row, entry) in zip(rows, entries) { + if (try? await store.putEntries(entries: [entry])) != nil { + taken.insert(row.id) + } + } + Self.logger.error("The core's history refused \(rows.count - taken.count, privacy: .public) runs") + return taken + } + } +} diff --git a/apple/TablePro/Core/Storage/CoreMirror/SavedQueryCoreAdapter.swift b/apple/TablePro/Core/Storage/CoreMirror/SavedQueryCoreAdapter.swift new file mode 100644 index 0000000000..745e723dd8 --- /dev/null +++ b/apple/TablePro/Core/Storage/CoreMirror/SavedQueryCoreAdapter.swift @@ -0,0 +1,275 @@ +// +// SavedQueryCoreAdapter.swift +// TablePro +// + +import Foundation +import TableProFFI + +internal enum SavedQueryMirrorKey: Hashable, Sendable, Encodable { + case query(UUID) + case folder(UUID) +} + +// Times in whole milliseconds, the precision the core and a CloudKit date keep. +internal enum SavedQueryMirrorValue: Equatable, Sendable, Encodable { + case query(Query) + case folder(Folder) + + internal struct Query: Equatable, Sendable, Encodable { + let id: UUID + let name: String + let sql: String + let keyword: String? + let folderId: UUID? + let connectionId: UUID? + let order: Int64 + let createdAtMs: Int64 + let updatedAtMs: Int64 + } + + internal struct Folder: Equatable, Sendable, Encodable { + let id: UUID + let name: String + let parentId: UUID? + let connectionId: UUID? + let order: Int64 + let createdAtMs: Int64 + let updatedAtMs: Int64 + } +} + +// `sql_favorites.db` and the core's saved queries and folders (core ADR 0010, slice 3). +internal struct SavedQueryCoreAdapter: CoreMirrorAdapter { + let storage: SQLFavoriteStorage + let database: CoreHistoryDatabase + let announceSettled: @Sendable (_ queries: [UUID], _ folders: [UUID]) async -> Void + + var name: String { "savedQueries" } + + func key(of value: SavedQueryMirrorValue) -> SavedQueryMirrorKey { + switch value { + case .query(let query): .query(query.id) + case .folder(let folder): .folder(folder.id) + } + } + + func readLegacy() async -> CoreMirrorLegacyRead? { + guard let read = await storage.readAllFavoritesAndFolders() else { return nil } + let refilling = await storage.isAwaitingSyncRefill() + let values = read.favorites.map { SavedQueryMirrorValue.query(.init($0)) } + + read.folders.map { SavedQueryMirrorValue.folder(.init($0)) } + return CoreMirrorLegacyRead(values: values, allowsRemovals: !refilling) + } + + func readCore() async throws -> CoreMirrorCoreRead { + let contents = try await database.savedQueries().contents() + let values = contents.queries.compactMap(SavedQueryMirrorValue.Query.init).map(SavedQueryMirrorValue.query) + + contents.folders.compactMap(SavedQueryMirrorValue.Folder.init).map(SavedQueryMirrorValue.folder) + return CoreMirrorCoreRead(values: values, digest: contents.digest) + } + + func writeCore(puts: [SavedQueryMirrorValue], removals: [SavedQueryMirrorKey]) async throws { + let (queries, folders) = Self.records(puts) + _ = try await database.savedQueries().writeRecords(write: SavedQueryRecordWrite( + queries: queries, + folders: folders, + removedQueries: removals.compactMap { key in + guard case .query(let id) = key else { return nil } + return id.uuidString + }, + removedFolders: removals.compactMap { key in + guard case .folder(let id) = key else { return nil } + return id.uuidString + } + )) + } + + func replaceCore(expected: String, values: [SavedQueryMirrorValue]) async throws { + let (queries, folders) = Self.records(values) + let store = try await database.savedQueries() + try await refusingOutdated { + _ = try await store.replaceRecords(expectedDigest: expected, queries: queries, folders: folders) + } + } + + func applyToLegacy( + puts: [SavedQueryMirrorValue], + removals: [SavedQueryMirrorKey], + expected: [SavedQueryMirrorKey: SavedQueryMirrorValue] + ) async -> Bool { + var favorites: [SQLFavorite] = [] + var folders: [SQLFavoriteFolder] = [] + for value in puts { + switch value { + case .query(let query): favorites.append(query.favorite) + case .folder(let folder): folders.append(folder.folder) + } + } + var removedFavorites: [UUID] = [] + var removedFolders: [UUID] = [] + for key in removals { + switch key { + case .query(let id): removedFavorites.append(id) + case .folder(let id): removedFolders.append(id) + } + } + return await storage.applyCoreRecords( + favorites: favorites, + folders: folders, + removedFavoriteIds: removedFavorites, + removedFolderIds: removedFolders, + expected: expected + ) + } + + func announce(settled: [SavedQueryMirrorValue]) async { + var queries: [UUID] = [] + var folders: [UUID] = [] + for value in settled { + switch value { + case .query(let query): queries.append(query.id) + case .folder(let folder): folders.append(folder.id) + } + } + await announceSettled(queries, folders) + } + + // The connection's name is a display copy only the core keeps; no Mac store holds it. + private static func records(_ values: [SavedQueryMirrorValue]) -> ([SavedQueryRecord], [SavedQueryFolderRecord]) { + var queries: [SavedQueryRecord] = [] + var folders: [SavedQueryFolderRecord] = [] + for value in values { + switch value { + case .query(let query): + queries.append(SavedQueryRecord( + id: query.id.uuidString, + name: query.name, + sql: query.sql, + keyword: query.keyword, + connectionId: query.connectionId?.uuidString, + connectionName: "", + folderId: query.folderId?.uuidString, + order: query.order, + createdAtMs: query.createdAtMs, + updatedAtMs: query.updatedAtMs + )) + case .folder(let folder): + folders.append(SavedQueryFolderRecord( + id: folder.id.uuidString, + name: folder.name, + connectionId: folder.connectionId?.uuidString, + parentId: folder.parentId?.uuidString, + order: folder.order, + createdAtMs: folder.createdAtMs, + updatedAtMs: folder.updatedAtMs + )) + } + } + return (queries, folders) + } +} + +// To the nearest millisecond, so a time read back from a store that keeps seconds as a double maps to the same value. +internal enum CoreMirrorTime { + static func milliseconds(_ date: Date) -> Int64 { + milliseconds(seconds: date.timeIntervalSince1970) + } + + // A value the Swift store holds outside what an Int64 of milliseconds takes is pinned to its end, never a trap. + static func milliseconds(seconds: Double) -> Int64 { + let value = (seconds * 1_000).rounded() + guard value.isFinite else { return 0 } + guard value < Double(Int64.max) else { return .max } + guard value > Double(Int64.min) else { return .min } + return Int64(value) + } + + static func date(_ milliseconds: Int64) -> Date { + Date(timeIntervalSince1970: Double(milliseconds) / 1_000) + } +} + +extension SavedQueryMirrorValue.Query { + init(_ favorite: SQLFavorite) { + self.init( + id: favorite.id, + name: favorite.name, + sql: favorite.query, + keyword: favorite.keyword, + folderId: favorite.folderId, + connectionId: favorite.connectionId, + order: Int64(favorite.sortOrder), + createdAtMs: CoreMirrorTime.milliseconds(favorite.createdAt), + updatedAtMs: CoreMirrorTime.milliseconds(favorite.updatedAt) + ) + } + + init?(_ record: SavedQueryRecord) { + guard let id = UUID(uuidString: record.id) else { return nil } + self.init( + id: id, + name: record.name, + sql: record.sql, + keyword: record.keyword, + folderId: record.folderId.flatMap(UUID.init(uuidString:)), + connectionId: record.connectionId.flatMap(UUID.init(uuidString:)), + order: record.order, + createdAtMs: record.createdAtMs, + updatedAtMs: record.updatedAtMs + ) + } + + var favorite: SQLFavorite { + SQLFavorite( + id: id, + name: name, + query: sql, + keyword: keyword, + folderId: folderId, + connectionId: connectionId, + sortOrder: Int(clamping: order), + createdAt: CoreMirrorTime.date(createdAtMs), + updatedAt: CoreMirrorTime.date(updatedAtMs) + ) + } +} + +extension SavedQueryMirrorValue.Folder { + init(_ folder: SQLFavoriteFolder) { + self.init( + id: folder.id, + name: folder.name, + parentId: folder.parentId, + connectionId: folder.connectionId, + order: Int64(folder.sortOrder), + createdAtMs: CoreMirrorTime.milliseconds(folder.createdAt), + updatedAtMs: CoreMirrorTime.milliseconds(folder.updatedAt) + ) + } + + init?(_ record: SavedQueryFolderRecord) { + guard let id = UUID(uuidString: record.id) else { return nil } + self.init( + id: id, + name: record.name, + parentId: record.parentId.flatMap(UUID.init(uuidString:)), + connectionId: record.connectionId.flatMap(UUID.init(uuidString:)), + order: record.order, + createdAtMs: record.createdAtMs, + updatedAtMs: record.updatedAtMs + ) + } + + var folder: SQLFavoriteFolder { + SQLFavoriteFolder( + id: id, + name: name, + parentId: parentId, + connectionId: connectionId, + sortOrder: Int(clamping: order), + createdAt: CoreMirrorTime.date(createdAtMs), + updatedAt: CoreMirrorTime.date(updatedAtMs) + ) + } +} diff --git a/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift b/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift index 47b52a1738..e949a20865 100644 --- a/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift +++ b/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift @@ -13,20 +13,26 @@ extension Notification.Name { // One key for every connection, so a sync push resolves a dirty id without knowing the connections. `FavoriteTablesStorage` is the same shape. @MainActor internal final class FavoriteDatabasesStorage { - internal static let shared = FavoriteDatabasesStorage() + internal static let shared = FavoriteDatabasesStorage(core: .shared) private static let storageKey = JSONDefaultsKey>("com.TablePro.favoriteDatabases") private let defaults: UserDefaults private let syncTracker: SyncChangeTracker private var cache: Set? + // Nil keeps the favourites out of the core, for a store nothing else reads. + internal private(set) var coreMirror: CoreMirror? internal init( defaults: UserDefaults = AppStorageEnvironment.shared.defaults, - syncTracker: SyncChangeTracker = .shared + syncTracker: SyncChangeTracker = .shared, + core: CoreHistoryDatabase? = nil ) { self.defaults = defaults self.syncTracker = syncTracker + if let core { + coreMirror = CoreMirror(adapter: FavoriteDatabasesCoreAdapter(store: self, database: core), defaults: defaults) + } } internal func loadFavorites() -> Set { @@ -136,6 +142,24 @@ internal final class FavoriteDatabasesStorage { case .discard: syncTracker.discardDirty(.favoriteDatabase, ids: removed.map(Self.syncId(for:))) } + coreMirror?.schedulePush() + postChangeNotification() + } + + // False when favourites are stored and do not decode, which reads as none and must not read as none removed. + internal var storedFavoritesRead: Bool { + !defaults.read(Self.storageKey).isUnreadable + } + + // The core's copy written back, marking nothing: it came from this Mac or a pull, never a new edit here. + internal func applyCoreFavorites(puts: [FavoriteDatabaseEntry], removals: [String]) { + let removed = Set(removals) + var favorites = loadFavorites().filter { !removed.contains($0.id) } + for entry in puts { + Self.upsert(entry, into: &favorites) + } + guard favorites != loadFavorites() else { return } + persist(favorites) postChangeNotification() } diff --git a/apple/TablePro/Core/Storage/FavoriteTablesStorage.swift b/apple/TablePro/Core/Storage/FavoriteTablesStorage.swift index 3adfdc1669..7d481dd5c6 100644 --- a/apple/TablePro/Core/Storage/FavoriteTablesStorage.swift +++ b/apple/TablePro/Core/Storage/FavoriteTablesStorage.swift @@ -8,7 +8,7 @@ extension Notification.Name { } final class FavoriteTablesStorage: @unchecked Sendable { - static let shared = FavoriteTablesStorage() + static let shared = FavoriteTablesStorage(core: .shared) private static let logger = Logger(subsystem: "com.TablePro", category: "FavoriteTablesStorage") private static let currentSyncIdentityVersion = 1 private static let escapedPathDomain = "escaped" @@ -62,10 +62,19 @@ final class FavoriteTablesStorage: @unchecked Sendable { private let syncIdentityVersionKey = "com.TablePro.favoriteTables.syncIdentityVersion" private var cache: Set? private let lock = NSLock() - - init(userDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, syncTracker: SyncChangeTracker = .shared) { + // Nil keeps the favourites out of the core, for a store nothing else reads. + private(set) var coreMirror: CoreMirror? + + init( + userDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, + syncTracker: SyncChangeTracker = .shared, + core: CoreHistoryDatabase? = nil + ) { self.defaults = userDefaults self.syncTracker = syncTracker + if let core { + coreMirror = CoreMirror(adapter: FavoriteTablesCoreAdapter(store: self, database: core), defaults: userDefaults) + } } func loadFavorites() -> Set { @@ -164,6 +173,7 @@ final class FavoriteTablesStorage: @unchecked Sendable { } syncTracker.discardDirty(.tableFavorite, ids: Array(deletedIds.union(Self.recordIds(of: change.removed)))) if change.changesEntries { + coreMirror?.schedulePush() NotificationCenter.default.post(name: .favoriteTablesDidChange, object: self) } return Self.syncIdsByConnection(of: removedThroughAliases) @@ -180,6 +190,24 @@ final class FavoriteTablesStorage: @unchecked Sendable { Self.logger.info("Re-keyed \(rekeyed.count, privacy: .public) favorite tables to escaped sync ids") } + // False when favourites are stored and do not decode, which reads as none and must not read as none removed. + var storedFavoritesRead: Bool { + guard let data = defaults.data(forKey: key) else { return true } + return (try? JSONDecoder().decode([FavoriteEntry].self, from: data)) != nil + } + + // The core's copy written back, marking nothing: it came from this Mac or a pull, never a new edit here. + @MainActor + func applyCoreFavorites(puts: [FavoriteEntry], removals: [FavoriteEntry]) { + let change = mutateState { favorites in + favorites.subtract(removals) + favorites.formUnion(puts) + } + if change.changesEntries { + NotificationCenter.default.post(name: .favoriteTablesDidChange, object: self) + } + } + static func syncId(for entry: FavoriteEntry) -> String { let path = IdentityPath.joined(identityComponents(of: entry), separator: "|") guard path != legacyPath(of: entry) else { return path.sha256 } @@ -231,6 +259,7 @@ final class FavoriteTablesStorage: @unchecked Sendable { case .discard: syncTracker.discardDirty(.tableFavorite, ids: removedIds.values.flatMap { $0 }) } + coreMirror?.schedulePush() NotificationCenter.default.post(name: .favoriteTablesDidChange, object: self) return change } diff --git a/apple/TablePro/Core/Storage/QueryHistoryManager.swift b/apple/TablePro/Core/Storage/QueryHistoryManager.swift index 3ea0d54397..b3699df29a 100644 --- a/apple/TablePro/Core/Storage/QueryHistoryManager.swift +++ b/apple/TablePro/Core/Storage/QueryHistoryManager.swift @@ -3,22 +3,33 @@ import Foundation import TableProPluginKit final class QueryHistoryManager: QueryHistoryRecording, QueryHistoryReading, QueryPlanSnapshotReading, Sendable { - static let shared = QueryHistoryManager( - storage: QueryHistoryStorage(onSetAside: { DamagedStoreNotice.queryHistorySetAside($0) }) - ) + static let shared: QueryHistoryManager = { + let storage = QueryHistoryStorage(onSetAside: { DamagedStoreNotice.queryHistorySetAside($0) }) + let mirror = QueryHistoryCoreMirror(storage: storage, database: .shared) { ids in + await MainActor.run { + let named = ConnectionStorage.shared.loadConnections().filter { ids.contains($0.id) } + return Dictionary(named.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) + } + } + return QueryHistoryManager(storage: storage, coreMirror: mirror) + }() // Not private: QueryHistoryManager+Rewind reaches it from another file. internal let storage: QueryHistoryStorage let rewindAvailability: RewindAvailabilityCache private let isCapturePaused: @Sendable () -> Bool + // Nil keeps the history out of the core, for a store nothing else reads. + internal let coreMirror: QueryHistoryCoreMirror? init( storage: QueryHistoryStorage = QueryHistoryStorage(), - isCapturePaused: @escaping @Sendable () -> Bool = { QueryHistoryCaptureStore.isPaused } + isCapturePaused: @escaping @Sendable () -> Bool = { QueryHistoryCaptureStore.isPaused }, + coreMirror: QueryHistoryCoreMirror? = nil ) { self.storage = storage self.rewindAvailability = RewindAvailabilityCache(storage: storage) self.isCapturePaused = isCapturePaused + self.coreMirror = coreMirror } // MARK: - Recording @@ -59,6 +70,7 @@ final class QueryHistoryManager: QueryHistoryRecording, QueryHistoryReading, Que let success = await storage.record(entry) if success { + coreMirror?.scheduleRecorded(entry.id) await MainActor.run { AppEvents.shared.queryHistoryDidUpdate.send(entry.connectionId) } @@ -122,14 +134,15 @@ final class QueryHistoryManager: QueryHistoryRecording, QueryHistoryReading, Que // MARK: - Deleting + // Each reports a failure while the core still holds what went, so nobody is told SQL is gone that is not. func delete(id: UUID) async -> Bool { let success = await storage.delete(id: id) - if success { - await MainActor.run { - AppEvents.shared.queryHistoryDidUpdate.send(nil) - } + guard success else { return false } + let mirrored = await coreMirror?.dropped([id]) ?? true + await MainActor.run { + AppEvents.shared.queryHistoryDidUpdate.send(nil) } - return success + return mirrored } /// Used when the connection itself is gone, so it takes the plan and rewind snapshots with the @@ -137,31 +150,46 @@ final class QueryHistoryManager: QueryHistoryRecording, QueryHistoryReading, Que @discardableResult func deleteEverything(forConnection connectionId: UUID) async -> Bool { let success = await storage.deleteEverything(forConnection: connectionId) - if success { - await MainActor.run { - AppEvents.shared.queryHistoryDidUpdate.send(nil) - } + guard success else { return false } + let mirrored = await coreMirror?.cleared(connectionId: connectionId) ?? true + await MainActor.run { + AppEvents.shared.queryHistoryDidUpdate.send(nil) } - return success + return mirrored } func clear(matching filter: QueryHistoryFilter) async -> Bool { + let everyRow = QueryHistoryStorage.coversEveryRow(filter) + var before: Set? + if coreMirror != nil, !everyRow { + before = await storage.entryIds() + } let success = await storage.clear(matching: filter) - if success { - await MainActor.run { - AppEvents.shared.queryHistoryDidUpdate.send(nil) - } + guard success else { return false } + let mirrored: Bool + if everyRow { + mirrored = await coreMirror?.cleared(connectionId: nil) ?? true + } else if let before, let after = await storage.entryIds() { + mirrored = await coreMirror?.dropped(before.subtracting(after)) ?? true + } else { + mirrored = await coreMirror?.push() ?? true } - return success + await MainActor.run { + AppEvents.shared.queryHistoryDidUpdate.send(nil) + } + return mirrored } // MARK: - Retention + // Then the core takes in the runs it lacks, the previous stable's included. @MainActor func performStartupCleanup() async { await applyRetentionSettings() - guard AppSettingsManager.shared.history.autoCleanup else { return } - await runCleanup() + if AppSettingsManager.shared.history.autoCleanup { + await runCleanup() + } + await coreMirror?.push() } @MainActor @@ -179,6 +207,7 @@ final class QueryHistoryManager: QueryHistoryRecording, QueryHistoryReading, Que private func runCleanup() async { guard await storage.cleanup() else { return } + coreMirror?.schedulePush() await MainActor.run { AppEvents.shared.queryHistoryDidUpdate.send(nil) } diff --git a/apple/TablePro/Core/Storage/QueryHistoryStorage+CoreMirror.swift b/apple/TablePro/Core/Storage/QueryHistoryStorage+CoreMirror.swift new file mode 100644 index 0000000000..62cfb842d3 --- /dev/null +++ b/apple/TablePro/Core/Storage/QueryHistoryStorage+CoreMirror.swift @@ -0,0 +1,137 @@ +import Foundation +import SQLite3 + +// What the core's history keeps of a run: the fields that sync (core ADR 0052, History). +internal struct CoreHistoryRow: Equatable, Sendable { + let id: UUID + let query: String + let connectionId: UUID + let databaseType: String + let executedAt: Date + let executionTime: TimeInterval + let rowCount: Int + let wasSuccessful: Bool + let errorMessage: String? +} + +internal extension QueryHistoryStorage { + // Nil when the store is closed, so a missing store never reads as an empty one. + func entryIds() -> Set? { + guard let db else { return nil } + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + guard sqlite3_prepare_v2(db, "SELECT id FROM history;", -1, &statement, nil) == SQLITE_OK else { + logSqliteError(context: "prepare entry ids") + return nil + } + var ids: Set = [] + while true { + switch sqlite3_step(statement) { + case SQLITE_ROW: + if let text = sqlite3_column_text(statement, 0), let id = UUID(uuidString: String(cString: text)) { + ids.insert(id) + } + case SQLITE_DONE: + return ids + default: + logSqliteError(context: "entry ids") + return nil + } + } + } + + func coreRows(ids: [UUID]) -> [CoreHistoryRow] { + guard let db, !ids.isEmpty else { return [] } + let sql = """ + SELECT id, query, connection_id, database_type, executed_at, execution_time, row_count, + was_successful, error_message + FROM history WHERE id IN (\(Array(repeating: "?", count: ids.count).joined(separator: ","))); + """ + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { + logSqliteError(context: "prepare core rows") + return [] + } + for (offset, id) in ids.enumerated() { + QueryHistorySqlBinding.text(id.uuidString).bind(to: statement, at: Int32(offset + 1)) + } + var rows: [CoreHistoryRow] = [] + while sqlite3_step(statement) == SQLITE_ROW { + guard let idText = sqlite3_column_text(statement, 0), + let id = UUID(uuidString: String(cString: idText)), + let query = sqlite3_column_text(statement, 1).map({ String(cString: $0) }), + let connectionText = sqlite3_column_text(statement, 2), + let connectionId = UUID(uuidString: String(cString: connectionText)) + else { continue } + rows.append(CoreHistoryRow( + id: id, + query: query, + connectionId: connectionId, + databaseType: sqlite3_column_text(statement, 3).map { String(cString: $0) } ?? "", + executedAt: Date(timeIntervalSince1970: sqlite3_column_double(statement, 4)), + executionTime: sqlite3_column_double(statement, 5), + rowCount: Int(sqlite3_column_int64(statement, 6)), + wasSuccessful: sqlite3_column_int(statement, 7) != 0, + errorMessage: sqlite3_column_text(statement, 8).map { String(cString: $0) } + )) + } + return rows + } + + // The runs this store and the core's copy both held when they last agreed. It lives in this file, so a damaged + // file set aside takes it along and the core keeps what it holds; the previous stable never touches it, so a run + // it deleted shows as one that left. Nil when the store is closed. + func coreMirrorBase() -> Set? { + guard let db, execute("CREATE TABLE IF NOT EXISTS core_mirror (id TEXT PRIMARY KEY) WITHOUT ROWID;") else { + return nil + } + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + guard sqlite3_prepare_v2(db, "SELECT id FROM core_mirror;", -1, &statement, nil) == SQLITE_OK else { + logSqliteError(context: "prepare core mirror base") + return nil + } + var ids: Set = [] + while true { + switch sqlite3_step(statement) { + case SQLITE_ROW: + if let text = sqlite3_column_text(statement, 0), let id = UUID(uuidString: String(cString: text)) { + ids.insert(id) + } + case SQLITE_DONE: + return ids + default: + logSqliteError(context: "core mirror base") + return nil + } + } + } + + @discardableResult + func updateCoreMirrorBase(adding added: Set, removing removed: Set) -> Bool { + guard let db, !added.isEmpty || !removed.isEmpty, + execute("CREATE TABLE IF NOT EXISTS core_mirror (id TEXT PRIMARY KEY) WITHOUT ROWID;"), + execute("BEGIN IMMEDIATE;") + else { return added.isEmpty && removed.isEmpty } + let written = Self.each(added, in: db, "INSERT OR IGNORE INTO core_mirror (id) VALUES (?);") + && Self.each(removed, in: db, "DELETE FROM core_mirror WHERE id = ?;") + guard written, execute("COMMIT;") else { + execute("ROLLBACK;") + return false + } + return true + } + + private static func each(_ ids: Set, in db: OpaquePointer, _ sql: String) -> Bool { + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { return false } + for id in ids { + sqlite3_reset(statement) + QueryHistorySqlBinding.text(id.uuidString).bind(to: statement, at: 1) + guard sqlite3_step(statement) == SQLITE_DONE else { return false } + } + return true + } +} diff --git a/apple/TablePro/Core/Storage/QueryHistoryStorage.swift b/apple/TablePro/Core/Storage/QueryHistoryStorage.swift index a45cd61f72..9d97004989 100644 --- a/apple/TablePro/Core/Storage/QueryHistoryStorage.swift +++ b/apple/TablePro/Core/Storage/QueryHistoryStorage.swift @@ -30,6 +30,8 @@ actor QueryHistoryStorage { private var cachedMaxDays: Int = 90 private var cachedAutoCleanup: Bool = true private var insertsSinceCleanup: Int = 0 + // Moves on each retention pass, so the core's copy knows the runs it dropped and drops them too. + private(set) var cleanupRuns = 0 private var didBackfillFingerprints = false var rewindRevision = 0 @@ -1223,6 +1225,7 @@ actor QueryHistoryStorage { @discardableResult private func performCleanup() -> Bool { guard let db else { return false } + cleanupRuns += 1 let changesBefore = sqlite3_total_changes(db) beginTransaction() diff --git a/apple/TablePro/Core/Storage/SQLFavoriteManager.swift b/apple/TablePro/Core/Storage/SQLFavoriteManager.swift index fca41a492b..3a35078d73 100644 --- a/apple/TablePro/Core/Storage/SQLFavoriteManager.swift +++ b/apple/TablePro/Core/Storage/SQLFavoriteManager.swift @@ -12,7 +12,8 @@ import TableProUtilities internal final class SQLFavoriteManager: @unchecked Sendable { static let shared = SQLFavoriteManager( - storage: SQLFavoriteStorage(onSetAside: { DamagedStoreNotice.savedQueriesSetAside($0) }) + storage: SQLFavoriteStorage(onSetAside: { DamagedStoreNotice.savedQueriesSetAside($0) }), + core: .shared ) private static let logger = Logger(subsystem: "com.TablePro", category: "SQLFavoriteManager") @@ -20,15 +21,35 @@ internal final class SQLFavoriteManager: @unchecked Sendable { private let syncTracker: SyncChangeTracker private let appEvents: @MainActor @Sendable () -> AppEvents private let operations = MainActorSerialQueue() + // Nil keeps the saved queries out of the core, for a store nothing else reads. + internal let coreMirror: CoreMirror? init( storage: SQLFavoriteStorage = SQLFavoriteStorage(), syncTracker: SyncChangeTracker = .shared, - appEvents: @escaping @MainActor @Sendable @autoclosure () -> AppEvents = .shared + appEvents: @escaping @MainActor @Sendable @autoclosure () -> AppEvents = .shared, + core: CoreHistoryDatabase? = nil, + mirrorDefaults: UserDefaults = AppStorageEnvironment.shared.defaults ) { self.storage = storage self.syncTracker = syncTracker self.appEvents = appEvents + coreMirror = core.map { database in + let adapter = SavedQueryCoreAdapter(storage: storage, database: database) { queries, folders in + await MainActor.run { + syncTracker.markDirty(.favorite, ids: queries.map(\.uuidString)) + syncTracker.markDirty(.favoriteFolder, ids: folders.map(\.uuidString)) + appEvents().sqlFavoritesDidUpdate.send(nil) + } + } + return CoreMirror(adapter: adapter, defaults: mirrorDefaults) + } + } + + // At launch, and after a write: the core takes what the store holds. + @discardableResult + func pushToCore() async -> Bool { + await coreMirror?.push() ?? true } // MARK: - Favorites @@ -52,13 +73,16 @@ internal final class SQLFavoriteManager: @unchecked Sendable { } } + // A delete waits for the core's copy and reports a failure while the core still holds the SQL. func deleteFavorite(id: UUID) async -> Bool { - await operations.run { [self] in + let deleted = await operations.run { [self] in guard let connectionIds = await storage.deleteFavorites(ids: [id]) else { return false } markDeleted(.favorite, ids: [id], connectionIds: connectionIds) postUpdateNotification(connectionId: nil) return true } + guard deleted else { return false } + return await pushToCore() } func deleteFavorites(ids: [UUID]) async { @@ -67,6 +91,7 @@ internal final class SQLFavoriteManager: @unchecked Sendable { markDeleted(.favorite, ids: ids, connectionIds: connectionIds) postUpdateNotification(connectionId: nil) } + await pushToCore() } /// Tombstones every record it removed, the same as the other delete paths. Deleting a @@ -86,6 +111,7 @@ internal final class SQLFavoriteManager: @unchecked Sendable { markDetachedDirty(removed.detached) postUpdateNotification(connectionId: nil) } + await pushToCore() } /// A row that survived the delete holding a reference the delete had to clear is a local edit @@ -161,6 +187,7 @@ internal final class SQLFavoriteManager: @unchecked Sendable { func finishSyncRefill() async { await storage.finishSyncRefill() + coreMirror?.schedulePush() } func ledgerEntries() async -> [SavedQueryLedger.Entry]? { @@ -222,7 +249,7 @@ internal final class SQLFavoriteManager: @unchecked Sendable { /// to sync. The moved records kept the id of the deleted folder on the wire, so a device /// fetching the account fresh stored a `folderId` matching no folder. func deleteFolder(id: UUID) async -> Bool { - await operations.run { [self] in + let deleted = await operations.run { [self] in guard let deletion = await storage.deleteFolder(id: id) else { return false } syncTracker.markDeleted(.favoriteFolder, ids: [id.uuidString], owner: deletion.connectionId) syncTracker.markDirty(.favorite, ids: deletion.movedFavorites.map(\.uuidString)) @@ -230,6 +257,8 @@ internal final class SQLFavoriteManager: @unchecked Sendable { postUpdateNotification(connectionId: nil) return true } + guard deleted else { return false } + return await pushToCore() } func fetchFolders(connectionId: UUID? = nil) async -> [SQLFavoriteFolder] { @@ -275,19 +304,24 @@ internal final class SQLFavoriteManager: @unchecked Sendable { // MARK: - Remote Apply + // `isStopped` is asked on the store's actor right before each write, so a policy stop that lands while a write + // waits for the store commits nothing after it (core ADR 0055); what already landed stays and the batch arrives + // again. func applyRemote( _ batch: RemoteSQLFavoriteBatch, - echoGuard: SyncEchoGuard? = nil + echoGuard: SyncEchoGuard? = nil, + isStopped: @escaping @Sendable () -> Bool = { false } ) async -> RemoteApplyOutcome { guard !batch.isEmpty else { return .skipped } return await operations.run { [self] in + guard !isStopped() else { return .failed } let refilling = await storage.isAwaitingSyncRefill() let admitted = admitting(batch, echoGuard: echoGuard, refilling: refilling) guard !admitted.isEmpty else { return .skipped } - guard await applyRemoteFavoriteDeletions(admitted.deletedFavoriteIds), - await applyRemoteFolders(admitted.folders), - await applyRemoteFavorites(admitted.favoritesToUpsert), - await applyRemoteFolderDeletions(admitted.deletedFolderIds) + guard await applyRemoteFavoriteDeletions(admitted.deletedFavoriteIds, isStopped: isStopped), + await applyRemoteFolders(admitted.folders, isStopped: isStopped), + await applyRemoteFavorites(admitted.favoritesToUpsert, isStopped: isStopped), + await applyRemoteFolderDeletions(admitted.deletedFolderIds, isStopped: isStopped) else { return .failed } @@ -326,28 +360,33 @@ internal final class SQLFavoriteManager: @unchecked Sendable { } @MainActor - private func applyRemoteFavoriteDeletions(_ ids: Set) async -> Bool { + private func applyRemoteFavoriteDeletions(_ ids: Set, isStopped: @escaping @Sendable () -> Bool) async -> Bool { guard !ids.isEmpty else { return true } - guard await storage.deleteFavorites(ids: Array(ids)) != nil else { return false } + guard case .some(.some) = await storage.unlessStopped(isStopped, { $0.deleteFavorites(ids: Array(ids)) }) else { + return false + } syncTracker.discardDirty(.favorite, ids: ids.map(\.uuidString)) postUpdateNotification(connectionId: nil) return true } @MainActor - private func applyRemoteFolders(_ folders: [SQLFavoriteFolder]) async -> Bool { + private func applyRemoteFolders(_ folders: [SQLFavoriteFolder], isStopped: @escaping @Sendable () -> Bool) async -> Bool { for folder in folders { - let write = await storage.upsertFolder(folder) - guard write.succeeded else { return false } + guard let write = await storage.unlessStopped(isStopped, { $0.upsertFolder(folder) }), write.succeeded else { + return false + } postUpdateNotification(for: write, newConnectionId: folder.connectionId) } return true } @MainActor - private func applyRemoteFavorites(_ favorites: [SQLFavorite]) async -> Bool { + private func applyRemoteFavorites(_ favorites: [SQLFavorite], isStopped: @escaping @Sendable () -> Bool) async -> Bool { guard !favorites.isEmpty else { return true } - guard let result = await storage.applyRemoteFavorites(favorites) else { return false } + guard case .some(.some(let result)) = await storage.unlessStopped(isStopped, { $0.applyRemoteFavorites(favorites) }) else { + return false + } for write in result.writes { postUpdateNotification(for: write.write, newConnectionId: write.connectionId) } @@ -359,11 +398,11 @@ internal final class SQLFavoriteManager: @unchecked Sendable { } @MainActor - private func applyRemoteFolderDeletions(_ ids: Set) async -> Bool { + private func applyRemoteFolderDeletions(_ ids: Set, isStopped: @escaping @Sendable () -> Bool) async -> Bool { guard !ids.isEmpty else { return true } defer { postUpdateNotification(connectionId: nil) } for id in ids { - guard await storage.deleteFolder(id: id) != nil else { return false } + guard case .some(.some) = await storage.unlessStopped(isStopped, { $0.deleteFolder(id: id) }) else { return false } syncTracker.discardDirty(.favoriteFolder, ids: [id.uuidString]) } return true @@ -456,6 +495,7 @@ internal final class SQLFavoriteManager: @unchecked Sendable { // MARK: - Notifications private func postUpdateNotification(connectionId: UUID?) { + coreMirror?.schedulePush() let appEvents = appEvents Task { @MainActor in appEvents().sqlFavoritesDidUpdate.send(connectionId) @@ -488,6 +528,7 @@ extension SQLFavoriteManager: SavedQueryImportStore { syncTracker.markDirty(.favoriteFolder, ids: write.createdFolderIds.map(\.uuidString)) syncTracker.markDirty(.favorite, ids: write.insertedIds.map(\.uuidString)) if !write.insertedIds.isEmpty || !write.createdFolderIds.isEmpty { + coreMirror?.schedulePush() appEvents().sqlFavoritesDidUpdate.send(nil) } return write diff --git a/apple/TablePro/Core/Storage/SQLFavoriteStorage+CoreMirror.swift b/apple/TablePro/Core/Storage/SQLFavoriteStorage+CoreMirror.swift new file mode 100644 index 0000000000..03cf7a3684 --- /dev/null +++ b/apple/TablePro/Core/Storage/SQLFavoriteStorage+CoreMirror.swift @@ -0,0 +1,143 @@ +import Foundation +import SQLite3 + +// The core's copies written back as they are, times included, in one transaction: a collision the core settled, or a +// write of this build's that reached the core before the app ended. Nothing is written when a row moved since the +// mirror read it. +internal extension SQLFavoriteStorage { + // The write runs only when `isStopped` says no here, on the store's actor, and SQLite asks it again as the write + // commits, so a stop that lands while the write waits for the store or for SQLite's lock turns the commit into a + // rollback and the write reports a failure. + func unlessStopped( + _ isStopped: @escaping @Sendable () -> Bool, + _ write: @Sendable (isolated SQLFavoriteStorage) -> Value + ) -> Value? { + guard !isStopped(), let db else { return nil } + let check = Unmanaged.passRetained(CommitStop(isStopped)).toOpaque() + sqlite3_commit_hook(db, { context in + guard let context else { return 0 } + return Unmanaged.fromOpaque(context).takeUnretainedValue().isStopped() ? 1 : 0 + }, check) + defer { + sqlite3_commit_hook(db, nil, nil) + Unmanaged.fromOpaque(check).release() + } + return write(self) + } + + func applyCoreRecords( + favorites: [SQLFavorite], + folders: [SQLFavoriteFolder], + removedFavoriteIds: [UUID], + removedFolderIds: [UUID], + expected: [SavedQueryMirrorKey: SavedQueryMirrorValue] + ) -> Bool { + // On the actor and before the transaction, so no write of this store comes between the check and the write. + let touched = favorites.map { SavedQueryMirrorKey.query($0.id) } + folders.map { .folder($0.id) } + + removedFavoriteIds.map { .query($0) } + removedFolderIds.map { .folder($0) } + guard touched.allSatisfy({ current($0) == expected[$0] }) else { return false } + return inTransaction { () -> Bool? in + // Keywords move between rows here, and the unique index would refuse a row that takes one before the + // row giving it up was removed or written, so removals and cleared keywords go first. + guard delete(from: "favorites", ids: removedFavoriteIds), + delete(from: "folders", ids: removedFolderIds), + clearKeywords(of: favorites.map(\.id)), + folders.allSatisfy({ writeFolder($0) }), + favorites.allSatisfy({ writeFavorite($0) }) + else { + return nil + } + return true + } ?? false + } + + private func current(_ key: SavedQueryMirrorKey) -> SavedQueryMirrorValue? { + switch key { + case .query(let id): fetchFavorite(id: id).map { .query(.init($0)) } + case .folder(let id): fetchFolder(id: id).map { .folder(.init($0)) } + } + } + + private func clearKeywords(of ids: [UUID]) -> Bool { + ids.isEmpty || run( + "UPDATE favorites SET keyword = NULL WHERE id IN (\(Self.placeholders(count: ids.count)));", + bindings: ids.map(\.uuidString) + ) + } + + private func delete(from table: String, ids: [UUID]) -> Bool { + ids.isEmpty || run( + "DELETE FROM \(table) WHERE id IN (\(Self.placeholders(count: ids.count)));", + bindings: ids.map(\.uuidString) + ) + } + + private func writeFavorite(_ favorite: SQLFavorite) -> Bool { + let sql = """ + INSERT INTO favorites (id, name, query, keyword, folder_id, connection_id, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, query = excluded.query, keyword = excluded.keyword, + folder_id = excluded.folder_id, connection_id = excluded.connection_id, + sort_order = excluded.sort_order, created_at = excluded.created_at, updated_at = excluded.updated_at; + """ + return step(sql) { statement in + Self.bind(favorite.id.uuidString, to: statement, at: 1) + Self.bind(favorite.name, to: statement, at: 2) + Self.bind(favorite.query, to: statement, at: 3) + Self.bind(favorite.keyword, to: statement, at: 4) + Self.bind(favorite.folderId?.uuidString, to: statement, at: 5) + Self.bind(favorite.connectionId?.uuidString, to: statement, at: 6) + sqlite3_bind_int(statement, 7, Int32(clamping: favorite.sortOrder)) + sqlite3_bind_double(statement, 8, favorite.createdAt.timeIntervalSince1970) + sqlite3_bind_double(statement, 9, favorite.updatedAt.timeIntervalSince1970) + } + } + + private func writeFolder(_ folder: SQLFavoriteFolder) -> Bool { + let sql = """ + INSERT INTO folders (id, name, parent_id, connection_id, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, parent_id = excluded.parent_id, connection_id = excluded.connection_id, + sort_order = excluded.sort_order, created_at = excluded.created_at, updated_at = excluded.updated_at; + """ + return step(sql) { statement in + Self.bind(folder.id.uuidString, to: statement, at: 1) + Self.bind(folder.name, to: statement, at: 2) + Self.bind(folder.parentId?.uuidString, to: statement, at: 3) + Self.bind(folder.connectionId?.uuidString, to: statement, at: 4) + sqlite3_bind_int(statement, 5, Int32(clamping: folder.sortOrder)) + sqlite3_bind_double(statement, 6, folder.createdAt.timeIntervalSince1970) + sqlite3_bind_double(statement, 7, folder.updatedAt.timeIntervalSince1970) + } + } + + private func step(_ sql: String, binding: (OpaquePointer?) -> Void) -> Bool { + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { return false } + binding(statement) + return sqlite3_step(statement) == SQLITE_DONE + } + + private static func bind(_ text: String?, to statement: OpaquePointer?, at index: Int32) { + guard let text else { + sqlite3_bind_null(statement, index) + return + } + sqlite3_bind_text(statement, index, text, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self)) + } + + private static func placeholders(count: Int) -> String { + Array(repeating: "?", count: count).joined(separator: ",") + } +} + +private final class CommitStop { + let isStopped: @Sendable () -> Bool + + init(_ isStopped: @escaping @Sendable () -> Bool) { + self.isStopped = isStopped + } +} diff --git a/apple/TablePro/Core/Storage/TableFolderStorage.swift b/apple/TablePro/Core/Storage/TableFolderStorage.swift index 2a6dbfc8a1..03dd7f581c 100644 --- a/apple/TablePro/Core/Storage/TableFolderStorage.swift +++ b/apple/TablePro/Core/Storage/TableFolderStorage.swift @@ -14,7 +14,7 @@ extension Notification.Name { // A folder only records which objects it holds, so nothing here ever reaches the database. @MainActor internal final class TableFolderStorage: TableScopedSettingsStore { - static let shared = TableFolderStorage() + static let shared = TableFolderStorage(core: .shared) nonisolated static let connectionIdUserInfoKey = "connectionId" private static let logger = Logger(subsystem: "com.TablePro", category: "TableFolderStorage") @@ -44,15 +44,22 @@ internal final class TableFolderStorage: TableScopedSettingsStore { private var documents: [UUID: Document] = [:] // Read as empty and never written, so a damaged or newer document is not replaced by the next edit. private var unreadableConnectionIds: Set = [] + // Nil keeps the folders out of the core, for a store nothing else reads. + private(set) var coreMirror: CoreMirror? init( defaults: KeyValueStore = AppStorageEnvironment.shared.defaults, syncTracker: SyncChangeTracker = .shared, - notificationCenter: NotificationCenter = .default + notificationCenter: NotificationCenter = .default, + core: CoreHistoryDatabase? = nil, + mirrorDefaults: UserDefaults = AppStorageEnvironment.shared.defaults ) { self.store = defaults self.syncTracker = syncTracker self.notificationCenter = notificationCenter + if let core { + coreMirror = CoreMirror(adapter: TableFolderCoreAdapter(store: self, database: core), defaults: mirrorDefaults) + } } // MARK: - Reading @@ -272,6 +279,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { touched[connectionId] = document } commitRemote(touched) + coreMirror?.schedulePush() } // Placements go with their folder; waiting for their own tombstones would hide the objects meanwhile. @@ -292,6 +300,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { discardedItems += removedItems.map(\.syncId) } commitRemote(touched) + coreMirror?.schedulePush() syncTracker.discardDirty(.tableFolder, ids: discardedFolders) syncTracker.discardDirty(.tableFolderItem, ids: discardedItems) } @@ -302,6 +311,42 @@ internal final class TableFolderStorage: TableScopedSettingsStore { postChange(for: Set(written.keys)) } + // MARK: - The core's copy + + var hasUnreadableDocumentsAfterReadingAll: Bool { + _ = storedConnectionIds().map(document(for:)) + return hasUnreadableDocuments + } + + // The core's copy written back, marking nothing: it came from this Mac or a pull, never a new edit here. + func applyCoreRecords( + folders: [TableFolder], + items: [TableFolderItem], + removedFolderIds: Set, + removedItemKeys: Set + ) { + let connections = Set(folders.map(\.scope.connectionId)) + .union(items.map(\.scope.connectionId)) + .union(storedConnectionIds()) + var touched: [UUID: Document] = [:] + for connectionId in connections { + var document = document(for: connectionId) + let before = document + let incomingFolders = folders.filter { $0.scope.connectionId == connectionId } + let incomingItems = items.filter { $0.scope.connectionId == connectionId } + let replacedFolders = Set(incomingFolders.map(\.id)).union(removedFolderIds) + let replacedItems = Set(incomingItems.map(\.key)).union(removedItemKeys) + document.folders.removeAll { replacedFolders.contains($0.id) } + document.folders += incomingFolders + document.items.removeAll { replacedItems.contains($0.key) } + document.items += incomingItems + if document != before { + touched[connectionId] = document + } + } + commitRemote(touched) + } + // MARK: - TableScopedSettingsStore func renameTable(from oldScope: TableScope, to newScope: TableScope) { @@ -390,6 +435,9 @@ internal final class TableFolderStorage: TableScopedSettingsStore { } purged.insert(connectionId) } + if !purged.isEmpty { + coreMirror?.schedulePush() + } postChange(for: purged) } @@ -404,6 +452,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { @discardableResult private func commit(_ document: Document, for connectionId: UUID, marks: SyncMarks) -> Bool { guard persist(document, for: connectionId) else { return false } + coreMirror?.schedulePush() syncTracker.markDeleted(.tableFolder, ids: marks.deletedFolders, owner: connectionId) syncTracker.markDeleted(.tableFolderItem, ids: marks.deletedItems, owner: connectionId) syncTracker.markDirty(.tableFolder, ids: marks.dirtyFolders) diff --git a/apple/TablePro/Core/Sync/SyncCoordinator.swift b/apple/TablePro/Core/Sync/SyncCoordinator.swift index 13c33a41b6..2baf6b8f87 100644 --- a/apple/TablePro/Core/Sync/SyncCoordinator.swift +++ b/apple/TablePro/Core/Sync/SyncCoordinator.swift @@ -42,8 +42,12 @@ final class SyncCoordinator: ObservableObject { private var policyCancellable: AnyCancellable? // Counts the organization's stops, so a run that began before one keeps nothing after it, even once iCloud is // allowed again. - private var policyStops = 0 + private var policyStops = 0 { + didSet { policyStopCount.value = policyStops } + } private var runPolicyStops = 0 + // The same count for a store's actor, which asks it right before each write a pull makes. + private let policyStopCount = PolicyStopCount() // Cancelled by a stop, so the transport sends no further batch or retry of it. private var pushInFlight: Task? private var debounceTask: Task? @@ -826,7 +830,8 @@ final class SyncCoordinator: ObservableObject { guard !isStoppedByPolicy else { return false } let favoritesOutcome = await services.sqlFavoriteManager.applyRemote( remoteSQLFavoriteBatch(from: admitted, deletedRecordIDs: deletedRecordIDs, settings: settings), - echoGuard: echoGuard + echoGuard: echoGuard, + isStopped: { [policyStopCount, runPolicyStops] in policyStopCount.value != runPolicyStops } ) /// The token and the cache are the record of what this device holds, so neither is @@ -1369,3 +1374,12 @@ private final class SyncTriggers { NotificationCenter.default.removeObserver(accountObserver) } } + +private final class PolicyStopCount: Sendable { + private let count = OSAllocatedUnfairLock(initialState: 0) + + var value: Int { + get { count.withLock { $0 } } + set { count.withLock { $0 = newValue } } + } +} diff --git a/apple/TableProTests/Core/Storage/CoreMirror/CoreMirrorFixture.swift b/apple/TableProTests/Core/Storage/CoreMirror/CoreMirrorFixture.swift new file mode 100644 index 0000000000..3f89eeafd5 --- /dev/null +++ b/apple/TableProTests/Core/Storage/CoreMirror/CoreMirrorFixture.swift @@ -0,0 +1,31 @@ +import Foundation +@testable import TablePro +import TableProFFI + +// A folder of its own for each test's stores and the core's history.db beside them. +final class CoreMirrorFixture { + let directory: URL + let core: CoreHistoryDatabase + let pool = EphemeralDefaultsPool() + + init() throws { + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("CoreMirror-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + core = CoreHistoryDatabase(folder: directory.appendingPathComponent("Core", isDirectory: true), clientVersion: "test") + } + + deinit { + try? FileManager.default.removeItem(at: directory) + } + + func url(_ name: String) -> URL { + directory.appendingPathComponent(name) + } +} + +extension Array where Element == String { + var uuids: Set { + Set(compactMap(UUID.init(uuidString:))) + } +} diff --git a/apple/TableProTests/Core/Storage/CoreMirror/FavoriteCoreMirrorTests.swift b/apple/TableProTests/Core/Storage/CoreMirror/FavoriteCoreMirrorTests.swift new file mode 100644 index 0000000000..78142f1725 --- /dev/null +++ b/apple/TableProTests/Core/Storage/CoreMirror/FavoriteCoreMirrorTests.swift @@ -0,0 +1,148 @@ +import Foundation +@testable import TablePro +import TableProFFI +import TableProSyncTransport +import Testing + +@MainActor +struct FavoriteCoreMirrorTests { + private let fixture: CoreMirrorFixture + private let connectionId = UUID() + + init() throws { + fixture = try CoreMirrorFixture() + } + + private func tracker() throws -> SyncChangeTracker { + SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: try fixture.pool.make().defaults)) + } + + private func favoriteTables(_ defaults: UserDefaults) throws -> FavoriteTablesStorage { + FavoriteTablesStorage(userDefaults: defaults, syncTracker: try tracker(), core: fixture.core) + } + + @Test("Favourite tables move in, and a toggle and the previous stable's removal reach the core") + func favoriteTablesReachTheCore() async throws { + let defaults = try fixture.pool.make().defaults + let store = try favoriteTables(defaults) + store.addFavorite(name: "orders", schema: "public", database: "shop", connectionId: connectionId) + store.addFavorite(name: "users", schema: nil, database: "shop", connectionId: connectionId) + let mirror = try #require(store.coreMirror) + await mirror.push() + + var tables = try await fixture.core.favourites().contents().tables + let names = tables.map { $0.name }.sorted() + #expect(names == ["orders", "users"]) + #expect(tables.first { $0.name == "orders" }?.schema == "public") + + // The previous stable writes the defaults alone; this build's next launch reads them. + let kept = store.loadFavorites().filter { $0.name != "users" } + defaults.set(try JSONEncoder().encode(Array(kept)), forKey: "com.TablePro.favoriteTables") + let relaunched = try favoriteTables(defaults) + await relaunched.coreMirror?.push() + + tables = try await fixture.core.favourites().contents().tables + #expect(tables.map { $0.name } == ["orders"]) + } + + @Test("Favourites that no longer decode take nothing out of the core") + func unreadableFavoritesKeepTheCoreCopy() async throws { + let defaults = try fixture.pool.make().defaults + let store = try favoriteTables(defaults) + store.addFavorite(name: "orders", schema: nil, database: "shop", connectionId: connectionId) + await store.coreMirror?.push() + defaults.set(Data("not json".utf8), forKey: "com.TablePro.favoriteTables") + + let relaunched = try favoriteTables(defaults) + await relaunched.coreMirror?.push() + + let tables = try await fixture.core.favourites().contents().tables + #expect(tables.map { $0.name } == ["orders"]) + } + + @Test("Favourite databases move in with their environment and leave the tables alone") + func favoriteDatabasesReachTheCore() async throws { + let tables = try favoriteTables(try fixture.pool.make().defaults) + tables.addFavorite(name: "orders", schema: nil, database: "shop", connectionId: connectionId) + await tables.coreMirror?.push() + let store = FavoriteDatabasesStorage( + defaults: try fixture.pool.make().defaults, + syncTracker: try tracker(), + core: fixture.core + ) + store.setFavorite(database: "shop", environment: .production, connectionId: connectionId) + store.setFavorite(database: "audit", environment: .testing, connectionId: connectionId) + await store.coreMirror?.push() + + store.removeFavorite(database: "audit", connectionId: connectionId) + await store.coreMirror?.push() + + let contents = try await fixture.core.favourites().contents() + #expect(contents.databases.map { $0.database } == ["shop"]) + #expect(contents.databases.first?.environment == .production) + #expect(contents.tables.map { $0.name } == ["orders"]) + } + + @Test("Table folders move in with their ids and times, and a folder deleted here leaves the core with its items") + func tableFoldersReachTheCore() async throws { + let store = TableFolderStorage( + defaults: try fixture.pool.make().defaults, + syncTracker: try tracker(), + core: fixture.core, + mirrorDefaults: try fixture.pool.make().defaults + ) + let scope = DatabaseScope(connectionId: connectionId, database: "shop", schema: nil) + let folder = store.createFolder(named: "Billing", in: scope, containing: ["invoices"]) + let mirror = try #require(store.coreMirror) + await mirror.push() + + var contents = try await fixture.core.tableFolders().contents() + let held = try #require(contents.folders.first) + #expect(UUID(uuidString: held.id) == folder.id) + #expect(held.createdAtMs == CoreMirrorTime.milliseconds(folder.createdAt)) + #expect(held.schema.isEmpty) + #expect(contents.items.map { $0.table.name } == ["invoices"]) + + store.deleteFolder(id: folder.id, connectionId: connectionId) + await mirror.push() + + contents = try await fixture.core.tableFolders().contents() + #expect(contents.folders.isEmpty) + #expect(contents.items.isEmpty) + } + + @Test("A table folder the core holds and the Mac's store lost comes back into the store") + func tableFolderFromTheCoreComesBack() async throws { + let defaults = try fixture.pool.make().defaults + let mirrorDefaults = try fixture.pool.make().defaults + let store = TableFolderStorage( + defaults: defaults, + syncTracker: try tracker(), + core: fixture.core, + mirrorDefaults: mirrorDefaults + ) + let scope = DatabaseScope(connectionId: connectionId, database: "shop", schema: "public") + _ = store.createFolder(named: "Billing", in: scope) + await store.coreMirror?.push() + let added = TableFolderRecord( + id: UUID().uuidString, + connectionId: connectionId.uuidString, + database: "shop", + schema: "public", + name: "Reports", + createdAtMs: 1_700_000_000_000, + updatedAtMs: 1_700_000_000_000 + ) + _ = try await fixture.core.tableFolders().writeRecords(write: TableFolderRecordWrite( + folders: [added], + items: [], + removedFolders: [], + removedItems: [] + )) + + await store.coreMirror?.push() + + let names = store.layout(in: scope).folders.map { $0.name } + #expect(names == ["Billing", "Reports"]) + } +} diff --git a/apple/TableProTests/Core/Storage/CoreMirror/QueryHistoryCoreMirrorTests.swift b/apple/TableProTests/Core/Storage/CoreMirror/QueryHistoryCoreMirrorTests.swift new file mode 100644 index 0000000000..0dd00b3fc5 --- /dev/null +++ b/apple/TableProTests/Core/Storage/CoreMirror/QueryHistoryCoreMirrorTests.swift @@ -0,0 +1,109 @@ +import Foundation +@testable import TablePro +import TableProFFI +import Testing + +struct QueryHistoryCoreMirrorTests { + private let fixture: CoreMirrorFixture + private let storage: QueryHistoryStorage + private let mirror: QueryHistoryCoreMirror + private let manager: QueryHistoryManager + private let connectionId = UUID() + + init() throws { + fixture = try CoreMirrorFixture() + storage = QueryHistoryStorage(databaseURL: fixture.url("query_history.db")) + let connectionId = connectionId + mirror = QueryHistoryCoreMirror(storage: storage, database: fixture.core) { ids in + ids.contains(connectionId) ? [connectionId: "shop"] : [:] + } + manager = QueryHistoryManager(storage: storage, isCapturePaused: { false }, coreMirror: mirror) + } + + private func run(_ query: String, succeeded: Bool = true, at seconds: TimeInterval) -> QueryHistoryEntry { + QueryHistoryEntry( + query: query, + connectionId: connectionId, + databaseName: "shop", + databaseType: .postgresql, + source: .editor, + executedAt: Date(timeIntervalSince1970: seconds), + executionTime: 0.25, + rowCount: 3, + wasSuccessful: succeeded, + errorMessage: succeeded ? nil : "syntax error" + ) + } + + private func coreIds() async throws -> Set { + try await fixture.core.history().recordIds().uuids + } + + @Test("The history moves into the core under the Mac's ids, with the fields that sync") + func historyMovesInUnderItsIds() async throws { + let failed = run("SELECT broken", succeeded: false, at: 1_700_000_000) + #expect(await storage.record(failed)) + #expect(await storage.record(run("SELECT 1", at: 1_700_000_100))) + + await mirror.push() + + let mine = await storage.entryIds() ?? [] + #expect(mine.count == 2) + #expect(try await coreIds() == mine) + let page = try await fixture.core.history().search(text: "broken", connectionId: nil, after: nil, limit: 10) + let entry = try #require(page.entries.first) + #expect(UUID(uuidString: entry.recordId) == failed.id) + #expect(entry.connectionName == "shop") + #expect(entry.driverId == DatabaseType.postgresql.rawValue) + #expect(entry.executedAtMs == 1_700_000_000_000) + #expect(entry.durationMs == 250) + #expect(entry.outcome == .failed(message: "syntax error")) + } + + @Test("A run recorded through the manager reaches the core, and a deleted one leaves it") + func recordedAndDeletedRunsReachTheCore() async throws { + let entry = run("SELECT 1", at: 1_700_000_000) + #expect(await manager.record(entry)) + await mirror.recorded(entry.id) + #expect(try await coreIds() == [entry.id]) + + #expect(await manager.delete(id: entry.id)) + await mirror.push() + + #expect(try await coreIds().isEmpty) + } + + @Test("Runs the previous stable recorded and deleted after a downgrade reach the core") + func previousStableRunsReachTheCore() async throws { + let first = run("SELECT 1", at: 1_700_000_000) + #expect(await storage.record(first)) + await mirror.push() + + let later = run("SELECT 2", at: 1_700_000_100) + #expect(await storage.record(later)) + #expect(await storage.delete(id: first.id)) + await mirror.push() + + #expect(try await coreIds() == [later.id]) + } + + @Test("A history file set aside for damage leaves the core's runs, and Clear History clears them") + func setAsideKeepsTheCoreRuns() async throws { + let kept = run("SELECT kept", at: 1_700_000_000) + #expect(await storage.record(kept)) + await mirror.push() + + let replacement = QueryHistoryStorage(databaseURL: fixture.url("replacement.db")) + let replacementMirror = QueryHistoryCoreMirror(storage: replacement, database: fixture.core) { _ in [:] } + #expect(await replacementMirror.push()) + #expect(try await coreIds() == [kept.id]) + + let replacementManager = QueryHistoryManager( + storage: replacement, + isCapturePaused: { false }, + coreMirror: replacementMirror + ) + #expect(await replacementManager.clear(matching: QueryHistoryFilter(scope: .all))) + #expect(try await coreIds().isEmpty) + } +} diff --git a/apple/TableProTests/Core/Storage/CoreMirror/SavedQueryCoreMirrorTests.swift b/apple/TableProTests/Core/Storage/CoreMirror/SavedQueryCoreMirrorTests.swift new file mode 100644 index 0000000000..f11a996956 --- /dev/null +++ b/apple/TableProTests/Core/Storage/CoreMirror/SavedQueryCoreMirrorTests.swift @@ -0,0 +1,239 @@ +import Foundation +import os +@testable import TablePro +import TableProFFI +import TableProSyncTransport +import Testing + +struct SavedQueryCoreMirrorTests { + private let fixture: CoreMirrorFixture + private let storage: SQLFavoriteStorage + private let metadata: SyncMetadataStorage + private let manager: SQLFavoriteManager + private let connectionId = UUID() + + init() throws { + fixture = try CoreMirrorFixture() + storage = SQLFavoriteStorage(databaseURL: fixture.url("sql_favorites.db")) + metadata = SyncMetadataStorage(userDefaults: try fixture.pool.make().defaults, prefix: "tests.\(UUID().uuidString)") + manager = SQLFavoriteManager( + storage: storage, + syncTracker: SyncChangeTracker(metadataStorage: metadata), + core: fixture.core, + mirrorDefaults: try fixture.pool.make().defaults + ) + } + + private func coreContents() async throws -> SavedQueryStoreContents { + try await fixture.core.savedQueries().contents() + } + + private func favorite(_ name: String, keyword: String? = nil, folderId: UUID? = nil, createdAt: Date) -> SQLFavorite { + SQLFavorite( + name: name, + query: "SELECT '\(name)'", + keyword: keyword, + folderId: folderId, + connectionId: connectionId, + sortOrder: 3, + createdAt: createdAt, + updatedAt: createdAt.addingTimeInterval(5) + ) + } + + @Test("The first push moves every saved query and folder in under its own id, with its times and place") + func firstPushKeepsIdsTimesAndPlaces() async throws { + let folder = SQLFavoriteFolder(name: "Reports", connectionId: connectionId, sortOrder: 1) + let daily = favorite("Daily", keyword: "dl", folderId: folder.id, createdAt: Date(timeIntervalSince1970: 1_700_000_000.123)) + #expect(await storage.addFolder(folder)) + #expect(await storage.addFavorite(daily)) + + await manager.pushToCore() + + let contents = try await coreContents() + let query = try #require(contents.queries.first) + #expect(UUID(uuidString: query.id) == daily.id) + #expect(UUID(uuidString: query.folderId ?? "") == folder.id) + #expect(UUID(uuidString: query.connectionId ?? "") == connectionId) + #expect(query.keyword == "dl") + #expect(query.order == 3) + #expect(query.createdAtMs == 1_700_000_000_123) + #expect(query.updatedAtMs == 1_700_000_005_123) + let folderIds = contents.folders.map { $0.id }.uuids + #expect(folderIds == [folder.id]) + } + + @Test("A save, an edit and a delete through the manager reach the core") + func managerWritesReachTheCore() async throws { + let report = favorite("Report", createdAt: Date(timeIntervalSince1970: 1_000)) + #expect(await manager.addFavorite(report)) + await manager.pushToCore() + let saved = try await coreContents().queries.map { $0.id }.uuids + #expect(saved == [report.id]) + + var edited = report + edited.query = "SELECT 2" + #expect(await manager.updateFavorite(edited)) + await manager.pushToCore() + #expect(try await coreContents().queries.first?.sql == "SELECT 2") + + #expect(await manager.deleteFavorite(id: report.id)) + await manager.pushToCore() + #expect(try await coreContents().queries.isEmpty) + } + + @Test("Two saved queries of one name in a connection move in with the later one renamed, and the rename syncs") + func collidingNamesSettleAndSync() async throws { + let older = favorite("Report", createdAt: Date(timeIntervalSince1970: 1_000)) + let newer = favorite("Report", createdAt: Date(timeIntervalSince1970: 2_000)) + #expect(await storage.addFavorite(older)) + #expect(await storage.addFavorite(newer)) + + await manager.pushToCore() + + #expect(await storage.fetchFavorite(id: older.id)?.name == "Report") + #expect(await storage.fetchFavorite(id: newer.id)?.name == "Report (2)") + #expect(metadata.dirtyIds(for: .favorite) == [newer.id.uuidString]) + let names = try await coreContents().queries.map { $0.name }.sorted() + #expect(names == ["Report", "Report (2)"]) + } + + @Test("An older query of one name arriving later renames the one already agreed, and that rename syncs") + func settlementOfAnAgreedQuerySyncs() async throws { + let agreed = favorite("Report", createdAt: Date(timeIntervalSince1970: 2_000)) + #expect(await storage.addFavorite(agreed)) + await manager.pushToCore() + let older = favorite("Report", createdAt: Date(timeIntervalSince1970: 1_000)) + #expect(await storage.addFavorite(older)) + + await manager.pushToCore() + + #expect(await storage.fetchFavorite(id: older.id)?.name == "Report") + #expect(await storage.fetchFavorite(id: agreed.id)?.name == "Report (2)") + #expect(metadata.dirtyIds(for: .favorite) == [agreed.id.uuidString]) + } + + @Test("What the previous stable changed and deleted in its store after a downgrade reaches the core") + func previousStableEditsReachTheCore() async throws { + let kept = favorite("Kept", createdAt: Date(timeIntervalSince1970: 1_000)) + let dropped = favorite("Dropped", createdAt: Date(timeIntervalSince1970: 2_000)) + #expect(await storage.addFavorite(kept)) + #expect(await storage.addFavorite(dropped)) + await manager.pushToCore() + + var edited = kept + edited.name = "Kept, renamed by 0.88" + #expect(await storage.updateFavorite(edited).succeeded) + #expect(await storage.deleteFavorites(ids: [dropped.id]) != nil) + await manager.pushToCore() + + let contents = try await coreContents() + let held = contents.queries.map { $0.id }.uuids + #expect(held == [kept.id]) + #expect(contents.queries.first?.name == "Kept, renamed by 0.88") + } + + @Test("A write that reached the core and not the Mac's store comes back into the store") + func coreAheadComesBack() async throws { + let report = favorite("Report", createdAt: Date(timeIntervalSince1970: 1_000)) + #expect(await storage.addFavorite(report)) + await manager.pushToCore() + var record = try #require(try await coreContents().queries.first) + record.name = "Renamed in the core" + _ = try await fixture.core.savedQueries().writeRecords(write: SavedQueryRecordWrite( + queries: [record], + folders: [], + removedQueries: [], + removedFolders: [] + )) + + await manager.pushToCore() + + #expect(await storage.fetchFavorite(id: report.id)?.name == "Renamed in the core") + #expect(metadata.dirtyIds(for: .favorite).isEmpty) + } + + @Test("A deletion that reached the core before a crash, then one on the previous stable, leaves both gone") + func deletionsOnBothSidesStayDeleted() async throws { + let first = favorite("First", createdAt: Date(timeIntervalSince1970: 1_000)) + let second = favorite("Second", createdAt: Date(timeIntervalSince1970: 2_000)) + #expect(await storage.addFavorite(first)) + #expect(await storage.addFavorite(second)) + await manager.pushToCore() + #expect(await storage.deleteFavorites(ids: [first.id]) != nil) + _ = try await fixture.core.savedQueries().writeRecords(write: SavedQueryRecordWrite( + queries: [], + folders: [], + removedQueries: [first.id.uuidString], + removedFolders: [] + )) + #expect(await storage.deleteFavorites(ids: [second.id]) != nil) + + await manager.pushToCore() + + #expect(try await coreContents().queries.isEmpty) + #expect(await storage.readAllFavorites()?.isEmpty == true) + } + + @Test("A pushed store pushes nothing again until it changes") + func aSecondPushWritesNothing() async throws { + #expect(await storage.addFavorite(favorite("Report", createdAt: Date(timeIntervalSince1970: 1_000)))) + await manager.pushToCore() + let digest = try await coreContents().digest + + await manager.pushToCore() + + #expect(try await coreContents().digest == digest) + } + + @Test("A policy stop before a pull's apply writes nothing of it (P1-M4)") + func policyStopEndsTheApply() async throws { + let deleted = favorite("Deleted", createdAt: Date(timeIntervalSince1970: 1_000)) + #expect(await storage.addFavorite(deleted)) + let folder = SQLFavoriteFolder(name: "Pulled", connectionId: connectionId) + let pulled = favorite("Pulled", createdAt: Date(timeIntervalSince1970: 2_000)) + // The check before the apply starts passes; the stop lands before the store's first write. + let checks = StopAfter(checks: 1) + + let outcome = await manager.applyRemote( + RemoteSQLFavoriteBatch(favorites: [pulled], folders: [folder], deletedFavoriteIds: [deleted.id]), + isStopped: { checks.isStopped() } + ) + + #expect(outcome == .failed) + #expect(await storage.fetchFavorite(id: deleted.id) != nil) + #expect(await storage.fetchFolder(id: folder.id) == nil) + #expect(await storage.fetchFavorite(id: pulled.id) == nil) + } + + @Test("A stop that lands while a pulled write waits to commit rolls the write back (P1-M4)") + func stopWhileTheWriteWaits() async throws { + let pulled = SQLFavoriteFolder(name: "Pulled", connectionId: connectionId) + // The checks before the apply and on the store's actor pass; SQLite's commit asks again and sees the stop. + let stop = StopAfter(checks: 2) + + let outcome = await manager.applyRemote( + RemoteSQLFavoriteBatch(folders: [pulled]), + isStopped: { stop.isStopped() } + ) + + #expect(outcome == .failed) + #expect(await storage.fetchFolder(id: pulled.id) == nil) + } +} + +private final class StopAfter: Sendable { + private let remaining: OSAllocatedUnfairLock + + init(checks: Int) { + remaining = OSAllocatedUnfairLock(initialState: checks) + } + + func isStopped() -> Bool { + remaining.withLock { left in + guard left > 0 else { return true } + left -= 1 + return false + } + } +} diff --git a/apple/scripts/probes/check-history-downgrade.sh b/apple/scripts/probes/check-history-downgrade.sh new file mode 100755 index 0000000000..d384637edd --- /dev/null +++ b/apple/scripts/probes/check-history-downgrade.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# T-DWN for the saved queries, favourites, table folders and history (core ADR 0010, slices 3 and 9): the previous +# stable keeps reading the stores this build writes, and this build's core copy takes in what was written there while +# it was not running. Both apps run in one storage sandbox, one at a time. The edits between runs are written straight +# into the stores, in the formats the previous stable writes, since its UI cannot be scripted. +# +# Usage: check-history-downgrade.sh +set -euo pipefail + +NEW_APP="$(cd "${1:?the TablePro.app of this build}" && pwd)" +OLD_APP="$(cd "${2:?the TablePro.app of the previous stable}" && pwd)" +if pgrep -x TablePro >/dev/null; then + echo "Quit every TablePro first: a run here must be the only one" >&2 + exit 2 +fi +SANDBOX="$(mktemp -d "${TMPDIR:-/tmp}/tablepro-history-downgrade.XXXXXX")" +SUPPORT="$SANDBOX/TablePro" +mkdir -p "$SUPPORT" +touch "$SUPPORT/.defaults-suite" +FAVORITES="$SUPPORT/sql_favorites.db" +HISTORY="$SUPPORT/query_history.db" +CORE="$SUPPORT/Core/state/history.db" + +# PluginHostStorage.suiteName(forSandboxAt:): FNV-1a over the sandbox path. +SUITE="$(python3 -I -c ' +import sys +h = 0xcbf29ce484222325 +for b in sys.argv[1].encode(): + h = ((h ^ b) * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF +print("com.TablePro.uitest.%016x" % h) +' "$SANDBOX")" + +cleanup() { + [ -z "${PID:-}" ] || kill "$PID" 2>/dev/null || true + defaults delete "$SUITE" >/dev/null 2>&1 || true + rm -rf "$SANDBOX" +} +trap cleanup EXIT + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +core() { + [ -f "$CORE" ] || return 0 + sqlite3 -readonly "$CORE" "$1" 2>/dev/null | paste -sd'|' - +} + +# Launches the app until `check` passes or 90 seconds go by, then stops it. +run() { + local app="$1" check="$2" + TABLEPRO_UI_TEST_SANDBOX="$SANDBOX" "$app/Contents/MacOS/TablePro" >/dev/null 2>&1 & + PID=$! + for _ in $(seq 1 90); do + eval "$check" && break + sleep 1 + done + sleep 3 + kill "$PID" 2>/dev/null || true + wait "$PID" 2>/dev/null || true + PID="" +} + +CONNECTION=55555555-5555-4555-8555-555555555555 +FOLDER=66666666-6666-4666-8666-666666666666 +OLDER=77777777-7777-4777-8777-777777777777 +NEWER=88888888-8888-4888-8888-888888888888 +FIRST_RUN=99999999-9999-4999-8999-999999999999 +SECOND_RUN=AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA +TABLE_FOLDER=BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB +# Within the default 90-day history window, so the launch's retention pass keeps the runs. +NOW="$(date +%s)" + +# The previous stable makes its own stores first. +run "$OLD_APP" '[ -f "$HISTORY" ]' +[ -f "$HISTORY" ] || fail "the previous stable made no query history" + +# What it holds before this build ever ran: two saved queries of one name in one connection and a folder, two runs, +# a favourite table and database, and a table folder with a table in it. +sqlite3 "$FAVORITES" < Date: Thu, 26 Nov 2026 17:33:52 +0700 Subject: [PATCH 4/5] test(macos): the downgrade probe plants the saved queries' full-text index and leaves other TablePro apps running --- .../scripts/probes/check-history-downgrade.sh | 49 +++++++++++++++---- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/apple/scripts/probes/check-history-downgrade.sh b/apple/scripts/probes/check-history-downgrade.sh index d384637edd..92b7484426 100755 --- a/apple/scripts/probes/check-history-downgrade.sh +++ b/apple/scripts/probes/check-history-downgrade.sh @@ -9,8 +9,9 @@ set -euo pipefail NEW_APP="$(cd "${1:?the TablePro.app of this build}" && pwd)" OLD_APP="$(cd "${2:?the TablePro.app of the previous stable}" && pwd)" -if pgrep -x TablePro >/dev/null; then - echo "Quit every TablePro first: a run here must be the only one" >&2 +# Another TablePro, such as the installed one, keeps its own storage; only these two builds must not be running. +if pgrep -f "^($NEW_APP|$OLD_APP)/Contents/MacOS/TablePro" >/dev/null; then + echo "Quit this build and the previous stable first: a run here must be the only one of them" >&2 exit 2 fi SANDBOX="$(mktemp -d "${TMPDIR:-/tmp}/tablepro-history-downgrade.XXXXXX")" @@ -77,13 +78,28 @@ run "$OLD_APP" '[ -f "$HISTORY" ]' [ -f "$HISTORY" ] || fail "the previous stable made no query history" # What it holds before this build ever ran: two saved queries of one name in one connection and a folder, two runs, -# a favourite table and database, and a table folder with a table in it. +# a favourite table and database, and a table folder with a table in it. The saved queries' schema and full-text +# index are the ones the app keeps, so a row written here is one the app can update. sqlite3 "$FAVORITES" < Date: Thu, 26 Nov 2026 17:36:00 +0700 Subject: [PATCH 5/5] docs(macos): changelog for saved queries renamed on their move into the core --- apple/changelog.d/4611.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 apple/changelog.d/4611.changed.md diff --git a/apple/changelog.d/4611.changed.md b/apple/changelog.d/4611.changed.md new file mode 100644 index 0000000000..08a87bea7e --- /dev/null +++ b/apple/changelog.d/4611.changed.md @@ -0,0 +1 @@ +Two saved queries with one name in a connection keep both, with a number added to the newer one's name.