From 4fc57cf42df24d6a35bccaebf1bf7095de59c523 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:15:49 +0700 Subject: [PATCH 01/11] feat(windows): save queries in folders, pin history runs, import CSV into a table, duplicate and export connections --- core/crates/ffi/src/export.rs | 11 + core/crates/ffi/src/favourites.rs | 173 + core/crates/ffi/src/history.rs | 48 +- core/crates/ffi/src/import.rs | 522 +++ core/crates/ffi/src/lib.rs | 12 +- core/crates/ffi/src/library.rs | 89 + core/crates/ffi/src/row_edits.rs | 2 +- core/crates/ffi/src/saved_queries.rs | 205 + core/crates/ffi/tests/csv_import.rs | 396 ++ core/crates/ffi/tests/library_copies.rs | 244 ++ core/crates/ffi/tests/saved_queries.rs | 359 ++ core/docs/decisions/0017-favourites.md | 2 +- ...rage-import-and-library-through-the-ffi.md | 37 + core/docs/decisions/README.md | 3 +- windows/AGENTS.md | 1 + ...ueries-csv-import-and-connection-copies.md | 43 + windows/docs/decisions/README.md | 1 + windows/src/TablePro.App.Model/CopyName.cs | 97 + .../src/TablePro.App.Model/CsvImportForm.cs | 287 ++ windows/src/TablePro.App.Model/HistoryList.cs | 22 + .../src/TablePro.App.Model/SavedQueryText.cs | 85 + .../src/TablePro.App.Model/SavedQueryTree.cs | 105 + windows/src/TablePro.App/MainWindow.xaml | 7 + windows/src/TablePro.App/MainWindow.xaml.cs | 36 + .../src/TablePro.App/Services/Workbench.cs | 35 + .../TablePro.App/Strings/en-US/Resources.resw | 385 +- .../src/TablePro.App/Views/HistoryPane.xaml | 10 + .../TablePro.App/Views/HistoryPane.xaml.cs | 36 +- windows/src/TablePro.App/Views/HomeView.xaml | 3 + .../src/TablePro.App/Views/HomeView.xaml.cs | 67 + .../src/TablePro.App/Views/ImportCsvDialog.cs | 566 +++ .../src/TablePro.App/Views/SaveQueryDialog.cs | 409 ++ .../TablePro.App/Views/SavedQueriesPane.xaml | 113 + .../Views/SavedQueriesPane.xaml.cs | 533 +++ .../TablePro.App/Views/TableTabView.xaml.cs | 5 +- .../src/TablePro.App/Views/WorkspaceView.xaml | 6 +- .../TablePro.App/Views/WorkspaceView.xaml.cs | 255 +- .../src/TablePro.Interop/ConnectionLibrary.cs | 16 + windows/src/TablePro.Interop/CsvImport.cs | 169 + .../DatabaseSession.Import.cs | 15 + windows/src/TablePro.Interop/Favourites.cs | 88 + .../Generated/tablepro_ffi.cs | 3711 +++++++++++++++-- windows/src/TablePro.Interop/QueryHistory.cs | 25 + windows/src/TablePro.Interop/SavedQueries.cs | 99 + .../TablePro.App.Model.Tests/CopyNameTests.cs | 47 + .../CsvImportFormTests.cs | 249 ++ .../HistoryListTests.cs | 56 +- .../SavedQueryTreeTests.cs | 150 + .../ConnectionCopyTests.cs | 45 + .../TablePro.App.UITests/CsvImportTests.cs | 121 + .../TablePro.App.UITests/SavedQueriesTests.cs | 116 + .../ConnectionCopyTests.cs | 64 + .../TablePro.Interop.Tests/CsvImportTests.cs | 112 + .../TablePro.Interop.Tests/SavedQueryTests.cs | 152 + 54 files changed, 10039 insertions(+), 406 deletions(-) create mode 100644 core/crates/ffi/src/favourites.rs create mode 100644 core/crates/ffi/src/import.rs create mode 100644 core/crates/ffi/src/saved_queries.rs create mode 100644 core/crates/ffi/tests/csv_import.rs create mode 100644 core/crates/ffi/tests/library_copies.rs create mode 100644 core/crates/ffi/tests/saved_queries.rs create mode 100644 core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md create mode 100644 windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md create mode 100644 windows/src/TablePro.App.Model/CopyName.cs create mode 100644 windows/src/TablePro.App.Model/CsvImportForm.cs create mode 100644 windows/src/TablePro.App.Model/SavedQueryText.cs create mode 100644 windows/src/TablePro.App.Model/SavedQueryTree.cs create mode 100644 windows/src/TablePro.App/Views/ImportCsvDialog.cs create mode 100644 windows/src/TablePro.App/Views/SaveQueryDialog.cs create mode 100644 windows/src/TablePro.App/Views/SavedQueriesPane.xaml create mode 100644 windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs create mode 100644 windows/src/TablePro.Interop/CsvImport.cs create mode 100644 windows/src/TablePro.Interop/DatabaseSession.Import.cs create mode 100644 windows/src/TablePro.Interop/Favourites.cs create mode 100644 windows/src/TablePro.Interop/SavedQueries.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/CopyNameTests.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/SavedQueryTreeTests.cs create mode 100644 windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs create mode 100644 windows/tests/TablePro.App.UITests/CsvImportTests.cs create mode 100644 windows/tests/TablePro.App.UITests/SavedQueriesTests.cs create mode 100644 windows/tests/TablePro.Interop.Tests/ConnectionCopyTests.cs create mode 100644 windows/tests/TablePro.Interop.Tests/CsvImportTests.cs create mode 100644 windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs diff --git a/core/crates/ffi/src/export.rs b/core/crates/ffi/src/export.rs index 248417bb42..63d2c8166c 100644 --- a/core/crates/ffi/src/export.rs +++ b/core/crates/ffi/src/export.rs @@ -606,6 +606,17 @@ impl Drop for PartFile { } } +// A file a store's export writes whole, beside its place and renamed over it once synced. Blocking. +pub(crate) fn write_whole_file(path: &str, bytes: &[u8]) -> Result<(), CoreError> { + let part = PartFile::beside(destination(path)?)?; + let mut file = File::create(&part.path).map_err(|error| io_error(&part.target, &error))?; + file.write_all(bytes) + .and_then(|()| file.sync_all()) + .map_err(|error| io_error(&part.target, &error))?; + drop(file); + part.place() +} + async fn blocking(tasks: &Tasks, work: F) -> Result where T: Send + 'static, diff --git a/core/crates/ffi/src/favourites.rs b/core/crates/ffi/src/favourites.rs new file mode 100644 index 0000000000..10ce2d26b8 --- /dev/null +++ b/core/crates/ffi/src/favourites.rs @@ -0,0 +1,173 @@ +use std::sync::Arc; + +use tablepro_session::runtime::Tasks; +use tablepro_storage::{DatabaseEnvironment, FavouriteDatabase, FavouriteTable, Favourites}; +use uuid::Uuid; + +use crate::error::CoreError; +use crate::library::parse_id; +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, +} + +// A table by its database and schema, None where the engine has neither. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteTableInfo { + pub database: Option, + pub schema: Option, + pub name: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum DatabaseEnvironmentTag { + Development, + Testing, + Production, + Unassigned, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FavouriteDatabaseInfo { + pub database: String, + pub environment: DatabaseEnvironmentTag, +} + +impl FavouriteStore { + pub(crate) fn new(favourites: Favourites, tasks: Tasks) -> Arc { + Arc::new(Self { favourites, tasks }) + } +} + +#[uniffi::export] +impl FavouriteStore { + // By database, schema and name. + pub async fn tables(&self, connection_id: String) -> Result, CoreError> { + let connection = parse_id(&connection_id)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + Ok(favourites + .tables(connection) + .await? + .into_iter() + .map(FavouriteTableInfo::from) + .collect()) + }) + .await + } + + // A table marked already stays as it is. + pub async fn add_table(&self, connection_id: String, table: FavouriteTableInfo) -> Result<(), CoreError> { + let table = stored(&connection_id, table)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { Ok(favourites.add_table(&table).await?) }).await + } + + pub async fn remove_table(&self, connection_id: String, table: FavouriteTableInfo) -> Result<(), CoreError> { + let table = stored(&connection_id, table)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { Ok(favourites.remove_table(&table).await?) }).await + } + + // By name, in any case. + pub async fn databases(&self, connection_id: String) -> Result, CoreError> { + let connection = parse_id(&connection_id)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + Ok(favourites + .databases(connection) + .await? + .into_iter() + .map(FavouriteDatabaseInfo::from) + .collect()) + }) + .await + } + + // Marks the database, or files a marked one under another environment. + pub async fn set_database( + &self, + connection_id: String, + database: String, + environment: DatabaseEnvironmentTag, + ) -> Result<(), CoreError> { + let connection = parse_id(&connection_id)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + Ok(favourites + .set_database(connection, &database, environment.into()) + .await?) + }) + .await + } + + pub async fn remove_database(&self, connection_id: String, database: String) -> Result<(), CoreError> { + let connection = parse_id(&connection_id)?; + let favourites = self.favourites.clone(); + on_runtime(&self.tasks, async move { + Ok(favourites.remove_database(connection, &database).await?) + }) + .await + } +} + +fn stored(connection_id: &str, table: FavouriteTableInfo) -> Result { + let connection_id: Uuid = parse_id(connection_id)?; + Ok(FavouriteTable { + connection_id, + database: table.database.filter(|database| !database.is_empty()), + schema: table.schema.filter(|schema| !schema.is_empty()), + name: table.name, + }) +} + +impl From for FavouriteTableInfo { + fn from(table: FavouriteTable) -> Self { + Self { + database: table.database, + schema: table.schema, + name: table.name, + } + } +} + +impl From for FavouriteDatabaseInfo { + fn from(database: FavouriteDatabase) -> Self { + Self { + database: database.database, + environment: database.environment.into(), + } + } +} + +impl From for DatabaseEnvironmentTag { + fn from(environment: DatabaseEnvironment) -> Self { + match environment { + DatabaseEnvironment::Development => Self::Development, + DatabaseEnvironment::Testing => Self::Testing, + DatabaseEnvironment::Production => Self::Production, + DatabaseEnvironment::Unassigned => Self::Unassigned, + } + } +} + +impl From for DatabaseEnvironment { + fn from(environment: DatabaseEnvironmentTag) -> Self { + match environment { + DatabaseEnvironmentTag::Development => Self::Development, + DatabaseEnvironmentTag::Testing => Self::Testing, + DatabaseEnvironmentTag::Production => Self::Production, + DatabaseEnvironmentTag::Unassigned => Self::Unassigned, + } + } +} + +impl std::fmt::Debug for FavouriteStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FavouriteStore").finish_non_exhaustive() + } +} diff --git a/core/crates/ffi/src/history.rs b/core/crates/ffi/src/history.rs index ac7f3eeab2..00365f43b8 100644 --- a/core/crates/ffi/src/history.rs +++ b/core/crates/ffi/src/history.rs @@ -11,8 +11,11 @@ use tablepro_storage::{QueryHistory, StoragePaths}; use uuid::Uuid; use crate::error::CoreError; +use crate::export::write_whole_file; +use crate::favourites::FavouriteStore; use crate::library::parse_id; use crate::runtime::on_runtime; +use crate::saved_queries::SavedQueryStore; use crate::session::DatabaseSession; #[derive(uniffi::Object)] @@ -60,6 +63,13 @@ pub struct HistoryPageInfo { pub next: Option, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum HistoryExportFormat { + // Each run as it ran, under comments that say where and when. + Sql, + Csv, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)] pub struct HistoryCursorArg { pub pinned: bool, @@ -144,6 +154,42 @@ impl QueryHistoryStore { }) .await } + + // A pinned run comes first in every search and stays through the store's pruning. + pub async fn set_pinned(&self, id: i64, pinned: bool) -> Result<(), CoreError> { + let history = self.history.clone(); + on_runtime(&self.tasks, async move { Ok(history.set_pinned(id, pinned).await?) }).await + } + + // The runs `ids` names, pinned first then newest, into the file at `path`, which appears only once whole. + pub async fn export(&self, ids: Vec, format: HistoryExportFormat, path: String) -> Result<(), CoreError> { + let history = self.history.clone(); + let tasks = self.tasks.clone(); + on_runtime(&self.tasks, async move { + let text = match format { + HistoryExportFormat::Sql => history.export_sql(&ids).await?, + HistoryExportFormat::Csv => history.export_csv(&ids).await?, + }; + tasks + .spawn_blocking_task(move || write_whole_file(&path, text.as_bytes())) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))? + }) + .await + } + + // The same database, so a store that opened serves both. + pub fn saved_queries(&self) -> Arc { + SavedQueryStore::new( + self.history.saved_queries(), + self.history.saved_query_folders(), + self.tasks.clone(), + ) + } + + pub fn favourites(&self) -> Arc { + FavouriteStore::new(self.history.favourites(), self.tasks.clone()) + } } // Without a dialect nobody can say which statements hold a secret, so nothing is kept. @@ -254,7 +300,7 @@ fn from_epoch(span: Duration, before: bool) -> SystemTime { time.unwrap_or(UNIX_EPOCH) } -fn millis(time: SystemTime) -> i64 { +pub(crate) fn millis(time: SystemTime) -> i64 { match time.duration_since(UNIX_EPOCH) { Ok(after) => i64::try_from(after.as_millis()).unwrap_or(i64::MAX), Err(before) => i64::try_from(before.duration().as_millis()).map_or(i64::MIN, |value| -value), diff --git a/core/crates/ffi/src/import.rs b/core/crates/ffi/src/import.rs new file mode 100644 index 0000000000..65652f9053 --- /dev/null +++ b/core/crates/ffi/src/import.rs @@ -0,0 +1,522 @@ +use std::io::Read; +use std::ops::Range; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use tablepro_core::dialect::SqlDialect; +use tablepro_core::edit::CellInput; +use tablepro_core::export::CsvDelimiter; +use tablepro_core::import::{ + CsvImportOptions, CsvRowError, ImportColumn, ImportError, MAX_CSV_FILE_BYTES, MAX_PREVIEW_ROWS, plan_import, + read_csv, row_to_cells, suggest_mapping, +}; +use tablepro_core::meta::TableRef; +use tablepro_core::{CallOptions, DriverError, ErrorCategory, WriteBatch, WriteKind}; +use tablepro_session::runtime::Tasks; +use tablepro_session::{OperationError, OperationKind, Session}; + +use crate::cancel_token::{CancelToken, token}; +use crate::catalog::TableName; +use crate::error::{BoxedErrorInfo, CoreError}; +use crate::row_edits::{SaveGate, save_gate}; +use crate::runtime::on_runtime; +use crate::session::DatabaseSession; + +// As the Linux import allows: each statement gets this much on top of the call's own deadline. +const TIME_PER_STATEMENT: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum CsvDelimiterTag { + Comma, + Semicolon, + Tab, + Pipe, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CsvReadOptions { + pub delimiter: CsvDelimiterTag, + // The first record names the fields. + pub has_header: bool, + // A field holding exactly this reads as NULL. Empty by default, as every export writes NULL. + pub null_text: String, +} + +// Headers are empty strings when the file has none, one per field of the widest row. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CsvPreview { + pub headers: Vec, + pub rows: Vec>, + // More rows follow the ones shown; the import reads them all. + pub truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ImportColumnInfo { + pub name: String, + pub type_name: String, + pub nullable: bool, + pub has_default: bool, + // A generated column or an identity that refuses a value: no field is ever mapped to it. + pub server_filled: bool, +} + +// A field the column's type cannot read. `line` counts the header as line 1, as a spreadsheet shows it. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CsvRowFault { + pub line: u64, + pub column: String, + pub text: String, + // The edit parse error's code, as a cell edit refused for the same reason has. + pub reason: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum CsvImportCheck { + // `statements` are the SQL texts the rows write as, in order; Safe Mode shows them before a confirmed run. + Ready { + rows: u64, + statements: Vec, + gate: SaveGate, + }, + // The file has no rows past its header. + Empty, + RowRefused { + fault: CsvRowFault, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum CsvImportOutcome { + Imported { + rows: u64, + }, + // Nothing was written. The lines are those of the statement that failed, when the engine said which. + RolledBack { + error: BoxedErrorInfo, + lines: Option, + }, + // The engine has no transaction to undo the import: `written_rows` rows before the failed lines stay. + PartlyWritten { + error: BoxedErrorInfo, + written_rows: u64, + lines: Option, + }, + // Stopped, or the connection went before the server answered: the table may hold some rows or none. + Unknown { + error: BoxedErrorInfo, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)] +pub struct LineSpan { + pub first: u64, + pub last: u64, +} + +// A table's columns as a CSV import writes them, and the import planned last. +#[derive(uniffi::Object)] +pub struct CsvImport { + session: Arc, + tasks: Tasks, + table: TableRef, + columns: Arc<[ImportColumn]>, + planned: Mutex>, +} + +struct Planned { + batch: Arc, + step_rows: Vec>, + first_line: usize, + rows: usize, + gate: SaveGate, +} + +#[uniffi::export] +impl DatabaseSession { + // The table's columns as the server defines them now. + pub async fn open_csv_import( + &self, + table: TableName, + cancel: Option>, + ) -> Result, CoreError> { + let session = self.session().clone(); + let tasks = self.tasks().clone(); + let cancel = token(cancel); + on_runtime(self.tasks(), async move { + let table: TableRef = table.into(); + let definition = session + .run_cancellable(OperationKind::Metadata, &cancel, |lease, options| { + let table = table.clone(); + async move { Ok(lease.fetch_table_definition(&table, options).await?) } + }) + .await?; + let columns: Arc<[ImportColumn]> = definition.columns.iter().map(ImportColumn::from_definition).collect(); + if columns.is_empty() { + return Err(CoreError::failed("import.no_table_columns", "the table has no columns")); + } + Ok(Arc::new(CsvImport { + session, + tasks, + table, + columns, + planned: Mutex::new(None), + })) + }) + .await + } +} + +#[uniffi::export] +impl CsvImport { + pub fn columns(&self) -> Vec { + self.columns + .iter() + .map(|column| ImportColumnInfo { + name: column.info.name.clone(), + type_name: column.info.column_type.name.clone(), + nullable: column.info.nullable, + has_default: !column.info.default.is_none(), + server_filled: column.server_filled, + }) + .collect() + } + + // The first rows, enough to judge the delimiter and the header. + pub async fn preview(&self, path: String, options: CsvReadOptions) -> Result { + let options = CsvImportOptions::from(options); + blocking(&self.tasks, move || { + let bytes = read_file(&path)?; + let sheet = read_csv(&bytes, &options, Some(MAX_PREVIEW_ROWS)).map_err(read_error)?; + Ok(CsvPreview { + headers: sheet.headers, + rows: sheet.rows, + truncated: sheet.truncated, + }) + }) + .await + } + + // Per column, the field whose header names it, ignoring case and surrounding space; never a server-filled one. + pub fn suggest_mapping(&self, headers: Vec) -> Vec> { + suggest_mapping(&headers, &self.columns) + .into_iter() + .map(|field| field.and_then(|field| u32::try_from(field).ok())) + .collect() + } + + // Reads the whole file and plans its rows into the table, `mapping` naming a field per column (None leaves the + // column to its default). The plan replaces any planned before and is what `run` writes. + pub async fn plan( + &self, + path: String, + options: CsvReadOptions, + mapping: Vec>, + ) -> Result { + if mapping.len() != self.columns.len() { + return Err(CoreError::failed( + "import.mapping_invalid", + format!("{} fields mapped for {} columns", mapping.len(), self.columns.len()), + )); + } + self.discard(); + let dialect = self + .session + .current_dialect() + .ok_or_else(|| CoreError::failed("ffi.not_connected", "the session has no connection"))?; + let gate = save_gate(self.session.safe_mode()); + let columns = self.columns.clone(); + let table = self.table.clone(); + let options = CsvImportOptions::from(options); + let planned = blocking(&self.tasks, move || { + plan_file(&path, &options, &mapping, &columns, &table, &*dialect, gate) + }) + .await?; + let check = match &planned { + Ok(Some(planned)) => CsvImportCheck::Ready { + rows: u64::try_from(planned.rows).unwrap_or(u64::MAX), + statements: planned + .batch + .steps + .iter() + .map(|step| step.statement.sql().to_owned()) + .collect(), + gate: planned.gate, + }, + Ok(None) => CsvImportCheck::Empty, + Err(fault) => CsvImportCheck::RowRefused { fault: fault.clone() }, + }; + if let Ok(Some(planned)) = planned { + *self.planned.lock().unwrap_or_else(PoisonError::into_inner) = Some(planned); + } + Ok(check) + } + + // Writes the import planned last, once. `confirmed` says the user answered Safe Mode's question; a level saved + // since the plan refuses before anything is sent. + pub async fn run(&self, confirmed: bool, cancel: Option>) -> Result { + let Some(planned) = self.planned.lock().unwrap_or_else(PoisonError::into_inner).take() else { + return Err(CoreError::failed("import.not_planned", "no import is planned")); + }; + if planned.gate == SaveGate::Confirm && !confirmed { + return Err(CoreError::failed( + "import.not_confirmed", + "Safe Mode asks before this import and it was not answered", + )); + } + match save_gate(self.session.safe_mode()) { + SaveGate::Refuse => { + return Err(CoreError::failed( + "edit.read_only_connection", + "the connection is read-only", + )); + } + now if now != planned.gate => return Err(safe_mode_changed()), + _ => {} + } + let session = self.session.clone(); + let cancel = token(cancel); + on_runtime(&self.tasks, async move { + let gated = session.clone(); + let batch = planned.batch.clone(); + let gate = planned.gate; + let written = session + .run_cancellable( + OperationKind::Save(WriteKind::RowChanges), + &cancel, + move |lease, options| { + let (batch, gated) = (batch.clone(), gated.clone()); + async move { + // Checked again on the lease, so a level saved while the import waited for it holds. + if save_gate(gated.safe_mode()) != gate { + return Ok(Err(safe_mode_changed())); + } + let options = with_time_for(options, batch.steps.len()); + Ok(Ok(lease.write_batch(&batch, options).await?)) + } + }, + ) + .await; + match written { + Ok(Err(refused)) => Err(refused), + Ok(Ok(_)) => Ok(CsvImportOutcome::Imported { + rows: u64::try_from(planned.rows).unwrap_or(u64::MAX), + }), + Err(error) => Ok(failed(&error, &planned)), + } + }) + .await + } +} + +impl CsvImport { + fn discard(&self) { + *self.planned.lock().unwrap_or_else(PoisonError::into_inner) = None; + } +} + +fn plan_file( + path: &str, + options: &CsvImportOptions, + mapping: &[Option], + columns: &[ImportColumn], + table: &TableRef, + dialect: &dyn SqlDialect, + gate: SaveGate, +) -> Result, CsvRowFault>, CoreError> { + let bytes = read_file(path)?; + let sheet = read_csv(&bytes, options, None).map_err(read_error)?; + drop(bytes); + let width = sheet.headers.len(); + let mapping: Vec> = mapping + .iter() + .map(|field| field.and_then(|field| usize::try_from(field).ok())) + .collect(); + if let Some(field) = mapping.iter().flatten().find(|field| **field >= width) { + return Err(CoreError::failed( + "import.mapping_invalid", + format!("field {field} is past the file's {width} fields"), + )); + } + if sheet.rows.is_empty() { + return Ok(Ok(None)); + } + let first_line = if options.has_header { 2 } else { 1 }; + let mut rows: Vec> = Vec::with_capacity(sheet.rows.len()); + for (index, row) in sheet.rows.iter().enumerate() { + match row_to_cells(row, &mapping, columns, options, first_line + index) { + Ok(cells) => rows.push(cells), + Err(error) => return Ok(Err(CsvRowFault::from(error))), + } + } + drop(sheet); + let count = rows.len(); + let plan = plan_import(dialect, table, columns, rows) + .map_err(|error| CoreError::failed(error.code(), error.to_string()))?; + Ok(Ok(Some(Planned { + batch: Arc::new(plan.batch), + step_rows: plan.step_rows, + first_line, + rows: count, + gate, + }))) +} + +fn read_file(path: &str) -> Result, CoreError> { + let path = PathBuf::from(path); + let unreadable = |error: std::io::Error| { + let mut failed = CoreError::failed("import.unreadable", format!("{}: {error}", path.display())); + if let CoreError::Failed { info } = &mut failed { + info.path = Some(path.display().to_string()); + } + failed + }; + let file = std::fs::File::open(&path).map_err(&unreadable)?; + // Every row becomes part of one write held in memory, so a file past the cap is refused, not read whole. + let cap = u64::try_from(MAX_CSV_FILE_BYTES).unwrap_or(u64::MAX); + let mut bytes = Vec::new(); + file.take(cap.saturating_add(1)) + .read_to_end(&mut bytes) + .map_err(&unreadable)?; + if bytes.len() > MAX_CSV_FILE_BYTES { + return Err(CoreError::failed( + "import.too_large", + format!("the file is past the {MAX_CSV_FILE_BYTES} bytes an import reads"), + )); + } + Ok(bytes) +} + +fn read_error(error: ImportError) -> CoreError { + let code = match &error { + ImportError::NotUtf8 { .. } => "import.not_utf8", + ImportError::Malformed { .. } => "import.malformed", + ImportError::NoColumns => "import.no_columns", + ImportError::TooManyFields { .. } => "import.too_many_fields", + }; + CoreError::failed(code, error.to_string()) +} + +fn with_time_for(options: CallOptions, statements: usize) -> CallOptions { + let extra = TIME_PER_STATEMENT.saturating_mul(u32::try_from(statements).unwrap_or(u32::MAX)); + CallOptions::new( + options.deadline().map(|deadline| deadline + extra), + options.cancel().clone(), + ) +} + +fn safe_mode_changed() -> CoreError { + CoreError::failed( + "import.safe_mode_changed", + "the connection's Safe Mode changed after the import was planned", + ) +} + +// As the Linux import words a failure: by the lines of the file the failed statement held. +fn failed(error: &OperationError, planned: &Planned) -> CsvImportOutcome { + let info = || CoreError::from(error).into_info(); + let lines = |step: usize| { + planned.step_rows.get(step).map(|rows| LineSpan { + first: line(planned.first_line + rows.start), + last: line(planned.first_line + rows.end.saturating_sub(1)), + }) + }; + match error { + OperationError::Driver(driver) => match driver { + DriverError::RolledBack { statement_index, .. } + | DriverError::RowGuardFailed { statement_index, .. } + | DriverError::GuardUnsupported { statement_index } => CsvImportOutcome::RolledBack { + error: info(), + lines: lines(*statement_index), + }, + DriverError::PartiallyApplied { statement_index, .. } => { + let written: usize = planned + .step_rows + .iter() + .take(*statement_index) + .map(ExactSizeIterator::len) + .sum(); + CsvImportOutcome::PartlyWritten { + error: info(), + written_rows: line(written), + lines: lines(*statement_index), + } + } + DriverError::ReadOnly(_) => CsvImportOutcome::RolledBack { + error: info(), + lines: None, + }, + DriverError::CommitOutcomeUnknown { .. } => CsvImportOutcome::Unknown { error: info() }, + other => match other.category() { + ErrorCategory::Interrupted | ErrorCategory::Timeout | ErrorCategory::ConnectionLost => { + CsvImportOutcome::Unknown { error: info() } + } + _ => CsvImportOutcome::RolledBack { + error: info(), + lines: None, + }, + }, + }, + OperationError::Sql(_) | OperationError::Build(_) | OperationError::Browse(_) => CsvImportOutcome::RolledBack { + error: info(), + lines: None, + }, + OperationError::Cancelled | OperationError::Panicked(_) | OperationError::Closed => { + CsvImportOutcome::Unknown { error: info() } + } + } +} + +fn line(value: usize) -> u64 { + u64::try_from(value).unwrap_or(u64::MAX) +} + +async fn blocking(tasks: &Tasks, work: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + let runner = tasks.clone(); + on_runtime(tasks, async move { + runner + .spawn_blocking_task(work) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))? + }) + .await +} + +impl From for CsvImportOptions { + fn from(options: CsvReadOptions) -> Self { + Self { + delimiter: match options.delimiter { + CsvDelimiterTag::Comma => CsvDelimiter::Comma, + CsvDelimiterTag::Semicolon => CsvDelimiter::Semicolon, + CsvDelimiterTag::Tab => CsvDelimiter::Tab, + CsvDelimiterTag::Pipe => CsvDelimiter::Pipe, + }, + has_header: options.has_header, + null_marker: options.null_text, + } + } +} + +impl From for CsvRowFault { + fn from(error: CsvRowError) -> Self { + Self { + line: line(error.line), + column: error.column, + text: error.text, + reason: error.reason.code().to_owned(), + } + } +} + +impl std::fmt::Debug for CsvImport { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CsvImport") + .field("table", &self.table) + .finish_non_exhaustive() + } +} diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index f1a22133b6..1c2abf48aa 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -15,10 +15,12 @@ mod drivers; mod editor; mod error; mod export; +mod favourites; mod filter; mod history; mod host; mod host_key; +mod import; mod library; mod masking; mod prompter; @@ -27,6 +29,7 @@ mod row_edits; mod run; mod runtime; mod safe_mode_gate; +mod saved_queries; mod session; mod statement_at; mod structure; @@ -50,13 +53,19 @@ pub use drivers::{DataModelTag, DriverInfo, EndpointInfo, EngineCategoryTag, Ser pub use editor::{QueryEditor, RunSettings}; pub use error::{BoxedErrorInfo, CoreError, ErrorInfo, HostKeyFailure, ServerMessage, TlsFailureTag}; pub use export::ExportFormatTag; +pub use favourites::{DatabaseEnvironmentTag, FavouriteDatabaseInfo, FavouriteStore, FavouriteTableInfo}; pub use filter::{ CombinatorTag, FilterChoices, FilterColumn, FilterOpTag, FilterRuleArg, FilterValueArg, TableFilterArg, }; pub use history::{ - HistoryCursorArg, HistoryEntryInfo, HistoryOutcomeTag, HistoryPageInfo, HistoryRun, QueryHistoryStore, + HistoryCursorArg, HistoryEntryInfo, HistoryExportFormat, HistoryOutcomeTag, HistoryPageInfo, HistoryRun, + QueryHistoryStore, }; pub use host::{HostConfig, HostSecretError, HostSecretStore, HostSecrets, SecretItemTag, SecretKindTag}; +pub use import::{ + CsvDelimiterTag, CsvImport, CsvImportCheck, CsvImportOutcome, CsvPreview, CsvReadOptions, CsvRowFault, + ImportColumnInfo, LineSpan, +}; pub use library::{ ConnectionLibrary, ConnectionRecord, ConnectionSecrets, GroupRecord, ImportSummary, LibrarySnapshot, SafeModeTag, SshAuthTag, SshSettings, TagRecord, TlsModeTag, TlsSettings, @@ -73,6 +82,7 @@ pub use row_edits::{ }; pub use run::{QueryRun, RunEvent, RunListener, RunOutcome, TransactionStateTag, TruncationTag}; pub use safe_mode_gate::RunGate; +pub use saved_queries::{SavedQueriesInfo, SavedQueryDraft, SavedQueryFolderInfo, SavedQueryInfo, SavedQueryStore}; pub use session::{ColumnSort, DatabaseSession, FailureCauseTag, RowEstimate, SessionHealthTag, TablePageRead}; pub use statement_at::StatementSpan; pub use structure::{StructureColumn, StructureForeignKey, StructureIndex, TableStructure}; diff --git a/core/crates/ffi/src/library.rs b/core/crates/ffi/src/library.rs index 26ea269e5a..d3ead72881 100644 --- a/core/crates/ffi/src/library.rs +++ b/core/crates/ffi/src/library.rs @@ -15,6 +15,7 @@ use tablepro_storage::{ use uuid::Uuid; use crate::error::CoreError; +use crate::export::write_whole_file; use crate::runtime::on_runtime; #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] @@ -280,6 +281,31 @@ impl ConnectionLibrary { .await } + // A secret the store cannot read stops the copy, which would otherwise fail to connect for no reason it shows. + async fn copy_secrets(&self, source: &SavedConnection, copy: &SavedConnection) -> Result<(), CoreError> { + let vault = self.secrets.clone(); + let (from, to) = (source.id, copy.clone()); + on_runtime(&self.tasks, async move { + for kind in SecretKind::ALL { + if let SecretLookup::Found(secret) = vault.load(from, kind).await.map_err(secret_error)? { + let label = english_secret_label(kind, &to.secret_target(kind)); + vault.store(to.id, kind, &secret, &label).await.map_err(secret_error)?; + } + } + Ok(()) + }) + .await + } + + async fn forget_secrets(&self, id: Uuid) { + if let Err(error) = self.delete_secrets(vec![id]).await { + tracing::warn!( + code = error.code(), + "the secrets of a copy that was not saved are still in the store" + ); + } + } + // A value that cannot be read counts as none, so putting it back removes the new one rather than keep it. async fn held_values(&self, id: Uuid, kinds: Vec) -> Result, CoreError> { let vault = self.secrets.clone(); @@ -646,6 +672,69 @@ impl ConnectionLibrary { .await } + // A copy under a new id right after the original in its group, with every secret the original keeps, so either + // connects alone. It has never been opened and is no favourite. + pub async fn duplicate(&self, id: String, name: String) -> Result { + let id = parse_id(&id)?; + let name = name.trim().to_owned(); + if name.is_empty() { + return Err(CoreError::failed("library.name_required", "a connection needs a name")); + } + let _held = self.hold_writes().await; + let source = self + .blocking(move |store| { + store + .list_blocking()? + .connections + .iter() + .find(|saved| saved.id == id) + .cloned() + .ok_or_else(|| StorageError::ConnectionNotFound { id }.into()) + }) + .await?; + let copy = SavedConnection { + id: Uuid::new_v4(), + name, + last_opened_at: None, + ..source.clone() + }; + if let Err(error) = self.copy_secrets(&source, ©).await { + self.forget_secrets(copy.id).await; + return Err(error); + } + let entry = copy.clone(); + let written = self + .blocking(move |store| { + let id = entry.id; + store.insert_after_blocking(entry, source.id)?; + // The store gives the copy its place in the group; a read that fails now leaves the copy saved. + Ok(store + .list_blocking() + .ok() + .and_then(|list| list.connections.iter().find(|saved| saved.id == id).cloned())) + }) + .await; + match written { + Ok(stored) => Ok(ConnectionRecord::from(&stored.unwrap_or(copy))), + Err(error) => { + self.forget_secrets(copy.id).await; + Err(error) + } + } + } + + // The saved connections, groups and tags as a TablePro connections file at `path`, which appears only once + // whole. It carries no passwords: those stay in the system's store. Gives how many connections it holds. + pub async fn export_file(&self, path: String) -> Result { + self.blocking(move |store| { + let count = store.list_blocking()?.connections.len(); + let bytes = store.export_blocking()?; + write_whole_file(&path, &bytes)?; + Ok(u32::try_from(count).unwrap_or(u32::MAX)) + }) + .await + } + // Merges a TablePro connections file; it carries no passwords. pub async fn import_file(&self, path: String) -> Result { let _held = self.hold_writes().await; diff --git a/core/crates/ffi/src/row_edits.rs b/core/crates/ffi/src/row_edits.rs index 300a2c2f9a..e6664657a0 100644 --- a/core/crates/ffi/src/row_edits.rs +++ b/core/crates/ffi/src/row_edits.rs @@ -600,7 +600,7 @@ impl RowSave { } } -fn save_gate(level: SafeModeLevel) -> SaveGate { +pub(crate) fn save_gate(level: SafeModeLevel) -> SaveGate { match level.gate(StatementAccess::Write) { WriteGate::Run => SaveGate::Run, WriteGate::Confirm => SaveGate::Confirm, diff --git a/core/crates/ffi/src/saved_queries.rs b/core/crates/ffi/src/saved_queries.rs new file mode 100644 index 0000000000..11bca4fe76 --- /dev/null +++ b/core/crates/ffi/src/saved_queries.rs @@ -0,0 +1,205 @@ +use std::sync::Arc; + +use tablepro_session::runtime::Tasks; +use tablepro_storage::saved_queries::{NewSavedQuery, SavedQuery}; +use tablepro_storage::{SavedQueries, SavedQueriesSnapshot, SavedQueryFolder, SavedQueryFolders}; + +use crate::error::CoreError; +use crate::history::millis; +use crate::library::parse_id; +use crate::runtime::on_runtime; + +// A connection's saved queries and their folders, in the query history's database (core ADR 0017). +#[derive(uniffi::Object)] +pub struct SavedQueryStore { + queries: SavedQueries, + folders: SavedQueryFolders, + tasks: Tasks, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryInfo { + pub id: i64, + pub name: String, + pub sql: String, + pub keyword: Option, + // None at the top, outside every folder. + pub folder_id: Option, + // Dense from 0 within its folder. + pub order: i64, + pub updated_at_ms: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryFolderInfo { + pub id: i64, + pub name: String, + pub parent_id: Option, + pub order: i64, +} + +// Read in one transaction, each list in its place's order. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueriesInfo { + pub queries: Vec, + pub folders: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SavedQueryDraft { + pub connection_id: String, + pub connection_name: String, + pub name: String, + pub sql: String, +} + +impl SavedQueryStore { + pub(crate) fn new(queries: SavedQueries, folders: SavedQueryFolders, tasks: Tasks) -> Arc { + Arc::new(Self { + queries, + folders, + tasks, + }) + } +} + +#[uniffi::export] +impl SavedQueryStore { + pub async fn snapshot(&self, connection_id: String) -> Result { + let connection = parse_id(&connection_id)?; + let queries = self.queries.clone(); + on_runtime( + &self.tasks, + async move { Ok(queries.snapshot(connection).await?.into()) }, + ) + .await + } + + // A name the connection already uses is replaced only when `replace` says so, keeping the query's keyword and + // place; otherwise None comes back and nothing is written. + pub async fn save(&self, draft: SavedQueryDraft, replace: bool) -> Result, CoreError> { + let query = NewSavedQuery { + connection_id: parse_id(&draft.connection_id)?, + connection_name: draft.connection_name, + name: draft.name, + query: draft.sql, + }; + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { + match replace { + true => Ok(Some(queries.save(query).await?.id)), + false => Ok(queries.save_if_new(query).await?), + } + }) + .await + } + + pub async fn rename(&self, id: i64, name: String) -> Result<(), CoreError> { + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { Ok(queries.rename(id, &name).await?) }).await + } + + // None or blank clears it. One word of at most 64 characters, unique among the connection's queries in any case. + pub async fn set_keyword(&self, id: i64, keyword: Option) -> Result<(), CoreError> { + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { + Ok(queries.set_keyword(id, keyword.as_deref()).await?) + }) + .await + } + + // Into `folder_id`, None for the top, before the query `before` names there, or at the end. + pub async fn move_query(&self, id: i64, folder_id: Option, before: Option) -> Result<(), CoreError> { + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { + Ok(queries.move_to_folder(id, folder_id, before).await?) + }) + .await + } + + pub async fn delete(&self, id: i64) -> Result<(), CoreError> { + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { Ok(queries.delete(id).await?) }).await + } + + pub async fn create_folder( + &self, + connection_id: String, + name: String, + parent_id: Option, + ) -> Result { + let connection = parse_id(&connection_id)?; + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { + Ok(folders.create(connection, &name, parent_id).await?) + }) + .await + } + + pub async fn rename_folder(&self, id: i64, name: String) -> Result<(), CoreError> { + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { Ok(folders.rename(id, &name).await?) }).await + } + + pub async fn move_folder(&self, id: i64, parent_id: Option) -> Result<(), CoreError> { + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { Ok(folders.move_to(id, parent_id).await?) }).await + } + + // The folders inside go too; their queries move to the top. + pub async fn delete_folder(&self, id: i64) -> Result<(), CoreError> { + let folders = self.folders.clone(); + on_runtime(&self.tasks, async move { Ok(folders.delete(id).await?) }).await + } + + // The connection's queries, folders and favourite tables and databases, for a connection deleted. + pub async fn delete_for_connection(&self, connection_id: String) -> Result { + let connection = parse_id(&connection_id)?; + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { + let removed = queries.delete_for_connection(connection).await?; + Ok(u64::try_from(removed).unwrap_or(u64::MAX)) + }) + .await + } +} + +impl From for SavedQueriesInfo { + fn from(snapshot: SavedQueriesSnapshot) -> Self { + Self { + queries: snapshot.queries.into_iter().map(SavedQueryInfo::from).collect(), + folders: snapshot.folders.into_iter().map(SavedQueryFolderInfo::from).collect(), + } + } +} + +impl From for SavedQueryInfo { + fn from(query: SavedQuery) -> Self { + Self { + id: query.id, + name: query.name, + sql: query.query, + keyword: query.keyword, + folder_id: query.folder_id, + order: query.order, + updated_at_ms: millis(query.updated_at), + } + } +} + +impl From for SavedQueryFolderInfo { + fn from(folder: SavedQueryFolder) -> Self { + Self { + id: folder.id, + name: folder.name, + parent_id: folder.parent_id, + order: folder.order, + } + } +} + +impl std::fmt::Debug for SavedQueryStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SavedQueryStore").finish_non_exhaustive() + } +} diff --git a/core/crates/ffi/tests/csv_import.rs b/core/crates/ffi/tests/csv_import.rs new file mode 100644 index 0000000000..707560e0db --- /dev/null +++ b/core/crates/ffi/tests/csv_import.rs @@ -0,0 +1,396 @@ +#![cfg(feature = "engines")] +#![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::{ + ConnectionRecord, ConnectionSecrets, Core, CsvDelimiterTag, CsvImportCheck, CsvImportOutcome, CsvReadOptions, + DatabaseSession, FileOpenRequest, HostConfig, HostSecretError, HostSecrets, ResultSet, RunListener, RunOutcome, + RunSettings, SafeModeTag, SaveGate, SecretItemTag, SecretKindTag, TableName, TlsModeTag, TlsSettings, +}; + +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(()) + } +} + +struct Quiet; + +impl RunListener for Quiet { + fn events_pending(&self) {} +} + +fn core(dir: &Path) -> Arc { + Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: Some(dir.display().to_string()), + }, + Box::new(NoSecrets), + ) + .unwrap() +} + +fn people() -> TableName { + TableName { + schema: None, + name: "people".to_owned(), + } +} + +fn comma() -> CsvReadOptions { + CsvReadOptions { + delimiter: CsvDelimiterTag::Comma, + has_header: true, + null_text: String::new(), + } +} + +async fn run(session: &DatabaseSession, sql: &str) -> Option> { + let editor = session.open_editor(None).await.unwrap(); + let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); + assert!(matches!(run.outcome().await.unwrap(), RunOutcome::Completed { .. })); + let set = run.result_set(0); + editor.close().await.unwrap(); + set +} + +async fn open(core: &Core, path: &Path) -> Arc { + let request = FileOpenRequest { + path: path.display().to_string(), + driver_id: None, + read_only: false, + create: !path.exists(), + }; + core.open_file(request, None).await.unwrap() +} + +async fn seeded(core: &Core, path: &Path) -> Arc { + let session = open(core, path).await; + run( + &session, + "CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER, \ + joined TEXT NOT NULL DEFAULT 'today', initials TEXT GENERATED ALWAYS AS (substr(name, 1, 1)) VIRTUAL)", + ) + .await; + session +} + +async fn rows(session: &DatabaseSession) -> Vec>> { + let set = run(session, "SELECT id, name, age, joined FROM people ORDER BY id") + .await + .unwrap(); + (0..set.row_count()) + .map(|row| (0..4).map(|column| set.cell_text(row, column).unwrap()).collect()) + .collect() +} + +fn row(values: [Option<&str>; 4]) -> Vec> { + values.iter().map(|value| value.map(str::to_owned)).collect() +} + +fn write(dir: &Path, name: &str, text: &str) -> String { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + path.display().to_string() +} + +#[tokio::test] +async fn a_file_lands_in_the_table_by_the_mapping_its_headers_suggest() { + let dir = tempfile::tempdir().unwrap(); + let core = core(dir.path()); + let session = seeded(&core, &dir.path().join("people.sqlite")).await; + let csv = write( + dir.path(), + "people.csv", + "Name, AGE ,id,joined\nAda,36,1,\nGrace,,2,1906\n", + ); + let import = session.open_csv_import(people(), None).await.unwrap(); + + let columns = import.columns(); + let preview = import.preview(csv.clone(), comma()).await.unwrap(); + let mapping = import.suggest_mapping(preview.headers.clone()); + let check = import.plan(csv, comma(), mapping.clone()).await.unwrap(); + let outcome = import.run(false, None).await.unwrap(); + + let names: Vec<(&str, bool)> = columns + .iter() + .map(|column| (column.name.as_str(), column.server_filled)) + .collect(); + assert_eq!( + names, + [ + ("id", false), + ("name", false), + ("age", false), + ("joined", false), + ("initials", true) + ] + ); + assert!(columns[3].has_default && !columns[3].nullable); + assert_eq!(preview.headers, ["Name", " AGE ", "id", "joined"]); + assert_eq!(preview.rows.len(), 2); + assert!(!preview.truncated); + assert_eq!(mapping, [Some(2), Some(0), Some(1), Some(3), None]); + let CsvImportCheck::Ready { + rows: 2, + statements, + gate, + } = check + else { + panic!("{check:?}") + }; + assert!(!statements.is_empty()); + assert_eq!(gate, SaveGate::Run); + assert_eq!(outcome, CsvImportOutcome::Imported { rows: 2 }); + // An empty field is an empty text in a text column and NULL in a number column. + assert_eq!( + rows(&session).await, + [ + row([Some("1"), Some("Ada"), Some("36"), Some("")]), + row([Some("2"), Some("Grace"), None, Some("1906")]), + ] + ); + let again = import.run(false, None).await.unwrap_err(); + assert_eq!(again.code(), "import.not_planned"); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn a_field_the_column_cannot_read_names_its_line_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let core = core(dir.path()); + let session = seeded(&core, &dir.path().join("people.sqlite")).await; + let csv = write(dir.path(), "bad.csv", "id;name;age\n1;Ada;36\n2;Grace;old\n"); + let options = CsvReadOptions { + delimiter: CsvDelimiterTag::Semicolon, + ..comma() + }; + let import = session.open_csv_import(people(), None).await.unwrap(); + + let check = import + .plan(csv, options, vec![Some(0), Some(1), Some(2), None, None]) + .await + .unwrap(); + let unplanned = import.run(false, None).await.unwrap_err(); + + let CsvImportCheck::RowRefused { fault } = check else { + panic!("{check:?}") + }; + assert_eq!( + (fault.line, fault.column.as_str(), fault.text.as_str()), + (3, "age", "old") + ); + assert!(fault.reason.starts_with("edit."), "{}", fault.reason); + assert_eq!(unplanned.code(), "import.not_planned"); + assert!(rows(&session).await.is_empty()); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn a_row_the_table_refuses_rolls_the_whole_file_back_and_names_its_lines() { + let dir = tempfile::tempdir().unwrap(); + let core = core(dir.path()); + let session = seeded(&core, &dir.path().join("people.sqlite")).await; + run(&session, "INSERT INTO people (id, name) VALUES (2, 'Taken')").await; + let csv = write(dir.path(), "clash.csv", "1,Ada\n2,Grace\n"); + let options = CsvReadOptions { + has_header: false, + ..comma() + }; + let import = session.open_csv_import(people(), None).await.unwrap(); + + let preview = import.preview(csv.clone(), options.clone()).await.unwrap(); + let check = import + .plan(csv, options, vec![Some(0), Some(1), None, None, None]) + .await + .unwrap(); + let outcome = import.run(false, None).await.unwrap(); + + assert_eq!(preview.headers, ["", ""], "a file with no header names no field"); + assert!(matches!(check, CsvImportCheck::Ready { rows: 2, .. }), "{check:?}"); + let CsvImportOutcome::RolledBack { lines: Some(lines), .. } = outcome else { + panic!("{outcome:?}") + }; + assert_eq!((lines.first, lines.last), (1, 2)); + assert_eq!( + rows(&session).await, + [row([Some("2"), Some("Taken"), None, Some("today")])] + ); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn a_file_that_is_not_csv_text_or_has_no_rows_is_told_apart() { + let dir = tempfile::tempdir().unwrap(); + let core = core(dir.path()); + let session = seeded(&core, &dir.path().join("people.sqlite")).await; + let import = session.open_csv_import(people(), None).await.unwrap(); + let binary = dir.path().join("binary.csv"); + std::fs::write(&binary, b"id,name\n1,\xff\xfe\n").unwrap(); + let header_only = write(dir.path(), "empty.csv", "id,name\n"); + let mapping = vec![Some(0), Some(1), None, None, None]; + + let not_text = import.preview(binary.display().to_string(), comma()).await.unwrap_err(); + let missing = import + .preview(dir.path().join("gone.csv").display().to_string(), comma()) + .await + .unwrap_err(); + let empty = import.plan(header_only.clone(), comma(), mapping).await.unwrap(); + let short = import + .plan(header_only.clone(), comma(), vec![Some(0)]) + .await + .unwrap_err(); + let past = import + .plan(header_only, comma(), vec![Some(5), None, None, None, None]) + .await + .unwrap_err(); + let gone = session + .open_csv_import( + TableName { + schema: None, + name: "nowhere".to_owned(), + }, + None, + ) + .await; + + assert_eq!(not_text.code(), "import.not_utf8"); + assert_eq!(missing.code(), "import.unreadable"); + assert_eq!(empty, CsvImportCheck::Empty); + assert_eq!(short.code(), "import.mapping_invalid"); + assert_eq!(past.code(), "import.mapping_invalid"); + assert!(gone.is_err()); + session.close().await.unwrap(); +} + +#[tokio::test] +async fn confirm_writes_asks_first_and_read_only_refuses() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await.close().await.unwrap(); + let csv = write(dir.path(), "people.csv", "id,name\n1,Ada\n"); + let mapping = vec![Some(0), Some(1), None, None, None]; + let library = core.library().unwrap(); + let record = ConnectionRecord { + id: String::new(), + name: "people".to_owned(), + driver_id: "sqlite".to_owned(), + host: String::new(), + port: 0, + database: path.display().to_string(), + username: String::new(), + integrated_auth: false, + tls: TlsSettings { + mode: TlsModeTag::Disable, + ca_file: None, + client_certificate: None, + client_key: None, + server_name: None, + }, + ssh: None, + safe_mode: SafeModeTag::ConfirmWrites, + query_timeout_secs: None, + color: None, + group_id: None, + last_opened_ms: None, + tags: Vec::new(), + }; + let saved = library.save(record, ConnectionSecrets::default()).await.unwrap(); + let session = core + .connect_saved( + saved.id, + ConnectionSecrets::default(), + ConnectionSecrets::default(), + None, + None, + ) + .await + .unwrap(); + let import = session.open_csv_import(people(), None).await.unwrap(); + + let check = import.plan(csv.clone(), comma(), mapping.clone()).await.unwrap(); + let unanswered = import.run(false, None).await.unwrap_err(); + import.plan(csv.clone(), comma(), mapping.clone()).await.unwrap(); + let answered = import.run(true, None).await.unwrap(); + session.close().await.unwrap(); + let read_only = core + .open_file( + FileOpenRequest { + path: path.display().to_string(), + driver_id: None, + read_only: true, + create: false, + }, + None, + ) + .await + .unwrap(); + let import = read_only.open_csv_import(people(), None).await.unwrap(); + let refused = import.plan(csv, comma(), mapping).await.unwrap(); + + assert!( + matches!( + check, + CsvImportCheck::Ready { + gate: SaveGate::Confirm, + .. + } + ), + "{check:?}" + ); + assert_eq!(unanswered.code(), "import.not_confirmed"); + assert_eq!(answered, CsvImportOutcome::Imported { rows: 1 }); + assert!( + matches!( + refused, + CsvImportCheck::Ready { + gate: SaveGate::Refuse, + .. + } + ), + "{refused:?}" + ); + assert_eq!( + import.run(true, None).await.unwrap_err().code(), + "edit.read_only_connection" + ); + session.close().await.unwrap(); +} diff --git a/core/crates/ffi/tests/library_copies.rs b/core/crates/ffi/tests/library_copies.rs new file mode 100644 index 0000000000..e13975a856 --- /dev/null +++ b/core/crates/ffi/tests/library_copies.rs @@ -0,0 +1,244 @@ +#![cfg(feature = "engines")] +#![expect( + clippy::unwrap_used, + reason = "the setup helpers fail a test the way the test functions themselves do" +)] + +use std::collections::HashMap; +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use secrecy::{ExposeSecret, SecretString}; +use tablepro_ffi::{ + ConnectionRecord, ConnectionSecrets, Core, HostConfig, HostSecretError, HostSecrets, SafeModeTag, SecretItemTag, + SecretKindTag, SshAuthTag, SshSettings, TlsModeTag, TlsSettings, +}; + +type Stored = Arc>>; + +// Refuses every store while `locked` is set, as a locked keychain does. +#[derive(Default, Clone)] +struct MemorySecrets { + held: Stored, + locked: Arc, +} + +impl MemorySecrets { + fn value(&self, id: &str, kind: SecretKindTag) -> Option { + self.held + .lock() + .unwrap() + .get(&(id.to_owned(), kind)) + .map(|secret| secret.expose_secret().to_owned()) + } + + fn ids(&self) -> Vec { + let mut ids: Vec = self.held.lock().unwrap().keys().map(|(id, _)| id.clone()).collect(); + ids.sort(); + ids.dedup(); + ids + } +} + +impl HostSecrets for MemorySecrets { + fn load(&self, connection_id: String, kind: SecretKindTag) -> Result, HostSecretError> { + Ok(self.held.lock().unwrap().get(&(connection_id, kind)).cloned()) + } + + fn store( + &self, + connection_id: String, + kind: SecretKindTag, + secret: SecretString, + _: String, + ) -> Result<(), HostSecretError> { + if self.locked.load(Ordering::SeqCst) { + return Err(HostSecretError::Locked); + } + self.held.lock().unwrap().insert((connection_id, kind), secret); + Ok(()) + } + + fn relabel(&self, _: String, _: SecretKindTag, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete(&self, connection_id: String, kind: SecretKindTag) -> Result<(), HostSecretError> { + self.held.lock().unwrap().remove(&(connection_id, kind)); + Ok(()) + } + + fn delete_connection(&self, connection_id: String) -> Result<(), HostSecretError> { + self.held.lock().unwrap().retain(|(id, _), _| *id != connection_id); + 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(()) + } +} + +fn core(dir: &Path, secrets: MemorySecrets) -> Arc { + Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: Some(dir.display().to_string()), + }, + Box::new(secrets), + ) + .unwrap() +} + +fn record(name: &str) -> ConnectionRecord { + ConnectionRecord { + id: String::new(), + name: name.to_owned(), + driver_id: "postgres".to_owned(), + host: "db.example.com".to_owned(), + port: 5432, + database: "shop".to_owned(), + username: "app".to_owned(), + integrated_auth: false, + tls: TlsSettings { + mode: TlsModeTag::Require, + ca_file: None, + client_certificate: None, + client_key: None, + server_name: None, + }, + ssh: Some(SshSettings { + host: "bastion.example.com".to_owned(), + port: Some(22), + username: Some("ops".to_owned()), + jump_hosts: Vec::new(), + auth: SshAuthTag::Password, + }), + safe_mode: SafeModeTag::ConfirmWrites, + query_timeout_secs: Some(30), + color: None, + group_id: None, + last_opened_ms: None, + tags: Vec::new(), + } +} + +fn secrets() -> ConnectionSecrets { + ConnectionSecrets { + database_password: Some(SecretString::from("hunter2")), + ssh_password: Some(SecretString::from("tunnel")), + ..ConnectionSecrets::default() + } +} + +#[tokio::test] +async fn a_copy_lands_after_its_original_with_a_new_id_and_every_secret() { + let dir = tempfile::tempdir().unwrap(); + let vault = MemorySecrets::default(); + let library = core(dir.path(), vault.clone()).library().unwrap(); + let group = library.create_group("Work".to_owned(), None).await.unwrap(); + let mut shop = record("Shop"); + shop.group_id = Some(group.id.clone()); + let shop = library.save(shop, secrets()).await.unwrap(); + let mut after = record("After"); + after.group_id = Some(group.id.clone()); + let after = library.save(after, ConnectionSecrets::default()).await.unwrap(); + library.set_favorite(shop.id.clone(), true).await.unwrap(); + + let copy = library + .duplicate(shop.id.clone(), " Shop (Copy) ".to_owned()) + .await + .unwrap(); + let snapshot = library.snapshot().await.unwrap(); + + assert_ne!(copy.id, shop.id); + assert_eq!(copy.name, "Shop (Copy)"); + assert_eq!(copy.group_id.as_deref(), Some(group.id.as_str())); + assert_eq!((copy.host.as_str(), copy.port), ("db.example.com", 5432)); + assert_eq!(copy.ssh, shop.ssh); + assert_eq!(copy.safe_mode, SafeModeTag::ConfirmWrites); + assert_eq!(copy.last_opened_ms, None); + let order: Vec<&str> = snapshot.connections.iter().map(|saved| saved.id.as_str()).collect(); + assert_eq!(order, [shop.id.as_str(), copy.id.as_str(), after.id.as_str()]); + assert_eq!(snapshot.favorites, std::slice::from_ref(&shop.id)); + for kind in [SecretKindTag::DatabasePassword, SecretKindTag::SshPassword] { + assert_eq!(vault.value(©.id, kind), vault.value(&shop.id, kind), "{kind:?}"); + } + assert_eq!( + vault.value(©.id, SecretKindTag::DatabasePassword).as_deref(), + Some("hunter2") + ); + + library.delete(shop.id.clone()).await.unwrap(); + assert_eq!( + vault.value(©.id, SecretKindTag::SshPassword).as_deref(), + Some("tunnel") + ); +} + +#[tokio::test] +async fn a_copy_whose_secrets_are_refused_is_not_saved_and_leaves_none_behind() { + let dir = tempfile::tempdir().unwrap(); + let vault = MemorySecrets::default(); + let library = core(dir.path(), vault.clone()).library().unwrap(); + let shop = library.save(record("Shop"), secrets()).await.unwrap(); + vault.locked.store(true, Ordering::SeqCst); + + let refused = library + .duplicate(shop.id.clone(), "Shop (Copy)".to_owned()) + .await + .unwrap_err(); + let unnamed = library.duplicate(shop.id.clone(), " ".to_owned()).await.unwrap_err(); + let unknown = library + .duplicate("6f0b6a4e-3a52-4c2f-9d1e-0c6a2b7f9e11".to_owned(), "Gone".to_owned()) + .await + .unwrap_err(); + + assert_eq!(refused.code(), "secret.locked"); + assert_eq!(unnamed.code(), "library.name_required"); + assert_eq!(unknown.code(), "storage.connection_not_found"); + assert_eq!(library.snapshot().await.unwrap().connections.len(), 1); + assert_eq!(vault.ids(), [shop.id]); +} + +#[tokio::test] +async fn an_exported_file_holds_every_connection_and_no_secret_and_imports_back() { + let dir = tempfile::tempdir().unwrap(); + let library = core(&dir.path().join("one"), MemorySecrets::default()) + .library() + .unwrap(); + library.save(record("Shop"), secrets()).await.unwrap(); + library + .save(record("Warehouse"), ConnectionSecrets::default()) + .await + .unwrap(); + let file = dir.path().join("connections.json"); + + let count = library.export_file(file.display().to_string()).await.unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + let elsewhere = core(&dir.path().join("two"), MemorySecrets::default()) + .library() + .unwrap(); + let imported = elsewhere.import_file(file.display().to_string()).await.unwrap(); + let relative = library.export_file("connections.json".to_owned()).await.unwrap_err(); + + assert_eq!(count, 2); + assert!(text.contains("db.example.com") && text.contains("Warehouse"), "{text}"); + assert!(!text.contains("hunter2") && !text.contains("tunnel"), "{text}"); + assert_eq!((imported.added, imported.updated), (2, 0)); + assert_eq!(relative.code(), "ffi.export_bad_path"); + let leftovers: Vec = std::fs::read_dir(dir.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.ends_with(".part")) + .collect(); + assert!(leftovers.is_empty(), "{leftovers:?}"); +} diff --git a/core/crates/ffi/tests/saved_queries.rs b/core/crates/ffi/tests/saved_queries.rs new file mode 100644 index 0000000000..fbd09d558c --- /dev/null +++ b/core/crates/ffi/tests/saved_queries.rs @@ -0,0 +1,359 @@ +#![cfg(feature = "engines")] +#![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, FavouriteTableInfo, FileOpenRequest, HistoryExportFormat, HistoryOutcomeTag, + HistoryRun, HostConfig, HostSecretError, HostSecrets, SavedQueryDraft, SecretItemTag, SecretKindTag, +}; + +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 OTHER: &str = "1c2d3e4f-5a6b-4c7d-8e9f-a0b1c2d3e4f5"; + +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 draft(connection: &str, name: &str, sql: &str) -> SavedQueryDraft { + SavedQueryDraft { + connection_id: connection.to_owned(), + connection_name: "shop".to_owned(), + name: name.to_owned(), + sql: sql.to_owned(), + } +} + +#[tokio::test] +async fn a_saved_query_comes_back_for_its_connection_only() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let queries = core.history().await.unwrap().saved_queries(); + + let id = queries + .save(draft(SHOP, "Orders today", "SELECT * FROM orders"), false) + .await + .unwrap() + .unwrap(); + queries + .save(draft(OTHER, "Elsewhere", "SELECT 1"), false) + .await + .unwrap(); + let shop = queries.snapshot(SHOP.to_owned()).await.unwrap(); + + let [query] = shop.queries.as_slice() else { + panic!("{:?}", shop.queries) + }; + assert_eq!(query.id, id); + assert_eq!(query.name, "Orders today"); + assert_eq!(query.sql, "SELECT * FROM orders"); + assert_eq!( + (query.folder_id, query.keyword.as_deref(), query.order), + (None, None, 0) + ); + assert!(query.updated_at_ms > 0); + assert!(shop.folders.is_empty()); +} + +#[tokio::test] +async fn a_taken_name_is_replaced_only_when_asked_and_keeps_its_id() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let queries = core.history().await.unwrap().saved_queries(); + let first = queries + .save(draft(SHOP, "Daily", "SELECT 1"), false) + .await + .unwrap() + .unwrap(); + + let kept = queries.save(draft(SHOP, "Daily", "SELECT 2"), false).await.unwrap(); + let before = queries.snapshot(SHOP.to_owned()).await.unwrap(); + let replaced = queries.save(draft(SHOP, "Daily", "SELECT 2"), true).await.unwrap(); + let after = queries.snapshot(SHOP.to_owned()).await.unwrap(); + + assert_eq!(kept, None); + assert_eq!(before.queries[0].sql, "SELECT 1"); + assert_eq!(replaced, Some(first)); + assert_eq!(after.queries.len(), 1); + assert_eq!(after.queries[0].sql, "SELECT 2"); +} + +#[tokio::test] +async fn folders_nest_hold_queries_in_order_and_give_them_back_to_the_top_when_deleted() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let queries = core.history().await.unwrap().saved_queries(); + let reports = queries + .create_folder(SHOP.to_owned(), "Reports".to_owned(), None) + .await + .unwrap(); + let monthly = queries + .create_folder(SHOP.to_owned(), "Monthly".to_owned(), Some(reports)) + .await + .unwrap(); + let a = queries + .save(draft(SHOP, "A", "SELECT 'a'"), false) + .await + .unwrap() + .unwrap(); + let b = queries + .save(draft(SHOP, "B", "SELECT 'b'"), false) + .await + .unwrap() + .unwrap(); + + queries.move_query(a, Some(monthly), None).await.unwrap(); + queries.move_query(b, Some(monthly), Some(a)).await.unwrap(); + let filed = queries.snapshot(SHOP.to_owned()).await.unwrap(); + queries.delete_folder(reports).await.unwrap(); + let after = queries.snapshot(SHOP.to_owned()).await.unwrap(); + + assert_eq!(filed.folders.len(), 2); + let inner = filed.folders.iter().find(|folder| folder.id == monthly).unwrap(); + assert_eq!(inner.parent_id, Some(reports)); + let order: Vec<(i64, Option, i64)> = filed + .queries + .iter() + .map(|query| (query.id, query.folder_id, query.order)) + .collect(); + assert_eq!(order, [(b, Some(monthly), 0), (a, Some(monthly), 1)]); + assert!(after.folders.is_empty()); + assert!(after.queries.iter().all(|query| query.folder_id.is_none())); + assert_eq!(after.queries.len(), 2); +} + +#[tokio::test] +async fn a_rename_a_keyword_or_a_folder_name_already_taken_is_refused_by_code() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let queries = core.history().await.unwrap().saved_queries(); + let one = queries + .save(draft(SHOP, "One", "SELECT 1"), false) + .await + .unwrap() + .unwrap(); + let two = queries + .save(draft(SHOP, "Two", "SELECT 2"), false) + .await + .unwrap() + .unwrap(); + queries.set_keyword(one, Some("sel".to_owned())).await.unwrap(); + queries + .create_folder(SHOP.to_owned(), "Reports".to_owned(), None) + .await + .unwrap(); + + let name = queries.rename(two, "One".to_owned()).await.unwrap_err(); + let keyword = queries.set_keyword(two, Some("SEL".to_owned())).await.unwrap_err(); + let spaced = queries + .set_keyword(two, Some("two words".to_owned())) + .await + .unwrap_err(); + let folder = queries + .create_folder(SHOP.to_owned(), "reports".to_owned(), None) + .await + .unwrap_err(); + let empty = queries.save(draft(SHOP, " ", "SELECT 3"), false).await.unwrap_err(); + let unknown = queries.delete(9_999).await.unwrap_err(); + + assert_eq!(name.code(), "storage.name_taken"); + assert_eq!(keyword.code(), "storage.keyword_taken"); + assert_eq!(spaced.code(), "storage.keyword_invalid"); + assert_eq!(folder.code(), "storage.folder_name_taken"); + assert_eq!(empty.code(), "storage.empty_name"); + assert_eq!(unknown.code(), "storage.not_found"); + let snapshot = queries.snapshot(SHOP.to_owned()).await.unwrap(); + let keywords: Vec> = snapshot.queries.iter().map(|query| query.keyword.as_deref()).collect(); + assert_eq!(keywords, [Some("sel"), None]); +} + +#[tokio::test] +async fn deleting_a_connections_data_takes_its_queries_folders_and_favourites_only() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let history = core.history().await.unwrap(); + let queries = history.saved_queries(); + let favourites = history.favourites(); + queries.save(draft(SHOP, "Mine", "SELECT 1"), false).await.unwrap(); + queries + .create_folder(SHOP.to_owned(), "Reports".to_owned(), None) + .await + .unwrap(); + queries.save(draft(OTHER, "Theirs", "SELECT 2"), false).await.unwrap(); + let table = FavouriteTableInfo { + database: None, + schema: Some("main".to_owned()), + name: "orders".to_owned(), + }; + favourites.add_table(SHOP.to_owned(), table.clone()).await.unwrap(); + favourites.add_table(OTHER.to_owned(), table).await.unwrap(); + + let removed = queries.delete_for_connection(SHOP.to_owned()).await.unwrap(); + + assert_eq!(removed, 1); + let mine = queries.snapshot(SHOP.to_owned()).await.unwrap(); + assert!(mine.queries.is_empty() && mine.folders.is_empty()); + assert!(favourites.tables(SHOP.to_owned()).await.unwrap().is_empty()); + assert_eq!(queries.snapshot(OTHER.to_owned()).await.unwrap().queries.len(), 1); + assert_eq!(favourites.tables(OTHER.to_owned()).await.unwrap().len(), 1); +} + +#[tokio::test] +async fn favourite_tables_and_databases_are_kept_per_connection() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let favourites = core.history().await.unwrap().favourites(); + let orders = FavouriteTableInfo { + database: Some("shop".to_owned()), + schema: Some(String::new()), + name: "orders".to_owned(), + }; + + favourites.add_table(SHOP.to_owned(), orders.clone()).await.unwrap(); + favourites.add_table(SHOP.to_owned(), orders.clone()).await.unwrap(); + favourites + .set_database(SHOP.to_owned(), "shop".to_owned(), DatabaseEnvironmentTag::Testing) + .await + .unwrap(); + favourites + .set_database(SHOP.to_owned(), "shop".to_owned(), DatabaseEnvironmentTag::Production) + .await + .unwrap(); + let tables = favourites.tables(SHOP.to_owned()).await.unwrap(); + let databases = favourites.databases(SHOP.to_owned()).await.unwrap(); + favourites.remove_table(SHOP.to_owned(), orders).await.unwrap(); + favourites + .remove_database(SHOP.to_owned(), "shop".to_owned()) + .await + .unwrap(); + + let [table] = tables.as_slice() else { + panic!("{tables:?}") + }; + assert_eq!(table.database.as_deref(), Some("shop")); + assert_eq!(table.schema, None, "an empty schema is none"); + assert_eq!(table.name, "orders"); + assert_eq!(databases.len(), 1); + assert_eq!(databases[0].environment, DatabaseEnvironmentTag::Production); + assert!(favourites.tables(SHOP.to_owned()).await.unwrap().is_empty()); + assert!(favourites.databases(SHOP.to_owned()).await.unwrap().is_empty()); + assert!(favourites.tables("not-an-id".to_owned()).await.is_err()); +} + +#[tokio::test] +async fn a_pinned_run_comes_first_and_an_export_writes_the_runs_asked_for() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let session = core + .open_file( + FileOpenRequest { + path: dir.path().join("app.sqlite").display().to_string(), + driver_id: None, + read_only: false, + create: true, + }, + None, + ) + .await + .unwrap(); + let history = core.history().await.unwrap(); + let ran = |sql: &str, at_secs: i64| HistoryRun { + sql: sql.to_owned(), + executed_at_ms: at_secs * 1_000, + duration_ms: None, + rows_affected: None, + outcome: HistoryOutcomeTag::Succeeded, + }; + let old = history + .record(session.clone(), ran("SELECT 'old'", 1_700_000_000)) + .await + .unwrap() + .unwrap(); + let new = history + .record(session.clone(), ran("SELECT 'new'", 1_700_000_100)) + .await + .unwrap() + .unwrap(); + + history.set_pinned(old, true).await.unwrap(); + let pinned = history.search(String::new(), None, None, 50).await.unwrap(); + history.set_pinned(old, false).await.unwrap(); + let unpinned = history.search(String::new(), None, None, 50).await.unwrap(); + let sql_file = dir.path().join("history.sql"); + let csv_file = dir.path().join("history.csv"); + history + .export(vec![old], HistoryExportFormat::Sql, sql_file.display().to_string()) + .await + .unwrap(); + history + .export(vec![old, new], HistoryExportFormat::Csv, csv_file.display().to_string()) + .await + .unwrap(); + let relative = history + .export(vec![old], HistoryExportFormat::Sql, "history.sql".to_owned()) + .await + .unwrap_err(); + + let order: Vec<(i64, bool)> = pinned.entries.iter().map(|entry| (entry.id, entry.pinned)).collect(); + assert_eq!(order, [(old, true), (new, false)]); + let order: Vec = unpinned.entries.iter().map(|entry| entry.id).collect(); + assert_eq!(order, [new, old]); + let script = std::fs::read_to_string(&sql_file).unwrap(); + assert!( + script.contains("SELECT 'old'") && !script.contains("SELECT 'new'"), + "{script}" + ); + let csv = std::fs::read_to_string(&csv_file).unwrap(); + assert!(csv.starts_with("\"executed_at\","), "{csv}"); + assert_eq!(csv.lines().count(), 3, "{csv}"); + assert_eq!(relative.code(), "ffi.export_bad_path"); + session.close().await.unwrap(); +} diff --git a/core/docs/decisions/0017-favourites.md b/core/docs/decisions/0017-favourites.md index b771612102..c8fd4631dd 100644 --- a/core/docs/decisions/0017-favourites.md +++ b/core/docs/decisions/0017-favourites.md @@ -1,6 +1,6 @@ # 0017: Favourites keep folders and keywords on saved queries, and the tables and databases a user marks -- **Status**: Accepted +- **Status**: Accepted; the FFI surface added by [0029](0029-storage-import-and-library-through-the-ffi.md) - **Date**: 2026-11-08 ## Context diff --git a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md new file mode 100644 index 0000000000..c653e20234 --- /dev/null +++ b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md @@ -0,0 +1,37 @@ +# 0029: Saved queries, favourites, history pins, CSV import and connection copies cross the FFI + +- **Status**: Accepted +- **Date**: 2026-11-15 + +## Context + +The Windows app reaches the core only through `crates/ffi`. Saved queries with folders and keywords, favourite tables and databases ([0017](0017-favourites.md)), history pins and export, the CSV import (`tablepro_core::import`) and the connection library's export are core code the Linux app calls directly and the FFI did not expose. Duplicating a connection with its secrets lived only in the Linux app, over storage calls the FFI already has. + +## Decision + +- `QueryHistoryStore` gains `set_pinned`, `export(ids, format, path)` and two stores over the same database: `saved_queries()` and `favourites()`. +- `SavedQueryStore` reads a connection's queries and folders in one transaction (`snapshot`) and writes through `SavedQueries` and `SavedQueryFolders` as they are. `save(draft, replace)` gives the id, or nothing when the name is taken and `replace` is false, so the app asks before replacing. `delete_for_connection` takes a deleted connection's queries, folders and favourites. +- `FavouriteStore` lists, marks and unmarks tables and databases per connection, a database with one of the four environments. +- `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the row count, the statements' SQL and the Safe Mode gate. +- `CsvImport::run(confirmed)` writes the import planned last, once, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack`, `PartlyWritten` with the rows before it on an engine without a transaction, or `Unknown`. +- `ConnectionLibrary::duplicate(id, name)` copies the connection under a new id right after the original (`insert_after_blocking`), never opened and no favourite, after copying every secret kind the original keeps; a refused secret or write takes the copy's secrets back. The app names the copy, since the name is in the user's language. `export_file(path)` writes `export_blocking`'s document, which carries no secret. +- History exports and connection exports are written beside the target and renamed over it once synced, as result exports are. + +## Rationale + +- The storage and import code stays where Linux runs it; the FFI only maps records and codes, so both apps keep one behavior. +- A row the file cannot fill and an empty file are things the user fixes in the dialog, so they come back as values the app words with the cell edit's own codes. +- The plan is kept in the `CsvImport` object, so the statements shown before a confirmed run are the ones sent, without the rows crossing the boundary twice. +- The copy's secrets go in before its entry, so no listed connection points at secrets that are not there. + +## Consequences + +- The app words the copy's name and every error code (`import.*`, `storage.*`, `secret.*`). +- `DraftStore` stays off the FFI: the Windows app keeps a query tab's text in its own session file and calls nothing that needs it. +- `PastedTable` and `PastedRows` stay off the FFI until a paste into the grid has its key-based edits (roadmap C-10). +- An import of a file past 64 MiB is refused; one larger import needs the streaming the SQL file import has ([0011](0011-sql-dump-and-import-in-process.md)). + +## Alternatives considered + +- **The app reads the file and sends rows.** Every value would cross as text twice and the app would hold a copy of the file the core already reads. +- **A row fault as an error with fields.** `ErrorInfo` would grow fields only one call fills, in every binding. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index e197123ccc..b4c5ab9fa4 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -24,7 +24,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0014](0014-tls-mode-of-a-new-connection.md) | A new connection starts on the TLS mode the engine's own client starts on | Accepted | `TlsMode::Prefer` for PostgreSQL and MySQL, Verify full for SQL Server, Disable for the engines that decide TLS by the port, with a DNS seed list and ClickHouse's HTTPS ports on Verify full; the core holds the rule, and every TLS failure a mode change fixes offers Change Encryption. | | [0015](0015-editing-a-query-result.md) | A query result edits when its statement reads one table and its driver traces the columns | Accepted | The parser accepts one row-preserving SELECT over one table; each driver sets `ResultColumn::origin` only for a direct column of a permanent base table, from the wire or a lookup on its own connection; the result maps to the catalog with its full primary key and saves through `plan_save`. | | [0016](0016-tablepro-accounts.md) | TablePro accounts live in the core, with features gated by the entitlement | Accepted; the Windows app amended by 0026, share links amended by 0027 | `tablepro-account` signs in through the browser with OAuth and a loopback redirect, registers the device, verifies the Ed25519 entitlement and gates features by its codes; each app passes its keyring, browser, machine ID and OAuth client in. | -| [0017](0017-favourites.md) | Favourites keep folders and keywords on saved queries, and the tables and databases a user marks | Accepted | One migration in the history's database adds per-connection folders that nest, a keyword and an order on saved queries, and favourite tables and databases with the four macOS environments; stable error codes, no UUID ids, and a database an older build wrote is copied first. | +| [0017](0017-favourites.md) | Favourites keep folders and keywords on saved queries, and the tables and databases a user marks | Accepted; the FFI surface added by 0029 | One migration in the history's database adds per-connection folders that nest, a keyword and an order on saved queries, and favourite tables and databases with the four macOS environments; stable error codes, no UUID ids, and a database an older build wrote is copied first. | | [0018](0018-command-line.md) | One command line for the apps on the core | Accepted | `tablepro-cli` parses with clap, writes the macOS command's formats and exit status, and reaches the app's MCP server with the token the app's host reads; `classify` leaves files, links and GUI options to the app. | | [0019](0019-row-edits-through-the-ffi.md) | A table tab's row edits cross the FFI as typed text, and the core plans and runs the save | Accepted | `TableEditor` over the catalog's primary key reads keys and stored values from the result set, parses typed text with `parse_edit_text` and plans with `plan_save`; `RowSave` shows its statements with their values, gates at `SafeModeLevel::gate(Write)`, plans again on the writing lease and reports saved, rolled back or unknown. | | [0020](0020-a-run-keeps-a-byte-limit-of-rows.md) | A run keeps a byte limit of rows | Accepted | `RunOptions::byte_limit`, 256 MB by default, bounds the rows an editor run keeps, measured by `Value::retained_bytes`; the session wraps every editor session in `ByteLimitSink`, which keeps whole rows, never stops the statement and finishes a cut set as `Truncation::ByteLimit`; MongoDB stops reading itself; table pages are exempt. | @@ -36,3 +36,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0026](0026-the-windows-app-signs-in-through-the-ffi.md) | The Windows app signs in to its TablePro account through the FFI | Accepted | `Core::open_account` builds the account with `AppClient::WINDOWS`, the Core's secret store for the refresh token, a `HostBrowser` callback and `MachineId::derive_machine_guid` of the registry's MachineGuid, keyed as Linux keys `/etc/machine-id`; `status()` is a snapshot and `AccountListener` only signals. | | [0027](0027-share-links.md) | Share links go through the account, with the snapshot and the secret scan in the core | Accepted; masked columns and the secret scan amended by 0028 | `Account` adds the share calls through the generated `/v2` client, `fetch_shared` without a token; problem codes stay `Refused` with their own `code()`; `build_snapshot` writes raw JSON cells by the export's lossless rules up to the plan's rows; a table page shares `build_view_sql`, its export with the filter's values written in; `secret_scan` warns; the deep link takes one 43-character base62 token. | | [0028](0028-data-masking.md) | A shared result masks its columns before it leaves the machine, with the macOS app's output | Accepted | `tablepro_core::masking` gives the macOS styles byte for byte; `SharePlan` applies the sheet's Keep, Mask or Remove per column for the snapshot, its preview and summary; the snapshot names each masked column's style and keeps to the macOS body budget; `masking::detect` suggests masks from names, values and the SQL by PLAN-MASKING 8.3. | +| [0029](0029-storage-import-and-library-through-the-ffi.md) | Saved queries, favourites, history pins, CSV import and connection copies cross the FFI | Accepted | `QueryHistoryStore` gives `SavedQueryStore` and `FavouriteStore` over its database, pins and exports runs; `CsvImport` previews, suggests a mapping, plans a file of up to 64 MiB with row faults as values and runs it once under the row save's Safe Mode gate; `ConnectionLibrary` duplicates with every secret after the original and exports without secrets. | diff --git a/windows/AGENTS.md b/windows/AGENTS.md index 602bbbb48d..578a527266 100644 --- a/windows/AGENTS.md +++ b/windows/AGENTS.md @@ -43,6 +43,7 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `DataGridView.SetData(new ResultSetData(set, columns))` shows a set. Call the grid's `RowsChanged` after each `RowsAppended`. Sorting is the host's: the grid raises `SortRequested` and shows `Sort`. - The core writes every sorted statement: `ReadTablePageAsync` reads a table's page with its sort and filter on a pooled connection and returns its run, `SortedQuery` writes a query result's, null when the statement cannot run again or the engine cannot name the column. `ResultSet.SortedAsync` then sorts the rows held (`core/docs/decisions/0007-sorting-a-result.md`). `ReadTablePageAsync` takes the page's offset, and `CanSeek` says whether the engine has later pages; `CountRowsAsync` counts the rows the filter picks, and `EstimateRowsAsync` gives the whole table's count from the engine's statistics, null where it keeps none. The filter's values are bound by the core, never written into SQL here (`core/docs/decisions/0022-browsing-through-the-ffi.md`). - `GetStructureAsync` gives a table's columns, indexes, foreign keys and CREATE script, `GetObjectDefinitionAsync` a routine's, trigger's or sequence's source, `ExportRowsAsync` and `ExportTableAsync` write a file through the core's encoders, and `TableProCore.OpenHistoryAsync` the query history, which withholds what the engine says holds a secret. +- `QueryHistory.OpenSavedQueries` and `OpenFavourites` give the saved queries with their folders and the marked tables and databases, per saved connection, from the history's database; `SetPinnedAsync` pins a run and `ExportAsync` writes runs to a file. `DatabaseSession.OpenCsvImportAsync` gives a `CsvImport` that previews a file, suggests a mapping, plans it with a Safe Mode gate and runs it once; a field a column cannot read comes back as `CsvImportCheck.RowRefused`, not an exception. `ConnectionLibrary.DuplicateAsync` copies a connection with its secrets and `ExportAsync` writes the connections file without them (`core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md`). - A table tab edits through `DatabaseSession.OpenTableEditorAsync`: the app sends what was typed (`CellEdit`) per row of the page's `ResultSet`, and `TableEditor.Plan` gives a `RowSave` with its statements and Safe Mode gate, which `RunAsync` saves (`core/docs/decisions/0019-row-edits-through-the-ffi.md`). - `QueryEvent.Finished.Transaction` is the transaction the editor's connection is left in. A session's `Health` is waited on with `WaitForHealthChangeAsync`, which returns once it differs from the one passed in. - The app starts the core with `TableProCore.CreateWithSystemSecrets`, so the core keeps secrets in Credential Manager itself. `ISecretStore` is for tests and hosts with a store of their own; the core calls it on a thread of its own. diff --git a/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md b/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md new file mode 100644 index 0000000000..36bb0b402c --- /dev/null +++ b/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md @@ -0,0 +1,43 @@ +# 0011: Saved queries, history pins, CSV import and connection copies + +- **Status**: Accepted +- **Date**: 2026-11-15 + +## Context + +The Windows app could not keep a query, pin a run in the history, import a file into a table, duplicate a connection or export the connections file. The macOS app has each, and the core now carries them through the FFI ([core 0029](../../../core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md)). + +## Decision + +Each works as the macOS app's does, with its words in Windows sentence case, over the core's stores and plans; the logic sits in `src/TablePro.App.Model` with fakes in `tests/TablePro.App.Model.Tests`, and the views lay out. + +### Saved queries + +- Query > Save query... keeps a query tab's whole text under a name, and the history's entry menu keeps a run's. A dialog asks for the name, prefilled from the text as macOS names a favorite, and a folder once there are folders. A name the connection already uses asks before it replaces that query, which keeps its place. +- View > Show saved queries opens a pane in the place the history pane takes, one of the two at a time. A tree lists folders, then queries, each in its stored order. Invoking a query inserts it in the editor, as macOS does: it replaces an empty query tab's text, follows a tab's text after a blank line, and opens a new query tab when none is in front. Its menu has Insert in editor, Open in new tab, Copy query, Edit..., Move to and Delete; a folder's has New subfolder, Rename and Delete folder, whose folders go with it and whose queries move to the top level. +- Saved queries belong to a saved connection. A file opened without saving gets a new id each time, so it keeps none. Deleting a connection deletes its saved queries, folders and favourites, as the Linux app does. +- Keywords are kept by the core but not edited here: macOS expands one through completion, which the Windows editor does not have yet. + +### History pins + +- Pin and Unpin on a run's menu. A pinned run shows a pin, comes first and is never pruned. + +### CSV import + +- Import CSV... on a table's menu in the object tree. The system open picker chooses the file; a dialog sets the delimiter (Tab for a .tsv), whether the first row names the fields and the text that means NULL, shows how many fields and rows the file has, and maps a field to each column, starting from the fields whose header names a column. A column the server fills is left to it. A field a column cannot read keeps the dialog open with its line and column. +- Safe Mode gates the import as a save: Confirm writes lists the statements first, Read only refuses. The result names the rows imported or, on a failure, the lines of the file that failed and whether the table kept any rows. + +### Connections + +- Duplicate on a connection's menu copies it with its passwords under "Name (Copy)", then "Name (Copy 2)", right after the original, and opens the form on the copy, as macOS does. +- Export on the Connections page and File > Export connections... write the file Import reads, through the system save picker. It holds no password, and the bar after the export says so. + +## Rationale + +- The core keeps every saved query, plans every INSERT and copies every secret, so Windows keeps no store and writes no SQL the Linux app does not. +- Stock WinUI controls: TreeView, ContentDialog, ComboBox, CheckBox, InfoBar, MenuFlyout, and the Windows App SDK's FileOpenPicker and FileSavePicker. + +## Consequences + +- A CSV file past 64 MiB is refused. +- A saved query cannot be dragged between folders yet; Move to moves it, as macOS has no drop target either. diff --git a/windows/docs/decisions/README.md b/windows/docs/decisions/README.md index d1f42919ad..efc7dfcae8 100644 --- a/windows/docs/decisions/README.md +++ b/windows/docs/decisions/README.md @@ -18,3 +18,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0008](0008-tablepro-account.md) | Signing in to the TablePro account | Accepted | One account opened at launch through the core's `AccountService` (core 0026); Settings shows it with sign in, sign out, refresh, devices and the device limit; every `account.*` code has its sentence. | | [0009](0009-share-links.md) | Share links | Accepted | Share result, Share query and Share in the grids', editor's and File menus; a ContentDialog sheet over the plan's limits with preview, Hide SQL, Pro options, secret warnings and the cap's Revoke list; `tablepro://share` links open their SQL in a new query tab, never run (core 0027). | | [0010](0010-data-masking.md) | Masking a shared result | Accepted | The share sheet's Keep, Mask or Remove per column, detected columns masked by default, the core's preview and summary of what a link sends, and the Hide SQL suggestion; nothing else masks (core 0028). | +| [0011](0011-saved-queries-csv-import-and-connection-copies.md) | Saved queries, history pins, CSV import and connection copies | Accepted | Query > Save query... and a Saved queries pane with folders where the history pane sits, Insert in editor as macOS; Pin on a history run; Import CSV... on a table with a field per column under the save's Safe Mode gate; Duplicate a connection with its passwords and Export the connections file without them. | diff --git a/windows/src/TablePro.App.Model/CopyName.cs b/windows/src/TablePro.App.Model/CopyName.cs new file mode 100644 index 0000000000..ef6d9143ee --- /dev/null +++ b/windows/src/TablePro.App.Model/CopyName.cs @@ -0,0 +1,97 @@ +using System.Globalization; + +namespace TablePro.App.Model; + +// The name a duplicated connection takes: "Shop (Copy)", then "Shop (Copy 2)", and a copy of a copy counts on from the +// original rather than stacking a second suffix. The patterns come in the user's language, "{0} (Copy)" and +// "{0} (Copy {1})". +public static class CopyName +{ + private const string Name = "\u0000"; + private const string Number = "\u0001"; + + public static string For(string name, IEnumerable taken, string pattern, string numberedPattern) + { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(taken); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(numberedPattern); + var names = taken.ToHashSet(StringComparer.Ordinal); + var original = Original(name, pattern, numberedPattern); + var first = Format(pattern, original); + if (!names.Contains(first)) + { + return first; + } + + // A person's own connections, so the count ends within as many steps as they have copies. + for (var n = 2; n < int.MaxValue; n++) + { + var candidate = Format(numberedPattern, original, n.ToString(CultureInfo.CurrentCulture)); + if (!names.Contains(candidate)) + { + return candidate; + } + } + + return first; + } + + private static string Original(string name, string pattern, string numberedPattern) + { + if (Strip(name, Format(pattern, Name)) is { Length: > 0 } plain) + { + return plain; + } + + var numbered = Format(numberedPattern, Name, Number); + var at = numbered.IndexOf(Name, StringComparison.Ordinal); + var between = numbered.IndexOf(Number, StringComparison.Ordinal); + // A translation that puts the number before the name is left as it is: the copy then reads "(Copy) (Copy)". + if (at < 0 || between < at) + { + return name; + } + + var before = numbered[..at]; + var middle = numbered[(at + Name.Length)..between]; + var after = numbered[(between + Number.Length)..]; + if (!name.StartsWith(before, StringComparison.Ordinal) || !name.EndsWith(after, StringComparison.Ordinal) + || name.Length < before.Length + after.Length) + { + return name; + } + + var inner = name[before.Length..(name.Length - after.Length)]; + var split = inner.LastIndexOf(middle, StringComparison.Ordinal); + if (split <= 0) + { + return name; + } + + var count = inner[(split + middle.Length)..]; + return int.TryParse(count, NumberStyles.None, CultureInfo.CurrentCulture, out var n) && n >= 2 + ? inner[..split] + : name; + } + + private static string? Strip(string name, string template) + { + var at = template.IndexOf(Name, StringComparison.Ordinal); + if (at < 0) + { + return null; + } + + var before = template[..at]; + var after = template[(at + Name.Length)..]; + return name.Length > before.Length + after.Length + && name.StartsWith(before, StringComparison.Ordinal) + && name.EndsWith(after, StringComparison.Ordinal) + ? name[before.Length..(name.Length - after.Length)] + : null; + } + + private static string Format(string pattern, params object?[] values) => + string.Format(CultureInfo.CurrentCulture, pattern, values); +} diff --git a/windows/src/TablePro.App.Model/CsvImportForm.cs b/windows/src/TablePro.App.Model/CsvImportForm.cs new file mode 100644 index 0000000000..c42e8c89d4 --- /dev/null +++ b/windows/src/TablePro.App.Model/CsvImportForm.cs @@ -0,0 +1,287 @@ +using System.Text; +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum CsvImportState +{ + Reading, + // The file could not be read under the options; ReadError says why. + Failed, + NoRows, + NothingMapped, + Ready, +} + +public enum CsvColumnNote +{ + // The mapped field's values in the first rows. + Samples, + ServerFilled, + UsesDefault, + LeftOut, +} + +public enum CsvImportEnding +{ + Imported, + // Refused before anything was sent, or rolled back: the table is as it was. + NotWritten, + PartlyWritten, + // Stopped or cut off before the server answered: the table may hold some of the rows. + Unknown, +} + +// Header is null where the file names none. Sample is the first row's value, null when it has none. +public sealed record CsvField(int Index, string? Header, string? Sample); + +// Samples hold null where the file's NULL text stands. +public sealed record CsvColumnLine(ImportColumn Column, int? Field, CsvColumnNote Note, IReadOnlyList Samples); + +public sealed record CsvPreviewSummary(int Fields, int Rows, bool Truncated); + +// Text is what Safe Mode's review lists; Shown counts the statements in it. +public sealed record CsvImportReview(string Text, int Shown); + +// Rows: imported, or written before the failure. Lines: those the failed statement held. No Error: stopped here. +public sealed record CsvImportReport(CsvImportEnding Ending, long Rows, LineSpan? Lines, CoreError? Error) +{ + public static CsvImportReport Stopped { get; } = new(CsvImportEnding.Unknown, 0, null, null); + + // Rows may have reached the table, so a tab showing it reads its rows again. + public bool TableChanged => Ending != CsvImportEnding.NotWritten; + + public static CsvImportReport From(CsvImportOutcome outcome) + { + ArgumentNullException.ThrowIfNull(outcome); + return outcome switch + { + CsvImportOutcome.Imported imported => new CsvImportReport( + CsvImportEnding.Imported, imported.Rows, null, null), + CsvImportOutcome.RolledBack rolledBack => new CsvImportReport( + CsvImportEnding.NotWritten, 0, rolledBack.Lines, rolledBack.Error), + CsvImportOutcome.PartlyWritten partly => new CsvImportReport( + CsvImportEnding.PartlyWritten, partly.WrittenRows, partly.Lines, partly.Error), + CsvImportOutcome.Unknown unknown => new CsvImportReport(CsvImportEnding.Unknown, 0, null, unknown.Error), + _ => throw new ArgumentOutOfRangeException(nameof(outcome)), + }; + } + + public static CsvImportReport Refused(CoreError error) + { + ArgumentNullException.ThrowIfNull(error); + return new CsvImportReport(CsvImportEnding.NotWritten, 0, null, error); + } +} + +// The import dialog's state from the file to the plan: the options, the preview read, and a field per table column. +public sealed class CsvImportForm +{ + public const int SampleCount = 3; + public const int SampleLength = 40; + + // A whole file's statements can run to megabytes, more than a dialog can lay out. + public const int ReviewLength = 50_000; + + private readonly int?[] _mapping; + private int _read; + + public CsvImportForm(IReadOnlyList columns, string filePath) + { + ArgumentNullException.ThrowIfNull(columns); + ArgumentException.ThrowIfNullOrEmpty(filePath); + Columns = columns; + FilePath = filePath; + Options = CsvOptions.Default with { Delimiter = DelimiterFor(filePath) }; + _mapping = new int?[columns.Count]; + } + + public IReadOnlyList Columns { get; } + + public string FilePath { get; } + + public string FileName => Path.GetFileName(FilePath); + + public CsvOptions Options { get; private set; } + + public CsvPreview? Preview { get; private set; } + + public CoreError? ReadError { get; private set; } + + public bool IsReading { get; private set; } + + // Set while the whole file is planned, which the dialog waits for with Import off. + public bool IsPlanning { get; set; } + + public IReadOnlyList Fields { get; private set; } = []; + + public IReadOnlyList Mapping => _mapping; + + public CsvImportState State + { + get + { + if (IsReading || (Preview is null && ReadError is null)) + { + return CsvImportState.Reading; + } + + if (Preview is not { } preview) + { + return CsvImportState.Failed; + } + + if (preview.Rows.Count == 0) + { + return CsvImportState.NoRows; + } + + return _mapping.Any(mapped => mapped is not null) ? CsvImportState.Ready : CsvImportState.NothingMapped; + } + } + + public bool CanImport => State == CsvImportState.Ready && !IsPlanning; + + public CsvPreviewSummary? Summary => Preview is { } preview + ? new CsvPreviewSummary(preview.Headers.Count, preview.Rows.Count, preview.Truncated) + : null; + + // A .tsv is tab separated by its name; any other file starts as comma separated. + public static CsvDelimiter DelimiterFor(string filePath) => + string.Equals(Path.GetExtension(filePath), ".tsv", StringComparison.OrdinalIgnoreCase) + ? CsvDelimiter.Tab + : CsvDelimiter.Comma; + + // The file names the fields, so another delimiter or header choice reads it again. The number names this read. + public int Read(CsvDelimiter delimiter, bool hasHeader) + { + Options = Options with { Delimiter = delimiter, HasHeader = hasHeader }; + IsReading = true; + return ++_read; + } + + // False when a later read replaced this one. Suggested has a field per column, as the core suggests them. + public bool Show(int read, CsvPreview preview, IReadOnlyList suggested) + { + ArgumentNullException.ThrowIfNull(preview); + ArgumentNullException.ThrowIfNull(suggested); + if (read != _read) + { + return false; + } + + IsReading = false; + Preview = preview; + ReadError = null; + IReadOnlyList first = preview.Rows.Count > 0 ? preview.Rows[0] : []; + Fields = [.. preview.Headers.Select((header, index) => new CsvField( + index, + string.IsNullOrWhiteSpace(header) ? null : Clip(header), + index < first.Count && first[index].Length > 0 ? Clip(first[index]) : null))]; + for (var column = 0; column < _mapping.Length; column++) + { + Map(column, column < suggested.Count ? suggested[column] : null); + } + + return true; + } + + public bool Fail(int read, CoreError error) + { + ArgumentNullException.ThrowIfNull(error); + if (read != _read) + { + return false; + } + + IsReading = false; + Preview = null; + ReadError = error; + Fields = []; + Array.Clear(_mapping); + return true; + } + + // It decides what a field means, not how the file splits, so the preview and the mapping stand. + public void SetNullText(string text) => Options = Options with { NullText = text ?? string.Empty }; + + // A column the server fills takes no field, and a field the file lacks is none. + public void Map(int column, int? field) + { + ArgumentOutOfRangeException.ThrowIfNegative(column); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(column, _mapping.Length); + _mapping[column] = Columns[column].ServerFilled || field is not { } index || index < 0 || index >= Fields.Count + ? null + : index; + } + + // The dialog lists Skip first, then field n at n + 1. + public int Choice(int column) => _mapping[column] is { } field ? field + 1 : 0; + + public void Choose(int column, int choice) => Map(column, choice > 0 ? choice - 1 : null); + + public CsvColumnLine Line(int column) + { + var info = Columns[column]; + var field = _mapping[column]; + var note = info.ServerFilled ? CsvColumnNote.ServerFilled + : field is not null ? CsvColumnNote.Samples + : info.HasDefault ? CsvColumnNote.UsesDefault + : CsvColumnNote.LeftOut; + return new CsvColumnLine(info, field, note, field is { } index ? Samples(index) : []); + } + + // One line, cut short, so a value fits a list item. + public static string Clip(string text) + { + ArgumentNullException.ThrowIfNull(text); + var cut = text.Length > SampleLength; + var head = cut ? Cut(text, SampleLength) : text; + var line = new string(head.Select(c => char.IsControl(c) ? ' ' : c).ToArray()); + return cut ? line + "..." : line; + } + + // Whole statements while they fit, and always the first; one cut short ends in an ellipsis, not a semicolon. + public static CsvImportReview Review(IReadOnlyList statements, int length = ReviewLength) + { + ArgumentNullException.ThrowIfNull(statements); + ArgumentOutOfRangeException.ThrowIfLessThan(length, 1); + var text = new StringBuilder(); + var shown = 0; + foreach (var statement in statements) + { + if (shown > 0) + { + if (text.Length + 2 + statement.Length + 1 > length) + { + break; + } + + text.Append("\n\n"); + } + + shown++; + if (statement.Length + 1 > length) + { + text.Append(Cut(statement, length)).Append("..."); + break; + } + + text.Append(statement).Append(';'); + } + + return new CsvImportReview(text.ToString(), shown); + } + + private IReadOnlyList Samples(int field) => + Preview is not { } preview + ? [] + : [.. preview.Rows + .Where(row => field < row.Count) + .Take(SampleCount) + .Select(row => row[field] == Options.NullText ? null : Clip(row[field]))]; + + // Never between the halves of a surrogate pair. + private static string Cut(string text, int length) => + text[..(char.IsHighSurrogate(text[length - 1]) ? length - 1 : length)]; +} diff --git a/windows/src/TablePro.App.Model/HistoryList.cs b/windows/src/TablePro.App.Model/HistoryList.cs index 27d22d01dc..b8cb895645 100644 --- a/windows/src/TablePro.App.Model/HistoryList.cs +++ b/windows/src/TablePro.App.Model/HistoryList.cs @@ -15,6 +15,8 @@ Task SearchAsync( Task DeleteAsync(IReadOnlyList ids, CancellationToken cancellationToken); Task ClearAsync(CancellationToken cancellationToken); + + Task SetPinnedAsync(long id, bool pinned); } public sealed class CoreHistoryStore(QueryHistory history) : IHistoryStore @@ -31,6 +33,8 @@ public Task DeleteAsync(IReadOnlyList ids, CancellationToken cancellationT history.DeleteAsync(ids, cancellationToken); public Task ClearAsync(CancellationToken cancellationToken) => history.ClearAsync(cancellationToken); + + public Task SetPinnedAsync(long id, bool pinned) => history.SetPinnedAsync(id, pinned); } // One connection's runs, a page at a time in the store's order. A failure lands in Failure and is never thrown. @@ -105,6 +109,24 @@ public async Task DeleteAsync(HistoryEntry entry) OnChanged(); } + // Pinned runs come first, so the list is read again in the store's order. + public async Task SetPinnedAsync(HistoryEntry entry, bool pinned) + { + ArgumentNullException.ThrowIfNull(entry); + try + { + await _store.SetPinnedAsync(entry.Id, pinned).ConfigureAwait(true); + } + catch (TableProException exception) + { + Failure = exception.Error; + OnChanged(); + return; + } + + await RefreshAsync().ConfigureAwait(true); + } + // The core's store clears every connection's runs, not only this list's. public async Task ClearAsync() { diff --git a/windows/src/TablePro.App.Model/SavedQueryText.cs b/windows/src/TablePro.App.Model/SavedQueryText.cs new file mode 100644 index 0000000000..cb7678bd7d --- /dev/null +++ b/windows/src/TablePro.App.Model/SavedQueryText.cs @@ -0,0 +1,85 @@ +namespace TablePro.App.Model; + +public enum SavedQueryInsertKind +{ + NewTab, + Replace, + Append, +} + +// Text is what goes in: the whole tab for NewTab and Replace, what follows the editor's end for Append. +public readonly record struct SavedQueryInsertion(SavedQueryInsertKind Kind, string Text); + +public static class SavedQueryText +{ + public const int NameLength = 50; + + // As macOS names one: the first comment's text, else the first line, cut to 50 characters. + public static string AutoName(string sql, string untitled) + { + ArgumentNullException.ThrowIfNull(sql); + ArgumentNullException.ThrowIfNull(untitled); + var rest = sql.AsSpan(); + while (!rest.IsEmpty) + { + var end = rest.IndexOfAny('\r', '\n'); + var line = (end < 0 ? rest : rest[..end]).Trim(); + rest = end < 0 ? ReadOnlySpan.Empty : rest[(end + 1)..]; + if (line.StartsWith("--", StringComparison.Ordinal)) + { + var comment = line[2..].Trim(); + if (!comment.IsEmpty) + { + return Cut(comment); + } + } + else if (!line.IsEmpty) + { + return Cut(line); + } + } + + return untitled; + } + + public static string FirstLine(string sql) + { + ArgumentNullException.ThrowIfNull(sql); + foreach (var line in sql.AsSpan().EnumerateLines()) + { + var trimmed = line.Trim(); + if (!trimmed.IsEmpty) + { + return trimmed.ToString(); + } + } + + return string.Empty; + } + + // Null editorText: no query tab is shown. A blank editor takes the query, one with text gets it after a blank line. + public static SavedQueryInsertion Insertion(string? editorText, string sql) + { + ArgumentNullException.ThrowIfNull(sql); + if (editorText is null) + { + return new SavedQueryInsertion(SavedQueryInsertKind.NewTab, sql); + } + + return string.IsNullOrWhiteSpace(editorText) + ? new SavedQueryInsertion(SavedQueryInsertKind.Replace, sql) + : new SavedQueryInsertion(SavedQueryInsertKind.Append, "\n\n" + sql); + } + + private static string Cut(ReadOnlySpan line) + { + var length = Math.Min(NameLength, line.Length); + // Half a surrogate pair is no character, and the core keeps names as UTF-8. + if (length < line.Length && char.IsHighSurrogate(line[length - 1])) + { + length--; + } + + return line[..length].ToString(); + } +} diff --git a/windows/src/TablePro.App.Model/SavedQueryTree.cs b/windows/src/TablePro.App.Model/SavedQueryTree.cs new file mode 100644 index 0000000000..662fb427fb --- /dev/null +++ b/windows/src/TablePro.App.Model/SavedQueryTree.cs @@ -0,0 +1,105 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// A folder and a query can share an id, so a row holds one or the other. +public sealed class SavedQueryNode +{ + public SavedQueryNode(SavedQueryFolder folder) + { + ArgumentNullException.ThrowIfNull(folder); + Folder = folder; + Name = folder.Name; + } + + public SavedQueryNode(SavedQuery query) + { + ArgumentNullException.ThrowIfNull(query); + Query = query; + Name = query.Name; + } + + public SavedQueryFolder? Folder { get; } + + public SavedQuery? Query { get; } + + public string Name { get; } + + public List Children { get; } = []; +} + +// Path names every folder above it too, so two folders of one name in different places tell apart. +public sealed record SavedQueryFolderChoice(long Id, string Name, string Path, int Depth); + +public static class SavedQueryTree +{ + public const string PathSeparator = " / "; + + // Each level lists its folders, then its queries, each in the order the user gave them. + public static IReadOnlyList Build(SavedQueryList list) + { + ArgumentNullException.ThrowIfNull(list); + var known = list.Folders.Select(folder => folder.Id).ToHashSet(); + // A place the list does not hold shows at the top level rather than nowhere. + long? Place(long? folderId) => folderId is { } id && known.Contains(id) ? id : null; + var folders = list.Folders.ToLookup(folder => Place(folder.ParentId)); + var queries = list.Queries.ToLookup(query => Place(query.FolderId)); + + List Level(long? parent) + { + var level = new List(); + foreach (var folder in folders[parent].OrderBy(folder => folder.Order)) + { + var node = new SavedQueryNode(folder); + node.Children.AddRange(Level(folder.Id)); + level.Add(node); + } + + level.AddRange(queries[parent].OrderBy(query => query.Order).Select(query => new SavedQueryNode(query))); + return level; + } + + return Level(null); + } + + // In tree order, for the folder picker and the Move to menu. + public static IReadOnlyList Folders(SavedQueryList list) + { + ArgumentNullException.ThrowIfNull(list); + var choices = new List(); + + void Walk(IEnumerable nodes, string? above, int depth) + { + foreach (var node in nodes) + { + if (node.Folder is not { } folder) + { + continue; + } + + var path = above is null ? folder.Name : above + PathSeparator + folder.Name; + choices.Add(new SavedQueryFolderChoice(folder.Id, folder.Name, path, depth)); + Walk(node.Children, path, depth + 1); + } + } + + Walk(Build(list), null, 0); + return choices; + } + + // The folder and every folder above it, so the pane can open the way down to a query put there. + public static IReadOnlyList FolderAndAncestors(long folderId, SavedQueryList list) + { + ArgumentNullException.ThrowIfNull(list); + var parents = list.Folders.ToDictionary(folder => folder.Id, folder => folder.ParentId); + var chain = new List(); + long? at = folderId; + while (at is { } id && parents.TryGetValue(id, out var parent) && !chain.Contains(id)) + { + chain.Add(id); + at = parent; + } + + return chain; + } +} diff --git a/windows/src/TablePro.App/MainWindow.xaml b/windows/src/TablePro.App/MainWindow.xaml index 954de63c53..a315fe258c 100644 --- a/windows/src/TablePro.App/MainWindow.xaml +++ b/windows/src/TablePro.App/MainWindow.xaml @@ -39,6 +39,7 @@ + @@ -149,6 +150,7 @@ + @@ -185,6 +187,11 @@ + + + + + diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index b0dd7e6b74..f0b7b53340 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -238,6 +238,19 @@ public async Task ImportAsync() } } + public async Task ExportConnectionsAsync() + { + if (_home is null) + { + _primary.Activate(); + await _primary.ExportConnectionsAsync(); + return; + } + + ShowHome(); + await _home.ExportConnectionsAsync(); + } + public async Task OpenSampleAsync() { if (_home is null) @@ -1274,6 +1287,9 @@ private void UpdateCommands() MenuFilterObjects.IsEnabled = workspace is not null; MenuShowHistory.IsEnabled = workspace is not null; MenuShowHistory.IsChecked = workspace?.HistoryVisible ?? false; + MenuShowSavedQueries.IsEnabled = workspace?.CanShowSavedQueries ?? false; + MenuShowSavedQueries.IsChecked = workspace?.SavedQueriesVisible ?? false; + MenuSaveQuery.IsEnabled = workspace?.CanSaveQuery ?? false; MenuExportResults.IsEnabled = workspace?.CanExport ?? false; MenuShareResult.IsEnabled = workspace?.CanShareResult ?? false; MenuShareQuery.IsEnabled = workspace?.CanShareQuery ?? false; @@ -1311,6 +1327,8 @@ private void UpdateCommands() private async void OnImport(object sender, RoutedEventArgs e) => await ImportAsync(); + private async void OnExportConnections(object sender, RoutedEventArgs e) => await ExportConnectionsAsync(); + private void OnNewQueryTab(object sender, RoutedEventArgs e) => Workspace?.NewQueryTab(); private void OnCloseTab(object sender, RoutedEventArgs e) => Workspace?.CloseActiveTab(); @@ -1418,6 +1436,24 @@ private async void OnToggleHistory(object sender, RoutedEventArgs e) UpdateCommands(); } + private async void OnToggleSavedQueries(object sender, RoutedEventArgs e) + { + if (Workspace is { } workspace) + { + await workspace.ToggleSavedQueriesAsync(); + } + + UpdateCommands(); + } + + private async void OnSaveQuery(object sender, RoutedEventArgs e) + { + if (Workspace is { } workspace) + { + await workspace.SaveQueryAsync(); + } + } + private async void OnExportResults(object sender, RoutedEventArgs e) { if (Workspace is { } workspace) diff --git a/windows/src/TablePro.App/Services/Workbench.cs b/windows/src/TablePro.App/Services/Workbench.cs index f39ae995ea..4696a62f5a 100644 --- a/windows/src/TablePro.App/Services/Workbench.cs +++ b/windows/src/TablePro.App/Services/Workbench.cs @@ -9,6 +9,7 @@ internal sealed class Workbench : IDisposable private readonly CancellationTokenSource _lifetime = new(); private bool _settingsUnsaved; private Task? _history; + private Task? _savedQueries; private Task? _account; private CancellationTokenSource? _signingIn; @@ -197,6 +198,35 @@ private async Task WatchAccountAsync(TableProAccount account) } } + // Kept in the history's database, so null when the history cannot open. + public Task GetSavedQueriesAsync() => _savedQueries ??= OpenSavedQueriesAsync(); + + private async Task OpenSavedQueriesAsync() + { + if (await GetHistoryAsync().ConfigureAwait(true) is not { } history) + { + return null; + } + + try + { + return history.OpenSavedQueries(); + } + catch (TableProException) + { + return null; + } + } + + // A deleted connection's saved queries, folders and favourites go with it, as on Linux; none are kept without a store. + public async Task ForgetSavedQueriesAsync(Guid connectionId) + { + if (await GetSavedQueriesAsync().ConfigureAwait(true) is { } savedQueries) + { + await savedQueries.DeleteForConnectionAsync(connectionId).ConfigureAwait(true); + } + } + // The Chinook sample is copied out of the app once, so edits to it stay. public async Task InstallSampleAsync() { @@ -227,6 +257,11 @@ public void Dispose() { _lifetime.Cancel(); _signingIn?.Cancel(); + if (_savedQueries is { IsCompletedSuccessfully: true, Result: { } savedQueries }) + { + savedQueries.Dispose(); + } + if (_history is { IsCompletedSuccessfully: true, Result: { } history }) { history.Dispose(); diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index bef28b743a..e3a7b12356 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -868,7 +868,7 @@ Delete {0}? - The connection and its saved passwords leave this PC. This can't be undone. + The connection, its saved passwords and its saved queries leave this PC. This can't be undone. Delete the group {0}? @@ -1231,7 +1231,7 @@ Delete {0} connections? - The connections and their saved passwords leave this PC. This can't be undone. + The connections, their saved passwords and their saved queries leave this PC. This can't be undone. Add to Favorites @@ -3219,4 +3219,385 @@ New fingerprint: {2} The rows are still arriving. Share them once the query finishes. + + Duplicate + + + {0} (Copy) + + + {0} (Copy {1}) + + + The connection couldn't be duplicated. {0} + + + Export + + + Export the connections to a file, without their passwords + + + Export connections... + + + TablePro connections + + + TablePro connections + + + Exported {0} connections. Passwords are not in the file. + + + Exported 1 connection. Its password is not in the file. + + + The connections couldn't be exported. {0} + + + Another saved query of this connection has that name. + + + Enter a name. + + + It's too large to save. + + + It's gone. It may have been deleted. + + + Another folder in the same place has that name. + + + A folder name can't hold control characters. + + + A folder can't go inside itself. + + + Save query... + + + Q + + + Show saved queries + + + S + + + Saved queries commands + + + Saved queries + + + New folder + + + New folder + + + Close saved queries + + + Close saved queries + + + Queries saved for this connection + + + No saved queries. Save one from a query tab with Query > Save query. + + + Saved queries are unavailable + + + The history database couldn't be opened, so queries can't be saved. + + + The saved queries couldn't be read + + + The change couldn't be saved + + + Insert in editor + + + Open in new tab + + + Copy query + + + Move to + + + Top level + + + New subfolder... + + + Delete folder + + + Delete saved query? + + + "{0}" will be deleted. + + + Delete folder? + + + The folders inside "{0}" are deleted too, and every query it holds moves to the top level. + + + New folder + + + New subfolder + + + Rename folder + + + New folder + + + Save query + + + Edit saved query + + + Save + + + Name + + + Folder + + + None + + + Query + + + Untitled + + + A saved query named {0} already exists. Replace it? + + + Replace + + + Save query... + + + Pin + + + Unpin + + + Pinned + + + Import CSV... + + + Import into {0} + + + From {0} + + + Import + + + Delimiter + + + Comma + + + Semicolon + + + Tab + + + Pipe + + + First row is a header + + + NULL text + + + An empty field + + + Reading the file... + + + Reading the whole file... + + + 1 field + + + {0:N0} fields + + + 1 row + + + {0:N0} rows + + + {0}, {1}. + + + {0}. Showing the first {1}; the whole file is imported. + + + The file has no rows to import. + + + Every column is set to Skip. Pick a field for at least one column to import. + + + Columns + + + Skip + + + Field {0} + + + {0} ({1}) + + + The database fills this column + + + Uses the column's own default + + + Left out of the import + + + No values in the file + + + Line {0}, column {1}: "{2}" {3} + + + The column can't hold this value. + + + Import 1 row into {0}? + + + Import {0:N0} rows into {1}? + + + The import runs 1 statement. + + + The import runs {0:N0} statements. + + + The import runs {0:N0} statements; the first is shown. + + + The import runs {0:N0} statements; the first {1:N0} are shown. + + + Imported 1 row into {0}. + + + Imported {0:N0} rows into {1}. + + + Line {0} + + + Lines {0} to {1} + + + Some lines + + + {0} could not be written, so the import was rolled back and no rows were added. + + + No rows were imported. + + + {0} could not be written. The table has no transaction to undo the import. + + + {0} could not be written. The table has no transaction to undo the import, so the row written before stays in it. + + + {0} could not be written. The table has no transaction to undo the import, so the {1:N0} rows written before stay in it. + + + Some of those lines may be in it too. + + + The import did not finish, so the table may hold some of the rows. Refresh it to see what is there. + + + Import stopped. The table may hold some of the rows. + + + That file could not be read. + + + That file is too large to import in one go. An import reads up to 64 MB. + + + The file isn't UTF-8 text. Save it as UTF-8 and import it again. + + + The file couldn't be read as CSV. + + + The file has no columns. + + + A line has more than 4,096 fields, more than any table holds. Check the delimiter. + + + A column is set to a field the file doesn't have. Check the mapping and import again. + + + The table has no columns to import into. + + + Safe Mode asks before this import. Import again to answer it. + + + The connection's Safe Mode changed. Import again to see what it asks. + + + Nothing is ready to import. Import again. + + + Importing the file into {1}... + diff --git a/windows/src/TablePro.App/Views/HistoryPane.xaml b/windows/src/TablePro.App/Views/HistoryPane.xaml index 8bc621974c..8703ff39b2 100644 --- a/windows/src/TablePro.App/Views/HistoryPane.xaml +++ b/windows/src/TablePro.App/Views/HistoryPane.xaml @@ -66,6 +66,7 @@ + @@ -83,9 +84,18 @@ Text="{x:Bind FirstLine}" TextTrimming="CharacterEllipsis" TextWrapping="NoWrap" /> + ? OpenRequested; + // Save query...: the workspace asks its name and folder. + public event EventHandler? SaveRequested; + public event EventHandler? CloseRequested; + // Saved queries belong to a saved connection, which a file opened without saving is not. + public bool CanSaveQuery { get; set; } + public Task RefreshAsync() => _list?.RefreshAsync() ?? Task.CompletedTask; // A pane shown for the first time joins the tree only on the next layout, and an unloaded box takes no focus. @@ -182,10 +188,19 @@ private void OnEntryContextRequested(UIElement sender, ContextRequestedEventArgs open.Click += (_, _) => OpenRequested?.Invoke(this, item.Entry.Sql); var copy = MenuItem("HistoryMenuCopy", Symbol.Copy); copy.Click += (_, _) => WorkspaceView.CopyText(item.Entry.Sql); + var save = MenuItem("HistoryMenuSaveQuery", Symbol.Save); + save.IsEnabled = CanSaveQuery; + save.Click += (_, _) => SaveRequested?.Invoke(this, item.Entry.Sql); + var pinned = item.Entry.Pinned; + var pin = pinned ? MenuItem("HistoryMenuUnpin", Symbol.UnPin) : MenuItem("HistoryMenuPin", Symbol.Pin); + pin.Click += async (_, _) => await list.SetPinnedAsync(item.Entry, !pinned).ConfigureAwait(true); var menu = new MenuFlyout(); menu.Items.Add(open); menu.Items.Add(copy); menu.Items.Add(new MenuFlyoutSeparator()); + menu.Items.Add(save); + menu.Items.Add(pin); + menu.Items.Add(new MenuFlyoutSeparator()); menu.Items.Add(delete); if (args.TryGetPosition(container, out var point)) { @@ -197,8 +212,12 @@ private void OnEntryContextRequested(UIElement sender, ContextRequestedEventArgs } } - private static MenuFlyoutItem MenuItem(string text, Symbol icon) => - new() { Text = Strings.Get(text), Icon = new SymbolIcon(icon) }; + private static MenuFlyoutItem MenuItem(string text, Symbol icon) + { + var item = new MenuFlyoutItem { Text = Strings.Get(text), Icon = new SymbolIcon(icon) }; + AutomationProperties.SetAutomationId(item, text); + return item; + } // The row under the pointer, or the focused row, from whichever element inside it raised the event. private static ListViewItem? ContainerAt(object? source) @@ -241,7 +260,10 @@ internal HistoryItemCollection(HistoryList list) internal void Show(IReadOnlyList entries, DateTimeOffset now) { var kept = 0; - while (kept < Count && kept < entries.Count && this[kept].Entry.Id == entries[kept].Id) + while (kept < Count + && kept < entries.Count + && this[kept].Entry.Id == entries[kept].Id + && this[kept].Entry.Pinned == entries[kept].Pinned) { kept++; } @@ -286,7 +308,9 @@ internal HistoryItem(HistoryEntry entry, DateTimeOffset now, bool namesConnectio Glyph = glyph; MarkName = mark; MarkVisibility = glyph.Length > 0 ? Visibility.Visible : Visibility.Collapsed; - AccessibleName = string.Join(", ", new[] { FirstLine, Detail, MarkName }.Where(part => part.Length > 0)); + PinName = entry.Pinned ? Strings.Get("HistoryPinned") : string.Empty; + PinVisibility = entry.Pinned ? Visibility.Visible : Visibility.Collapsed; + AccessibleName = string.Join(", ", new[] { FirstLine, Detail, MarkName, PinName }.Where(part => part.Length > 0)); } public HistoryEntry Entry { get; } @@ -301,6 +325,10 @@ internal HistoryItem(HistoryEntry entry, DateTimeOffset now, bool namesConnectio public Visibility MarkVisibility { get; } + public string PinName { get; } + + public Visibility PinVisibility { get; } + public string AccessibleName { get; } private static string FirstLineOf(string sql) diff --git a/windows/src/TablePro.App/Views/HomeView.xaml b/windows/src/TablePro.App/Views/HomeView.xaml index e716c4c3ab..dd112ffbdf 100644 --- a/windows/src/TablePro.App/Views/HomeView.xaml +++ b/windows/src/TablePro.App/Views/HomeView.xaml @@ -35,6 +35,9 @@ + + + diff --git a/windows/src/TablePro.App/Views/HomeView.xaml.cs b/windows/src/TablePro.App/Views/HomeView.xaml.cs index 43ee91e390..fff624dbef 100644 --- a/windows/src/TablePro.App/Views/HomeView.xaml.cs +++ b/windows/src/TablePro.App/Views/HomeView.xaml.cs @@ -6,6 +6,7 @@ using Microsoft.UI.Xaml.Media; using TablePro.App.Model; using TablePro.App.Services; +using Microsoft.Windows.Storage.Pickers; using TablePro.Interop; using Windows.ApplicationModel.DataTransfer; using Windows.System; @@ -347,6 +348,7 @@ private void OnLibraryContextRequested(UIElement sender, ContextRequestedEventAr { AddItem(menu, "MenuEdit", Symbol.Edit, () => _shell.EditConnection(connection)); AddItem(menu, "MenuRename", Symbol.Rename, () => StartRename(item)); + AddItem(menu, "MenuDuplicate", Symbol.Copy, async () => await DuplicateAsync(connection).ConfigureAwait(true)); } var ids = Ids(targets); @@ -522,6 +524,68 @@ private async Task Write(Func change) _workbench.NotifyLibraryChanged(); } + // As macOS does, the form opens on the copy, which sits right after its original. + private async Task DuplicateAsync(SavedConnection connection) + { + if (connection.Id is not { } id) + { + return; + } + + SavedConnection copy; + try + { + var name = CopyName.For( + connection.Name, + _snapshot.Connections.Select(saved => saved.Name), + Strings.Get("CopyNamePattern"), + Strings.Get("CopyNameNumberedPattern")); + copy = await _workbench.Library.DuplicateAsync(id, name).ConfigureAwait(true); + } + catch (TableProException exception) + { + ShowMessage(Strings.Format("DuplicateFailed", Strings.Error(exception.Error)), InfoBarSeverity.Error); + return; + } + finally + { + _workbench.NotifyLibraryChanged(); + } + + _shell.EditConnection(copy); + } + + // The file is the one Import reads: every connection, group and tag, and no password. + public async Task ExportConnectionsAsync() + { + if (XamlRoot is not { } root) + { + return; + } + + var picker = new FileSavePicker(root.ContentIslandEnvironment.AppWindowId) + { + SuggestedStartLocation = PickerLocationId.DocumentsLibrary, + SuggestedFileName = Strings.Get("ExportConnectionsFileName"), + }; + picker.FileTypeChoices.Add(Strings.Get("ConnectionsFileType"), [".json"]); + var result = await picker.PickSaveFileAsync(); + if (result is null) + { + return; + } + + try + { + var count = await _workbench.Library.ExportAsync(result.Path).ConfigureAwait(true); + ShowMessage(Strings.Format(count == 1 ? "ExportConnectionsDoneOne" : "ExportConnectionsDone", count), InfoBarSeverity.Success); + } + catch (TableProException exception) + { + ShowMessage(Strings.Format("ExportConnectionsFailed", Strings.Error(exception.Error)), InfoBarSeverity.Error); + } + } + private async Task DeleteConnectionsAsync(List connections) { if (connections.Count == 0) @@ -548,6 +612,7 @@ await Write(async () => foreach (var id in Ids(connections)) { await _workbench.Library.DeleteAsync(id).ConfigureAwait(true); + await _workbench.ForgetSavedQueriesAsync(id).ConfigureAwait(true); } }).ConfigureAwait(true); } @@ -945,6 +1010,8 @@ private async Task MoveGroupsAsync(LibraryDrop.MoveGroups drop) private async void OnImport(object sender, RoutedEventArgs e) => await _shell.ImportAsync().ConfigureAwait(true); + private async void OnExportConnections(object sender, RoutedEventArgs e) => await ExportConnectionsAsync().ConfigureAwait(true); + private async void OnSample(object sender, RoutedEventArgs e) => await _shell.OpenSampleAsync().ConfigureAwait(true); private async void OnNewGroup(object sender, RoutedEventArgs e) => await NewGroupAsync(null).ConfigureAwait(true); diff --git a/windows/src/TablePro.App/Views/ImportCsvDialog.cs b/windows/src/TablePro.App/Views/ImportCsvDialog.cs new file mode 100644 index 0000000000..3cfd170848 --- /dev/null +++ b/windows/src/TablePro.App/Views/ImportCsvDialog.cs @@ -0,0 +1,566 @@ +using System.Globalization; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.Windows.Storage.Pickers; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.Interop; + +namespace TablePro.App.Views; + +// Message is worded for the status bar; when TableChanged, a tab showing the table reads its rows again. +internal sealed record CsvImportResult(CsvImportReport Report, string Message) +{ + public bool Succeeded => Report.Ending == CsvImportEnding.Imported; + + public bool TableChanged => Report.TableChanged; +} + +// A CSV file into a table, as the Linux app imports one: the file, its options, then a field for each column. +internal static class ImportCsvDialog +{ + private const double MappingHeight = 320; + private const double FieldWidth = 220; + private const double ScrollBarGutter = 16; + + private static readonly CsvDelimiter[] _delimiters = + [CsvDelimiter.Comma, CsvDelimiter.Semicolon, CsvDelimiter.Tab, CsvDelimiter.Pipe]; + + private static readonly string[] _extensions = [".csv", ".tsv", ".txt"]; + + // Null when cancelled or another dialog holds the window. `importing` hears the row count as the rows go out. + public static async Task RunAsync( + FrameworkElement owner, + DatabaseSession session, + TableName table, + Action? importing = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(session); + ArgumentNullException.ThrowIfNull(table); + if (WindowDialogs.IsOpen(owner.XamlRoot)) + { + return null; + } + + if (session.IsReadOnly) + { + return Ended(table, CsvImportReport.Refused(ReadOnlyRefusal)); + } + + if (await PickFileAsync(owner).ConfigureAwait(true) is not { } path) + { + return null; + } + + CsvImport import; + try + { + import = await session.OpenCsvImportAsync(table, cancellationToken).ConfigureAwait(true); + } + catch (TableProException exception) + { + return Ended(table, CsvImportReport.Refused(exception.Error)); + } + catch (OperationCanceledException) + { + return null; + } + + using (import) + { + var sheet = new Sheet(owner, import, table, path); + if (await sheet.ShowAsync(owner).ConfigureAwait(true) is not { } planned) + { + return null; + } + + var confirmed = planned.Gate == SaveGate.Run; + if (planned.Gate == SaveGate.Confirm) + { + if (!await ConfirmAsync(owner, session.Name, table, planned).ConfigureAwait(true)) + { + return null; + } + + confirmed = true; + } + + importing?.Invoke(planned.Rows); + CsvImportReport report; + try + { + var outcome = await import.RunAsync(confirmed, cancellationToken).ConfigureAwait(true); + report = CsvImportReport.From(outcome); + } + catch (TableProException exception) + { + report = CsvImportReport.Refused(exception.Error); + } + catch (OperationCanceledException) + { + report = CsvImportReport.Stopped; + } + + return Ended(table, report); + } + } + + private static CoreError ReadOnlyRefusal => + new("edit.read_only_connection", ["edit.read_only_connection"], "the connection is read-only", null, null); + + // A style keeps the dialog's own theme, which a brush read from the app's resources in code would not. + private static Style Caption => (Style)Application.Current.Resources["CaptionTextBlockStyle"]; + + private static CsvImportResult Ended(TableName table, CsvImportReport report) => + new(report, Describe(table, report)); + + // As the Linux app words a failure: by the lines of the file the failed statement held. + private static string Describe(TableName table, CsvImportReport report) + { + var error = report.Error is { } failure ? Strings.Error(failure) : null; + var lines = report.Lines switch + { + null => Strings.Get("ImportCsvSomeLines"), + { } span when span.First == span.Last => Strings.Format("ImportCsvLine", span.First), + { } span => Strings.Format("ImportCsvLines", span.First, span.Last), + }; + var range = report.Lines is { } held && held.First != held.Last; + return report.Ending switch + { + CsvImportEnding.Imported => report.Rows == 1 + ? Strings.Format("ImportCsvDoneOne", table.Name) + : Strings.Format("ImportCsvDoneMany", report.Rows, table.Name), + CsvImportEnding.NotWritten when report.Lines is null => + Sentences(Strings.Get("ImportCsvNotWritten"), error), + CsvImportEnding.NotWritten => Sentences(Strings.Format("ImportCsvRolledBack", lines), error), + CsvImportEnding.PartlyWritten => Sentences( + report.Rows switch + { + 0 => Strings.Format("ImportCsvPartlyNone", lines), + 1 => Strings.Format("ImportCsvPartlyOne", lines), + _ => Strings.Format("ImportCsvPartlyMany", lines, report.Rows), + }, + range ? Strings.Get("ImportCsvPartlyRange") : null, + error), + _ when report.Error is null => Strings.Get("ImportCsvStopped"), + _ => Sentences(Strings.Get("ImportCsvUnknown"), error), + }; + } + + private static string Sentences(params string?[] parts) => + string.Join(' ', parts.Where(part => !string.IsNullOrEmpty(part))); + + // The picker belongs to the window the workspace is in, which a tab window has its own of. + private static async Task PickFileAsync(FrameworkElement owner) + { + if (owner.XamlRoot is not { } root) + { + return null; + } + + var picker = new FileOpenPicker(root.ContentIslandEnvironment.AppWindowId) + { + SuggestedStartLocation = PickerLocationId.DocumentsLibrary, + }; + foreach (var extension in _extensions) + { + picker.FileTypeFilter.Add(extension); + } + + var result = await picker.PickSingleFileAsync(); + return result?.Path; + } + + // Safe Mode's question before the rows are sent, with the statements that send them. + private static async Task ConfirmAsync( + FrameworkElement owner, string connection, TableName table, CsvImportCheck.Ready planned) + { + var review = CsvImportForm.Review(planned.Statements); + var count = planned.Statements.Count; + var content = new StackPanel { Spacing = 12 }; + content.Children.Add(Named( + new TextBlock { Text = Strings.Format("SaveReviewRunsOn", connection), TextWrapping = TextWrapping.Wrap }, + "ImportReviewRunsOn")); + var counted = (count, review.Shown) switch + { + (1, _) => Strings.Get("ImportCsvReviewOne"), + var (all, shown) when shown == all => Strings.Format("ImportCsvReviewMany", all), + (_, 1) => Strings.Format("ImportCsvReviewFirstShown", count), + _ => Strings.Format("ImportCsvReviewSomeShown", count, review.Shown), + }; + content.Children.Add(Named( + new TextBlock { Text = counted, TextWrapping = TextWrapping.Wrap }, + "ImportReviewCount")); + content.Children.Add(Named( + new TextBlock + { + Text = review.Text, + FontFamily = new FontFamily("Cascadia Mono, Consolas, Courier New"), + TextWrapping = TextWrapping.Wrap, + IsTextSelectionEnabled = true, + }, + "ImportReviewStatements")); + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = planned.Rows == 1 + ? Strings.Format("ImportCsvReviewTitleOne", table.Name) + : Strings.Format("ImportCsvReviewTitleMany", planned.Rows, table.Name), + Content = new ScrollViewer { Content = content, MaxHeight = 480 }, + PrimaryButtonText = Strings.Get("ImportCsvAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }; + return await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true) == ContentDialogResult.Primary; + } + + private static T Named(T element, string automationId, string? name = null) + where T : UIElement + { + AutomationProperties.SetAutomationId(element, automationId); + if (name is not null) + { + AutomationProperties.SetName(element, name); + } + + return element; + } + + // The mapping dialog over one import; it stays open on a file it cannot read or a row a column refuses. + private sealed class Sheet + { + private readonly CsvImport _import; + private readonly CsvImportForm _form; + private readonly ContentDialog _dialog; + private readonly ComboBox _delimiter = new() { MinWidth = 160 }; + private readonly CheckBox _header = new() { IsChecked = true }; + private readonly TextBox _nullText = new() { MinWidth = 200, IsSpellCheckEnabled = false }; + private readonly TextBlock _summary = new() { TextWrapping = TextWrapping.Wrap }; + private readonly InfoBar _message = new() { IsClosable = false, Severity = InfoBarSeverity.Error }; + private readonly List<(ComboBox Fields, TextBlock Note)> _rows = []; + + // The previews and the plan run on the import, which the caller disposes once the dialog is done. + private readonly List _pending = []; + private CsvImportCheck.Ready? _planned; + private bool _filling; + + public Sheet(FrameworkElement owner, CsvImport import, TableName table, string path) + { + _import = import; + _form = new CsvImportForm(import.Columns, path); + _dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = Strings.Format("ImportCsvTitle", table.Name), + Content = Layout(), + PrimaryButtonText = Strings.Get("ImportCsvAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Primary, + IsPrimaryButtonEnabled = false, + }; + _dialog.PrimaryButtonClick += OnImport; + } + + // The plan when Import closed the dialog with one Safe Mode lets run, else null. + public async Task ShowAsync(FrameworkElement owner) + { + Read(); + var shown = await WindowDialogs.ShowAsync(_dialog, owner).ConfigureAwait(true); + await Task.WhenAll(_pending).ConfigureAwait(true); + return shown == ContentDialogResult.Primary ? _planned : null; + } + + private StackPanel Layout() + { + var root = new StackPanel { Spacing = 12 }; + root.Children.Add(Named( + new TextBlock + { + Text = Strings.Format("ImportCsvFile", _form.FileName), + TextWrapping = TextWrapping.Wrap, + }, + "ImportCsvFile")); + + _delimiter.Header = Strings.Get("ImportCsvDelimiter"); + foreach (var delimiter in _delimiters) + { + _delimiter.Items.Add(Strings.Get("ImportCsvDelimiter" + delimiter)); + } + + _delimiter.SelectedIndex = Array.IndexOf(_delimiters, _form.Options.Delimiter); + Named(_delimiter, "ImportCsvDelimiter", Strings.Get("ImportCsvDelimiter")); + _delimiter.SelectionChanged += (_, _) => Read(); + + _nullText.Header = Strings.Get("ImportCsvNullText"); + _nullText.PlaceholderText = Strings.Get("ImportCsvNullTextPlaceholder"); + Named(_nullText, "ImportCsvNullText", Strings.Get("ImportCsvNullText")); + _nullText.TextChanged += (_, _) => + { + _form.SetNullText(_nullText.Text); + Redraw(); + }; + + var options = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; + options.Children.Add(_delimiter); + options.Children.Add(_nullText); + root.Children.Add(options); + + _header.Content = Strings.Get("ImportCsvHasHeader"); + Named(_header, "ImportCsvHasHeader", Strings.Get("ImportCsvHasHeader")); + _header.Checked += (_, _) => Read(); + _header.Unchecked += (_, _) => Read(); + root.Children.Add(_header); + + root.Children.Add(Named(_summary, "ImportCsvSummary")); + root.Children.Add(Named(_message, "ImportCsvMessage")); + root.Children.Add(Named( + new TextBlock + { + Text = Strings.Get("ImportCsvColumns"), + Style = (Style)Application.Current.Resources["BodyStrongTextBlockStyle"], + }, + "ImportCsvColumns")); + + var list = new StackPanel { Spacing = 12, Padding = new Thickness(0, 0, ScrollBarGutter, 0) }; + for (var column = 0; column < _form.Columns.Count; column++) + { + list.Children.Add(Row(column)); + } + + // A wide table scrolls here, and the options above stay in view. + root.Children.Add(Named( + new ScrollViewer { Content = list, MaxHeight = MappingHeight }, + "ImportCsvMapping", + Strings.Get("ImportCsvColumns"))); + return root; + } + + private Grid Row(int column) + { + var info = _form.Columns[column]; + var id = column.ToString(CultureInfo.InvariantCulture); + var row = new Grid { ColumnSpacing = 12 }; + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + + var text = new StackPanel(); + text.Children.Add(Named( + new TextBlock { Text = info.Name, TextTrimming = TextTrimming.CharacterEllipsis }, + "ImportCsvColumn" + id)); + text.Children.Add(Named( + new TextBlock { Text = info.TypeName, Style = Caption, TextTrimming = TextTrimming.CharacterEllipsis }, + "ImportCsvType" + id)); + var note = Named(new TextBlock { Style = Caption, TextWrapping = TextWrapping.Wrap }, "ImportCsvNote" + id); + text.Children.Add(note); + row.Children.Add(text); + + var fields = Named( + new ComboBox { Width = FieldWidth, VerticalAlignment = VerticalAlignment.Center }, + "ImportCsvField" + id, + info.Name); + fields.SelectionChanged += (_, _) => + { + if (_filling) + { + return; + } + + _form.Choose(column, fields.SelectedIndex); + _message.IsOpen = false; + Redraw(); + }; + Grid.SetColumn(fields, 1); + row.Children.Add(fields); + _rows.Add((fields, note)); + return row; + } + + private void Read() + { + var read = _form.Read(_delimiters[Math.Max(0, _delimiter.SelectedIndex)], _header.IsChecked == true); + _message.IsOpen = false; + Redraw(); + _pending.RemoveAll(task => task.IsCompleted); + _pending.Add(ReadAsync(read, _form.Options)); + } + + private async Task ReadAsync(int read, CsvOptions options) + { + try + { + var preview = await _import.PreviewAsync(_form.FilePath, options).ConfigureAwait(true); + if (_form.Show(read, preview, _import.SuggestMapping(preview.Headers))) + { + Fill(); + } + } + catch (TableProException exception) + { + if (_form.Fail(read, exception.Error)) + { + Fill(); + } + } + } + + // One list for every column's box: each keeps its own selection, and a wide file is held once. + private void Fill() + { + List choices = [Strings.Get("ImportCsvSkip"), .. _form.Fields.Select(FieldText)]; + _filling = true; + try + { + for (var column = 0; column < _rows.Count; column++) + { + var fields = _rows[column].Fields; + fields.ItemsSource = choices; + fields.SelectedIndex = _form.Choice(column); + } + } + finally + { + _filling = false; + } + + if (_form.ReadError is { } error) + { + ShowMessage(Strings.Error(error)); + } + + Redraw(); + } + + private void Redraw() + { + var editable = !_form.IsPlanning; + for (var column = 0; column < _rows.Count; column++) + { + var (fields, note) = _rows[column]; + var line = _form.Line(column); + fields.IsEnabled = editable && !line.Column.ServerFilled; + note.Text = NoteText(line); + } + + _delimiter.IsEnabled = editable; + _header.IsEnabled = editable; + _nullText.IsEnabled = editable; + _summary.Text = _form.IsPlanning ? Strings.Get("ImportCsvPlanning") : _form.State switch + { + CsvImportState.Reading => Strings.Get("ImportCsvReading"), + CsvImportState.NoRows => Strings.Get("ImportCsvNoRows"), + CsvImportState.NothingMapped => Strings.Get("ImportCsvNothingMapped"), + CsvImportState.Ready when _form.Summary is { } summary => SummaryText(summary), + _ => string.Empty, + }; + _summary.Visibility = _summary.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + _dialog.IsPrimaryButtonEnabled = _form.CanImport; + } + + private async void OnImport(ContentDialog sender, ContentDialogButtonClickEventArgs args) + { + var deferral = args.GetDeferral(); + try + { + var planning = PlanAsync(); + _pending.Add(planning); + args.Cancel = !await planning.ConfigureAwait(true); + } + finally + { + deferral.Complete(); + } + } + + // Reads the whole file; true closes the dialog with the plan, anything else stays to be fixed here. + private async Task PlanAsync() + { + if (!_form.CanImport) + { + return false; + } + + _form.IsPlanning = true; + _message.IsOpen = false; + Redraw(); + try + { + switch (await _import.PlanAsync(_form.FilePath, _form.Options, _form.Mapping).ConfigureAwait(true)) + { + case CsvImportCheck.Ready { Gate: SaveGate.Refuse }: + ShowMessage(Strings.Get("Error_edit_read_only_connection")); + return false; + case CsvImportCheck.Ready ready: + _planned = ready; + return true; + case CsvImportCheck.RowRefused refused: + ShowMessage(FaultText(refused.Fault)); + return false; + default: + ShowMessage(Strings.Get("ImportCsvNoRows")); + return false; + } + } + catch (TableProException exception) + { + ShowMessage(Strings.Error(exception.Error)); + return false; + } + finally + { + _form.IsPlanning = false; + Redraw(); + } + } + + private void ShowMessage(string text) + { + _message.Message = text; + AutomationProperties.SetName(_message, text); + // Narrator reads an InfoBar when it opens, not when its text changes. + _message.IsOpen = false; + _message.IsOpen = true; + } + + private static string FieldText(CsvField field) + { + var label = field.Header ?? Strings.Format("ImportCsvFieldNumber", field.Index + 1); + return field.Sample is { } sample ? Strings.Format("ImportCsvFieldSample", label, sample) : label; + } + + private static string NoteText(CsvColumnLine line) => line.Note switch + { + CsvColumnNote.ServerFilled => Strings.Get("ImportCsvServerFilled"), + CsvColumnNote.UsesDefault => Strings.Get("ImportCsvUsesDefault"), + CsvColumnNote.LeftOut => Strings.Get("ImportCsvLeftOut"), + _ when line.Samples.Count == 0 => Strings.Get("ImportCsvNoValues"), + _ => string.Join(" · ", line.Samples.Select(sample => sample ?? Strings.Get("GridMenuNull"))), + }; + + private static string SummaryText(CsvPreviewSummary summary) + { + var fields = summary.Fields == 1 + ? Strings.Get("ImportCsvFieldsOne") + : Strings.Format("ImportCsvFieldsMany", summary.Fields); + var rows = summary.Rows == 1 + ? Strings.Get("ImportCsvRowsOne") + : Strings.Format("ImportCsvRowsMany", summary.Rows); + return Strings.Format(summary.Truncated ? "ImportCsvSummaryTruncated" : "ImportCsvSummary", fields, rows); + } + + // The reason is the code a cell edit refused alike has, which the app already words. + private static string FaultText(CsvRowFault fault) + { + var reason = Strings.Get("Error_" + fault.Reason.Replace('.', '_')); + return Strings.Format( + "ImportCsvRowFault", + fault.Line, + fault.Column, + CsvImportForm.Clip(fault.Text), + reason.Length > 0 ? reason : Strings.Get("ImportCsvRowFaultUnknown")); + } + } +} diff --git a/windows/src/TablePro.App/Views/SaveQueryDialog.cs b/windows/src/TablePro.App/Views/SaveQueryDialog.cs new file mode 100644 index 0000000000..ca8d5015a7 --- /dev/null +++ b/windows/src/TablePro.App/Views/SaveQueryDialog.cs @@ -0,0 +1,409 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.Editor.Model; +using TablePro.Interop; + +namespace TablePro.App.Views; + +// Where a saved query landed, so the pane can open its folder. +internal sealed record SavedQueryPlace(long Id, long? FolderId); + +// A saved query's name, folder and, when editing, its text, asked in a dialog; the core keeps them. +internal static class SaveQueryDialog +{ + // Null when cancelled, or when another dialog holds the window. + public static async Task SaveAsync( + FrameworkElement owner, + SavedQueries store, + Guid connectionId, + string connectionName, + string sql) + { + ArgumentNullException.ThrowIfNull(store); + var draft = new Draft(null, SavedQueryText.AutoName(sql, Strings.Get("SavedQueryUntitled")), sql, null); + var folders = await FoldersAsync(store, connectionId).ConfigureAwait(true); + while (true) + { + var answer = await ShowAsync( + owner, + Strings.Get("SaveQueryTitle"), + draft, + folders, + editsSql: false, + () => CommitAsync(store, connectionId, connectionName, draft, replace: false)) + .ConfigureAwait(true); + if (answer == Answer.Saved) + { + return draft.Place; + } + + if (answer == Answer.Cancelled) + { + return null; + } + + // WinUI shows one dialog at a time, so the question comes once the first has closed; Cancel goes back to it. + if (!await ConfirmReplaceAsync(owner, draft.Name).ConfigureAwait(true)) + { + continue; + } + + try + { + if (await CommitAsync(store, connectionId, connectionName, draft, replace: true).ConfigureAwait(true)) + { + return draft.Place; + } + } + catch (TableProException exception) + { + draft.Error = Strings.Error(exception.Error); + } + } + } + + // Writes only what changed: the name, the text by that name with replace keeping the id, then the folder. + public static async Task EditAsync( + FrameworkElement owner, + SavedQueries store, + Guid connectionId, + string connectionName, + SavedQuery query) + { + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(query); + var draft = new Draft(query.Id, query.Name, query.Sql, query.FolderId); + var folders = await FoldersAsync(store, connectionId).ConfigureAwait(true); + var answer = await ShowAsync( + owner, + Strings.Get("EditSavedQueryTitle"), + draft, + folders, + editsSql: true, + () => CommitAsync(store, connectionId, connectionName, draft, replace: true)) + .ConfigureAwait(true); + return answer == Answer.Saved ? draft.Place : null; + } + + // A refusal from apply shows under the box and keeps the dialog open. + public static async Task AskNameAsync( + FrameworkElement owner, + string title, + string name, + string action, + Func apply) + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(apply); + var box = NameBox(name, "NameDialogBox"); + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = title, + Content = box, + PrimaryButtonText = action, + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Primary, + IsPrimaryButtonEnabled = !string.IsNullOrWhiteSpace(name), + }; + box.TextChanged += (_, _) => dialog.IsPrimaryButtonEnabled = !string.IsNullOrWhiteSpace(box.Text); + dialog.PrimaryButtonClick += async (_, args) => + { + var deferral = args.GetDeferral(); + try + { + await apply(box.Text.Trim()).ConfigureAwait(true); + } + catch (TableProException exception) + { + args.Cancel = true; + box.Description = Strings.Error(exception.Error); + } + finally + { + deferral.Complete(); + } + }; + return await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true) == ContentDialogResult.Primary; + } + + // Enter cancels, as every question that removes something does. + public static async Task ConfirmDeleteAsync(FrameworkElement owner, string title, string message) + { + ArgumentNullException.ThrowIfNull(owner); + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = title, + Content = new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap }, + PrimaryButtonText = Strings.Get("DeleteButton"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }; + return await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true) == ContentDialogResult.Primary; + } + + // False when another query has the name and replace is false; nothing is written then. + private static async Task CommitAsync( + SavedQueries store, + Guid connectionId, + string connectionName, + Draft draft, + bool replace) + { + if (draft.Id is not { } id) + { + if (await store.SaveAsync(connectionId, connectionName, draft.Name, draft.Sql, replace).ConfigureAwait(true) + is not { } added) + { + return false; + } + + // A failed move after this leaves the query saved, so a second try only moves it. + draft.Id = id = added; + draft.StoredName = draft.Name; + draft.StoredSql = draft.Sql; + } + else + { + if (!string.Equals(draft.Name, draft.StoredName, StringComparison.Ordinal)) + { + await store.RenameAsync(id, draft.Name).ConfigureAwait(true); + draft.StoredName = draft.Name; + } + + if (!string.Equals(draft.Sql, draft.StoredSql, StringComparison.Ordinal)) + { + await store.SaveAsync(connectionId, connectionName, draft.Name, draft.Sql, replace: true).ConfigureAwait(true); + draft.StoredSql = draft.Sql; + } + } + + if (draft.FolderId != draft.StoredFolder) + { + await store.MoveAsync(id, draft.FolderId).ConfigureAwait(true); + draft.StoredFolder = draft.FolderId; + } + + return true; + } + + private static async Task ShowAsync( + FrameworkElement owner, + string title, + Draft draft, + IReadOnlyList folders, + bool editsSql, + Func> commit) + { + var content = new StackPanel { Spacing = 12, MinWidth = 360 }; + var error = new InfoBar + { + Severity = InfoBarSeverity.Error, + IsClosable = false, + IsOpen = draft.Error is not null, + Message = draft.Error ?? string.Empty, + Visibility = draft.Error is null ? Visibility.Collapsed : Visibility.Visible, + }; + AutomationProperties.SetAutomationId(error, "SaveQueryError"); + content.Children.Add(error); + + var name = NameBox(draft.Name, "SavedQueryNameBox"); + content.Children.Add(name); + + // Only a connection with folders is asked where the query goes. + ComboBox? folder = null; + if (folders.Count > 0) + { + folder = FolderBox(folders, draft.FolderId); + content.Children.Add(folder); + } + + TextBox? sql = null; + if (editsSql) + { + sql = new TextBox + { + Header = Strings.Get("SavedQuerySqlHeader"), + Text = draft.Sql, + AcceptsReturn = true, + TextWrapping = TextWrapping.NoWrap, + IsSpellCheckEnabled = false, + FontFamily = new FontFamily("Cascadia Mono, Consolas, Courier New"), + Height = 200, + }; + ScrollViewer.SetHorizontalScrollBarVisibility(sql, ScrollBarVisibility.Auto); + ScrollViewer.SetVerticalScrollBarVisibility(sql, ScrollBarVisibility.Auto); + AutomationProperties.SetAutomationId(sql, "SavedQuerySqlBox"); + AutomationProperties.SetName(sql, Strings.Get("SavedQuerySqlHeader")); + content.Children.Add(sql); + } + + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = title, + Content = content, + PrimaryButtonText = Strings.Get("SaveQueryAction"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Primary, + }; + void Validate() => dialog.IsPrimaryButtonEnabled = + !string.IsNullOrWhiteSpace(name.Text) && (sql is null || !string.IsNullOrWhiteSpace(sql.Text)); + name.TextChanged += (_, _) => Validate(); + if (sql is not null) + { + sql.TextChanged += (_, _) => Validate(); + } + + Validate(); + var taken = false; + dialog.PrimaryButtonClick += async (_, args) => + { + var deferral = args.GetDeferral(); + draft.Name = name.Text.Trim(); + if (folder is not null) + { + draft.FolderId = (folder.SelectedItem as ComboBoxItem)?.Tag as long?; + } + + if (sql is not null) + { + // A TextBox keeps its line breaks as CR. + draft.Sql = TextDocument.Normalize(sql.Text).Trim(); + } + + try + { + taken = !await commit().ConfigureAwait(true); + draft.Error = null; + } + catch (TableProException exception) + { + args.Cancel = true; + draft.Error = Strings.Error(exception.Error); + error.Message = draft.Error; + error.Visibility = Visibility.Visible; + // Narrator reads an InfoBar when it opens, not when its text changes. + error.IsOpen = false; + error.IsOpen = true; + } + finally + { + deferral.Complete(); + } + }; + var result = await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true); + if (result != ContentDialogResult.Primary) + { + return Answer.Cancelled; + } + + return taken ? Answer.Taken : Answer.Saved; + } + + private static TextBox NameBox(string name, string automationId) + { + var box = new TextBox + { + Header = Strings.Get("SavedQueryNameHeader"), + Text = name, + SelectionStart = 0, + SelectionLength = name.Length, + }; + AutomationProperties.SetAutomationId(box, automationId); + AutomationProperties.SetName(box, Strings.Get("SavedQueryNameHeader")); + return box; + } + + // Each folder by its path, indented under the one above it. + private static ComboBox FolderBox(IReadOnlyList folders, long? selected) + { + var box = new ComboBox { Header = Strings.Get("SavedQueryFolderHeader"), HorizontalAlignment = HorizontalAlignment.Stretch }; + box.Items.Add(new ComboBoxItem { Content = Strings.Get("SavedQueryNoFolder") }); + box.SelectedIndex = 0; + foreach (var choice in folders) + { + var item = new ComboBoxItem + { + Content = choice.Path, + Tag = choice.Id, + Padding = new Thickness(11 + (choice.Depth * 16), 5, 11, 7), + }; + AutomationProperties.SetName(item, choice.Path); + box.Items.Add(item); + if (choice.Id == selected) + { + box.SelectedItem = item; + } + } + + AutomationProperties.SetAutomationId(box, "SavedQueryFolderBox"); + AutomationProperties.SetName(box, Strings.Get("SavedQueryFolderHeader")); + return box; + } + + // A list that cannot be read leaves the picker out; the save itself still says what went wrong. + private static async Task> FoldersAsync(SavedQueries store, Guid connectionId) + { + try + { + return SavedQueryTree.Folders(await store.GetAsync(connectionId).ConfigureAwait(true)); + } + catch (TableProException) + { + return []; + } + } + + private static async Task ConfirmReplaceAsync(FrameworkElement owner, string name) + { + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Content = new TextBlock + { + Text = Strings.Format("ReplaceSavedQueryMessage", name), + TextWrapping = TextWrapping.Wrap, + }, + PrimaryButtonText = Strings.Get("ReplaceButton"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }; + return await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true) == ContentDialogResult.Primary; + } + + private enum Answer + { + Cancelled, + Saved, + Taken, + } + + // What the dialog shows again after the replace question, and what the store holds so far. + private sealed class Draft(long? id, string name, string sql, long? folderId) + { + public long? Id { get; set; } = id; + + public string Name { get; set; } = name; + + public string Sql { get; set; } = sql; + + public long? FolderId { get; set; } = folderId; + + public string StoredName { get; set; } = name; + + public string StoredSql { get; set; } = sql; + + // A new query starts at the top level, so it moves only when a folder was picked. + public long? StoredFolder { get; set; } = id is null ? null : folderId; + + public string? Error { get; set; } + + public SavedQueryPlace? Place => Id is { } saved ? new SavedQueryPlace(saved, FolderId) : null; + } +} diff --git a/windows/src/TablePro.App/Views/SavedQueriesPane.xaml b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml new file mode 100644 index 0000000000..fdcdbc6c50 --- /dev/null +++ b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs new file mode 100644 index 0000000000..61f502411c --- /dev/null +++ b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs @@ -0,0 +1,533 @@ +using System.Collections.ObjectModel; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.Interop; +using Windows.System; + +namespace TablePro.App.Views; + +// One saved connection's queries in their folders; the core keeps them, and the tree is read again after each change. +public sealed partial class SavedQueriesPane : UserControl +{ + private readonly SavedQueries? _store; + private readonly Guid _connectionId; + private readonly Func _connectionName; + + // Folders the user opened, kept across the rebuild each change makes. + private readonly HashSet _expanded = []; + private SavedQueryList _list = new([], []); + private long? _reveal; + private int _reading; + private int _rebuild; + + // Clearing the rows reports them collapsed, which is not the user's doing. + private bool _rebuilding; + + // Null store: the history's database could not open, so nothing is kept or shown. + internal SavedQueriesPane(SavedQueries? store, Guid connectionId, Func connectionName) + { + InitializeComponent(); + _store = store; + _connectionId = connectionId; + _connectionName = connectionName; + if (store is null) + { + NewFolderButton.IsEnabled = false; + ShowFailure(Strings.Get("SavedQueriesUnavailableTitle"), Strings.Get("SavedQueriesUnavailableMessage"), closable: false); + } + } + + // Insert in editor, the primary action: the workspace puts the text in the shown query tab, or a new one. + public event EventHandler? InsertRequested; + + public event EventHandler? OpenRequested; + + public event EventHandler? CloseRequested; + + public ObservableCollection Items { get; } = []; + + public async Task RefreshAsync() + { + if (_store is not { } store) + { + return; + } + + var reading = ++_reading; + SavedQueryList list; + try + { + list = await store.GetAsync(_connectionId).ConfigureAwait(true); + } + catch (TableProException exception) + { + if (reading == _reading) + { + ShowFailure(Strings.Get("SavedQueriesReadFailedTitle"), Strings.Error(exception.Error), closable: false); + } + + return; + } + + if (reading != _reading) + { + return; + } + + HideFailure(); + Show(list); + } + + // After a save from elsewhere: the folder it went into opens. + internal Task RevealAsync(SavedQueryPlace place) + { + ArgumentNullException.ThrowIfNull(place); + _reveal = place.FolderId; + return RefreshAsync(); + } + + // A pane shown for the first time joins the tree only on the next layout, and an unloaded row takes no focus. + public void FocusTree() + { + if (!IsLoaded) + { + void OnLoaded(object sender, RoutedEventArgs e) + { + Loaded -= OnLoaded; + FocusTree(); + } + + Loaded += OnLoaded; + return; + } + + var item = QueryTree.SelectedItem ?? Items.FirstOrDefault(); + if (item is null + || QueryTree.ContainerFromItem(item) is not TreeViewItem row + || !row.Focus(FocusState.Programmatic)) + { + NewFolderButton.Focus(FocusState.Programmatic); + } + } + + private void Show(SavedQueryList list) + { + _list = list; + if (_reveal is { } folder) + { + _expanded.UnionWith(SavedQueryTree.FolderAndAncestors(folder, list)); + _reveal = null; + } + + var rebuild = ++_rebuild; + _rebuilding = true; + Items.Clear(); + foreach (var node in SavedQueryTree.Build(list)) + { + Items.Add(ToItem(node)); + } + + EmptyText.Visibility = Items.Count == 0 ? Visibility.Visible : Visibility.Collapsed; + ApplyExpansion(Items); + Settle(rebuild, passes: 2); + } + + // The tree sets each new row's state in a later pass, which can fold a row opened here (seen on Arm64). + private void Settle(int rebuild, int passes) + { + DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => + { + if (rebuild != _rebuild) + { + return; + } + + ApplyExpansion(Items); + if (passes > 1) + { + Settle(rebuild, passes - 1); + } + else + { + _rebuilding = false; + } + }); + } + + private static SavedQueryItem ToItem(SavedQueryNode node) + { + var item = new SavedQueryItem(node); + foreach (var child in node.Children) + { + item.Children.Add(ToItem(child)); + } + + return item; + } + + // A bound IsExpanded is overwritten as the row joins the tree, and a row's children get containers only once open. + private void ApplyExpansion(IEnumerable items) + { + QueryTree.UpdateLayout(); + var opened = new List(); + foreach (var item in items.Where(IsOpen)) + { + if (QueryTree.ContainerFromItem(item) is TreeViewItem row) + { + row.IsExpanded = true; + opened.Add(item); + } + } + + if (opened.Count > 0) + { + ApplyExpansion(opened.SelectMany(item => item.Children)); + } + } + + private bool IsOpen(SavedQueryItem item) => + item.Node.Folder is { } folder && _expanded.Contains(folder.Id) && item.Children.Count > 0; + + private void OnRowLoaded(object sender, RoutedEventArgs e) + { + if (sender is TreeViewItem row && QueryTree.ItemFromContainer(row) is SavedQueryItem item && IsOpen(item)) + { + row.IsExpanded = true; + } + } + + private void OnFolderExpanding(TreeView sender, TreeViewExpandingEventArgs args) + { + if (!_rebuilding && args.Item is SavedQueryItem { Node.Folder: { } folder }) + { + _expanded.Add(folder.Id); + } + } + + private void OnFolderCollapsed(TreeView sender, TreeViewCollapsedEventArgs args) + { + if (!_rebuilding && args.Item is SavedQueryItem { Node.Folder: { } folder }) + { + _expanded.Remove(folder.Id); + } + } + + private void OnItemInvoked(TreeView sender, TreeViewItemInvokedEventArgs args) + { + if (args.InvokedItem is SavedQueryItem { Node.Folder: not null } item + && QueryTree.ContainerFromItem(item) is TreeViewItem row) + { + row.IsExpanded = !row.IsExpanded; + } + } + + private void OnRowDoubleTapped(object sender, DoubleTappedRoutedEventArgs e) + { + if (QueryTree.ItemFromContainer((DependencyObject)sender) is SavedQueryItem { Node.Query: { } query }) + { + e.Handled = true; + InsertRequested?.Invoke(this, query.Sql); + } + } + + private async void OnTreeKeyDown(object sender, KeyRoutedEventArgs e) + { + if (_store is null || QueryTree.SelectedItem is not SavedQueryItem item) + { + return; + } + + switch (e.Key) + { + case VirtualKey.Enter when item.Node.Query is { } query: + e.Handled = true; + InsertRequested?.Invoke(this, query.Sql); + break; + case VirtualKey.F2 when item.Node.Query is { } query: + e.Handled = true; + await EditAsync(query).ConfigureAwait(true); + break; + case VirtualKey.F2 when item.Node.Folder is { } folder: + e.Handled = true; + await RenameFolderAsync(folder).ConfigureAwait(true); + break; + case VirtualKey.Delete when item.Node.Query is { } query: + e.Handled = true; + await DeleteAsync(query).ConfigureAwait(true); + break; + case VirtualKey.Delete when item.Node.Folder is { } folder: + e.Handled = true; + await DeleteFolderAsync(folder).ConfigureAwait(true); + break; + default: + break; + } + } + + // Built when asked for, since a menu keeps the window it first opened in and a tab can move to another. + private void OnRowContextRequested(UIElement sender, ContextRequestedEventArgs args) + { + if (_store is null || QueryTree.ItemFromContainer(sender) is not SavedQueryItem item) + { + return; + } + + args.Handled = true; + var menu = item.Node.Query is { } query ? QueryMenu(query) : FolderMenu(item.Node.Folder!); + if (args.TryGetPosition(sender, out var point)) + { + menu.ShowAt(sender, new FlyoutShowOptions { Position = point }); + } + else + { + menu.ShowAt((FrameworkElement)sender); + } + } + + private MenuFlyout QueryMenu(SavedQuery query) + { + var insert = MenuItem("SavedQueryMenuInsert", Symbol.Paste); + insert.Click += (_, _) => InsertRequested?.Invoke(this, query.Sql); + var open = MenuItem("SavedQueryMenuOpen", Symbol.Add); + open.Click += (_, _) => OpenRequested?.Invoke(this, query.Sql); + var copy = MenuItem("SavedQueryMenuCopy", Symbol.Copy); + copy.Click += (_, _) => WorkspaceView.CopyText(query.Sql); + var edit = MenuItem("MenuEdit", Symbol.Edit); + edit.Click += async (_, _) => await EditAsync(query).ConfigureAwait(true); + var delete = MenuItem("MenuDelete", Symbol.Delete); + delete.Click += async (_, _) => await DeleteAsync(query).ConfigureAwait(true); + + var menu = new MenuFlyout(); + menu.Items.Add(insert); + menu.Items.Add(open); + menu.Items.Add(copy); + menu.Items.Add(new MenuFlyoutSeparator()); + menu.Items.Add(edit); + menu.Items.Add(MoveMenu(query)); + menu.Items.Add(new MenuFlyoutSeparator()); + menu.Items.Add(delete); + return menu; + } + + // The place the query is in now is offered but cannot be picked. + private MenuFlyoutSubItem MoveMenu(SavedQuery query) + { + var move = new MenuFlyoutSubItem + { + Text = Strings.Get("SavedQueryMenuMoveTo"), + Icon = new SymbolIcon(Symbol.MoveToFolder), + }; + AutomationProperties.SetAutomationId(move, "SavedQueryMenuMoveTo"); + var top = MenuItem("SavedQueryMenuTopLevel", null); + top.IsEnabled = query.FolderId is not null; + top.Click += async (_, _) => await MoveAsync(query, null).ConfigureAwait(true); + move.Items.Add(top); + foreach (var folder in SavedQueryTree.Folders(_list)) + { + var item = new MenuFlyoutItem { Text = folder.Path, IsEnabled = folder.Id != query.FolderId }; + AutomationProperties.SetAutomationId(item, "SavedQueryMoveTo_" + folder.Id); + var target = folder.Id; + item.Click += async (_, _) => await MoveAsync(query, target).ConfigureAwait(true); + move.Items.Add(item); + } + + return move; + } + + private MenuFlyout FolderMenu(SavedQueryFolder folder) + { + var subfolder = MenuItem("SavedQueryMenuNewSubfolder", Symbol.NewFolder); + subfolder.Click += async (_, _) => await NewFolderAsync(folder.Id).ConfigureAwait(true); + var rename = MenuItem("MenuRename", Symbol.Rename); + rename.Click += async (_, _) => await RenameFolderAsync(folder).ConfigureAwait(true); + var delete = MenuItem("SavedQueryMenuDeleteFolder", Symbol.Delete); + delete.Click += async (_, _) => await DeleteFolderAsync(folder).ConfigureAwait(true); + + var menu = new MenuFlyout(); + menu.Items.Add(subfolder); + menu.Items.Add(rename); + menu.Items.Add(new MenuFlyoutSeparator()); + menu.Items.Add(delete); + return menu; + } + + private static MenuFlyoutItem MenuItem(string text, Symbol? icon) + { + var item = new MenuFlyoutItem { Text = Strings.Get(text) }; + if (icon is { } symbol) + { + item.Icon = new SymbolIcon(symbol); + } + + AutomationProperties.SetAutomationId(item, text); + return item; + } + + private async Task EditAsync(SavedQuery query) + { + if (_store is not { } store) + { + return; + } + + if (await SaveQueryDialog.EditAsync(this, store, _connectionId, _connectionName(), query).ConfigureAwait(true) + is { } place) + { + await RevealAsync(place).ConfigureAwait(true); + } + } + + private async Task MoveAsync(SavedQuery query, long? folderId) + { + _reveal = folderId; + await ChangeAsync(store => store.MoveAsync(query.Id, folderId)).ConfigureAwait(true); + } + + private async Task DeleteAsync(SavedQuery query) + { + if (await SaveQueryDialog.ConfirmDeleteAsync( + this, + Strings.Get("DeleteSavedQueryTitle"), + Strings.Format("DeleteSavedQueryMessage", query.Name)).ConfigureAwait(true)) + { + await ChangeAsync(store => store.DeleteAsync(query.Id)).ConfigureAwait(true); + } + } + + // Null parent: a folder at the top level. + private async Task NewFolderAsync(long? parentId) + { + if (_store is not { } store) + { + return; + } + + var title = Strings.Get(parentId is null ? "NewSavedFolderTitle" : "NewSavedSubfolderTitle"); + if (await SaveQueryDialog.AskNameAsync( + this, + title, + Strings.Get("NewSavedFolderName"), + Strings.Get("CreateButton"), + name => store.CreateFolderAsync(_connectionId, name, parentId)).ConfigureAwait(true)) + { + _reveal = parentId; + await RefreshAsync().ConfigureAwait(true); + } + } + + private async Task RenameFolderAsync(SavedQueryFolder folder) + { + if (_store is not { } store) + { + return; + } + + if (await SaveQueryDialog.AskNameAsync( + this, + Strings.Get("RenameSavedFolderTitle"), + folder.Name, + Strings.Get("RenameButton"), + name => store.RenameFolderAsync(folder.Id, name)).ConfigureAwait(true)) + { + await RefreshAsync().ConfigureAwait(true); + } + } + + private async Task DeleteFolderAsync(SavedQueryFolder folder) + { + if (await SaveQueryDialog.ConfirmDeleteAsync( + this, + Strings.Get("DeleteSavedFolderTitle"), + Strings.Format("DeleteSavedFolderMessage", folder.Name)).ConfigureAwait(true)) + { + await ChangeAsync(store => store.DeleteFolderAsync(folder.Id)).ConfigureAwait(true); + } + } + + // The list is read again either way, since a refused change can follow one made in another window. + private async Task ChangeAsync(Func change) + { + if (_store is not { } store) + { + return; + } + + string? failure = null; + try + { + await change(store).ConfigureAwait(true); + } + catch (TableProException exception) + { + failure = Strings.Error(exception.Error); + } + + await RefreshAsync().ConfigureAwait(true); + if (failure is not null) + { + ShowFailure(Strings.Get("SavedQueriesChangeFailedTitle"), failure, closable: true); + } + } + + private void ShowFailure(string title, string message, bool closable) + { + // A closed InfoBar keeps its margin, so the bar is collapsed while it is closed. + FailureBar.Visibility = Visibility.Visible; + FailureBar.IsClosable = closable; + if (FailureBar.IsOpen && FailureBar.Title == title && FailureBar.Message == message) + { + return; + } + + FailureBar.Title = title; + FailureBar.Message = message; + // Narrator reads an InfoBar when it opens, not when its text changes. + FailureBar.IsOpen = false; + FailureBar.IsOpen = true; + } + + private void HideFailure() + { + FailureBar.IsOpen = false; + FailureBar.Visibility = Visibility.Collapsed; + } + + private void OnFailureBarClosed(InfoBar sender, InfoBarClosedEventArgs args) => + FailureBar.Visibility = Visibility.Collapsed; + + private async void OnNewFolder(object sender, RoutedEventArgs e) => await NewFolderAsync(null).ConfigureAwait(true); + + private void OnClose(object sender, RoutedEventArgs e) => CloseRequested?.Invoke(this, EventArgs.Empty); +} + +public sealed partial class SavedQueryItem +{ + internal SavedQueryItem(SavedQueryNode node) + { + Node = node; + Title = node.Name; + Detail = node.Query is { } query ? SavedQueryText.FirstLine(query.Sql) : string.Empty; + AccessibleName = Detail.Length == 0 ? Title : string.Concat(Title, ", ", Detail); + } + + public SavedQueryNode Node { get; } + + public string Title { get; } + + // A query's first line of text under its name. + public string Detail { get; } + + public Visibility DetailVisibility => Detail.Length == 0 ? Visibility.Collapsed : Visibility.Visible; + + public Symbol Icon => Node.Folder is null ? Symbol.Document : Symbol.Folder; + + public string AccessibleName { get; } + + public ObservableCollection Children { get; } = []; +} diff --git a/windows/src/TablePro.App/Views/TableTabView.xaml.cs b/windows/src/TablePro.App/Views/TableTabView.xaml.cs index 675df766f5..fbd98539eb 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -757,7 +757,10 @@ private async void OnPreviousPage(object sender, RoutedEventArgs e) => private async void OnCountRows(object sender, RoutedEventArgs e) => await _model.CountRowsAsync().ConfigureAwait(true); - private async void OnRefresh(object sender, RoutedEventArgs e) + private async void OnRefresh(object sender, RoutedEventArgs e) => await RefreshRowsAsync().ConfigureAwait(true); + + // As Refresh does, for rows written from outside the tab, such as an import. + internal async Task RefreshRowsAsync() { await _model.RefreshAsync().ConfigureAwait(true); await ReloadShownAsync().ConfigureAwait(true); diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml b/windows/src/TablePro.App/Views/WorkspaceView.xaml index df1e1491c2..7852b2ba2b 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml @@ -55,7 +55,7 @@ - + - + { - private const double HistoryPaneWidth = 320; + private const double SidePaneWidth = 320; private readonly Workbench _workbench; private readonly OpenConnection _connection; @@ -52,6 +53,11 @@ public sealed partial class WorkspaceView : UserControl, IWorkspaceTabsView _editorHasText = []; private CancellationTokenSource? _exporting; internal WorkspaceView(Workbench workbench, OpenConnection connection) @@ -108,7 +114,19 @@ internal WorkspaceView(Workbench workbench, OpenConnection connection) public bool CanReopenTab => _session is not null && _tabs.ClosedCount > 0; - public bool HistoryVisible => HistoryHost.Visibility == Visibility.Visible; + public bool HistoryVisible => SideHost.Visibility == Visibility.Visible && SideHost.Child is HistoryPane; + + public bool SavedQueriesVisible => SideHost.Visibility == Visibility.Visible && SideHost.Child is SavedQueriesPane; + + // A file opened without saving gets a new id each time it opens, so only a saved connection keeps queries. + public bool CanShowSavedQueries => _connection.ConnectionId is not null; + + // Read on every command update, so only the editor's leading blanks are read. + public bool CanSaveQuery => + _session is not null + && CanShowSavedQueries + && ActiveTab is QueryTabView { Editor: { } editor } + && HasText(editor.Document); // One export at a time, of rows the tab shows now. // Rows still arriving would be written as if they were all of them. @@ -223,6 +241,10 @@ internal void ShowConnected(SessionShare share, SessionConnecti { _ = ShowHistoryAsync(focus: false); } + else if (SavedQueriesVisible) + { + _ = ShowSavedQueriesAsync(focus: false); + } } public async void Start() @@ -444,7 +466,7 @@ public async Task ToggleHistoryAsync() { if (HistoryVisible) { - HideHistory(); + HideSidePane(); return; } @@ -480,21 +502,22 @@ private async Task ShowHistoryAsync(bool focus) // A file opened without saving gets a new id each time it opens, so its pane lists every connection's runs. var connection = _connection.ConnectionId is null ? (Guid?)null : session.Id; - pane = new HistoryPane(history is null ? null : new HistoryList(new CoreHistoryStore(history), connection)); + pane = new HistoryPane(history is null ? null : new HistoryList(new CoreHistoryStore(history), connection)) + { + CanSaveQuery = CanShowSavedQueries, + }; pane.OpenRequested += (_, sql) => NewQueryTab(sql); + pane.SaveRequested += async (_, sql) => await SaveQueryAsync(sql).ConfigureAwait(true); pane.CloseRequested += (_, _) => { - HideHistory(); + HideSidePane(); ActiveTab?.FocusContent(); }; _historyPane = pane; _historyConnection = session.Id; - HistoryHost.Child = pane; } - HistoryColumn.Width = new GridLength(HistoryPaneWidth); - HistoryHost.Visibility = Visibility.Visible; - CommandsChanged?.Invoke(this, EventArgs.Empty); + ShowSidePane(pane); if (focus) { pane.FocusSearch(); @@ -503,13 +526,151 @@ private async Task ShowHistoryAsync(bool focus) await pane.RefreshAsync().ConfigureAwait(true); } - private void HideHistory() + public async Task ToggleSavedQueriesAsync() + { + if (SavedQueriesVisible) + { + HideSidePane(); + return; + } + + await ShowSavedQueriesAsync(focus: true).ConfigureAwait(true); + } + + // The store opens once for the app, in the history's database; a pane without one says they are unavailable. + private async Task ShowSavedQueriesAsync(bool focus) + { + if (_session is not { } session || _connection.ConnectionId is not { } connectionId || _openingSaved) + { + return; + } + + var pane = _savedPane; + if (pane is null) + { + _openingSaved = true; + SavedQueries? store; + try + { + store = await _workbench.GetSavedQueriesAsync().ConfigureAwait(true); + } + finally + { + _openingSaved = false; + } + + if (!ReferenceEquals(_session, session)) + { + return; + } + + pane = new SavedQueriesPane(store, connectionId, () => _connection.Name); + pane.InsertRequested += (_, sql) => InsertQuery(sql); + pane.OpenRequested += (_, sql) => NewQueryTab(sql); + pane.CloseRequested += (_, _) => + { + HideSidePane(); + ActiveTab?.FocusContent(); + }; + _savedPane = pane; + } + + ShowSidePane(pane); + await pane.RefreshAsync().ConfigureAwait(true); + if (focus) + { + pane.FocusTree(); + } + } + + // One pane at a time beside the tabs, so showing one puts the other away. + private void ShowSidePane(UserControl pane) { - HistoryHost.Visibility = Visibility.Collapsed; - HistoryColumn.Width = new GridLength(0); + SideHost.Child = pane; + SideColumn.Width = new GridLength(SidePaneWidth); + SideHost.Visibility = Visibility.Visible; CommandsChanged?.Invoke(this, EventArgs.Empty); } + private void HideSidePane() + { + SideHost.Visibility = Visibility.Collapsed; + SideColumn.Width = new GridLength(0); + CommandsChanged?.Invoke(this, EventArgs.Empty); + } + + // Query > Save query...: the whole tab's text. + public async Task SaveQueryAsync() + { + if (CanSaveQuery && ActiveTab is QueryTabView { Editor: { } editor }) + { + await SaveQueryAsync(editor.Document.Snapshot()).ConfigureAwait(true); + } + } + + private async Task SaveQueryAsync(string sql) + { + sql = sql.Trim(); + if (_connection.ConnectionId is not { } connectionId || sql.Length == 0) + { + return; + } + + if (await _workbench.GetSavedQueriesAsync().ConfigureAwait(true) is not { } store) + { + var dialog = new ContentDialog + { + RequestedTheme = ActualTheme, + Title = Strings.Get("SavedQueriesUnavailableTitle"), + Content = Strings.Get("SavedQueriesUnavailableMessage"), + CloseButtonText = Strings.Get("Close"), + DefaultButton = ContentDialogButton.Close, + }; + await WindowDialogs.ShowAsync(dialog, this).ConfigureAwait(true); + return; + } + + if (await SaveQueryDialog.SaveAsync(this, store, connectionId, _connection.Name, sql).ConfigureAwait(true) + is { } place + && _savedPane is { } pane) + { + await pane.RevealAsync(place).ConfigureAwait(true); + } + } + + // Insert in editor: a blank query tab takes the text, one with text gets it after a blank line, else a new tab opens. + private void InsertQuery(string sql) + { + var query = ActiveTab as QueryTabView; + var editor = query?.Editor; + var insertion = SavedQueryText.Insertion(editor?.Document.Snapshot(), sql); + if (query is null || editor is null || insertion.Kind == SavedQueryInsertKind.NewTab) + { + NewQueryTab(sql); + return; + } + + // Through the editor's model, so Undo takes it back. + var start = insertion.Kind == SavedQueryInsertKind.Replace ? 0 : editor.Document.Length; + editor.Model.ReplaceRange(start, editor.Document.Length, insertion.Text); + editor.EnsureCaretVisible(); + editor.Invalidate(); + query.FocusContent(); + } + + private static bool HasText(TextDocument document) + { + foreach (var chunk in document.Chunks(0, document.Length)) + { + if (!chunk.Span.IsWhiteSpace()) + { + return true; + } + } + + return false; + } + private async void OnHistoryRecorded(object? sender, EventArgs e) { if (HistoryVisible && _historyPane is { } pane) @@ -592,6 +753,53 @@ public async Task ExportAsync() } } + // One at a time with exports, so the bar and its Stop button belong to it while the rows go in. + private async Task ImportCsvAsync(ObjectEntry entry) + { + if (_session is not { } session || _exporting is not null) + { + return; + } + + var table = new TableName(entry.Schema, entry.Name); + var importing = new CancellationTokenSource(); + _exporting = importing; + CommandsChanged?.Invoke(this, EventArgs.Empty); + try + { + var result = await ImportCsvDialog.RunAsync( + this, + session, + table, + rows => ShowExport(InfoBarSeverity.Informational, Strings.Format("ImportCsvRunning", rows, entry.Name), running: true), + importing.Token) + .ConfigureAwait(true); + if (result is null) + { + ExportBar.IsOpen = false; + return; + } + + ShowExport(result.Succeeded ? InfoBarSeverity.Success : InfoBarSeverity.Error, result.Message, running: false); + if (result.TableChanged) + { + foreach (var item in Tabs.TabItems.OfType()) + { + if (item.Content is TableTabView view && view.Shows(entry.Schema, entry.Name)) + { + await view.RefreshRowsAsync().ConfigureAwait(true); + } + } + } + } + finally + { + _exporting = null; + importing.Dispose(); + CommandsChanged?.Invoke(this, EventArgs.Empty); + } + } + private void ShowExport(InfoBarSeverity severity, string message, bool running) { ExportBar.Severity = severity; @@ -739,6 +947,7 @@ internal void Take(TabViewItem item, int? index = null) if (content.Editor is { } editor) { editor.TextChanged += OnEditorTextChanged; + _editorHasText[editor] = HasText(editor.Document); } } @@ -788,6 +997,7 @@ internal void Release(TabViewItem item) if (content.Editor is { } editor) { editor.TextChanged -= OnEditorTextChanged; + _editorHasText.Remove(editor); } _snapshots.Remove(content); @@ -871,7 +1081,21 @@ private void OnTabStateChanged(object? sender, EventArgs e) SessionChanged?.Invoke(this, EventArgs.Empty); } - private void OnEditorTextChanged(object? sender, EventArgs e) => SessionChanged?.Invoke(this, EventArgs.Empty); + private void OnEditorTextChanged(object? sender, EventArgs e) + { + SessionChanged?.Invoke(this, EventArgs.Empty); + if (sender is SqlEditor editor + && _editorHasText.TryGetValue(editor, out var had) + && HasText(editor.Document) is var has + && has != had) + { + _editorHasText[editor] = has; + if (ReferenceEquals(ActiveTab?.Editor, editor)) + { + CommandsChanged?.Invoke(this, EventArgs.Empty); + } + } + } private void OnSessionWriteRequested(object? sender, EventArgs e) => Host?.WriteSessionNow(); @@ -1492,6 +1716,11 @@ private void ShowObjectMenu(FrameworkElement row, ObjectEntry entry, ContextRequ menu.Items.Add(ObjectMenuItem("ObjectMenuOpen", Symbol.OpenFile, () => OpenTable(entry))); menu.Items.Add(ObjectMenuItem( "ObjectMenuShowStructure", Symbol.List, () => OpenTable(entry)?.ShowStructure())); + if (entry.Kind is ObjectKind.Table or ObjectKind.PartitionedTable) + { + menu.Items.Add(ObjectMenuItem("ObjectMenuImportCsv", Symbol.Import, async () => await ImportCsvAsync(entry).ConfigureAwait(true))); + } + menu.Items.Add(new MenuFlyoutSeparator()); } else if (ObjectFolders.HasDefinition(entry.Kind)) diff --git a/windows/src/TablePro.Interop/ConnectionLibrary.cs b/windows/src/TablePro.Interop/ConnectionLibrary.cs index efb6bbf9b2..ff4914a97a 100644 --- a/windows/src/TablePro.Interop/ConnectionLibrary.cs +++ b/windows/src/TablePro.Interop/ConnectionLibrary.cs @@ -115,6 +115,22 @@ public async Task ImportAsync(string path) return new ImportSummary(checked((int)summary.Added), checked((int)summary.Updated)); } + // A copy under a new id right after the original, with every secret the original keeps; it is no favourite. + public async Task DuplicateAsync(Guid id, string name) + { + ArgumentNullException.ThrowIfNull(name); + var copy = await CoreCall.RunAsync(() => _library.Duplicate(id.ToString(), name)).ConfigureAwait(false); + return Mapping.Connection(copy); + } + + // Every connection, group and tag, and no password, in a file that appears at path only once whole. + public async Task ExportAsync(string path) + { + ArgumentException.ThrowIfNullOrEmpty(path); + var count = await CoreCall.RunAsync(() => _library.ExportFile(path)).ConfigureAwait(false); + return checked((int)count); + } + public void Dispose() => _library.Dispose(); private static string[] Names(IReadOnlyList ids) diff --git a/windows/src/TablePro.Interop/CsvImport.cs b/windows/src/TablePro.Interop/CsvImport.cs new file mode 100644 index 0000000000..13362259e0 --- /dev/null +++ b/windows/src/TablePro.Interop/CsvImport.cs @@ -0,0 +1,169 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +public enum CsvDelimiter +{ + Comma, + Semicolon, + Tab, + Pipe, +} + +// NullText: a field holding exactly this reads as NULL; empty by default, as every export writes NULL. +public sealed record CsvOptions(CsvDelimiter Delimiter, bool HasHeader, string NullText) +{ + public static CsvOptions Default { get; } = new(CsvDelimiter.Comma, HasHeader: true, NullText: string.Empty); +} + +// Headers are empty strings when the file has none, one per field of the widest row. +public sealed record CsvPreview(IReadOnlyList Headers, IReadOnlyList> Rows, bool Truncated); + +// ServerFilled: a generated column or an identity that refuses a value; no field is ever mapped to it. +public sealed record ImportColumn(string Name, string TypeName, bool Nullable, bool HasDefault, bool ServerFilled); + +// Line counts the header as line 1, as a spreadsheet shows it. Reason is the code a cell edit refused alike has. +public sealed record CsvRowFault(long Line, string Column, string Text, string Reason); + +public sealed record LineSpan(long First, long Last); + +public abstract record CsvImportCheck +{ + private CsvImportCheck() + { + } + + // Statements are the SQL the rows write as, which Safe Mode shows before a confirmed run. + public sealed record Ready(long Rows, IReadOnlyList Statements, SaveGate Gate) : CsvImportCheck; + + public sealed record Empty : CsvImportCheck + { + public static Empty Instance { get; } = new(); + } + + public sealed record RowRefused(CsvRowFault Fault) : CsvImportCheck; +} + +public abstract record CsvImportOutcome +{ + private CsvImportOutcome() + { + } + + public sealed record Imported(long Rows) : CsvImportOutcome; + + // Nothing was written. Lines are those of the statement that failed, when the engine said which. + public sealed record RolledBack(CoreError Error, LineSpan? Lines) : CsvImportOutcome; + + // The engine has no transaction to undo it: WrittenRows rows before the failed lines stay in the table. + public sealed record PartlyWritten(CoreError Error, long WrittenRows, LineSpan? Lines) : CsvImportOutcome; + + // Stopped, or the connection went before the server answered: the table may hold some rows or none. + public sealed record Unknown(CoreError Error) : CsvImportOutcome; +} + +// A table's columns as a CSV import writes them; Run writes the import planned last, once. +public sealed class CsvImport : IDisposable +{ + private readonly Native.CsvImport _import; + + internal CsvImport(Native.CsvImport import) + { + _import = import; + Columns = [.. import.Columns().Select(column => new ImportColumn( + column.Name, + column.TypeName, + column.Nullable, + column.HasDefault, + column.ServerFilled))]; + } + + public IReadOnlyList Columns { get; } + + // The first rows, enough to judge the delimiter and the header. + public async Task PreviewAsync(string path, CsvOptions options, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(options); + cancellationToken.ThrowIfCancellationRequested(); + var native = Options(options); + var preview = await CoreCall.RunAsync(() => _import.Preview(path, native)) + .WaitAsync(cancellationToken) + .ConfigureAwait(false); + return new CsvPreview([.. preview.Headers], [.. preview.Rows.Select(row => (IReadOnlyList)[.. row])], preview.Truncated); + } + + // Per column, the field whose header names it, in any case; null leaves the column to its default. + public IReadOnlyList SuggestMapping(IReadOnlyList headers) + { + ArgumentNullException.ThrowIfNull(headers); + string[] native = [.. headers]; + return [.. CoreCall.Run(() => _import.SuggestMapping(native)).Select(field => field is { } index ? (int?)checked((int)index) : null)]; + } + + // Reads the whole file. Mapping has one field per column, null for none; the plan replaces any before it. + public async Task PlanAsync( + string path, + CsvOptions options, + IReadOnlyList mapping, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(mapping); + cancellationToken.ThrowIfCancellationRequested(); + var native = Options(options); + uint?[] fields = [.. mapping.Select(field => field is { } index ? (uint?)checked((uint)index) : null)]; + var check = await CoreCall.RunAsync(() => _import.Plan(path, native, fields)) + .WaitAsync(cancellationToken) + .ConfigureAwait(false); + return check switch + { + Native.CsvImportCheck.Ready ready => new CsvImportCheck.Ready( + Mapping.Count(ready.Rows), + [.. ready.Statements], + Mapping.Gate(ready.Gate)), + Native.CsvImportCheck.RowRefused refused => new CsvImportCheck.RowRefused(new CsvRowFault( + Mapping.Count(refused.Fault.Line), + refused.Fault.Column, + refused.Fault.Text, + refused.Fault.Reason)), + _ => CsvImportCheck.Empty.Instance, + }; + } + + // Confirmed says Safe Mode's question was answered; a level saved since the plan refuses before anything is sent. + public async Task RunAsync(bool confirmed, CancellationToken cancellationToken = default) + { + var outcome = await CoreCall.RunAsync(token => _import.Run(confirmed, token), cancellationToken).ConfigureAwait(false); + return outcome switch + { + Native.CsvImportOutcome.Imported imported => new CsvImportOutcome.Imported(Mapping.Count(imported.Rows)), + Native.CsvImportOutcome.RolledBack rolledBack => new CsvImportOutcome.RolledBack( + Mapping.Error(rolledBack.Error), + Lines(rolledBack.Lines)), + Native.CsvImportOutcome.PartlyWritten partly => new CsvImportOutcome.PartlyWritten( + Mapping.Error(partly.Error), + Mapping.Count(partly.WrittenRows), + Lines(partly.Lines)), + Native.CsvImportOutcome.Unknown unknown => new CsvImportOutcome.Unknown(Mapping.Error(unknown.Error)), + _ => throw new InvalidOperationException("The core reported an import outcome this build does not know."), + }; + } + + public void Dispose() => _import.Dispose(); + + private static LineSpan? Lines(Native.LineSpan? lines) => + lines is { } span ? new LineSpan(Mapping.Count(span.First), Mapping.Count(span.Last)) : null; + + private static Native.CsvReadOptions Options(CsvOptions options) => new( + options.Delimiter switch + { + CsvDelimiter.Semicolon => Native.CsvDelimiterTag.Semicolon, + CsvDelimiter.Tab => Native.CsvDelimiterTag.Tab, + CsvDelimiter.Pipe => Native.CsvDelimiterTag.Pipe, + _ => Native.CsvDelimiterTag.Comma, + }, + options.HasHeader, + options.NullText ?? string.Empty); +} diff --git a/windows/src/TablePro.Interop/DatabaseSession.Import.cs b/windows/src/TablePro.Interop/DatabaseSession.Import.cs new file mode 100644 index 0000000000..48d0e8a0dd --- /dev/null +++ b/windows/src/TablePro.Interop/DatabaseSession.Import.cs @@ -0,0 +1,15 @@ +namespace TablePro.Interop; + +public sealed partial class DatabaseSession +{ + // The table's columns as the server defines them now, for a CSV import into it. + public async Task OpenCsvImportAsync(TableName table, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(table); + var import = await CoreCall.RunAsync( + token => Handle.OpenCsvImport(Mapping.Table(table), token), + cancellationToken) + .ConfigureAwait(false); + return new CsvImport(import); + } +} diff --git a/windows/src/TablePro.Interop/Favourites.cs b/windows/src/TablePro.Interop/Favourites.cs new file mode 100644 index 0000000000..7b3f021bcb --- /dev/null +++ b/windows/src/TablePro.Interop/Favourites.cs @@ -0,0 +1,88 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +public enum DatabaseEnvironment +{ + Development, + Testing, + Production, + Unassigned, +} + +// Database and Schema are null where the engine has none. +public sealed record FavouriteTable(string? Database, string? Schema, string Name); + +public sealed record FavouriteDatabase(string Database, DatabaseEnvironment Environment); + +// The tables and databases a user marked, per connection, in the query history's database (core ADR 0017). +public sealed class Favourites : IDisposable +{ + private readonly Native.FavouriteStore _store; + + internal Favourites(Native.FavouriteStore store) + { + _store = store; + } + + public async Task> GetTablesAsync(Guid connectionId) + { + var tables = await CoreCall.RunAsync(() => _store.Tables(connectionId.ToString())).ConfigureAwait(false); + return [.. tables.Select(table => new FavouriteTable(table.Database, table.Schema, table.Name))]; + } + + // A table marked already stays as it is. + public Task AddTableAsync(Guid connectionId, FavouriteTable table) + { + ArgumentNullException.ThrowIfNull(table); + var native = Table(table); + return CoreCall.RunAsync(() => _store.AddTable(connectionId.ToString(), native)); + } + + public Task RemoveTableAsync(Guid connectionId, FavouriteTable table) + { + ArgumentNullException.ThrowIfNull(table); + var native = Table(table); + return CoreCall.RunAsync(() => _store.RemoveTable(connectionId.ToString(), native)); + } + + public async Task> GetDatabasesAsync(Guid connectionId) + { + var databases = await CoreCall.RunAsync(() => _store.Databases(connectionId.ToString())).ConfigureAwait(false); + return [.. databases.Select(database => new FavouriteDatabase(database.Database, Environment(database.Environment)))]; + } + + // Marks the database, or files a marked one under another environment. + public Task SetDatabaseAsync(Guid connectionId, string database, DatabaseEnvironment environment) + { + ArgumentNullException.ThrowIfNull(database); + var native = Environment(environment); + return CoreCall.RunAsync(() => _store.SetDatabase(connectionId.ToString(), database, native)); + } + + public Task RemoveDatabaseAsync(Guid connectionId, string database) + { + ArgumentNullException.ThrowIfNull(database); + return CoreCall.RunAsync(() => _store.RemoveDatabase(connectionId.ToString(), database)); + } + + public void Dispose() => _store.Dispose(); + + private static Native.FavouriteTableInfo Table(FavouriteTable table) => new(table.Database, table.Schema, table.Name); + + private static DatabaseEnvironment Environment(Native.DatabaseEnvironmentTag environment) => environment switch + { + Native.DatabaseEnvironmentTag.Development => DatabaseEnvironment.Development, + Native.DatabaseEnvironmentTag.Testing => DatabaseEnvironment.Testing, + Native.DatabaseEnvironmentTag.Production => DatabaseEnvironment.Production, + _ => DatabaseEnvironment.Unassigned, + }; + + private static Native.DatabaseEnvironmentTag Environment(DatabaseEnvironment environment) => environment switch + { + DatabaseEnvironment.Development => Native.DatabaseEnvironmentTag.Development, + DatabaseEnvironment.Testing => Native.DatabaseEnvironmentTag.Testing, + DatabaseEnvironment.Production => Native.DatabaseEnvironmentTag.Production, + _ => Native.DatabaseEnvironmentTag.Unassigned, + }; +} diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 597ac4d08b..6cad45aa26 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1143,6 +1143,70 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1623,7 +1687,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_queryhistorystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_favouritestore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1634,7 +1698,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_queryhistorystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_favouritestore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1645,7 +1709,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(ulong @ptr + ulong uniffi_tablepro_ffi_fn_method_favouritestore_add_table(ulong @ptr,RustBuffer @connectionId,RustBuffer @table ); #if NET8_0_OR_GREATER @@ -1656,7 +1720,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(ulong @ptr,RustBuffer @ids + ulong uniffi_tablepro_ffi_fn_method_favouritestore_databases(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -1667,7 +1731,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_record(ulong @ptr,ulong @session,RustBuffer @run + ulong uniffi_tablepro_ffi_fn_method_favouritestore_remove_database(ulong @ptr,RustBuffer @connectionId,RustBuffer @database ); #if NET8_0_OR_GREATER @@ -1678,7 +1742,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_search(ulong @ptr,RustBuffer @text,RustBuffer @connectionId,RustBuffer @after,uint @limit + ulong uniffi_tablepro_ffi_fn_method_favouritestore_remove_table(ulong @ptr,RustBuffer @connectionId,RustBuffer @table ); #if NET8_0_OR_GREATER @@ -1689,7 +1753,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_connectionlibrary(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_favouritestore_set_database(ulong @ptr,RustBuffer @connectionId,RustBuffer @database,RustBuffer @environment ); #if NET8_0_OR_GREATER @@ -1700,7 +1764,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_connectionlibrary(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_favouritestore_tables(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -1711,7 +1775,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_apply_cloud_pull(ulong @ptr,RustBuffer @pull + ulong uniffi_tablepro_ffi_fn_clone_queryhistorystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1722,7 +1786,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_cloud_edits(ulong @ptr,RustBuffer @base + void uniffi_tablepro_ffi_fn_free_queryhistorystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1733,7 +1797,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_add_favorites(ulong @ptr,RustBuffer @ids,RustBuffer @before + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(ulong @ptr ); #if NET8_0_OR_GREATER @@ -1744,7 +1808,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_create_group(ulong @ptr,RustBuffer @name,RustBuffer @parentId + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(ulong @ptr,RustBuffer @ids ); #if NET8_0_OR_GREATER @@ -1755,7 +1819,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_create_tag(ulong @ptr,RustBuffer @name,RustBuffer @color + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_export(ulong @ptr,RustBuffer @ids,RustBuffer @format,RustBuffer @path ); #if NET8_0_OR_GREATER @@ -1766,7 +1830,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_delete(ulong @ptr,RustBuffer @id + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_favourites(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1777,7 +1841,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_group(ulong @ptr,RustBuffer @id + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_record(ulong @ptr,ulong @session,RustBuffer @run ); #if NET8_0_OR_GREATER @@ -1788,7 +1852,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_tag(ulong @ptr,RustBuffer @id + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_saved_queries(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1799,7 +1863,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_import_file(ulong @ptr,RustBuffer @path + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_search(ulong @ptr,RustBuffer @text,RustBuffer @connectionId,RustBuffer @after,uint @limit ); #if NET8_0_OR_GREATER @@ -1810,7 +1874,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_move_groups(ulong @ptr,RustBuffer @ids,RustBuffer @parentId,RustBuffer @before + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_set_pinned(ulong @ptr,long @id,sbyte @pinned ); #if NET8_0_OR_GREATER @@ -1821,7 +1885,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_move_to_group(ulong @ptr,RustBuffer @ids,RustBuffer @groupId,RustBuffer @before + ulong uniffi_tablepro_ffi_fn_clone_csvimport(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1832,7 +1896,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_remove_favorites(ulong @ptr,RustBuffer @ids + void uniffi_tablepro_ffi_fn_free_csvimport(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1843,7 +1907,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_connection(ulong @ptr,RustBuffer @id,RustBuffer @name + RustBuffer uniffi_tablepro_ffi_fn_method_csvimport_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1854,7 +1918,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_group(ulong @ptr,RustBuffer @id,RustBuffer @name + ulong uniffi_tablepro_ffi_fn_method_csvimport_plan(ulong @ptr,RustBuffer @path,RustBuffer @options,RustBuffer @mapping ); #if NET8_0_OR_GREATER @@ -1865,7 +1929,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_save(ulong @ptr,RustBuffer @record,RustBuffer @secrets + ulong uniffi_tablepro_ffi_fn_method_csvimport_preview(ulong @ptr,RustBuffer @path,RustBuffer @options ); #if NET8_0_OR_GREATER @@ -1876,7 +1940,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_set_favorite(ulong @ptr,RustBuffer @id,sbyte @favorite + ulong uniffi_tablepro_ffi_fn_method_csvimport_run(ulong @ptr,sbyte @confirmed,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -1887,7 +1951,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_snapshot(ulong @ptr + RustBuffer uniffi_tablepro_ffi_fn_method_csvimport_suggest_mapping(ulong @ptr,RustBuffer @headers,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1898,7 +1962,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_tag_connections(ulong @ptr,RustBuffer @ids,RustBuffer @tagId,sbyte @tagged + ulong uniffi_tablepro_ffi_fn_clone_connectionlibrary(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1909,7 +1973,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_update_tag(ulong @ptr,RustBuffer @id,RustBuffer @name,RustBuffer @color + void uniffi_tablepro_ffi_fn_free_connectionlibrary(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1920,7 +1984,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_resultset(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_apply_cloud_pull(ulong @ptr,RustBuffer @pull ); #if NET8_0_OR_GREATER @@ -1931,7 +1995,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_resultset(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_cloud_edits(ulong @ptr,RustBuffer @base ); #if NET8_0_OR_GREATER @@ -1942,7 +2006,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_resultset_share_masking(ulong @ptr,uint @visibleColumns,uint @maxRows + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_add_favorites(ulong @ptr,RustBuffer @ids,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -1953,7 +2017,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_resultset_share_preview(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_create_group(ulong @ptr,RustBuffer @name,RustBuffer @parentId ); #if NET8_0_OR_GREATER @@ -1964,7 +2028,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_resultset_share_summary(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_create_tag(ulong @ptr,RustBuffer @name,RustBuffer @color ); #if NET8_0_OR_GREATER @@ -1975,7 +2039,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_text(ulong @ptr,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_delete(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -1986,7 +2050,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_resultset_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_group(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -1997,7 +2061,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint uniffi_tablepro_ffi_fn_method_resultset_index(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_tag(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -2008,7 +2072,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte uniffi_tablepro_ffi_fn_method_resultset_is_finished(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_duplicate(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2019,7 +2083,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_resultset_open_cursor(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_export_file(ulong @ptr,RustBuffer @path ); #if NET8_0_OR_GREATER @@ -2030,7 +2094,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_resultset_row_count(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_import_file(ulong @ptr,RustBuffer @path ); #if NET8_0_OR_GREATER @@ -2041,7 +2105,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_resultset_sorted(ulong @ptr,uint @column,sbyte @ascending,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_move_groups(ulong @ptr,RustBuffer @ids,RustBuffer @parentId,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -2052,7 +2116,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_rowsave(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_move_to_group(ulong @ptr,RustBuffer @ids,RustBuffer @groupId,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -2063,7 +2127,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_rowsave(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_remove_favorites(ulong @ptr,RustBuffer @ids ); #if NET8_0_OR_GREATER @@ -2074,7 +2138,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_rowsave_gate(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_connection(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2085,7 +2149,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte uniffi_tablepro_ffi_fn_method_rowsave_is_empty(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_group(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2096,7 +2160,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_rowsave_run(ulong @ptr,sbyte @confirmed,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_save(ulong @ptr,RustBuffer @record,RustBuffer @secrets ); #if NET8_0_OR_GREATER @@ -2107,7 +2171,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_rowsave_statements(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_set_favorite(ulong @ptr,RustBuffer @id,sbyte @favorite ); #if NET8_0_OR_GREATER @@ -2118,7 +2182,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_tableeditor(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_snapshot(ulong @ptr ); #if NET8_0_OR_GREATER @@ -2129,7 +2193,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_tableeditor(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_tag_connections(ulong @ptr,RustBuffer @ids,RustBuffer @tagId,sbyte @tagged ); #if NET8_0_OR_GREATER @@ -2140,7 +2204,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_method_tableeditor_check(ulong @ptr,uint @column,RustBuffer @edit,sbyte @newRow,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_update_tag(ulong @ptr,RustBuffer @id,RustBuffer @name,RustBuffer @color ); #if NET8_0_OR_GREATER @@ -2151,7 +2215,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_resultset(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2162,7 +2226,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_edit_start(ulong @ptr,ulong @rows,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_resultset(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2173,7 +2237,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_lock(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_resultset_share_masking(ulong @ptr,uint @visibleColumns,uint @maxRows ); #if NET8_0_OR_GREATER @@ -2184,7 +2248,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_lock_for(ulong @ptr,ulong @rows,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_resultset_share_preview(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns ); #if NET8_0_OR_GREATER @@ -2195,7 +2259,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tableeditor_plan(ulong @ptr,ulong @rows,RustBuffer @edits,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_resultset_share_summary(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns ); #if NET8_0_OR_GREATER @@ -2206,7 +2270,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_queryrun(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_text(ulong @ptr,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2217,7 +2281,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_queryrun(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_resultset_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2228,7 +2292,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_method_queryrun_cancel(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + uint uniffi_tablepro_ffi_fn_method_resultset_index(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2239,7 +2303,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_queryrun_drain_events(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + sbyte uniffi_tablepro_ffi_fn_method_resultset_is_finished(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2250,7 +2314,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_queryrun_outcome(ulong @ptr + ulong uniffi_tablepro_ffi_fn_method_resultset_open_cursor(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2261,7 +2325,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_method_queryrun_release_set(ulong @ptr,uint @index,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_resultset_row_count(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2272,7 +2336,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_queryrun_result_set(ulong @ptr,uint @index,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_resultset_sorted(ulong @ptr,uint @column,sbyte @ascending,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2283,7 +2347,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_databasesession(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_rowsave(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2294,7 +2358,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_databasesession(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_rowsave(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2305,7 +2369,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_export_rows(ulong @ptr,ulong @rows,uint @visibleColumns,RustBuffer @format,RustBuffer @table,RustBuffer @path,RustBuffer @cancel + RustBuffer uniffi_tablepro_ffi_fn_method_rowsave_gate(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2316,7 +2380,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_export_table(ulong @ptr,RustBuffer @table,RustBuffer @sort,RustBuffer @filter,RustBuffer @format,RustBuffer @path,RustBuffer @cancel + sbyte uniffi_tablepro_ffi_fn_method_rowsave_is_empty(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2327,7 +2391,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_close(ulong @ptr + ulong uniffi_tablepro_ffi_fn_method_rowsave_run(ulong @ptr,sbyte @confirmed,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2338,7 +2402,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_columns(ulong @ptr,RustBuffer @table,RustBuffer @cancel + RustBuffer uniffi_tablepro_ffi_fn_method_rowsave_statements(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2349,7 +2413,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_driver_id(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_tableeditor(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2360,7 +2424,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_filter_choices(ulong @ptr,RustBuffer @table,RustBuffer @cancel + void uniffi_tablepro_ffi_fn_free_tableeditor(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2371,7 +2435,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_gate_run(ulong @ptr,RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_method_tableeditor_check(ulong @ptr,uint @column,RustBuffer @edit,sbyte @newRow,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2382,7 +2446,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_health(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2393,7 +2457,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_health_change(ulong @ptr,RustBuffer @seen,RustBuffer @cancel + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_edit_start(ulong @ptr,ulong @rows,ulong @row,uint @column,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2404,7 +2468,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_id(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_lock(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2415,7 +2479,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_name(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_lock_for(ulong @ptr,ulong @rows,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2426,7 +2490,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_object_definition(ulong @ptr,RustBuffer @object,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_tableeditor_plan(ulong @ptr,ulong @rows,RustBuffer @edits,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2437,7 +2501,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_clone_queryrun(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2448,7 +2512,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_open_editor(ulong @ptr,RustBuffer @cancel + void uniffi_tablepro_ffi_fn_free_queryrun(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2459,7 +2523,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte uniffi_tablepro_ffi_fn_method_databasesession_read_only(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_method_queryrun_cancel(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2470,7 +2534,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_read_table_page(ulong @ptr,RustBuffer @table,RustBuffer @sort,RustBuffer @filter,ulong @limit,ulong @offset,ulong @listener,RustBuffer @cancel + RustBuffer uniffi_tablepro_ffi_fn_method_queryrun_drain_events(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2481,7 +2545,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_method_databasesession_reconnect(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_queryrun_outcome(ulong @ptr ); #if NET8_0_OR_GREATER @@ -2492,7 +2556,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel + void uniffi_tablepro_ffi_fn_method_queryrun_release_set(ulong @ptr,uint @index,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2503,7 +2567,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_schemas(ulong @ptr,RustBuffer @cancel + RustBuffer uniffi_tablepro_ffi_fn_method_queryrun_result_set(ulong @ptr,uint @index,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2514,7 +2578,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(ulong @ptr,RustBuffer @level,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_savedquerystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2525,7 +2589,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_sorted_query(ulong @ptr,RustBuffer @sql,RustBuffer @columns,uint @column,sbyte @ascending,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_savedquerystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2536,7 +2600,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_statement_at(ulong @ptr,RustBuffer @sql,uint @caret,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_create_folder(ulong @ptr,RustBuffer @connectionId,RustBuffer @name,RustBuffer @parentId ); #if NET8_0_OR_GREATER @@ -2547,7 +2611,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_table_editor(ulong @ptr,RustBuffer @table,sbyte @refresh,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_delete(ulong @ptr,long @id ); #if NET8_0_OR_GREATER @@ -2558,7 +2622,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(ulong @ptr,RustBuffer @table,RustBuffer @filter,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_delete_folder(ulong @ptr,long @id ); #if NET8_0_OR_GREATER @@ -2569,7 +2633,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(ulong @ptr,RustBuffer @table,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_delete_for_connection(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -2580,7 +2644,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_table_structure(ulong @ptr,RustBuffer @table,RustBuffer @kind,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_move_folder(ulong @ptr,long @id,RustBuffer @parentId ); #if NET8_0_OR_GREATER @@ -2591,7 +2655,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_tablepageread(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_move_query(ulong @ptr,long @id,RustBuffer @folderId,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -2602,7 +2666,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_tablepageread(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_rename(ulong @ptr,long @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2613,7 +2677,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte uniffi_tablepro_ffi_fn_method_tablepageread_can_seek(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_rename_folder(ulong @ptr,long @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2624,7 +2688,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablepageread_run(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_save(ulong @ptr,RustBuffer @draft,sbyte @replace ); #if NET8_0_OR_GREATER @@ -2635,7 +2699,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tablepageread_view_sql(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_set_keyword(ulong @ptr,long @id,RustBuffer @keyword ); #if NET8_0_OR_GREATER @@ -2646,7 +2710,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint uniffi_tablepro_ffi_fn_method_tablepageread_visible_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_snapshot(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -2657,7 +2721,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_accountlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAccountListener*/ @vtable + ulong uniffi_tablepro_ffi_fn_clone_databasesession(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2668,7 +2732,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostbrowser(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostBrowser*/ @vtable + void uniffi_tablepro_ffi_fn_free_databasesession(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2679,7 +2743,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_databasesession_export_rows(ulong @ptr,ulong @rows,uint @visibleColumns,RustBuffer @format,RustBuffer @table,RustBuffer @path,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2690,7 +2754,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_databasesession_export_table(ulong @ptr,RustBuffer @table,RustBuffer @sort,RustBuffer @filter,RustBuffer @format,RustBuffer @path,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2701,7 +2765,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_databasesession_open_csv_import(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2712,7 +2776,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_scan_columns_for_secrets(RustBuffer @names,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_databasesession_close(ulong @ptr ); #if NET8_0_OR_GREATER @@ -2723,7 +2787,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_secrets(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_databasesession_columns(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2734,7 +2798,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_share_token_from_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_driver_id(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2745,7 +2809,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_databasesession_filter_choices(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2756,7 +2820,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_personal_data(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_gate_run(ulong @ptr,RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2767,7 +2831,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_health(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2778,7 +2842,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_databasesession_health_change(ulong @ptr,RustBuffer @seen,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2789,7 +2853,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_id(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2800,7 +2864,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_name(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2811,7 +2875,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_databasesession_object_definition(ulong @ptr,RustBuffer @object,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2822,7 +2886,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2833,7 +2897,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_open_editor(ulong @ptr,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2844,7 +2908,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - byte ffi_tablepro_ffi_rust_future_complete_u8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + sbyte uniffi_tablepro_ffi_fn_method_databasesession_read_only(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2855,7 +2919,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i8(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_databasesession_read_table_page(ulong @ptr,RustBuffer @table,RustBuffer @sort,RustBuffer @filter,ulong @limit,ulong @offset,ulong @listener,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2866,7 +2930,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i8(ulong @handle + void uniffi_tablepro_ffi_fn_method_databasesession_reconnect(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2877,7 +2941,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2888,7 +2952,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte ffi_tablepro_ffi_rust_future_complete_i8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_databasesession_schemas(ulong @ptr,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2899,7 +2963,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u16(ulong @handle,IntPtr @callback,ulong @callbackData + sbyte uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(ulong @ptr,RustBuffer @level,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2910,7 +2974,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u16(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_sorted_query(ulong @ptr,RustBuffer @sql,RustBuffer @columns,uint @column,sbyte @ascending,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2921,7 +2985,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u16(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_statement_at(ulong @ptr,RustBuffer @sql,uint @caret,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2932,7 +2996,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort ffi_tablepro_ffi_rust_future_complete_u16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_editor(ulong @ptr,RustBuffer @table,sbyte @refresh,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2943,7 +3007,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i16(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(ulong @ptr,RustBuffer @table,RustBuffer @filter,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2954,7 +3018,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2965,7 +3029,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_structure(ulong @ptr,RustBuffer @table,RustBuffer @kind,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2976,7 +3040,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - short ffi_tablepro_ffi_rust_future_complete_i16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_tablepageread(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2987,7 +3051,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u32(ulong @handle,IntPtr @callback,ulong @callbackData + void uniffi_tablepro_ffi_fn_free_tablepageread(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2998,7 +3062,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u32(ulong @handle + sbyte uniffi_tablepro_ffi_fn_method_tablepageread_can_seek(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3009,7 +3073,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u32(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_tablepageread_run(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3020,7 +3084,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint ffi_tablepro_ffi_rust_future_complete_u32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_tablepageread_view_sql(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3031,7 +3095,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i32(ulong @handle,IntPtr @callback,ulong @callbackData + uint uniffi_tablepro_ffi_fn_method_tablepageread_visible_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3042,7 +3106,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i32(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_accountlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAccountListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -3053,7 +3117,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i32(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostbrowser(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostBrowser*/ @vtable ); #if NET8_0_OR_GREATER @@ -3064,7 +3128,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - int ffi_tablepro_ffi_rust_future_complete_i32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable ); #if NET8_0_OR_GREATER @@ -3075,7 +3139,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u64(ulong @handle,IntPtr @callback,ulong @callbackData + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable ); #if NET8_0_OR_GREATER @@ -3086,7 +3150,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u64(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -3097,7 +3161,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u64(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_func_scan_columns_for_secrets(RustBuffer @names,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3108,7 +3172,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong ffi_tablepro_ffi_rust_future_complete_u64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_secrets(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3119,7 +3183,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i64(ulong @handle,IntPtr @callback,ulong @callbackData + RustBuffer uniffi_tablepro_ffi_fn_func_share_token_from_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3130,7 +3194,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i64(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_func_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3141,7 +3205,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i64(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_personal_data(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3152,7 +3216,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - long ffi_tablepro_ffi_rust_future_complete_i64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer ffi_tablepro_ffi_rustbuffer_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3163,7 +3227,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_f32(ulong @handle,IntPtr @callback,ulong @callbackData + RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3174,7 +3238,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_f32(ulong @handle + void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3185,7 +3249,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_f32(ulong @handle + RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3196,7 +3260,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - float ffi_tablepro_ffi_rust_future_complete_f32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void ffi_tablepro_ffi_rust_future_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3207,7 +3271,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_f64(ulong @handle,IntPtr @callback,ulong @callbackData + void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3218,7 +3282,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_f64(ulong @handle + void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3229,7 +3293,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_f64(ulong @handle + byte ffi_tablepro_ffi_rust_future_complete_u8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3240,7 +3304,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - double ffi_tablepro_ffi_rust_future_complete_f64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void ffi_tablepro_ffi_rust_future_poll_i8(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3251,7 +3315,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_rust_buffer(ulong @handle,IntPtr @callback,ulong @callbackData + void ffi_tablepro_ffi_rust_future_cancel_i8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3262,7 +3326,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_rust_buffer(ulong @handle + void ffi_tablepro_ffi_rust_future_free_i8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3273,7 +3337,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_rust_buffer(ulong @handle + sbyte ffi_tablepro_ffi_rust_future_complete_i8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3284,7 +3348,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rust_future_complete_rust_buffer(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void ffi_tablepro_ffi_rust_future_poll_u16(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3295,7 +3359,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_void(ulong @handle,IntPtr @callback,ulong @callbackData + void ffi_tablepro_ffi_rust_future_cancel_u16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3306,7 +3370,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_void(ulong @handle + void ffi_tablepro_ffi_rust_future_free_u16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3317,7 +3381,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_void(ulong @handle + ushort ffi_tablepro_ffi_rust_future_complete_u16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3328,7 +3392,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_complete_void(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void ffi_tablepro_ffi_rust_future_poll_i16(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3339,7 +3403,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets( + void ffi_tablepro_ffi_rust_future_cancel_i16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3350,7 +3414,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets( + void ffi_tablepro_ffi_rust_future_free_i16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3361,7 +3425,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_share_token_from_link( + short ffi_tablepro_ffi_rust_future_complete_i16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3372,7 +3436,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_parse_connection_url( + void ffi_tablepro_ffi_rust_future_poll_u32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3383,7 +3447,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data( + void ffi_tablepro_ffi_rust_future_cancel_u32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3394,7 +3458,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_devices( + void ffi_tablepro_ffi_rust_future_free_u32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3405,7 +3469,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( + uint ffi_tablepro_ffi_rust_future_complete_u32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3416,7 +3480,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_profile( + void ffi_tablepro_ffi_rust_future_poll_i32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3427,7 +3491,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh( + void ffi_tablepro_ffi_rust_future_cancel_i32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3438,7 +3502,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit( + void ffi_tablepro_ffi_rust_future_free_i32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3449,7 +3513,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_remove_device( + int ffi_tablepro_ffi_rust_future_complete_i32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3460,7 +3524,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_in( + void ffi_tablepro_ffi_rust_future_poll_u64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3471,7 +3535,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_out( + void ffi_tablepro_ffi_rust_future_cancel_u64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3482,7 +3546,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_status( + void ffi_tablepro_ffi_rust_future_free_u64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3493,7 +3557,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_create_share( + ulong ffi_tablepro_ffi_rust_future_complete_u64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3504,7 +3568,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_extend_share( + void ffi_tablepro_ffi_rust_future_poll_i64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3515,7 +3579,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared( + void ffi_tablepro_ffi_rust_future_cancel_i64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3526,7 +3590,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_list_shares( + void ffi_tablepro_ffi_rust_future_free_i64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3537,7 +3601,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share( + long ffi_tablepro_ffi_rust_future_complete_i64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3548,7 +3612,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_share_limits( + void ffi_tablepro_ffi_rust_future_poll_f32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3559,7 +3623,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_canceltoken_cancel( + void ffi_tablepro_ffi_rust_future_cancel_f32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3570,7 +3634,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_canceltoken_is_cancelled( + void ffi_tablepro_ffi_rust_future_free_f32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3581,7 +3645,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_open_account( + float ffi_tablepro_ffi_rust_future_complete_f32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3592,7 +3656,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_connect_saved( + void ffi_tablepro_ffi_rust_future_poll_f64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3603,7 +3667,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_drivers( + void ffi_tablepro_ffi_rust_future_cancel_f64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3614,7 +3678,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_history( + void ffi_tablepro_ffi_rust_future_free_f64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3625,7 +3689,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_library( + double ffi_tablepro_ffi_rust_future_complete_f64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3636,7 +3700,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_open_file( + void ffi_tablepro_ffi_rust_future_poll_rust_buffer(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3647,7 +3711,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_test_connection( + void ffi_tablepro_ffi_rust_future_cancel_rust_buffer(ulong @handle ); #if NET8_0_OR_GREATER @@ -3658,7 +3722,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_forget_changed_host_key( + void ffi_tablepro_ffi_rust_future_free_rust_buffer(ulong @handle ); #if NET8_0_OR_GREATER @@ -3669,7 +3733,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_close( + RustBuffer ffi_tablepro_ffi_rust_future_complete_rust_buffer(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3680,7 +3744,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_is_lost( + void ffi_tablepro_ffi_rust_future_poll_void(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3691,7 +3755,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_run( + void ffi_tablepro_ffi_rust_future_cancel_void(ulong @handle ); #if NET8_0_OR_GREATER @@ -3702,7 +3766,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_use_database( + void ffi_tablepro_ffi_rust_future_free_void(ulong @handle ); #if NET8_0_OR_GREATER @@ -3713,7 +3777,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear( + void ffi_tablepro_ffi_rust_future_complete_void(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3724,7 +3788,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete( + ushort uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets( ); #if NET8_0_OR_GREATER @@ -3735,7 +3799,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_record( + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets( ); #if NET8_0_OR_GREATER @@ -3746,7 +3810,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_search( + ushort uniffi_tablepro_ffi_checksum_func_share_token_from_link( ); #if NET8_0_OR_GREATER @@ -3757,7 +3821,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_apply_cloud_pull( + ushort uniffi_tablepro_ffi_checksum_func_parse_connection_url( ); #if NET8_0_OR_GREATER @@ -3768,7 +3832,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_cloud_edits( + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data( ); #if NET8_0_OR_GREATER @@ -3779,7 +3843,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_add_favorites( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_devices( ); #if NET8_0_OR_GREATER @@ -3790,7 +3854,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_group( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( ); #if NET8_0_OR_GREATER @@ -3801,7 +3865,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_tag( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_profile( ); #if NET8_0_OR_GREATER @@ -3812,7 +3876,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh( ); #if NET8_0_OR_GREATER @@ -3823,7 +3887,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_group( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit( ); #if NET8_0_OR_GREATER @@ -3834,7 +3898,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_remove_device( ); #if NET8_0_OR_GREATER @@ -3845,7 +3909,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_import_file( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_in( ); #if NET8_0_OR_GREATER @@ -3856,7 +3920,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_groups( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_out( ); #if NET8_0_OR_GREATER @@ -3867,7 +3931,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_to_group( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_status( ); #if NET8_0_OR_GREATER @@ -3878,7 +3942,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_remove_favorites( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_create_share( ); #if NET8_0_OR_GREATER @@ -3889,7 +3953,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_connection( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_extend_share( ); #if NET8_0_OR_GREATER @@ -3900,7 +3964,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_group( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared( ); #if NET8_0_OR_GREATER @@ -3911,7 +3975,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_list_shares( ); #if NET8_0_OR_GREATER @@ -3922,7 +3986,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_favorite( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share( ); #if NET8_0_OR_GREATER @@ -3933,7 +3997,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_snapshot( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_share_limits( ); #if NET8_0_OR_GREATER @@ -3944,7 +4008,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_tag_connections( + ushort uniffi_tablepro_ffi_checksum_method_canceltoken_cancel( ); #if NET8_0_OR_GREATER @@ -3955,7 +4019,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag( + ushort uniffi_tablepro_ffi_checksum_method_canceltoken_is_cancelled( ); #if NET8_0_OR_GREATER @@ -3966,7 +4030,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_share_masking( + ushort uniffi_tablepro_ffi_checksum_method_core_open_account( ); #if NET8_0_OR_GREATER @@ -3977,7 +4041,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_share_preview( + ushort uniffi_tablepro_ffi_checksum_method_core_connect_saved( ); #if NET8_0_OR_GREATER @@ -3988,7 +4052,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_share_summary( + ushort uniffi_tablepro_ffi_checksum_method_core_drivers( ); #if NET8_0_OR_GREATER @@ -3999,7 +4063,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text( + ushort uniffi_tablepro_ffi_checksum_method_core_history( ); #if NET8_0_OR_GREATER @@ -4010,7 +4074,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_columns( + ushort uniffi_tablepro_ffi_checksum_method_core_library( ); #if NET8_0_OR_GREATER @@ -4021,7 +4085,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_index( + ushort uniffi_tablepro_ffi_checksum_method_core_open_file( ); #if NET8_0_OR_GREATER @@ -4032,7 +4096,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_is_finished( + ushort uniffi_tablepro_ffi_checksum_method_core_test_connection( ); #if NET8_0_OR_GREATER @@ -4043,7 +4107,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_open_cursor( + ushort uniffi_tablepro_ffi_checksum_method_core_forget_changed_host_key( ); #if NET8_0_OR_GREATER @@ -4054,7 +4118,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_row_count( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_close( ); #if NET8_0_OR_GREATER @@ -4065,7 +4129,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_sorted( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_is_lost( ); #if NET8_0_OR_GREATER @@ -4076,7 +4140,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_gate( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_run( ); #if NET8_0_OR_GREATER @@ -4087,7 +4151,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_is_empty( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_use_database( ); #if NET8_0_OR_GREATER @@ -4098,7 +4162,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_run( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_add_table( ); #if NET8_0_OR_GREATER @@ -4109,7 +4173,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_statements( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_databases( ); #if NET8_0_OR_GREATER @@ -4120,7 +4184,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_check( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_remove_database( ); #if NET8_0_OR_GREATER @@ -4131,7 +4195,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_columns( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_remove_table( ); #if NET8_0_OR_GREATER @@ -4142,7 +4206,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_set_database( ); #if NET8_0_OR_GREATER @@ -4153,7 +4217,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_tables( ); #if NET8_0_OR_GREATER @@ -4164,7 +4228,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear( ); #if NET8_0_OR_GREATER @@ -4175,7 +4239,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_plan( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete( ); #if NET8_0_OR_GREATER @@ -4186,7 +4250,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_cancel( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_export( ); #if NET8_0_OR_GREATER @@ -4197,7 +4261,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_drain_events( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites( ); #if NET8_0_OR_GREATER @@ -4208,7 +4272,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_record( ); #if NET8_0_OR_GREATER @@ -4219,7 +4283,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_release_set( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_saved_queries( ); #if NET8_0_OR_GREATER @@ -4230,7 +4294,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_result_set( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_search( ); #if NET8_0_OR_GREATER @@ -4241,7 +4305,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_rows( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_set_pinned( ); #if NET8_0_OR_GREATER @@ -4252,7 +4316,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_table( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_columns( ); #if NET8_0_OR_GREATER @@ -4263,7 +4327,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_close( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_plan( ); #if NET8_0_OR_GREATER @@ -4274,7 +4338,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_columns( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_preview( ); #if NET8_0_OR_GREATER @@ -4285,7 +4349,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_driver_id( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_run( ); #if NET8_0_OR_GREATER @@ -4296,7 +4360,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_filter_choices( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_suggest_mapping( ); #if NET8_0_OR_GREATER @@ -4307,7 +4371,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_gate_run( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_apply_cloud_pull( ); #if NET8_0_OR_GREATER @@ -4318,7 +4382,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_health( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_cloud_edits( ); #if NET8_0_OR_GREATER @@ -4329,7 +4393,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_health_change( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_add_favorites( ); #if NET8_0_OR_GREATER @@ -4340,7 +4404,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_id( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_group( ); #if NET8_0_OR_GREATER @@ -4351,7 +4415,711 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_name( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_tag( + ); + + #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_connectionlibrary_delete( + ); + + #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_connectionlibrary_delete_group( + ); + + #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_connectionlibrary_delete_tag( + ); + + #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_connectionlibrary_duplicate( + ); + + #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_connectionlibrary_export_file( + ); + + #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_connectionlibrary_import_file( + ); + + #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_connectionlibrary_move_groups( + ); + + #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_connectionlibrary_move_to_group( + ); + + #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_connectionlibrary_remove_favorites( + ); + + #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_connectionlibrary_rename_connection( + ); + + #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_connectionlibrary_rename_group( + ); + + #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_connectionlibrary_save( + ); + + #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_connectionlibrary_set_favorite( + ); + + #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_connectionlibrary_snapshot( + ); + + #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_connectionlibrary_tag_connections( + ); + + #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_connectionlibrary_update_tag( + ); + + #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_resultset_share_masking( + ); + + #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_resultset_share_preview( + ); + + #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_resultset_share_summary( + ); + + #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_resultset_cell_text( + ); + + #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_resultset_columns( + ); + + #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_resultset_index( + ); + + #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_resultset_is_finished( + ); + + #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_resultset_open_cursor( + ); + + #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_resultset_row_count( + ); + + #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_resultset_sorted( + ); + + #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_rowsave_gate( + ); + + #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_rowsave_is_empty( + ); + + #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_rowsave_run( + ); + + #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_rowsave_statements( + ); + + #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_tableeditor_check( + ); + + #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_tableeditor_columns( + ); + + #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_tableeditor_edit_start( + ); + + #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_tableeditor_lock( + ); + + #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_tableeditor_lock_for( + ); + + #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_tableeditor_plan( + ); + + #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_queryrun_cancel( + ); + + #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_queryrun_drain_events( + ); + + #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_queryrun_outcome( + ); + + #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_queryrun_release_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_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_create_folder( + ); + + #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_delete( + ); + + #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_delete_folder( + ); + + #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_delete_for_connection( + ); + + #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_move_folder( + ); + + #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_move_query( + ); + + #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_rename( + ); + + #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_rename_folder( + ); + + #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_save( + ); + + #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_set_keyword( + ); + + #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_snapshot( + ); + + #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_databasesession_export_rows( + ); + + #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_databasesession_export_table( + ); + + #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_databasesession_open_csv_import( + ); + + #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_databasesession_close( + ); + + #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_databasesession_columns( + ); + + #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_databasesession_driver_id( + ); + + #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_databasesession_filter_choices( + ); + + #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_databasesession_gate_run( + ); + + #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_databasesession_health( + ); + + #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_databasesession_health_change( + ); + + #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_databasesession_id( + ); + + #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_databasesession_name( ); #if NET8_0_OR_GREATER @@ -4952,6 +5720,42 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryeditor_use_database` checksum `41238`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_add_table(); + if (checksum != 20993) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_add_table` checksum `20993`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_databases(); + if (checksum != 28125) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_databases` checksum `28125`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_remove_database(); + if (checksum != 21763) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_remove_database` checksum `21763`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_remove_table(); + if (checksum != 57779) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_remove_table` checksum `57779`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_set_database(); + if (checksum != 55747) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_set_database` checksum `55747`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_favouritestore_tables(); + if (checksum != 53725) { + 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_queryhistorystore_clear(); if (checksum != 34195) { @@ -4964,18 +5768,72 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete` checksum `49029`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_export(); + if (checksum != 44920) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_export` checksum `44920`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites(); + if (checksum != 6052) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites` checksum `6052`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_record(); if (checksum != 56193) { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_record` checksum `56193`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_saved_queries(); + if (checksum != 23109) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_saved_queries` checksum `23109`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_search(); if (checksum != 1588) { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_search` checksum `1588`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_set_pinned(); + if (checksum != 35139) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryhistorystore_set_pinned` checksum `35139`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_columns(); + if (checksum != 53368) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_columns` checksum `53368`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_plan(); + if (checksum != 47204) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_plan` checksum `47204`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_preview(); + if (checksum != 61172) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_preview` checksum `61172`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_run(); + if (checksum != 51215) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_run` checksum `51215`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_suggest_mapping(); + if (checksum != 55321) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_suggest_mapping` checksum `55321`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_connectionlibrary_apply_cloud_pull(); if (checksum != 50423) { @@ -5019,9 +5877,21 @@ static void uniffiCheckApiChecksums() { } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag(); - if (checksum != 12898) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag` checksum `12898`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag(); + if (checksum != 12898) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag` checksum `12898`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_connectionlibrary_duplicate(); + if (checksum != 33545) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_connectionlibrary_duplicate` checksum `33545`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_connectionlibrary_export_file(); + if (checksum != 30567) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_connectionlibrary_export_file` checksum `30567`, library returned `{checksum}`"); } } { @@ -5240,6 +6110,72 @@ 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_create_folder(); + if (checksum != 59321) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_create_folder` checksum `59321`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_delete(); + if (checksum != 53352) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_delete` checksum `53352`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_folder(); + if (checksum != 36458) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_folder` checksum `36458`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_for_connection(); + if (checksum != 64092) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_for_connection` checksum `64092`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_move_folder(); + if (checksum != 25305) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_move_folder` checksum `25305`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_move_query(); + if (checksum != 54680) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_move_query` checksum `54680`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_rename(); + if (checksum != 12960) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_rename` checksum `12960`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_rename_folder(); + if (checksum != 18150) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_rename_folder` checksum `18150`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_save(); + if (checksum != 6222) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_save` checksum `6222`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_set_keyword(); + if (checksum != 46468) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_set_keyword` checksum `46468`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_snapshot(); + if (checksum != 6061) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_snapshot` checksum `6061`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_export_rows(); if (checksum != 61480) { @@ -5252,6 +6188,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_export_table` checksum `50830`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_open_csv_import(); + if (checksum != 47282) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_open_csv_import` checksum `47282`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_close(); if (checksum != 35830) { @@ -6309,6 +7251,10 @@ internal interface IConnectionLibrary { /// Task DeleteTag(string @id); /// + Task Duplicate(string @id, string @name); + /// + Task ExportFile(string @path); + /// Task ImportFile(string @path); /// Task MoveGroups(string[] @ids, string? @parentId, string? @before); @@ -6576,6 +7522,50 @@ public async Task DeleteTag(string @id) {await _UniFFIAsync.UniffiRustCallAsync( ); } + /// + public async Task Duplicate(string @id, string @name) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_duplicate(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + }), + // 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) => FfiConverterTypeConnectionRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ExportFile(string @path) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_export_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u32(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u32(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u32(future), + // Lift + (result) => FfiConverterUInt32.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task ImportFile(string @path) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -7107,12 +8097,225 @@ public override void Write(Core value, BigEndianStream stream) { +internal interface ICsvImport { + ImportColumnInfo[] Columns(); + /// + Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping); + /// + Task Preview(string @path, CsvReadOptions @options); + /// + Task Run(bool @confirmed, CancelToken? @cancel); + uint?[] SuggestMapping(string[] @headers); +} +internal class CsvImport : ICsvImport, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public CsvImport(ulong pointer) { + this.pointer = pointer; + } + + ~CsvImport() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_csvimport(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_csvimport(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + + public ImportColumnInfo[] Columns() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeImportColumnInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_columns(thisPtr, ref _status) +))); + } + + + /// + public async Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_plan(thisPtr, FfiConverterString.INSTANCE.Lower(@path), FfiConverterTypeCsvReadOptions.INSTANCE.Lower(@options), FfiConverterSequenceOptionalUInt32.INSTANCE.Lower(@mapping)); + }), + // 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) => FfiConverterTypeCsvImportCheck.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Preview(string @path, CsvReadOptions @options) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_preview(thisPtr, FfiConverterString.INSTANCE.Lower(@path), FfiConverterTypeCsvReadOptions.INSTANCE.Lower(@options)); + }), + // 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) => FfiConverterTypeCsvPreview.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Run(bool @confirmed, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // 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) => FfiConverterTypeCsvImportOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public uint?[] SuggestMapping(string[] @headers) { + return CallWithPointer(thisPtr => FfiConverterSequenceOptionalUInt32.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_suggest_mapping(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@headers), ref _status) +))); + } + + + + +} +class FfiConverterTypeCsvImport: FfiConverter { + public static FfiConverterTypeCsvImport INSTANCE = new FfiConverterTypeCsvImport(); + + + public override ulong Lower(CsvImport value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override CsvImport Lift(ulong value) { + return new CsvImport(value); + } + + public override CsvImport Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(CsvImport value) { + return 8; + } + + public override void Write(CsvImport value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + internal interface IDatabaseSession { /// Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, CancelToken? @cancel); /// Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, CancelToken? @cancel); /// + Task OpenCsvImport(TableName @table, CancelToken? @cancel); + /// Task Close(); /// Task Columns(TableName @table, CancelToken? @cancel); @@ -7285,6 +8488,28 @@ public async Task ExportTable(TableName @table, ColumnSort? @sort, TableF ); } + /// + public async Task OpenCsvImport(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_csv_import(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // 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) => FfiConverterTypeCsvImport.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future @@ -7701,6 +8926,255 @@ public override void Write(DatabaseSession value, BigEndianStream stream) { +internal interface IFavouriteStore { + /// + Task AddTable(string @connectionId, FavouriteTableInfo @table); + /// + Task Databases(string @connectionId); + /// + Task RemoveDatabase(string @connectionId, string @database); + /// + Task RemoveTable(string @connectionId, FavouriteTableInfo @table); + /// + Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment); + /// + Task Tables(string @connectionId); +} +internal class FavouriteStore : IFavouriteStore, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public FavouriteStore(ulong pointer) { + this.pointer = pointer; + } + + ~FavouriteStore() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_favouritestore(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_favouritestore(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + + /// + public async Task AddTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_add_table(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterTypeFavouriteTableInfo.INSTANCE.Lower(@table)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Databases(string @connectionId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_databases(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + }), + // 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) => FfiConverterSequenceTypeFavouriteDatabaseInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RemoveDatabase(string @connectionId, string @database) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_remove_database(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@database)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RemoveTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_remove_table(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterTypeFavouriteTableInfo.INSTANCE.Lower(@table)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_set_database(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@database), FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Lower(@environment)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Tables(string @connectionId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_tables(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + }), + // 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) => FfiConverterSequenceTypeFavouriteTableInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + + +} +class FfiConverterTypeFavouriteStore: FfiConverter { + public static FfiConverterTypeFavouriteStore INSTANCE = new FfiConverterTypeFavouriteStore(); + + + public override ulong Lower(FavouriteStore value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override FavouriteStore Lift(ulong value) { + return new FavouriteStore(value); + } + + public override FavouriteStore Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(FavouriteStore value) { + return 8; + } + + public override void Write(FavouriteStore value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + /// /// An editor tab's own connection, which keeps its transaction and /// session settings from one run to the next. @@ -7918,9 +9392,15 @@ internal interface IQueryHistoryStore { /// Task Delete(long[] @ids); /// + Task Export(long[] @ids, HistoryExportFormat @format, string @path); + FavouriteStore Favourites(); + /// Task Record(DatabaseSession @session, HistoryRun @run); + SavedQueryStore SavedQueries(); /// Task Search(string @text, string? @connectionId, HistoryCursorArg? @after, uint @limit); + /// + Task SetPinned(long @id, bool @pinned); } internal class QueryHistoryStore : IQueryHistoryStore, IDisposable { protected ulong pointer; @@ -8009,13 +9489,31 @@ internal T CallWithPointer(Func func) DecrementCallCounter(); } } - + + + /// + public async Task Clear() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } /// - public async Task Clear() {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -8030,10 +9528,10 @@ public async Task Clear() {await _UniFFIAsync.UniffiRustCallAsync( } /// - public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Export(long[] @ids, HistoryExportFormat @format, string @path) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_export(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids), FfiConverterTypeHistoryExportFormat.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -8047,6 +9545,14 @@ public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( ); } + public FavouriteStore Favourites() { + return CallWithPointer(thisPtr => FfiConverterTypeFavouriteStore.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_favourites(thisPtr, ref _status) +))); + } + + /// public async Task Record(DatabaseSession @session, HistoryRun @run) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -8069,6 +9575,14 @@ public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( ); } + public SavedQueryStore SavedQueries() { + return CallWithPointer(thisPtr => FfiConverterTypeSavedQueryStore.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_saved_queries(thisPtr, ref _status) +))); + } + + /// public async Task Search(string @text, string? @connectionId, HistoryCursorArg? @after, uint @limit) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -8091,6 +9605,24 @@ public async Task Search(string @text, string? @connectionId, H ); } + /// + public async Task SetPinned(long @id, bool @pinned) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_set_pinned(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterBoolean.INSTANCE.Lower(@pinned)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + } @@ -8694,30 +10226,355 @@ internal T CallWithPointer(Func func) DecrementCallCounter(); } } - + + + public SaveGate Gate() { + return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_gate(thisPtr, ref _status) +))); + } + + + public bool IsEmpty() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_is_empty(thisPtr, ref _status) +))); + } + + + /// + public async Task Run(bool @confirmed, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // 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) => FfiConverterTypeRowSaveOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public PlannedStatement[] Statements() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypePlannedStatement.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_statements(thisPtr, ref _status) +))); + } + + + + +} +class FfiConverterTypeRowSave: FfiConverter { + public static FfiConverterTypeRowSave INSTANCE = new FfiConverterTypeRowSave(); + + + public override ulong Lower(RowSave value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override RowSave Lift(ulong value) { + return new RowSave(value); + } + + public override RowSave Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(RowSave value) { + return 8; + } + + public override void Write(RowSave value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface ISavedQueryStore { + /// + Task CreateFolder(string @connectionId, string @name, long? @parentId); + /// + Task Delete(long @id); + /// + Task DeleteFolder(long @id); + /// + Task DeleteForConnection(string @connectionId); + /// + Task MoveFolder(long @id, long? @parentId); + /// + Task MoveQuery(long @id, long? @folderId, long? @before); + /// + Task Rename(long @id, string @name); + /// + Task RenameFolder(long @id, string @name); + /// + Task Save(SavedQueryDraft @draft, bool @replace); + /// + Task SetKeyword(long @id, string? @keyword); + /// + Task Snapshot(string @connectionId); +} +internal class SavedQueryStore : ISavedQueryStore, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public SavedQueryStore(ulong pointer) { + this.pointer = pointer; + } + + ~SavedQueryStore() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_savedquerystore(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_savedquerystore(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + + /// + public async Task CreateFolder(string @connectionId, string @name, long? @parentId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_create_folder(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@name), FfiConverterOptionalInt64.INSTANCE.Lower(@parentId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i64(future), + // Lift + (result) => FfiConverterInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Delete(long @id) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task DeleteFolder(long @id) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task DeleteForConnection(string @connectionId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_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 SaveGate Gate() { - return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_gate(thisPtr, ref _status) -))); + /// + public async Task MoveFolder(long @id, long? @parentId) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_move_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalInt64.INSTANCE.Lower(@parentId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task MoveQuery(long @id, long? @folderId, long? @before) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_move_query(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalInt64.INSTANCE.Lower(@folderId), FfiConverterOptionalInt64.INSTANCE.Lower(@before)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } - public bool IsEmpty() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_is_empty(thisPtr, ref _status) -))); + /// + public async Task Rename(long @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_rename(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task RenameFolder(long @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_rename_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } /// - public async Task Run(bool @confirmed, CancelToken? @cancel) { + public async Task Save(SavedQueryDraft @draft, bool @replace) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_save(thisPtr, FfiConverterTypeSavedQueryDraft.INSTANCE.Lower(@draft), FfiConverterBoolean.INSTANCE.Lower(@replace)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -8728,44 +10585,76 @@ public async Task Run(bool @confirmed, CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeRowSaveOutcome.INSTANCE.Lift(result), + (result) => FfiConverterOptionalInt64.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public PlannedStatement[] Statements() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypePlannedStatement.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_statements(thisPtr, ref _status) -))); + /// + public async Task SetKeyword(long @id, string? @keyword) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_set_keyword(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@keyword)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task Snapshot(string @connectionId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_snapshot(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + }), + // 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) => FfiConverterTypeSavedQueriesInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } } -class FfiConverterTypeRowSave: FfiConverter { - public static FfiConverterTypeRowSave INSTANCE = new FfiConverterTypeRowSave(); +class FfiConverterTypeSavedQueryStore: FfiConverter { + public static FfiConverterTypeSavedQueryStore INSTANCE = new FfiConverterTypeSavedQueryStore(); - public override ulong Lower(RowSave value) { + public override ulong Lower(SavedQueryStore value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override RowSave Lift(ulong value) { - return new RowSave(value); + public override SavedQueryStore Lift(ulong value) { + return new SavedQueryStore(value); } - public override RowSave Read(BigEndianStream stream) { + public override SavedQueryStore Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(RowSave value) { + public override int AllocationSize(SavedQueryStore value) { return 8; } - public override void Write(RowSave value, BigEndianStream stream) { + public override void Write(SavedQueryStore value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } @@ -9673,6 +11562,112 @@ public override void Write(CreatedShareInfo value, BigEndianStream stream) { +internal record CsvPreview ( + string[] Headers, + string[][] Rows, + bool Truncated +) { +} + +class FfiConverterTypeCsvPreview: FfiConverterRustBuffer { + public static FfiConverterTypeCsvPreview INSTANCE = new FfiConverterTypeCsvPreview(); + + public override CsvPreview Read(BigEndianStream stream) { + return new CsvPreview( + Headers: FfiConverterSequenceString.INSTANCE.Read(stream), + Rows: FfiConverterSequenceSequenceString.INSTANCE.Read(stream), + Truncated: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CsvPreview value) { + return 0 + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Headers) + + FfiConverterSequenceSequenceString.INSTANCE.AllocationSize(value.Rows) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Truncated); + } + + public override void Write(CsvPreview value, BigEndianStream stream) { + FfiConverterSequenceString.INSTANCE.Write(value.Headers, stream); + FfiConverterSequenceSequenceString.INSTANCE.Write(value.Rows, stream); + FfiConverterBoolean.INSTANCE.Write(value.Truncated, stream); + } +} + + + +internal record CsvReadOptions ( + CsvDelimiterTag Delimiter, + bool HasHeader, + string NullText +) { +} + +class FfiConverterTypeCsvReadOptions: FfiConverterRustBuffer { + public static FfiConverterTypeCsvReadOptions INSTANCE = new FfiConverterTypeCsvReadOptions(); + + public override CsvReadOptions Read(BigEndianStream stream) { + return new CsvReadOptions( + Delimiter: FfiConverterTypeCsvDelimiterTag.INSTANCE.Read(stream), + HasHeader: FfiConverterBoolean.INSTANCE.Read(stream), + NullText: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CsvReadOptions value) { + return 0 + + FfiConverterTypeCsvDelimiterTag.INSTANCE.AllocationSize(value.Delimiter) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HasHeader) + + FfiConverterString.INSTANCE.AllocationSize(value.NullText); + } + + public override void Write(CsvReadOptions value, BigEndianStream stream) { + FfiConverterTypeCsvDelimiterTag.INSTANCE.Write(value.Delimiter, stream); + FfiConverterBoolean.INSTANCE.Write(value.HasHeader, stream); + FfiConverterString.INSTANCE.Write(value.NullText, stream); + } +} + + + +internal record CsvRowFault ( + ulong Line, + string Column, + string Text, + string Reason +) { +} + +class FfiConverterTypeCsvRowFault: FfiConverterRustBuffer { + public static FfiConverterTypeCsvRowFault INSTANCE = new FfiConverterTypeCsvRowFault(); + + public override CsvRowFault Read(BigEndianStream stream) { + return new CsvRowFault( + Line: FfiConverterUInt64.INSTANCE.Read(stream), + Column: FfiConverterString.INSTANCE.Read(stream), + Text: FfiConverterString.INSTANCE.Read(stream), + Reason: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CsvRowFault value) { + return 0 + + FfiConverterUInt64.INSTANCE.AllocationSize(value.Line) + + FfiConverterString.INSTANCE.AllocationSize(value.Column) + + FfiConverterString.INSTANCE.AllocationSize(value.Text) + + FfiConverterString.INSTANCE.AllocationSize(value.Reason); + } + + public override void Write(CsvRowFault value, BigEndianStream stream) { + FfiConverterUInt64.INSTANCE.Write(value.Line, stream); + FfiConverterString.INSTANCE.Write(value.Column, stream); + FfiConverterString.INSTANCE.Write(value.Text, stream); + FfiConverterString.INSTANCE.Write(value.Reason, stream); + } +} + + + internal record DeviceInfo ( string Id, string Platform, @@ -9933,6 +11928,70 @@ public override void Write(ErrorInfo value, BigEndianStream stream) { +internal record FavouriteDatabaseInfo ( + string Database, + DatabaseEnvironmentTag Environment +) { +} + +class FfiConverterTypeFavouriteDatabaseInfo: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteDatabaseInfo INSTANCE = new FfiConverterTypeFavouriteDatabaseInfo(); + + public override FavouriteDatabaseInfo Read(BigEndianStream stream) { + return new FavouriteDatabaseInfo( + Database: FfiConverterString.INSTANCE.Read(stream), + Environment: FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteDatabaseInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Database) + + FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.AllocationSize(value.Environment); + } + + public override void Write(FavouriteDatabaseInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Database, stream); + FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Write(value.Environment, stream); + } +} + + + +internal record FavouriteTableInfo ( + string? Database, + string? Schema, + string Name +) { +} + +class FfiConverterTypeFavouriteTableInfo: FfiConverterRustBuffer { + public static FfiConverterTypeFavouriteTableInfo INSTANCE = new FfiConverterTypeFavouriteTableInfo(); + + public override FavouriteTableInfo Read(BigEndianStream stream) { + return new FavouriteTableInfo( + Database: FfiConverterOptionalString.INSTANCE.Read(stream), + Schema: FfiConverterOptionalString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FavouriteTableInfo value) { + return 0 + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Database) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Schema) + + FfiConverterString.INSTANCE.AllocationSize(value.Name); + } + + public override void Write(FavouriteTableInfo value, BigEndianStream 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, @@ -10364,6 +12423,48 @@ public override void Write(HostKeyFailure value, BigEndianStream stream) { +internal record ImportColumnInfo ( + string Name, + string TypeName, + bool Nullable, + bool HasDefault, + bool ServerFilled +) { +} + +class FfiConverterTypeImportColumnInfo: FfiConverterRustBuffer { + public static FfiConverterTypeImportColumnInfo INSTANCE = new FfiConverterTypeImportColumnInfo(); + + public override ImportColumnInfo Read(BigEndianStream stream) { + return new ImportColumnInfo( + Name: FfiConverterString.INSTANCE.Read(stream), + TypeName: FfiConverterString.INSTANCE.Read(stream), + Nullable: FfiConverterBoolean.INSTANCE.Read(stream), + HasDefault: FfiConverterBoolean.INSTANCE.Read(stream), + ServerFilled: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ImportColumnInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.TypeName) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Nullable) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HasDefault) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.ServerFilled); + } + + public override void Write(ImportColumnInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.TypeName, stream); + FfiConverterBoolean.INSTANCE.Write(value.Nullable, stream); + FfiConverterBoolean.INSTANCE.Write(value.HasDefault, stream); + FfiConverterBoolean.INSTANCE.Write(value.ServerFilled, stream); + } +} + + + internal record ImportSummary ( uint Added, uint Updated @@ -10490,6 +12591,36 @@ public override void Write(LicenseInfo value, BigEndianStream stream) { +internal record LineSpan ( + ulong First, + ulong Last +) { +} + +class FfiConverterTypeLineSpan: FfiConverterRustBuffer { + public static FfiConverterTypeLineSpan INSTANCE = new FfiConverterTypeLineSpan(); + + public override LineSpan Read(BigEndianStream stream) { + return new LineSpan( + First: FfiConverterUInt64.INSTANCE.Read(stream), + Last: FfiConverterUInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(LineSpan value) { + return 0 + + FfiConverterUInt64.INSTANCE.AllocationSize(value.First) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.Last); + } + + public override void Write(LineSpan value, BigEndianStream stream) { + FfiConverterUInt64.INSTANCE.Write(value.First, stream); + FfiConverterUInt64.INSTANCE.Write(value.Last, stream); + } +} + + + internal record MaskSuggestionInfo ( MaskStyleTag Style, MaskReason Reason @@ -10975,6 +13106,162 @@ public override void Write(RunSettings value, BigEndianStream stream) { +internal record SavedQueriesInfo ( + SavedQueryInfo[] Queries, + SavedQueryFolderInfo[] Folders +) { +} + +class FfiConverterTypeSavedQueriesInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueriesInfo INSTANCE = new FfiConverterTypeSavedQueriesInfo(); + + public override SavedQueriesInfo Read(BigEndianStream stream) { + return new SavedQueriesInfo( + Queries: FfiConverterSequenceTypeSavedQueryInfo.INSTANCE.Read(stream), + Folders: FfiConverterSequenceTypeSavedQueryFolderInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueriesInfo value) { + return 0 + + FfiConverterSequenceTypeSavedQueryInfo.INSTANCE.AllocationSize(value.Queries) + + FfiConverterSequenceTypeSavedQueryFolderInfo.INSTANCE.AllocationSize(value.Folders); + } + + public override void Write(SavedQueriesInfo value, BigEndianStream stream) { + FfiConverterSequenceTypeSavedQueryInfo.INSTANCE.Write(value.Queries, stream); + FfiConverterSequenceTypeSavedQueryFolderInfo.INSTANCE.Write(value.Folders, stream); + } +} + + + +internal record SavedQueryDraft ( + string ConnectionId, + string ConnectionName, + string Name, + string Sql +) { +} + +class FfiConverterTypeSavedQueryDraft: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryDraft INSTANCE = new FfiConverterTypeSavedQueryDraft(); + + public override SavedQueryDraft Read(BigEndianStream stream) { + return new SavedQueryDraft( + ConnectionId: FfiConverterString.INSTANCE.Read(stream), + ConnectionName: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + Sql: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryDraft value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionId) + + FfiConverterString.INSTANCE.AllocationSize(value.ConnectionName) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.Sql); + } + + public override void Write(SavedQueryDraft value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.ConnectionId, stream); + FfiConverterString.INSTANCE.Write(value.ConnectionName, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.Sql, stream); + } +} + + + +internal record SavedQueryFolderInfo ( + long Id, + string Name, + long? ParentId, + long Order +) { +} + +class FfiConverterTypeSavedQueryFolderInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryFolderInfo INSTANCE = new FfiConverterTypeSavedQueryFolderInfo(); + + public override SavedQueryFolderInfo Read(BigEndianStream stream) { + return new SavedQueryFolderInfo( + Id: FfiConverterInt64.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + ParentId: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Order: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryFolderInfo value) { + return 0 + + FfiConverterInt64.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.ParentId) + + FfiConverterInt64.INSTANCE.AllocationSize(value.Order); + } + + public override void Write(SavedQueryFolderInfo value, BigEndianStream stream) { + FfiConverterInt64.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.ParentId, stream); + FfiConverterInt64.INSTANCE.Write(value.Order, stream); + } +} + + + +internal record SavedQueryInfo ( + long Id, + string Name, + string Sql, + string? Keyword, + long? FolderId, + long Order, + long UpdatedAtMs +) { +} + +class FfiConverterTypeSavedQueryInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQueryInfo INSTANCE = new FfiConverterTypeSavedQueryInfo(); + + public override SavedQueryInfo Read(BigEndianStream stream) { + return new SavedQueryInfo( + Id: FfiConverterInt64.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + Sql: FfiConverterString.INSTANCE.Read(stream), + Keyword: FfiConverterOptionalString.INSTANCE.Read(stream), + FolderId: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Order: FfiConverterInt64.INSTANCE.Read(stream), + UpdatedAtMs: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SavedQueryInfo value) { + return 0 + + FfiConverterInt64.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Keyword) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.FolderId) + + FfiConverterInt64.INSTANCE.AllocationSize(value.Order) + + FfiConverterInt64.INSTANCE.AllocationSize(value.UpdatedAtMs); + } + + public override void Write(SavedQueryInfo value, BigEndianStream stream) { + FfiConverterInt64.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.Sql, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Keyword, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.FolderId, stream); + FfiConverterInt64.INSTANCE.Write(value.Order, stream); + FfiConverterInt64.INSTANCE.Write(value.UpdatedAtMs, stream); + } +} + + + internal record SchemaEntry ( string Name, bool IsDefault, @@ -12108,15 +14395,226 @@ public override CombinatorTag Read(BigEndianStream stream) { } } - public override int AllocationSize(CombinatorTag value) { - return 4; + public override int AllocationSize(CombinatorTag value) { + return 4; + } + + public override void Write(CombinatorTag value, BigEndianStream stream) { + switch (value) { + case CombinatorTag.And: stream.WriteInt(1); break; + case CombinatorTag.Or: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCombinatorTag.Write()", value)); + } + } +} + + + + + + + +/// +/// Why a call produced no value. A cancel is its own variant, so a +/// binding can turn it into its language's cancellation. +/// +internal class CoreException: UniffiException { + CoreException() : base() {} + CoreException(String @Message) : base(@Message) {} + + // Each variant is a nested class + + public class Cancelled : CoreException { + public Cancelled() : base() {} + } + + + + public class Failed : CoreException { + // Members + public BoxedErrorInfo @info; + + // Constructor + public Failed( + BoxedErrorInfo @info) : base( + "@info" + "=" + @info) { + + this.@info = @info; + } + } + + + +} + +class FfiConverterTypeCoreError : FfiConverterRustBuffer, CallStatusErrorHandler { + public static FfiConverterTypeCoreError INSTANCE = new FfiConverterTypeCoreError(); + + public override CoreException Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new CoreException.Cancelled(); + case 2: + return new CoreException.Failed( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream)); + default: + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCoreError.Read()", value)); + } + } + + public override int AllocationSize(CoreException value) { + switch (value) { + + case CoreException.Cancelled variant_value: + return 4; + + case CoreException.Failed variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.@info); + default: + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCoreError.AllocationSize()", value)); + } + } + + public override void Write(CoreException value, BigEndianStream stream) { + switch (value) { + case CoreException.Cancelled variant_value: + stream.WriteInt(1); + break; + case CoreException.Failed variant_value: + stream.WriteInt(2); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.@info, stream); + break; + default: + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCoreError.Write()", value)); + } + } +} + + + + + +internal enum CsvDelimiterTag: int { + Comma, + Semicolon, + Tab, + Pipe +} + +class FfiConverterTypeCsvDelimiterTag: FfiConverterRustBuffer { + public static FfiConverterTypeCsvDelimiterTag INSTANCE = new FfiConverterTypeCsvDelimiterTag(); + + public override CsvDelimiterTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return CsvDelimiterTag.Comma; + case 2: return CsvDelimiterTag.Semicolon; + case 3: return CsvDelimiterTag.Tab; + case 4: return CsvDelimiterTag.Pipe; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvDelimiterTag.Read()", value)); + } + } + + public override int AllocationSize(CsvDelimiterTag value) { + return 4; + } + + public override void Write(CsvDelimiterTag value, BigEndianStream stream) { + switch (value) { + case CsvDelimiterTag.Comma: stream.WriteInt(1); break; + case CsvDelimiterTag.Semicolon: stream.WriteInt(2); break; + case CsvDelimiterTag.Tab: stream.WriteInt(3); break; + case CsvDelimiterTag.Pipe: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvDelimiterTag.Write()", value)); + } + } +} + + + + + + + +internal record CsvImportCheck { + + public record Ready ( + ulong Rows, + string[] Statements, + SaveGate Gate + ) : CsvImportCheck {} + + public record Empty: CsvImportCheck {} + + + public record RowRefused ( + CsvRowFault Fault + ) : CsvImportCheck {} + + + +} + +class FfiConverterTypeCsvImportCheck : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCsvImportCheck(); + + public override CsvImportCheck Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new CsvImportCheck.Ready( + FfiConverterUInt64.INSTANCE.Read(stream), + FfiConverterSequenceString.INSTANCE.Read(stream), + FfiConverterTypeSaveGate.INSTANCE.Read(stream) + ); + case 2: + return new CsvImportCheck.Empty( + ); + case 3: + return new CsvImportCheck.RowRefused( + FfiConverterTypeCsvRowFault.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportCheck.Read()", value)); + } + } + + public override int AllocationSize(CsvImportCheck value) { + switch (value) { + case CsvImportCheck.Ready variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Rows) + + FfiConverterSequenceString.INSTANCE.AllocationSize(variant_value.Statements) + + FfiConverterTypeSaveGate.INSTANCE.AllocationSize(variant_value.Gate); + case CsvImportCheck.Empty variant_value: + return 4; + case CsvImportCheck.RowRefused variant_value: + return 4 + + FfiConverterTypeCsvRowFault.INSTANCE.AllocationSize(variant_value.Fault); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportCheck.AllocationSize()", value)); + } } - public override void Write(CombinatorTag value, BigEndianStream stream) { + public override void Write(CsvImportCheck value, BigEndianStream stream) { switch (value) { - case CombinatorTag.And: stream.WriteInt(1); break; - case CombinatorTag.Or: stream.WriteInt(2); break; - default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCombinatorTag.Write()", value)); + case CsvImportCheck.Ready variant_value: + stream.WriteInt(1); + FfiConverterUInt64.INSTANCE.Write(variant_value.Rows, stream); + FfiConverterSequenceString.INSTANCE.Write(variant_value.Statements, stream); + FfiConverterTypeSaveGate.INSTANCE.Write(variant_value.Gate, stream); + break; + case CsvImportCheck.Empty variant_value: + stream.WriteInt(2); + break; + case CsvImportCheck.RowRefused variant_value: + stream.WriteInt(3); + FfiConverterTypeCsvRowFault.INSTANCE.Write(variant_value.Fault, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportCheck.Write()", value)); } } } @@ -12127,80 +14625,106 @@ public override void Write(CombinatorTag value, BigEndianStream stream) { -/// -/// Why a call produced no value. A cancel is its own variant, so a -/// binding can turn it into its language's cancellation. -/// -internal class CoreException: UniffiException { - CoreException() : base() {} - CoreException(String @Message) : base(@Message) {} - - // Each variant is a nested class +internal record CsvImportOutcome { - public class Cancelled : CoreException { - public Cancelled() : base() {} - } + public record Imported ( + ulong Rows + ) : CsvImportOutcome {} + public record RolledBack ( + BoxedErrorInfo Error, + LineSpan? Lines + ) : CsvImportOutcome {} + public record PartlyWritten ( + BoxedErrorInfo Error, + ulong WrittenRows, + LineSpan? Lines + ) : CsvImportOutcome {} - public class Failed : CoreException { - // Members - public BoxedErrorInfo @info; - - // Constructor - public Failed( - BoxedErrorInfo @info) : base( - "@info" + "=" + @info) { - - this.@info = @info; - } - } + public record Unknown ( + BoxedErrorInfo Error + ) : CsvImportOutcome {} } -class FfiConverterTypeCoreError : FfiConverterRustBuffer, CallStatusErrorHandler { - public static FfiConverterTypeCoreError INSTANCE = new FfiConverterTypeCoreError(); +class FfiConverterTypeCsvImportOutcome : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCsvImportOutcome(); - public override CoreException Read(BigEndianStream stream) { + public override CsvImportOutcome Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { case 1: - return new CoreException.Cancelled(); + return new CsvImportOutcome.Imported( + FfiConverterUInt64.INSTANCE.Read(stream) + ); case 2: - return new CoreException.Failed( - FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream)); + return new CsvImportOutcome.RolledBack( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterOptionalTypeLineSpan.INSTANCE.Read(stream) + ); + case 3: + return new CsvImportOutcome.PartlyWritten( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterUInt64.INSTANCE.Read(stream), + FfiConverterOptionalTypeLineSpan.INSTANCE.Read(stream) + ); + case 4: + return new CsvImportOutcome.Unknown( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream) + ); default: - throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCoreError.Read()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportOutcome.Read()", value)); } } - public override int AllocationSize(CoreException value) { + public override int AllocationSize(CsvImportOutcome value) { switch (value) { - - case CoreException.Cancelled variant_value: - return 4; - - case CoreException.Failed variant_value: + case CsvImportOutcome.Imported variant_value: return 4 - + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.@info); + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Rows); + case CsvImportOutcome.RolledBack variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) + + FfiConverterOptionalTypeLineSpan.INSTANCE.AllocationSize(variant_value.Lines); + case CsvImportOutcome.PartlyWritten variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.WrittenRows) + + FfiConverterOptionalTypeLineSpan.INSTANCE.AllocationSize(variant_value.Lines); + case CsvImportOutcome.Unknown variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error); default: - throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCoreError.AllocationSize()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportOutcome.AllocationSize()", value)); } } - public override void Write(CoreException value, BigEndianStream stream) { + public override void Write(CsvImportOutcome value, BigEndianStream stream) { switch (value) { - case CoreException.Cancelled variant_value: + case CsvImportOutcome.Imported variant_value: stream.WriteInt(1); + FfiConverterUInt64.INSTANCE.Write(variant_value.Rows, stream); break; - case CoreException.Failed variant_value: + case CsvImportOutcome.RolledBack variant_value: stream.WriteInt(2); - FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.@info, stream); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterOptionalTypeLineSpan.INSTANCE.Write(variant_value.Lines, stream); + break; + case CsvImportOutcome.PartlyWritten variant_value: + stream.WriteInt(3); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterUInt64.INSTANCE.Write(variant_value.WrittenRows, stream); + FfiConverterOptionalTypeLineSpan.INSTANCE.Write(variant_value.Lines, stream); + break; + case CsvImportOutcome.Unknown variant_value: + stream.WriteInt(4); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); break; default: - throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCoreError.Write()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportOutcome.Write()", value)); } } } @@ -12209,6 +14733,8 @@ public override void Write(CoreException value, BigEndianStream stream) { + + internal enum DataModelTag: int { Relational, KeyValue, @@ -12248,6 +14774,48 @@ public override void Write(DataModelTag value, BigEndianStream stream) { +internal enum DatabaseEnvironmentTag: int { + Development, + Testing, + Production, + Unassigned +} + +class FfiConverterTypeDatabaseEnvironmentTag: FfiConverterRustBuffer { + public static FfiConverterTypeDatabaseEnvironmentTag INSTANCE = new FfiConverterTypeDatabaseEnvironmentTag(); + + public override DatabaseEnvironmentTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return DatabaseEnvironmentTag.Development; + case 2: return DatabaseEnvironmentTag.Testing; + case 3: return DatabaseEnvironmentTag.Production; + case 4: return DatabaseEnvironmentTag.Unassigned; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDatabaseEnvironmentTag.Read()", value)); + } + } + + public override int AllocationSize(DatabaseEnvironmentTag value) { + return 4; + } + + public override void Write(DatabaseEnvironmentTag value, BigEndianStream stream) { + switch (value) { + case DatabaseEnvironmentTag.Development: stream.WriteInt(1); break; + case DatabaseEnvironmentTag.Testing: stream.WriteInt(2); break; + case DatabaseEnvironmentTag.Production: stream.WriteInt(3); break; + case DatabaseEnvironmentTag.Unassigned: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDatabaseEnvironmentTag.Write()", value)); + } + } +} + + + + + + + internal record EditLock { public record ReadOnlyConnection: EditLock {} @@ -12911,6 +15479,42 @@ public override void Write(FilterValueArg value, BigEndianStream stream) { +internal enum HistoryExportFormat: int { + Sql, + Csv +} + +class FfiConverterTypeHistoryExportFormat: FfiConverterRustBuffer { + public static FfiConverterTypeHistoryExportFormat INSTANCE = new FfiConverterTypeHistoryExportFormat(); + + public override HistoryExportFormat Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return HistoryExportFormat.Sql; + case 2: return HistoryExportFormat.Csv; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeHistoryExportFormat.Read()", value)); + } + } + + public override int AllocationSize(HistoryExportFormat value) { + return 4; + } + + public override void Write(HistoryExportFormat value, BigEndianStream stream) { + switch (value) { + case HistoryExportFormat.Sql: stream.WriteInt(1); break; + case HistoryExportFormat.Csv: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeHistoryExportFormat.Write()", value)); + } + } +} + + + + + + + internal record HistoryOutcomeTag { public record Succeeded: HistoryOutcomeTag {} @@ -16568,6 +19172,37 @@ public override void Write(HostKeyFailure? value, BigEndianStream stream) { +class FfiConverterOptionalTypeLineSpan: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeLineSpan INSTANCE = new FfiConverterOptionalTypeLineSpan(); + + public override LineSpan? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeLineSpan.INSTANCE.Read(stream); + } + + public override int AllocationSize(LineSpan? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeLineSpan.INSTANCE.AllocationSize((LineSpan)value); + } + } + + public override void Write(LineSpan? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeLineSpan.INSTANCE.Write((LineSpan)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeMaskSuggestionInfo: FfiConverterRustBuffer { public static FfiConverterOptionalTypeMaskSuggestionInfo INSTANCE = new FfiConverterOptionalTypeMaskSuggestionInfo(); @@ -17467,21 +20102,113 @@ public override void Write(CloudGroupFields[] value, BigEndianStream stream) { class FfiConverterSequenceTypeColumnEntry: FfiConverterRustBuffer { public static FfiConverterSequenceTypeColumnEntry INSTANCE = new FfiConverterSequenceTypeColumnEntry(); - public override ColumnEntry[] Read(BigEndianStream stream) { + public override ColumnEntry[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ColumnEntry[length]; + var readFn = FfiConverterTypeColumnEntry.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ColumnEntry[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeColumnEntry.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ColumnEntry[] 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 = FfiConverterTypeColumnEntry.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeConnectionRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeConnectionRecord INSTANCE = new FfiConverterSequenceTypeConnectionRecord(); + + public override ConnectionRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ConnectionRecord[length]; + var readFn = FfiConverterTypeConnectionRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ConnectionRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeConnectionRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ConnectionRecord[] 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 = FfiConverterTypeConnectionRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeDeviceInfo INSTANCE = new FfiConverterSequenceTypeDeviceInfo(); + + public override DeviceInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new ColumnEntry[length]; - var readFn = FfiConverterTypeColumnEntry.INSTANCE.Read; + var result = new DeviceInfo[length]; + var readFn = FfiConverterTypeDeviceInfo.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(ColumnEntry[] value) { + public override int AllocationSize(DeviceInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -17489,12 +20216,12 @@ public override int AllocationSize(ColumnEntry[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeColumnEntry.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeDeviceInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(ColumnEntry[] value, BigEndianStream stream) { + public override void Write(DeviceInfo[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -17502,7 +20229,7 @@ public override void Write(ColumnEntry[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeColumnEntry.INSTANCE.Write; + var writerFn = FfiConverterTypeDeviceInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -17510,24 +20237,24 @@ public override void Write(ColumnEntry[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeConnectionRecord: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeConnectionRecord INSTANCE = new FfiConverterSequenceTypeConnectionRecord(); +class FfiConverterSequenceTypeDriverInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeDriverInfo INSTANCE = new FfiConverterSequenceTypeDriverInfo(); - public override ConnectionRecord[] Read(BigEndianStream stream) { + public override DriverInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new ConnectionRecord[length]; - var readFn = FfiConverterTypeConnectionRecord.INSTANCE.Read; + var result = new DriverInfo[length]; + var readFn = FfiConverterTypeDriverInfo.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(ConnectionRecord[] value) { + public override int AllocationSize(DriverInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -17535,12 +20262,12 @@ public override int AllocationSize(ConnectionRecord[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeConnectionRecord.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeDriverInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(ConnectionRecord[] value, BigEndianStream stream) { + public override void Write(DriverInfo[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -17548,7 +20275,7 @@ public override void Write(ConnectionRecord[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeConnectionRecord.INSTANCE.Write; + var writerFn = FfiConverterTypeDriverInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -17556,24 +20283,24 @@ public override void Write(ConnectionRecord[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeDeviceInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeDeviceInfo INSTANCE = new FfiConverterSequenceTypeDeviceInfo(); +class FfiConverterSequenceTypeEditColumnInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeEditColumnInfo INSTANCE = new FfiConverterSequenceTypeEditColumnInfo(); - public override DeviceInfo[] Read(BigEndianStream stream) { + public override EditColumnInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new DeviceInfo[length]; - var readFn = FfiConverterTypeDeviceInfo.INSTANCE.Read; + var result = new EditColumnInfo[length]; + var readFn = FfiConverterTypeEditColumnInfo.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(DeviceInfo[] value) { + public override int AllocationSize(EditColumnInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -17581,12 +20308,12 @@ public override int AllocationSize(DeviceInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeDeviceInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeEditColumnInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(DeviceInfo[] value, BigEndianStream stream) { + public override void Write(EditColumnInfo[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -17594,7 +20321,7 @@ public override void Write(DeviceInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeDeviceInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeEditColumnInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -17602,24 +20329,24 @@ public override void Write(DeviceInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeDriverInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeDriverInfo INSTANCE = new FfiConverterSequenceTypeDriverInfo(); +class FfiConverterSequenceTypeFavouriteDatabaseInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteDatabaseInfo INSTANCE = new FfiConverterSequenceTypeFavouriteDatabaseInfo(); - public override DriverInfo[] Read(BigEndianStream stream) { + public override FavouriteDatabaseInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new DriverInfo[length]; - var readFn = FfiConverterTypeDriverInfo.INSTANCE.Read; + var result = new FavouriteDatabaseInfo[length]; + var readFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(DriverInfo[] value) { + public override int AllocationSize(FavouriteDatabaseInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -17627,12 +20354,12 @@ public override int AllocationSize(DriverInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeDriverInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(DriverInfo[] value, BigEndianStream stream) { + public override void Write(FavouriteDatabaseInfo[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -17640,7 +20367,7 @@ public override void Write(DriverInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeDriverInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -17648,24 +20375,24 @@ public override void Write(DriverInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeEditColumnInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeEditColumnInfo INSTANCE = new FfiConverterSequenceTypeEditColumnInfo(); +class FfiConverterSequenceTypeFavouriteTableInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteTableInfo INSTANCE = new FfiConverterSequenceTypeFavouriteTableInfo(); - public override EditColumnInfo[] Read(BigEndianStream stream) { + public override FavouriteTableInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new EditColumnInfo[length]; - var readFn = FfiConverterTypeEditColumnInfo.INSTANCE.Read; + var result = new FavouriteTableInfo[length]; + var readFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(EditColumnInfo[] value) { + public override int AllocationSize(FavouriteTableInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -17673,12 +20400,12 @@ public override int AllocationSize(EditColumnInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeEditColumnInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(EditColumnInfo[] value, BigEndianStream stream) { + public override void Write(FavouriteTableInfo[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -17686,7 +20413,7 @@ public override void Write(EditColumnInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeEditColumnInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -17878,6 +20605,52 @@ public override void Write(HistoryEntryInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeImportColumnInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeImportColumnInfo INSTANCE = new FfiConverterSequenceTypeImportColumnInfo(); + + public override ImportColumnInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ImportColumnInfo[length]; + var readFn = FfiConverterTypeImportColumnInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ImportColumnInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeImportColumnInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ImportColumnInfo[] 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 = FfiConverterTypeImportColumnInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeLicenseInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeLicenseInfo INSTANCE = new FfiConverterSequenceTypeLicenseInfo(); @@ -18200,6 +20973,98 @@ public override void Write(ResultColumnInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeSavedQueryFolderInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeSavedQueryFolderInfo INSTANCE = new FfiConverterSequenceTypeSavedQueryFolderInfo(); + + public override SavedQueryFolderInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new SavedQueryFolderInfo[length]; + var readFn = FfiConverterTypeSavedQueryFolderInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(SavedQueryFolderInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeSavedQueryFolderInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(SavedQueryFolderInfo[] 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 = FfiConverterTypeSavedQueryFolderInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeSavedQueryInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeSavedQueryInfo INSTANCE = new FfiConverterSequenceTypeSavedQueryInfo(); + + public override SavedQueryInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new SavedQueryInfo[length]; + var readFn = FfiConverterTypeSavedQueryInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(SavedQueryInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeSavedQueryInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(SavedQueryInfo[] 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 = FfiConverterTypeSavedQueryInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeSchemaEntry: FfiConverterRustBuffer { public static FfiConverterSequenceTypeSchemaEntry INSTANCE = new FfiConverterSequenceTypeSchemaEntry(); @@ -18982,6 +21847,98 @@ public override void Write(TlsModeTag[] value, BigEndianStream stream) { +class FfiConverterSequenceOptionalUInt32: FfiConverterRustBuffer { + public static FfiConverterSequenceOptionalUInt32 INSTANCE = new FfiConverterSequenceOptionalUInt32(); + + public override uint?[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new uint?[length]; + var readFn = FfiConverterOptionalUInt32.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(uint?[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterOptionalUInt32.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(uint?[] 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 = FfiConverterOptionalUInt32.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceSequenceString: FfiConverterRustBuffer { + public static FfiConverterSequenceSequenceString INSTANCE = new FfiConverterSequenceSequenceString(); + + public override string[][] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new string[length][]; + var readFn = FfiConverterSequenceString.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(string[][] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterSequenceString.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(string[][] 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 = FfiConverterSequenceString.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeSecretString: FfiConverterRustBuffer { public static FfiConverterSequenceTypeSecretString INSTANCE = new FfiConverterSequenceTypeSecretString(); diff --git a/windows/src/TablePro.Interop/QueryHistory.cs b/windows/src/TablePro.Interop/QueryHistory.cs index 8e6504b50d..f29b18405b 100644 --- a/windows/src/TablePro.Interop/QueryHistory.cs +++ b/windows/src/TablePro.Interop/QueryHistory.cs @@ -42,6 +42,13 @@ public sealed record HistoryEntry( HistoryOutcome Outcome, bool Pinned); +public enum HistoryExportFormat +{ + // Each run as it ran, under comments that say where and when. + Sql, + Csv, +} + // Next is null on the last page. public sealed record HistoryPage(IReadOnlyList Entries, HistoryCursor? Next); @@ -114,6 +121,24 @@ public Task ClearAsync(CancellationToken cancellationToken = default) return CoreCall.RunAsync(() => _store.Clear()); } + // A pinned run comes first in every search and is never pruned. + public Task SetPinnedAsync(long id, bool pinned) => CoreCall.RunAsync(() => _store.SetPinned(id, pinned)); + + // The file at path appears only once whole. + public Task ExportAsync(IReadOnlyList ids, HistoryExportFormat format, string path) + { + ArgumentNullException.ThrowIfNull(ids); + ArgumentException.ThrowIfNullOrEmpty(path); + long[] native = [.. ids]; + var tag = format == HistoryExportFormat.Csv ? Native.HistoryExportFormat.Csv : Native.HistoryExportFormat.Sql; + return CoreCall.RunAsync(() => _store.Export(native, tag, path)); + } + + // The same database, so every store from one QueryHistory sees the others' writes. + public SavedQueries OpenSavedQueries() => new(CoreCall.Run(() => _store.SavedQueries())); + + public Favourites OpenFavourites() => new(CoreCall.Run(() => _store.Favourites())); + public void Dispose() => _store.Dispose(); private static Native.HistoryRun Run(HistoryRun run) => new( diff --git a/windows/src/TablePro.Interop/SavedQueries.cs b/windows/src/TablePro.Interop/SavedQueries.cs new file mode 100644 index 0000000000..4c63f9f2b4 --- /dev/null +++ b/windows/src/TablePro.Interop/SavedQueries.cs @@ -0,0 +1,99 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +// FolderId is null at the top level; Order is dense from 0 within the folder. +public sealed record SavedQuery( + long Id, + string Name, + string Sql, + string? Keyword, + long? FolderId, + long Order, + DateTimeOffset UpdatedAt); + +public sealed record SavedQueryFolder(long Id, string Name, long? ParentId, long Order); + +// Read in one transaction, each list in its place's order. +public sealed record SavedQueryList(IReadOnlyList Queries, IReadOnlyList Folders); + +// A connection's saved queries and their folders, kept in the query history's database (core ADR 0017). +public sealed class SavedQueries : IDisposable +{ + private readonly Native.SavedQueryStore _store; + + internal SavedQueries(Native.SavedQueryStore store) + { + _store = store; + } + + public async Task GetAsync(Guid connectionId, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + // A read, so one the caller stopped waiting for is left to finish. + var list = await CoreCall.RunAsync(() => _store.Snapshot(connectionId.ToString())) + .WaitAsync(cancellationToken) + .ConfigureAwait(false); + return new SavedQueryList( + [.. list.Queries.Select(query => new SavedQuery( + query.Id, + query.Name, + query.Sql, + query.Keyword, + query.FolderId, + query.Order, + DateTimeOffset.FromUnixTimeMilliseconds(query.UpdatedAtMs)))], + [.. list.Folders.Select(folder => new SavedQueryFolder(folder.Id, folder.Name, folder.ParentId, folder.Order))]); + } + + // Null when the connection has a query of that name and replace is false; nothing is written then. + public Task SaveAsync(Guid connectionId, string connectionName, string name, string sql, bool replace) + { + ArgumentNullException.ThrowIfNull(connectionName); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(sql); + var draft = new Native.SavedQueryDraft(connectionId.ToString(), connectionName, name, sql); + return CoreCall.RunAsync(() => _store.Save(draft, replace)); + } + + public Task RenameAsync(long id, string name) + { + ArgumentNullException.ThrowIfNull(name); + return CoreCall.RunAsync(() => _store.Rename(id, name)); + } + + // Null or blank clears it. + public Task SetKeywordAsync(long id, string? keyword) => CoreCall.RunAsync(() => _store.SetKeyword(id, keyword)); + + // Into the folder, null for the top level, before the query named there or at the end. + public Task MoveAsync(long id, long? folderId, long? before = null) => + CoreCall.RunAsync(() => _store.MoveQuery(id, folderId, before)); + + public Task DeleteAsync(long id) => CoreCall.RunAsync(() => _store.Delete(id)); + + public Task CreateFolderAsync(Guid connectionId, string name, long? parentId) + { + ArgumentNullException.ThrowIfNull(name); + return CoreCall.RunAsync(() => _store.CreateFolder(connectionId.ToString(), name, parentId)); + } + + public Task RenameFolderAsync(long id, string name) + { + ArgumentNullException.ThrowIfNull(name); + return CoreCall.RunAsync(() => _store.RenameFolder(id, name)); + } + + public Task MoveFolderAsync(long id, long? parentId) => CoreCall.RunAsync(() => _store.MoveFolder(id, parentId)); + + // The folders inside go too, and every query they held moves to the top level. + public Task DeleteFolderAsync(long id) => CoreCall.RunAsync(() => _store.DeleteFolder(id)); + + // Its queries, folders and favourite tables and databases, for a connection the user deleted. + public async Task DeleteForConnectionAsync(Guid connectionId) + { + var removed = await CoreCall.RunAsync(() => _store.DeleteForConnection(connectionId.ToString())).ConfigureAwait(false); + return Mapping.Count(removed); + } + + public void Dispose() => _store.Dispose(); +} diff --git a/windows/tests/TablePro.App.Model.Tests/CopyNameTests.cs b/windows/tests/TablePro.App.Model.Tests/CopyNameTests.cs new file mode 100644 index 0000000000..94075de200 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/CopyNameTests.cs @@ -0,0 +1,47 @@ +namespace TablePro.App.Model.Tests; + +public sealed class CopyNameTests +{ + private const string Pattern = "{0} (Copy)"; + private const string Numbered = "{0} (Copy {1})"; + + [Fact] + public void ACopyTakesTheSuffixThenTheSmallestFreeNumber() + { + List names = ["Prod"]; + foreach (var expected in new[] { "Prod (Copy)", "Prod (Copy 2)", "Prod (Copy 3)" }) + { + var name = CopyName.For("Prod", names, Pattern, Numbered); + Assert.Equal(expected, name); + names.Add(name); + } + + Assert.Equal("db (Copy 2)", CopyName.For("db", ["db", "db (Copy)", "db (Copy 3)"], Pattern, Numbered)); + } + + [Fact] + public void ACopyOfACopyCountsOnFromTheOriginal() + { + string[] names = ["Prod", "Prod (Copy)", "Prod (Copy 2)"]; + + Assert.Equal("Prod (Copy 3)", CopyName.For("Prod (Copy)", names, Pattern, Numbered)); + Assert.Equal("Prod (Copy 3)", CopyName.For("Prod (Copy 2)", names, Pattern, Numbered)); + } + + [Fact] + public void ANameThatOnlyLooksNumberedKeepsItsText() + { + string[] names = ["Release (Copy 1)", "(Copy)"]; + + Assert.Equal("Release (Copy 1) (Copy)", CopyName.For("Release (Copy 1)", names, Pattern, Numbered)); + Assert.Equal("(Copy) (Copy)", CopyName.For("(Copy)", names, Pattern, Numbered)); + } + + [Fact] + public void ATranslationThatPutsTheWordFirstStillStripsIt() + { + string[] names = ["Prod", "Copie de Prod"]; + + Assert.Equal("Copie 2 de Prod", CopyName.For("Copie de Prod", names, "Copie de {0}", "Copie {1} de {0}")); + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs new file mode 100644 index 0000000000..efe028cb5e --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs @@ -0,0 +1,249 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class CsvImportFormTests +{ + [Theory] + [InlineData("people.csv", CsvDelimiter.Comma)] + [InlineData("people.txt", CsvDelimiter.Comma)] + [InlineData("people.tsv", CsvDelimiter.Tab)] + [InlineData("PEOPLE.TSV", CsvDelimiter.Tab)] + public void ATsvFileStartsTabSeparatedAndAnyOtherCommaSeparated(string name, CsvDelimiter delimiter) + { + var form = new CsvImportForm(Columns(), Path.Combine("data", name)); + + Assert.Equal(new CsvOptions(delimiter, HasHeader: true, NullText: string.Empty), form.Options); + Assert.Equal(name, form.FileName); + Assert.Equal(CsvImportState.Reading, form.State); + Assert.False(form.CanImport); + } + + [Fact] + public void AReadTakesTheSuggestedFieldsButNoneForAColumnTheServerFillsOrPastTheFile() + { + var form = Form(); + + Assert.True(form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [0, 0, 1, 7])); + + Assert.Equal([null, 0, 1, null], form.Mapping); + Assert.Equal(CsvImportState.Ready, form.State); + Assert.True(form.CanImport); + } + + [Fact] + public void AnOlderReadDoesNotReplaceTheLatest() + { + var form = Form(); + var older = form.Read(CsvDelimiter.Comma, hasHeader: true); + var latest = form.Read(CsvDelimiter.Semicolon, hasHeader: false); + + Assert.False(form.Show(older, People(), [null, 0, 1, null])); + Assert.False(form.Fail(older, Failure("import.malformed"))); + Assert.Equal(CsvImportState.Reading, form.State); + Assert.Equal(new CsvOptions(CsvDelimiter.Semicolon, HasHeader: false, NullText: string.Empty), form.Options); + + Assert.True(form.Show(latest, People(), [null, 1, null, null])); + Assert.Equal([null, 1, null, null], form.Mapping); + } + + [Fact] + public void AFieldIsNamedByItsHeaderOrByPositionWithTheFirstRowsValueAsItsSample() + { + var form = Form(); + var preview = new CsvPreview(["name", " ", ""], [["Ada", "", "two\nlines"], ["Grace", "x", "y"]], false); + + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), preview, []); + + Assert.Equal( + [new CsvField(0, "name", "Ada"), new CsvField(1, null, null), new CsvField(2, null, "two lines")], + form.Fields); + } + + [Fact] + public void EachColumnSaysWhatItTakes() + { + var form = Form(); + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, 0, null, null]); + + Assert.Equal(CsvColumnNote.ServerFilled, form.Line(0).Note); + var name = form.Line(1); + Assert.Equal(CsvColumnNote.Samples, name.Note); + Assert.Equal(0, name.Field); + Assert.Equal(["Ada", "Grace", "Linus"], name.Samples); + Assert.Equal(CsvColumnNote.LeftOut, form.Line(2).Note); + Assert.Empty(form.Line(2).Samples); + Assert.Equal(CsvColumnNote.UsesDefault, form.Line(3).Note); + } + + [Fact] + public void AFieldHoldingTheNullTextSamplesAsNull() + { + var form = Form(); + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, 0, 1, null]); + + Assert.Equal(["London", null, "Helsinki"], form.Line(2).Samples); + + form.SetNullText("Helsinki"); + Assert.Equal(["London", string.Empty, null], form.Line(2).Samples); + } + + [Fact] + public void TheNullTextKeepsThePreviewAndTheMapping() + { + var form = Form(); + form.Show(form.Read(CsvDelimiter.Pipe, hasHeader: true), People(), [null, 1, 0, null]); + + form.SetNullText("\\N"); + + Assert.Equal(new CsvOptions(CsvDelimiter.Pipe, HasHeader: true, NullText: "\\N"), form.Options); + Assert.False(form.IsReading); + Assert.Equal([null, 1, 0, null], form.Mapping); + Assert.Equal(CsvImportState.Ready, form.State); + } + + [Fact] + public void TheDialogListsSkipFirstThenEachField() + { + var form = Form(); + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, null, null, null]); + + form.Choose(1, 2); + Assert.Equal(1, form.Mapping[1]); + Assert.Equal(2, form.Choice(1)); + + form.Choose(1, 0); + Assert.Null(form.Mapping[1]); + Assert.Equal(0, form.Choice(1)); + + form.Choose(0, 1); + form.Choose(2, 3); + Assert.Null(form.Mapping[0]); + Assert.Null(form.Mapping[2]); + } + + [Fact] + public void ImportWaitsForARowAndAMappedField() + { + var form = Form(); + var headerOnly = new CsvPreview(["name", "city"], [], false); + + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), headerOnly, [null, 0, 1, null]); + Assert.Equal(CsvImportState.NoRows, form.State); + Assert.False(form.CanImport); + + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, null, null, null]); + Assert.Equal(CsvImportState.NothingMapped, form.State); + Assert.False(form.CanImport); + + form.Map(2, 1); + Assert.True(form.CanImport); + + form.IsPlanning = true; + Assert.False(form.CanImport); + + form.IsPlanning = false; + form.Read(CsvDelimiter.Tab, hasHeader: true); + Assert.Equal(CsvImportState.Reading, form.State); + Assert.False(form.CanImport); + } + + [Fact] + public void AFailedReadSaysWhyAndLeavesNothingMapped() + { + var form = Form(); + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, 0, 1, null]); + var error = Failure("import.too_many_fields"); + + Assert.True(form.Fail(form.Read(CsvDelimiter.Semicolon, hasHeader: true), error)); + + Assert.Equal(CsvImportState.Failed, form.State); + Assert.Same(error, form.ReadError); + Assert.Empty(form.Fields); + Assert.Equal([null, null, null, null], form.Mapping); + Assert.Null(form.Summary); + Assert.False(form.CanImport); + } + + [Fact] + public void TheSummaryCountsTheFieldsAndTheRowsShown() + { + var form = Form(); + + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(truncated: true), []); + + Assert.Equal(new CsvPreviewSummary(2, 4, Truncated: true), form.Summary); + } + + [Theory] + [InlineData("Ada", "Ada")] + [InlineData("two\r\nlines\tand a tab", "two lines and a tab")] + [InlineData("0123456789012345678901234567890123456789", "0123456789012345678901234567890123456789")] + [InlineData("01234567890123456789012345678901234567890", "0123456789012345678901234567890123456789...")] + public void AValueIsShownAsOneShortLine(string text, string shown) => + Assert.Equal(shown, CsvImportForm.Clip(text)); + + [Fact] + public void AValueIsNeverCutBetweenTheHalvesOfACharacter() + { + var text = new string('a', CsvImportForm.SampleLength - 1) + "😀tail"; + + Assert.Equal(new string('a', CsvImportForm.SampleLength - 1) + "...", CsvImportForm.Clip(text)); + } + + [Fact] + public void TheReviewListsWholeStatementsWhileTheyFit() + { + Assert.Equal( + new CsvImportReview("INSERT 1;\n\nINSERT 2;", 2), + CsvImportForm.Review(["INSERT 1", "INSERT 2"], 100)); + Assert.Equal(new CsvImportReview("aaaa;", 1), CsvImportForm.Review(["aaaa", "bbbb"], 8)); + Assert.Equal(new CsvImportReview("abcde...", 1), CsvImportForm.Review(["abcdefghij", "k"], 5)); + Assert.Equal(new CsvImportReview(string.Empty, 0), CsvImportForm.Review([], 5)); + } + + [Fact] + public void AnOutcomeSaysWhetherTheTableChanged() + { + var error = Failure("driver.server"); + var lines = new LineSpan(12, 12); + + Assert.Equal( + new CsvImportReport(CsvImportEnding.Imported, 3, null, null), + CsvImportReport.From(new CsvImportOutcome.Imported(3))); + Assert.Equal( + new CsvImportReport(CsvImportEnding.NotWritten, 0, lines, error), + CsvImportReport.From(new CsvImportOutcome.RolledBack(error, lines))); + Assert.Equal( + new CsvImportReport(CsvImportEnding.PartlyWritten, 10, lines, error), + CsvImportReport.From(new CsvImportOutcome.PartlyWritten(error, 10, lines))); + Assert.Equal( + new CsvImportReport(CsvImportEnding.Unknown, 0, null, error), + CsvImportReport.From(new CsvImportOutcome.Unknown(error))); + + Assert.True(CsvImportReport.From(new CsvImportOutcome.Imported(3)).TableChanged); + Assert.True(CsvImportReport.From(new CsvImportOutcome.PartlyWritten(error, 0, null)).TableChanged); + Assert.True(CsvImportReport.From(new CsvImportOutcome.Unknown(error)).TableChanged); + Assert.True(CsvImportReport.Stopped.TableChanged); + Assert.False(CsvImportReport.From(new CsvImportOutcome.RolledBack(error, null)).TableChanged); + Assert.False(CsvImportReport.Refused(error).TableChanged); + } + + // The id is an identity the server fills; joined has a default, city takes NULL. + private static ImportColumn[] Columns() => + [ + new ImportColumn("id", "INTEGER", Nullable: false, HasDefault: false, ServerFilled: true), + new ImportColumn("name", "TEXT", Nullable: false, HasDefault: false, ServerFilled: false), + new ImportColumn("city", "TEXT", Nullable: true, HasDefault: false, ServerFilled: false), + new ImportColumn("joined", "DATE", Nullable: true, HasDefault: true, ServerFilled: false), + ]; + + private static CsvImportForm Form() => new(Columns(), Path.Combine("data", "people.csv")); + + private static CsvPreview People(bool truncated = false) => new( + ["name", "city"], + [["Ada", "London"], ["Grace", string.Empty], ["Linus", "Helsinki"], ["Ken", "Murray Hill"]], + truncated); + + private static CoreError Failure(string code) => new(code, [code], code, null, null); +} diff --git a/windows/tests/TablePro.App.Model.Tests/HistoryListTests.cs b/windows/tests/TablePro.App.Model.Tests/HistoryListTests.cs index 9348ca4037..9635f3edd2 100644 --- a/windows/tests/TablePro.App.Model.Tests/HistoryListTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/HistoryListTests.cs @@ -219,10 +219,44 @@ public async Task APageThatFailsKeepsTheRunsShownAndCanBeAskedForAgain() Assert.Null(list.Failure); } + [Fact] + public async Task APinnedRunComesFirstAndAnUnpinnedOneGoesBack() + { + var list = new HistoryList(_store, Chinook); + await list.SearchAsync(string.Empty); + + await list.SetPinnedAsync(list.Entries[3], pinned: true); + + Assert.Equal([2, 5, 4, 3, 1], Ids(list)); + Assert.True(list.Entries[0].Pinned); + Assert.Equal((2L, true), Assert.Single(_store.Pins)); + + await list.SetPinnedAsync(list.Entries[0], pinned: false); + + Assert.Equal([5, 4, 3, 2, 1], Ids(list)); + Assert.All(list.Entries, entry => Assert.False(entry.Pinned)); + Assert.Null(list.Failure); + } + + [Fact] + public async Task APinThatFailsKeepsTheRunsAndSaysWhy() + { + var list = new HistoryList(_store, Chinook); + await list.SearchAsync(string.Empty); + _store.Failure = Errors.Of("storage.not_found"); + + await list.SetPinnedAsync(list.Entries[3], pinned: true); + + Assert.Equal("storage.not_found", list.Failure?.Code); + Assert.Equal([5, 4, 3, 2, 1], Ids(list)); + Assert.Empty(_store.Pins); + Assert.False(list.IsLoading); + } + private static IEnumerable Ids(HistoryList list) => list.Entries.Select(entry => entry.Id); } -// Newest first, paged by offset behind a cursor only it reads back, as the core's store pages. +// Pinned first, then newest, paged by offset behind a cursor only it reads back, as the core's store pages. internal sealed class FakeHistoryStore : IHistoryStore { private readonly Dictionary _cursors = new(ReferenceEqualityComparer.Instance); @@ -243,6 +277,8 @@ internal sealed class FakeHistoryStore : IHistoryStore public int Clears { get; private set; } + public List<(long Id, bool Pinned)> Pins { get; } = []; + public static HistoryEntry Entry(long id, string sql, Guid? connectionId) => new( id, sql, @@ -272,6 +308,7 @@ public async Task SearchAsync( var found = Entries .Where(entry => connectionId is null || entry.ConnectionId == connectionId) .Where(entry => entry.Sql.Contains(text, StringComparison.OrdinalIgnoreCase)) + .OrderByDescending(entry => entry.Pinned) .ToList(); var page = found.Skip(offset).Take(limit).ToList(); HistoryCursor? next = null; @@ -313,6 +350,23 @@ public Task ClearAsync(CancellationToken cancellationToken) return Task.CompletedTask; } + public Task SetPinnedAsync(long id, bool pinned) + { + if (Failure is { } failure) + { + return Task.FromException(new TableProException(failure)); + } + + Pins.Add((id, pinned)); + var at = Entries.FindIndex(entry => entry.Id == id); + if (at >= 0) + { + Entries[at] = Entries[at] with { Pinned = pinned }; + } + + return Task.CompletedTask; + } + // Only the core makes a cursor; a test needs one it can tell apart from the others. private static HistoryCursor Cursor() => (HistoryCursor)RuntimeHelpers.GetUninitializedObject(typeof(HistoryCursor)); diff --git a/windows/tests/TablePro.App.Model.Tests/SavedQueryTreeTests.cs b/windows/tests/TablePro.App.Model.Tests/SavedQueryTreeTests.cs new file mode 100644 index 0000000000..ab29353759 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/SavedQueryTreeTests.cs @@ -0,0 +1,150 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class SavedQueryTreeTests +{ + private static readonly SavedQueryList Library = new( + [ + Query(1, "Top second", null, 1), + Query(2, "Monthly totals", 11, 0), + Query(3, "Top first", null, 0), + Query(4, "Invoices", 10, 1), + Query(5, "Customers", 10, 0), + ], + [ + Folder(10, "Reports", null, 1), + Folder(11, "Monthly", 10, 0), + Folder(12, "Admin", null, 0), + Folder(13, "Archive", 10, 1), + ]); + + [Fact] + public void EachLevelListsItsFoldersThenItsQueriesInTheirOrder() + { + var roots = SavedQueryTree.Build(Library); + + Assert.Equal(["Admin", "Reports", "Top first", "Top second"], roots.Select(node => node.Name)); + var reports = roots[1]; + Assert.Equal(10L, reports.Folder?.Id); + Assert.Equal(["Monthly", "Archive", "Customers", "Invoices"], reports.Children.Select(node => node.Name)); + Assert.Equal(["Monthly totals"], reports.Children[0].Children.Select(node => node.Name)); + Assert.Empty(roots[0].Children); + Assert.Null(roots[2].Folder); + Assert.Equal(3L, roots[2].Query?.Id); + } + + [Fact] + public void APlaceTheListLacksShowsAtTheTopLevel() + { + var list = new SavedQueryList([Query(1, "Lost", 99, 0)], [Folder(10, "Orphan", 98, 0)]); + + var roots = SavedQueryTree.Build(list); + + Assert.Equal(["Orphan", "Lost"], roots.Select(node => node.Name)); + } + + [Fact] + public void AnEmptyListBuildsNoRows() + { + Assert.Empty(SavedQueryTree.Build(new SavedQueryList([], []))); + Assert.Empty(SavedQueryTree.Folders(new SavedQueryList([], []))); + } + + [Fact] + public void FoldersComeInTreeOrderWithThePathAboveEach() + { + var folders = SavedQueryTree.Folders(Library); + + Assert.Equal([12, 10, 11, 13], folders.Select(folder => folder.Id)); + Assert.Equal(["Admin", "Reports", "Reports / Monthly", "Reports / Archive"], folders.Select(folder => folder.Path)); + Assert.Equal([0, 0, 1, 1], folders.Select(folder => folder.Depth)); + Assert.Equal("Monthly", folders[2].Name); + } + + [Fact] + public void AFolderLeadsUpToTheTopLevel() + { + Assert.Equal([11, 10], SavedQueryTree.FolderAndAncestors(11, Library)); + Assert.Equal([12], SavedQueryTree.FolderAndAncestors(12, Library)); + Assert.Empty(SavedQueryTree.FolderAndAncestors(99, Library)); + } + + [Fact] + public void AFolderLoopEndsTheWayUp() + { + var list = new SavedQueryList([], [Folder(1, "A", 2, 0), Folder(2, "B", 1, 0)]); + + Assert.Equal([1, 2], SavedQueryTree.FolderAndAncestors(1, list)); + } + + [Theory] + [InlineData("-- Get active users\nSELECT * FROM users WHERE active = 1", "Get active users")] + [InlineData("SELECT * FROM orders", "SELECT * FROM orders")] + [InlineData("--\nSELECT 1", "SELECT 1")] + [InlineData("\r\n \r\n -- Totals \r\nSELECT 1", "Totals")] + [InlineData(" select 1 ", "select 1")] + [InlineData("", "Untitled")] + [InlineData("--\n -- \n", "Untitled")] + public void TheAutomaticNameIsTheFirstCommentOrLine(string sql, string name) + { + Assert.Equal(name, SavedQueryText.AutoName(sql, "Untitled")); + } + + [Fact] + public void TheAutomaticNameIsCutToFiftyCharacters() + { + Assert.Equal(new string('A', 50), SavedQueryText.AutoName(new string('A', 100), "Untitled")); + } + + [Fact] + public void TheCutNeverSplitsACharacter() + { + var sql = new string('a', 49) + "\U0001F600" + "tail"; + + var name = SavedQueryText.AutoName(sql, "Untitled"); + + Assert.Equal(new string('a', 49), name); + } + + [Theory] + [InlineData("\n\n SELECT 1\nFROM t", "SELECT 1")] + [InlineData("-- note\nSELECT 1", "-- note")] + [InlineData(" \n ", "")] + public void TheCaptionIsTheFirstLineWithText(string sql, string line) + { + Assert.Equal(line, SavedQueryText.FirstLine(sql)); + } + + [Fact] + public void WithNoQueryTabTheQueryOpensInANewTab() + { + Assert.Equal( + new SavedQueryInsertion(SavedQueryInsertKind.NewTab, "SELECT 1"), + SavedQueryText.Insertion(null, "SELECT 1")); + } + + [Theory] + [InlineData("")] + [InlineData(" \n\t ")] + public void ABlankEditorTakesTheQuery(string text) + { + Assert.Equal( + new SavedQueryInsertion(SavedQueryInsertKind.Replace, "SELECT 1"), + SavedQueryText.Insertion(text, "SELECT 1")); + } + + [Fact] + public void AnEditorWithTextGetsTheQueryAfterABlankLine() + { + Assert.Equal( + new SavedQueryInsertion(SavedQueryInsertKind.Append, "\n\nSELECT * FROM users"), + SavedQueryText.Insertion("SELECT 1", "SELECT * FROM users")); + } + + private static SavedQuery Query(long id, string name, long? folderId, long order) => + new(id, name, $"SELECT {id}", null, folderId, order, DateTimeOffset.FromUnixTimeSeconds(1_700_000_000)); + + private static SavedQueryFolder Folder(long id, string name, long? parentId, long order) => + new(id, name, parentId, order); +} diff --git a/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs new file mode 100644 index 0000000000..34418d59e6 --- /dev/null +++ b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs @@ -0,0 +1,45 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Definitions; +using FlaUI.Core.Tools; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + [Theory] + [MemberData(nameof(Themes))] + public void ADuplicateOpensTheFormOnTheCopyAndAnExportWritesTheFile(string theme) + { + using var app = AppSession.Launch(theme); + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + app.Find("HomeItem").AsListBoxItem().Select(); + var tree = app.Find("ConnectionTree"); + + app.Front(); + app.RightClick( + app.FindByNamePrefix("Chinook (Sample),", tree), + () => app.TryFindMenuItem("Duplicate") is not null); + app.FindMenuItem("Duplicate").Patterns.Invoke.Pattern.Invoke(); + var form = app.WaitForWindow("Edit connection"); + Assert.Equal("Chinook (Sample) (Copy)", app.Find("NameBox", form).AsTextBox().Text); + app.Screenshot("78-duplicate-connection", form); + app.Find("CancelButton", form).AsButton().Invoke(); + app.WaitForClose("Edit connection"); + app.FindByNamePrefix("Chinook (Sample) (Copy),", tree); + + var file = Path.Combine(app.DataFolder, "exported-connections.json"); + app.Click(app.Find("ExportConnectionsButton"), () => app.HasWindow("Save As")); + var save = app.WaitForWindow("Save As"); + var name = Retry.WhileNull( + () => save.FindFirstDescendant(condition => condition.ByControlType(ControlType.Edit).And(condition.ByName("File name:"))), + AppSession.Wait) + .Result ?? throw new InvalidOperationException("The Save As dialog has no File name box."); + name.AsTextBox().Text = file; + app.Find("1", save).AsButton().Invoke(); + Assert.True(Retry.WhileFalse(() => File.Exists(file), AppSession.Wait).Success, "The export wrote no file."); + app.FindByNamePrefix("Exported 2 connections.", app.Find("HomeMessageBar")); + app.Screenshot("79-connections-exported"); + var text = File.ReadAllText(file); + Assert.Contains("Chinook (Sample) (Copy)", text, StringComparison.Ordinal); + } +} diff --git a/windows/tests/TablePro.App.UITests/CsvImportTests.cs b/windows/tests/TablePro.App.UITests/CsvImportTests.cs new file mode 100644 index 0000000000..e1186a5cb2 --- /dev/null +++ b/windows/tests/TablePro.App.UITests/CsvImportTests.cs @@ -0,0 +1,121 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Definitions; +using FlaUI.Core.Input; +using FlaUI.Core.Tools; +using FlaUI.Core.WindowsAPI; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + [Theory] + [MemberData(nameof(Themes))] + public void ACsvFileImportsIntoATableByItsColumnMapping(string theme) + { + using var app = AppSession.Launch(theme); + // Name matches the Genre table's column and Notes none, so GenreId is left to SQLite's rowid. + var file = Path.Combine(app.DataFolder, "genres.csv"); + File.WriteAllText(file, "Name,Notes\r\nTablePro Jazz,first\r\nTablePro Folk,second\r\n"); + + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + var tree = app.Find("ObjectTree"); + app.RightClick(app.FindByName("Genre", tree), () => app.TryFindMenuItem("Import CSV...") is not null); + // A click, not UIA's Invoke, which would wait on the picker the item opens. + app.Click(app.FindMenuItem("Import CSV...")); + OpenInFileDialog(app, file); + + Assert.Equal( + "2 fields, 2 rows.", + AppSession.WaitForText(app.Find("ImportCsvSummary"), text => text == "2 fields, 2 rows.")); + Assert.Equal("From genres.csv", app.Find("ImportCsvFile").Name); + Assert.Equal("Skip", app.Find("ImportCsvField0").AsComboBox().SelectedItem?.Text); + Assert.Equal("Name (TablePro Jazz)", app.Find("ImportCsvField1").AsComboBox().SelectedItem?.Text); + Assert.Equal("TablePro Jazz · TablePro Folk", app.Find("ImportCsvNote1").Name); + Assert.True(Retry.WhileFalse( + () => app.Find("PrimaryButton").IsEnabled, + AppSession.Wait, + throwOnTimeout: false).Success); + app.Screenshot("75-csv-import-dialog"); + + // Safe Mode may ask first, listing the INSERT the rows go out as. + app.PressDialogButton(); + var review = Retry.WhileNull( + () => app.TryFind("ImportReviewStatements"), + TimeSpan.FromSeconds(3), + throwOnTimeout: false).Result; + if (review is not null) + { + Assert.Contains("INSERT", review.Name, StringComparison.OrdinalIgnoreCase); + app.PressDialogButton(); + } + + Assert.True(Retry.WhileTrue( + () => app.TryFind("ImportCsvSummary") is not null || app.TryFind("ImportReviewStatements") is not null, + AppSession.Wait, + throwOnTimeout: false).Success); + + app.Click(app.FindByName("Genre", tree), () => app.TryFind("TableStatus") is not null); + var status = app.Find("TableStatus"); + // The tab can read its page before the import's rows land, so it reads it again until they show. + var shown = ShowsRows(status, 27); + for (var attempt = 0; attempt < 3 && !shown; attempt++) + { + app.Find("RefreshTableButton").AsButton().Invoke(); + shown = ShowsRows(status, 27); + } + + Assert.True(shown, status.Properties.Name.ValueOrDefault); + var grid = app.Find("ResultsGrid"); + Assert.Equal("TablePro Jazz", app.WaitForCell(grid, 25, 1, value => value == "TablePro Jazz")); + Assert.Equal("TablePro Folk", app.WaitForCell(grid, 26, 1, value => value == "TablePro Folk")); + app.Screenshot("76-csv-imported"); + } + + private static bool ShowsRows(AutomationElement status, int rows) => + Retry.WhileFalse( + () => (status.Properties.Name.ValueOrDefault ?? string.Empty) + .StartsWith($"Rows: {rows} ", StringComparison.Ordinal), + TimeSpan.FromSeconds(10), + throwOnTimeout: false).Success; + + // The system's Open dialog is Win32: control 1148 is its File name box, and Enter opens the path typed there. + private static void OpenInFileDialog(AppSession app, string path) + { + for (var attempt = 0; attempt < 3; attempt++) + { + var dialog = Retry.WhileNull(() => FileDialog(app), AppSession.Wait, throwOnTimeout: false).Result + ?? throw new InvalidOperationException("The Open dialog did not appear."); + var name = Retry.WhileNull( + () => dialog.FindFirstDescendant(condition => + condition.ByAutomationId("1148").And(condition.ByControlType(ControlType.Edit))), + AppSession.Wait, + throwOnTimeout: false).Result + ?? throw new InvalidOperationException("The Open dialog has no File name box."); + dialog.SetForeground(); + name.Focus(); + name.AsTextBox().Text = path; + Keyboard.Type(VirtualKeyShort.RETURN); + if (Retry.WhileFalse(() => FileDialog(app) is null, TimeSpan.FromSeconds(5), throwOnTimeout: false).Success) + { + return; + } + } + + throw new InvalidOperationException("The Open dialog did not take the file."); + } + + // The app's window owns the dialog, so UI Automation may list it under that window or under the desktop. + private static Window? FileDialog(AppSession app) + { + var owned = app.Window.FindFirstChild(condition => condition.ByClassName("#32770")); + if (owned is not null) + { + return owned.AsWindow(); + } + + var process = app.Window.Properties.ProcessId.Value; + return app.Window.Automation.GetDesktop() + .FindFirstChild(condition => condition.ByClassName("#32770").And(condition.ByProcessId(process))) + ?.AsWindow(); + } +} diff --git a/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs b/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs new file mode 100644 index 0000000000..01661d51c0 --- /dev/null +++ b/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs @@ -0,0 +1,116 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Definitions; +using FlaUI.Core.Tools; +using FlaUI.Core.WindowsAPI; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + private const string FiveTracks = "SELECT Name FROM Track LIMIT 5;"; + + [Theory] + [MemberData(nameof(Themes))] + public void AQueryIsSavedIntoAFolderAndARunIsPinned(string theme) + { + using var app = AppSession.Launch(theme); + + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + app.FindByName("Track", app.Find("ObjectTree")); + app.TypeInto("Query 1", FiveTracks); + app.Chord( + () => app.Find("QueryStatus").Name.StartsWith("Rows: 5", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, + VirtualKeyShort.ENTER); + + // The name starts as the query's first line. + app.Click(app.Find("QueryMenu"), () => app.TryFindMenuItem("Save query...") is { IsEnabled: true }); + app.Click(app.FindMenuItem("Save query..."), () => app.TryFind("SavedQueryNameBox") is not null); + var name = app.Find("SavedQueryNameBox").AsTextBox(); + Assert.Equal(FiveTracks, name.Text); + name.Text = "Five tracks"; + app.Screenshot("71-save-query-dialog"); + app.PressDialogButton(); + Assert.True(Retry.WhileTrue(() => app.TryFind("SavedQueryNameBox") is not null, AppSession.Wait, throwOnTimeout: false).Success); + + app.Click(app.Find("ViewMenu"), () => app.TryFindMenuItem("Show saved queries") is not null); + app.Click(app.FindMenuItem("Show saved queries"), () => app.TryFind("SavedQueriesTree") is { IsOffscreen: false }); + var tree = app.Find("SavedQueriesTree"); + AutomationElement Saved() => app.FindByNamePrefix("Five tracks,", tree); + Assert.Equal($"Five tracks, {FiveTracks}", Saved().Name); + app.Screenshot("70-saved-queries"); + + // A blank query tab takes the saved text. + bool Open() => app.Find("Tabs").FindFirstDescendant(condition => condition.ByName("Query 2")) is not null; + app.Chord(Open, VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_T); + InsertSaved(app, Saved, "Query 2"); + Assert.Equal(FiveTracks, AppSession.EditorText(app.FindEditor("Query 2")).TrimEnd('\r', '\n')); + + app.Find("NewSavedFolderButton").AsButton().Invoke(); + var folderName = app.Find("NameDialogBox").AsTextBox(); + Assert.Equal("New folder", folderName.Text); + folderName.Text = "Reports"; + app.PressDialogButton(); + app.FindByName("Reports", tree); + + app.RightClick(Saved(), () => app.TryFindMenuItem("Move to") is not null); + app.OpenSubmenu("Move to", "Reports").Patterns.Invoke.Pattern.Invoke(); + + // The folder opens to show the query moved into it, and closing the folder hides it. + AutomationElement Folder() => app.FindByName("Reports", tree); + bool Shown() => tree.FindFirstDescendant(condition => + condition.ByName($"Five tracks, {FiveTracks}")) is { IsOffscreen: false }; + Assert.True(Retry.WhileFalse( + () => Folder().Patterns.ExpandCollapse.Pattern.ExpandCollapseState.Value == ExpandCollapseState.Expanded && Shown(), + AppSession.Wait, + throwOnTimeout: false).Success); + app.Screenshot("72-saved-query-folders"); + Folder().Patterns.ExpandCollapse.Pattern.Collapse(); + Assert.True(Retry.WhileTrue(Shown, AppSession.Wait, throwOnTimeout: false).Success); + Folder().Patterns.ExpandCollapse.Pattern.Expand(); + Assert.True(Retry.WhileFalse(Shown, AppSession.Wait, throwOnTimeout: false).Success); + + // Showing the history puts the saved queries away. + app.Click(app.Find("ViewMenu"), () => app.TryFindMenuItem("Show query history") is not null); + app.Click(app.FindMenuItem("Show query history"), () => app.TryFind("HistoryList") is { IsOffscreen: false }); + Assert.True(Retry.WhileFalse( + () => app.TryFind("SavedQueriesTree") is null or { IsOffscreen: true }, + AppSession.Wait, + throwOnTimeout: false).Success); + var runs = app.Find("HistoryList"); + app.RightClick(app.FindByNamePrefix(FiveTracks, runs), () => app.TryFindMenuItem("Pin") is not null); + app.FindMenuItem("Pin").Patterns.Invoke.Pattern.Invoke(); + var pinned = Retry.WhileFalse( + () => app.FindByNamePrefix(FiveTracks, runs).Name.EndsWith(", Pinned", StringComparison.Ordinal), + AppSession.Wait, + throwOnTimeout: false).Success; + Assert.True(pinned, app.FindByNamePrefix(FiveTracks, runs).Name); + app.Screenshot("73-history-pinned"); + + app.RightClick(app.FindByNamePrefix(FiveTracks, runs), () => app.TryFindMenuItem("Unpin") is not null); + app.FindMenuItem("Unpin").Patterns.Invoke.Pattern.Invoke(); + Assert.True(Retry.WhileTrue( + () => app.FindByNamePrefix(FiveTracks, runs).Name.EndsWith(", Pinned", StringComparison.Ordinal), + AppSession.Wait, + throwOnTimeout: false).Success); + } + + // The runner's own windows can take a double-click, so it goes again until the editor holds the text. + private static void InsertSaved(AppSession app, Func row, string tab) + { + for (var attempt = 0; attempt < 3; attempt++) + { + app.Front(); + row().DoubleClick(); + if (Retry.WhileFalse( + () => AppSession.EditorText(app.FindEditor(tab)).TrimEnd('\r', '\n').Length > 0, + TimeSpan.FromSeconds(5), + throwOnTimeout: false).Success) + { + return; + } + } + + throw new InvalidOperationException($"Double-clicking the saved query did not fill {tab}."); + } +} diff --git a/windows/tests/TablePro.Interop.Tests/ConnectionCopyTests.cs b/windows/tests/TablePro.Interop.Tests/ConnectionCopyTests.cs new file mode 100644 index 0000000000..6033de5f68 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/ConnectionCopyTests.cs @@ -0,0 +1,64 @@ +namespace TablePro.Interop.Tests; + +public sealed class ConnectionCopyTests : IDisposable +{ + private readonly string _directory = Directory.CreateTempSubdirectory("tablepro-copies-").FullName; + private readonly MemorySecretStore _secrets = new(); + private readonly TableProCore _core; + + public ConnectionCopyTests() + { + _core = TableProCore.Create(new HostConfiguration("test", Path.Combine(_directory, "one")), _secrets); + } + + public void Dispose() + { + _core.Dispose(); + Directory.Delete(_directory, recursive: true); + } + + private static SavedConnection Network(string name) => + new(null, name, "postgres", "db.example.com", 5432, "shop", "app", TlsSettings.Disabled); + + [Fact] + public async Task ACopyLandsAfterItsOriginalWithItsOwnIdAndTheSamePassword() + { + var library = _core.Library; + var shop = await library.SaveAsync(Network("Shop"), new ConnectionSecrets(DatabasePassword: "hunter2")); + var after = await library.SaveAsync(Network("After"), ConnectionSecrets.None); + await library.SetFavoriteAsync(shop.Id!.Value, true); + + var copy = await library.DuplicateAsync(shop.Id.Value, "Shop (Copy)"); + var snapshot = await library.GetSnapshotAsync(); + await library.DeleteAsync(shop.Id.Value); + + Assert.NotEqual(shop.Id, copy.Id); + Assert.Equal("Shop (Copy)", copy.Name); + Assert.Equal(("db.example.com", 5432, "app"), (copy.Host, copy.Port, copy.UserName)); + Assert.Null(copy.LastOpened); + Assert.Equal([shop.Id, copy.Id, after.Id], snapshot.Connections.Select(connection => connection.Id)); + Assert.Equal([shop.Id.Value], snapshot.Favorites); + Assert.Equal("hunter2", _secrets.Load(copy.Id!.Value, SecretKind.DatabasePassword)); + } + + [Fact] + public async Task AnExportedFileHoldsEveryConnectionAndNoPassword() + { + var library = _core.Library; + await library.SaveAsync(Network("Shop"), new ConnectionSecrets(DatabasePassword: "hunter2")); + await library.SaveAsync(Network("Warehouse"), ConnectionSecrets.None); + var file = Path.Combine(_directory, "connections.json"); + + var count = await library.ExportAsync(file); + var text = await File.ReadAllTextAsync(file, TestContext.Current.CancellationToken); + using var elsewhere = TableProCore.Create(new HostConfiguration("test", Path.Combine(_directory, "two")), new MemorySecretStore()); + var imported = await elsewhere.Library.ImportAsync(file); + + Assert.Equal(2, count); + Assert.Contains("Warehouse", text, StringComparison.Ordinal); + Assert.DoesNotContain("hunter2", text, StringComparison.Ordinal); + Assert.Equal(2, imported.Added); + var unnamed = await Assert.ThrowsAsync(() => library.DuplicateAsync(Guid.NewGuid(), " ")); + Assert.Equal("library.name_required", unnamed.Error.Code); + } +} diff --git a/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs b/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs new file mode 100644 index 0000000000..9f7dd99e34 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs @@ -0,0 +1,112 @@ +namespace TablePro.Interop.Tests; + +public sealed class CsvImportTests +{ + private static readonly TableName People = new(null, "people"); + + [Fact] + public async Task AFileLandsInTheTableByTheMappingItsHeadersSuggest() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + var file = await WriteAsync(database, "people.csv", "Name,NOTE\nLinus,kernel\nBarbara,\n", cancellationToken); + using var import = await database.Session.OpenCsvImportAsync(People, cancellationToken); + + var preview = await import.PreviewAsync(file, CsvOptions.Default, cancellationToken); + var mapping = import.SuggestMapping(preview.Headers); + var check = await import.PlanAsync(file, CsvOptions.Default, mapping, cancellationToken); + var outcome = await import.RunAsync(confirmed: false, cancellationToken); + + Assert.Equal(["id", "name", "note"], import.Columns.Select(column => column.Name)); + Assert.Equal(["Name", "NOTE"], preview.Headers); + Assert.Equal(["Linus", "kernel"], preview.Rows[0]); + Assert.False(preview.Truncated); + Assert.Equal([null, 0, 1], mapping); + var ready = Assert.IsType(check); + Assert.Equal(2, ready.Rows); + Assert.Equal(SaveGate.Run, ready.Gate); + Assert.NotEmpty(ready.Statements); + Assert.Equal(new CsvImportOutcome.Imported(2), outcome); + Assert.Equal( + ["Ada", "Grace", "Zoë 👋", "Linus", "Barbara"], + await ReadAsync(database, "SELECT name FROM people ORDER BY id", cancellationToken)); + Assert.Equal("", (await ReadAsync(database, "SELECT note FROM people WHERE name = 'Barbara'", cancellationToken))[0]); + } + + [Fact] + public async Task AFieldTheColumnCannotReadNamesItsLine() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + var file = await WriteAsync(database, "people.tsv", "id\tname\n7\tAda\nseven\tGrace\n", cancellationToken); + var options = CsvOptions.Default with { Delimiter = CsvDelimiter.Tab }; + using var import = await database.Session.OpenCsvImportAsync(People, cancellationToken); + + var check = await import.PlanAsync(file, options, [0, 1, null], cancellationToken); + var unplanned = await Assert.ThrowsAsync(() => import.RunAsync(confirmed: false, cancellationToken)); + + var fault = Assert.IsType(check).Fault; + Assert.Equal((3L, "id", "seven"), (fault.Line, fault.Column, fault.Text)); + Assert.StartsWith("edit.", fault.Reason, StringComparison.Ordinal); + Assert.Equal("import.not_planned", unplanned.Error.Code); + Assert.Equal(SqliteDatabase.PeopleRows, (await ReadAsync(database, "SELECT id FROM people", cancellationToken)).Count); + } + + [Fact] + public async Task ARowTheTableRefusesRollsTheFileBackAndNamesItsLines() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + var file = await WriteAsync(database, "clash.csv", "10,Linus\n1,Taken\n", cancellationToken); + var options = CsvOptions.Default with { HasHeader = false }; + using var import = await database.Session.OpenCsvImportAsync(People, cancellationToken); + + var preview = await import.PreviewAsync(file, options, cancellationToken); + Assert.IsType(await import.PlanAsync(file, options, [0, 1, null], cancellationToken)); + var outcome = await import.RunAsync(confirmed: false, cancellationToken); + + Assert.Equal(["", ""], preview.Headers); + var rolledBack = Assert.IsType(outcome); + Assert.Equal(new LineSpan(1, 2), rolledBack.Lines); + Assert.Equal(SqliteDatabase.PeopleRows, (await ReadAsync(database, "SELECT id FROM people", cancellationToken)).Count); + } + + [Fact] + public async Task AFileThatIsNotTextOrHasNoRowsIsToldApart() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + var binary = Path.Combine(Path.GetDirectoryName(database.Path)!, "binary.csv"); + await File.WriteAllBytesAsync(binary, [(byte)'a', (byte)'\n', 0xff, 0xfe], cancellationToken); + var headerOnly = await WriteAsync(database, "empty.csv", "id,name\n", cancellationToken); + using var import = await database.Session.OpenCsvImportAsync(People, cancellationToken); + + var notText = await Assert.ThrowsAsync(() => import.PreviewAsync(binary, CsvOptions.Default, cancellationToken)); + var empty = await import.PlanAsync(headerOnly, CsvOptions.Default, [0, 1, null], cancellationToken); + var shortMapping = await Assert.ThrowsAsync( + () => import.PlanAsync(headerOnly, CsvOptions.Default, [0], cancellationToken)); + + Assert.Equal("import.not_utf8", notText.Error.Code); + Assert.Same(CsvImportCheck.Empty.Instance, empty); + Assert.Equal("import.mapping_invalid", shortMapping.Error.Code); + } + + private static async Task WriteAsync( + SqliteDatabase database, + string name, + string text, + CancellationToken cancellationToken) + { + var path = Path.Combine(Path.GetDirectoryName(database.Path)!, name); + await File.WriteAllTextAsync(path, text, cancellationToken); + return path; + } + + private static async Task> ReadAsync(SqliteDatabase database, string sql, CancellationToken cancellationToken) + { + using var run = database.Editor.Run(sql, cancellationToken: cancellationToken); + Assert.IsType(await run.Completion); + using var set = run.GetResultSet(0) ?? throw new InvalidOperationException("The read held no set."); + return [.. Enumerable.Range(0, (int)set.RowCount).Select(row => set.GetCellText(row, 0))]; + } +} diff --git a/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs b/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs new file mode 100644 index 0000000000..a06bb1bae1 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs @@ -0,0 +1,152 @@ +namespace TablePro.Interop.Tests; + +public sealed class SavedQueryTests : IDisposable +{ + private static readonly Guid Shop = Guid.Parse("6f0b6a4e-3a52-4c2f-9d1e-0c6a2b7f9e11"); + private static readonly Guid Other = Guid.Parse("1c2d3e4f-5a6b-4c7d-8e9f-a0b1c2d3e4f5"); + + private readonly string _directory = Directory.CreateTempSubdirectory("tablepro-saved-").FullName; + private readonly TableProCore _core; + + public SavedQueryTests() + { + _core = TableProCore.Create(new HostConfiguration("test", _directory), new MemorySecretStore()); + } + + public void Dispose() + { + _core.Dispose(); + try + { + Directory.Delete(_directory, recursive: true); + } + catch (IOException) + { + // The history database closes on the core's own threads, which can still hold it here on Windows. + } + } + + [Fact] + public async Task AQueryIsSavedFiledInAFolderAndReplacedOnlyWhenAsked() + { + var cancellationToken = TestContext.Current.CancellationToken; + using var history = await _core.OpenHistoryAsync(cancellationToken); + using var queries = history.OpenSavedQueries(); + + var reports = await queries.CreateFolderAsync(Shop, "Reports", null); + var monthly = await queries.CreateFolderAsync(Shop, "Monthly", reports); + var id = await queries.SaveAsync(Shop, "shop", "Orders", "SELECT * FROM orders", replace: false); + await queries.SaveAsync(Other, "other", "Elsewhere", "SELECT 1", replace: false); + await queries.MoveAsync(id!.Value, monthly); + var taken = await queries.SaveAsync(Shop, "shop", "Orders", "SELECT 2", replace: false); + var replaced = await queries.SaveAsync(Shop, "shop", "Orders", "SELECT 2", replace: true); + var list = await queries.GetAsync(Shop, cancellationToken); + + Assert.Null(taken); + Assert.Equal(id, replaced); + var query = Assert.Single(list.Queries); + Assert.Equal(("Orders", "SELECT 2", (long?)monthly, 0L), (query.Name, query.Sql, query.FolderId, query.Order)); + Assert.Null(query.Keyword); + Assert.True(query.UpdatedAt > DateTimeOffset.UnixEpoch); + Assert.Equal(2, list.Folders.Count); + Assert.Equal(reports, Assert.Single(list.Folders, folder => folder.Id == monthly).ParentId); + } + + [Fact] + public async Task ARefusedNameOrKeywordThrowsItsCode() + { + using var history = await _core.OpenHistoryAsync(TestContext.Current.CancellationToken); + using var queries = history.OpenSavedQueries(); + var one = await queries.SaveAsync(Shop, "shop", "One", "SELECT 1", replace: false); + var two = await queries.SaveAsync(Shop, "shop", "Two", "SELECT 2", replace: false); + await queries.SetKeywordAsync(one!.Value, "sel"); + await queries.CreateFolderAsync(Shop, "Reports", null); + + var name = await Assert.ThrowsAsync(() => queries.RenameAsync(two!.Value, "One")); + var keyword = await Assert.ThrowsAsync(() => queries.SetKeywordAsync(two!.Value, "SEL")); + var folder = await Assert.ThrowsAsync(() => queries.CreateFolderAsync(Shop, "reports", null)); + var empty = await Assert.ThrowsAsync(() => queries.SaveAsync(Shop, "shop", " ", "SELECT 3", replace: false)); + + Assert.Equal("storage.name_taken", name.Error.Code); + Assert.Equal("storage.keyword_taken", keyword.Error.Code); + Assert.Equal("storage.folder_name_taken", folder.Error.Code); + Assert.Equal("storage.empty_name", empty.Error.Code); + } + + [Fact] + public async Task DeletingAFolderGivesItsQueriesToTheTopAndAConnectionsDataGoesWithIt() + { + var cancellationToken = TestContext.Current.CancellationToken; + using var history = await _core.OpenHistoryAsync(cancellationToken); + using var queries = history.OpenSavedQueries(); + using var favourites = history.OpenFavourites(); + var folder = await queries.CreateFolderAsync(Shop, "Reports", null); + var id = await queries.SaveAsync(Shop, "shop", "Mine", "SELECT 1", replace: false); + await queries.MoveAsync(id!.Value, folder); + await queries.SaveAsync(Other, "other", "Theirs", "SELECT 2", replace: false); + await favourites.AddTableAsync(Shop, new FavouriteTable(null, "main", "orders")); + + await queries.DeleteFolderAsync(folder); + var unfiled = await queries.GetAsync(Shop, cancellationToken); + var removed = await queries.DeleteForConnectionAsync(Shop); + + Assert.Empty(unfiled.Folders); + Assert.Null(Assert.Single(unfiled.Queries).FolderId); + Assert.Equal(1, removed); + Assert.Empty((await queries.GetAsync(Shop, cancellationToken)).Queries); + Assert.Empty(await favourites.GetTablesAsync(Shop)); + Assert.Single((await queries.GetAsync(Other, cancellationToken)).Queries); + } + + [Fact] + public async Task FavouriteTablesAndDatabasesAreKeptPerConnection() + { + using var history = await _core.OpenHistoryAsync(TestContext.Current.CancellationToken); + using var favourites = history.OpenFavourites(); + var orders = new FavouriteTable("shop", null, "orders"); + + await favourites.AddTableAsync(Shop, orders); + await favourites.AddTableAsync(Shop, orders); + await favourites.SetDatabaseAsync(Shop, "shop", DatabaseEnvironment.Testing); + await favourites.SetDatabaseAsync(Shop, "shop", DatabaseEnvironment.Production); + var tables = await favourites.GetTablesAsync(Shop); + var databases = await favourites.GetDatabasesAsync(Shop); + await favourites.RemoveTableAsync(Shop, orders); + await favourites.RemoveDatabaseAsync(Shop, "shop"); + + Assert.Equal(orders, Assert.Single(tables)); + Assert.Equal(new FavouriteDatabase("shop", DatabaseEnvironment.Production), Assert.Single(databases)); + Assert.Empty(await favourites.GetTablesAsync(Shop)); + Assert.Empty(await favourites.GetDatabasesAsync(Shop)); + Assert.Empty(await favourites.GetTablesAsync(Other)); + } + + [Fact] + public async Task APinnedRunComesFirstAndAnExportWritesTheRunsAskedFor() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var session = await _core.OpenFileAsync( + new FileOpenOptions(Path.Combine(_directory, "app.sqlite"), Create: true), + cancellationToken); + using var history = await _core.OpenHistoryAsync(cancellationToken); + var at = DateTimeOffset.FromUnixTimeSeconds(1_700_000_000); + var old = await history.RecordAsync(session, Ran("SELECT 'old'", at), cancellationToken); + var recent = await history.RecordAsync(session, Ran("SELECT 'new'", at.AddMinutes(1)), cancellationToken); + var file = Path.Combine(_directory, "history.sql"); + + await history.SetPinnedAsync(old!.Value, pinned: true); + var pinned = await history.SearchAsync(string.Empty, null, null, 50, cancellationToken); + await history.SetPinnedAsync(old.Value, pinned: false); + var unpinned = await history.SearchAsync(string.Empty, null, null, 50, cancellationToken); + await history.ExportAsync([old.Value], HistoryExportFormat.Sql, file); + + Assert.Equal([(old, true), (recent, false)], pinned.Entries.Select(entry => ((long?)entry.Id, entry.Pinned))); + Assert.Equal([recent, old], unpinned.Entries.Select(entry => (long?)entry.Id)); + var script = await File.ReadAllTextAsync(file, cancellationToken); + Assert.Contains("SELECT 'old'", script, StringComparison.Ordinal); + Assert.DoesNotContain("SELECT 'new'", script, StringComparison.Ordinal); + } + + private static HistoryRun Ran(string sql, DateTimeOffset at) => + new(sql, at, null, null, HistoryOutcome.Succeeded.Instance); +} From e730a3699a2550485a39ffe45748452c50aa8041 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:25:37 +0700 Subject: [PATCH 02/11] fix(windows): run only the CSV import plan the user saw and preview what the import writes --- core/crates/ffi/src/import.rs | 80 ++++++++++++++----- core/crates/ffi/src/library.rs | 16 +++- core/crates/ffi/tests/csv_import.rs | 57 ++++++++++--- ...rage-import-and-library-through-the-ffi.md | 6 +- .../src/TablePro.App.Model/CsvImportForm.cs | 43 ++++++++-- .../TablePro.App/Strings/en-US/Resources.resw | 6 ++ .../src/TablePro.App/Views/ImportCsvDialog.cs | 12 ++- windows/src/TablePro.Interop/CsvImport.cs | 37 +++++++-- .../Generated/tablepro_ffi.cs | 26 +++--- .../CsvImportFormTests.cs | 43 ++++++++-- .../TablePro.Interop.Tests/CsvImportTests.cs | 14 ++-- 11 files changed, 266 insertions(+), 74 deletions(-) diff --git a/core/crates/ffi/src/import.rs b/core/crates/ffi/src/import.rs index 65652f9053..9d7b9369e7 100644 --- a/core/crates/ffi/src/import.rs +++ b/core/crates/ffi/src/import.rs @@ -1,6 +1,7 @@ use std::io::Read; use std::ops::Range; use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; @@ -60,6 +61,8 @@ pub struct ImportColumnInfo { pub has_default: bool, // A generated column or an identity that refuses a value: no field is ever mapped to it. pub server_filled: bool, + // An empty field is an empty value here rather than NULL, when the NULL text is empty. + pub takes_empty: bool, } // A field the column's type cannot read. `line` counts the header as line 1, as a spreadsheet shows it. @@ -75,7 +78,9 @@ pub struct CsvRowFault { #[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] pub enum CsvImportCheck { // `statements` are the SQL texts the rows write as, in order; Safe Mode shows them before a confirmed run. + // `plan` names this plan to `run`, so a plan replaced since is never the one written. Ready { + plan: u64, rows: u64, statements: Vec, gate: SaveGate, @@ -123,9 +128,11 @@ pub struct CsvImport { table: TableRef, columns: Arc<[ImportColumn]>, planned: Mutex>, + plans: AtomicU64, } struct Planned { + id: u64, batch: Arc, step_rows: Vec>, first_line: usize, @@ -162,6 +169,7 @@ impl DatabaseSession { table, columns, planned: Mutex::new(None), + plans: AtomicU64::new(0), })) }) .await @@ -179,6 +187,7 @@ impl CsvImport { nullable: column.info.nullable, has_default: !column.info.default.is_none(), server_filled: column.server_filled, + takes_empty: column.info.column_type.kind.accepts_empty_string(), }) .collect() } @@ -220,6 +229,8 @@ impl CsvImport { format!("{} fields mapped for {} columns", mapping.len(), self.columns.len()), )); } + // A plan that finishes after a later one began is dropped, whatever order they end in. + let id = self.plans.fetch_add(1, Ordering::AcqRel).wrapping_add(1); self.discard(); let dialect = self .session @@ -230,11 +241,12 @@ impl CsvImport { let table = self.table.clone(); let options = CsvImportOptions::from(options); let planned = blocking(&self.tasks, move || { - plan_file(&path, &options, &mapping, &columns, &table, &*dialect, gate) + plan_file(id, &path, &options, &mapping, &columns, &table, &*dialect, gate) }) .await?; let check = match &planned { Ok(Some(planned)) => CsvImportCheck::Ready { + plan: planned.id, rows: u64::try_from(planned.rows).unwrap_or(u64::MAX), statements: planned .batch @@ -248,33 +260,53 @@ impl CsvImport { Err(fault) => CsvImportCheck::RowRefused { fault: fault.clone() }, }; if let Ok(Some(planned)) = planned { - *self.planned.lock().unwrap_or_else(PoisonError::into_inner) = Some(planned); + let mut held = self.planned.lock().unwrap_or_else(PoisonError::into_inner); + if self.plans.load(Ordering::Acquire) != id { + return Err(CoreError::failed( + "import.plan_replaced", + "a later plan replaced this one", + )); + } + *held = Some(planned); } Ok(check) } - // Writes the import planned last, once. `confirmed` says the user answered Safe Mode's question; a level saved - // since the plan refuses before anything is sent. - pub async fn run(&self, confirmed: bool, cancel: Option>) -> Result { - let Some(planned) = self.planned.lock().unwrap_or_else(PoisonError::into_inner).take() else { - return Err(CoreError::failed("import.not_planned", "no import is planned")); - }; - if planned.gate == SaveGate::Confirm && !confirmed { - return Err(CoreError::failed( - "import.not_confirmed", - "Safe Mode asks before this import and it was not answered", - )); - } - match save_gate(self.session.safe_mode()) { - SaveGate::Refuse => { + // Writes the plan `plan` names, once, while it is the last one made. `confirmed` says the user answered Safe Mode's + // question; a level saved since the plan refuses before anything is sent. + pub async fn run( + &self, + plan: u64, + confirmed: bool, + cancel: Option>, + ) -> Result { + // Checked before the plan is taken, so a refusal leaves it to run once answered. + let planned = { + let mut held = self.planned.lock().unwrap_or_else(PoisonError::into_inner); + let Some(planned) = held.as_ref().filter(|planned| planned.id == plan) else { + return Err(CoreError::failed("import.not_planned", "no import is planned")); + }; + if planned.gate == SaveGate::Confirm && !confirmed { return Err(CoreError::failed( - "edit.read_only_connection", - "the connection is read-only", + "import.not_confirmed", + "Safe Mode asks before this import and it was not answered", )); } - now if now != planned.gate => return Err(safe_mode_changed()), - _ => {} - } + match save_gate(self.session.safe_mode()) { + SaveGate::Refuse => { + return Err(CoreError::failed( + "edit.read_only_connection", + "the connection is read-only", + )); + } + now if now != planned.gate => return Err(safe_mode_changed()), + _ => {} + } + held.take() + }; + let Some(planned) = planned else { + return Err(CoreError::failed("import.not_planned", "no import is planned")); + }; let session = self.session.clone(); let cancel = token(cancel); on_runtime(&self.tasks, async move { @@ -316,7 +348,12 @@ impl CsvImport { } } +#[expect( + clippy::too_many_arguments, + reason = "one call, from plan, with what it read from the import" +)] fn plan_file( + id: u64, path: &str, options: &CsvImportOptions, mapping: &[Option], @@ -355,6 +392,7 @@ fn plan_file( let plan = plan_import(dialect, table, columns, rows) .map_err(|error| CoreError::failed(error.code(), error.to_string()))?; Ok(Ok(Some(Planned { + id, batch: Arc::new(plan.batch), step_rows: plan.step_rows, first_line, diff --git a/core/crates/ffi/src/library.rs b/core/crates/ffi/src/library.rs index d3ead72881..1a17a06296 100644 --- a/core/crates/ffi/src/library.rs +++ b/core/crates/ffi/src/library.rs @@ -714,12 +714,22 @@ impl ConnectionLibrary { .and_then(|list| list.connections.iter().find(|saved| saved.id == id).cloned())) }) .await; - match written { - Ok(stored) => Ok(ConnectionRecord::from(&stored.unwrap_or(copy))), - Err(error) => { + let error = match written { + Ok(stored) => return Ok(ConnectionRecord::from(&stored.unwrap_or(copy))), + Err(error) => error, + }; + // A write can fail after the file was replaced, as when the folder's sync fails; a listed copy keeps its secrets. + let id = copy.id; + let listed = self + .blocking(move |store| Ok(store.list_blocking()?.connections.iter().any(|saved| saved.id == id))) + .await; + match listed { + Ok(true) => Ok(ConnectionRecord::from(©)), + Ok(false) => { self.forget_secrets(copy.id).await; Err(error) } + Err(_) => Err(error), } } diff --git a/core/crates/ffi/tests/csv_import.rs b/core/crates/ffi/tests/csv_import.rs index 707560e0db..40e9462753 100644 --- a/core/crates/ffi/tests/csv_import.rs +++ b/core/crates/ffi/tests/csv_import.rs @@ -125,6 +125,14 @@ fn row(values: [Option<&str>; 4]) -> Vec> { values.iter().map(|value| value.map(str::to_owned)).collect() } +// The plan a Ready check names, which run takes; 0 names none, so a run of anything else is refused. +fn plan_of(check: &CsvImportCheck) -> u64 { + match check { + CsvImportCheck::Ready { plan, .. } => *plan, + CsvImportCheck::Empty | CsvImportCheck::RowRefused { .. } => 0, + } +} + fn write(dir: &Path, name: &str, text: &str) -> String { let path = dir.join(name); std::fs::write(&path, text).unwrap(); @@ -147,7 +155,7 @@ async fn a_file_lands_in_the_table_by_the_mapping_its_headers_suggest() { let preview = import.preview(csv.clone(), comma()).await.unwrap(); let mapping = import.suggest_mapping(preview.headers.clone()); let check = import.plan(csv, comma(), mapping.clone()).await.unwrap(); - let outcome = import.run(false, None).await.unwrap(); + let outcome = import.run(plan_of(&check), false, None).await.unwrap(); let names: Vec<(&str, bool)> = columns .iter() @@ -164,6 +172,10 @@ async fn a_file_lands_in_the_table_by_the_mapping_its_headers_suggest() { ] ); assert!(columns[3].has_default && !columns[3].nullable); + assert!( + columns[1].takes_empty && !columns[2].takes_empty, + "text takes an empty value, an integer does not" + ); assert_eq!(preview.headers, ["Name", " AGE ", "id", "joined"]); assert_eq!(preview.rows.len(), 2); assert!(!preview.truncated); @@ -172,12 +184,13 @@ async fn a_file_lands_in_the_table_by_the_mapping_its_headers_suggest() { rows: 2, statements, gate, - } = check + .. + } = &check else { panic!("{check:?}") }; assert!(!statements.is_empty()); - assert_eq!(gate, SaveGate::Run); + assert_eq!(*gate, SaveGate::Run); assert_eq!(outcome, CsvImportOutcome::Imported { rows: 2 }); // An empty field is an empty text in a text column and NULL in a number column. assert_eq!( @@ -187,7 +200,7 @@ async fn a_file_lands_in_the_table_by_the_mapping_its_headers_suggest() { row([Some("2"), Some("Grace"), None, Some("1906")]), ] ); - let again = import.run(false, None).await.unwrap_err(); + let again = import.run(plan_of(&check), false, None).await.unwrap_err(); assert_eq!(again.code(), "import.not_planned"); session.close().await.unwrap(); } @@ -208,7 +221,7 @@ async fn a_field_the_column_cannot_read_names_its_line_and_writes_nothing() { .plan(csv, options, vec![Some(0), Some(1), Some(2), None, None]) .await .unwrap(); - let unplanned = import.run(false, None).await.unwrap_err(); + let unplanned = import.run(1, false, None).await.unwrap_err(); let CsvImportCheck::RowRefused { fault } = check else { panic!("{check:?}") @@ -241,7 +254,7 @@ async fn a_row_the_table_refuses_rolls_the_whole_file_back_and_names_its_lines() .plan(csv, options, vec![Some(0), Some(1), None, None, None]) .await .unwrap(); - let outcome = import.run(false, None).await.unwrap(); + let outcome = import.run(plan_of(&check), false, None).await.unwrap(); assert_eq!(preview.headers, ["", ""], "a file with no header names no field"); assert!(matches!(check, CsvImportCheck::Ready { rows: 2, .. }), "{check:?}"); @@ -347,9 +360,8 @@ async fn confirm_writes_asks_first_and_read_only_refuses() { let import = session.open_csv_import(people(), None).await.unwrap(); let check = import.plan(csv.clone(), comma(), mapping.clone()).await.unwrap(); - let unanswered = import.run(false, None).await.unwrap_err(); - import.plan(csv.clone(), comma(), mapping.clone()).await.unwrap(); - let answered = import.run(true, None).await.unwrap(); + let unanswered = import.run(plan_of(&check), false, None).await.unwrap_err(); + let answered = import.run(plan_of(&check), true, None).await.unwrap(); session.close().await.unwrap(); let read_only = core .open_file( @@ -389,8 +401,33 @@ async fn confirm_writes_asks_first_and_read_only_refuses() { "{refused:?}" ); assert_eq!( - import.run(true, None).await.unwrap_err().code(), + import.run(plan_of(&refused), true, None).await.unwrap_err().code(), "edit.read_only_connection" ); session.close().await.unwrap(); } + +#[tokio::test] +async fn a_plan_made_later_replaces_the_one_before_it() { + let dir = tempfile::tempdir().unwrap(); + let core = core(dir.path()); + let session = seeded(&core, &dir.path().join("people.sqlite")).await; + let first = write(dir.path(), "first.csv", "id,name\n1,Ada\n"); + let second = write(dir.path(), "second.csv", "id,name\n2,Grace\n"); + let mapping = vec![Some(0), Some(1), None, None, None]; + let import = session.open_csv_import(people(), None).await.unwrap(); + + let earlier = import.plan(first, comma(), mapping.clone()).await.unwrap(); + let later = import.plan(second, comma(), mapping).await.unwrap(); + let replaced = import.run(plan_of(&earlier), false, None).await.unwrap_err(); + let outcome = import.run(plan_of(&later), false, None).await.unwrap(); + + assert_ne!(plan_of(&earlier), plan_of(&later)); + assert_eq!(replaced.code(), "import.not_planned"); + assert_eq!(outcome, CsvImportOutcome::Imported { rows: 1 }); + assert_eq!( + rows(&session).await, + [row([Some("2"), Some("Grace"), None, Some("today")])] + ); + session.close().await.unwrap(); +} diff --git a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md index c653e20234..5d90b7d1e4 100644 --- a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md +++ b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md @@ -12,9 +12,9 @@ The Windows app reaches the core only through `crates/ffi`. Saved queries with f - `QueryHistoryStore` gains `set_pinned`, `export(ids, format, path)` and two stores over the same database: `saved_queries()` and `favourites()`. - `SavedQueryStore` reads a connection's queries and folders in one transaction (`snapshot`) and writes through `SavedQueries` and `SavedQueryFolders` as they are. `save(draft, replace)` gives the id, or nothing when the name is taken and `replace` is false, so the app asks before replacing. `delete_for_connection` takes a deleted connection's queries, folders and favourites. - `FavouriteStore` lists, marks and unmarks tables and databases per connection, a database with one of the four environments. -- `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the row count, the statements' SQL and the Safe Mode gate. -- `CsvImport::run(confirmed)` writes the import planned last, once, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack`, `PartlyWritten` with the rows before it on an engine without a transaction, or `Unknown`. -- `ConnectionLibrary::duplicate(id, name)` copies the connection under a new id right after the original (`insert_after_blocking`), never opened and no favourite, after copying every secret kind the original keeps; a refused secret or write takes the copy's secrets back. The app names the copy, since the name is in the user's language. `export_file(path)` writes `export_blocking`'s document, which carries no secret. +- `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the plan's id, the row count, the statements' SQL and the Safe Mode gate. Each column says whether an empty field is an empty value in it (`takes_empty`), so a preview shows what the import writes. +- `CsvImport::run(plan, confirmed)` writes the plan `Ready` named, once and only while no later plan replaced it, so a plan still finishing after the user moved on is never the one written, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack`, `PartlyWritten` with the rows before it on an engine without a transaction, or `Unknown`. +- `ConnectionLibrary::duplicate(id, name)` copies the connection under a new id right after the original (`insert_after_blocking`), never opened and no favourite, after copying every secret kind the original keeps; a refused secret takes the copy's secrets back, and so does a refused write unless the list shows the copy saved after all. The app names the copy, since the name is in the user's language. `export_file(path)` writes `export_blocking`'s document, which carries no secret. - History exports and connection exports are written beside the target and renamed over it once synced, as result exports are. ## Rationale diff --git a/windows/src/TablePro.App.Model/CsvImportForm.cs b/windows/src/TablePro.App.Model/CsvImportForm.cs index c42e8c89d4..35c81958f6 100644 --- a/windows/src/TablePro.App.Model/CsvImportForm.cs +++ b/windows/src/TablePro.App.Model/CsvImportForm.cs @@ -35,8 +35,20 @@ public enum CsvImportEnding // Header is null where the file names none. Sample is the first row's value, null when it has none. public sealed record CsvField(int Index, string? Header, string? Sample); -// Samples hold null where the file's NULL text stands. -public sealed record CsvColumnLine(ImportColumn Column, int? Field, CsvColumnNote Note, IReadOnlyList Samples); +public enum CsvSampleKind +{ + Text, + Empty, + Null, + + // A NOT NULL column with a default takes its default for the NULL text, as the core imports it. + Default, +} + +// A field's value as the import writes it into the column, which the NULL text and the column's type decide. +public sealed record CsvSample(CsvSampleKind Kind, string Text); + +public sealed record CsvColumnLine(ImportColumn Column, int? Field, CsvColumnNote Note, IReadOnlyList Samples); public sealed record CsvPreviewSummary(int Fields, int Rows, bool Truncated); @@ -228,7 +240,7 @@ public CsvColumnLine Line(int column) : field is not null ? CsvColumnNote.Samples : info.HasDefault ? CsvColumnNote.UsesDefault : CsvColumnNote.LeftOut; - return new CsvColumnLine(info, field, note, field is { } index ? Samples(index) : []); + return new CsvColumnLine(info, field, note, field is { } index ? Samples(info, index) : []); } // One line, cut short, so a value fits a list item. @@ -273,13 +285,34 @@ public static CsvImportReview Review(IReadOnlyList statements, int lengt return new CsvImportReview(text.ToString(), shown); } - private IReadOnlyList Samples(int field) => + private IReadOnlyList Samples(ImportColumn column, int field) => Preview is not { } preview ? [] : [.. preview.Rows .Where(row => field < row.Count) .Take(SampleCount) - .Select(row => row[field] == Options.NullText ? null : Clip(row[field]))]; + .Select(row => Sample(column, row[field]))]; + + // The core's rule: the NULL text is an empty value where it is empty and the column takes one, else the default of + // a NOT NULL column that has one, else NULL. + private CsvSample Sample(ImportColumn column, string value) + { + if (string.Equals(value, Options.NullText, StringComparison.Ordinal)) + { + if (value.Length == 0 && column.TakesEmpty) + { + return new CsvSample(CsvSampleKind.Empty, string.Empty); + } + + return !column.Nullable && column.HasDefault + ? new CsvSample(CsvSampleKind.Default, string.Empty) + : new CsvSample(CsvSampleKind.Null, string.Empty); + } + + return value.Length == 0 + ? new CsvSample(CsvSampleKind.Empty, string.Empty) + : new CsvSample(CsvSampleKind.Text, Clip(value)); + } // Never between the halves of a surrogate pair. private static string Cut(string text, int length) => diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index e3a7b12356..ad05151e1f 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -3600,4 +3600,10 @@ New fingerprint: {2} Importing the file into {1}... + + DEFAULT + + + (empty) + diff --git a/windows/src/TablePro.App/Views/ImportCsvDialog.cs b/windows/src/TablePro.App/Views/ImportCsvDialog.cs index 3cfd170848..acc6f84f30 100644 --- a/windows/src/TablePro.App/Views/ImportCsvDialog.cs +++ b/windows/src/TablePro.App/Views/ImportCsvDialog.cs @@ -93,7 +93,7 @@ internal static class ImportCsvDialog CsvImportReport report; try { - var outcome = await import.RunAsync(confirmed, cancellationToken).ConfigureAwait(true); + var outcome = await import.RunAsync(planned, confirmed, cancellationToken).ConfigureAwait(true); report = CsvImportReport.From(outcome); } catch (TableProException exception) @@ -537,7 +537,15 @@ private static string FieldText(CsvField field) CsvColumnNote.UsesDefault => Strings.Get("ImportCsvUsesDefault"), CsvColumnNote.LeftOut => Strings.Get("ImportCsvLeftOut"), _ when line.Samples.Count == 0 => Strings.Get("ImportCsvNoValues"), - _ => string.Join(" · ", line.Samples.Select(sample => sample ?? Strings.Get("GridMenuNull"))), + _ => string.Join(" · ", line.Samples.Select(SampleText)), + }; + + private static string SampleText(CsvSample sample) => sample.Kind switch + { + CsvSampleKind.Null => Strings.Get("GridMenuNull"), + CsvSampleKind.Default => Strings.Get("ImportCsvSampleDefault"), + CsvSampleKind.Empty => Strings.Get("ImportCsvSampleEmpty"), + _ => sample.Text, }; private static string SummaryText(CsvPreviewSummary summary) diff --git a/windows/src/TablePro.Interop/CsvImport.cs b/windows/src/TablePro.Interop/CsvImport.cs index 13362259e0..78ccbb5a09 100644 --- a/windows/src/TablePro.Interop/CsvImport.cs +++ b/windows/src/TablePro.Interop/CsvImport.cs @@ -20,7 +20,14 @@ public sealed record CsvOptions(CsvDelimiter Delimiter, bool HasHeader, string N public sealed record CsvPreview(IReadOnlyList Headers, IReadOnlyList> Rows, bool Truncated); // ServerFilled: a generated column or an identity that refuses a value; no field is ever mapped to it. -public sealed record ImportColumn(string Name, string TypeName, bool Nullable, bool HasDefault, bool ServerFilled); +// TakesEmpty: an empty field is an empty value here rather than NULL, while the NULL text is empty. +public sealed record ImportColumn( + string Name, + string TypeName, + bool Nullable, + bool HasDefault, + bool ServerFilled, + bool TakesEmpty); // Line counts the header as line 1, as a spreadsheet shows it. Reason is the code a cell edit refused alike has. public sealed record CsvRowFault(long Line, string Column, string Text, string Reason); @@ -34,7 +41,11 @@ private CsvImportCheck() } // Statements are the SQL the rows write as, which Safe Mode shows before a confirmed run. - public sealed record Ready(long Rows, IReadOnlyList Statements, SaveGate Gate) : CsvImportCheck; + public sealed record Ready(long Rows, IReadOnlyList Statements, SaveGate Gate) : CsvImportCheck + { + // Names this plan to RunAsync, so a plan made since is never the one written. + internal ulong Plan { get; init; } + } public sealed record Empty : CsvImportCheck { @@ -62,7 +73,7 @@ public sealed record PartlyWritten(CoreError Error, long WrittenRows, LineSpan? public sealed record Unknown(CoreError Error) : CsvImportOutcome; } -// A table's columns as a CSV import writes them; Run writes the import planned last, once. +// A table's columns as a CSV import writes them; RunAsync writes the import planned last, once. public sealed class CsvImport : IDisposable { private readonly Native.CsvImport _import; @@ -75,7 +86,8 @@ internal CsvImport(Native.CsvImport import) column.TypeName, column.Nullable, column.HasDefault, - column.ServerFilled))]; + column.ServerFilled, + column.TakesEmpty))]; } public IReadOnlyList Columns { get; } @@ -122,7 +134,10 @@ public async Task PlanAsync( Native.CsvImportCheck.Ready ready => new CsvImportCheck.Ready( Mapping.Count(ready.Rows), [.. ready.Statements], - Mapping.Gate(ready.Gate)), + Mapping.Gate(ready.Gate)) + { + Plan = ready.Plan, + }, Native.CsvImportCheck.RowRefused refused => new CsvImportCheck.RowRefused(new CsvRowFault( Mapping.Count(refused.Fault.Line), refused.Fault.Column, @@ -132,10 +147,16 @@ public async Task PlanAsync( }; } - // Confirmed says Safe Mode's question was answered; a level saved since the plan refuses before anything is sent. - public async Task RunAsync(bool confirmed, CancellationToken cancellationToken = default) + // Writes the plan PlanAsync gave, once, while no later plan replaced it. Confirmed says Safe Mode's question was + // answered; a level saved since the plan refuses before anything is sent. + public async Task RunAsync( + CsvImportCheck.Ready plan, + bool confirmed, + CancellationToken cancellationToken = default) { - var outcome = await CoreCall.RunAsync(token => _import.Run(confirmed, token), cancellationToken).ConfigureAwait(false); + ArgumentNullException.ThrowIfNull(plan); + var id = plan.Plan; + var outcome = await CoreCall.RunAsync(token => _import.Run(id, confirmed, token), cancellationToken).ConfigureAwait(false); return outcome switch { Native.CsvImportOutcome.Imported imported => new CsvImportOutcome.Imported(Mapping.Count(imported.Rows)), diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 6cad45aa26..af581c1af3 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1940,7 +1940,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_csvimport_run(ulong @ptr,sbyte @confirmed,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_csvimport_run(ulong @ptr,ulong @plan,sbyte @confirmed,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -5824,8 +5824,8 @@ static void uniffiCheckApiChecksums() { } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_csvimport_run(); - if (checksum != 51215) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_run` checksum `51215`, library returned `{checksum}`"); + if (checksum != 28861) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_run` checksum `28861`, library returned `{checksum}`"); } } { @@ -8104,7 +8104,7 @@ internal interface ICsvImport { /// Task Preview(string @path, CsvReadOptions @options); /// - Task Run(bool @confirmed, CancelToken? @cancel); + Task Run(ulong @plan, bool @confirmed, CancelToken? @cancel); uint?[] SuggestMapping(string[] @headers); } internal class CsvImport : ICsvImport, IDisposable { @@ -8249,11 +8249,11 @@ public async Task Preview(string @path, CsvReadOptions @options) { } /// - public async Task Run(bool @confirmed, CancelToken? @cancel) { + public async Task Run(ulong @plan, bool @confirmed, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_run(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@plan), FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12428,7 +12428,8 @@ internal record ImportColumnInfo ( string TypeName, bool Nullable, bool HasDefault, - bool ServerFilled + bool ServerFilled, + bool TakesEmpty ) { } @@ -12441,7 +12442,8 @@ public override ImportColumnInfo Read(BigEndianStream stream) { TypeName: FfiConverterString.INSTANCE.Read(stream), Nullable: FfiConverterBoolean.INSTANCE.Read(stream), HasDefault: FfiConverterBoolean.INSTANCE.Read(stream), - ServerFilled: FfiConverterBoolean.INSTANCE.Read(stream) + ServerFilled: FfiConverterBoolean.INSTANCE.Read(stream), + TakesEmpty: FfiConverterBoolean.INSTANCE.Read(stream) ); } @@ -12451,7 +12453,8 @@ public override int AllocationSize(ImportColumnInfo value) { + FfiConverterString.INSTANCE.AllocationSize(value.TypeName) + FfiConverterBoolean.INSTANCE.AllocationSize(value.Nullable) + FfiConverterBoolean.INSTANCE.AllocationSize(value.HasDefault) - + FfiConverterBoolean.INSTANCE.AllocationSize(value.ServerFilled); + + FfiConverterBoolean.INSTANCE.AllocationSize(value.ServerFilled) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.TakesEmpty); } public override void Write(ImportColumnInfo value, BigEndianStream stream) { @@ -12460,6 +12463,7 @@ public override void Write(ImportColumnInfo value, BigEndianStream stream) { FfiConverterBoolean.INSTANCE.Write(value.Nullable, stream); FfiConverterBoolean.INSTANCE.Write(value.HasDefault, stream); FfiConverterBoolean.INSTANCE.Write(value.ServerFilled, stream); + FfiConverterBoolean.INSTANCE.Write(value.TakesEmpty, stream); } } @@ -14541,6 +14545,7 @@ public override void Write(CsvDelimiterTag value, BigEndianStream stream) { internal record CsvImportCheck { public record Ready ( + ulong Plan, ulong Rows, string[] Statements, SaveGate Gate @@ -14565,6 +14570,7 @@ public override CsvImportCheck Read(BigEndianStream stream) { switch (value) { case 1: return new CsvImportCheck.Ready( + FfiConverterUInt64.INSTANCE.Read(stream), FfiConverterUInt64.INSTANCE.Read(stream), FfiConverterSequenceString.INSTANCE.Read(stream), FfiConverterTypeSaveGate.INSTANCE.Read(stream) @@ -14585,6 +14591,7 @@ public override int AllocationSize(CsvImportCheck value) { switch (value) { case CsvImportCheck.Ready variant_value: return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Plan) + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Rows) + FfiConverterSequenceString.INSTANCE.AllocationSize(variant_value.Statements) + FfiConverterTypeSaveGate.INSTANCE.AllocationSize(variant_value.Gate); @@ -14602,6 +14609,7 @@ public override void Write(CsvImportCheck value, BigEndianStream stream) { switch (value) { case CsvImportCheck.Ready variant_value: stream.WriteInt(1); + FfiConverterUInt64.INSTANCE.Write(variant_value.Plan, stream); FfiConverterUInt64.INSTANCE.Write(variant_value.Rows, stream); FfiConverterSequenceString.INSTANCE.Write(variant_value.Statements, stream); FfiConverterTypeSaveGate.INSTANCE.Write(variant_value.Gate, stream); diff --git a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs index efe028cb5e..17979cf80b 100644 --- a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs @@ -70,22 +70,47 @@ public void EachColumnSaysWhatItTakes() var name = form.Line(1); Assert.Equal(CsvColumnNote.Samples, name.Note); Assert.Equal(0, name.Field); - Assert.Equal(["Ada", "Grace", "Linus"], name.Samples); + Assert.Equal(["Ada", "Grace", "Linus"], name.Samples.Select(sample => sample.Text)); Assert.Equal(CsvColumnNote.LeftOut, form.Line(2).Note); Assert.Empty(form.Line(2).Samples); Assert.Equal(CsvColumnNote.UsesDefault, form.Line(3).Note); } [Fact] - public void AFieldHoldingTheNullTextSamplesAsNull() + public void ASampleShowsWhatTheImportWritesForTheNullText() { var form = Form(); form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, 0, 1, null]); - Assert.Equal(["London", null, "Helsinki"], form.Line(2).Samples); + // An empty field in a text column is an empty value while the NULL text is empty, as the core imports it. + Assert.Equal( + [Text("London"), new CsvSample(CsvSampleKind.Empty, string.Empty), Text("Helsinki")], + form.Line(2).Samples); form.SetNullText("Helsinki"); - Assert.Equal(["London", string.Empty, null], form.Line(2).Samples); + Assert.Equal( + [Text("London"), new CsvSample(CsvSampleKind.Empty, string.Empty), new CsvSample(CsvSampleKind.Null, string.Empty)], + form.Line(2).Samples); + } + + [Fact] + public void TheNullTextIsNullInAColumnThatTakesNoEmptyValueAndTheDefaultWhereTheColumnRefusesNull() + { + ImportColumn[] columns = + [ + new("rank", "INTEGER", Nullable: true, HasDefault: false, ServerFilled: false, TakesEmpty: false), + new("status", "TEXT", Nullable: false, HasDefault: true, ServerFilled: false, TakesEmpty: true), + ]; + var form = new CsvImportForm(columns, Path.Combine("data", "ranks.csv")); + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), new CsvPreview(["rank", "status"], [["", "-"]], false), [0, 1]); + form.SetNullText("-"); + + Assert.Equal([new CsvSample(CsvSampleKind.Empty, string.Empty)], form.Line(0).Samples); + Assert.Equal([new CsvSample(CsvSampleKind.Default, string.Empty)], form.Line(1).Samples); + + form.SetNullText(string.Empty); + Assert.Equal([new CsvSample(CsvSampleKind.Null, string.Empty)], form.Line(0).Samples); + Assert.Equal([Text("-")], form.Line(1).Samples); } [Fact] @@ -232,12 +257,14 @@ public void AnOutcomeSaysWhetherTheTableChanged() // The id is an identity the server fills; joined has a default, city takes NULL. private static ImportColumn[] Columns() => [ - new ImportColumn("id", "INTEGER", Nullable: false, HasDefault: false, ServerFilled: true), - new ImportColumn("name", "TEXT", Nullable: false, HasDefault: false, ServerFilled: false), - new ImportColumn("city", "TEXT", Nullable: true, HasDefault: false, ServerFilled: false), - new ImportColumn("joined", "DATE", Nullable: true, HasDefault: true, ServerFilled: false), + new ImportColumn("id", "INTEGER", Nullable: false, HasDefault: false, ServerFilled: true, TakesEmpty: false), + new ImportColumn("name", "TEXT", Nullable: false, HasDefault: false, ServerFilled: false, TakesEmpty: true), + new ImportColumn("city", "TEXT", Nullable: true, HasDefault: false, ServerFilled: false, TakesEmpty: true), + new ImportColumn("joined", "DATE", Nullable: true, HasDefault: true, ServerFilled: false, TakesEmpty: false), ]; + private static CsvSample Text(string text) => new(CsvSampleKind.Text, text); + private static CsvImportForm Form() => new(Columns(), Path.Combine("data", "people.csv")); private static CsvPreview People(bool truncated = false) => new( diff --git a/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs b/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs index 9f7dd99e34..f0f6503096 100644 --- a/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs +++ b/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs @@ -15,18 +15,21 @@ public async Task AFileLandsInTheTableByTheMappingItsHeadersSuggest() var preview = await import.PreviewAsync(file, CsvOptions.Default, cancellationToken); var mapping = import.SuggestMapping(preview.Headers); var check = await import.PlanAsync(file, CsvOptions.Default, mapping, cancellationToken); - var outcome = await import.RunAsync(confirmed: false, cancellationToken); + var ready = Assert.IsType(check); + var outcome = await import.RunAsync(ready, confirmed: false, cancellationToken); + var again = await Assert.ThrowsAsync(() => import.RunAsync(ready, confirmed: false, cancellationToken)); Assert.Equal(["id", "name", "note"], import.Columns.Select(column => column.Name)); + Assert.Equal([false, true, true], import.Columns.Select(column => column.TakesEmpty)); Assert.Equal(["Name", "NOTE"], preview.Headers); Assert.Equal(["Linus", "kernel"], preview.Rows[0]); Assert.False(preview.Truncated); Assert.Equal([null, 0, 1], mapping); - var ready = Assert.IsType(check); Assert.Equal(2, ready.Rows); Assert.Equal(SaveGate.Run, ready.Gate); Assert.NotEmpty(ready.Statements); Assert.Equal(new CsvImportOutcome.Imported(2), outcome); + Assert.Equal("import.not_planned", again.Error.Code); Assert.Equal( ["Ada", "Grace", "Zoë 👋", "Linus", "Barbara"], await ReadAsync(database, "SELECT name FROM people ORDER BY id", cancellationToken)); @@ -43,7 +46,8 @@ public async Task AFieldTheColumnCannotReadNamesItsLine() using var import = await database.Session.OpenCsvImportAsync(People, cancellationToken); var check = await import.PlanAsync(file, options, [0, 1, null], cancellationToken); - var unplanned = await Assert.ThrowsAsync(() => import.RunAsync(confirmed: false, cancellationToken)); + var unplanned = await Assert.ThrowsAsync( + () => import.RunAsync(new CsvImportCheck.Ready(2, [], SaveGate.Run), confirmed: false, cancellationToken)); var fault = Assert.IsType(check).Fault; Assert.Equal((3L, "id", "seven"), (fault.Line, fault.Column, fault.Text)); @@ -62,8 +66,8 @@ public async Task ARowTheTableRefusesRollsTheFileBackAndNamesItsLines() using var import = await database.Session.OpenCsvImportAsync(People, cancellationToken); var preview = await import.PreviewAsync(file, options, cancellationToken); - Assert.IsType(await import.PlanAsync(file, options, [0, 1, null], cancellationToken)); - var outcome = await import.RunAsync(confirmed: false, cancellationToken); + var ready = Assert.IsType(await import.PlanAsync(file, options, [0, 1, null], cancellationToken)); + var outcome = await import.RunAsync(ready, confirmed: false, cancellationToken); Assert.Equal(["", ""], preview.Headers); var rolledBack = Assert.IsType(outcome); From 334f30480bfa16aa2f05a1a886f7f042d4594a62 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:32:57 +0700 Subject: [PATCH 03/11] fix(windows): edit a saved query by its id and add Save query to the editor's menu --- core/crates/ffi/src/import.rs | 40 +++++++------ core/crates/ffi/src/saved_queries.rs | 6 ++ core/crates/ffi/tests/saved_queries.rs | 26 +++++++++ core/crates/storage/src/saved_queries/mod.rs | 57 +++++++++++++++++++ ...rage-import-and-library-through-the-ffi.md | 2 +- .../TablePro.App/Strings/en-US/Resources.resw | 3 + .../TablePro.App/Views/QueryTabView.xaml.cs | 13 +++++ .../src/TablePro.App/Views/SaveQueryDialog.cs | 4 +- .../TablePro.App/Views/WorkspaceView.xaml.cs | 29 +++++++++- .../Generated/tablepro_ffi.cs | 50 ++++++++++++++++ windows/src/TablePro.Interop/SavedQueries.cs | 7 +++ .../TablePro.Interop.Tests/SavedQueryTests.cs | 6 +- 12 files changed, 221 insertions(+), 22 deletions(-) diff --git a/core/crates/ffi/src/import.rs b/core/crates/ffi/src/import.rs index 9d7b9369e7..4fc961084e 100644 --- a/core/crates/ffi/src/import.rs +++ b/core/crates/ffi/src/import.rs @@ -1,7 +1,6 @@ use std::io::Read; use std::ops::Range; use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; @@ -127,8 +126,14 @@ pub struct CsvImport { tasks: Tasks, table: TableRef, columns: Arc<[ImportColumn]>, - planned: Mutex>, - plans: AtomicU64, + plans: Mutex, +} + +// The last plan begun and the one ready to run, changed together so a slower plan never replaces a later one. +#[derive(Default)] +struct Plans { + last: u64, + ready: Option, } struct Planned { @@ -168,8 +173,7 @@ impl DatabaseSession { tasks, table, columns, - planned: Mutex::new(None), - plans: AtomicU64::new(0), + plans: Mutex::new(Plans::default()), })) }) .await @@ -229,9 +233,12 @@ impl CsvImport { format!("{} fields mapped for {} columns", mapping.len(), self.columns.len()), )); } - // A plan that finishes after a later one began is dropped, whatever order they end in. - let id = self.plans.fetch_add(1, Ordering::AcqRel).wrapping_add(1); - self.discard(); + let id = { + let mut plans = self.plans(); + plans.last = plans.last.wrapping_add(1); + plans.ready = None; + plans.last + }; let dialect = self .session .current_dialect() @@ -260,14 +267,15 @@ impl CsvImport { Err(fault) => CsvImportCheck::RowRefused { fault: fault.clone() }, }; if let Ok(Some(planned)) = planned { - let mut held = self.planned.lock().unwrap_or_else(PoisonError::into_inner); - if self.plans.load(Ordering::Acquire) != id { + // A plan that finishes after a later one began is dropped, whatever order they end in. + let mut plans = self.plans(); + if plans.last != id { return Err(CoreError::failed( "import.plan_replaced", "a later plan replaced this one", )); } - *held = Some(planned); + plans.ready = Some(planned); } Ok(check) } @@ -282,8 +290,8 @@ impl CsvImport { ) -> Result { // Checked before the plan is taken, so a refusal leaves it to run once answered. let planned = { - let mut held = self.planned.lock().unwrap_or_else(PoisonError::into_inner); - let Some(planned) = held.as_ref().filter(|planned| planned.id == plan) else { + let mut plans = self.plans(); + let Some(planned) = plans.ready.as_ref().filter(|planned| planned.id == plan) else { return Err(CoreError::failed("import.not_planned", "no import is planned")); }; if planned.gate == SaveGate::Confirm && !confirmed { @@ -302,7 +310,7 @@ impl CsvImport { now if now != planned.gate => return Err(safe_mode_changed()), _ => {} } - held.take() + plans.ready.take() }; let Some(planned) = planned else { return Err(CoreError::failed("import.not_planned", "no import is planned")); @@ -343,8 +351,8 @@ impl CsvImport { } impl CsvImport { - fn discard(&self) { - *self.planned.lock().unwrap_or_else(PoisonError::into_inner) = None; + fn plans(&self) -> std::sync::MutexGuard<'_, Plans> { + self.plans.lock().unwrap_or_else(PoisonError::into_inner) } } diff --git a/core/crates/ffi/src/saved_queries.rs b/core/crates/ffi/src/saved_queries.rs index 11bca4fe76..80c23a545e 100644 --- a/core/crates/ffi/src/saved_queries.rs +++ b/core/crates/ffi/src/saved_queries.rs @@ -99,6 +99,12 @@ impl SavedQueryStore { on_runtime(&self.tasks, async move { Ok(queries.rename(id, &name).await?) }).await } + // By id, so an edit from a list read before a rename elsewhere still changes the query it showed. + pub async fn set_sql(&self, id: i64, sql: String) -> Result<(), CoreError> { + let queries = self.queries.clone(); + on_runtime(&self.tasks, async move { Ok(queries.set_query(id, &sql).await?) }).await + } + // None or blank clears it. One word of at most 64 characters, unique among the connection's queries in any case. pub async fn set_keyword(&self, id: i64, keyword: Option) -> Result<(), CoreError> { let queries = self.queries.clone(); diff --git a/core/crates/ffi/tests/saved_queries.rs b/core/crates/ffi/tests/saved_queries.rs index fbd09d558c..0a21e17294 100644 --- a/core/crates/ffi/tests/saved_queries.rs +++ b/core/crates/ffi/tests/saved_queries.rs @@ -357,3 +357,29 @@ async fn a_pinned_run_comes_first_and_an_export_writes_the_runs_asked_for() { assert_eq!(relative.code(), "ffi.export_bad_path"); session.close().await.unwrap(); } + +#[tokio::test] +async fn an_edit_by_id_reaches_the_query_after_a_rename_elsewhere() { + let dir = tempfile::tempdir().unwrap(); + let core = started(dir.path()); + let queries = core.history().await.unwrap().saved_queries(); + let id = queries + .save(draft(SHOP, "Daily", "SELECT 1"), false) + .await + .unwrap() + .unwrap(); + queries.rename(id, "Weekly".to_owned()).await.unwrap(); + + queries.set_sql(id, "SELECT 7".to_owned()).await.unwrap(); + let gone = queries.set_sql(9_999, "SELECT 2".to_owned()).await.unwrap_err(); + + let snapshot = queries.snapshot(SHOP.to_owned()).await.unwrap(); + let [query] = snapshot.queries.as_slice() else { + panic!("{:?}", snapshot.queries) + }; + assert_eq!( + (query.id, query.name.as_str(), query.sql.as_str()), + (id, "Weekly", "SELECT 7") + ); + assert_eq!(gone.code(), "storage.not_found"); +} diff --git a/core/crates/storage/src/saved_queries/mod.rs b/core/crates/storage/src/saved_queries/mod.rs index d329bcc0ef..259900372d 100644 --- a/core/crates/storage/src/saved_queries/mod.rs +++ b/core/crates/storage/src/saved_queries/mod.rs @@ -200,6 +200,34 @@ impl SavedQueries { Ok(()) } + // By id, so an edit made from a list read before a rename still reaches the query it showed. + pub async fn set_query(&self, id: i64, query: &str) -> Result<(), StorageError> { + if query.len() > MAX_QUERY_BYTES { + return Err(StorageError::TooLarge { + got: query.len(), + limit: MAX_QUERY_BYTES, + }); + } + let mut connection = self.pool.acquire().await?; + let mut transaction = connection.begin_with(AssertSqlSafe("BEGIN IMMEDIATE")).await?; + let previous: Option = sqlx::query_scalar("SELECT query FROM saved_queries WHERE id = ?") + .bind(id) + .fetch_optional(&mut *transaction) + .await?; + if previous.ok_or(StorageError::NotFound)? == query { + return Ok(()); + } + sqlx::query("UPDATE saved_queries SET query = ?, updated_at = ? WHERE id = ?") + .bind(query) + .bind(to_unix(SystemTime::now())) + .bind(id) + .execute(&mut *transaction) + .await?; + transaction.commit().await?; + self.changed(); + Ok(()) + } + pub async fn set_keyword(&self, id: i64, keyword: Option<&str>) -> Result<(), StorageError> { let keyword: Option = keyword .map(str::trim) @@ -970,4 +998,33 @@ mod tests { "renamed" ); } + + #[tokio::test] + async fn set_query_changes_the_text_by_id_and_keeps_its_name_and_place() { + let root = tempfile::tempdir().expect("tempdir"); + let queries = store(&root).await; + let connection = Uuid::new_v4(); + let id = queries + .save(new_query("Daily", "SELECT 1", connection)) + .await + .expect("save") + .id; + queries.rename(id, "Weekly").await.expect("rename"); + + queries.set_query(id, "SELECT 7").await.expect("set the query"); + let missing = queries + .set_query(id + 100, "SELECT 2") + .await + .expect_err("an unknown id"); + let large = queries + .set_query(id, &"x".repeat(MAX_QUERY_BYTES + 1)) + .await + .expect_err("past the cap"); + + let saved = queries.get(id).await.expect("get").expect("the query"); + assert_eq!((saved.name.as_str(), saved.query.as_str()), ("Weekly", "SELECT 7")); + assert_eq!(queries.list(Some(connection)).await.expect("list").len(), 1); + assert!(matches!(missing, StorageError::NotFound), "{missing:?}"); + assert!(matches!(large, StorageError::TooLarge { .. }), "{large:?}"); + } } diff --git a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md index 5d90b7d1e4..88f774a1c5 100644 --- a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md +++ b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md @@ -10,7 +10,7 @@ The Windows app reaches the core only through `crates/ffi`. Saved queries with f ## Decision - `QueryHistoryStore` gains `set_pinned`, `export(ids, format, path)` and two stores over the same database: `saved_queries()` and `favourites()`. -- `SavedQueryStore` reads a connection's queries and folders in one transaction (`snapshot`) and writes through `SavedQueries` and `SavedQueryFolders` as they are. `save(draft, replace)` gives the id, or nothing when the name is taken and `replace` is false, so the app asks before replacing. `delete_for_connection` takes a deleted connection's queries, folders and favourites. +- `SavedQueryStore` reads a connection's queries and folders in one transaction (`snapshot`) and writes through `SavedQueries` and `SavedQueryFolders` as they are. `save(draft, replace)` gives the id, or nothing when the name is taken and `replace` is false, so the app asks before replacing. `set_sql` changes a query's text by id through the new `SavedQueries::set_query`, so an edit made from a list read before a rename elsewhere still reaches the query it showed. `delete_for_connection` takes a deleted connection's queries, folders and favourites. - `FavouriteStore` lists, marks and unmarks tables and databases per connection, a database with one of the four environments. - `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the plan's id, the row count, the statements' SQL and the Safe Mode gate. Each column says whether an empty field is an empty value in it (`takes_empty`), so a preview shows what the import writes. - `CsvImport::run(plan, confirmed)` writes the plan `Ready` named, once and only while no later plan replaced it, so a plan still finishing after the user moved on is never the one written, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack`, `PartlyWritten` with the rows before it on an engine without a transaction, or `Unknown`. diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index ad05151e1f..f31005f050 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -3606,4 +3606,7 @@ New fingerprint: {2} (empty) + + Save query... + diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs index cb2070c2bc..94ceb2b494 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs @@ -71,6 +71,12 @@ internal QueryTabView( // The history kept a run of this tab, so a history pane reads it again. public event EventHandler? HistoryRecorded; + // Save query... on the editor's menu; the workspace asks its name and folder. + public event EventHandler? SaveQueryRequested; + + // Set by the workspace that holds the tab: only a saved connection keeps queries. + public bool CanSaveQuery { get; set; } + public string Title => _model.Title; public TabKind Kind => _model.Kind; @@ -265,7 +271,14 @@ private void OnEditorMenuOpening(object? sender, IList items IsEnabled = !string.IsNullOrWhiteSpace(QueryToShare), }; share.Click += (_, _) => ShareRequested?.Invoke(this, ShareKind.Query); + var save = new MenuFlyoutItem + { + Text = Strings.Get("SaveQueryCommand"), + IsEnabled = CanSaveQuery && !string.IsNullOrWhiteSpace(SqlText.Document.Snapshot()), + }; + save.Click += (_, _) => SaveQueryRequested?.Invoke(this, EventArgs.Empty); items.Add(new MenuFlyoutSeparator()); + items.Add(save); items.Add(share); } diff --git a/windows/src/TablePro.App/Views/SaveQueryDialog.cs b/windows/src/TablePro.App/Views/SaveQueryDialog.cs index ca8d5015a7..351af02802 100644 --- a/windows/src/TablePro.App/Views/SaveQueryDialog.cs +++ b/windows/src/TablePro.App/Views/SaveQueryDialog.cs @@ -66,7 +66,7 @@ internal static class SaveQueryDialog } } - // Writes only what changed: the name, the text by that name with replace keeping the id, then the folder. + // Writes only what changed, each by the query's id: the name, the text, then the folder. public static async Task EditAsync( FrameworkElement owner, SavedQueries store, @@ -178,7 +178,7 @@ private static async Task CommitAsync( if (!string.Equals(draft.Sql, draft.StoredSql, StringComparison.Ordinal)) { - await store.SaveAsync(connectionId, connectionName, draft.Name, draft.Sql, replace: true).ConfigureAwait(true); + await store.SetSqlAsync(id, draft.Sql).ConfigureAwait(true); draft.StoredSql = draft.Sql; } } diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index c3416a838a..120e54f2b6 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -638,6 +638,14 @@ private async Task SaveQueryAsync(string sql) } } + private async void OnSaveQueryRequested(object? sender, EventArgs e) + { + if (sender is QueryTabView { Editor: { } editor }) + { + await SaveQueryAsync(editor.Document.Snapshot()).ConfigureAwait(true); + } + } + // Insert in editor: a blank query tab takes the text, one with text gets it after a blank line, else a new tab opens. private void InsertQuery(string sql) { @@ -783,9 +791,15 @@ private async Task ImportCsvAsync(ObjectEntry entry) ShowExport(result.Succeeded ? InfoBarSeverity.Success : InfoBarSeverity.Error, result.Message, running: false); if (result.TableChanged) { - foreach (var item in Tabs.TabItems.OfType()) + // Taken before the first refresh, since a tab can open, close or move while one runs. + var views = Tabs.TabItems.OfType() + .Select(item => item.Content) + .OfType() + .Where(view => view.Shows(entry.Schema, entry.Name)) + .ToList(); + foreach (var view in views) { - if (item.Content is TableTabView view && view.Shows(entry.Schema, entry.Name)) + if (Tabs.TabItems.OfType().Any(item => ReferenceEquals(item.Content, view))) { await view.RefreshRowsAsync().ConfigureAwait(true); } @@ -957,6 +971,12 @@ internal void Take(TabViewItem item, int? index = null) source.ShareRequested += OnShareRequested; } + if (item.Content is QueryTabView query) + { + query.CanSaveQuery = CanShowSavedQueries; + query.SaveQueryRequested += OnSaveQueryRequested; + } + if (item.Content is TableTabView tableTab) { tableTab.DraftChanged += OnEditorTextChanged; @@ -1008,6 +1028,11 @@ internal void Release(TabViewItem item) source.ShareRequested -= OnShareRequested; } + if (item.Content is QueryTabView query) + { + query.SaveQueryRequested -= OnSaveQueryRequested; + } + if (item.Content is TableTabView tableTab) { tableTab.DraftChanged -= OnEditorTextChanged; diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index af581c1af3..1fe3fc8765 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1224,6 +1224,8 @@ public struct UniffiVTableCallbackInterfaceRunListener + + @@ -2702,6 +2704,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_savedquerystore_set_keyword(ulong @ptr,long @id,RustBuffer @keyword ); + #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_set_sql(ulong @ptr,long @id,RustBuffer @sql + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4979,6 +4992,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_set_keyword( ); + #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_set_sql( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -6170,6 +6194,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_set_keyword` checksum `46468`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_set_sql(); + if (checksum != 60674) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_savedquerystore_set_sql` checksum `60674`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_savedquerystore_snapshot(); if (checksum != 6061) { @@ -10326,6 +10356,8 @@ internal interface ISavedQueryStore { /// Task SetKeyword(long @id, string? @keyword); /// + Task SetSql(long @id, string @sql); + /// Task Snapshot(string @connectionId); } internal class SavedQueryStore : ISavedQueryStore, IDisposable { @@ -10609,6 +10641,24 @@ public async Task SetKeyword(long @id, string? @keyword) {await _UniFFIAsync.Uni ); } + /// + public async Task SetSql(long @id, string @sql) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_set_sql(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@sql)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task Snapshot(string @connectionId) { return await _UniFFIAsync.UniffiRustCallAsync( diff --git a/windows/src/TablePro.Interop/SavedQueries.cs b/windows/src/TablePro.Interop/SavedQueries.cs index 4c63f9f2b4..6c065b6d76 100644 --- a/windows/src/TablePro.Interop/SavedQueries.cs +++ b/windows/src/TablePro.Interop/SavedQueries.cs @@ -62,6 +62,13 @@ public Task RenameAsync(long id, string name) return CoreCall.RunAsync(() => _store.Rename(id, name)); } + // By id, so an edit from a list read before a rename elsewhere still changes the query it showed. + public Task SetSqlAsync(long id, string sql) + { + ArgumentNullException.ThrowIfNull(sql); + return CoreCall.RunAsync(() => _store.SetSql(id, sql)); + } + // Null or blank clears it. public Task SetKeywordAsync(long id, string? keyword) => CoreCall.RunAsync(() => _store.SetKeyword(id, keyword)); diff --git a/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs b/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs index a06bb1bae1..b8baa8ec53 100644 --- a/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs +++ b/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs @@ -62,7 +62,11 @@ public async Task ARefusedNameOrKeywordThrowsItsCode() await queries.SetKeywordAsync(one!.Value, "sel"); await queries.CreateFolderAsync(Shop, "Reports", null); - var name = await Assert.ThrowsAsync(() => queries.RenameAsync(two!.Value, "One")); + await queries.RenameAsync(one.Value, "First"); + await queries.SetSqlAsync(one.Value, "SELECT 11"); + var edited = Assert.Single((await queries.GetAsync(Shop, TestContext.Current.CancellationToken)).Queries, query => query.Id == one.Value); + Assert.Equal(("First", "SELECT 11"), (edited.Name, edited.Sql)); + var name = await Assert.ThrowsAsync(() => queries.RenameAsync(two!.Value, "First")); var keyword = await Assert.ThrowsAsync(() => queries.SetKeywordAsync(two!.Value, "SEL")); var folder = await Assert.ThrowsAsync(() => queries.CreateFolderAsync(Shop, "reports", null)); var empty = await Assert.ThrowsAsync(() => queries.SaveAsync(Shop, "shop", " ", "SELECT 3", replace: false)); From 340c01d99eefac107ba3bce633c7c94624c8095d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:38:35 +0700 Subject: [PATCH 04/11] fix(core): pad a CSV import's rows one at a time so one wide record cannot multiply the file's memory --- core/crates/core/src/import/csv_import.rs | 74 +++++++++++++++++-- core/crates/core/src/import/mod.rs | 4 +- core/crates/ffi/src/import.rs | 19 ++--- core/crates/ffi/tests/csv_import.rs | 26 +++++++ ...rage-import-and-library-through-the-ffi.md | 3 +- 5 files changed, 107 insertions(+), 19 deletions(-) diff --git a/core/crates/core/src/import/csv_import.rs b/core/crates/core/src/import/csv_import.rs index 28fbd82751..c7e37bb89b 100644 --- a/core/crates/core/src/import/csv_import.rs +++ b/core/crates/core/src/import/csv_import.rs @@ -95,6 +95,41 @@ pub struct CsvSheet { /// mapping decides which fields matter and a file the user already has /// is not improved by refusing to look at it. pub fn read_csv(bytes: &[u8], options: &CsvImportOptions, limit: Option) -> Result { + let CsvRecords { + headers, + mut rows, + width, + truncated, + } = read_csv_records(bytes, options, limit)?; + // A short row is padded so every row can be indexed by field + // number without a bounds check at every cell. + for row in &mut rows { + row.resize(width.max(row.len()), String::new()); + } + + Ok(CsvSheet { + headers, + rows, + truncated, + }) +} + +// A file's records as `read_csv` reads them, each as long as it was written, with the widest record's width. A +// whole-file import pads one row at a time with `padded_row`: one wide record padding every row of a file of +// narrow ones would take far more memory than the file. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CsvRecords { + pub headers: Vec, + pub rows: Vec>, + pub width: usize, + pub truncated: bool, +} + +pub fn read_csv_records( + bytes: &[u8], + options: &CsvImportOptions, + limit: Option, +) -> Result { if let Err(error) = std::str::from_utf8(bytes) { return Err(ImportError::NotUtf8 { offset: error.valid_up_to(), @@ -137,19 +172,20 @@ pub fn read_csv(bytes: &[u8], options: &CsvImportOptions, limit: Option) true => vec![String::new(); width], false => headers, }; - // A short row is padded so every row can be indexed by field - // number without a bounds check at every cell. - for row in &mut rows { - row.resize(width.max(row.len()), String::new()); - } - - Ok(CsvSheet { + Ok(CsvRecords { headers, rows, + width, truncated, }) } +// A row of `read_csv_records` as `read_csv` gives it: short rows padded to `width` with empty fields. +pub fn padded_row(mut row: Vec, width: usize) -> Vec { + row.resize(width.max(row.len()), String::new()); + row +} + pub(super) fn malformed(error: csv::Error) -> ImportError { ImportError::Malformed { line: error.position().map(csv::Position::line), @@ -342,6 +378,30 @@ mod tests { assert_eq!(sheet.rows[0], vec!["1".to_owned(), String::new(), String::new()]); } + #[test] + fn records_keep_each_row_as_written_and_padding_gives_what_read_csv_gives() { + let file = b"a,b\n1\n2,3,4\n"; + + let records = read_csv_records(file, &options(), None).expect("records"); + let sheet = read_csv(file, &options(), None).expect("sheet"); + + assert_eq!(records.width, 3); + assert_eq!( + records.rows, + vec![ + vec!["1".to_owned()], + vec!["2".to_owned(), "3".to_owned(), "4".to_owned()] + ] + ); + let padded: Vec> = records + .rows + .into_iter() + .map(|row| padded_row(row, records.width)) + .collect(); + assert_eq!(padded, sheet.rows); + assert_eq!(records.headers, sheet.headers); + } + #[test] fn a_long_row_keeps_the_fields_the_header_did_not_name() { let sheet = read_csv(b"a,b\n1,2,3\n", &options(), None).expect("read"); diff --git a/core/crates/core/src/import/mod.rs b/core/crates/core/src/import/mod.rs index 2fea197687..62a7f5d0e4 100644 --- a/core/crates/core/src/import/mod.rs +++ b/core/crates/core/src/import/mod.rs @@ -10,8 +10,8 @@ mod sql_file; mod sql_import; pub use csv_import::{ - CsvImportOptions, CsvRowError, CsvSheet, ImportError, MAX_CSV_FILE_BYTES, MAX_FIELDS, MAX_PREVIEW_ROWS, read_csv, - row_to_cells, suggest_mapping, + CsvImportOptions, CsvRecords, CsvRowError, CsvSheet, ImportError, MAX_CSV_FILE_BYTES, MAX_FIELDS, MAX_PREVIEW_ROWS, + padded_row, read_csv, read_csv_records, row_to_cells, suggest_mapping, }; pub use import_column::ImportColumn; pub use import_plan::{ImportPlan, plan_import}; diff --git a/core/crates/ffi/src/import.rs b/core/crates/ffi/src/import.rs index 4fc961084e..6be33accec 100644 --- a/core/crates/ffi/src/import.rs +++ b/core/crates/ffi/src/import.rs @@ -8,8 +8,8 @@ use tablepro_core::dialect::SqlDialect; use tablepro_core::edit::CellInput; use tablepro_core::export::CsvDelimiter; use tablepro_core::import::{ - CsvImportOptions, CsvRowError, ImportColumn, ImportError, MAX_CSV_FILE_BYTES, MAX_PREVIEW_ROWS, plan_import, - read_csv, row_to_cells, suggest_mapping, + CsvImportOptions, CsvRowError, ImportColumn, ImportError, MAX_CSV_FILE_BYTES, MAX_PREVIEW_ROWS, padded_row, + plan_import, read_csv, read_csv_records, row_to_cells, suggest_mapping, }; use tablepro_core::meta::TableRef; use tablepro_core::{CallOptions, DriverError, ErrorCategory, WriteBatch, WriteKind}; @@ -371,9 +371,9 @@ fn plan_file( gate: SaveGate, ) -> Result, CsvRowFault>, CoreError> { let bytes = read_file(path)?; - let sheet = read_csv(&bytes, options, None).map_err(read_error)?; + let records = read_csv_records(&bytes, options, None).map_err(read_error)?; drop(bytes); - let width = sheet.headers.len(); + let width = records.width; let mapping: Vec> = mapping .iter() .map(|field| field.and_then(|field| usize::try_from(field).ok())) @@ -384,18 +384,19 @@ fn plan_file( format!("field {field} is past the file's {width} fields"), )); } - if sheet.rows.is_empty() { + if records.rows.is_empty() { return Ok(Ok(None)); } let first_line = if options.has_header { 2 } else { 1 }; - let mut rows: Vec> = Vec::with_capacity(sheet.rows.len()); - for (index, row) in sheet.rows.iter().enumerate() { - match row_to_cells(row, &mapping, columns, options, first_line + index) { + let mut rows: Vec> = Vec::with_capacity(records.rows.len()); + // One row padded at a time, as read_csv pads them all, so a wide record cannot multiply every other row. + for (index, row) in records.rows.into_iter().enumerate() { + let row = padded_row(row, width); + match row_to_cells(&row, &mapping, columns, options, first_line + index) { Ok(cells) => rows.push(cells), Err(error) => return Ok(Err(CsvRowFault::from(error))), } } - drop(sheet); let count = rows.len(); let plan = plan_import(dialect, table, columns, rows) .map_err(|error| CoreError::failed(error.code(), error.to_string()))?; diff --git a/core/crates/ffi/tests/csv_import.rs b/core/crates/ffi/tests/csv_import.rs index 40e9462753..e28d2764d5 100644 --- a/core/crates/ffi/tests/csv_import.rs +++ b/core/crates/ffi/tests/csv_import.rs @@ -431,3 +431,29 @@ async fn a_plan_made_later_replaces_the_one_before_it() { ); session.close().await.unwrap(); } + +#[tokio::test] +async fn one_wide_record_after_many_narrow_rows_plans_with_only_the_mapped_fields() { + let dir = tempfile::tempdir().unwrap(); + let core = core(dir.path()); + let session = seeded(&core, &dir.path().join("people.sqlite")).await; + let mut text = String::from("id,name\n"); + for id in 1..=20_000 { + text.push_str(&format!("{id},n{id}\n")); + } + text.push_str("20001,wide"); + text.push_str(&",".repeat(4_094)); + text.push('\n'); + let csv = write(dir.path(), "wide.csv", &text); + let import = session.open_csv_import(people(), None).await.unwrap(); + + let check = import + .plan(csv, comma(), vec![Some(0), Some(1), None, None, None]) + .await + .unwrap(); + let outcome = import.run(plan_of(&check), false, None).await.unwrap(); + + assert!(matches!(check, CsvImportCheck::Ready { rows: 20_001, .. }), "{check:?}"); + assert_eq!(outcome, CsvImportOutcome::Imported { rows: 20_001 }); + session.close().await.unwrap(); +} diff --git a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md index 88f774a1c5..4a71a26ccf 100644 --- a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md +++ b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md @@ -12,7 +12,7 @@ The Windows app reaches the core only through `crates/ffi`. Saved queries with f - `QueryHistoryStore` gains `set_pinned`, `export(ids, format, path)` and two stores over the same database: `saved_queries()` and `favourites()`. - `SavedQueryStore` reads a connection's queries and folders in one transaction (`snapshot`) and writes through `SavedQueries` and `SavedQueryFolders` as they are. `save(draft, replace)` gives the id, or nothing when the name is taken and `replace` is false, so the app asks before replacing. `set_sql` changes a query's text by id through the new `SavedQueries::set_query`, so an edit made from a list read before a rename elsewhere still reaches the query it showed. `delete_for_connection` takes a deleted connection's queries, folders and favourites. - `FavouriteStore` lists, marks and unmarks tables and databases per connection, a database with one of the four environments. -- `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the plan's id, the row count, the statements' SQL and the Safe Mode gate. Each column says whether an empty field is an empty value in it (`takes_empty`), so a preview shows what the import writes. +- `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, keeps each record as written (`read_csv_records`, new) and pads one row at a time as `read_csv` pads them all, so one wide record cannot multiply the memory every narrow row takes, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the plan's id, the row count, the statements' SQL and the Safe Mode gate. Each column says whether an empty field is an empty value in it (`takes_empty`), so a preview shows what the import writes. - `CsvImport::run(plan, confirmed)` writes the plan `Ready` named, once and only while no later plan replaced it, so a plan still finishing after the user moved on is never the one written, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack`, `PartlyWritten` with the rows before it on an engine without a transaction, or `Unknown`. - `ConnectionLibrary::duplicate(id, name)` copies the connection under a new id right after the original (`insert_after_blocking`), never opened and no favourite, after copying every secret kind the original keeps; a refused secret takes the copy's secrets back, and so does a refused write unless the list shows the copy saved after all. The app names the copy, since the name is in the user's language. `export_file(path)` writes `export_blocking`'s document, which carries no secret. - History exports and connection exports are written beside the target and renamed over it once synced, as result exports are. @@ -29,6 +29,7 @@ The Windows app reaches the core only through `crates/ffi`. Saved queries with f - The app words the copy's name and every error code (`import.*`, `storage.*`, `secret.*`). - `DraftStore` stays off the FFI: the Windows app keeps a query tab's text in its own session file and calls nothing that needs it. - `PastedTable` and `PastedRows` stay off the FFI until a paste into the grid has its key-based edits (roadmap C-10). +- The Linux import still reads a whole file through `read_csv`, which pads every row to the widest; it moves to `read_csv_records` in a Linux change. - An import of a file past 64 MiB is refused; one larger import needs the streaming the SQL file import has ([0011](0011-sql-dump-and-import-in-process.md)). ## Alternatives considered From 634c1a174ca52f4b557d73cb824d98656f4868ea Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:43:19 +0700 Subject: [PATCH 05/11] fix(windows): offer a CSV field past the header in the import's mapping --- windows/src/TablePro.App.Model/CsvImportForm.cs | 12 +++++++++--- .../TablePro.App.Model.Tests/CsvImportFormTests.cs | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/windows/src/TablePro.App.Model/CsvImportForm.cs b/windows/src/TablePro.App.Model/CsvImportForm.cs index 35c81958f6..aefb4c530b 100644 --- a/windows/src/TablePro.App.Model/CsvImportForm.cs +++ b/windows/src/TablePro.App.Model/CsvImportForm.cs @@ -155,9 +155,12 @@ public CsvImportState State public bool CanImport => State == CsvImportState.Ready && !IsPlanning; public CsvPreviewSummary? Summary => Preview is { } preview - ? new CsvPreviewSummary(preview.Headers.Count, preview.Rows.Count, preview.Truncated) + ? new CsvPreviewSummary(Width(preview), preview.Rows.Count, preview.Truncated) : null; + private static int Width(CsvPreview preview) => + Math.Max(preview.Headers.Count, preview.Rows.Count == 0 ? 0 : preview.Rows.Max(row => row.Count)); + // A .tsv is tab separated by its name; any other file starts as comma separated. public static CsvDelimiter DelimiterFor(string filePath) => string.Equals(Path.GetExtension(filePath), ".tsv", StringComparison.OrdinalIgnoreCase) @@ -186,9 +189,12 @@ public bool Show(int read, CsvPreview preview, IReadOnlyList suggested) Preview = preview; ReadError = null; IReadOnlyList first = preview.Rows.Count > 0 ? preview.Rows[0] : []; - Fields = [.. preview.Headers.Select((header, index) => new CsvField( + // A row wider than the header keeps its extra fields, which are offered by position. + Fields = [.. Enumerable.Range(0, Width(preview)).Select(index => new CsvField( index, - string.IsNullOrWhiteSpace(header) ? null : Clip(header), + index < preview.Headers.Count && !string.IsNullOrWhiteSpace(preview.Headers[index]) + ? Clip(preview.Headers[index]) + : null, index < first.Count && first[index].Length > 0 ? Clip(first[index]) : null))]; for (var column = 0; column < _mapping.Length; column++) { diff --git a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs index 17979cf80b..b50cb6973f 100644 --- a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs @@ -60,6 +60,20 @@ public void AFieldIsNamedByItsHeaderOrByPositionWithTheFirstRowsValueAsItsSample form.Fields); } + [Fact] + public void AFieldPastTheHeaderIsOfferedByPositionAndCounted() + { + var form = Form(); + var preview = new CsvPreview(["id"], [["1", "Ada"], ["2", "Grace"]], false); + + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), preview, []); + form.Choose(1, 2); + + Assert.Equal([new CsvField(0, "id", "1"), new CsvField(1, null, "Ada")], form.Fields); + Assert.Equal(1, form.Mapping[1]); + Assert.Equal(new CsvPreviewSummary(2, 2, false), form.Summary); + } + [Fact] public void EachColumnSaysWhatItTakes() { From e7d54962071b9c05161c2861d9b1a3ac7a55520b Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:51:49 +0700 Subject: [PATCH 06/11] fix(windows): report a CSV import written in part as unknown and keep a replaced saved query's place --- core/crates/ffi/src/import.rs | 45 +++++++++---------- ...rage-import-and-library-through-the-ffi.md | 2 +- ...ueries-csv-import-and-connection-copies.md | 4 +- .../src/TablePro.App.Model/CsvImportForm.cs | 11 +++-- .../TablePro.App/Strings/en-US/Resources.resw | 15 ++----- .../src/TablePro.App/Views/ImportCsvDialog.cs | 11 +---- .../src/TablePro.App/Views/SaveQueryDialog.cs | 8 ++++ windows/src/TablePro.Interop/CsvImport.cs | 16 +++---- .../Generated/tablepro_ffi.cs | 27 ++--------- .../CsvImportFormTests.cs | 9 ++-- 10 files changed, 54 insertions(+), 94 deletions(-) diff --git a/core/crates/ffi/src/import.rs b/core/crates/ffi/src/import.rs index 6be33accec..6b5aef624a 100644 --- a/core/crates/ffi/src/import.rs +++ b/core/crates/ffi/src/import.rs @@ -101,15 +101,11 @@ pub enum CsvImportOutcome { error: BoxedErrorInfo, lines: Option, }, - // The engine has no transaction to undo the import: `written_rows` rows before the failed lines stay. - PartlyWritten { - error: BoxedErrorInfo, - written_rows: u64, - lines: Option, - }, - // Stopped, or the connection went before the server answered: the table may hold some rows or none. + // Stopped, cut off, or written in part where the engine has no transaction to undo it: the table may hold some + // rows or none. The lines are those of the statement that failed, when the engine said which. Unknown { error: BoxedErrorInfo, + lines: Option, }, } @@ -477,27 +473,25 @@ fn failed(error: &OperationError, planned: &Planned) -> CsvImportOutcome { error: info(), lines: lines(*statement_index), }, - DriverError::PartiallyApplied { statement_index, .. } => { - let written: usize = planned - .step_rows - .iter() - .take(*statement_index) - .map(ExactSizeIterator::len) - .sum(); - CsvImportOutcome::PartlyWritten { - error: info(), - written_rows: line(written), - lines: lines(*statement_index), - } - } + // As a row save reads it: what landed before the failed statement is not known to have stayed. + DriverError::PartiallyApplied { statement_index, .. } => CsvImportOutcome::Unknown { + error: info(), + lines: lines(*statement_index), + }, DriverError::ReadOnly(_) => CsvImportOutcome::RolledBack { error: info(), lines: None, }, - DriverError::CommitOutcomeUnknown { .. } => CsvImportOutcome::Unknown { error: info() }, + DriverError::CommitOutcomeUnknown { .. } => CsvImportOutcome::Unknown { + error: info(), + lines: None, + }, other => match other.category() { ErrorCategory::Interrupted | ErrorCategory::Timeout | ErrorCategory::ConnectionLost => { - CsvImportOutcome::Unknown { error: info() } + CsvImportOutcome::Unknown { + error: info(), + lines: None, + } } _ => CsvImportOutcome::RolledBack { error: info(), @@ -509,9 +503,10 @@ fn failed(error: &OperationError, planned: &Planned) -> CsvImportOutcome { error: info(), lines: None, }, - OperationError::Cancelled | OperationError::Panicked(_) | OperationError::Closed => { - CsvImportOutcome::Unknown { error: info() } - } + OperationError::Cancelled | OperationError::Panicked(_) | OperationError::Closed => CsvImportOutcome::Unknown { + error: info(), + lines: None, + }, } } diff --git a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md index 4a71a26ccf..96ee9860bf 100644 --- a/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md +++ b/core/docs/decisions/0029-storage-import-and-library-through-the-ffi.md @@ -13,7 +13,7 @@ The Windows app reaches the core only through `crates/ffi`. Saved queries with f - `SavedQueryStore` reads a connection's queries and folders in one transaction (`snapshot`) and writes through `SavedQueries` and `SavedQueryFolders` as they are. `save(draft, replace)` gives the id, or nothing when the name is taken and `replace` is false, so the app asks before replacing. `set_sql` changes a query's text by id through the new `SavedQueries::set_query`, so an edit made from a list read before a rename elsewhere still reaches the query it showed. `delete_for_connection` takes a deleted connection's queries, folders and favourites. - `FavouriteStore` lists, marks and unmarks tables and databases per connection, a database with one of the four environments. - `DatabaseSession::open_csv_import(table)` reads the table's definition into `ImportColumn`s. `CsvImport` previews the first `MAX_PREVIEW_ROWS`, suggests a mapping by header, and `plan(path, options, mapping)` reads the whole file, at most `MAX_CSV_FILE_BYTES` read through a bounded reader, keeps each record as written (`read_csv_records`, new) and pads one row at a time as `read_csv` pads them all, so one wide record cannot multiply the memory every narrow row takes, turns each row into cells with `row_to_cells` and plans with `plan_import`. A field the column cannot read comes back as `RowRefused` with its line, column, text and the `EditParseError` code, and an empty file as `Empty`; neither is an error. `Ready` carries the plan's id, the row count, the statements' SQL and the Safe Mode gate. Each column says whether an empty field is an empty value in it (`takes_empty`), so a preview shows what the import writes. -- `CsvImport::run(plan, confirmed)` writes the plan `Ready` named, once and only while no later plan replaced it, so a plan still finishing after the user moved on is never the one written, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack`, `PartlyWritten` with the rows before it on an engine without a transaction, or `Unknown`. +- `CsvImport::run(plan, confirmed)` writes the plan `Ready` named, once and only while no later plan replaced it, so a plan still finishing after the user moved on is never the one written, as one `WriteBatch` under `OperationKind::Save(WriteKind::RowChanges)`, gated as a row save ([0019](0019-row-edits-through-the-ffi.md)): Confirm writes needs `confirmed`, Read only refuses, and a level changed since the plan refuses on the writing lease. Each statement adds 5 seconds to the call's deadline, as the Linux import allows. A failure reports the file lines of the statement that failed: `RolledBack` when nothing was written, else `Unknown`, which also covers a write in part where the engine has no transaction, as a row save reports it, since what landed before the failed statement is not known to have stayed. - `ConnectionLibrary::duplicate(id, name)` copies the connection under a new id right after the original (`insert_after_blocking`), never opened and no favourite, after copying every secret kind the original keeps; a refused secret takes the copy's secrets back, and so does a refused write unless the list shows the copy saved after all. The app names the copy, since the name is in the user's language. `export_file(path)` writes `export_blocking`'s document, which carries no secret. - History exports and connection exports are written beside the target and renamed over it once synced, as result exports are. diff --git a/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md b/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md index 36bb0b402c..55c35844b4 100644 --- a/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md +++ b/windows/docs/decisions/0011-saved-queries-csv-import-and-connection-copies.md @@ -13,7 +13,7 @@ Each works as the macOS app's does, with its words in Windows sentence case, ove ### Saved queries -- Query > Save query... keeps a query tab's whole text under a name, and the history's entry menu keeps a run's. A dialog asks for the name, prefilled from the text as macOS names a favorite, and a folder once there are folders. A name the connection already uses asks before it replaces that query, which keeps its place. +- Query > Save query... and the editor's menu keep a query tab's whole text under a name, and the history's entry menu keeps a run's. A dialog asks for the name, prefilled from the text as macOS names a favorite, and a folder once there are folders. A name the connection already uses asks before it replaces that query, which keeps its place unless another folder was picked. - View > Show saved queries opens a pane in the place the history pane takes, one of the two at a time. A tree lists folders, then queries, each in its stored order. Invoking a query inserts it in the editor, as macOS does: it replaces an empty query tab's text, follows a tab's text after a blank line, and opens a new query tab when none is in front. Its menu has Insert in editor, Open in new tab, Copy query, Edit..., Move to and Delete; a folder's has New subfolder, Rename and Delete folder, whose folders go with it and whose queries move to the top level. - Saved queries belong to a saved connection. A file opened without saving gets a new id each time, so it keeps none. Deleting a connection deletes its saved queries, folders and favourites, as the Linux app does. - Keywords are kept by the core but not edited here: macOS expands one through completion, which the Windows editor does not have yet. @@ -25,7 +25,7 @@ Each works as the macOS app's does, with its words in Windows sentence case, ove ### CSV import - Import CSV... on a table's menu in the object tree. The system open picker chooses the file; a dialog sets the delimiter (Tab for a .tsv), whether the first row names the fields and the text that means NULL, shows how many fields and rows the file has, and maps a field to each column, starting from the fields whose header names a column. A column the server fills is left to it. A field a column cannot read keeps the dialog open with its line and column. -- Safe Mode gates the import as a save: Confirm writes lists the statements first, Read only refuses. The result names the rows imported or, on a failure, the lines of the file that failed and whether the table kept any rows. +- Safe Mode gates the import as a save: Confirm writes lists the statements first, Read only refuses. The result names the rows imported or, on a failure, the lines of the file that failed and whether the table may hold any of the rows. ### Connections diff --git a/windows/src/TablePro.App.Model/CsvImportForm.cs b/windows/src/TablePro.App.Model/CsvImportForm.cs index aefb4c530b..278721ec24 100644 --- a/windows/src/TablePro.App.Model/CsvImportForm.cs +++ b/windows/src/TablePro.App.Model/CsvImportForm.cs @@ -27,8 +27,8 @@ public enum CsvImportEnding Imported, // Refused before anything was sent, or rolled back: the table is as it was. NotWritten, - PartlyWritten, - // Stopped or cut off before the server answered: the table may hold some of the rows. + + // Stopped, cut off, or written in part without a transaction to undo it: the table may hold some of the rows. Unknown, } @@ -55,7 +55,7 @@ public sealed record CsvPreviewSummary(int Fields, int Rows, bool Truncated); // Text is what Safe Mode's review lists; Shown counts the statements in it. public sealed record CsvImportReview(string Text, int Shown); -// Rows: imported, or written before the failure. Lines: those the failed statement held. No Error: stopped here. +// Rows: imported. Lines: those the failed statement held. No Error: stopped here. public sealed record CsvImportReport(CsvImportEnding Ending, long Rows, LineSpan? Lines, CoreError? Error) { public static CsvImportReport Stopped { get; } = new(CsvImportEnding.Unknown, 0, null, null); @@ -72,9 +72,8 @@ public static CsvImportReport From(CsvImportOutcome outcome) CsvImportEnding.Imported, imported.Rows, null, null), CsvImportOutcome.RolledBack rolledBack => new CsvImportReport( CsvImportEnding.NotWritten, 0, rolledBack.Lines, rolledBack.Error), - CsvImportOutcome.PartlyWritten partly => new CsvImportReport( - CsvImportEnding.PartlyWritten, partly.WrittenRows, partly.Lines, partly.Error), - CsvImportOutcome.Unknown unknown => new CsvImportReport(CsvImportEnding.Unknown, 0, null, unknown.Error), + CsvImportOutcome.Unknown unknown => new CsvImportReport( + CsvImportEnding.Unknown, 0, unknown.Lines, unknown.Error), _ => throw new ArgumentOutOfRangeException(nameof(outcome)), }; } diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index f31005f050..49aa06e475 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -3546,18 +3546,6 @@ New fingerprint: {2} No rows were imported. - - {0} could not be written. The table has no transaction to undo the import. - - - {0} could not be written. The table has no transaction to undo the import, so the row written before stays in it. - - - {0} could not be written. The table has no transaction to undo the import, so the {1:N0} rows written before stay in it. - - - Some of those lines may be in it too. - The import did not finish, so the table may hold some of the rows. Refresh it to see what is there. @@ -3609,4 +3597,7 @@ New fingerprint: {2} Save query... + + {0} could not be written, and the table has no transaction to undo the import, so it may hold some of the rows. Refresh it to see what is there. + diff --git a/windows/src/TablePro.App/Views/ImportCsvDialog.cs b/windows/src/TablePro.App/Views/ImportCsvDialog.cs index acc6f84f30..7e00d11404 100644 --- a/windows/src/TablePro.App/Views/ImportCsvDialog.cs +++ b/windows/src/TablePro.App/Views/ImportCsvDialog.cs @@ -128,7 +128,6 @@ private static string Describe(TableName table, CsvImportReport report) { } span when span.First == span.Last => Strings.Format("ImportCsvLine", span.First), { } span => Strings.Format("ImportCsvLines", span.First, span.Last), }; - var range = report.Lines is { } held && held.First != held.Last; return report.Ending switch { CsvImportEnding.Imported => report.Rows == 1 @@ -137,16 +136,8 @@ private static string Describe(TableName table, CsvImportReport report) CsvImportEnding.NotWritten when report.Lines is null => Sentences(Strings.Get("ImportCsvNotWritten"), error), CsvImportEnding.NotWritten => Sentences(Strings.Format("ImportCsvRolledBack", lines), error), - CsvImportEnding.PartlyWritten => Sentences( - report.Rows switch - { - 0 => Strings.Format("ImportCsvPartlyNone", lines), - 1 => Strings.Format("ImportCsvPartlyOne", lines), - _ => Strings.Format("ImportCsvPartlyMany", lines, report.Rows), - }, - range ? Strings.Get("ImportCsvPartlyRange") : null, - error), _ when report.Error is null => Strings.Get("ImportCsvStopped"), + _ when report.Lines is not null => Sentences(Strings.Format("ImportCsvUnknownLines", lines), error), _ => Sentences(Strings.Get("ImportCsvUnknown"), error), }; } diff --git a/windows/src/TablePro.App/Views/SaveQueryDialog.cs b/windows/src/TablePro.App/Views/SaveQueryDialog.cs index 351af02802..f68a318db2 100644 --- a/windows/src/TablePro.App/Views/SaveQueryDialog.cs +++ b/windows/src/TablePro.App/Views/SaveQueryDialog.cs @@ -167,6 +167,14 @@ private static async Task CommitAsync( draft.Id = id = added; draft.StoredName = draft.Name; draft.StoredSql = draft.Sql; + if (replace) + { + // A replaced query keeps its place unless another folder was picked. + var held = (await store.GetAsync(connectionId).ConfigureAwait(true)).Queries + .FirstOrDefault(query => query.Id == added); + draft.StoredFolder = held?.FolderId; + draft.FolderId ??= draft.StoredFolder; + } } else { diff --git a/windows/src/TablePro.Interop/CsvImport.cs b/windows/src/TablePro.Interop/CsvImport.cs index 78ccbb5a09..b57e849ddb 100644 --- a/windows/src/TablePro.Interop/CsvImport.cs +++ b/windows/src/TablePro.Interop/CsvImport.cs @@ -66,11 +66,9 @@ public sealed record Imported(long Rows) : CsvImportOutcome; // Nothing was written. Lines are those of the statement that failed, when the engine said which. public sealed record RolledBack(CoreError Error, LineSpan? Lines) : CsvImportOutcome; - // The engine has no transaction to undo it: WrittenRows rows before the failed lines stay in the table. - public sealed record PartlyWritten(CoreError Error, long WrittenRows, LineSpan? Lines) : CsvImportOutcome; - - // Stopped, or the connection went before the server answered: the table may hold some rows or none. - public sealed record Unknown(CoreError Error) : CsvImportOutcome; + // Stopped, cut off, or written in part where the engine has no transaction to undo it: the table may hold some of + // the rows or none. Lines are those of the statement that failed, when the engine said which. + public sealed record Unknown(CoreError Error, LineSpan? Lines) : CsvImportOutcome; } // A table's columns as a CSV import writes them; RunAsync writes the import planned last, once. @@ -163,11 +161,9 @@ public async Task RunAsync( Native.CsvImportOutcome.RolledBack rolledBack => new CsvImportOutcome.RolledBack( Mapping.Error(rolledBack.Error), Lines(rolledBack.Lines)), - Native.CsvImportOutcome.PartlyWritten partly => new CsvImportOutcome.PartlyWritten( - Mapping.Error(partly.Error), - Mapping.Count(partly.WrittenRows), - Lines(partly.Lines)), - Native.CsvImportOutcome.Unknown unknown => new CsvImportOutcome.Unknown(Mapping.Error(unknown.Error)), + Native.CsvImportOutcome.Unknown unknown => new CsvImportOutcome.Unknown( + Mapping.Error(unknown.Error), + Lines(unknown.Lines)), _ => throw new InvalidOperationException("The core reported an import outcome this build does not know."), }; } diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 1fe3fc8765..f9b709d1b2 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -14694,16 +14694,11 @@ public record RolledBack ( LineSpan? Lines ) : CsvImportOutcome {} - public record PartlyWritten ( + public record Unknown ( BoxedErrorInfo Error, - ulong WrittenRows, LineSpan? Lines ) : CsvImportOutcome {} - public record Unknown ( - BoxedErrorInfo Error - ) : CsvImportOutcome {} - } @@ -14724,15 +14719,10 @@ public override CsvImportOutcome Read(BigEndianStream stream) { FfiConverterOptionalTypeLineSpan.INSTANCE.Read(stream) ); case 3: - return new CsvImportOutcome.PartlyWritten( + return new CsvImportOutcome.Unknown( FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), - FfiConverterUInt64.INSTANCE.Read(stream), FfiConverterOptionalTypeLineSpan.INSTANCE.Read(stream) ); - case 4: - return new CsvImportOutcome.Unknown( - FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream) - ); default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportOutcome.Read()", value)); } @@ -14747,14 +14737,10 @@ public override int AllocationSize(CsvImportOutcome value) { return 4 + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) + FfiConverterOptionalTypeLineSpan.INSTANCE.AllocationSize(variant_value.Lines); - case CsvImportOutcome.PartlyWritten variant_value: + case CsvImportOutcome.Unknown variant_value: return 4 + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) - + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.WrittenRows) + FfiConverterOptionalTypeLineSpan.INSTANCE.AllocationSize(variant_value.Lines); - case CsvImportOutcome.Unknown variant_value: - return 4 - + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error); default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportOutcome.AllocationSize()", value)); } @@ -14771,16 +14757,11 @@ public override void Write(CsvImportOutcome value, BigEndianStream stream) { FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); FfiConverterOptionalTypeLineSpan.INSTANCE.Write(variant_value.Lines, stream); break; - case CsvImportOutcome.PartlyWritten variant_value: + case CsvImportOutcome.Unknown variant_value: stream.WriteInt(3); FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); - FfiConverterUInt64.INSTANCE.Write(variant_value.WrittenRows, stream); FfiConverterOptionalTypeLineSpan.INSTANCE.Write(variant_value.Lines, stream); break; - case CsvImportOutcome.Unknown variant_value: - stream.WriteInt(4); - FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); - break; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCsvImportOutcome.Write()", value)); } diff --git a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs index b50cb6973f..0bfda91648 100644 --- a/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs @@ -254,15 +254,14 @@ public void AnOutcomeSaysWhetherTheTableChanged() new CsvImportReport(CsvImportEnding.NotWritten, 0, lines, error), CsvImportReport.From(new CsvImportOutcome.RolledBack(error, lines))); Assert.Equal( - new CsvImportReport(CsvImportEnding.PartlyWritten, 10, lines, error), - CsvImportReport.From(new CsvImportOutcome.PartlyWritten(error, 10, lines))); + new CsvImportReport(CsvImportEnding.Unknown, 0, lines, error), + CsvImportReport.From(new CsvImportOutcome.Unknown(error, lines))); Assert.Equal( new CsvImportReport(CsvImportEnding.Unknown, 0, null, error), - CsvImportReport.From(new CsvImportOutcome.Unknown(error))); + CsvImportReport.From(new CsvImportOutcome.Unknown(error, null))); Assert.True(CsvImportReport.From(new CsvImportOutcome.Imported(3)).TableChanged); - Assert.True(CsvImportReport.From(new CsvImportOutcome.PartlyWritten(error, 0, null)).TableChanged); - Assert.True(CsvImportReport.From(new CsvImportOutcome.Unknown(error)).TableChanged); + Assert.True(CsvImportReport.From(new CsvImportOutcome.Unknown(error, lines)).TableChanged); Assert.True(CsvImportReport.Stopped.TableChanged); Assert.False(CsvImportReport.From(new CsvImportOutcome.RolledBack(error, null)).TableChanged); Assert.False(CsvImportReport.Refused(error).TableChanged); From c5b58ffabc593f53847957e84cd8c1e39d801015 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 02:56:29 +0700 Subject: [PATCH 07/11] fix(windows): move a replaced saved query to the top level when that is picked --- windows/src/TablePro.App/Views/SaveQueryDialog.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/windows/src/TablePro.App/Views/SaveQueryDialog.cs b/windows/src/TablePro.App/Views/SaveQueryDialog.cs index f68a318db2..5e7650a5e3 100644 --- a/windows/src/TablePro.App/Views/SaveQueryDialog.cs +++ b/windows/src/TablePro.App/Views/SaveQueryDialog.cs @@ -173,7 +173,10 @@ private static async Task CommitAsync( var held = (await store.GetAsync(connectionId).ConfigureAwait(true)).Queries .FirstOrDefault(query => query.Id == added); draft.StoredFolder = held?.FolderId; - draft.FolderId ??= draft.StoredFolder; + if (!draft.FolderChosen) + { + draft.FolderId = draft.StoredFolder; + } } } else @@ -228,6 +231,7 @@ private static async Task ShowAsync( if (folders.Count > 0) { folder = FolderBox(folders, draft.FolderId); + folder.SelectionChanged += (_, _) => draft.FolderChosen = true; content.Children.Add(folder); } @@ -403,6 +407,9 @@ private sealed class Draft(long? id, string name, string sql, long? folderId) public long? FolderId { get; set; } = folderId; + // No folder is also the box's start, so only a pick tells a move to the top level from no choice. + public bool FolderChosen { get; set; } + public string StoredName { get; set; } = name; public string StoredSql { get; set; } = sql; From cc6d4e58cdd59e126394d31e2c0d8b153a4e7f6d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 04:04:00 +0700 Subject: [PATCH 08/11] fix(windows): name the dispatcher priority and hook Save query in the tab's query block --- .../TablePro.App/Views/SavedQueriesPane.xaml.cs | 3 +-- .../src/TablePro.App/Views/WorkspaceView.xaml.cs | 14 +++----------- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs index 61f502411c..5825db7b23 100644 --- a/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs +++ b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs @@ -1,5 +1,4 @@ using System.Collections.ObjectModel; -using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Controls; @@ -141,7 +140,7 @@ private void Show(SavedQueryList list) // The tree sets each new row's state in a later pass, which can fold a row opened here (seen on Arm64). private void Settle(int rebuild, int passes) { - DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => + DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => { if (rebuild != _rebuild) { diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index 120e54f2b6..44835665d6 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -971,12 +971,6 @@ internal void Take(TabViewItem item, int? index = null) source.ShareRequested += OnShareRequested; } - if (item.Content is QueryTabView query) - { - query.CanSaveQuery = CanShowSavedQueries; - query.SaveQueryRequested += OnSaveQueryRequested; - } - if (item.Content is TableTabView tableTab) { tableTab.DraftChanged += OnEditorTextChanged; @@ -986,6 +980,8 @@ internal void Take(TabViewItem item, int? index = null) if (item.Content is QueryTabView query) { query.HistoryRecorded += OnHistoryRecorded; + query.CanSaveQuery = CanShowSavedQueries; + query.SaveQueryRequested += OnSaveQueryRequested; } else if (item.Content is DefinitionTabView definition) { @@ -1028,11 +1024,6 @@ internal void Release(TabViewItem item) source.ShareRequested -= OnShareRequested; } - if (item.Content is QueryTabView query) - { - query.SaveQueryRequested -= OnSaveQueryRequested; - } - if (item.Content is TableTabView tableTab) { tableTab.DraftChanged -= OnEditorTextChanged; @@ -1042,6 +1033,7 @@ internal void Release(TabViewItem item) if (item.Content is QueryTabView query) { query.HistoryRecorded -= OnHistoryRecorded; + query.SaveQueryRequested -= OnSaveQueryRequested; } else if (item.Content is DefinitionTabView definition) { From 4325538408381825c131f43cd4699e8ffd2114ef Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 05:15:23 +0700 Subject: [PATCH 09/11] test(windows): save the connections export through the Save As dialog with Enter --- .../ConnectionCopyTests.cs | 43 +++++++++++++++---- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs index 34418d59e6..6a34becbf7 100644 --- a/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs +++ b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs @@ -1,6 +1,8 @@ using FlaUI.Core.AutomationElements; using FlaUI.Core.Definitions; +using FlaUI.Core.Input; using FlaUI.Core.Tools; +using FlaUI.Core.WindowsAPI; namespace TablePro.App.UITests; @@ -28,18 +30,41 @@ public void ADuplicateOpensTheFormOnTheCopyAndAnExportWritesTheFile(string theme app.FindByNamePrefix("Chinook (Sample) (Copy),", tree); var file = Path.Combine(app.DataFolder, "exported-connections.json"); - app.Click(app.Find("ExportConnectionsButton"), () => app.HasWindow("Save As")); - var save = app.WaitForWindow("Save As"); - var name = Retry.WhileNull( - () => save.FindFirstDescendant(condition => condition.ByControlType(ControlType.Edit).And(condition.ByName("File name:"))), - AppSession.Wait) - .Result ?? throw new InvalidOperationException("The Save As dialog has no File name box."); - name.AsTextBox().Text = file; - app.Find("1", save).AsButton().Invoke(); - Assert.True(Retry.WhileFalse(() => File.Exists(file), AppSession.Wait).Success, "The export wrote no file."); + app.Click(app.Find("ExportConnectionsButton"), () => FileDialog(app) is not null); + SaveInFileDialog(app, file); + // The bar says what happened, and a wait that gives up keeps a shot of it. app.FindByNamePrefix("Exported 2 connections.", app.Find("HomeMessageBar")); + Assert.True(File.Exists(file), "The export wrote no file."); app.Screenshot("79-connections-exported"); var text = File.ReadAllText(file); Assert.Contains("Chinook (Sample) (Copy)", text, StringComparison.Ordinal); } + + // The system's Save As dialog is Win32, as the Open dialog is: Enter saves to the path typed in its File name box. + private static void SaveInFileDialog(AppSession app, string path) + { + for (var attempt = 0; attempt < 3; attempt++) + { + var dialog = Retry.WhileNull(() => FileDialog(app), AppSession.Wait, throwOnTimeout: false).Result + ?? throw new InvalidOperationException("The Save As dialog did not appear."); + var name = Retry.WhileNull( + () => dialog.FindFirstDescendant(condition => condition.ByControlType(ControlType.Edit) + .And(condition.ByAutomationId("1001").Or(condition.ByName("File name:")))), + AppSession.Wait, + throwOnTimeout: false).Result + ?? throw new InvalidOperationException("The Save As dialog has no File name box."); + dialog.SetForeground(); + name.Focus(); + name.AsTextBox().Text = path; + Keyboard.Type(VirtualKeyShort.RETURN); + if (Retry.WhileFalse(() => FileDialog(app) is null, TimeSpan.FromSeconds(5), throwOnTimeout: false).Success) + { + return; + } + } + + // Left open, the dialog would keep the window from closing after the test. + Keyboard.Type(VirtualKeyShort.ESCAPE); + throw new InvalidOperationException("The Save As dialog did not take the path."); + } } From 133eece434b047f74ddab981b861ed8a47d033f0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 05:16:41 +0700 Subject: [PATCH 10/11] test(windows): shoot the pinned history run once it is drawn --- windows/tests/TablePro.App.UITests/SavedQueriesTests.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs b/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs index 01661d51c0..c22cc939ef 100644 --- a/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs +++ b/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs @@ -85,6 +85,12 @@ bool Shown() => tree.FindFirstDescendant(condition => AppSession.Wait, throwOnTimeout: false).Success; Assert.True(pinned, app.FindByNamePrefix(FiveTracks, runs).Name); + // The list is built again with the pinned run first, and UI Automation lists a row before it is drawn. + Assert.True(Retry.WhileFalse( + () => app.FindByNamePrefix(FiveTracks, runs) is { IsOffscreen: false } row && row.BoundingRectangle.Height > 0, + AppSession.Wait, + throwOnTimeout: false).Success); + Thread.Sleep(1_000); app.Screenshot("73-history-pinned"); app.RightClick(app.FindByNamePrefix(FiveTracks, runs), () => app.TryFindMenuItem("Unpin") is not null); From ed3b48d274dff71d04fa6cd88b9b19fef305ff61 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 06:00:06 +0700 Subject: [PATCH 11/11] test(windows): check the connections export opens Save As and leave the file to the core's tests --- .../ConnectionCopyTests.cs | 43 +++---------------- 1 file changed, 7 insertions(+), 36 deletions(-) diff --git a/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs index 6a34becbf7..66d3f3b0fd 100644 --- a/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs +++ b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs @@ -10,7 +10,7 @@ public sealed partial class ShellTests { [Theory] [MemberData(nameof(Themes))] - public void ADuplicateOpensTheFormOnTheCopyAndAnExportWritesTheFile(string theme) + public void ADuplicateOpensTheFormOnTheCopyAndExportAsksWhereToSave(string theme) { using var app = AppSession.Launch(theme); app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); @@ -29,42 +29,13 @@ public void ADuplicateOpensTheFormOnTheCopyAndAnExportWritesTheFile(string theme app.WaitForClose("Edit connection"); app.FindByNamePrefix("Chinook (Sample) (Copy),", tree); - var file = Path.Combine(app.DataFolder, "exported-connections.json"); + // The system's Save As dialog is not driven here; the core's and the interop's tests write the file. app.Click(app.Find("ExportConnectionsButton"), () => FileDialog(app) is not null); - SaveInFileDialog(app, file); - // The bar says what happened, and a wait that gives up keeps a shot of it. - app.FindByNamePrefix("Exported 2 connections.", app.Find("HomeMessageBar")); - Assert.True(File.Exists(file), "The export wrote no file."); - app.Screenshot("79-connections-exported"); - var text = File.ReadAllText(file); - Assert.Contains("Chinook (Sample) (Copy)", text, StringComparison.Ordinal); - } - - // The system's Save As dialog is Win32, as the Open dialog is: Enter saves to the path typed in its File name box. - private static void SaveInFileDialog(AppSession app, string path) - { - for (var attempt = 0; attempt < 3; attempt++) - { - var dialog = Retry.WhileNull(() => FileDialog(app), AppSession.Wait, throwOnTimeout: false).Result - ?? throw new InvalidOperationException("The Save As dialog did not appear."); - var name = Retry.WhileNull( - () => dialog.FindFirstDescendant(condition => condition.ByControlType(ControlType.Edit) - .And(condition.ByAutomationId("1001").Or(condition.ByName("File name:")))), - AppSession.Wait, - throwOnTimeout: false).Result - ?? throw new InvalidOperationException("The Save As dialog has no File name box."); - dialog.SetForeground(); - name.Focus(); - name.AsTextBox().Text = path; - Keyboard.Type(VirtualKeyShort.RETURN); - if (Retry.WhileFalse(() => FileDialog(app) is null, TimeSpan.FromSeconds(5), throwOnTimeout: false).Success) - { - return; - } - } - - // Left open, the dialog would keep the window from closing after the test. + var dialog = FileDialog(app) ?? throw new InvalidOperationException("The Save As dialog did not appear."); + dialog.SetForeground(); Keyboard.Type(VirtualKeyShort.ESCAPE); - throw new InvalidOperationException("The Save As dialog did not take the path."); + Assert.True( + Retry.WhileFalse(() => FileDialog(app) is null, AppSession.Wait, throwOnTimeout: false).Success, + "The Save As dialog stayed open."); } }