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/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 3c9bbe514d..ce1d938de9 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, @@ -158,6 +168,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. @@ -268,7 +314,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..6b5aef624a --- /dev/null +++ b/core/crates/ffi/src/import.rs @@ -0,0 +1,564 @@ +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, 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}; +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, + // 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. +#[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. + // `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, + }, + // 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, + }, + // 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, + }, +} + +#[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]>, + 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 { + id: u64, + 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, + plans: Mutex::new(Plans::default()), + })) + }) + .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, + takes_empty: column.info.column_type.kind.accepts_empty_string(), + }) + .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()), + )); + } + 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() + .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(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 + .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 { + // 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", + )); + } + plans.ready = Some(planned); + } + Ok(check) + } + + // 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 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 { + 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()), + _ => {} + } + plans.ready.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 { + 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 plans(&self) -> std::sync::MutexGuard<'_, Plans> { + self.plans.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +#[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], + columns: &[ImportColumn], + table: &TableRef, + dialect: &dyn SqlDialect, + gate: SaveGate, +) -> Result, CsvRowFault>, CoreError> { + let bytes = read_file(path)?; + let records = read_csv_records(&bytes, options, None).map_err(read_error)?; + drop(bytes); + let width = records.width; + 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 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(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))), + } + } + 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 { + id, + 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), + }, + // 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(), + lines: None, + }, + other => match other.category() { + ErrorCategory::Interrupted | ErrorCategory::Timeout | ErrorCategory::ConnectionLost => { + CsvImportOutcome::Unknown { + error: info(), + lines: None, + } + } + _ => 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(), + lines: None, + }, + } +} + +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 114969d31a..8b74ac7ab0 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 key_read; mod library; mod masking; @@ -29,6 +31,7 @@ mod row_edits; mod run; mod runtime; mod safe_mode_gate; +mod saved_queries; mod session; mod statement_at; mod structure; @@ -54,13 +57,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 key_read::{KeyKindTag, KeyReader, KeyTtlTag, KeyWindowInfo}; pub use library::{ ConnectionLibrary, ConnectionRecord, ConnectionSecrets, GroupRecord, ImportSummary, LibrarySnapshot, SafeModeTag, @@ -79,6 +88,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, DatabaseLayoutTag, DatabaseSession, FailureCauseTag, PageResume, RowEstimate, SessionHealthTag, TablePageRead, diff --git a/core/crates/ffi/src/library.rs b/core/crates/ffi/src/library.rs index 26ea269e5a..1a17a06296 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,79 @@ 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; + 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), + } + } + + // 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..80c23a545e --- /dev/null +++ b/core/crates/ffi/src/saved_queries.rs @@ -0,0 +1,211 @@ +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 + } + + // 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(); + 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..4daf3858a8 --- /dev/null +++ b/core/crates/ffi/tests/csv_import.rs @@ -0,0 +1,460 @@ +#![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, 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() +} + +// 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(); + 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(plan_of(&check), 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!( + 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); + 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(plan_of(&check), 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(1, 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(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:?}"); + 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, + None, + 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(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( + 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(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(); +} + +#[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/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..0a21e17294 --- /dev/null +++ b/core/crates/ffi/tests/saved_queries.rs @@ -0,0 +1,385 @@ +#![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(); +} + +#[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/0017-favourites.md b/core/docs/decisions/0017-favourites.md index b771612102..4020cbc58b 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 [0030](0030-storage-import-and-library-through-the-ffi.md) - **Date**: 2026-11-08 ## Context diff --git a/core/docs/decisions/0030-storage-import-and-library-through-the-ffi.md b/core/docs/decisions/0030-storage-import-and-library-through-the-ffi.md new file mode 100644 index 0000000000..f29d76fc77 --- /dev/null +++ b/core/docs/decisions/0030-storage-import-and-library-through-the-ffi.md @@ -0,0 +1,38 @@ +# 0030: 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. `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` 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. + +## 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). +- 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 + +- **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 d3e14d0bd3..8d9e4c7e0e 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 0030 | 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. | @@ -37,3 +37,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [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-a-catalog-read-keeps-a-byte-budget.md) | A catalog read keeps a byte budget | Accepted | `CatalogBudget` bounds what one SQLite or DuckDB catalog read holds at 64 MB, counting each text kept and each copy made per key, and fails `DriverError::CatalogTooLarge` past it; SQLite costs a key list before it compiles one and streams rows unsorted; DuckDB bounds a constraint read before it runs; a save's foreign key check rolls back past the budget. | +| [0030](0030-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 8ecd3f645b..56a22116a3 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, or for an engine that pages on the server (`CanSeek` false, Cassandra) the `PageResume` the page before handed back through `NextPage()`, since an offset there reads through every row before it; `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 and keeps the age and count `PruneAsync` is given. +- `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/0030-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`). - `DatabaseSession.Layout` says how the server's databases stand to the catalog, `GetDatabasesAsync` lists them, and `OpenEditorAsync(database)` opens an editor that runs in one (opened there or moved there; one that cannot reach it throws). `QueryEditor.Database` follows a typed USE. `TableProCore.ConnectAsync(database:)` opens a saved connection in another of its databases, and `OpenKey` reads a key-value engine's key a window at a time (`KeyReader`). - `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. 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..b4a2fa4668 --- /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 0030](../../../core/docs/decisions/0030-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... 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. + +### 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 may hold any of the 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..278721ec24 --- /dev/null +++ b/windows/src/TablePro.App.Model/CsvImportForm.cs @@ -0,0 +1,325 @@ +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, + + // Stopped, cut off, or written in part without a transaction to undo it: 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); + +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); + +// Text is what Safe Mode's review lists; Shown counts the statements in it. +public sealed record CsvImportReview(string Text, int Shown); + +// 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); + + // 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.Unknown unknown => new CsvImportReport( + CsvImportEnding.Unknown, 0, unknown.Lines, 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(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) + ? 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] : []; + // 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, + 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++) + { + 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(info, 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(ImportColumn column, int field) => + Preview is not { } preview + ? [] + : [.. preview.Rows + .Where(row => field < row.Count) + .Take(SampleCount) + .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) => + 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 d2293f6a77..c340199c06 100644 --- a/windows/src/TablePro.App/MainWindow.xaml +++ b/windows/src/TablePro.App/MainWindow.xaml @@ -40,6 +40,7 @@ + @@ -156,6 +157,7 @@ + @@ -198,6 +200,11 @@ + + + + + diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index 686cac286e..18a171ab5f 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -361,6 +361,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) @@ -1508,6 +1521,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; @@ -1548,6 +1564,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(); @@ -1663,6 +1681,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 378bbf2a1c..34c145ebf7 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; @@ -273,6 +274,35 @@ public async Task ClearHistoryAsync() return true; } + // 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() { @@ -303,6 +333,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 088b8e3c2f..a5d404eba4 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 @@ -3276,6 +3276,387 @@ 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. + + + 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}... + + + DEFAULT + + + (empty) + + + 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. + Key commands 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..7e00d11404 --- /dev/null +++ b/windows/src/TablePro.App/Views/ImportCsvDialog.cs @@ -0,0 +1,565 @@ +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(planned, 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), + }; + 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), + _ 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), + }; + } + + 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(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) + { + 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/QueryTabView.xaml.cs b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs index 4b8fc9d224..a7c116e02c 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs @@ -104,6 +104,12 @@ private async void LoadRestoredFile(SqlFileStamp? stamp, bool unsaved) => // 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; @@ -522,7 +528,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 new file mode 100644 index 0000000000..5e7650a5e3 --- /dev/null +++ b/windows/src/TablePro.App/Views/SaveQueryDialog.cs @@ -0,0 +1,424 @@ +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, each by the query's id: the name, the text, 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; + 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; + if (!draft.FolderChosen) + { + draft.FolderId = draft.StoredFolder; + } + } + } + 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.SetSqlAsync(id, draft.Sql).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); + folder.SelectionChanged += (_, _) => draft.FolderChosen = true; + 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; + + // 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; + + // 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..5825db7b23 --- /dev/null +++ b/windows/src/TablePro.App/Views/SavedQueriesPane.xaml.cs @@ -0,0 +1,532 @@ +using System.Collections.ObjectModel; +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(Microsoft.UI.Dispatching.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 f581391439..5e2d933ae8 100644 --- a/windows/src/TablePro.App/Views/TableTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/TableTabView.xaml.cs @@ -831,7 +831,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 bbc39a91a3..7729a891ee 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; private string? _cueColor; @@ -137,7 +143,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. @@ -268,6 +286,10 @@ internal void ShowConnected(SessionShare share, SessionConnecti { _ = ShowHistoryAsync(focus: false); } + else if (SavedQueriesVisible) + { + _ = ShowSavedQueriesAsync(focus: false); + } } public async void Start() @@ -596,7 +618,7 @@ public async Task ToggleHistoryAsync() { if (HistoryVisible) { - HideHistory(); + HideSidePane(); return; } @@ -632,21 +654,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(); @@ -655,13 +678,159 @@ 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); + } + } + + 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) + { + 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) @@ -744,6 +913,59 @@ 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) + { + // 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 (Tabs.TabItems.OfType().Any(item => ReferenceEquals(item.Content, view))) + { + 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; @@ -927,6 +1149,7 @@ internal void Take(TabViewItem item, int? index = null) if (content.Editor is { } editor) { editor.TextChanged += OnEditorTextChanged; + _editorHasText[editor] = HasText(editor.Document); } } @@ -952,6 +1175,8 @@ internal void Take(TabViewItem item, int? index = null) { query.DialogOwner = this; query.HistoryRecorded += OnHistoryRecorded; + query.CanSaveQuery = CanShowSavedQueries; + query.SaveQueryRequested += OnSaveQueryRequested; query.OpenFilesRequested += OnOpenFilesRequested; query.FileSaved += OnFileSaved; } @@ -986,6 +1211,7 @@ internal void Release(TabViewItem item) if (content.Editor is { } editor) { editor.TextChanged -= OnEditorTextChanged; + _editorHasText.Remove(editor); } _snapshots.Remove(content); @@ -1011,6 +1237,7 @@ internal void Release(TabViewItem item) if (item.Content is QueryTabView query) { query.HistoryRecorded -= OnHistoryRecorded; + query.SaveQueryRequested -= OnSaveQueryRequested; query.OpenFilesRequested -= OnOpenFilesRequested; query.FileSaved -= OnFileSaved; } @@ -1108,7 +1335,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(); @@ -1733,6 +1974,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..b57e849ddb --- /dev/null +++ b/windows/src/TablePro.Interop/CsvImport.cs @@ -0,0 +1,186 @@ +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. +// 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); + +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 + { + // 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 + { + 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; + + // 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. +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, + column.TakesEmpty))]; + } + + 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)) + { + Plan = ready.Plan, + }, + 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, + }; + } + + // 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) + { + 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)), + Native.CsvImportOutcome.RolledBack rolledBack => new CsvImportOutcome.RolledBack( + Mapping.Error(rolledBack.Error), + Lines(rolledBack.Lines)), + 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."), + }; + } + + 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 1c84d19926..0ae8683d32 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1179,6 +1179,72 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1670,7 +1736,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 @@ -1681,7 +1747,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 @@ -1692,7 +1758,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 @@ -1703,7 +1769,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 @@ -1714,7 +1780,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_prune(ulong @ptr,uint @retentionDays,uint @maxEntries + ulong uniffi_tablepro_ffi_fn_method_favouritestore_remove_database(ulong @ptr,RustBuffer @connectionId,RustBuffer @database ); #if NET8_0_OR_GREATER @@ -1725,7 +1791,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_table(ulong @ptr,RustBuffer @connectionId,RustBuffer @table ); #if NET8_0_OR_GREATER @@ -1736,7 +1802,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_set_database(ulong @ptr,RustBuffer @connectionId,RustBuffer @database,RustBuffer @environment ); #if NET8_0_OR_GREATER @@ -1747,7 +1813,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_keyreader(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_favouritestore_tables(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -1758,7 +1824,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_keyreader(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_queryhistorystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1769,7 +1835,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_keyreader_key(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_queryhistorystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1780,7 +1846,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_keyreader_read_more(ulong @ptr,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(ulong @ptr ); #if NET8_0_OR_GREATER @@ -1791,7 +1857,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_keyreader_rows(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(ulong @ptr,RustBuffer @ids ); #if NET8_0_OR_GREATER @@ -1802,7 +1868,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_queryhistorystore_export(ulong @ptr,RustBuffer @ids,RustBuffer @format,RustBuffer @path ); #if NET8_0_OR_GREATER @@ -1813,7 +1879,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_queryhistorystore_favourites(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1824,7 +1890,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_method_queryhistorystore_prune(ulong @ptr,uint @retentionDays,uint @maxEntries ); #if NET8_0_OR_GREATER @@ -1835,7 +1901,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 + ulong uniffi_tablepro_ffi_fn_method_queryhistorystore_record(ulong @ptr,ulong @session,RustBuffer @run ); #if NET8_0_OR_GREATER @@ -1846,7 +1912,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_saved_queries(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1857,7 +1923,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_search(ulong @ptr,RustBuffer @text,RustBuffer @connectionId,RustBuffer @after,uint @limit ); #if NET8_0_OR_GREATER @@ -1868,7 +1934,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_set_pinned(ulong @ptr,long @id,sbyte @pinned ); #if NET8_0_OR_GREATER @@ -1879,7 +1945,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_clone_csvimport(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1890,7 +1956,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 + void uniffi_tablepro_ffi_fn_free_csvimport(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1901,7 +1967,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 + RustBuffer uniffi_tablepro_ffi_fn_method_csvimport_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1912,7 +1978,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_csvimport_plan(ulong @ptr,RustBuffer @path,RustBuffer @options,RustBuffer @mapping ); #if NET8_0_OR_GREATER @@ -1923,7 +1989,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_csvimport_preview(ulong @ptr,RustBuffer @path,RustBuffer @options ); #if NET8_0_OR_GREATER @@ -1934,7 +2000,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_method_csvimport_run(ulong @ptr,ulong @plan,sbyte @confirmed,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -1945,7 +2011,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 + RustBuffer uniffi_tablepro_ffi_fn_method_csvimport_suggest_mapping(ulong @ptr,RustBuffer @headers,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1956,7 +2022,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 + ulong uniffi_tablepro_ffi_fn_clone_keyreader(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1967,7 +2033,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 + void uniffi_tablepro_ffi_fn_free_keyreader(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1978,7 +2044,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 + RustBuffer uniffi_tablepro_ffi_fn_method_keyreader_key(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -1989,7 +2055,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_keyreader_read_more(ulong @ptr,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2000,7 +2066,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_keyreader_rows(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2011,7 +2077,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 @@ -2022,7 +2088,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 @@ -2033,7 +2099,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_tablekeys(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 @@ -2044,7 +2110,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_tablekeys(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 @@ -2055,7 +2121,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tablekeys_follow_reference(ulong @ptr,ulong @rows,ulong @row,sbyte @referencing,uint @key,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_add_favorites(ulong @ptr,RustBuffer @ids,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -2066,7 +2132,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tablekeys_row_references(ulong @ptr,ulong @rows,ulong @row,RustBuffer @column,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_create_group(ulong @ptr,RustBuffer @name,RustBuffer @parentId ); #if NET8_0_OR_GREATER @@ -2077,7 +2143,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_create_tag(ulong @ptr,RustBuffer @name,RustBuffer @color ); #if NET8_0_OR_GREATER @@ -2088,7 +2154,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_delete(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -2099,7 +2165,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_delete_group(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -2110,7 +2176,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_delete_tag(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -2121,7 +2187,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_duplicate(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2132,7 +2198,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(ulong @ptr,ulong @row,uint @column,ulong @maxBytes,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_connectionlibrary_export_file(ulong @ptr,RustBuffer @path ); #if NET8_0_OR_GREATER @@ -2143,7 +2209,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_import_file(ulong @ptr,RustBuffer @path ); #if NET8_0_OR_GREATER @@ -2154,7 +2220,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_text_head(ulong @ptr,ulong @row,uint @column,uint @maxChars,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 @@ -2165,7 +2231,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_move_to_group(ulong @ptr,RustBuffer @ids,RustBuffer @groupId,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -2176,7 +2242,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_remove_favorites(ulong @ptr,RustBuffer @ids ); #if NET8_0_OR_GREATER @@ -2187,7 +2253,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_rename_connection(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2198,7 +2264,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_rename_group(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2209,7 +2275,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_save(ulong @ptr,RustBuffer @record,RustBuffer @secrets ); #if NET8_0_OR_GREATER @@ -2220,7 +2286,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_set_favorite(ulong @ptr,RustBuffer @id,sbyte @favorite ); #if NET8_0_OR_GREATER @@ -2231,7 +2297,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_snapshot(ulong @ptr ); #if NET8_0_OR_GREATER @@ -2242,7 +2308,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_tag_connections(ulong @ptr,RustBuffer @ids,RustBuffer @tagId,sbyte @tagged ); #if NET8_0_OR_GREATER @@ -2253,7 +2319,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_update_tag(ulong @ptr,RustBuffer @id,RustBuffer @name,RustBuffer @color ); #if NET8_0_OR_GREATER @@ -2264,7 +2330,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_clone_tablekeys(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2275,7 +2341,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 + void uniffi_tablepro_ffi_fn_free_tablekeys(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2286,7 +2352,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 + RustBuffer uniffi_tablepro_ffi_fn_method_tablekeys_follow_reference(ulong @ptr,ulong @rows,ulong @row,sbyte @referencing,uint @key,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2297,7 +2363,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 + RustBuffer uniffi_tablepro_ffi_fn_method_tablekeys_row_references(ulong @ptr,ulong @rows,ulong @row,RustBuffer @column,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2308,7 +2374,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_clone_resultset(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2319,7 +2385,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 + void uniffi_tablepro_ffi_fn_free_resultset(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2330,7 +2396,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_method_resultset_share_masking(ulong @ptr,uint @visibleColumns,uint @maxRows ); #if NET8_0_OR_GREATER @@ -2341,7 +2407,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 + ulong uniffi_tablepro_ffi_fn_method_resultset_share_preview(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns ); #if NET8_0_OR_GREATER @@ -2352,7 +2418,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_summary(ulong @ptr,uint @visibleColumns,uint @maxRows,RustBuffer @columns ); #if NET8_0_OR_GREATER @@ -2363,7 +2429,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 + RustBuffer uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(ulong @ptr,ulong @row,uint @column,ulong @maxBytes,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2374,7 +2440,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 + 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 @@ -2385,7 +2451,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_head(ulong @ptr,ulong @row,uint @column,uint @maxChars,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2396,7 +2462,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 @@ -2407,7 +2473,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 @@ -2418,7 +2484,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 @@ -2429,7 +2495,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 @@ -2440,7 +2506,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 @@ -2451,7 +2517,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 @@ -2462,7 +2528,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 @@ -2473,7 +2539,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 @@ -2484,7 +2550,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 @@ -2495,7 +2561,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 @@ -2506,7 +2572,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_table_keys(ulong @ptr,RustBuffer @table,RustBuffer @cancel + ulong uniffi_tablepro_ffi_fn_method_rowsave_run(ulong @ptr,sbyte @confirmed,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2517,7 +2583,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_close(ulong @ptr + RustBuffer uniffi_tablepro_ffi_fn_method_rowsave_statements(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2528,7 +2594,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 + ulong uniffi_tablepro_ffi_fn_clone_tableeditor(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2539,7 +2605,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_database(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_tableeditor(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2550,7 +2616,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_database_layout(ulong @ptr,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 @@ -2561,7 +2627,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_databases(ulong @ptr,RustBuffer @cancel + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2572,7 +2638,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 + 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 @@ -2583,7 +2649,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 + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_lock(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2594,7 +2660,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 + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_lock_for(ulong @ptr,ulong @rows,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2605,7 +2671,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 + ulong uniffi_tablepro_ffi_fn_method_tableeditor_plan(ulong @ptr,ulong @rows,RustBuffer @edits,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2616,7 +2682,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 + ulong uniffi_tablepro_ffi_fn_clone_queryrun(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2627,7 +2693,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 + void uniffi_tablepro_ffi_fn_free_queryrun(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2638,7 +2704,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 + void uniffi_tablepro_ffi_fn_method_queryrun_cancel(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2649,7 +2715,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 + RustBuffer uniffi_tablepro_ffi_fn_method_queryrun_drain_events(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2660,7 +2726,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_method_queryrun_outcome(ulong @ptr ); #if NET8_0_OR_GREATER @@ -2671,7 +2737,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 @database,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 @@ -2682,7 +2748,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_databasesession_open_key(ulong @ptr,RustBuffer @key,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_method_queryrun_result_set(ulong @ptr,uint @index,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2693,7 +2759,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 + ulong uniffi_tablepro_ffi_fn_clone_savedquerystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2704,7 +2770,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,RustBuffer @resume,ulong @listener,RustBuffer @cancel + void uniffi_tablepro_ffi_fn_free_savedquerystore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2715,7 +2781,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_savedquerystore_create_folder(ulong @ptr,RustBuffer @connectionId,RustBuffer @name,RustBuffer @parentId ); #if NET8_0_OR_GREATER @@ -2726,7 +2792,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 + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_delete(ulong @ptr,long @id ); #if NET8_0_OR_GREATER @@ -2737,7 +2803,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 + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_delete_folder(ulong @ptr,long @id ); #if NET8_0_OR_GREATER @@ -2748,7 +2814,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_method_savedquerystore_delete_for_connection(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -2759,7 +2825,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 + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_move_folder(ulong @ptr,long @id,RustBuffer @parentId ); #if NET8_0_OR_GREATER @@ -2770,7 +2836,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_move_query(ulong @ptr,long @id,RustBuffer @folderId,RustBuffer @before ); #if NET8_0_OR_GREATER @@ -2781,7 +2847,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_rename(ulong @ptr,long @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2792,7 +2858,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_rename_folder(ulong @ptr,long @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -2803,7 +2869,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_save(ulong @ptr,RustBuffer @draft,sbyte @replace ); #if NET8_0_OR_GREATER @@ -2814,7 +2880,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_set_keyword(ulong @ptr,long @id,RustBuffer @keyword ); #if NET8_0_OR_GREATER @@ -2825,7 +2891,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_pageresume(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_set_sql(ulong @ptr,long @id,RustBuffer @sql ); #if NET8_0_OR_GREATER @@ -2836,7 +2902,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_pageresume(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_savedquerystore_snapshot(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -2847,7 +2913,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_clone_databasesession(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2858,7 +2924,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 + void uniffi_tablepro_ffi_fn_free_databasesession(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2869,7 +2935,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_databasesession_export_rows(ulong @ptr,ulong @rows,uint @visibleColumns,RustBuffer @format,RustBuffer @table,RustBuffer @path,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2880,7 +2946,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_method_tablepageread_next_page(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + 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 @@ -2891,7 +2957,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_databasesession_open_csv_import(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2902,7 +2968,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_databasesession_table_keys(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2913,7 +2979,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_databasesession_close(ulong @ptr ); #if NET8_0_OR_GREATER @@ -2924,7 +2990,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_method_databasesession_columns(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2935,7 +3001,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 + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_database(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2946,7 +3012,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 + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_database_layout(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2957,7 +3023,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_databases(ulong @ptr,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2968,7 +3034,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 + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_driver_id(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2979,7 +3045,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_filter_choices(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -2990,7 +3056,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 + RustBuffer uniffi_tablepro_ffi_fn_method_databasesession_gate_run(ulong @ptr,RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3001,7 +3067,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_health(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3012,7 +3078,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_health_change(ulong @ptr,RustBuffer @seen,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3023,7 +3089,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_id(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3034,7 +3100,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_name(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3045,7 +3111,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_object_definition(ulong @ptr,RustBuffer @object,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3056,7 +3122,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 + ulong uniffi_tablepro_ffi_fn_method_databasesession_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3067,7 +3133,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 + ulong uniffi_tablepro_ffi_fn_method_databasesession_open_editor(ulong @ptr,RustBuffer @database,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3078,7 +3144,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_open_key(ulong @ptr,RustBuffer @key,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3089,7 +3155,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle + sbyte uniffi_tablepro_ffi_fn_method_databasesession_read_only(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3100,7 +3166,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_read_table_page(ulong @ptr,RustBuffer @table,RustBuffer @sort,RustBuffer @filter,ulong @limit,ulong @offset,RustBuffer @resume,ulong @listener,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3111,7 +3177,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 + void uniffi_tablepro_ffi_fn_method_databasesession_reconnect(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3122,7 +3188,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_refresh_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3133,7 +3199,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_schemas(ulong @ptr,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3144,7 +3210,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i8(ulong @handle + sbyte uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(ulong @ptr,RustBuffer @level,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3155,7 +3221,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 + 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 @@ -3166,7 +3232,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 + 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 @@ -3177,7 +3243,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_editor(ulong @ptr,RustBuffer @table,sbyte @refresh,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3188,7 +3254,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(ulong @ptr,RustBuffer @table,RustBuffer @filter,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3199,7 +3265,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_row_estimate(ulong @ptr,RustBuffer @table,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3210,7 +3276,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_structure(ulong @ptr,RustBuffer @table,RustBuffer @kind,RustBuffer @cancel ); #if NET8_0_OR_GREATER @@ -3221,7 +3287,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_clone_pageresume(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3232,7 +3298,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i16(ulong @handle + void uniffi_tablepro_ffi_fn_free_pageresume(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3243,7 +3309,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 @@ -3254,7 +3320,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 @@ -3265,7 +3331,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 @@ -3276,7 +3342,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u32(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_method_tablepageread_next_page(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3287,7 +3353,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 + ulong uniffi_tablepro_ffi_fn_method_tablepageread_run(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3298,7 +3364,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 + RustBuffer uniffi_tablepro_ffi_fn_method_tablepageread_view_sql(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3309,7 +3375,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i32(ulong @handle + uint uniffi_tablepro_ffi_fn_method_tablepageread_visible_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3320,7 +3386,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_accountlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAccountListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -3331,7 +3397,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_hostbrowser(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostBrowser*/ @vtable ); #if NET8_0_OR_GREATER @@ -3342,7 +3408,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_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable ); #if NET8_0_OR_GREATER @@ -3353,7 +3419,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_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable ); #if NET8_0_OR_GREATER @@ -3364,7 +3430,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u64(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -3375,7 +3441,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_columns_for_secrets(RustBuffer @names,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3386,7 +3452,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_scan_sql_for_secrets(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3397,7 +3463,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_share_token_from_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3408,7 +3474,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_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3419,7 +3485,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 uniffi_tablepro_ffi_fn_func_scan_sql_for_personal_data(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3430,7 +3496,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_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3441,7 +3507,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_f32(ulong @handle + RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3452,7 +3518,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_f32(ulong @handle + void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3463,7 +3529,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 + RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3474,7 +3540,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_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3485,7 +3551,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_cancel_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3496,7 +3562,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_f64(ulong @handle + void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3507,7 +3573,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 + byte ffi_tablepro_ffi_rust_future_complete_u8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3518,7 +3584,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_poll_i8(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3529,7 +3595,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_cancel_i8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3540,7 +3606,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 + void ffi_tablepro_ffi_rust_future_free_i8(ulong @handle ); #if NET8_0_OR_GREATER @@ -3551,7 +3617,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 + sbyte ffi_tablepro_ffi_rust_future_complete_i8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3562,7 +3628,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_poll_u16(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3573,7 +3639,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_cancel_u16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3584,7 +3650,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_void(ulong @handle + void ffi_tablepro_ffi_rust_future_free_u16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3595,7 +3661,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 + ushort ffi_tablepro_ffi_rust_future_complete_u16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3606,7 +3672,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_poll_i16(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3617,7 +3683,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_cancel_i16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3628,7 +3694,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_share_token_from_link( + void ffi_tablepro_ffi_rust_future_free_i16(ulong @handle ); #if NET8_0_OR_GREATER @@ -3639,7 +3705,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_parse_connection_url( + short ffi_tablepro_ffi_rust_future_complete_i16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3650,7 +3716,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_poll_u32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3661,7 +3727,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_cancel_u32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3672,7 +3738,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( + void ffi_tablepro_ffi_rust_future_free_u32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3683,7 +3749,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_profile( + uint ffi_tablepro_ffi_rust_future_complete_u32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3694,7 +3760,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_poll_i32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3705,7 +3771,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_cancel_i32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3716,7 +3782,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_remove_device( + void ffi_tablepro_ffi_rust_future_free_i32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3727,7 +3793,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_in( + int ffi_tablepro_ffi_rust_future_complete_i32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3738,7 +3804,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_poll_u64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3749,7 +3815,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_cancel_u64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3760,7 +3826,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_create_share( + void ffi_tablepro_ffi_rust_future_free_u64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3771,7 +3837,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_extend_share( + ulong ffi_tablepro_ffi_rust_future_complete_u64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3782,7 +3848,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_poll_i64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3793,7 +3859,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_cancel_i64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3804,7 +3870,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share( + void ffi_tablepro_ffi_rust_future_free_i64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3815,7 +3881,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_share_limits( + long ffi_tablepro_ffi_rust_future_complete_i64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3826,7 +3892,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_poll_f32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3837,7 +3903,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_cancel_f32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3848,7 +3914,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_open_account( + void ffi_tablepro_ffi_rust_future_free_f32(ulong @handle ); #if NET8_0_OR_GREATER @@ -3859,7 +3925,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_connect_saved( + float ffi_tablepro_ffi_rust_future_complete_f32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3870,7 +3936,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_poll_f64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3881,7 +3947,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_cancel_f64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3892,7 +3958,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_library( + void ffi_tablepro_ffi_rust_future_free_f64(ulong @handle ); #if NET8_0_OR_GREATER @@ -3903,7 +3969,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_open_file( + double ffi_tablepro_ffi_rust_future_complete_f64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3914,7 +3980,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_poll_rust_buffer(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -3925,7 +3991,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_cancel_rust_buffer(ulong @handle ); #if NET8_0_OR_GREATER @@ -3936,7 +4002,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_close( + void ffi_tablepro_ffi_rust_future_free_rust_buffer(ulong @handle ); #if NET8_0_OR_GREATER @@ -3947,7 +4013,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_database( + RustBuffer ffi_tablepro_ffi_rust_future_complete_rust_buffer(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -3958,7 +4024,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 @@ -3969,7 +4035,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 @@ -3980,7 +4046,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 @@ -3991,7 +4057,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 @@ -4002,7 +4068,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 @@ -4013,7 +4079,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_prune( + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets( ); #if NET8_0_OR_GREATER @@ -4024,7 +4090,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_share_token_from_link( ); #if NET8_0_OR_GREATER @@ -4035,7 +4101,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_parse_connection_url( ); #if NET8_0_OR_GREATER @@ -4046,7 +4112,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_keyreader_key( + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data( ); #if NET8_0_OR_GREATER @@ -4057,7 +4123,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_keyreader_read_more( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_devices( ); #if NET8_0_OR_GREATER @@ -4068,7 +4134,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_keyreader_rows( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( ); #if NET8_0_OR_GREATER @@ -4079,7 +4145,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_method_accountservice_profile( ); #if NET8_0_OR_GREATER @@ -4090,7 +4156,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_method_accountservice_refresh( ); #if NET8_0_OR_GREATER @@ -4101,7 +4167,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_refresh_past_device_limit( ); #if NET8_0_OR_GREATER @@ -4112,7 +4178,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_remove_device( ); #if NET8_0_OR_GREATER @@ -4123,7 +4189,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_sign_in( ); #if NET8_0_OR_GREATER @@ -4134,7 +4200,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_sign_out( ); #if NET8_0_OR_GREATER @@ -4145,7 +4211,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_status( ); #if NET8_0_OR_GREATER @@ -4156,7 +4222,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_create_share( ); #if NET8_0_OR_GREATER @@ -4167,7 +4233,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_extend_share( ); #if NET8_0_OR_GREATER @@ -4178,7 +4244,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_fetch_shared( ); #if NET8_0_OR_GREATER @@ -4189,7 +4255,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_list_shares( ); #if NET8_0_OR_GREATER @@ -4200,7 +4266,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_revoke_share( ); #if NET8_0_OR_GREATER @@ -4211,7 +4277,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_share_limits( ); #if NET8_0_OR_GREATER @@ -4222,7 +4288,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_canceltoken_cancel( ); #if NET8_0_OR_GREATER @@ -4233,7 +4299,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_canceltoken_is_cancelled( ); #if NET8_0_OR_GREATER @@ -4244,7 +4310,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_core_open_account( ); #if NET8_0_OR_GREATER @@ -4255,7 +4321,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_core_connect_saved( ); #if NET8_0_OR_GREATER @@ -4266,7 +4332,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_core_drivers( ); #if NET8_0_OR_GREATER @@ -4277,7 +4343,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_core_history( ); #if NET8_0_OR_GREATER @@ -4288,7 +4354,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablekeys_follow_reference( + ushort uniffi_tablepro_ffi_checksum_method_core_library( ); #if NET8_0_OR_GREATER @@ -4299,7 +4365,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablekeys_row_references( + ushort uniffi_tablepro_ffi_checksum_method_core_open_file( ); #if NET8_0_OR_GREATER @@ -4310,7 +4376,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_test_connection( ); #if NET8_0_OR_GREATER @@ -4321,7 +4387,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_forget_changed_host_key( ); #if NET8_0_OR_GREATER @@ -4332,7 +4398,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_queryeditor_close( ); #if NET8_0_OR_GREATER @@ -4343,7 +4409,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_database( ); #if NET8_0_OR_GREATER @@ -4354,7 +4420,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_queryeditor_is_lost( ); #if NET8_0_OR_GREATER @@ -4365,7 +4431,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text_head( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_run( ); #if NET8_0_OR_GREATER @@ -4376,7 +4442,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_queryeditor_use_database( ); #if NET8_0_OR_GREATER @@ -4387,7 +4453,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_favouritestore_add_table( ); #if NET8_0_OR_GREATER @@ -4398,7 +4464,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_favouritestore_databases( ); #if NET8_0_OR_GREATER @@ -4409,7 +4475,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_favouritestore_remove_database( ); #if NET8_0_OR_GREATER @@ -4420,7 +4486,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_favouritestore_remove_table( ); #if NET8_0_OR_GREATER @@ -4431,7 +4497,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_favouritestore_set_database( ); #if NET8_0_OR_GREATER @@ -4442,7 +4508,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_favouritestore_tables( ); #if NET8_0_OR_GREATER @@ -4453,7 +4519,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_queryhistorystore_clear( ); #if NET8_0_OR_GREATER @@ -4464,7 +4530,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_queryhistorystore_delete( ); #if NET8_0_OR_GREATER @@ -4475,7 +4541,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_queryhistorystore_export( ); #if NET8_0_OR_GREATER @@ -4486,7 +4552,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_queryhistorystore_favourites( ); #if NET8_0_OR_GREATER @@ -4497,7 +4563,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_queryhistorystore_prune( ); #if NET8_0_OR_GREATER @@ -4508,7 +4574,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_queryhistorystore_record( ); #if NET8_0_OR_GREATER @@ -4519,7 +4585,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_queryhistorystore_saved_queries( ); #if NET8_0_OR_GREATER @@ -4530,7 +4596,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_search( ); #if NET8_0_OR_GREATER @@ -4541,7 +4607,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_set_pinned( ); #if NET8_0_OR_GREATER @@ -4552,7 +4618,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_csvimport_columns( ); #if NET8_0_OR_GREATER @@ -4563,7 +4629,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_csvimport_plan( ); #if NET8_0_OR_GREATER @@ -4574,7 +4640,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_csvimport_preview( ); #if NET8_0_OR_GREATER @@ -4585,7 +4651,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_csvimport_run( ); #if NET8_0_OR_GREATER @@ -4596,7 +4662,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_csvimport_suggest_mapping( ); #if NET8_0_OR_GREATER @@ -4607,7 +4673,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_keyreader_key( ); #if NET8_0_OR_GREATER @@ -4618,7 +4684,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_keyreader_read_more( ); #if NET8_0_OR_GREATER @@ -4629,7 +4695,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_keys( + ushort uniffi_tablepro_ffi_checksum_method_keyreader_rows( ); #if NET8_0_OR_GREATER @@ -4640,7 +4706,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_connectionlibrary_apply_cloud_pull( ); #if NET8_0_OR_GREATER @@ -4651,7 +4717,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_connectionlibrary_cloud_edits( ); #if NET8_0_OR_GREATER @@ -4662,7 +4728,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_database( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_add_favorites( ); #if NET8_0_OR_GREATER @@ -4673,7 +4739,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_database_layout( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_group( ); #if NET8_0_OR_GREATER @@ -4684,7 +4750,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_databases( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_tag( ); #if NET8_0_OR_GREATER @@ -4695,7 +4761,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_connectionlibrary_delete( ); #if NET8_0_OR_GREATER @@ -4706,7 +4772,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_connectionlibrary_delete_group( ); #if NET8_0_OR_GREATER @@ -4717,7 +4783,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_delete_tag( ); #if NET8_0_OR_GREATER @@ -4728,7 +4794,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_duplicate( ); #if NET8_0_OR_GREATER @@ -4739,7 +4805,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_export_file( ); #if NET8_0_OR_GREATER @@ -4750,7 +4816,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_import_file( ); #if NET8_0_OR_GREATER @@ -4761,7 +4827,7 @@ 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_move_groups( ); #if NET8_0_OR_GREATER @@ -4772,7 +4838,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_object_definition( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_to_group( ); #if NET8_0_OR_GREATER @@ -4783,7 +4849,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_objects( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_remove_favorites( ); #if NET8_0_OR_GREATER @@ -4794,7 +4860,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_editor( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_connection( ); #if NET8_0_OR_GREATER @@ -4805,7 +4871,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_key( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_group( ); #if NET8_0_OR_GREATER @@ -4816,7 +4882,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_only( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save( ); #if NET8_0_OR_GREATER @@ -4827,7 +4893,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_favorite( ); #if NET8_0_OR_GREATER @@ -4838,7 +4904,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_reconnect( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_snapshot( ); #if NET8_0_OR_GREATER @@ -4849,7 +4915,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_tag_connections( ); #if NET8_0_OR_GREATER @@ -4860,7 +4926,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_schemas( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag( ); #if NET8_0_OR_GREATER @@ -4871,7 +4937,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode( + ushort uniffi_tablepro_ffi_checksum_method_tablekeys_follow_reference( ); #if NET8_0_OR_GREATER @@ -4882,7 +4948,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query( + ushort uniffi_tablepro_ffi_checksum_method_tablekeys_row_references( ); #if NET8_0_OR_GREATER @@ -4893,7 +4959,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_statement_at( + ushort uniffi_tablepro_ffi_checksum_method_resultset_share_masking( ); #if NET8_0_OR_GREATER @@ -4904,7 +4970,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_editor( + ushort uniffi_tablepro_ffi_checksum_method_resultset_share_preview( ); #if NET8_0_OR_GREATER @@ -4915,7 +4981,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count( + ushort uniffi_tablepro_ffi_checksum_method_resultset_share_summary( ); #if NET8_0_OR_GREATER @@ -4926,7 +4992,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate( + ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes( ); #if NET8_0_OR_GREATER @@ -4937,7 +5003,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_structure( + ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text( ); #if NET8_0_OR_GREATER @@ -4948,7 +5014,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek( + ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text_head( ); #if NET8_0_OR_GREATER @@ -4959,7 +5025,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_next_page( + ushort uniffi_tablepro_ffi_checksum_method_resultset_columns( ); #if NET8_0_OR_GREATER @@ -4970,7 +5036,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_run( + ushort uniffi_tablepro_ffi_checksum_method_resultset_index( ); #if NET8_0_OR_GREATER @@ -4981,7 +5047,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql( + ushort uniffi_tablepro_ffi_checksum_method_resultset_is_finished( ); #if NET8_0_OR_GREATER @@ -4992,7 +5058,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns( + ushort uniffi_tablepro_ffi_checksum_method_resultset_open_cursor( ); #if NET8_0_OR_GREATER @@ -5003,7 +5069,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_canceltoken_new( + ushort uniffi_tablepro_ffi_checksum_method_resultset_row_count( ); #if NET8_0_OR_GREATER @@ -5014,7 +5080,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_core_new( + ushort uniffi_tablepro_ffi_checksum_method_resultset_sorted( ); #if NET8_0_OR_GREATER @@ -5025,7 +5091,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_gate( ); #if NET8_0_OR_GREATER @@ -5036,7 +5102,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_is_empty( ); #if NET8_0_OR_GREATER @@ -5047,7 +5113,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_run( ); #if NET8_0_OR_GREATER @@ -5058,7 +5124,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_statements( ); #if NET8_0_OR_GREATER @@ -5069,7 +5135,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_check( ); #if NET8_0_OR_GREATER @@ -5080,7 +5146,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_columns( ); #if NET8_0_OR_GREATER @@ -5091,7 +5157,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start( ); #if NET8_0_OR_GREATER @@ -5102,7 +5168,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock( ); #if NET8_0_OR_GREATER @@ -5113,7 +5179,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for( ); #if NET8_0_OR_GREATER @@ -5124,7 +5190,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_plan( ); #if NET8_0_OR_GREATER @@ -5135,7 +5201,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_cancel( ); #if NET8_0_OR_GREATER @@ -5146,7 +5212,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostprompter_prompt( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_drain_events( ); #if NET8_0_OR_GREATER @@ -5157,7 +5223,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_runlistener_events_pending( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( ); #if NET8_0_OR_GREATER @@ -5168,117 +5234,843 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint ffi_tablepro_ffi_uniffi_contract_version( + 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( + ); - static void uniffiCheckContractApiVersion() { - var scaffolding_contract_version = _UniFFILib.ffi_tablepro_ffi_uniffi_contract_version(); - if (30 != scaffolding_contract_version) { - throw new UniffiContractVersionException($"TablePro.Interop.Native: uniffi bindings expected version `30`, library returned `{scaffolding_contract_version}`"); - } - } - static void uniffiCheckApiChecksums() { - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets(); - if (checksum != 2030) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets` checksum `2030`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets(); - if (checksum != 6288) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets` checksum `6288`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_share_token_from_link(); - if (checksum != 49369) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_share_token_from_link` checksum `49369`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_connection_url(); - if (checksum != 48047) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_connection_url` checksum `48047`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data(); - if (checksum != 17541) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data` checksum `17541`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_devices(); - if (checksum != 18213) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_devices` checksum `18213`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_feature_access(); - if (checksum != 31576) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_feature_access` checksum `31576`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_profile(); - if (checksum != 61215) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_profile` checksum `61215`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_refresh(); - if (checksum != 5597) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_refresh` checksum `5597`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit(); - if (checksum != 6648) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit` checksum `6648`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_remove_device(); - if (checksum != 12305) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_remove_device` checksum `12305`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_sign_in(); - if (checksum != 18871) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_sign_in` checksum `18871`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_sign_out(); - if (checksum != 10320) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_sign_out` checksum `10320`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_status(); - if (checksum != 7584) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_status` checksum `7584`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_create_share(); - if (checksum != 7238) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_create_share` checksum `7238`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_extend_share(); - if (checksum != 63736) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_extend_share` checksum `63736`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared(); - if (checksum != 32477) { + #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_set_sql( + ); + + #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_table_keys( + ); + + #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_database( + ); + + #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_database_layout( + ); + + #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_databases( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_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 + [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_object_definition( + ); + + #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_objects( + ); + + #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_editor( + ); + + #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_key( + ); + + #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_read_only( + ); + + #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_read_table_page( + ); + + #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_reconnect( + ); + + #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_refresh_objects( + ); + + #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_schemas( + ); + + #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_set_safe_mode( + ); + + #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_sorted_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_databasesession_statement_at( + ); + + #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_table_editor( + ); + + #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_table_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_databasesession_table_row_estimate( + ); + + #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_table_structure( + ); + + #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_tablepageread_can_seek( + ); + + #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_tablepageread_next_page( + ); + + #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_tablepageread_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_tablepageread_view_sql( + ); + + #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_tablepageread_visible_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_constructor_canceltoken_new( + ); + + #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_constructor_core_new( + ); + + #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_constructor_core_with_system_secrets( + ); + + #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_accountlistener_status_changed( + ); + + #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_hostbrowser_open_url( + ); + + #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_hostsecrets_load( + ); + + #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_hostsecrets_store( + ); + + #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_hostsecrets_relabel( + ); + + #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_hostsecrets_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_hostsecrets_delete_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_hostsecrets_load_item( + ); + + #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_hostsecrets_store_item( + ); + + #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_hostsecrets_delete_item( + ); + + #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_hostprompter_prompt( + ); + + #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_runlistener_events_pending( + ); + + #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 + uint ffi_tablepro_ffi_uniffi_contract_version( + ); + + + + static void uniffiCheckContractApiVersion() { + var scaffolding_contract_version = _UniFFILib.ffi_tablepro_ffi_uniffi_contract_version(); + if (30 != scaffolding_contract_version) { + throw new UniffiContractVersionException($"TablePro.Interop.Native: uniffi bindings expected version `30`, library returned `{scaffolding_contract_version}`"); + } + } + static void uniffiCheckApiChecksums() { + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets(); + if (checksum != 2030) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets` checksum `2030`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets(); + if (checksum != 6288) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets` checksum `6288`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_share_token_from_link(); + if (checksum != 49369) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_share_token_from_link` checksum `49369`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_connection_url(); + if (checksum != 48047) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_connection_url` checksum `48047`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data(); + if (checksum != 17541) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data` checksum `17541`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_devices(); + if (checksum != 18213) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_devices` checksum `18213`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_feature_access(); + if (checksum != 31576) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_feature_access` checksum `31576`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_profile(); + if (checksum != 61215) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_profile` checksum `61215`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_refresh(); + if (checksum != 5597) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_refresh` checksum `5597`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit(); + if (checksum != 6648) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit` checksum `6648`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_remove_device(); + if (checksum != 12305) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_remove_device` checksum `12305`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_sign_in(); + if (checksum != 18871) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_sign_in` checksum `18871`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_sign_out(); + if (checksum != 10320) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_sign_out` checksum `10320`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_status(); + if (checksum != 7584) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_status` checksum `7584`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_create_share(); + if (checksum != 7238) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_create_share` checksum `7238`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_extend_share(); + if (checksum != 63736) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_extend_share` checksum `63736`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared(); + if (checksum != 32477) { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared` checksum `32477`, library returned `{checksum}`"); } } @@ -5390,6 +6182,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) { @@ -5402,6 +6230,18 @@ 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_prune(); if (checksum != 50413) { @@ -5414,12 +6254,54 @@ static void uniffiCheckApiChecksums() { 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 != 28861) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_csvimport_run` checksum `28861`, 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_keyreader_key(); if (checksum != 50607) { @@ -5486,6 +6368,18 @@ static void uniffiCheckApiChecksums() { 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}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_connectionlibrary_import_file(); if (checksum != 61381) { @@ -5673,57 +6567,129 @@ static void uniffiCheckApiChecksums() { } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start(); - if (checksum != 21277) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start` checksum `21277`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start(); + if (checksum != 21277) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start` checksum `21277`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_lock(); + if (checksum != 43387) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_lock` checksum `43387`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for(); + if (checksum != 43908) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for` checksum `43908`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_plan(); + if (checksum != 7349) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_plan` checksum `7349`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_cancel(); + if (checksum != 58442) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_cancel` checksum `58442`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_drain_events(); + if (checksum != 56526) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_drain_events` checksum `56526`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_outcome(); + if (checksum != 54313) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_outcome` checksum `54313`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_release_set(); + if (checksum != 49856) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_release_set` checksum `49856`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_result_set(); + if (checksum != 63812) { + 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_tableeditor_lock(); - if (checksum != 43387) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_lock` checksum `43387`, 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_tableeditor_lock_for(); - if (checksum != 43908) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for` checksum `43908`, 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_tableeditor_plan(); - if (checksum != 7349) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_plan` checksum `7349`, 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_queryrun_cancel(); - if (checksum != 58442) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_cancel` checksum `58442`, 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_queryrun_drain_events(); - if (checksum != 56526) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_drain_events` checksum `56526`, 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_queryrun_outcome(); - if (checksum != 54313) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_outcome` checksum `54313`, 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_queryrun_release_set(); - if (checksum != 49856) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_queryrun_release_set` checksum `49856`, 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_queryrun_result_set(); - if (checksum != 63812) { - 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_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}`"); } } { @@ -5738,6 +6704,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_table_keys(); if (checksum != 62706) { @@ -6852,6 +7824,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); @@ -7119,6 +8095,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( @@ -7611,39 +8631,250 @@ public async Task ForgetChangedHostKey(ConnectionRecord @record, string @host, s ); } - - - /// - public static Core WithSystemSecrets(HostConfig @config) { - return new Core( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_constructor_core_with_system_secrets(FfiConverterTypeHostConfig.INSTANCE.Lower(@config), ref _status) -)); + + + /// + public static Core WithSystemSecrets(HostConfig @config) { + return new Core( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_constructor_core_with_system_secrets(FfiConverterTypeHostConfig.INSTANCE.Lower(@config), ref _status) +)); + } + + +} +class FfiConverterTypeCore: FfiConverter { + public static FfiConverterTypeCore INSTANCE = new FfiConverterTypeCore(); + + + public override ulong Lower(Core value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override Core Lift(ulong value) { + return new Core(value); + } + + public override Core Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(Core value) { + return 8; + } + + public override void Write(Core value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface ICsvImport { + ImportColumnInfo[] Columns(); + /// + Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping); + /// + Task Preview(string @path, CsvReadOptions @options); + /// + Task Run(ulong @plan, 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(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, 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), + // 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 FfiConverterTypeCore: FfiConverter { - public static FfiConverterTypeCore INSTANCE = new FfiConverterTypeCore(); +class FfiConverterTypeCsvImport: FfiConverter { + public static FfiConverterTypeCsvImport INSTANCE = new FfiConverterTypeCsvImport(); - public override ulong Lower(Core value) { + public override ulong Lower(CsvImport value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override Core Lift(ulong value) { - return new Core(value); + public override CsvImport Lift(ulong value) { + return new CsvImport(value); } - public override Core Read(BigEndianStream stream) { + public override CsvImport Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(Core value) { + public override int AllocationSize(CsvImport value) { return 8; } - public override void Write(Core value, BigEndianStream stream) { + public override void Write(CsvImport value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } @@ -7656,6 +8887,8 @@ internal interface IDatabaseSession { /// Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, CancelToken? @cancel); /// + Task OpenCsvImport(TableName @table, CancelToken? @cancel); + /// Task TableKeys(TableName @table, CancelToken? @cancel); /// Task Close(); @@ -7789,58 +9022,308 @@ internal T CallWithPointer(Func func) DecrementCallCounter(); } } - + + + /// + public async Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_rows(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterOptionalTypeTableName.INSTANCE.Lower(@table), FfiConverterString.INSTANCE.Lower(@path), 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) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_table(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path), 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) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + 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 TableKeys(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_keys(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) => FfiConverterTypeTableKeys.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_close(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 Columns(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_columns(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), 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) => FfiConverterSequenceTypeColumnEntry.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public string? Database() { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database(thisPtr, ref _status) +))); + } + + + public DatabaseLayoutTag DatabaseLayout() { + return CallWithPointer(thisPtr => FfiConverterTypeDatabaseLayoutTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database_layout(thisPtr, ref _status) +))); + } + + + /// + public async Task Databases(CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_databases(thisPtr, 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) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public string DriverId() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_driver_id(thisPtr, ref _status) +))); + } + + + /// + public async Task FilterChoices(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_filter_choices(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), 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) => FfiConverterTypeFilterChoices.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public RunGate GateRun(string @sql) { + return CallWithPointer(thisPtr => FfiConverterTypeRunGate.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_gate_run(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), ref _status) +))); + } + + + public SessionHealthTag Health() { + return CallWithPointer(thisPtr => FfiConverterTypeSessionHealthTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health(thisPtr, ref _status) +))); + } + + + /// + public async Task HealthChange(SessionHealthTag @seen, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health_change(thisPtr, FfiConverterTypeSessionHealthTag.INSTANCE.Lower(@seen), 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) => FfiConverterTypeSessionHealthTag.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public string Id() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_id(thisPtr, ref _status) +))); + } + + + public string Name() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_name(thisPtr, ref _status) +))); + } + /// - public async Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, CancelToken? @cancel) { + public async Task ObjectDefinition(ObjectEntry @object, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_rows(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterOptionalTypeTableName.INSTANCE.Lower(@table), FfiConverterString.INSTANCE.Lower(@path), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_object_definition(thisPtr, FfiConverterTypeObjectEntry.INSTANCE.Lower(@object), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (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_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), + (result) => FfiConverterOptionalTypeObjectSource.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, CancelToken? @cancel) { + public async Task Objects(ObjectScopeArg @scope, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_table(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (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_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task TableKeys(TableName @table, CancelToken? @cancel) { + public async Task OpenEditor(string? @database, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_keys(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_editor(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), @@ -7851,74 +9334,65 @@ public async Task TableKeys(TableName @table, CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterTypeTableKeys.INSTANCE.Lift(result), + (result) => FfiConverterTypeQueryEditor.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_close(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 KeyReader OpenKey(string @key) { + return CallWithPointer(thisPtr => FfiConverterTypeKeyReader.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_key(thisPtr, FfiConverterString.INSTANCE.Lower(@key), ref _status) +))); + } + + + public bool ReadOnly() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_only(thisPtr, ref _status) +))); } + /// - public async Task Columns(TableName @table, CancelToken? @cancel) { + public async Task ReadTablePage(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ulong @limit, ulong @offset, PageResume? @resume, RunListener @listener, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_columns(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_table_page(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterUInt64.INSTANCE.Lower(@limit), FfiConverterUInt64.INSTANCE.Lower(@offset), FfiConverterOptionalTypePageResume.INSTANCE.Lower(@resume), FfiConverterTypeRunListener.INSTANCE.Lower(@listener), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (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_rust_buffer(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterSequenceTypeColumnEntry.INSTANCE.Lift(result), + (result) => FfiConverterTypeTablePageRead.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public string? Database() { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + public void Reconnect() { + CallWithPointer(thisPtr => _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database(thisPtr, ref _status) -))); + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_reconnect(thisPtr, ref _status) +)); } - public DatabaseLayoutTag DatabaseLayout() { - return CallWithPointer(thisPtr => FfiConverterTypeDatabaseLayoutTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database_layout(thisPtr, ref _status) -))); - } - /// - public async Task Databases(CancelToken? @cancel) { + public async Task RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_databases(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -7929,26 +9403,18 @@ public async Task Databases(CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public string DriverId() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_driver_id(thisPtr, ref _status) -))); - } - - /// - public async Task FilterChoices(TableName @table, CancelToken? @cancel) { + public async Task Schemas(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_filter_choices(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_schemas(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -7959,72 +9425,87 @@ public async Task FilterChoices(TableName @table, CancelToken? @c // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeFilterChoices.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public RunGate GateRun(string @sql) { - return CallWithPointer(thisPtr => FfiConverterTypeRunGate.INSTANCE.Lift( + public bool SetSafeMode(SafeModeTag @level) { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_gate_run(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(thisPtr, FfiConverterTypeSafeModeTag.INSTANCE.Lower(@level), ref _status) ))); } - public SessionHealthTag Health() { - return CallWithPointer(thisPtr => FfiConverterTypeSessionHealthTag.INSTANCE.Lift( + /// + public string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending) { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_sorted_query(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterSequenceString.INSTANCE.Lower(@columns), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterBoolean.INSTANCE.Lower(@ascending), ref _status) +))); + } + + + public StatementSpan? StatementAt(string @sql, uint @caret) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeStatementSpan.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_statement_at(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterUInt32.INSTANCE.Lower(@caret), ref _status) ))); } /// - public async Task HealthChange(SessionHealthTag @seen, CancelToken? @cancel) { + public async Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health_change(thisPtr, FfiConverterTypeSessionHealthTag.INSTANCE.Lower(@seen), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_editor(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterBoolean.INSTANCE.Lower(@refresh), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (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_rust_buffer(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterTypeSessionHealthTag.INSTANCE.Lift(result), + (result) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public string Id() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_id(thisPtr, ref _status) -))); - } - - - public string Name() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_name(thisPtr, ref _status) -))); + /// + public async Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), 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) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task ObjectDefinition(ObjectEntry @object, CancelToken? @cancel) { + public async Task TableRowEstimate(TableName @table, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_object_definition(thisPtr, FfiConverterTypeObjectEntry.INSTANCE.Lower(@object), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -8035,18 +9516,18 @@ public string Name() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterOptionalTypeObjectSource.INSTANCE.Lift(result), + (result) => FfiConverterTypeRowEstimate.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Objects(ObjectScopeArg @scope, CancelToken? @cancel) { + public async Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_structure(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterTypeObjectKindTag.INSTANCE.Lower(@kind), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -8057,109 +9538,169 @@ public async Task Objects(ObjectScopeArg @scope, CancelToken? @ca // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), + (result) => FfiConverterTypeTableStructure.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - - /// - public async Task OpenEditor(string? @database, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_editor(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@database), 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) => FfiConverterTypeQueryEditor.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + + +} +class FfiConverterTypeDatabaseSession: FfiConverter { + public static FfiConverterTypeDatabaseSession INSTANCE = new FfiConverterTypeDatabaseSession(); + + + public override ulong Lower(DatabaseSession value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override DatabaseSession Lift(ulong value) { + return new DatabaseSession(value); + } + + public override DatabaseSession Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(DatabaseSession value) { + return 8; + } + + public override void Write(DatabaseSession value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +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 KeyReader OpenKey(string @key) { - return CallWithPointer(thisPtr => FfiConverterTypeKeyReader.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_key(thisPtr, FfiConverterString.INSTANCE.Lower(@key), ref _status) -))); + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. } - - - public bool ReadOnly() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_only(thisPtr, ref _status) -))); + + 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); } - - - /// - public async Task ReadTablePage(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ulong @limit, ulong @offset, PageResume? @resume, RunListener @listener, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_table_page(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterUInt64.INSTANCE.Lower(@limit), FfiConverterUInt64.INSTANCE.Lower(@offset), FfiConverterOptionalTypePageResume.INSTANCE.Lower(@resume), FfiConverterTypeRunListener.INSTANCE.Lower(@listener), 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) => FfiConverterTypeTablePageRead.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } } - - public void Reconnect() { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_reconnect(thisPtr, ref _status) -)); + + 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 RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task AddTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + 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_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (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_rust_buffer(future), - // Lift - (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Schemas(CancelToken? @cancel) { + public async Task Databases(string @connectionId) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_schemas(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + 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), @@ -8170,109 +9711,72 @@ public async Task Schemas(CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeFavouriteDatabaseInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public bool SetSafeMode(SafeModeTag @level) { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(thisPtr, FfiConverterTypeSafeModeTag.INSTANCE.Lower(@level), ref _status) -))); - } - - - /// - public string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending) { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_sorted_query(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterSequenceString.INSTANCE.Lower(@columns), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterBoolean.INSTANCE.Lower(@ascending), ref _status) -))); - } - - - public StatementSpan? StatementAt(string @sql, uint @caret) { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeStatementSpan.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_statement_at(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterUInt32.INSTANCE.Lower(@caret), ref _status) -))); - } - - /// - public async Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task RemoveDatabase(string @connectionId, string @database) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_editor(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterBoolean.INSTANCE.Lower(@refresh), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + 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_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + (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_u64(future), - // Lift - (result) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task RemoveTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + 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_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + (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_u64(future), - // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task TableRowEstimate(TableName @table, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + 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_databasesession_table_row_estimate(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + 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_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (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_rust_buffer(future), - // Lift - (result) => FfiConverterTypeRowEstimate.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel) { + public async Task Tables(string @connectionId) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_structure(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterTypeObjectKindTag.INSTANCE.Lower(@kind), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + 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), @@ -8283,7 +9787,7 @@ public async Task TableStructure(TableName @table, ObjectKindTag // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeTableStructure.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeFavouriteTableInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); @@ -8292,27 +9796,27 @@ public async Task TableStructure(TableName @table, ObjectKindTag } -class FfiConverterTypeDatabaseSession: FfiConverter { - public static FfiConverterTypeDatabaseSession INSTANCE = new FfiConverterTypeDatabaseSession(); +class FfiConverterTypeFavouriteStore: FfiConverter { + public static FfiConverterTypeFavouriteStore INSTANCE = new FfiConverterTypeFavouriteStore(); - public override ulong Lower(DatabaseSession value) { + public override ulong Lower(FavouriteStore value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override DatabaseSession Lift(ulong value) { - return new DatabaseSession(value); + public override FavouriteStore Lift(ulong value) { + return new FavouriteStore(value); } - public override DatabaseSession Read(BigEndianStream stream) { + public override FavouriteStore Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(DatabaseSession value) { + public override int AllocationSize(FavouriteStore value) { return 8; } - public override void Write(DatabaseSession value, BigEndianStream stream) { + public override void Write(FavouriteStore value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } @@ -8829,11 +10333,17 @@ internal interface IQueryHistoryStore { /// Task Delete(long[] @ids); /// + Task Export(long[] @ids, HistoryExportFormat @format, string @path); + FavouriteStore Favourites(); + /// Task Prune(uint @retentionDays, uint @maxEntries); /// 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; @@ -8960,6 +10470,32 @@ 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_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), + // 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 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 Prune(uint @retentionDays, uint @maxEntries) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -9004,6 +10540,14 @@ public async Task Prune(uint @retentionDays, uint @maxEntries) { ); } + 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( @@ -9026,6 +10570,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 + ); + } + } @@ -9651,30 +11213,357 @@ 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 SetSql(long @id, string @sql); + /// + 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 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 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 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), @@ -9685,44 +11574,94 @@ 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 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( + // 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)); } } @@ -10842,6 +12781,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, @@ -11102,6 +13147,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, @@ -11521,13 +13630,59 @@ public override int AllocationSize(HostKeyFailure value) { + FfiConverterBoolean.INSTANCE.AllocationSize(value.TrustAllowed); } - public override void Write(HostKeyFailure value, BigEndianStream stream) { - FfiConverterString.INSTANCE.Write(value.Host, stream); - FfiConverterString.INSTANCE.Write(value.Algorithm, stream); - FfiConverterString.INSTANCE.Write(value.Fingerprint, stream); - FfiConverterString.INSTANCE.Write(value.KnownHosts, stream); - FfiConverterUInt64.INSTANCE.Write(value.Line, stream); - FfiConverterBoolean.INSTANCE.Write(value.TrustAllowed, stream); + public override void Write(HostKeyFailure value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Host, stream); + FfiConverterString.INSTANCE.Write(value.Algorithm, stream); + FfiConverterString.INSTANCE.Write(value.Fingerprint, stream); + FfiConverterString.INSTANCE.Write(value.KnownHosts, stream); + FfiConverterUInt64.INSTANCE.Write(value.Line, stream); + FfiConverterBoolean.INSTANCE.Write(value.TrustAllowed, stream); + } +} + + + +internal record ImportColumnInfo ( + string Name, + string TypeName, + bool Nullable, + bool HasDefault, + bool ServerFilled, + bool TakesEmpty +) { +} + +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), + TakesEmpty: 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) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.TakesEmpty); + } + + 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); + FfiConverterBoolean.INSTANCE.Write(value.TakesEmpty, stream); } } @@ -11713,6 +13868,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 @@ -12270,6 +14455,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, @@ -13403,15 +15744,230 @@ 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 Plan, + 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), + 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.Plan) + + 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.Plan, stream); + 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)); } } } @@ -13422,80 +15978,87 @@ 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 - - public class Cancelled : CoreException { - public Cancelled() : base() {} - } +internal record CsvImportOutcome { + public record Imported ( + ulong Rows + ) : CsvImportOutcome {} + public record RolledBack ( + BoxedErrorInfo Error, + 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, + LineSpan? Lines + ) : 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.Unknown( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterOptionalTypeLineSpan.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.Unknown variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error) + + FfiConverterOptionalTypeLineSpan.INSTANCE.AllocationSize(variant_value.Lines); 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.Unknown variant_value: + stream.WriteInt(3); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterOptionalTypeLineSpan.INSTANCE.Write(variant_value.Lines, 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)); } } } @@ -13504,6 +16067,8 @@ public override void Write(CoreException value, BigEndianStream stream) { + + internal enum DataModelTag: int { Relational, KeyValue, @@ -13543,6 +16108,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 enum DatabaseLayoutTag: int { Single, AsSchemas, @@ -14317,6 +16924,42 @@ public override void Write(FollowedReference 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 {} @@ -18322,6 +20965,37 @@ public override void Write(KeyWindowInfo? 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(); @@ -19221,21 +21895,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 @@ -19243,12 +22009,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); @@ -19256,7 +22022,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)); } } @@ -19264,24 +22030,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 @@ -19289,12 +22055,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); @@ -19302,7 +22068,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)); } } @@ -19310,24 +22076,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 @@ -19335,12 +22101,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); @@ -19348,7 +22114,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)); } } @@ -19356,24 +22122,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 @@ -19381,12 +22147,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); @@ -19394,7 +22160,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)); } } @@ -19402,24 +22168,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 @@ -19427,12 +22193,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); @@ -19440,7 +22206,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)); } } @@ -19632,6 +22398,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(); @@ -20000,6 +22812,98 @@ public override void Write(RowReferenceChoice[] 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(); @@ -20782,6 +23686,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 609a09d97f..f5c2696ae9 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); @@ -126,6 +133,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..6c065b6d76 --- /dev/null +++ b/windows/src/TablePro.Interop/SavedQueries.cs @@ -0,0 +1,106 @@ +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)); + } + + // 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)); + + // 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..0bfda91648 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/CsvImportFormTests.cs @@ -0,0 +1,289 @@ +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 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() + { + 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.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 ASampleShowsWhatTheImportWritesForTheNullText() + { + var form = Form(); + form.Show(form.Read(CsvDelimiter.Comma, hasHeader: true), People(), [null, 0, 1, null]); + + // 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( + [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] + 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.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, null))); + + Assert.True(CsvImportReport.From(new CsvImportOutcome.Imported(3)).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); + } + + // 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, 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( + ["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..66d3f3b0fd --- /dev/null +++ b/windows/tests/TablePro.App.UITests/ConnectionCopyTests.cs @@ -0,0 +1,41 @@ +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 ADuplicateOpensTheFormOnTheCopyAndExportAsksWhereToSave(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); + + // 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); + var dialog = FileDialog(app) ?? throw new InvalidOperationException("The Save As dialog did not appear."); + dialog.SetForeground(); + Keyboard.Type(VirtualKeyShort.ESCAPE); + Assert.True( + Retry.WhileFalse(() => FileDialog(app) is null, AppSession.Wait, throwOnTimeout: false).Success, + "The Save As dialog stayed open."); + } +} 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..c22cc939ef --- /dev/null +++ b/windows/tests/TablePro.App.UITests/SavedQueriesTests.cs @@ -0,0 +1,122 @@ +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); + // 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); + 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..f0f6503096 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/CsvImportTests.cs @@ -0,0 +1,116 @@ +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 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); + 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)); + 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(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)); + 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); + 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); + 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..b8baa8ec53 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/SavedQueryTests.cs @@ -0,0 +1,156 @@ +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); + + 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)); + + 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); +}