diff --git a/Cargo.lock b/Cargo.lock index eac7c32deb..2ef8cf7d6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7973,6 +7973,7 @@ dependencies = [ "tablepro-driver-postgres", "tablepro-driver-redis", "tablepro-driver-sqlite", + "tablepro-foreign-import", "tablepro-session", "tablepro-ssh", "tablepro-storage", diff --git a/Cargo.toml b/Cargo.toml index d1fe00c6dd..a9b8284f5b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -172,13 +172,15 @@ uuid = { version = "1", features = ["v4", "serde"] } url = "2" percent-encoding = "2" # The Windows Credential Manager, where the core keeps secrets on Windows, the -# owning process of a loopback connection, from GetExtendedTcpTable, and the -# MachineGuid the TablePro account derives the machine ID from. +# owning process of a loopback connection, from GetExtendedTcpTable, the +# MachineGuid the TablePro account derives the machine ID from, and DPAPI, +# which another app's key sealed to the user opens with. windows-sys = { version = "0.61", features = [ "Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Credentials", + "Win32_Security_Cryptography", "Win32_System_Registry", ] } # What other apps' saved connections are kept in: binary and XML property diff --git a/core/crates/ffi/Cargo.toml b/core/crates/ffi/Cargo.toml index 05f0eb5723..1b56fabdda 100644 --- a/core/crates/ffi/Cargo.toml +++ b/core/crates/ffi/Cargo.toml @@ -37,6 +37,7 @@ tablepro-driver-mysql = { workspace = true, optional = true } tablepro-driver-postgres = { workspace = true, optional = true } tablepro-driver-redis = { workspace = true, optional = true } tablepro-driver-sqlite = { workspace = true, optional = true } +tablepro-foreign-import.workspace = true tablepro-session = { workspace = true, features = ["in-process-ssh"] } tablepro-ssh = { workspace = true, features = ["in-process"] } tablepro-storage.workspace = true diff --git a/core/crates/ffi/src/core_handle.rs b/core/crates/ffi/src/core_handle.rs index cd3380585c..134cdfd884 100644 --- a/core/crates/ffi/src/core_handle.rs +++ b/core/crates/ffi/src/core_handle.rs @@ -352,6 +352,18 @@ impl Core { self.vault.clone() } + pub(crate) fn connection_store(&self) -> Result { + self.store.clone().ok_or_else(no_storage) + } + + pub(crate) fn registry(&self) -> Arc { + self.registry.clone() + } + + pub(crate) fn writes(&self) -> LibraryWrites { + self.writes.clone() + } + pub fn secret_items(&self) -> Arc { self.items.clone() } diff --git a/core/crates/ffi/src/foreign_import.rs b/core/crates/ffi/src/foreign_import.rs new file mode 100644 index 0000000000..abb782d4d0 --- /dev/null +++ b/core/crates/ffi/src/foreign_import.rs @@ -0,0 +1,844 @@ +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use tablepro_foreign_import::review::{ + ConnectionRow, ImportReview, ImportSelection, QueryAvailability, QueryRow, Resolution, ReviewInputs, RowNote, + TlsFileReason, apply_blocking, plan, save_queries, +}; +use tablepro_foreign_import::{ + ForeignApp, ForeignAppDirs, ForeignHost, ForeignImportError, ForeignImporter, ForeignPlatform, ForeignSslMode, + ImportRequest, PasswordOutcome, PasswordSource, SavedQuerySupport, +}; +use tablepro_storage::english_secret_label; + +use crate::cancel_token::{CancelToken, token}; +use crate::core_handle::Core; +use crate::error::CoreError; +use crate::library::{ConnectionRecord, TlsModeTag, parse_id}; +use crate::runtime::on_runtime; + +// The cap the core library puts on one saved query's text, which the review also holds a larger one to. +const SAVED_QUERY_BYTE_LIMIT: u64 = 1024 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ForeignAppTag { + TablePlus, + SequelAce, + DBeaver, + DataGrip, + BeekeeperStudio, + Navicat, + Dbx, +} + +impl From for ForeignAppTag { + fn from(app: ForeignApp) -> Self { + match app { + ForeignApp::TablePlus => Self::TablePlus, + ForeignApp::SequelAce => Self::SequelAce, + ForeignApp::DBeaver => Self::DBeaver, + ForeignApp::DataGrip => Self::DataGrip, + ForeignApp::BeekeeperStudio => Self::BeekeeperStudio, + ForeignApp::Navicat => Self::Navicat, + ForeignApp::Dbx => Self::Dbx, + } + } +} + +impl From for ForeignApp { + fn from(app: ForeignAppTag) -> Self { + match app { + ForeignAppTag::TablePlus => Self::TablePlus, + ForeignAppTag::SequelAce => Self::SequelAce, + ForeignAppTag::DBeaver => Self::DBeaver, + ForeignAppTag::DataGrip => Self::DataGrip, + ForeignAppTag::BeekeeperStudio => Self::BeekeeperStudio, + ForeignAppTag::Navicat => Self::Navicat, + ForeignAppTag::Dbx => Self::Dbx, + } + } +} + +// Where other apps keep their files on this machine: the home folder, %APPDATA% and %LOCALAPPDATA% on Windows. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignAppDirsArg { + pub home: String, + pub config: String, + pub data: String, +} + +impl From for ForeignAppDirs { + fn from(dirs: ForeignAppDirsArg) -> Self { + Self { + platform: ForeignPlatform::current(), + home: PathBuf::from(dirs.home), + config: PathBuf::from(dirs.config), + data: PathBuf::from(dirs.data), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum PasswordSourceTag { + // The system keychain, which another app reads only on macOS. DataGrip may keep them in a KeePass file instead. + Keychain, + // Its own files under a fixed key, decrypted while reading. + AppFiles, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SavedQuerySupportTag { + // Saved queries sit apart from the connections, and the core keeps each with a connection. + GlobalFolder, + // Scripts land with the connection they run on; one with a default name starts unchecked. + Scripts, + // Query consoles land with their data source; one with a default name starts unchecked. + Consoles, + NotInExport, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignSourceInfo { + pub app: ForeignAppTag, + pub name: String, + // Its files are where it keeps them; always true for an app that imports from a file the user picks. + pub available: bool, + pub connections: u64, + pub saved_queries: u64, + // The export file's extensions for an app imported from a file the user picks; empty otherwise. + pub file_extensions: Vec, + pub passwords: PasswordSourceTag, + pub saved_query_support: SavedQuerySupportTag, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)] +pub struct ForeignImportRequest { + pub include_passwords: bool, + pub include_saved_queries: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum PasswordOutcomeTag { + NotRequested, + Read, + // A store was locked or would not answer, so the rest were not read. + Stopped, + // The app keeps them where this platform does not let another app read. + LeftInKeychain, +} + +impl From for PasswordOutcomeTag { + fn from(outcome: PasswordOutcome) -> Self { + match outcome { + PasswordOutcome::NotRequested => Self::NotRequested, + PasswordOutcome::Read => Self::Read, + PasswordOutcome::Stopped => Self::Stopped, + PasswordOutcome::LeftInKeychain => Self::LeftInKeychain, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ForeignSslModeTag { + Disabled, + Preferred, + Required, + VerifyCa, + VerifyIdentity, +} + +impl From for ForeignSslModeTag { + fn from(mode: ForeignSslMode) -> Self { + match mode { + ForeignSslMode::Disabled => Self::Disabled, + ForeignSslMode::Preferred => Self::Preferred, + ForeignSslMode::Required => Self::Required, + ForeignSslMode::VerifyCa => Self::VerifyCa, + ForeignSslMode::VerifyIdentity => Self::VerifyIdentity, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TlsFileReasonTag { + EngineLacks, + // A CA file needs Verify Full, and a client identity needs TLS on. + ModeLacks, + RelativePath, + // A certificate without its key, or a key without its certificate. + Incomplete, +} + +impl From for TlsFileReasonTag { + fn from(reason: TlsFileReason) -> Self { + match reason { + TlsFileReason::EngineLacks => Self::EngineLacks, + TlsFileReason::ModeLacks => Self::ModeLacks, + TlsFileReason::RelativePath => Self::RelativePath, + TlsFileReason::Incomplete => Self::Incomplete, + } + } +} + +// What the review tells the user about a row. Paths are as the other app wrote them. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum RowNoteInfo { + UnsupportedEngine { engine: String }, + SshKeyMissing { path: String }, + JumpHostKeyMissing { path: String }, + CaCertificateMissing { path: String }, + ClientCertificateMissing { path: String }, + ClientKeyMissing { path: String }, + TlsModeChanged { from: ForeignSslModeTag, to: TlsModeTag }, + TlsSettingsNotRead, + TlsFromDriverDefault { mode: ForeignSslModeTag }, + TlsNotKept { from: ForeignSslModeTag }, + CaFileNotKept { path: String, reason: TlsFileReasonTag }, + ClientIdentityNotKept { reason: TlsFileReasonTag }, + SshNotKept, + SshKeyNotKept { path: String }, + JumpHostNotKept { host: String }, + JumpHostPasswordNotKept { host: String }, + JumpHostKeyNotKept { host: String, path: String }, + FieldsNotKept { fields: Vec }, +} + +impl From<&RowNote> for RowNoteInfo { + fn from(note: &RowNote) -> Self { + match note.clone() { + RowNote::UnsupportedEngine { engine } => Self::UnsupportedEngine { engine }, + RowNote::SshKeyMissing { path } => Self::SshKeyMissing { path }, + RowNote::JumpHostKeyMissing { path } => Self::JumpHostKeyMissing { path }, + RowNote::CaCertificateMissing { path } => Self::CaCertificateMissing { path }, + RowNote::ClientCertificateMissing { path } => Self::ClientCertificateMissing { path }, + RowNote::ClientKeyMissing { path } => Self::ClientKeyMissing { path }, + RowNote::TlsModeChanged { from, to } => Self::TlsModeChanged { + from: from.into(), + to: to.into(), + }, + RowNote::TlsSettingsNotRead => Self::TlsSettingsNotRead, + RowNote::TlsFromDriverDefault { mode } => Self::TlsFromDriverDefault { mode: mode.into() }, + RowNote::TlsNotKept { from } => Self::TlsNotKept { from: from.into() }, + RowNote::CaFileNotKept { path, reason } => Self::CaFileNotKept { + path, + reason: reason.into(), + }, + RowNote::ClientIdentityNotKept { reason } => Self::ClientIdentityNotKept { reason: reason.into() }, + RowNote::SshNotKept => Self::SshNotKept, + RowNote::SshKeyNotKept { path } => Self::SshKeyNotKept { path }, + RowNote::JumpHostNotKept { host } => Self::JumpHostNotKept { host }, + RowNote::JumpHostPasswordNotKept { host } => Self::JumpHostPasswordNotKept { host }, + RowNote::JumpHostKeyNotKept { host, path } => Self::JumpHostKeyNotKept { host, path }, + RowNote::FieldsNotKept { fields } => Self::FieldsNotKept { fields }, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ExistingConnectionInfo { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignConnectionRow { + pub reference: String, + pub name: String, + // As the other app named it. + pub engine: String, + // As it would be saved; None when no engine here opens it, and such a row cannot be checked. + pub connection: Option, + pub group_path: Vec, + // The saved connection it matches by host, port, database and user. + pub duplicate: Option, + pub notes: Vec, + pub saved_query_count: u32, + pub carries_passwords: bool, +} + +impl From<&ConnectionRow> for ForeignConnectionRow { + fn from(row: &ConnectionRow) -> Self { + Self { + reference: row.reference.clone(), + name: row.name.clone(), + engine: row.engine.clone(), + connection: row.connection.as_ref().map(ConnectionRecord::from), + group_path: row.group_path.clone(), + duplicate: row.duplicate.as_ref().map(|existing| ExistingConnectionInfo { + id: existing.id.to_string(), + name: existing.name.clone(), + }), + notes: row.notes.iter().map(RowNoteInfo::from).collect(), + saved_query_count: u32::try_from(row.saved_query_count).unwrap_or(u32::MAX), + carries_passwords: row.carries_credentials, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignQueryRow { + pub reference: String, + pub name: String, + // The reference of the connection row it runs on. + pub connection: Option, + pub connection_name: Option, + pub byte_count: u64, +} + +impl From<&QueryRow> for ForeignQueryRow { + fn from(row: &QueryRow) -> Self { + Self { + reference: row.reference.clone(), + name: row.name.clone(), + connection: row.connection.clone(), + connection_name: row.connection_name.clone(), + byte_count: row.byte_count, + } + } +} + +// What a row does when a saved connection matches it. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum ResolutionTag { + Add, + AddCopy, + // Keeps the saved connection's id and secrets; offered only when both connect the same way. + Replace { id: String }, + // Writes nothing, so the row's saved queries land on the saved connection. + KeepExisting { id: String }, +} + +impl From for ResolutionTag { + fn from(resolution: Resolution) -> Self { + match resolution { + Resolution::Add => Self::Add, + Resolution::AddCopy => Self::AddCopy, + Resolution::Replace(id) => Self::Replace { id: id.to_string() }, + Resolution::KeepExisting(id) => Self::KeepExisting { id: id.to_string() }, + } + } +} + +impl TryFrom for Resolution { + type Error = CoreError; + + fn try_from(tag: ResolutionTag) -> Result { + Ok(match tag { + ResolutionTag::Add => Self::Add, + ResolutionTag::AddCopy => Self::AddCopy, + ResolutionTag::Replace { id } => Self::Replace(parse_id(&id)?), + ResolutionTag::KeepExisting { id } => Self::KeepExisting(parse_id(&id)?), + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignConnectionChoice { + pub reference: String, + pub selected: bool, + // What a checked row does; kept across an uncheck, so checking it again restores it. + pub resolution: Option, + // A Replace another checked row took is withdrawn here. + pub offered: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum QueryAvailabilityTag { + Available, + // The library keeps one query per name on a connection, and an earlier row of this import takes it. + AddedByAnotherRow, + TooLarge, + NameTooLong, + // Its connection is not imported, or its Replace went to another row. + ConnectionSkipped, + // The other app filed it under no connection, and the library keeps each query under one. + NoConnection, +} + +impl From for QueryAvailabilityTag { + fn from(availability: QueryAvailability) -> Self { + match availability { + QueryAvailability::Available => Self::Available, + QueryAvailability::AddedByAnotherRow => Self::AddedByAnotherRow, + QueryAvailability::TooLarge => Self::TooLarge, + QueryAvailability::NameTooLong => Self::NameTooLong, + QueryAvailability::ConnectionSkipped => Self::ConnectionSkipped, + QueryAvailability::NoConnection => Self::NoConnection, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignQueryChoice { + pub reference: String, + pub availability: QueryAvailabilityTag, + pub included: bool, +} + +// The review's checks as the import would write them, worked out again after every change. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ForeignImportChoices { + pub connections: Vec, + pub queries: Vec, + // False when the plan writes nothing. + pub importable: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)] +pub struct ForeignImportOutcome { + pub connections: u32, + pub replaced: u32, + // Passwords the secret store refused; their connections were imported without them. + pub passwords_not_kept: u32, + pub queries_added: u32, + // The connection already holds a query of that name, which is left alone. + pub queries_already_saved: u32, + pub queries_failed: u32, +} + +// Another app's connections and queries read once, checked against the library as it was then, and imported once. +#[derive(uniffi::Object)] +pub struct ForeignImportReview { + core: Arc, + review: ImportReview, + selection: Mutex, + applied: AtomicBool, +} + +impl ForeignImportReview { + fn selection(&self) -> std::sync::MutexGuard<'_, ImportSelection> { + self.selection.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +#[uniffi::export] +impl ForeignImportReview { + pub fn app(&self) -> ForeignAppTag { + self.review.app().into() + } + + pub fn passwords(&self) -> PasswordOutcomeTag { + self.review.passwords().into() + } + + pub fn connections(&self) -> Vec { + self.review + .connections() + .iter() + .map(ForeignConnectionRow::from) + .collect() + } + + pub fn saved_queries(&self) -> Vec { + self.review.saved_queries().iter().map(ForeignQueryRow::from).collect() + } + + pub fn choices(&self) -> ForeignImportChoices { + let selection = self.selection().clone(); + let planned = plan(&self.review, &selection); + ForeignImportChoices { + connections: self + .review + .connections() + .iter() + .map(|row| ForeignConnectionChoice { + reference: row.reference.clone(), + selected: selection.is_selected(&row.reference), + resolution: selection + .resolution(&row.reference) + .or_else(|| selection.offered_resolutions(row).first().copied()) + .map(ResolutionTag::from), + offered: selection + .offered_resolutions(row) + .into_iter() + .map(ResolutionTag::from) + .collect(), + }) + .collect(), + queries: self + .review + .saved_queries() + .iter() + .map(|row| { + let status = planned.query_status(&row.reference); + ForeignQueryChoice { + reference: row.reference.clone(), + availability: status + .map_or(QueryAvailabilityTag::NoConnection, |status| status.availability.into()), + included: status.is_some_and(|status| status.included), + } + }) + .collect(), + importable: !planned.is_empty(), + } + } + + // A row no engine here opens stays unchecked. + pub fn set_selected(&self, reference: String, selected: bool) { + self.selection().set_selected(selected, &reference, &self.review); + } + + // False when the row does not offer it, or another checked row took that Replace. + pub fn resolve(&self, reference: String, resolution: ResolutionTag) -> Result { + let resolution = Resolution::try_from(resolution)?; + Ok(self.selection().resolve(&reference, resolution, &self.review)) + } + + pub fn set_included(&self, reference: String, included: bool) { + self.selection().set_included(included, &reference); + } + + // Writes the checked rows once: the connections, their passwords into the secret store, then their saved queries. + // A library that changed since the read refuses with storage.import_outdated and writes nothing. + pub async fn apply(&self) -> Result { + if self.applied.swap(true, Ordering::AcqRel) { + return Err(CoreError::failed("foreign_import.applied", "this import already ran")); + } + let planned = plan(&self.review, &self.selection().clone()); + let core = self.core.clone(); + let review = self.review.clone(); + let tasks = core.tasks.clone(); + let written = on_runtime(&tasks, async move { write(&core, review, planned).await }).await; + // Refused before anything was written, so the user can read the other app again and import. + if written.is_err() { + self.applied.store(false, Ordering::Release); + } + written + } +} + +impl std::fmt::Debug for ForeignImportReview { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ForeignImportReview") + .field("app", &self.review.app()) + .field("connections", &self.review.connections().len()) + .finish_non_exhaustive() + } +} + +async fn write( + core: &Core, + review: ImportReview, + planned: tablepro_foreign_import::review::ImportPlan, +) -> Result { + let store = core.connection_store()?; + let vault = core.secret_vault(); + let held = core.writes(); + let _held = held.lock().await; + let reader = store.clone(); + let applied = core + .tasks + .spawn_blocking_task(move || apply_blocking(&review, &planned, &reader)) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))??; + let mut passwords_not_kept = 0_u32; + for imported in &applied.connections { + for secret in &imported.secrets { + let label = english_secret_label(secret.kind, &imported.connection.secret_target(secret.kind)); + if let Err(error) = vault + .store(imported.connection.id, secret.kind, &secret.secret, &label) + .await + { + tracing::warn!(code = error.code(), "a password of an imported connection was not kept"); + passwords_not_kept = passwords_not_kept.saturating_add(1); + } + } + } + let mut outcome = ForeignImportOutcome { + connections: count(applied.connections.len()), + replaced: count(applied.connections.iter().filter(|imported| imported.replaced).count()), + passwords_not_kept, + queries_added: 0, + queries_already_saved: 0, + queries_failed: 0, + }; + if applied.queries.is_empty() { + return Ok(outcome); + } + match core.history().await { + Ok(history) => { + let saved = save_queries(&applied, &history.saved_query_rows()).await; + outcome.queries_added = count(saved.added); + outcome.queries_already_saved = count(saved.already_saved); + outcome.queries_failed = count(saved.failed); + } + Err(error) => { + tracing::warn!(code = error.code(), "the saved queries of an import were not added"); + outcome.queries_failed = count(applied.queries.len()); + } + } + Ok(outcome) +} + +fn count(value: usize) -> u32 { + u32::try_from(value).unwrap_or(u32::MAX) +} + +#[uniffi::export] +impl Core { + // The apps this platform has, each looked for where it keeps its files. Reads files only, never a keychain. + pub async fn foreign_sources(&self, dirs: ForeignAppDirsArg) -> Result, CoreError> { + let dirs = ForeignAppDirs::from(dirs); + let tasks = self.tasks.clone(); + on_runtime(&self.tasks, async move { + tasks + .spawn_blocking_task(move || sources_blocking(&dirs)) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string())) + }) + .await + } + + // Reads the app's connections and saved queries, from `file` for one imported from an export the user picked, and + // checks them against the library as it is now. Fails with a foreign_import.* code. + pub async fn read_foreign( + self: Arc, + app: ForeignAppTag, + dirs: ForeignAppDirsArg, + file: Option, + request: ForeignImportRequest, + cancel: Option>, + ) -> Result, CoreError> { + let store = self.connection_store()?; + let dirs = ForeignAppDirs::from(dirs); + let importer = importer(app.into(), &dirs); + let importer = match file { + Some(file) => importer.with_file(PathBuf::from(file)), + None => importer, + }; + let request = ImportRequest { + include_passwords: request.include_passwords, + include_saved_queries: request.include_saved_queries, + saved_query_byte_limit: SAVED_QUERY_BYTE_LIMIT, + }; + let cancel = token(cancel); + let registry = self.registry(); + let core = self.clone(); + let tasks = self.tasks.clone(); + on_runtime(&self.tasks, async move { + let read = tasks.spawn_blocking_task(move || { + let collected = importer.collect_blocking(&request, &cancel).map_err(foreign_error)?; + let library = store.list_blocking()?; + let file_exists = |path: &Path| path.exists(); + Ok::<_, CoreError>(ImportReview::analyze( + collected, + ReviewInputs { + drivers: ®istry, + library, + dirs: &dirs, + file_exists: &file_exists, + }, + )) + }); + let review = read + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))??; + Ok(Arc::new(ForeignImportReview { + selection: Mutex::new(ImportSelection::defaults(&review)), + core, + review, + applied: AtomicBool::new(false), + })) + }) + .await + } +} + +fn sources_blocking(dirs: &ForeignAppDirs) -> Vec { + ForeignApp::ALL + .into_iter() + .filter(|app| app.runs_on(dirs.platform)) + .map(|app| { + let importer = importer(app, dirs); + let available = importer.is_available_blocking(); + let picks_file = app.picked_file_extensions(); + let inventory = if available && picks_file.is_none() { + importer.inventory_blocking() + } else { + tablepro_foreign_import::Inventory::default() + }; + ForeignSourceInfo { + app: app.into(), + name: app.display_name().to_owned(), + available, + connections: inventory.connections as u64, + saved_queries: inventory.saved_queries as u64, + file_extensions: picks_file + .unwrap_or_default() + .iter() + .map(|extension| (*extension).to_owned()) + .collect(), + passwords: match app.password_source() { + PasswordSource::Keychain => PasswordSourceTag::Keychain, + PasswordSource::AppFiles => PasswordSourceTag::AppFiles, + }, + saved_query_support: match app.saved_query_support() { + SavedQuerySupport::GlobalFolder => SavedQuerySupportTag::GlobalFolder, + SavedQuerySupport::Scripts => SavedQuerySupportTag::Scripts, + SavedQuerySupport::Consoles => SavedQuerySupportTag::Consoles, + SavedQuerySupport::NotInExport => SavedQuerySupportTag::NotInExport, + }, + } + }) + .collect() +} + +fn importer(app: ForeignApp, dirs: &ForeignAppDirs) -> ForeignImporter { + ForeignImporter::new(app, dirs.clone(), host()) +} + +fn foreign_error(error: ForeignImportError) -> CoreError { + match error { + ForeignImportError::Cancelled => CoreError::Cancelled, + error => CoreError::failed(error.code(), error.to_string()), + } +} + +#[cfg(windows)] +fn host() -> Arc { + Arc::new(WindowsHost) +} + +#[cfg(not(windows))] +fn host() -> Arc { + Arc::new(tablepro_foreign_import::PlainHost) +} + +// No installed-app lookup and no other app's keychain; the user's DPAPI opens a key another app sealed to them. +#[cfg(windows)] +struct WindowsHost; + +#[cfg(windows)] +impl ForeignHost for WindowsHost { + fn data_protection(&self) -> Option> { + Some(Arc::new(dpapi::UserDataProtection)) + } +} + +#[cfg(windows)] +pub(crate) mod dpapi { + use windows_sys::Win32::Foundation::LocalFree; + use windows_sys::Win32::Security::Cryptography::{ + CRYPT_INTEGER_BLOB, CRYPTPROTECT_UI_FORBIDDEN, CryptUnprotectData, + }; + + // CryptUnprotectData with no entropy and no prompt, as IntelliJ seals its KeePass main key. + pub(crate) struct UserDataProtection; + + impl tablepro_foreign_import::DataProtection for UserDataProtection { + fn unprotect(&self, blob: &[u8]) -> Option> { + let input = CRYPT_INTEGER_BLOB { + cbData: u32::try_from(blob.len()).ok()?, + pbData: blob.as_ptr().cast_mut(), + }; + let mut output = CRYPT_INTEGER_BLOB { + cbData: 0, + pbData: std::ptr::null_mut(), + }; + // SAFETY: input points at `blob` for the call; output is written by the call and freed by `take`. + let ok = unsafe { + CryptUnprotectData( + &input, + std::ptr::null_mut(), + std::ptr::null(), + std::ptr::null(), + std::ptr::null(), + CRYPTPROTECT_UI_FORBIDDEN, + &mut output, + ) + }; + if ok == 0 { + tracing::warn!("another app's data protection blob did not open for this user"); + return None; + } + Some(take(output)) + } + } + + // The other side, for tests: what an app seals for the signed-in user. + #[cfg(test)] + pub(crate) fn protect(data: &[u8]) -> Option> { + use windows_sys::Win32::Security::Cryptography::CryptProtectData; + + let input = CRYPT_INTEGER_BLOB { + cbData: u32::try_from(data.len()).ok()?, + pbData: data.as_ptr().cast_mut(), + }; + let mut output = CRYPT_INTEGER_BLOB { + cbData: 0, + pbData: std::ptr::null_mut(), + }; + // SAFETY: as in `unprotect`. + let ok = unsafe { + CryptProtectData( + &input, + std::ptr::null(), + std::ptr::null(), + std::ptr::null(), + std::ptr::null(), + CRYPTPROTECT_UI_FORBIDDEN, + &mut output, + ) + }; + (ok != 0).then(|| take(output)) + } + + fn take(blob: CRYPT_INTEGER_BLOB) -> Vec { + if blob.pbData.is_null() { + return Vec::new(); + } + let length = usize::try_from(blob.cbData).unwrap_or(0); + // SAFETY: the call that filled `blob` allocated `cbData` bytes at `pbData`, freed once copied. + let bytes = unsafe { std::slice::from_raw_parts(blob.pbData, length) }.to_vec(); + // SAFETY: `pbData` came from LocalAlloc inside the call and is freed once. + unsafe { + LocalFree(blob.pbData.cast()); + } + bytes + } + + #[cfg(test)] + mod tests { + use tablepro_foreign_import::DataProtection; + + use super::*; + + #[test] + fn a_blob_sealed_for_this_user_opens_and_another_does_not() { + let sealed = protect(b"main key").expect("a sealed blob"); + assert_eq!( + UserDataProtection.unprotect(&sealed).as_deref(), + Some(b"main key".as_slice()) + ); + assert_eq!(UserDataProtection.unprotect(b"not a blob"), None); + } + } +} + +#[cfg(test)] +mod tests { + use uuid::Uuid; + + use super::*; + + #[test] + fn every_app_and_resolution_crosses_and_comes_back() { + for app in ForeignApp::ALL { + assert_eq!(ForeignApp::from(ForeignAppTag::from(app)), app); + } + let id = Uuid::new_v4(); + for resolution in [ + Resolution::Add, + Resolution::AddCopy, + Resolution::Replace(id), + Resolution::KeepExisting(id), + ] { + assert_eq!( + Resolution::try_from(ResolutionTag::from(resolution)).ok(), + Some(resolution) + ); + } + assert!(Resolution::try_from(ResolutionTag::Replace { id: "x".to_owned() }).is_err()); + } +} diff --git a/core/crates/ffi/src/history.rs b/core/crates/ffi/src/history.rs index ce1d938de9..7210d550e1 100644 --- a/core/crates/ffi/src/history.rs +++ b/core/crates/ffi/src/history.rs @@ -79,6 +79,10 @@ pub struct HistoryCursorArg { impl QueryHistoryStore { // The prune keeps every entry however old and drops the oldest past the store's cap. + pub(crate) fn saved_query_rows(&self) -> tablepro_storage::SavedQueries { + self.history.saved_queries() + } + pub(crate) async fn open(paths: StoragePaths, tasks: Tasks) -> Result, CoreError> { let history = QueryHistory::open(&paths).await?; match history.prune(0).await { diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index ac16e653c4..a6b0d7a710 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -18,6 +18,7 @@ mod error; mod export; mod favourites; mod filter; +mod foreign_import; mod history; mod host; mod host_key; @@ -66,6 +67,12 @@ pub use favourites::{DatabaseEnvironmentTag, FavouriteDatabaseInfo, FavouriteSto pub use filter::{ CombinatorTag, FilterChoices, FilterColumn, FilterOpTag, FilterRuleArg, FilterValueArg, TableFilterArg, }; +pub use foreign_import::{ + ExistingConnectionInfo, ForeignAppDirsArg, ForeignAppTag, ForeignConnectionChoice, ForeignConnectionRow, + ForeignImportChoices, ForeignImportOutcome, ForeignImportRequest, ForeignImportReview, ForeignQueryChoice, + ForeignQueryRow, ForeignSourceInfo, ForeignSslModeTag, PasswordOutcomeTag, PasswordSourceTag, QueryAvailabilityTag, + ResolutionTag, RowNoteInfo, SavedQuerySupportTag, TlsFileReasonTag, +}; pub use history::{ HistoryCursorArg, HistoryEntryInfo, HistoryExportFormat, HistoryOutcomeTag, HistoryPageInfo, HistoryRun, QueryHistoryStore, diff --git a/core/crates/ffi/src/results/result_set.rs b/core/crates/ffi/src/results/result_set.rs index 903e2f55e7..985b6e3c92 100644 --- a/core/crates/ffi/src/results/result_set.rs +++ b/core/crates/ffi/src/results/result_set.rs @@ -44,6 +44,10 @@ impl ResultSet { self.store.columns() } + pub(crate) fn store(&self) -> &Arc { + &self.store + } + pub(crate) fn extent(&self) -> tablepro_core::export::ResultExtent { self.store.extent() } diff --git a/core/crates/ffi/src/row_edits.rs b/core/crates/ffi/src/row_edits.rs index a740e0cff3..a591f99dba 100644 --- a/core/crates/ffi/src/row_edits.rs +++ b/core/crates/ffi/src/row_edits.rs @@ -1,13 +1,13 @@ use std::collections::{HashMap, HashSet}; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; -use tablepro_core::column::{ColumnInfo, ResultColumn}; +use tablepro_core::column::{ColumnDefault, ColumnInfo, ResultColumn}; use tablepro_core::dialect::SqlDialect; use tablepro_core::dml::BuildSqlError; use tablepro_core::edit::{ - CellInput, EditContext, EditParseError, is_unchanged, new_draft_cell, parse_edit_text, read_only_reason, - value_for_column, + CellInput, EditContext, EditParseError, ResultLock, is_unchanged, new_draft_cell, parse_edit_text, + read_only_reason, result_source, result_target, value_for_column, }; use tablepro_core::export::value_to_text; use tablepro_core::meta::{RowIdentity, TableRef}; @@ -24,7 +24,7 @@ use tablepro_session::{OperationError, OperationKind, Session}; use crate::cancel_token::{CancelToken, token}; use crate::catalog::TableName; use crate::error::{BoxedErrorInfo, CoreError}; -use crate::results::{ResultSet, ValueKind}; +use crate::results::{ResultSet, ResultStore, ValueKind}; use crate::runtime::on_runtime; // What the user put in a cell. An empty text means what `parse_edit_text` says it means for the column. @@ -51,7 +51,7 @@ pub enum RowEdit { Delete { row: u64 }, } -// Why no row of the table, or of the page, can be changed. +// Why no row of the table, of the page or of the query result can be changed. #[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] pub enum EditLock { ReadOnlyConnection, @@ -60,6 +60,30 @@ pub enum EditLock { KeyUnreadable { column: String }, // The page was read with other columns than the editor's catalog. ColumnsChanged, + // A query result's statement is not one SELECT (core ADR 0015). + NotOneSelect, + // A join, a subquery or a CTE. + MoreThanOneTable, + // DISTINCT, GROUP BY or an aggregate, so a row is not one row of the table. + Collapsed, + // The driver traced no column to the statement's table: a view, a temporary table, or an engine that reports none. + Untraced, + // The result leaves out part of the table's primary key. + KeyNotShown, +} + +impl From for EditLock { + fn from(lock: ResultLock) -> Self { + match lock { + ResultLock::NotOneSelect => Self::NotOneSelect, + ResultLock::MoreThanOneTable => Self::MoreThanOneTable, + ResultLock::Collapsed => Self::Collapsed, + ResultLock::Untraced => Self::Untraced, + ResultLock::NoPrimaryKey => Self::NoPrimaryKey, + ResultLock::KeyNotShown => Self::KeyNotShown, + ResultLock::ColumnsChanged => Self::ColumnsChanged, + } + } } // The Linux grid's rules: a saved row's key and a column the server fills are locked, a new row may set its key. @@ -108,15 +132,28 @@ pub enum RowSaveOutcome { Unknown { error: BoxedErrorInfo, edit: Option }, } -// A table tab's rows as the save sees them: the catalog's columns, keyed by the primary key, as the Linux tracker keys +// A table tab's rows, or a query result's, as the save sees them: keyed by the primary key, as the Linux tracker keys // them. #[derive(uniffi::Object)] pub struct TableEditor { session: Arc, tasks: Tasks, table: TableRef, + // The columns a save writes, one per column of the rows; a query result's column that writes none is generated. columns: Arc<[ColumnInfo]>, lock: Option, + layout: Layout, +} + +enum Layout { + // A table tab's page holds the catalog's columns first, in the table's order. + Page, + // A query result keeps the columns it was read with; each writes the catalog column it traced to (core ADR 0015). + // Edits name rows of that one result, so rows of another statement can never be keyed against this table. + Result { + read: Arc<[ResultColumn]>, + rows: Weak, + }, } impl TableEditor { @@ -155,6 +192,73 @@ impl TableEditor { table, columns, lock, + layout: Layout::Page, + })) + }) + .await + } + + // `sql` is the statement the result was read with. The table's columns are read again, so a result read after the + // table changed locks rather than writes a column by its old place. + pub(crate) async fn open_result( + session: Arc, + tasks: Tasks, + sql: String, + rows: Arc, + cancel: Option>, + ) -> Result, CoreError> { + let cancel = token(cancel); + let runtime = tasks.clone(); + on_runtime(&runtime, async move { + let read = rows.result_columns(); + let held = Arc::downgrade(rows.store()); + let locked = |session, tasks, read, lock: EditLock| { + Arc::new(Self { + session, + tasks, + table: TableRef::new(None, String::new()), + columns: Arc::from([]), + lock: Some(lock), + layout: Layout::Result { + read, + rows: held.clone(), + }, + }) + }; + if session.read_only() { + return Ok(locked(session, tasks, read, EditLock::ReadOnlyConnection)); + } + let source = match result_source(&sql, session.grammar(), &read) { + Ok(source) => source, + Err(lock) => return Ok(locked(session, tasks, read, lock.into())), + }; + let catalog = tokio::select! { + biased; + () = cancel.cancelled() => return Err(CoreError::Cancelled), + columns = session.refresh_columns(source.table.clone()) => columns?, + }; + let target = match result_target(&source, &read, &catalog) { + Ok(target) => target, + Err(lock) => return Ok(locked(session, tasks, read, lock.into())), + }; + let columns = read + .iter() + .zip(&target.positions) + .enumerate() + .map( + |(index, (column, position))| match position.and_then(|position| catalog.get(position)) { + Some(info) => info.clone(), + None => unwritable(index, column), + }, + ) + .collect(); + Ok(Arc::new(Self { + session, + tasks, + table: target.table, + columns, + lock: None, + layout: Layout::Result { read, rows: held }, })) }) .await @@ -175,14 +279,24 @@ impl TableEditor { } } - // The result set holds the page's columns first, which build_page lays out in the catalog's order. - fn check_layout(&self, rows: &[ResultColumn]) -> Result<(), CoreError> { - let same = rows.len() >= self.columns.len() - && self - .columns - .iter() - .zip(rows) - .all(|(catalog, read)| catalog.name == read.name); + // A page holds the catalog's columns first, which build_page lays out in the catalog's order; a query result is + // the one the editor was opened on, sorted or not. + fn check_layout(&self, set: &ResultSet, rows: &[ResultColumn]) -> Result<(), CoreError> { + let same = match &self.layout { + Layout::Page => { + rows.len() >= self.columns.len() + && self + .columns + .iter() + .zip(rows) + .all(|(catalog, read)| catalog.name == read.name) + } + Layout::Result { read, rows: held } => { + std::ptr::eq(held.as_ptr(), Arc::as_ptr(set.store())) + && rows.len() == read.len() + && read.iter().zip(rows).all(|(opened, now)| opened.name == now.name) + } + }; match same { true => Ok(()), false => Err(CoreError::failed( @@ -246,7 +360,7 @@ impl TableEditor { let read = rows.result_columns(); let reads_rows = edits.iter().any(|edit| !matches!(edit, RowEdit::Insert { .. })); if reads_rows { - self.check_layout(&read)?; + self.check_layout(rows, &read)?; } let deleted: HashSet = edits .iter() @@ -395,13 +509,30 @@ impl TableEditor { } } + // Whether a copy of the row holds its values exactly. PostgreSQL's server text for a float, a time or money may not + // name the stored value (core ADR 0015), so such a query result row is not duplicated; a table page's are typed. + pub fn copies_exactly(&self, rows: Arc, row: u64) -> bool { + match &self.layout { + Layout::Page => true, + Layout::Result { read, .. } => copies_exactly(read, &self.columns, &rows, row), + } + } + + // The table a save writes, as the result's driver named it; None while a query result is locked. + pub fn table(&self) -> Option { + (!self.table.name.is_empty()).then(|| TableName { + schema: self.table.schema.clone(), + name: self.table.name.clone(), + }) + } + // The page's own locks too: a lock here leaves every row of `rows` as it is. pub fn lock_for(&self, rows: Arc) -> Option { if let Some(lock) = self.lock() { return Some(lock); } let read = rows.result_columns(); - if self.check_layout(&read).is_err() { + if self.check_layout(&rows, &read).is_err() { return Some(EditLock::ColumnsChanged); } if rows.row_count() == 0 { @@ -415,8 +546,12 @@ impl TableEditor { let dialect = self.session.current_dialect(); self.columns .iter() - .map(|column| EditColumnInfo { - name: column.name.clone(), + .enumerate() + .map(|(index, column)| EditColumnInfo { + name: match &self.layout { + Layout::Result { read, .. } => read.get(index).map_or_else(String::new, |read| read.name.clone()), + Layout::Page => column.name.clone(), + }, editable: editable(column), editable_in_new_row: editable_in_new_row(column), new_row: match new_draft_cell(column) { @@ -608,7 +743,36 @@ pub(crate) fn save_gate(level: SafeModeLevel) -> SaveGate { } } -// The primary key columns in the table's order, the order a key is read in. +// The values a copy takes, as Duplicate copies them: every column but the key and what the server fills. +fn copies_exactly(read: &[ResultColumn], columns: &[ColumnInfo], rows: &ResultSet, row: u64) -> bool { + columns + .iter() + .enumerate() + .filter(|(_, column)| !column.primary_key && editable_in_new_row(column)) + .all(|(index, column)| match rows.stored_value(row, index) { + None | Some(Value::Null) => true, + Some(value) => read + .get(index) + .is_some_and(|read| value_for_column(&value, &read.column_type, &column.column_type).is_some()), + }) +} + +// A NUL cannot be in an identifier, so no key lookup by name ever lands on this column, and no statement names it. +fn unwritable(index: usize, column: &ResultColumn) -> ColumnInfo { + ColumnInfo { + name: format!("\0{index}"), + column_type: column.column_type.clone(), + nullable: true, + primary_key: false, + is_auto_increment: false, + is_generated: true, + partition_scoped: false, + default: ColumnDefault::None, + comment: None, + } +} + +// The primary key columns in the editor's order, the order a key is read in. fn pk_identity(columns: &[ColumnInfo]) -> RowIdentity { RowIdentity::UniqueKey { columns: columns @@ -793,6 +957,19 @@ fn lock_error(lock: &EditLock) -> CoreError { "edit.columns_changed", "the rows were read with other columns than the table has now", ), + EditLock::NotOneSelect => CoreError::failed("edit.not_one_select", "only the rows of one SELECT can be edited"), + EditLock::MoreThanOneTable => CoreError::failed( + "edit.more_than_one_table", + "rows from more than one table, a subquery or a CTE cannot be edited", + ), + EditLock::Collapsed => { + CoreError::failed("edit.collapsed", "grouped, distinct or computed rows cannot be edited") + } + EditLock::Untraced => CoreError::failed("edit.untraced", "only rows read straight from a table can be edited"), + EditLock::KeyNotShown => CoreError::failed( + "edit.key_not_shown", + "the result leaves out part of the table's primary key", + ), } } @@ -803,3 +980,59 @@ fn parse_error(error: EditParseError) -> CoreError { fn build_error(error: BuildSqlError) -> CoreError { CoreError::failed(error.code(), error.to_string()) } + +#[cfg(test)] +mod tests { + use tablepro_core::column::{ColumnKind, ColumnType, FloatWidth, IntegerKind, IntegerWidth, ReadForm}; + + use super::*; + use crate::results::ResultStore; + + fn catalog(name: &str, kind: ColumnKind) -> ColumnInfo { + ColumnInfo { + name: name.to_owned(), + column_type: ColumnType { + name: name.to_owned(), + kind, + catalog: None, + dynamic_storage: false, + read_form: ReadForm::Native, + }, + nullable: true, + primary_key: false, + is_auto_increment: false, + is_generated: false, + partition_scoped: false, + default: ColumnDefault::None, + comment: None, + } + } + + #[test] + fn server_text_for_a_float_does_not_copy_and_an_integer_s_does() { + let read: Arc<[ResultColumn]> = vec![ + ResultColumn::new("amount", ColumnType::untyped_text("float8")), + ResultColumn::new("count", ColumnType::untyped_text("int4")), + ] + .into(); + let columns = [ + catalog("amount", ColumnKind::Float(FloatWidth::F64)), + catalog( + "count", + ColumnKind::Integer(IntegerKind { + width: IntegerWidth::W32, + signed: true, + }), + ), + ]; + let store = Arc::new(ResultStore::new(read.clone())); + store.append(&[ + vec![Value::Text("0.1".to_owned()), Value::Text("7".to_owned())], + vec![Value::Null, Value::Text("8".to_owned())], + ]); + let rows = ResultSet::new(0, store); + + assert!(!copies_exactly(&read, &columns, &rows, 0)); + assert!(copies_exactly(&read, &columns, &rows, 1)); + } +} diff --git a/core/crates/ffi/src/session.rs b/core/crates/ffi/src/session.rs index 4d03ee8317..ff3bea64ee 100644 --- a/core/crates/ffi/src/session.rs +++ b/core/crates/ffi/src/session.rs @@ -24,6 +24,7 @@ use crate::error::{BoxedErrorInfo, CoreError}; use crate::filter::{self, FilterChoices, TableFilterArg}; use crate::key_read::KeyReader; use crate::library::SafeModeTag; +use crate::results::ResultSet; use crate::row_edits::TableEditor; use crate::run::{QueryRun, RunListener, RunOutcome, RunSink, RunState, TransactionStateTag}; use crate::runtime::on_runtime; @@ -554,6 +555,18 @@ impl DatabaseSession { TableEditor::open(self.session.clone(), self.tasks.clone(), table, refresh, cancel).await } + // A query result's rows as a save sees them, when its statement reads one table and the driver traced its columns + // (core ADR 0015); otherwise the editor carries the lock that says why not. `rows` is the run's only result set, + // read outside a transaction in the session's own database, which the app checks. + pub async fn result_editor( + &self, + sql: String, + rows: Arc, + cancel: Option>, + ) -> Result, CoreError> { + TableEditor::open_result(self.session.clone(), self.tasks.clone(), sql, rows, cancel).await + } + // `database` is where the editor runs: an engine that binds it at connect opens there, another moves there. pub async fn open_editor( &self, diff --git a/core/crates/ffi/tests/foreign_import.rs b/core/crates/ffi/tests/foreign_import.rs new file mode 100644 index 0000000000..5aa37ddbeb --- /dev/null +++ b/core/crates/ffi/tests/foreign_import.rs @@ -0,0 +1,290 @@ +#![expect( + clippy::unwrap_used, + reason = "the setup helpers fail a test the way the test functions themselves do" +)] + +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use secrecy::{ExposeSecret, SecretString}; +use tablepro_ffi::{ + Core, ForeignAppDirsArg, ForeignAppTag, ForeignImportRequest, HostConfig, HostSecretError, HostSecrets, + PasswordOutcomeTag, QueryAvailabilityTag, ResolutionTag, SecretItemTag, SecretKindTag, +}; + +#[derive(Default)] +struct Vault { + stored: Mutex>, +} + +struct Shared(Arc); + +impl HostSecrets for Shared { + fn load(&self, id: String, kind: SecretKindTag) -> Result, HostSecretError> { + Ok(self + .0 + .stored + .lock() + .unwrap() + .get(&(id, kind)) + .cloned() + .map(SecretString::from)) + } + + fn store(&self, id: String, kind: SecretKindTag, secret: SecretString, _: String) -> Result<(), HostSecretError> { + self.0 + .stored + .lock() + .unwrap() + .insert((id, kind), secret.expose_secret().to_owned()); + Ok(()) + } + + fn relabel(&self, _: String, _: SecretKindTag, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete(&self, id: String, kind: SecretKindTag) -> Result<(), HostSecretError> { + self.0.stored.lock().unwrap().remove(&(id, kind)); + Ok(()) + } + + fn delete_connection(&self, id: String) -> Result<(), HostSecretError> { + self.0.stored.lock().unwrap().retain(|(stored, _), _| *stored != 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, vault: &Arc) -> Arc { + Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: Some(dir.join("storage").display().to_string()), + }, + Box::new(Shared(vault.clone())), + ) + .unwrap() +} + +fn dirs(home: &Path) -> ForeignAppDirsArg { + ForeignAppDirsArg { + home: home.display().to_string(), + config: home.join("config").display().to_string(), + data: home.join("data").display().to_string(), + } +} + +// Where DBeaver keeps its workspace on the platform the test runs on. +fn dbeaver_root(home: &Path) -> PathBuf { + if cfg!(target_os = "macos") { + home.join("Library") + } else if cfg!(windows) { + home.join("config") + } else { + home.join("data") + } +} + +// The importer's Windows fixture: one PostgreSQL connection whose password DBeaver encrypted, and a script bound to it. +fn dbeaver(home: &Path) { + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join( + "../foreign-import/tests/fixtures/dbeaver/windows/AppData/Roaming/DBeaverData/workspace6/General/.dbeaver", + ); + let project = dbeaver_root(home).join("DBeaverData/workspace6/General"); + let metadata = project.join(".dbeaver"); + fs::create_dir_all(&metadata).unwrap(); + for name in ["data-sources.json", "credentials-config.json"] { + fs::copy(fixture.join(name), metadata.join(name)).unwrap(); + } + fs::write( + metadata.join("project-metadata.json"), + r#"{"resources":{"Scripts/Report.sql":{"default-datasource":"windows"}}}"#, + ) + .unwrap(); + fs::create_dir_all(project.join("Scripts")).unwrap(); + fs::write(project.join("Scripts/Report.sql"), "select 42;").unwrap(); +} + +const EVERYTHING: ForeignImportRequest = ForeignImportRequest { + include_passwords: true, + include_saved_queries: true, +}; + +#[tokio::test] +async fn another_app_s_connection_lands_with_its_password_and_saved_query_once() { + let dir = tempfile::tempdir().unwrap(); + let vault = Arc::new(Vault::default()); + let core = core(dir.path(), &vault); + dbeaver(dir.path()); + + let sources = core.foreign_sources(dirs(dir.path())).await.unwrap(); + let review = core + .clone() + .read_foreign(ForeignAppTag::DBeaver, dirs(dir.path()), None, EVERYTHING, None) + .await + .unwrap(); + let rows = review.connections(); + let choices = review.choices(); + let outcome = review.apply().await.unwrap(); + let again = review.apply().await.err().unwrap(); + let library = core.library().unwrap().snapshot().await.unwrap(); + let saved = &library.connections[0]; + let queries = core + .history() + .await + .unwrap() + .saved_queries() + .snapshot(saved.id.clone()) + .await + .unwrap(); + + let source = sources + .iter() + .find(|source| source.app == ForeignAppTag::DBeaver) + .unwrap(); + assert!(source.available); + assert_eq!((source.connections, source.saved_queries), (1, 1)); + let navicat = sources + .iter() + .find(|source| source.app == ForeignAppTag::Navicat) + .unwrap(); + assert_eq!(navicat.file_extensions, ["ncx"]); + assert_eq!(review.passwords(), PasswordOutcomeTag::Read); + assert_eq!(rows[0].name, "Windows PG"); + assert_eq!(rows[0].connection.as_ref().unwrap().host, "windows.example.com"); + assert!(rows[0].carries_passwords && rows[0].duplicate.is_none()); + assert!(choices.connections[0].selected && choices.importable); + assert_eq!(choices.connections[0].resolution, Some(ResolutionTag::Add)); + assert_eq!(choices.queries[0].availability, QueryAvailabilityTag::Available); + assert!(choices.queries[0].included); + assert_eq!( + (outcome.connections, outcome.passwords_not_kept, outcome.queries_added), + (1, 0, 1) + ); + assert_eq!(again.code(), "foreign_import.applied"); + assert_eq!(library.connections.len(), 1); + assert_eq!(saved.name, "Windows PG"); + assert_eq!( + vault + .stored + .lock() + .unwrap() + .get(&(saved.id.clone(), SecretKindTag::DatabasePassword)) + .map(String::as_str), + Some("windows-pass") + ); + assert_eq!(queries.queries[0].name, "Report"); + assert_eq!(queries.queries[0].sql, "select 42;"); +} + +#[tokio::test] +async fn a_second_read_matches_the_saved_connection_and_keeps_it_for_the_queries() { + let dir = tempfile::tempdir().unwrap(); + let vault = Arc::new(Vault::default()); + let core = core(dir.path(), &vault); + dbeaver(dir.path()); + let read = || { + core.clone() + .read_foreign(ForeignAppTag::DBeaver, dirs(dir.path()), None, EVERYTHING, None) + }; + read().await.unwrap().apply().await.unwrap(); + let saved_id = core.library().unwrap().snapshot().await.unwrap().connections[0] + .id + .clone(); + + let review = read().await.unwrap(); + let before = review.choices(); + review.set_selected("windows".to_owned(), true); + let checked = review.choices(); + let outcome = review.apply().await.unwrap(); + let count = core.library().unwrap().snapshot().await.unwrap().connections.len(); + + assert_eq!(review.connections()[0].duplicate.as_ref().unwrap().id, saved_id); + assert!(!before.connections[0].selected && !before.importable); + assert_eq!( + checked.connections[0].offered, + [ + ResolutionTag::KeepExisting { id: saved_id.clone() }, + ResolutionTag::AddCopy, + ResolutionTag::Replace { id: saved_id.clone() }, + ] + ); + assert_eq!( + checked.connections[0].resolution, + Some(ResolutionTag::KeepExisting { id: saved_id }) + ); + assert_eq!((outcome.connections, outcome.queries_already_saved), (0, 1)); + assert_eq!(count, 1); +} + +#[tokio::test] +async fn a_library_that_changed_after_the_read_refuses_the_import() { + let dir = tempfile::tempdir().unwrap(); + let vault = Arc::new(Vault::default()); + let core = core(dir.path(), &vault); + dbeaver(dir.path()); + let first = core + .clone() + .read_foreign(ForeignAppTag::DBeaver, dirs(dir.path()), None, EVERYTHING, None) + .await + .unwrap(); + let late = core + .clone() + .read_foreign(ForeignAppTag::DBeaver, dirs(dir.path()), None, EVERYTHING, None) + .await + .unwrap(); + first.apply().await.unwrap(); + + let refused = late.apply().await.err().unwrap(); + let count = core.library().unwrap().snapshot().await.unwrap().connections.len(); + + assert_eq!(refused.code(), "storage.import_outdated"); + assert_eq!(count, 1); +} + +#[tokio::test] +async fn an_app_with_nothing_to_read_fails_with_its_code() { + let dir = tempfile::tempdir().unwrap(); + let vault = Arc::new(Vault::default()); + let core = core(dir.path(), &vault); + + let missing = core + .clone() + .read_foreign(ForeignAppTag::DBeaver, dirs(dir.path()), None, EVERYTHING, None) + .await + .err() + .unwrap(); + let unreadable = core + .clone() + .read_foreign( + ForeignAppTag::Navicat, + dirs(dir.path()), + Some(dir.path().join("none.ncx").display().to_string()), + EVERYTHING, + None, + ) + .await + .err() + .unwrap(); + + assert_eq!(missing.code(), "foreign_import.file_not_found"); + assert!( + unreadable.code().starts_with("foreign_import."), + "{}", + unreadable.code() + ); +} diff --git a/core/crates/ffi/tests/result_edits.rs b/core/crates/ffi/tests/result_edits.rs new file mode 100644 index 0000000000..a6296e5d05 --- /dev/null +++ b/core/crates/ffi/tests/result_edits.rs @@ -0,0 +1,301 @@ +#![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::{ + CellChange, CellEdit, Core, DatabaseSession, EditLock, FileOpenRequest, HostConfig, HostSecretError, HostSecrets, + ResultSet, RowEdit, RowSaveOutcome, RunListener, RunOutcome, RunSettings, 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(()) + } +} + +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 file(path: &Path, read_only: bool) -> FileOpenRequest { + FileOpenRequest { + path: path.display().to_string(), + driver_id: None, + read_only, + create: false, + } +} + +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 seeded(core: &Core, path: &Path) { + let create = FileOpenRequest { + create: true, + ..file(path, false) + }; + let session = core.open_file(create, None).await.unwrap(); + run( + &session, + "CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER, \ + joined TEXT DEFAULT 'today'); \ + INSERT INTO people (id, name, age) VALUES (1, 'Ada', 36), (2, 'Grace', 45), (3, 'Linus', 21); \ + CREATE TABLE notes (body TEXT)", + ) + .await; + session.close().await.unwrap(); +} + +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 text(value: &str) -> CellEdit { + CellEdit::Text { text: value.to_owned() } +} + +fn row(values: [Option<&str>; 4]) -> Vec> { + values.iter().map(|value| value.map(str::to_owned)).collect() +} + +async fn lock_of(session: &DatabaseSession, sql: &str) -> Option { + let set = run(session, sql).await.unwrap(); + session.result_editor(sql.to_owned(), set, None).await.unwrap().lock() +} + +#[tokio::test] +async fn a_result_of_one_keyed_table_saves_an_update_an_insert_and_a_delete() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let sql = "SELECT name, id, age FROM people WHERE age > 20 ORDER BY id"; + let shown = run(&session, sql).await.unwrap(); + let editor = session + .result_editor(sql.to_owned(), shown.clone(), None) + .await + .unwrap(); + let columns = editor.columns(); + let copies = editor.copies_exactly(shown.clone(), 0); + + let save = editor + .plan( + shown, + vec![ + RowEdit::Update { + row: 0, + cells: vec![CellChange { + column: 0, + edit: text("Ada Lovelace"), + }], + }, + RowEdit::Insert { + cells: vec![text("Edsger"), CellEdit::Default, CellEdit::Null], + }, + RowEdit::Delete { row: 2 }, + ], + ) + .unwrap(); + let statements = save.statements(); + let outcome = save.run(false, None).await.unwrap(); + let after = rows(&session).await; + session.close().await.unwrap(); + + assert_eq!(editor.lock(), None); + assert!(copies); + assert_eq!(editor.table().map(|table| table.name).as_deref(), Some("people")); + assert_eq!( + columns.iter().map(|column| column.name.as_str()).collect::>(), + ["name", "id", "age"] + ); + assert!(columns[0].editable && !columns[1].editable && columns[1].primary_key && columns[2].editable); + assert!(statements[0].sql.starts_with("UPDATE"), "{statements:?}"); + assert_eq!(statements[0].values, ["'Ada Lovelace'", "1"]); + assert!(statements[1].sql.starts_with("INSERT"), "{statements:?}"); + assert!(!statements[1].sql.contains("joined"), "{statements:?}"); + assert!(statements[2].sql.starts_with("DELETE"), "{statements:?}"); + assert_eq!(statements[2].values, ["3"]); + assert_eq!(outcome, RowSaveOutcome::Saved { rows: Some(3) }); + assert_eq!( + after, + [ + row([Some("1"), Some("Ada Lovelace"), Some("36"), Some("today")]), + row([Some("2"), Some("Grace"), Some("45"), Some("today")]), + row([Some("4"), Some("Edsger"), None, Some("today")]), + ] + ); +} + +#[tokio::test] +async fn a_second_copy_of_a_column_is_locked_and_left_out_of_every_statement() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let sql = "SELECT id, name, name AS again FROM people ORDER BY id"; + let shown = run(&session, sql).await.unwrap(); + let editor = session + .result_editor(sql.to_owned(), shown.clone(), None) + .await + .unwrap(); + let columns = editor.columns(); + let refused = editor.check(2, text("x"), false).err().unwrap(); + let save = editor + .plan( + shown, + vec![RowEdit::Insert { + cells: vec![CellEdit::Default, text("Edsger"), text("ignored")], + }], + ) + .unwrap(); + let statements = save.statements(); + session.close().await.unwrap(); + + assert_eq!(columns[2].name, "again"); + assert!(!columns[2].editable && !columns[2].editable_in_new_row); + assert_eq!(refused.code(), "edit.not_editable"); + assert_eq!(statements.len(), 1); + assert_eq!(statements[0].values, ["'Edsger'"], "{statements:?}"); +} + +#[tokio::test] +async fn a_result_that_is_not_one_keyed_table_s_rows_says_why() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + run(&session, "CREATE VIEW grown AS SELECT * FROM people WHERE age > 30").await; + + let joined = lock_of(&session, "SELECT * FROM people, notes").await; + let common = lock_of(&session, "WITH p AS (SELECT * FROM people) SELECT * FROM p").await; + let counted = lock_of(&session, "SELECT count(*) FROM people").await; + let computed = lock_of(&session, "SELECT id, upper(name) FROM people").await; + let keyless = lock_of(&session, "SELECT name FROM people").await; + let no_key = lock_of(&session, "SELECT body FROM notes").await; + let view = lock_of(&session, "SELECT * FROM grown").await; + let pragma = lock_of(&session, "PRAGMA table_info(people)").await; + session.close().await.unwrap(); + let read_only = core.open_file(file(&path, true), None).await.unwrap(); + let locked = lock_of(&read_only, "SELECT id, name FROM people").await; + read_only.close().await.unwrap(); + + assert_eq!(joined, Some(EditLock::MoreThanOneTable)); + assert_eq!(common, Some(EditLock::MoreThanOneTable)); + assert_eq!(counted, Some(EditLock::Collapsed)); + assert_eq!(computed, Some(EditLock::Collapsed)); + assert_eq!(keyless, Some(EditLock::KeyNotShown)); + assert_eq!(no_key, Some(EditLock::NoPrimaryKey)); + assert_eq!(view, Some(EditLock::Untraced)); + assert_eq!(pragma, Some(EditLock::NotOneSelect)); + assert_eq!(locked, Some(EditLock::ReadOnlyConnection)); +} + +#[tokio::test] +async fn a_locked_result_names_no_table() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let sql = "SELECT count(*) FROM people"; + let set = run(&session, sql).await.unwrap(); + let editor = session.result_editor(sql.to_owned(), set, None).await.unwrap(); + session.close().await.unwrap(); + + assert_eq!(editor.table(), None); +} + +#[tokio::test] +async fn edits_name_rows_of_the_editor_s_own_result_sorted_or_not() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("people.sqlite"); + let core = core(dir.path()); + seeded(&core, &path).await; + let session = core.open_file(file(&path, false), None).await.unwrap(); + let sql = "SELECT id, name FROM people"; + let shown = run(&session, sql).await.unwrap(); + let editor = session + .result_editor(sql.to_owned(), shown.clone(), None) + .await + .unwrap(); + let sorted = shown.sorted(1, false).unwrap(); + let again = run(&session, sql).await.unwrap(); + let other = run(&session, "SELECT id, age FROM people").await.unwrap(); + let sorted_lock = editor.lock_for(sorted.clone()); + let again_lock = editor.lock_for(again.clone()); + let other_lock = editor.lock_for(other.clone()); + let refused = editor.plan(again, vec![RowEdit::Delete { row: 0 }]).err().unwrap(); + let save = editor.plan(sorted, vec![RowEdit::Delete { row: 0 }]).unwrap(); + let statements = save.statements(); + session.close().await.unwrap(); + + assert_eq!(sorted_lock, None); + assert_eq!(again_lock, Some(EditLock::ColumnsChanged)); + assert_eq!(other_lock, Some(EditLock::ColumnsChanged)); + assert_eq!(refused.code(), "edit.columns_changed"); + // Linus sorts first by name, descending. + assert_eq!(statements[0].values, ["3"]); +} diff --git a/core/crates/foreign-import/src/app.rs b/core/crates/foreign-import/src/app.rs index 96530e550d..3cd450feb4 100644 --- a/core/crates/foreign-import/src/app.rs +++ b/core/crates/foreign-import/src/app.rs @@ -203,7 +203,11 @@ impl ForeignImporter { ForeignApp::TablePlus => Box::new(apps::tableplus::TablePlus::locate(&self.dirs, keychain)), ForeignApp::SequelAce => Box::new(apps::sequel_ace::SequelAce::locate(&self.dirs, keychain)), ForeignApp::DBeaver => Box::new(apps::dbeaver::DBeaver::locate(&self.dirs)), - ForeignApp::DataGrip => Box::new(apps::datagrip::DataGrip::locate(&self.dirs, keychain)), + ForeignApp::DataGrip => Box::new(apps::datagrip::DataGrip::locate( + &self.dirs, + keychain, + self.host.data_protection(), + )), ForeignApp::BeekeeperStudio => Box::new(apps::beekeeper::Beekeeper::locate(&self.dirs)), ForeignApp::Navicat => Box::new(apps::navicat::Navicat::new(self.picked_file.clone())), ForeignApp::Dbx => Box::new(apps::dbx::Dbx::locate(&self.dirs)), diff --git a/core/crates/foreign-import/src/apps/datagrip/mod.rs b/core/crates/foreign-import/src/apps/datagrip/mod.rs index 778abc03fe..67b38690cc 100644 --- a/core/crates/foreign-import/src/apps/datagrip/mod.rs +++ b/core/crates/foreign-import/src/apps/datagrip/mod.rs @@ -16,9 +16,9 @@ use crate::apps::jetbrains::{CredentialStore, Lookup}; use crate::apps::{jdbc, resolve_key_path}; use crate::collect::{PasswordOutcome, assemble}; use crate::{ - CollectedImport, ForeignApp, ForeignAppDirs, ForeignConnection, ForeignConnectionRecord, ForeignCredentials, - ForeignImportError, ForeignKeychain, ForeignPlatform, ForeignSsh, ForeignSshAuth, ForeignSsl, ForeignSslMode, - ImportRequest, Inventory, engine, + CollectedImport, DataProtection, ForeignApp, ForeignAppDirs, ForeignConnection, ForeignConnectionRecord, + ForeignCredentials, ForeignImportError, ForeignKeychain, ForeignPlatform, ForeignSsh, ForeignSshAuth, ForeignSsl, + ForeignSslMode, ImportRequest, Inventory, engine, }; pub(crate) struct DataGrip { @@ -26,6 +26,7 @@ pub(crate) struct DataGrip { home: PathBuf, platform: ForeignPlatform, keychain: Option>, + protection: Option>, } struct ScannedSource { @@ -51,21 +52,28 @@ impl DataGrip { home: PathBuf, platform: ForeignPlatform, keychain: Option>, + protection: Option>, ) -> Self { Self { roots, home, platform, keychain, + protection, } } - pub(crate) fn locate(dirs: &ForeignAppDirs, keychain: Option>) -> Self { + pub(crate) fn locate( + dirs: &ForeignAppDirs, + keychain: Option>, + protection: Option>, + ) -> Self { Self::new( locations::jetbrains_roots(dirs), dirs.home.clone(), dirs.platform, keychain, + protection, ) } @@ -126,6 +134,7 @@ impl DataGrip { fn credential_store(&self, config_dir: &Path) -> CredentialStore { CredentialStore::new(config_dir.to_path_buf(), self.platform, self.keychain.clone()) + .with_data_protection(self.protection.clone()) } fn password_outcome( diff --git a/core/crates/foreign-import/src/apps/jetbrains/credential_store.rs b/core/crates/foreign-import/src/apps/jetbrains/credential_store.rs index 7208221de9..d0ab3aff19 100644 --- a/core/crates/foreign-import/src/apps/jetbrains/credential_store.rs +++ b/core/crates/foreign-import/src/apps/jetbrains/credential_store.rs @@ -16,7 +16,7 @@ use base64::engine::general_purpose::STANDARD; use secrecy::{ExposeSecret, SecretString}; use super::kdbx::{self, KdbxEntry}; -use crate::{ForeignKeychain, ForeignPlatform, KeychainRead}; +use crate::{DataProtection, ForeignKeychain, ForeignPlatform, KeychainRead}; const BUILT_IN_KEY: &[u8; 16] = b"Proxy Config Sec"; const BUILT_IN: &str = "BUILT_IN"; @@ -26,7 +26,7 @@ const CRYPT_32: &str = "CRYPT_32"; pub(crate) enum Lookup { Found(SecretString), NotFound, - // The user refused the keychain, or the KeePass main key is one this platform cannot open. + // The user refused the keychain, or the KeePass main key is one this host cannot open. Stopped, } @@ -40,6 +40,7 @@ pub(crate) struct CredentialStore { config_dir: PathBuf, platform: ForeignPlatform, keychain: Option>, + protection: Option>, entries: Option>, loaded: bool, locked: bool, @@ -55,12 +56,19 @@ impl CredentialStore { config_dir, platform, keychain, + protection: None, entries: None, loaded: false, locked: false, } } + // A CRYPT_32 main key opens only through the user's data protection; without it the lookups stop. + #[must_use] + pub(crate) fn with_data_protection(self, protection: Option>) -> Self { + Self { protection, ..self } + } + pub(crate) fn service_name(uuid: &str) -> String { format!("IntelliJ Platform DB \u{2014} {uuid}") } @@ -143,12 +151,12 @@ impl CredentialStore { let main_key = match crate::files::read_capped(self.config_dir.join("c.pwd")) { Ok(data) => { let (encryption, blob) = parse_main_key_file(std::str::from_utf8(&data).ok()?)?; - decrypt_main_key(&encryption, &blob) + decrypt_main_key(&encryption, &blob, self.protection.as_deref()) } // The IDE reads the older `pdb.pwd`, raw bytes rather than YAML, only when `c.pwd` is missing. Err(error) if error.kind() == ErrorKind::NotFound => { let blob = crate::files::read_capped(self.config_dir.join("pdb.pwd")).ok()?; - decrypt_main_key(legacy_encryption(self.platform), &blob) + decrypt_main_key(legacy_encryption(self.platform), &blob, self.protection.as_deref()) } Err(_) => return None, }; @@ -172,11 +180,20 @@ fn legacy_encryption(platform: ForeignPlatform) -> &'static str { } // Every main key is decrypted here. CRYPT_32 is BUILT_IN wrapped in the Windows data protection API. -fn decrypt_main_key(encryption: &str, blob: &[u8]) -> MainKey { - if encryption != BUILT_IN { - return MainKey::Locked; - } - decrypt_built_in(blob).map_or(MainKey::Unreadable, MainKey::Key) +fn decrypt_main_key(encryption: &str, blob: &[u8], protection: Option<&dyn DataProtection>) -> MainKey { + let unsealed; + let built_in = match encryption { + BUILT_IN => blob, + CRYPT_32 => match protection.and_then(|protection| protection.unprotect(blob)) { + Some(inner) => { + unsealed = inner; + &unsealed + } + None => return MainKey::Locked, + }, + _ => return MainKey::Locked, + }; + decrypt_built_in(built_in).map_or(MainKey::Unreadable, MainKey::Key) } fn decrypt_built_in(blob: &[u8]) -> Option> { @@ -277,6 +294,26 @@ mod tests { CredentialStore::new(dir.to_path_buf(), platform, None) } + const SEAL: &[u8] = b"sealed for this user:"; + + // Stands in for DPAPI: a blob opens when it carries this user's seal. + struct Sealed; + + impl DataProtection for Sealed { + fn unprotect(&self, blob: &[u8]) -> Option> { + blob.strip_prefix(SEAL).map(<[u8]>::to_vec) + } + } + + fn sealed(blob: &[u8]) -> Vec { + [SEAL, blob].concat() + } + + fn protected_store(dir: &Path) -> CredentialStore { + CredentialStore::new(dir.to_path_buf(), ForeignPlatform::Windows, None) + .with_data_protection(Some(Arc::new(Sealed))) + } + fn found(lookup: Lookup) -> String { match lookup { Lookup::Found(value) => value.expose_secret().to_owned(), @@ -373,6 +410,55 @@ mod tests { )); } + #[test] + fn a_crypt_32_main_key_opens_through_the_users_data_protection() { + let dir = tempfile::tempdir().expect("a temp dir"); + let main_key = test_kdbx::bytes("main key", 64); + write_kdbx( + dir.path(), + &main_key, + &CredentialStore::service_name("u"), + "dpapi-secret", + ); + let blob = STANDARD.encode(sealed(&test_kdbx::built_in_blob(&main_key))); + fs::write( + dir.path().join("c.pwd"), + format!("encryption: CRYPT_32\nisAutoGenerated: true\nvalue: !!binary {blob}\n"), + ) + .expect("c.pwd"); + let mut store = protected_store(dir.path()); + assert_eq!(found(store.password("u")), "dpapi-secret"); + assert!(store.kdbx_loaded()); + } + + #[test] + fn a_crypt_32_main_key_another_user_sealed_stops_the_lookups() { + let dir = tempfile::tempdir().expect("a temp dir"); + let main_key = test_kdbx::bytes("main key", 64); + write_kdbx(dir.path(), &main_key, &CredentialStore::service_name("u"), "p"); + let blob = STANDARD.encode(test_kdbx::built_in_blob(&main_key)); + fs::write( + dir.path().join("c.pwd"), + format!("encryption: CRYPT_32\nisAutoGenerated: true\nvalue: !!binary {blob}\n"), + ) + .expect("c.pwd"); + assert!(matches!(protected_store(dir.path()).password("u"), Lookup::Stopped)); + } + + #[test] + fn a_pdb_pwd_on_windows_opens_through_the_users_data_protection() { + let dir = tempfile::tempdir().expect("a temp dir"); + let main_key = test_kdbx::bytes("legacy main key", 64); + write_kdbx( + dir.path(), + &main_key, + &CredentialStore::service_name("old"), + "legacy-secret", + ); + fs::write(dir.path().join("pdb.pwd"), sealed(&test_kdbx::built_in_blob(&main_key))).expect("pdb.pwd"); + assert_eq!(found(protected_store(dir.path()).password("old")), "legacy-secret"); + } + #[test] fn a_raw_pdb_pwd_is_read_when_c_pwd_is_missing() { let dir = tempfile::tempdir().expect("a temp dir"); diff --git a/core/crates/foreign-import/src/host.rs b/core/crates/foreign-import/src/host.rs index 48472427fc..b21348d748 100644 --- a/core/crates/foreign-import/src/host.rs +++ b/core/crates/foreign-import/src/host.rs @@ -18,6 +18,12 @@ pub trait ForeignKeychain: Send + Sync { fn read_password(&self, service: &str, account: Option<&str>) -> KeychainRead; } +// Windows' data protection API, which seals a blob to the signed-in user: another app's key sealed with it opens only +// for that user on that machine. +pub trait DataProtection: Send + Sync { + fn unprotect(&self, blob: &[u8]) -> Option>; +} + pub trait ForeignHost: Send + Sync { // `None` when the platform cannot tell, so an app counts as there when its files are. fn installed(&self, _app: ForeignApp) -> Option { @@ -27,9 +33,13 @@ pub trait ForeignHost: Send + Sync { fn keychain(&self) -> Option> { None } + + fn data_protection(&self) -> Option> { + None + } } -// Linux and Windows: no installed-app lookup and no other app's keychain. +// No installed-app lookup, no other app's keychain and no data protection. #[derive(Debug, Clone, Copy, Default)] pub struct PlainHost; diff --git a/core/crates/foreign-import/src/lib.rs b/core/crates/foreign-import/src/lib.rs index c07acd0300..d420b4a72e 100644 --- a/core/crates/foreign-import/src/lib.rs +++ b/core/crates/foreign-import/src/lib.rs @@ -17,7 +17,7 @@ pub use app::{ForeignApp, ForeignImporter, ImportRequest, Inventory, PasswordSou pub use collect::{CollectedConnection, CollectedImport, CollectedSavedQuery, PasswordOutcome}; pub use dirs::{ForeignAppDirs, ForeignPlatform}; pub use error::ForeignImportError; -pub use host::{ForeignHost, ForeignKeychain, KeychainRead, PlainHost}; +pub use host::{DataProtection, ForeignHost, ForeignKeychain, KeychainRead, PlainHost}; pub use record::{ ForeignColor, ForeignConnection, ForeignConnectionRecord, ForeignCredentials, ForeignJumpHost, ForeignSavedQuery, ForeignSsh, ForeignSshAuth, ForeignSsl, ForeignSslMode, SavedQueryContent, TLS_SETTINGS_UNREAD, diff --git a/core/docs/decisions/0008-importers-from-other-apps.md b/core/docs/decisions/0008-importers-from-other-apps.md index 040f4d5652..10f6af604e 100644 --- a/core/docs/decisions/0008-importers-from-other-apps.md +++ b/core/docs/decisions/0008-importers-from-other-apps.md @@ -1,6 +1,6 @@ # 0008: Importers from other apps live in the core -- **Status**: Accepted +- **Status**: Accepted; the Windows host and the FFI surface amended by 0032 - **Date**: 2026-11-03 ## Context diff --git a/core/docs/decisions/0019-row-edits-through-the-ffi.md b/core/docs/decisions/0019-row-edits-through-the-ffi.md index 32185689f7..2547dbf4f3 100644 --- a/core/docs/decisions/0019-row-edits-through-the-ffi.md +++ b/core/docs/decisions/0019-row-edits-through-the-ffi.md @@ -1,6 +1,6 @@ # 0019: A table tab's row edits cross the FFI as typed text, and the core plans and runs the save -- **Status**: Accepted +- **Status**: Accepted; query results amended by 0032 - **Date**: 2026-11-11 ## Context diff --git a/core/docs/decisions/0032-foreign-import-and-result-editing-through-the-ffi.md b/core/docs/decisions/0032-foreign-import-and-result-editing-through-the-ffi.md new file mode 100644 index 0000000000..81cebc495e --- /dev/null +++ b/core/docs/decisions/0032-foreign-import-and-result-editing-through-the-ffi.md @@ -0,0 +1,41 @@ +# 0032: Importing from other apps and editing a query result cross the FFI + +- **Status**: Accepted +- **Date**: 2026-11-18 + +## Context + +The importers ([0008](0008-importers-from-other-apps.md)) and the rules for editing a query result ([0015](0015-editing-a-query-result.md)) were core code the FFI did not expose, so the Windows app could import only TablePro's own file and edit only a table tab ([0019](0019-row-edits-through-the-ffi.md)). DataGrip on Windows keeps its passwords in a KeePass file whose main key is sealed with DPAPI (`CRYPT_32`), which the core read as locked. + +## Decision + +### Importing + +- `ForeignHost::data_protection` hands the importers the platform's data protection. The JetBrains store unseals a `CRYPT_32` main key through it, then reads it as `BUILT_IN`; with none, or a blob another user sealed, the lookups stop and the review says so (`PasswordOutcome::Stopped`). +- The FFI's Windows host passes `CryptUnprotectData` with no entropy and no prompt, as IntelliJ seals the key. It reads no other app's Credential Manager items and reports no installed apps. +- `Core::foreign_sources` lists the platform's apps with their counts, read from files only. `Core::read_foreign` reads one app, or a Navicat export the user picked, and analyzes it against the library as it is then. The app passes the home, config and data folders (`ForeignAppDirsArg`). +- `ForeignImportReview` holds the review and the user's checks. `choices()` works the plan out again after each `set_selected`, `resolve` or `set_included`, so a Replace another row took is withdrawn and a query follows its connection. +- `apply()` runs once, under the library's write lock: `apply_blocking`, each imported password into the core's secret store under the new id, then the saved queries into the history's store, leaving a name the connection already holds alone. A library changed since the read refuses with `storage.import_outdated` and writes nothing, and the review can apply again after a refusal. + +### Editing a query result + +- `DatabaseSession::result_editor(sql, rows)` gives a `TableEditor` over a run's result set. A read-only connection, a statement `edit::result_source` refuses and a result `edit::result_target` refuses each give an editor locked with the reason, as new `EditLock` variants: `NotOneSelect`, `MoreThanOneTable`, `Collapsed`, `Untraced`, `KeyNotShown`, and `NoPrimaryKey` and `ColumnsChanged` as before. +- The table's columns are read again from the server first, so a result read before the table changed locks rather than writes by an old place. +- The editor has one column per result column. A traced column is the catalog's; a second copy of a column and an untraced one are generated columns with a name no statement can hold, so they are locked to typing, left out of an insert and never named by an update. The key is read from the result's own columns, through `value_for_column`. +- `copies_exactly(rows, row)` says whether a row's copied values read back as the catalog's types, so an app refuses a duplicate that would write PostgreSQL's server text for a float, a time or money, as 0015 asks. A table page's values are typed, so its rows always copy. +- Planning, the Safe Mode gate and the save are the table tab's: `plan_save` over the traced table, planned again on the writing lease. Edits name rows of the editor's own result set, sorted or not: rows of any other set, the same statement run again included, refuse with `edit.columns_changed`. + +## Rationale + +- One editor type keeps one save path: a query result writes nothing a table tab would not, as 0015 asks. +- The app keeps what only it knows: a run with several results, a transaction left open, a tab in another database than the session's. It refuses those before it asks the core. + +## Consequences + +- DBX keeps its key in the system keyring on Windows as well, under its own scheme; its passwords stay behind until an importer reads that scheme on every platform. +- An insert from a query result leaves out every column the result does not show, so the server fills them. + +## Alternatives considered + +- **A separate result editor type.** A second copy of the key reading, the plan and the save. +- **Reading other apps' Credential Manager items.** No importer keeps a password there that the core could decrypt today. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index 99dba4484f..7c9e7b8f8d 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -15,7 +15,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0005](0005-sql-server-transport.md) | SQL Server on tiberius everywhere, with Kerberos added and ODBC as a Windows option | Accepted | tiberius on every platform with SSPI Negotiate added in a fork, Entra ID tokens from the core, and an optional Windows connection type over an installed ODBC Driver 18 for Always Encrypted; msodbcsql18 is never bundled. | | [0006](0006-connection-library.md) | The connection library holds a group tree, manual order and favourites | Accepted; how the Linux app shows groups superseded by linux 0032, the version 2 upgrade by linux 0033 | Groups form a tree by id, connections and groups carry an explicit order, favourites are one ordered list; version 2 group names become top-level groups. | | [0007](0007-sorting-a-result.md) | A sort names its column by name or position, else the core sorts the rows held | Accepted | `sort_reference` names a unique plain column, else its position on PostgreSQL, SQLite, SQL Server and DuckDB; otherwise, and for a statement that cannot run again, `value::order` sorts the rows held, which `ResultSet::sorted` gives the FFI as a view. | -| [0008](0008-importers-from-other-apps.md) | Importers from other apps live in the core | Accepted | One crate reads each app's files on every platform into one record shape, takes keychains and directories from the app, says what it cannot carry, and reviews the result against the library with the macOS duplicate handling. | +| [0008](0008-importers-from-other-apps.md) | Importers from other apps live in the core | Accepted; the Windows host and the FFI surface amended by 0032 | One crate reads each app's files on every platform into one record shape, takes keychains and directories from the app, says what it cannot carry, and reviews the result against the library with the macOS duplicate handling. | | [0009](0009-in-process-ssh-on-windows.md) | SSH on Windows runs in process on russh | Accepted | russh behind `tablepro-ssh`'s `in-process` feature, on every target; Windows uses it, Linux keeps OpenSSH. Forwards are channels with no address, so MySQL and MongoDB relay them through a private listener that serves only this process. | | [0010](0010-macos-on-the-core.md) | The macOS app moves to the core in slices, starting with the connection library | Accepted | UniFFI Swift bindings in an XCFramework of the static library, without the engines, at the app's deployment target; UI, Keychain and the CloudKit transport stay Swift; the core maps the library's CloudKit records both ways with the existing fields and merges a pull field by field. | | [0011](0011-sql-dump-and-import-in-process.md) | SQL dumps and SQL file imports run in process | Accepted; the import of COPY rows as INSERTs superseded by 0024 | Export Database writes one `.sql` file from each driver's catalog read in `pg_dump` and `mysqldump` order, and Import SQL File splits a file of any size as the engine's client does and runs it on an editor session; no app calls `pg_dump` or `mysqldump`. | @@ -26,7 +26,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [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; 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. | +| [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; query results amended by 0032 | `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. | | [0021](0021-an-int32-keeps-its-width.md) | An int32 keeps its width, and an edited number keeps its type | Accepted | `Value::Int32` holds MongoDB's int32, equal to the `Int` of the same number; a save carries each edited cell's read value, and a number binds in the read's BSON type when it is exactly one, else the column's. | | [0022](0022-browsing-through-the-ffi.md) | A table page is read on the session with its filter bound, and structure, definitions, export and history cross the FFI | Accepted | `read_table_page` builds the page with the filter, binds its values and reads it with `read_page` on a pooled connection as run events; `table_structure`, `object_definition`, `export_rows`, `export_table` and `Core::history` give the Linux app's reads to an app on the FFI. | @@ -39,3 +39,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [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. | | [0031](0031-duckdb-expression-depth.md) | DuckDB's expression depth fits the stacks it runs on | Accepted | Every DuckDB open of a user's file sets `max_expression_depth` to 250, which fits the 512 KiB DuckDB gives its own threads on macOS, past which DuckDB refuses the statement; the core runs each DuckDB call and the close on an 8 MiB thread, and the Swift apps run their DuckDB actor on one. | +| [0032](0032-foreign-import-and-result-editing-through-the-ffi.md) | Importing from other apps and editing a query result cross the FFI | Accepted | `ForeignHost::data_protection` opens DataGrip's DPAPI-sealed KeePass key on Windows; `Core::read_foreign` gives a `ForeignImportReview` whose `apply` writes connections, passwords into the core's secret store and saved queries once under the library's lock; `DatabaseSession::result_editor` gives a `TableEditor` over a query result with one column per result column and a lock that says why when 0015 refuses it. | diff --git a/windows/AGENTS.md b/windows/AGENTS.md index 9a20d58802..cccfb8c75a 100644 --- a/windows/AGENTS.md +++ b/windows/AGENTS.md @@ -47,6 +47,8 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `DatabaseSession.CatalogAbilities` says what the engine does to whole tables, schemas and databases, and `PlanCatalogChange` gives a `CatalogChange` with its statements and Safe Mode gate, which `RunAsync` runs once; `RefreshSchemasAsync` reads the schemas again. `ExportRowsAsync` and `ExportTableAsync` report the rows written to an `IProgress` (`docs/decisions/0012-catalog-operations-table-filters-and-export-progress.md`). - `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`). +- A query result edits through `DatabaseSession.OpenResultEditorAsync(sql, rows)`, the same `TableEditor` with one column per result column; its `Lock` says why a result is not one keyed table's rows. The app refuses a run with several results, an open or unknown transaction and a tab in another database before it asks (`core/docs/decisions/0032-foreign-import-and-result-editing-through-the-ffi.md`). +- `TableProCore.GetForeignSourcesAsync` lists the other apps found under `ForeignAppDirs.ForCurrentUser()`, `ReadForeignAsync` gives a `ForeignImportReview` whose `Choices()` follow each check, and `ApplyAsync` writes the connections, their passwords into Credential Manager and the saved queries once; DataGrip's KeePass key opens with the user's DPAPI (core 0032). - `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. - The app starts the core with `TableProCore.CreateWithSystemSecrets`, so the core keeps secrets in Credential Manager itself. `ISecretStore` is for tests and hosts with a store of their own; the core calls it on a thread of its own. diff --git a/windows/docs/decisions/0006-editing-table-rows.md b/windows/docs/decisions/0006-editing-table-rows.md index 40ec03334a..aed2032806 100644 --- a/windows/docs/decisions/0006-editing-table-rows.md +++ b/windows/docs/decisions/0006-editing-table-rows.md @@ -1,6 +1,6 @@ # 0006: Editing a table's rows -- **Status**: Accepted +- **Status**: Accepted; query results amended by 0014 - **Date**: 2026-11-11 ## Context diff --git a/windows/docs/decisions/0014-foreign-import-and-query-result-editing.md b/windows/docs/decisions/0014-foreign-import-and-query-result-editing.md new file mode 100644 index 0000000000..c6227e5d20 --- /dev/null +++ b/windows/docs/decisions/0014-foreign-import-and-query-result-editing.md @@ -0,0 +1,37 @@ +# 0014: Importing from other apps and editing a query result + +- **Status**: Accepted +- **Date**: 2026-11-18 + +## Context + +The Windows app imported only TablePro's own connections file, and only a table tab edited its rows ([0006](0006-editing-table-rows.md)). The macOS app imports connections and saved queries from six other clients and edits a query result that reads one keyed table. The core now carries both through the FFI ([core 0032](../../../core/docs/decisions/0032-foreign-import-and-result-editing-through-the-ffi.md)). + +## Decision + +Each works as the macOS app's does, in Windows sentence case, over the core's review and editor. The logic sits in `src/TablePro.App.Model` with fakes in `tests/TablePro.App.Model.Tests`; the views lay out and ask. + +### Import from another app + +- The Connections page's Import button and the File menu offer Import from file... (TablePro's own file, as before) and Import from another app.... +- A ContentDialog lists the apps Windows has, each with what was found or "Not found on this PC"; Navicat imports an `.ncx` export picked with the system open picker. Passwords and saved queries are options, each offered where the app keeps them somewhere TablePro can read on Windows: decrypted from the app's own files, or DataGrip's KeePass file, whose main key opens with the user's DPAPI. +- The review lists every connection with a check box, what it connects to, its group, the saved connection it matches, and every note the core makes about it. A match starts unchecked and offers Add as copy, Replace when both connect the same way, and Keep existing, add queries when the row brings saved queries. Saved queries follow their connection and say why one cannot import. A bar says when passwords stayed behind. +- Import writes once: the connections, their passwords into Credential Manager, then the saved queries. The Connections page then says what landed. A library changed meanwhile refuses and asks to import again. + +### Editing a query result + +- A query tab's result edits as a table tab's page does, with the same commands, marks and questions, when the run returned one result set, left no transaction open, ran in the session's own database, and the core proves the result is one keyed table's rows. Otherwise the grid stays read only and trying to edit says why. +- Duplicate refuses a row whose values were read as text that may not name them exactly, as PostgreSQL's for a float, and says so. +- Save writes through the table tab's path, then runs the statement again for what the table holds; the run is not added to the history. A save whose outcome is unknown holds Save back until the changes are discarded, which runs the statement again. +- Save changes, Discard changes and Preview SQL show in the query tab's command bar while its result edits, and the menus' Save, Discard changes, Preview SQL, Add row, Duplicate row and Delete act on it as on a table tab. Ctrl+S in the result grid saves the rows, never the file. +- A new run, a sort, another database or Commit and Roll back ask before they replace rows with pending changes, and closing the tab asks Save, Don't save or Cancel. A switch of database ends the edits, since the statement would be read again elsewhere. + +## Rationale + +- The core plans every import and every save, so Windows keeps no importer, no SQL and no second copy of the edit rules. +- Stock WinUI controls: ContentDialog, RadioButtons, CheckBox, ComboBox, ListView, InfoBar, ProgressRing and the Windows App SDK's FileOpenPicker. + +## Consequences + +- DBX's passwords stay behind on Windows, as on every platform, until the core reads its key. +- Pending changes in a query result are not kept in the session file: the rows are gone after a relaunch, unlike a table tab's page. diff --git a/windows/docs/decisions/README.md b/windows/docs/decisions/README.md index 1786efcae4..85d3e1dab3 100644 --- a/windows/docs/decisions/README.md +++ b/windows/docs/decisions/README.md @@ -13,7 +13,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0003](0003-data-grid-control.md) | TablePro's own data grid control | Accepted; column order amended by 0013 | A WinUI 3 control that edits cells in place: ItemsRepeater rows that draw their visible cells with DirectWrite into composition surfaces through the editor's drawing layer, cells as UIA peers with no element, data read from the core in windows of cells with the host's pending changes laid over them. | | [0004](0004-app-shell.md) | The app shell | Accepted; packaging amended by 0005, table reads by 0007 | One window with the TitleBar, a MenuBar and a NavigationView rail of open connections, each with its own TabView; the Connections page, an owned connection form window, Settings as a page; the core keeps connections and Credential Manager secrets, the app its settings and session in LocalState. | | [0005](0005-distribution.md) | Shipping the app | Accepted | One self-contained Native AOT MSIX per architecture in an `.msixbundle` signed with Azure Artifact Signing, on GitHub Releases and winget; the core on the hybrid CRT; the 1809 floor checked in the package and on Windows Server 2022. | -| [0006](0006-editing-table-rows.md) | Editing a table's rows | Accepted | A table tab edits as the macOS app does: F2, Enter or a double-click edits a cell, rows are added, duplicated and deleted, every change stays pending until Save, reloads and closes ask first, Safe Mode's Confirm writes shows the statements, and the core plans and runs the save (core 0019). | +| [0006](0006-editing-table-rows.md) | Editing a table's rows | Accepted; query results amended by 0014 | A table tab edits as the macOS app does: F2, Enter or a double-click edits a cell, rows are added, duplicated and deleted, every change stays pending until Save, reloads and closes ask first, Safe Mode's Confirm writes shows the statements, and the core plans and runs the save (core 0019). | | [0007](0007-browsing-a-connection.md) | Filtering, structure, definitions, export and query history | Accepted; amended by 0012 | A table tab has Data and Structure and a filter bar over the core's bound page read; functions, procedures, triggers and sequences open their source read only; Export results writes through the core's encoders; Show query history lists the runs the core recorded. | | [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). | @@ -21,3 +21,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [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. | | [0012](0012-catalog-operations-table-filters-and-export-progress.md) | Catalog operations, filters kept per table, filter by a cell and export progress | Accepted | Truncate and Drop in the tree, New and Drop schema and database, each showing the core's statements under Safe Mode; a table's last filter comes back when it opens again; a cell's Filter menu; SQL INSERT of a query result and a running row count while an export writes. | | [0013](0013-row-details-column-layout-and-selection-summary.md) | Row details, table info, column layout, selection summary and connection URLs | Accepted | A Details pane with the focused row's fields edited in place and the table's size and comment; column order, hidden and frozen columns kept per table; Sum, Average and Count of the selected cells; New from URL and Ctrl+V on the Connections page; jump hosts in the SSH section; a group's colour. | +| [0014](0014-foreign-import-and-query-result-editing.md) | Importing from other apps and editing a query result | Accepted | Import from another app... on the Connections page and the File menu reads TablePlus, DBeaver, DataGrip, Beekeeper Studio, Navicat's export and DBX through the core's review, with a check, a resolution and the notes per row, passwords into Credential Manager; a query result that is one keyed table's rows edits as a table tab's page, refused with its reason otherwise, and runs again after a save. | diff --git a/windows/src/TablePro.App.Model/EditedRows.cs b/windows/src/TablePro.App.Model/EditedRows.cs new file mode 100644 index 0000000000..f8174c7cef --- /dev/null +++ b/windows/src/TablePro.App.Model/EditedRows.cs @@ -0,0 +1,236 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// What was typed per row of one set and the editor that reads and saves it: a table tab's page, a query tab's result. +internal sealed class EditedRows(ITableEditor editor, TableEdits edits, ResultSet? source) +{ + // The refusals the core makes before it sends anything, so a save after one cannot write twice. + private static readonly HashSet NothingSent = new(StringComparer.Ordinal) + { + "edit.not_confirmed", + "edit.safe_mode_changed", + "edit.not_as_planned", + "edit.already_saved", + "edit.read_only_connection", + "ffi.not_connected", + }; + + public ITableEditor Editor => editor; + + public TableEdits Edits => edits; + + // The set the edits name rows of, which the core reads each key and stored value from. + public ResultSet? Source => source; + + // A new row's editor opens on the first column the server does not fill. + public static int FirstColumnToFill(IReadOnlyList columns) + { + ArgumentNullException.ThrowIfNull(columns); + for (var column = 0; column < columns.Count; column++) + { + if (columns[column] is { EditableInNewRow: true, NewRow: not CellEdit.ServerDefault }) + { + return column; + } + } + + return 0; + } + + public static EditRefusal? CellRefusal(TableEdits edits, int row, int column) + { + ArgumentNullException.ThrowIfNull(edits); + if (row < 0 || row >= edits.RowCount || column < 0 || column >= edits.Columns.Count) + { + return EditRefusal.CellLocked.Instance; + } + + if (edits.IsDeleted(row)) + { + return EditRefusal.RowDeleted.Instance; + } + + // A saved row's key stays as it is; a new row leaves to the server what it fills. + var info = edits.Columns[column]; + return (edits.IsAdded(row) ? info.EditableInNewRow : info.Editable) ? null : EditRefusal.CellLocked.Instance; + } + + // As the core says the column takes each; in a new row, Default is where the server fills the column. + public static bool CanSetValue(TableEdits edits, int row, int column, CellValueKind kind) + { + if (CellRefusal(edits, row, column) is not null) + { + return false; + } + + var info = edits.Columns[column]; + return kind switch + { + CellValueKind.Empty => info.TakesEmpty, + CellValueKind.Null => info.Nullable, + _ => edits.IsAdded(row) ? info.NewRow is CellEdit.ServerDefault : info.TakesDefault, + }; + } + + // Any failure but one the core makes before it sends anything may follow the batch, so it is an unknown outcome. + public static async Task<(RowSaveOutcome? Outcome, CoreError? Failure)> RunSaveAsync(IRowSave save, bool confirmed) + { + ArgumentNullException.ThrowIfNull(save); + try + { + return (await save.RunAsync(confirmed, CancellationToken.None).ConfigureAwait(true), null); + } + catch (TableProException exception) when (exception.Error.Codes.Any(NothingSent.Contains)) + { + return (null, exception.Error); + } + catch (TableProException exception) + { + return (new RowSaveOutcome.Unknown(exception.Error, null), null); + } + } + + // The grid row of the change the engine said the save stopped at. + public static int? RowOf(PlannedEdits planned, int? edit) + { + ArgumentNullException.ThrowIfNull(planned); + return edit is { } index && index >= 0 && index < planned.Rows.Count ? planned.Rows[index] : null; + } + + // The text a cell's editor opens with: the pending edit, else the whole stored value, never the grid's cut text. + public EditRefusal? StartEdit(int row, int column, out string text) + { + text = string.Empty; + if (CellRefusal(edits, row, column) is { } cell) + { + return cell; + } + + if (edits.GetCell(row, column) is { } pending) + { + text = pending is CellEdit.Text typed ? typed.Value : string.Empty; + return null; + } + + if (ReadStored(row, column, out var stored) is { } unreadable) + { + return unreadable; + } + + text = stored ?? string.Empty; + return null; + } + + // Read as the save will read it, so a cell the user leaves says why it would not save. + public EditRefusal? CommitEdit(int row, int column, string text) + { + ArgumentNullException.ThrowIfNull(text); + return CellRefusal(edits, row, column) ?? Apply(row, column, new CellEdit.Text(text)); + } + + public EditRefusal? SetValue(int row, int column, CellValueKind kind) + { + if (!CanSetValue(edits, row, column, kind)) + { + return EditRefusal.CellLocked.Instance; + } + + CellEdit edit = kind switch + { + CellValueKind.Empty => new CellEdit.Text(string.Empty), + CellValueKind.Null => CellEdit.Null.Instance, + _ => CellEdit.ServerDefault.Instance, + }; + return Apply(row, column, edit); + } + + // Each copy starts its key and the columns the server computes as a new row would, as on macOS. + public int DuplicateRows(IReadOnlyList rows) => edits.DuplicateRows(rows, StoredEdit); + + // A data row copies only when its values do exactly; a new row holds what was typed. + public EditRefusal? CopyRefusal(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + try + { + return rows.Any(row => row >= 0 && row < edits.DataRows && !editor.CopiesExactly(source, row)) + ? EditRefusal.NotCopyable.Instance + : null; + } + catch (TableProException exception) + { + return new EditRefusal.Invalid(exception.Error); + } + } + + // A data row's edit back to its stored value is no change; a new row has none to compare with. + public EditRefusal? Apply(int row, int column, CellEdit edit) + { + var newRow = edits.IsAdded(row); + string? stored = null; + if (!newRow && ReadStored(row, column, out stored) is { } unreadable) + { + return unreadable; + } + + if (editor.Check(column, edit, newRow) is { } failure) + { + return new EditRefusal.Invalid(failure); + } + + edits.SetCell(row, column, edit, stored); + return null; + } + + // The stored value as text, null for NULL; a value with no text that writes it back is refused. + public EditRefusal? ReadStored(int row, int column, out string? stored) + { + stored = null; + try + { + if (editor.GetEditStart(source, row, column) is not EditStart.Editable editable) + { + return EditRefusal.CellLocked.Instance; + } + + stored = editable.IsNull ? null : editable.Text; + return null; + } + catch (TableProException exception) + { + return new EditRefusal.Invalid(exception.Error); + } + } + + public IRowSave Plan(PlannedEdits planned) + { + ArgumentNullException.ThrowIfNull(planned); + return editor.Plan(source, planned.Edits); + } + + // The same plan a save makes, with the values it binds, or why the edits cannot be planned. + public (IReadOnlyList Statements, CoreError? Failure) Preview() + { + try + { + using var save = Plan(edits.ToRowEdits()); + return (save.Statements, null); + } + catch (TableProException exception) + { + return ([], exception.Error); + } + } + + // What a copy of a data row holds where it was not edited, or null where its value has no text to copy. + private CellEdit? StoredEdit(int row, int column) + { + if (ReadStored(row, column, out var stored) is not null) + { + return null; + } + + return stored is null ? CellEdit.Null.Instance : new CellEdit.Text(stored); + } +} diff --git a/windows/src/TablePro.App.Model/ForeignImportForm.cs b/windows/src/TablePro.App.Model/ForeignImportForm.cs new file mode 100644 index 0000000000..2e2d81fc65 --- /dev/null +++ b/windows/src/TablePro.App.Model/ForeignImportForm.cs @@ -0,0 +1,533 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// The core calls an import from another app makes. +public interface IForeignImporter +{ + Task> GetSourcesAsync(); + + // File is the export the user picked, for an app imported from one. Throws foreign_import.* codes. + Task ReadAsync( + ForeignApp app, + string? file, + ForeignImportRequest request, + CancellationToken cancellationToken); +} + +// One read of another app, as ForeignImportReview holds it. +public interface IForeignReview : IDisposable +{ + ForeignApp App { get; } + + ForeignPasswordOutcome Passwords { get; } + + IReadOnlyList Connections { get; } + + IReadOnlyList SavedQueries { get; } + + ForeignImportChoices Choices(); + + void SetSelected(string reference, bool selected); + + bool Resolve(string reference, ForeignResolution resolution); + + void SetIncluded(string reference, bool included); + + Task ApplyAsync(); +} + +public sealed class CoreForeignImporter(TableProCore core, ForeignAppDirs dirs) : IForeignImporter +{ + public Task> GetSourcesAsync() => core.GetForeignSourcesAsync(dirs); + + public async Task ReadAsync( + ForeignApp app, + string? file, + ForeignImportRequest request, + CancellationToken cancellationToken) => + new CoreForeignReview( + await core.ReadForeignAsync(app, dirs, file, request, cancellationToken).ConfigureAwait(true)); + + private sealed class CoreForeignReview(ForeignImportReview review) : IForeignReview + { + public ForeignApp App => review.App; + + public ForeignPasswordOutcome Passwords => review.Passwords; + + public IReadOnlyList Connections => review.Connections; + + public IReadOnlyList SavedQueries => review.SavedQueries; + + public ForeignImportChoices Choices() => review.Choices(); + + public void SetSelected(string reference, bool selected) => review.SetSelected(reference, selected); + + public bool Resolve(string reference, ForeignResolution resolution) => review.Resolve(reference, resolution); + + public void SetIncluded(string reference, bool included) => review.SetIncluded(reference, included); + + public Task ApplyAsync() => review.ApplyAsync(); + + public void Dispose() => review.Dispose(); + } +} + +public enum ForeignImportStep +{ + Loading, + Choosing, + Reading, + Reviewing, + Importing, + Done, +} + +public enum ForeignSourceNote +{ + // The counts say what it holds. + Found, + NotFound, + PicksFile, +} + +public enum ForeignPasswordNote +{ + DecryptedWhileReading, + + // DataGrip can keep them in a KeePass file, which the core opens with DPAPI. + PasswordFile, + + // Where Windows does not let another app read them. + SystemStore, +} + +public sealed record ForeignPasswordOption(bool Offered, bool Checked, ForeignPasswordNote Note); + +public sealed record ForeignQueryOption(bool Offered, bool Checked, ForeignSavedQuerySupport Support); + +public enum ForeignReadFailureKind +{ + NotFound, + NothingFound, + + // Files of a version or shape the core does not know. + Unreadable, + + // The saved connections to compare against could not be read. + Library, + Other, +} + +public sealed record ForeignReadFailure(ForeignApp App, ForeignReadFailureKind Kind, CoreError Error) +{ + public static ForeignReadFailure From(ForeignApp app, CoreError error) + { + ArgumentNullException.ThrowIfNull(error); + var kind = error.Code switch + { + "foreign_import.file_not_found" => ForeignReadFailureKind.NotFound, + "foreign_import.nothing_found" => ForeignReadFailureKind.NothingFound, + "foreign_import.unreadable" or "foreign_import.parse" or "foreign_import.unsupported_format" => + ForeignReadFailureKind.Unreadable, + "ffi.no_storage" => ForeignReadFailureKind.Library, + var code when code.StartsWith("storage.", StringComparison.Ordinal) => ForeignReadFailureKind.Library, + _ => ForeignReadFailureKind.Other, + }; + return new ForeignReadFailure(app, kind, error); + } +} + +// Offered is what the resolution box lists: a Replace another checked row took is left out. +public sealed record ForeignConnectionLine( + ForeignConnectionRow Row, + bool Selected, + ForeignResolution? Resolution, + IReadOnlyList Offered) +{ + public string Reference => Row.Reference; + + // No engine here opens it. + public bool Selectable => Row.Connection is not null; + + public bool ShowsResolution => Row.Duplicate is not null && Selected; + + public bool CanResolve => ShowsResolution && Offered.Count > 1; +} + +// Availability is null while the core has no choice for the row. +public sealed record ForeignQueryLine(ForeignQueryRow Row, ForeignQueryAvailability? Availability, bool Included) +{ + public string Reference => Row.Reference; + + public bool Importable => Availability == ForeignQueryAvailability.Available; +} + +public sealed record ForeignImportSummary(int SelectedConnections, int Connections, int IncludedQueries, int Queries); + +public enum ForeignImportPart +{ + Connections, + QueriesAdded, + QueriesNotAdded, + PasswordsNotKept, + Nothing, + Outdated, + Failed, +} + +public sealed record ForeignImportSentence(ForeignImportPart Part, int Count = 0); + +// Outcome is set once the import wrote, Error when it refused; Sentences are in the order the bar shows them. +public sealed record ForeignImportEnding( + IReadOnlyList Sentences, + ForeignImportOutcome? Outcome, + CoreError? Error) +{ + public const string OutdatedCode = "storage.import_outdated"; + + public bool Wrote => Outcome is not null; + + public bool Outdated => Error?.Code == OutdatedCode; + + // Some passwords or saved queries did not land. + public bool Partial => Outcome is { PasswordsNotKept: > 0 } or { QueriesFailed: > 0 }; + + public bool Nothing => Outcome is { Connections: 0, QueriesAdded: 0 }; + + public static ForeignImportEnding From(ForeignImportOutcome outcome) + { + ArgumentNullException.ThrowIfNull(outcome); + List sentences = []; + if (outcome.Connections > 0) + { + sentences.Add(new ForeignImportSentence(ForeignImportPart.Connections, outcome.Connections)); + } + + if (outcome.QueriesAdded > 0) + { + sentences.Add(new ForeignImportSentence(ForeignImportPart.QueriesAdded, outcome.QueriesAdded)); + } + + if (outcome.QueriesFailed > 0) + { + sentences.Add(new ForeignImportSentence(ForeignImportPart.QueriesNotAdded, outcome.QueriesFailed)); + } + + if (outcome.PasswordsNotKept > 0) + { + sentences.Add(new ForeignImportSentence(ForeignImportPart.PasswordsNotKept, outcome.PasswordsNotKept)); + } + + if (sentences.Count == 0) + { + sentences.Add(new ForeignImportSentence(ForeignImportPart.Nothing)); + } + + return new ForeignImportEnding(sentences, outcome, null); + } + + public static ForeignImportEnding Refused(CoreError error) + { + ArgumentNullException.ThrowIfNull(error); + var part = error.Code == OutdatedCode ? ForeignImportPart.Outdated : ForeignImportPart.Failed; + return new ForeignImportEnding([new ForeignImportSentence(part)], null, error); + } +} + +// The macOS Import from Other App sheet's steps: the app and what to bring, the read, then the review of each row. +public sealed class ForeignImportForm : IDisposable +{ + private readonly IForeignImporter _importer; + private IForeignReview? _review; + private bool _importable; + + // The boxes' own answers, kept while an app that cannot honour one is chosen. + private bool _wantsPasswords = true; + private bool _wantsQueries = true; + + // A read the user left for another is dropped when it lands. + private int _read; + + public ForeignImportForm(IForeignImporter importer) + { + ArgumentNullException.ThrowIfNull(importer); + _importer = importer; + } + + public ForeignImportStep Step { get; private set; } + + public IReadOnlyList Sources { get; private set; } = []; + + // Set when the apps could not be looked for, which leaves the list empty. + public CoreError? SourcesError { get; private set; } + + public ForeignSource? Chosen { get; private set; } + + // The last read's, shown on the first page until another app or read. + public ForeignReadFailure? Failure { get; private set; } + + public ForeignPasswordOption Passwords => PasswordOption(Chosen, _wantsPasswords); + + public ForeignQueryOption Queries => QueryOption(Chosen, _wantsQueries); + + public bool CanContinue => Step == ForeignImportStep.Choosing && Chosen is { IsAvailable: true }; + + public ForeignApp? ReviewedApp => _review?.App; + + public ForeignPasswordOutcome PasswordOutcome => _review?.Passwords ?? ForeignPasswordOutcome.NotRequested; + + // A new list after each change, since a check can move another row. + public IReadOnlyList Connections { get; private set; } = []; + + public IReadOnlyList SavedQueries { get; private set; } = []; + + public ForeignImportSummary Summary { get; private set; } = new(0, 0, 0, 0); + + public bool CanImport => Step == ForeignImportStep.Reviewing && _importable; + + public static ForeignSourceNote NoteFor(ForeignSource source) + { + ArgumentNullException.ThrowIfNull(source); + return source.PicksFile ? ForeignSourceNote.PicksFile + : source.IsAvailable ? ForeignSourceNote.Found + : ForeignSourceNote.NotFound; + } + + // The first app found is chosen. + public async Task LoadAsync() + { + if (Step != ForeignImportStep.Loading) + { + return; + } + + try + { + Sources = await _importer.GetSourcesAsync().ConfigureAwait(true); + SourcesError = null; + } + catch (TableProException exception) + { + Sources = []; + SourcesError = exception.Error; + } + + if (Step != ForeignImportStep.Loading) + { + return; + } + + Chosen = Sources.FirstOrDefault(source => source.IsAvailable); + Step = ForeignImportStep.Choosing; + } + + // False for an app not found here. + public bool Choose(ForeignApp app) + { + if (Step != ForeignImportStep.Choosing + || Sources.FirstOrDefault(source => source.App == app) is not { IsAvailable: true } source) + { + return false; + } + + Chosen = source; + Failure = null; + return true; + } + + public void SetPasswords(bool wanted) + { + if (Passwords.Offered) + { + _wantsPasswords = wanted; + } + } + + public void SetQueries(bool wanted) + { + if (Queries.Offered) + { + _wantsQueries = wanted; + } + } + + public ForeignImportRequest Request() + { + var passwords = Passwords; + // An app that keeps them where Windows does not let us read is still asked, so the review says they stayed. + var includePasswords = passwords.Offered + ? passwords.Checked + : Chosen?.Passwords == ForeignPasswordSource.Keychain; + return new ForeignImportRequest(includePasswords, Queries is { Offered: true, Checked: true }); + } + + // File is the export the user picked. False when the read failed, was cancelled or was left for another. + public async Task ReadAsync(string? file, CancellationToken cancellationToken = default) + { + if (!CanContinue || Chosen is not { } source || (source.PicksFile && string.IsNullOrEmpty(file))) + { + return false; + } + + var read = ++_read; + var request = Request(); + Step = ForeignImportStep.Reading; + Failure = null; + try + { + var review = await _importer + .ReadAsync(source.App, source.PicksFile ? file : null, request, cancellationToken) + .ConfigureAwait(true); + if (read != _read || Step != ForeignImportStep.Reading) + { + review.Dispose(); + return false; + } + + _review = review; + Step = ForeignImportStep.Reviewing; + Refresh(); + return true; + } + catch (TableProException exception) + { + if (read == _read && Step == ForeignImportStep.Reading) + { + Failure = ForeignReadFailure.From(source.App, exception.Error); + Step = ForeignImportStep.Choosing; + } + + return false; + } + catch (OperationCanceledException) + { + if (read == _read && Step == ForeignImportStep.Reading) + { + Step = ForeignImportStep.Choosing; + } + + return false; + } + } + + public void SetSelected(string reference, bool selected) + { + ArgumentNullException.ThrowIfNull(reference); + if (Reviewing() is { } review) + { + review.SetSelected(reference, selected); + Refresh(); + } + } + + // False when the row does not offer it, or another checked row took that Replace. + public bool Resolve(string reference, ForeignResolution resolution) + { + ArgumentNullException.ThrowIfNull(reference); + ArgumentNullException.ThrowIfNull(resolution); + if (Reviewing() is not { } review) + { + return false; + } + + var resolved = review.Resolve(reference, resolution); + Refresh(); + return resolved; + } + + public void SetIncluded(string reference, bool included) + { + ArgumentNullException.ThrowIfNull(reference); + if (Reviewing() is { } review) + { + review.SetIncluded(reference, included); + Refresh(); + } + } + + // Null when there is nothing to import yet. The import runs once, refused or not. + public async Task ImportAsync() + { + if (!CanImport || _review is not { } review) + { + return null; + } + + Step = ForeignImportStep.Importing; + try + { + return ForeignImportEnding.From(await review.ApplyAsync().ConfigureAwait(true)); + } + catch (TableProException exception) + { + return ForeignImportEnding.Refused(exception.Error); + } + finally + { + Step = ForeignImportStep.Done; + } + } + + public void Dispose() + { + Step = ForeignImportStep.Done; + _review?.Dispose(); + _review = null; + } + + private IForeignReview? Reviewing() => Step == ForeignImportStep.Reviewing ? _review : null; + + private void Refresh() + { + if (_review is not { } review) + { + return; + } + + var choices = review.Choices(); + var connections = new Dictionary(StringComparer.Ordinal); + foreach (var choice in choices.Connections) + { + connections.TryAdd(choice.Reference, choice); + } + + var queries = new Dictionary(StringComparer.Ordinal); + foreach (var choice in choices.Queries) + { + queries.TryAdd(choice.Reference, choice); + } + + Connections = [.. review.Connections.Select(row => connections.TryGetValue(row.Reference, out var choice) + ? new ForeignConnectionLine(row, choice.Selected, choice.Resolution, choice.Offered) + : new ForeignConnectionLine(row, false, null, []))]; + SavedQueries = [.. review.SavedQueries.Select(row => queries.TryGetValue(row.Reference, out var choice) + ? new ForeignQueryLine(row, choice.Availability, choice.Included) + : new ForeignQueryLine(row, null, false))]; + Summary = new ForeignImportSummary( + Connections.Count(line => line.Selected), + Connections.Count, + SavedQueries.Count(line => line.Included), + SavedQueries.Count); + _importable = choices.Importable; + } + + private static ForeignPasswordOption PasswordOption(ForeignSource? source, bool wanted) + { + var note = source switch + { + null or { Passwords: ForeignPasswordSource.AppFiles } => ForeignPasswordNote.DecryptedWhileReading, + { App: ForeignApp.DataGrip } => ForeignPasswordNote.PasswordFile, + _ => ForeignPasswordNote.SystemStore, + }; + var offered = source is not null && note != ForeignPasswordNote.SystemStore; + return new ForeignPasswordOption(offered, offered && wanted, note); + } + + private static ForeignQueryOption QueryOption(ForeignSource? source, bool wanted) + { + var support = source?.SavedQuerySupport ?? ForeignSavedQuerySupport.NotInExport; + var offered = support is ForeignSavedQuerySupport.Scripts or ForeignSavedQuerySupport.Consoles; + return new ForeignQueryOption(offered, offered && wanted, support); + } +} diff --git a/windows/src/TablePro.App.Model/QueryTab.Editing.cs b/windows/src/TablePro.App.Model/QueryTab.Editing.cs new file mode 100644 index 0000000000..f5c70d14ba --- /dev/null +++ b/windows/src/TablePro.App.Model/QueryTab.Editing.cs @@ -0,0 +1,605 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model; + +// Why a query result does not edit, found before the core is asked; the core's own reasons come as an EditLock. +public enum ResultEditBlock +{ + SeveralResults, + + // A save writes on another connection, which would not see what the transaction holds. + OpenTransaction, + UnknownTransaction, + + // A save writes in the session's database, not the one the tab's connection moved to. + OtherDatabase, + + // The core could not read the table's columns. + ColumnsUnread, + + // No statement to read the rows again: Commit or Roll back ran, the run did not finish, or the database changed. + RunAgain, +} + +// What would replace the result's rows, which the question about their pending edits names. +public enum ResultReplacement +{ + Run, + Sort, + Database, +} + +// What a query tab shows and asks while its result's rows are edited, as a table tab's view does for its page. +public interface IResultEditView +{ + // The edits, or what may be edited, changed. + void ShowEdits(); + + void ShowSaving(bool saving); + + void ShowEditRefusal(EditRefusal refusal); + + void ShowSaveCancelled(); + + // The grid has an editor open, whose text counts as a change until it is kept or cancelled. + bool HasOpenEdit { get; } + + // The grid's open editor keeps its text first; false when the text was refused and the editor stays open. + bool CommitOpenEdit(); + + void FocusRow(int row); + + Task ConfirmDiscardForReplaceAsync(ResultReplacement reason); + + Task ConfirmDiscardAsync(); + + // Without Save when offerSave is off, as when the connection is being made read only. + Task AskSaveBeforeCloseAsync(string tab, bool offerSave); + + Task ConfirmDeleteAsync(string table, int rows); + + Task ConfirmSaveAsync(string connection, IReadOnlyList statements); + + // A failure takes the place of the statements when the edits cannot be planned. + Task ShowPreviewAsync(IReadOnlyList statements, CoreError? failure); + + Task ShowSaveFailedAsync(CoreError failure, bool incomplete); +} + +// A result that is one keyed table's rows edits as a table tab's page does, and a save reads it again (core ADR 0032). +public sealed partial class QueryTab +{ + private EditedRows? _editing; + + // What locked the result's rows when they were read, as a key the core cannot read back exactly. + private EditLock? _resultLock; + private ResultEditBlock? _resultBlock; + + // The statement whose rows the editor was opened on, and the sort it ran with, which a save runs again. + private string? _ranSql; + private GridSort _ranSort = GridSort.None; + + // Where an editor opened without a database landed: the session's own, when the connection names none. + private string? _home; + private bool _saveBlocked; + private Task _rowSave = Task.FromResult(true); + + // The result's pending changes, made anew for each result that edits. + public TableEdits? ResultEdits => _editing?.Edits; + + // The connection's lock now, else what locked the rows when they were read. + public EditLock? ResultLock => _editing is { } editing ? editing.Editor.Lock ?? _resultLock : null; + + // The core opened an editor on the result and found nothing to lock it, so Save reaches its rows. + public bool EditsResult => _editing is not null && _resultLock is null; + + // The grid opens an editor, which a block or a lock then refuses with its reason. + public bool ResultAcceptsEdits => + (_editing is not null || _resultBlock is not null) + && !IsRunning && !IsSavingRows && !_sorting && !_switching && !_work.IsClosed; + + public bool CanEditResult => _editing is not null && ResultRefusal() is null; + + public bool IsSavingRows { get; private set; } + + // An open editor counts, so Save takes it and every close asks; both keep its text first. + public bool HasPendingRows => + _editing is { } editing && (editing.Edits.HasChanges || _resultView?.HasOpenEdit == true); + + public bool CanSaveRows => CanEditResult && HasPendingRows && !_saveBlocked; + + public bool CanDiscardRows => HasPendingRows && !IsRunning && !IsSavingRows; + + public bool CanPreviewRows => HasPendingRows && !IsSavingRows; + + public int FirstColumnToFill => _editing is { } editing ? EditedRows.FirstColumnToFill(editing.Edits.Columns) : 0; + + public bool IsDeleted(int row) => _editing?.Edits.IsDeleted(row) == true; + + public EditRefusal? StartEdit(int row, int column, out string text) + { + text = string.Empty; + return ResultRefusal() ?? _editing!.StartEdit(row, column, out text); + } + + public EditRefusal? CommitEdit(int row, int column, string text) + { + ArgumentNullException.ThrowIfNull(text); + return ResultRefusal() ?? _editing!.CommitEdit(row, column, text); + } + + public bool CanSetValue(int row, int column, CellValueKind kind) => + CanEditResult && EditedRows.CanSetValue(_editing!.Edits, row, column, kind); + + public EditRefusal? SetValue(int row, int column, CellValueKind kind) => + ResultRefusal() ?? _editing!.SetValue(row, column, kind); + + public EditRefusal? AddRow(out int row) + { + row = -1; + if (ResultRefusal() is { } refused) + { + return refused; + } + + row = _editing!.Edits.AddRow(); + return null; + } + + public EditRefusal? DuplicateRows(IReadOnlyList rows, out int last) + { + ArgumentNullException.ThrowIfNull(rows); + last = -1; + if (ResultRefusal() is { } refused) + { + return refused; + } + + if (_editing!.CopyRefusal(rows) is { } copy) + { + return copy; + } + + last = _editing.DuplicateRows(rows); + return null; + } + + // A new row goes at once; a data row is marked for the save to delete. + public EditRefusal? DeleteRows(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + if (ResultRefusal() is { } refused) + { + return refused; + } + + _editing!.Edits.DeleteRows(rows); + return null; + } + + public EditRefusal? RestoreRows(IReadOnlyList rows) + { + ArgumentNullException.ThrowIfNull(rows); + if (ResultRefusal() is { } refused) + { + return refused; + } + + _editing!.Edits.RestoreRows(rows); + return null; + } + + // After a save whose outcome is unknown, the statement runs again so the rows show what the server holds. + public async Task DiscardRowsAsync() + { + if (_resultView is not { } view) + { + return; + } + + // The open edit goes with the rest; kept or not, it is not saved. + view.CommitOpenEdit(); + if (!CanDiscardRows || !await view.ConfirmDiscardAsync().ConfigureAwait(true) || _editing is not { } editing) + { + return; + } + + var reread = _saveBlocked; + _saveBlocked = false; + editing.Edits.Discard(); + if (reread) + { + await RereadAsync().ConfigureAwait(true); + } + } + + // The same plan a save makes, with the values it binds. + public async Task PreviewRowsAsync() + { + if (_resultView is not { } view || !view.CommitOpenEdit() || !CanPreviewRows || _editing is not { } editing) + { + return; + } + + var (statements, failure) = editing.Preview(); + await view.ShowPreviewAsync(statements, failure).ConfigureAwait(true); + } + + // True once every change is written, or there was nothing to write; the statement then runs again. + public Task SaveRowsAsync() => TrackRowSave(SaveRowsOnceAsync(reread: true)); + + private Task TrackRowSave(Task save) + { + _rowSave = save; + return save; + } + + private EditRefusal? ResultRefusal() + { + if (!ResultAcceptsEdits) + { + return EditRefusal.Busy.Instance; + } + + if (_resultBlock is { } block) + { + return new EditRefusal.ResultBlocked(block); + } + + return ResultLock is { } locked ? new EditRefusal.TableLocked(locked) : null; + } + + // The edits name rows of the set shown, so a run, a sort or a database switch asks first while any is pending. + private async Task MayReplaceResultAsync(ResultReplacement reason) + { + if (_editing is null || _resultView is not { } view) + { + return true; + } + + // An open edit is a change too; one the grid cannot keep holds the run back while it shows why. + if (!view.CommitOpenEdit()) + { + return false; + } + + if (!HasPendingRows) + { + return true; + } + + _confirming = true; + try + { + if (!await view.ConfirmDiscardForReplaceAsync(reason).ConfigureAwait(true)) + { + return false; + } + } + finally + { + _confirming = false; + } + + // A save that may have landed stays blocked until rows are read again, which a held sort does not do. + _editing?.Edits.Discard(); + return true; + } + + // What only the app knows refuses first; then the core says whether the rows are one keyed table's. + private async Task BindResultAsync(string sql, CancellationToken cancellationToken) + { + if (_resultView is null || _work.IsClosed || _results.ResultSetCount == 0) + { + return; + } + + if (BlockFor() is { } block) + { + ReleaseResult(block); + return; + } + + var rows = _results.ShownSet; + ITableEditor editor; + try + { + editor = await _session.OpenResultEditorAsync(sql, rows, cancellationToken).ConfigureAwait(true); + } + catch (TableProException) + { + if (!_work.IsClosed) + { + ReleaseResult(ResultEditBlock.ColumnsUnread); + } + + return; + } + + if (_work.IsClosed) + { + editor.Dispose(); + return; + } + + _ranSql = sql; + _ranSort = _sort; + Bind(editor, rows); + } + + // What only the app knows (core ADR 0032): several results, a transaction, another database, no statement. + private ResultEditBlock? BlockFor() + { + if (_results.ResultSetCount > 1) + { + return ResultEditBlock.SeveralResults; + } + + if (_results.Transaction == TransactionState.Unknown) + { + return ResultEditBlock.UnknownTransaction; + } + + if (_results.Transaction != TransactionState.Idle) + { + return ResultEditBlock.OpenTransaction; + } + + if (InOtherDatabase()) + { + return ResultEditBlock.OtherDatabase; + } + + return _statement is null || _results.Outcome is not QueryOutcome.Completed ? ResultEditBlock.RunAgain : null; + } + + // The editor's database as the server last said, else the one the tab opened it in, against the session's own. + private bool InOtherDatabase() + { + var home = _session.Database ?? _home; + var ran = _editor?.Database ?? Database; + return ran is not null && !string.Equals(ran, home, StringComparison.Ordinal); + } + + // New edits for the set shown, with what locks its rows. + private void Bind(ITableEditor editor, ResultSet? rows) + { + ReleaseResult(); + EditLock? locked; + try + { + locked = editor.LockFor(rows); + } + catch (TableProException) + { + // Rows whose locks cannot be read are only read. + editor.Dispose(); + ReleaseResult(ResultEditBlock.RunAgain); + return; + } + + var count = (int)Math.Clamp(_results.ShownRowCount, 0, int.MaxValue); + _editing = new EditedRows(editor, new TableEdits(editor.Columns, count), rows); + _resultLock = locked; + _editing.Edits.Changed += OnResultEditsChanged; + ResultEditsChanged(); + } + + // The editor and its edits go with the rows they were opened on; a block says why the rows shown do not edit. + private void ReleaseResult(ResultEditBlock? block = null) + { + var shown = _editing is not null || _resultBlock is not null || block is not null; + if (_editing is { } editing) + { + editing.Edits.Changed -= OnResultEditsChanged; + editing.Editor.Dispose(); + } + + _editing = null; + _resultLock = null; + _resultBlock = block; + _saveBlocked = false; + if (shown) + { + ResultEditsChanged(); + } + } + + // A held sort shows a sorted copy of the same rows, which the editor reads as well; any other set ends the edits. + private void OnShownSetChanged(object? sender, EventArgs e) + { + if (_editing is not { } editing || ReferenceEquals(_results.ShownSet, editing.Source)) + { + return; + } + + if (_sorting && _results.ShownSet is { } sorted && !editing.Edits.HasChanges) + { + editing.Edits.Changed -= OnResultEditsChanged; + _editing = null; + var blocked = _saveBlocked; + Bind(editing.Editor, sorted); + _saveBlocked = blocked; + return; + } + + ReleaseResult(); + } + + private void OnResultEditsChanged(object? sender, EventArgs e) => ResultEditsChanged(); + + private void ResultEditsChanged() + { + _resultView?.ShowEdits(); + StateChanged?.Invoke(this, EventArgs.Empty); + } + + // Rows came and went, so the statement runs again, as the Linux app reads them; the history keeps only typed runs. + private async Task RereadAsync() + { + if (_ranSql is not { } sql || IsRunning || _work.IsClosed) + { + return; + } + + // A sort the rows took here rather than in the statement is applied again to the rows read. + var held = _sort != _ranSort ? _sort : GridSort.None; + _sort = _ranSort; + if (await RunSqlAsync(sql, record: false).ConfigureAwait(true) && held != GridSort.None && !_work.IsClosed) + { + await _work.RunAsync(_ => SortHeldRowsAsync(held)).ConfigureAwait(true); + } + } + + private async Task SaveRowsOnceAsync(bool reread) + { + if (_resultView is not { } view || _editing is null || !view.CommitOpenEdit()) + { + return false; + } + + if (_saveBlocked || ResultLock is not null) + { + view.ShowEditRefusal(_saveBlocked ? EditRefusal.SaveBlocked.Instance : ResultRefusal()!); + return false; + } + + if (!CanSaveRows || _editing is not { } editing) + { + return false; + } + + var planned = editing.Edits.ToRowEdits(); + IRowSave save; + try + { + save = editing.Plan(planned); + } + catch (TableProException exception) + { + await view.ShowSaveFailedAsync(exception.Error, incomplete: false).ConfigureAwait(true); + return false; + } + + using (save) + { + return await RunRowSaveAsync(view, save, editing, planned, reread).ConfigureAwait(true); + } + } + + // The delete question comes at every Safe Mode level, as on a table tab, then the level's own. + private async Task RunRowSaveAsync( + IResultEditView view, IRowSave save, EditedRows editing, PlannedEdits planned, bool reread) + { + if (save.IsEmpty) + { + editing.Edits.Discard(); + return true; + } + + if (save.Gate == SaveGate.Refuse) + { + view.ShowEditRefusal(new EditRefusal.TableLocked(EditLock.ReadOnlyConnection)); + return false; + } + + var deletes = planned.Edits.Count(edit => edit is RowEdit.Delete); + if (deletes > 0 + && !await view.ConfirmDeleteAsync(editing.Editor.Table?.Name ?? Title, deletes).ConfigureAwait(true)) + { + return false; + } + + var confirmed = save.Gate == SaveGate.Run; + if (save.Gate == SaveGate.Confirm) + { + if (!await view.ConfirmSaveAsync(_session.Name, save.Statements).ConfigureAwait(true)) + { + view.ShowSaveCancelled(); + return false; + } + + confirmed = true; + } + + // Asked while the tab closed or its rows went, the save no longer names what it was planned for. + if (!ReferenceEquals(editing, _editing) || !CanSaveRows) + { + return false; + } + + RowSaveOutcome? outcome = null; + CoreError? failure = null; + // A save is not stopped halfway: a close waits for the server's answer and for what the answer changes here. + await _work.RunAsync(async _ => + { + SetSavingRows(true); + try + { + (outcome, failure) = await EditedRows.RunSaveAsync(save, confirmed).ConfigureAwait(true); + } + finally + { + SetSavingRows(false); + } + + if (outcome is RowSaveOutcome.Saved) + { + editing.Edits.Discard(); + } + else if (outcome is RowSaveOutcome.Unknown) + { + _saveBlocked = true; + ResultEditsChanged(); + } + }).ConfigureAwait(true); + + // A tab that closed meanwhile says nothing more. + if (_work.IsClosed) + { + return outcome is RowSaveOutcome.Saved; + } + + switch (outcome) + { + case RowSaveOutcome.Saved: + if (reread) + { + await RereadAsync().ConfigureAwait(true); + } + + return true; + case RowSaveOutcome.RolledBack rolledBack: + await view.ShowSaveFailedAsync(rolledBack.Error, incomplete: false).ConfigureAwait(true); + FocusEdit(view, planned, rolledBack.Edit); + return false; + case RowSaveOutcome.Unknown unknown: + await view.ShowSaveFailedAsync(unknown.Error, incomplete: true).ConfigureAwait(true); + FocusEdit(view, planned, unknown.Edit); + return false; + default: + if (failure is not null) + { + await view.ShowSaveFailedAsync(failure, incomplete: false).ConfigureAwait(true); + } + + return false; + } + } + + private static void FocusEdit(IResultEditView view, PlannedEdits planned, int? edit) + { + if (EditedRows.RowOf(planned, edit) is { } row) + { + view.FocusRow(row); + } + } + + private void SetSavingRows(bool saving) + { + IsSavingRows = saving; + _resultView?.ShowSaving(saving); + ResultEditsChanged(); + } +} diff --git a/windows/src/TablePro.App.Model/QueryTab.cs b/windows/src/TablePro.App.Model/QueryTab.cs index 4f744e7d6b..0a4548893b 100644 --- a/windows/src/TablePro.App.Model/QueryTab.cs +++ b/windows/src/TablePro.App.Model/QueryTab.cs @@ -87,7 +87,7 @@ public sealed record DatabaseChoices( string? Current); // One editor connection for the tab, so a transaction holds from one run to the next. -public sealed class QueryTab : IWorkspaceTab +public sealed partial class QueryTab : IWorkspaceTab { private readonly ITabSession _session; private readonly IQueryTabView _view; @@ -96,6 +96,7 @@ public sealed class QueryTab : IWorkspaceTab private readonly Func _settings; private readonly IHistoryRecorder? _history; private readonly IQueryFileView? _files; + private readonly IResultEditView? _resultView; private readonly TabWork _work = new(); private ITabEditor? _editor; private Task? _closing; @@ -131,7 +132,8 @@ public QueryTab( string? filePath = null, SqlFileRead? onDisk = null, bool baselineUnknown = false, - bool restoring = false) + bool restoring = false, + IResultEditView? resultEdits = null) { ArgumentNullException.ThrowIfNull(title); ArgumentNullException.ThrowIfNull(session); @@ -146,6 +148,7 @@ public QueryTab( _settings = settings; _history = history; _files = files; + _resultView = resultEdits; Database = Kept(database); if (files is not null && !string.IsNullOrEmpty(filePath)) { @@ -161,6 +164,8 @@ public QueryTab( IsDirty = TextDiffers(); _awaitingFile = restoring && onDisk is null; } + + _results.ShownSetChanged += OnShownSetChanged; } public event EventHandler? StateChanged; @@ -183,7 +188,8 @@ public QueryTab( // As the Linux app waits: a move would part a run or a transaction from the database it began in. public bool CanPickDatabase => - !IsRunning && !_confirming && !_switching && !_work.IsClosed && !WorkspaceNotices.Holds(Transaction); + !IsRunning && !IsSavingRows && !_confirming && !_switching && !_work.IsClosed + && !WorkspaceNotices.Holds(Transaction); public bool IsRunning { get; private set; } @@ -194,29 +200,53 @@ public QueryTab( // The text differs from the file as last read or saved; set as the view reports edits. public bool IsDirty { get; private set; } - // Read afresh, since the view reports edits a moment later than they land; a file still being written counts too. - public bool HasUnsavedChanges => (FilePath is not null && TextDiffers()) || _saving is { IsCompleted: false }; + public bool HasUnsavedChanges => FileUnsaved || HasPendingRows; // The typed SQL whose results the tab shows, which a result share sends; null after Commit or Roll back. public string? LastStatement => _statement; - // A scratch tab's text is kept in the session, so only a file tab's unsaved text is asked about. + // Read afresh, since the view reports edits a moment later than they land; a file still being written counts too. + private bool FileUnsaved => (FilePath is not null && TextDiffers()) || _saving is { IsCompleted: false }; + + // A scratch tab's text is kept in the session, so only a file's text is asked about, with the result's rows. public async Task ConfirmCloseAsync(bool offerSave) { - if (_files is null || !HasUnsavedChanges) + // A row save in flight is waited for, never asked about halfway; what it left pending is asked about after. + await _rowSave.ConfigureAwait(true); + // An open edit the grid cannot keep holds the close back while it shows why. + if (_editing is not null && _resultView is { } view && !view.CommitOpenEdit()) + { + return false; + } + + var rows = HasPendingRows; + var file = _files is not null && FileUnsaved; + if (!rows && !file) { return true; } - // A read-only connection takes away Save for its table edits; a file is written here, not to the database. - var answer = await _files.AskSaveBeforeCloseAsync(Title, offerSave: true).ConfigureAwait(true); - return answer switch + // A read-only connection takes away Save for the rows; a file is written here, not to the database. + var saves = offerSave || !rows; + var answer = rows + ? await _resultView!.AskSaveBeforeCloseAsync(Title, saves).ConfigureAwait(true) + : await _files!.AskSaveBeforeCloseAsync(Title, offerSave: true).ConfigureAwait(true); + switch (answer) { - // Text typed while the file was written is still unsaved, so the tab stays. - SaveBeforeClose.Save => await SaveAsync().ConfigureAwait(true) && !HasUnsavedChanges, - SaveBeforeClose.DontSave => true, - _ => false, - }; + // The rows are read again after their save: the file's save, or another tab's answer, can keep this one open. + case SaveBeforeClose.Save when saves: + if (rows && !await TrackRowSave(SaveRowsOnceAsync(reread: true)).ConfigureAwait(true)) + { + return false; + } + + // Text typed while the file was written is still unsaved, so the tab stays. + return !file || (await SaveAsync().ConfigureAwait(true) && !FileUnsaved); + case SaveBeforeClose.DontSave: + return true; + default: + return false; + } } // Don't Save leaves the file as it was; the text stays with the tab either way, as macOS keeps a closed tab's SQL. @@ -244,7 +274,7 @@ public SessionTab WithPendingWork(SessionTab snapshot) public async Task RunAsync() { - if (IsRunning || _confirming || _switching || _work.IsClosed) + if (IsRunning || IsSavingRows || _confirming || _switching || _work.IsClosed) { return; } @@ -261,7 +291,7 @@ public async Task RunAsync() // The statement is selected first so the tab shows which of its statements ran, as the Linux app does. public async Task RunStatementAsync() { - if (IsRunning || _confirming || _switching || _work.IsClosed) + if (IsRunning || IsSavingRows || _confirming || _switching || _work.IsClosed) { return; } @@ -293,7 +323,9 @@ public async Task RollBackAsync() // Only one query that reads runs again: running a script or a write again would repeat it. public async Task SortAsync(GridSort sort) { - if (IsRunning || _sorting || _switching) + if (IsRunning || IsSavingRows || _sorting || _switching + || !await MayReplaceResultAsync(ResultReplacement.Sort).ConfigureAwait(true) + || IsRunning || _sorting || _switching) { _results.Sort = _sort; return; @@ -357,7 +389,8 @@ [.. listed.Where(entry => entry.IsSystem).Select(entry => entry.Name)], public async Task PickDatabaseAsync(string database) { ArgumentException.ThrowIfNullOrEmpty(database); - if (!CanPickDatabase || database == ShownDatabase) + if (!CanPickDatabase || database == ShownDatabase + || !await MayReplaceResultAsync(ResultReplacement.Database).ConfigureAwait(true) || !CanPickDatabase) { return; } @@ -538,6 +571,7 @@ private async Task CloseOnceAsync() _run?.Dispose(); _run = null; _results.Clear(); + ReleaseResult(); if (_editor is not null) { await _editor.DisposeAsync().ConfigureAwait(true); @@ -556,7 +590,8 @@ private async Task RunTypedAsync(string sql) return; } - if (!await SafeModeAllowsAsync(sql).ConfigureAwait(true) || IsRunning || _work.IsClosed) + if (!await SafeModeAllowsAsync(sql).ConfigureAwait(true) || IsRunning || _work.IsClosed + || !await MayReplaceResultAsync(ResultReplacement.Run).ConfigureAwait(true) || IsRunning || _work.IsClosed) { return; } @@ -599,6 +634,8 @@ private Task RunSqlAsync(string sql, bool record) => private async Task RunOnEditorAsync(string sql, bool record, CancellationToken cancellationToken) { HistoryRun? ran = null; + // The run replaces the rows the result's edits name, which were asked about first. + ReleaseResult(); SetRunning(true); try { @@ -611,8 +648,13 @@ private async Task RunOnEditorAsync(string sql, bool record, CancellationToken c // An editor that opens as the tab closes stays in _editor, which the close disposes. if (_editor is null) { + var opening = Database; // Run elsewhere, the text would make its objects in the wrong database, so the core refuses the open. _editor = await _session.OpenEditorAsync(Database, cancellationToken).ConfigureAwait(true); + if (opening is null) + { + _home ??= _editor.Database; + } } if (_work.IsClosed) @@ -635,6 +677,7 @@ await _results.ShowRunAsync(_run, _sort, int.MaxValue, settings.ResultSetsKeptPe } await AfterRunAsync().ConfigureAwait(true); + await BindResultAsync(sql, cancellationToken).ConfigureAwait(true); } } catch (TableProException exception) @@ -743,7 +786,8 @@ private void ShowTransaction(TransactionState state) // Run as typed SQL is, so the results and the bar follow it, as the Linux app ends one. private async Task EndTransactionAsync(bool commit) { - if (IsRunning || _editor is null) + if (IsRunning || IsSavingRows || _editor is null + || !await MayReplaceResultAsync(ResultReplacement.Run).ConfigureAwait(true) || IsRunning) { return; } @@ -773,6 +817,11 @@ private void SetDatabase(string? database, bool switched = false) if (switched) { _statement = null; + // The rows shown came from the database before, which a save would read again in this one. + if (_editing is not null) + { + ReleaseResult(ResultEditBlock.RunAgain); + } } StateChanged?.Invoke(this, EventArgs.Empty); @@ -979,6 +1028,8 @@ private async Task SortHeldRowsAsync(GridSort sort) finally { _sorting = false; + // A sorted copy bound while the sort ran was shown as not taking edits. + ResultEditsChanged(); } } diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 073ec7eb65..bae5e89a25 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -58,6 +58,9 @@ Task ReadTablePageAsync( // Refresh reads the table's columns from the server again, as a Refresh of the tab asks. Task OpenTableEditorAsync(TableName table, bool refresh, CancellationToken cancellationToken); + // Lock says why not when the rows are not one keyed table's; `rows` is the run's only set, null when none shows. + Task OpenResultEditorAsync(string sql, ResultSet? rows, CancellationToken cancellationToken); + Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken); ValueTask ReleaseAsync(); @@ -86,8 +89,14 @@ public interface ITableEditor : IDisposable IReadOnlyList Columns { get; } + // The table a save writes; null while a query result is locked. + TableName? Table { get; } + EditStart GetEditStart(ResultSet? rows, long row, int column); + // False for a query result row whose values would not copy exactly, as PostgreSQL's text for a float. + bool CopiesExactly(ResultSet? rows, long row); + // One column's stored values with their kinds, for rowCount rows from firstRow, as a key names a row in the file. IReadOnlyList GetStoredValues(ResultSet? rows, int column, long firstRow, int rowCount); @@ -227,6 +236,21 @@ public async Task OpenTableEditorAsync( new CoreTableEditor( await _share.Session.OpenTableEditorAsync(table, refresh, cancellationToken).ConfigureAwait(true)); + public async Task OpenResultEditorAsync( + string sql, + ResultSet? rows, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(sql); + if (rows is null) + { + throw new TableProException(CoreTableEditor.RowsGone); + } + + return new CoreTableEditor( + await _share.Session.OpenResultEditorAsync(sql, rows, cancellationToken).ConfigureAwait(true)); + } + public async Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken) => new CoreTableKeys(await _share.Session.ReadTableKeysAsync(table, cancellationToken).ConfigureAwait(true)); @@ -253,7 +277,7 @@ internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor private const int KindWindow = 4096; // The rows the edits name are gone, as when the page went before its save was planned. - private static readonly CoreError RowsGone = new( + internal static readonly CoreError RowsGone = new( "edit.out_of_range", ["edit.out_of_range"], "The page's rows are no longer held.", null, null); public EditLock? Lock => editor.Lock; @@ -263,9 +287,13 @@ internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor public IReadOnlyList Columns => editor.Columns; + public TableName? Table => editor.Table; + public EditStart GetEditStart(ResultSet? rows, long row, int column) => rows is null ? EditStart.Locked.Instance : editor.GetEditStart(rows, row, column); + public bool CopiesExactly(ResultSet? rows, long row) => rows is null || editor.CopiesExactly(rows, row); + // A window holds the kinds; the text is the whole value, which a window cuts. public IReadOnlyList GetStoredValues(ResultSet? rows, int column, long firstRow, int rowCount) { diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index b741fae61b..9ac676143a 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -81,6 +81,15 @@ public sealed record SaveBlocked : EditRefusal } public sealed record Invalid(CoreError Failure) : EditRefusal; + + // A query result the app refuses before it asks the core, as one read inside a transaction. + public sealed record ResultBlocked(ResultEditBlock Block) : EditRefusal; + + // A row whose values were read as text that may not name them, so a copy could change them. + public sealed record NotCopyable : EditRefusal + { + public static NotCopyable Instance { get; } = new(); + } } // What a table tab shows and asks; the view words the pager from the tab's Page. @@ -151,17 +160,6 @@ public interface ITableTabView // A sort and a filter are the page's ORDER BY and WHERE, so they order and pick from the whole table. public sealed class TableTab : IWorkspaceTab { - // The refusals the core makes before it sends anything, so a save after one cannot write twice. - private static readonly HashSet NothingSent = new(StringComparer.Ordinal) - { - "edit.not_confirmed", - "edit.safe_mode_changed", - "edit.not_as_planned", - "edit.already_saved", - "edit.read_only_connection", - "ffi.not_connected", - }; - private readonly ITabSession _session; private readonly ITableTabView _view; private readonly IResultsView _results; @@ -335,28 +333,7 @@ public TableTab( public bool CanPreview => HasUnsavedChanges && _tableEditor is not null && !IsSaving; - // A new row's editor opens on the first column the server does not fill. - public int FirstColumnToFill - { - get - { - if (_tableEditor is not { } editor) - { - return 0; - } - - var columns = editor.Columns; - for (var column = 0; column < columns.Count; column++) - { - if (columns[column] is { EditableInNewRow: true, NewRow: not CellEdit.ServerDefault }) - { - return column; - } - } - - return 0; - } - } + public int FirstColumnToFill => _tableEditor is { } editor ? EditedRows.FirstColumnToFill(editor.Columns) : 0; public bool Shows(string? schema, string table) => string.Equals(Table.Name, table, StringComparison.Ordinal) @@ -663,25 +640,7 @@ public void PageRead(long rows, long milliseconds, bool truncated) return refused; } - var edits = Edits!; - if (CellRefusal(edits, row, column) is { } cell) - { - return cell; - } - - if (edits.GetCell(row, column) is { } pending) - { - text = pending is CellEdit.Text typed ? typed.Value : string.Empty; - return null; - } - - if (ReadStored(row, column, out var stored) is { } unreadable) - { - return unreadable; - } - - text = stored ?? string.Empty; - return null; + return Rows(Edits!).StartEdit(row, column, out text); } // Each column of the row in the table's own order; a binary value shows as the grid shows it, 0x and hex. A stored @@ -723,7 +682,7 @@ public IReadOnlyList FieldsAt(int row, int maxCharacters = CellValue.M var held = StoredField(rows, row, column, info, maxCharacters); // An editable cell opens with its whole stored text, as the grid's editor does, once it fits. - if (editable && !held.TextCut && ReadStored(row, column, out var stored) is null) + if (editable && !held.TextCut && Rows(edits!).ReadStored(row, column, out var stored) is null) { // A TextBox ends its text at a NUL, so such a value is shown and never edited here, as in the grid. var editableText = stored?.Contains('\0', StringComparison.Ordinal) != true; @@ -776,26 +735,11 @@ private static RowField StoredField(ResultSet? rows, int row, int column, Result return refused; } - var edits = Edits!; - return CellRefusal(edits, row, column) ?? Apply(edits, row, column, new CellEdit.Text(text)); + return Rows(Edits!).CommitEdit(row, column, text); } - // As the core says the column takes each; in a new row, Default is where the server fills the column. - public bool CanSetValue(int row, int column, CellValueKind kind) - { - if (!CanEdit || Edits is not { } edits || CellRefusal(edits, row, column) is not null) - { - return false; - } - - var info = edits.Columns[column]; - return kind switch - { - CellValueKind.Empty => info.TakesEmpty, - CellValueKind.Null => info.Nullable, - _ => edits.IsAdded(row) ? info.NewRow is CellEdit.ServerDefault : info.TakesDefault, - }; - } + public bool CanSetValue(int row, int column, CellValueKind kind) => + CanEdit && Edits is { } edits && EditedRows.CanSetValue(edits, row, column, kind); public EditRefusal? SetValue(int row, int column, CellValueKind kind) { @@ -804,18 +748,7 @@ public bool CanSetValue(int row, int column, CellValueKind kind) return refused; } - if (!CanSetValue(row, column, kind)) - { - return EditRefusal.CellLocked.Instance; - } - - CellEdit edit = kind switch - { - CellValueKind.Empty => new CellEdit.Text(string.Empty), - CellValueKind.Null => CellEdit.Null.Instance, - _ => CellEdit.ServerDefault.Instance, - }; - return Apply(Edits!, row, column, edit); + return Rows(Edits!).SetValue(row, column, kind); } // A new row holds the server's value where it has one, else NULL, until the user types. @@ -841,7 +774,7 @@ public bool CanSetValue(int row, int column, CellValueKind kind) return refused; } - last = Edits!.DuplicateRows(rows, StoredEdit); + last = Rows(Edits!).DuplicateRows(rows); return null; } @@ -892,19 +825,8 @@ public async Task PreviewAsync() return; } - IReadOnlyList statements; - try - { - using var save = _tableEditor!.Plan(_editsRows, edits.ToRowEdits().Edits); - statements = save.Statements; - } - catch (TableProException exception) - { - await _view.ShowPreviewAsync([], exception.Error).ConfigureAwait(true); - return; - } - - await _view.ShowPreviewAsync(statements, null).ConfigureAwait(true); + var (statements, failure) = Rows(edits).Preview(); + await _view.ShowPreviewAsync(statements, failure).ConfigureAwait(true); } // True once every change is written, or there was nothing to write. @@ -1247,8 +1169,9 @@ private void RestoreRecovered() return; } + var rows = Rows(edits); var (restored, uncertain, waiting) = recovered.RestoreTo(edits, ReadStoredValues, (row, column, edit) => - CellRefusal(edits, row, column) is null && Apply(edits, row, column, edit) is null); + CellRefusal(edits, row, column) is null && rows.Apply(row, column, edit) is null); _recovered = waiting; // Changes a save may have written wait for a reload or a discard before the next save, as here after one. if (uncertain) @@ -1329,71 +1252,11 @@ private void OnShownSetChanged(object? sender, EventArgs e) return Lock is { } locked ? new EditRefusal.TableLocked(locked) : null; } - private static EditRefusal? CellRefusal(TableEdits edits, int row, int column) - { - if (row < 0 || row >= edits.RowCount || column < 0 || column >= edits.Columns.Count) - { - return EditRefusal.CellLocked.Instance; - } - - if (edits.IsDeleted(row)) - { - return EditRefusal.RowDeleted.Instance; - } - - // A saved row's key stays as it is; a new row leaves to the server what it fills. - var info = edits.Columns[column]; - return (edits.IsAdded(row) ? info.EditableInNewRow : info.Editable) ? null : EditRefusal.CellLocked.Instance; - } - - private EditRefusal? Apply(TableEdits edits, int row, int column, CellEdit edit) - { - var newRow = edits.IsAdded(row); - string? stored = null; - if (!newRow && ReadStored(row, column, out stored) is { } unreadable) - { - return unreadable; - } - - if (_tableEditor!.Check(column, edit, newRow) is { } failure) - { - return new EditRefusal.Invalid(failure); - } - - edits.SetCell(row, column, edit, stored); - return null; - } - - // The stored value as text, null for NULL; a value with no text that writes it back is refused. - private EditRefusal? ReadStored(int row, int column, out string? stored) - { - stored = null; - try - { - if (_tableEditor!.GetEditStart(_editsRows, row, column) is not EditStart.Editable editable) - { - return EditRefusal.CellLocked.Instance; - } + private static EditRefusal? CellRefusal(TableEdits edits, int row, int column) => + EditedRows.CellRefusal(edits, row, column); - stored = editable.IsNull ? null : editable.Text; - return null; - } - catch (TableProException exception) - { - return new EditRefusal.Invalid(exception.Error); - } - } - - // What a copy of a data row holds where it was not edited, or null where its value has no text to copy. - private CellEdit? StoredEdit(int row, int column) - { - if (ReadStored(row, column, out var stored) is not null) - { - return null; - } - - return stored is null ? CellEdit.Null.Instance : new CellEdit.Text(stored); - } + // The page's edits over the set they were made on, read and checked by the table's editor. + private EditedRows Rows(TableEdits edits) => new(_tableEditor!, edits, _editsRows); private async Task SaveEditsAsync(bool reload) { @@ -1480,16 +1343,7 @@ await _work.RunAsync(async _ => { // On disk before the first statement: an end while it runs leaves the edits blocked, not saved twice. _view.WriteSessionNow(); - outcome = await save.RunAsync(confirmed, CancellationToken.None).ConfigureAwait(true); - } - catch (TableProException exception) when (exception.Error.Codes.Any(NothingSent.Contains)) - { - failure = exception.Error; - } - catch (TableProException exception) - { - // Any other failure may have come after the batch was sent, so saving again could write it twice. - outcome = new RowSaveOutcome.Unknown(exception.Error, null); + (outcome, failure) = await EditedRows.RunSaveAsync(save, confirmed).ConfigureAwait(true); } finally { @@ -1551,9 +1405,9 @@ private async Task AfterSaveAsync( // The row of the change the engine said the save stopped at. private void FocusEdit(PlannedEdits planned, int? edit) { - if (edit is { } index && index >= 0 && index < planned.Rows.Count) + if (EditedRows.RowOf(planned, edit) is { } row) { - _view.FocusRow(planned.Rows[index]); + _view.FocusRow(row); } } diff --git a/windows/src/TablePro.App/MainWindow.xaml b/windows/src/TablePro.App/MainWindow.xaml index c94d61cfb4..78556151f4 100644 --- a/windows/src/TablePro.App/MainWindow.xaml +++ b/windows/src/TablePro.App/MainWindow.xaml @@ -40,6 +40,7 @@ + diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index 2b3cc94b8e..7a0ddb7b91 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -373,6 +373,30 @@ public async Task ImportAsync() } } + // The outcome lands in the Connections page's bar, as a file import's does. + public async Task ImportFromAppAsync() + { + if (_home is null) + { + _primary.Activate(); + await _primary.ImportFromAppAsync(); + return; + } + + ShowHome(); + if (await ImportFromAppDialog.RunAsync(Root, _workbench) is not { } ending) + { + return; + } + + if (ending.Wrote) + { + _workbench.NotifyLibraryChanged(); + } + + _home.ShowMessage(ImportFromAppDialog.Describe(ending), ImportFromAppDialog.Severity(ending)); + } + public async Task ExportConnectionsAsync() { if (_home is null) @@ -1565,16 +1589,17 @@ private void UpdateCommands() MenuCopy.IsEnabled = tab is not null; MenuSelectAll.IsEnabled = tab is not null; - // A query tab never edits; a table tab says what its page can do now. + // A table tab says what its page can do now, a query tab what its result can. var table = tab as TableTabView; + var query = tab as QueryTabView; MenuFilterRows.IsEnabled = table is not null; - MenuSaveChanges.IsEnabled = table is { CanSave: true } || tab is QueryTabView; - MenuSaveAs.IsEnabled = tab is QueryTabView; - MenuDiscardChanges.IsEnabled = table is { CanDiscard: true }; - MenuPreviewSql.IsEnabled = table is { CanPreview: true }; - MenuAddRow.IsEnabled = table is { CanAddRow: true }; - MenuDuplicateRow.IsEnabled = table is { CanChangeRows: true }; - MenuDeleteRows.IsEnabled = table is { CanChangeRows: true }; + MenuSaveChanges.IsEnabled = table is { CanSave: true } || query is not null; + MenuSaveAs.IsEnabled = query is not null; + MenuDiscardChanges.IsEnabled = table is { CanDiscard: true } || query is { CanDiscardRows: true }; + MenuPreviewSql.IsEnabled = table is { CanPreview: true } || query is { CanPreviewRows: true }; + MenuAddRow.IsEnabled = table is { CanAddRow: true } || query is { CanAddRow: true }; + MenuDuplicateRow.IsEnabled = table is { CanChangeRows: true } || query is { CanChangeRows: true }; + MenuDeleteRows.IsEnabled = table is { CanChangeRows: true } || query is { CanChangeRows: true }; _primary._sessionEnd?.Update(); } @@ -1584,6 +1609,8 @@ private void UpdateCommands() private async void OnImport(object sender, RoutedEventArgs e) => await ImportAsync(); + private async void OnImportFromApp(object sender, RoutedEventArgs e) => await ImportFromAppAsync(); + private async void OnExportConnections(object sender, RoutedEventArgs e) => await ExportConnectionsAsync(); private void OnNewQueryTab(object sender, RoutedEventArgs e) => Workspace?.NewQueryTab(); @@ -1811,25 +1838,78 @@ private async void OnSaveAs(object sender, RoutedEventArgs e) private async void OnDiscardChanges(object sender, RoutedEventArgs e) { - if (Workspace?.ActiveTab is TableTabView table) + switch (Workspace?.ActiveTab) { - await table.DiscardAsync(); + case TableTabView table: + await table.DiscardAsync(); + break; + case QueryTabView query: + await query.DiscardRowsAsync(); + break; + default: + break; } } private async void OnPreviewSql(object sender, RoutedEventArgs e) { - if (Workspace?.ActiveTab is TableTabView table) + switch (Workspace?.ActiveTab) { - await table.PreviewAsync(); + case TableTabView table: + await table.PreviewAsync(); + break; + case QueryTabView query: + await query.PreviewRowsAsync(); + break; + default: + break; } } - private void OnAddRow(object sender, RoutedEventArgs e) => (Workspace?.ActiveTab as TableTabView)?.AddRow(); + private void OnAddRow(object sender, RoutedEventArgs e) + { + switch (Workspace?.ActiveTab) + { + case TableTabView table: + table.AddRow(); + break; + case QueryTabView query: + query.AddRow(); + break; + default: + break; + } + } - private void OnDuplicateRow(object sender, RoutedEventArgs e) => (Workspace?.ActiveTab as TableTabView)?.DuplicateRows(); + private void OnDuplicateRow(object sender, RoutedEventArgs e) + { + switch (Workspace?.ActiveTab) + { + case TableTabView table: + table.DuplicateRows(); + break; + case QueryTabView query: + query.DuplicateRows(); + break; + default: + break; + } + } - private void OnDeleteRows(object sender, RoutedEventArgs e) => (Workspace?.ActiveTab as TableTabView)?.DeleteRows(); + private void OnDeleteRows(object sender, RoutedEventArgs e) + { + switch (Workspace?.ActiveTab) + { + case TableTabView table: + table.DeleteRows(); + break; + case QueryTabView query: + query.DeleteRows(); + break; + default: + break; + } + } private async void OnDocumentation(object sender, RoutedEventArgs e) => await Launcher.LaunchUriAsync(SettingsView.DocumentationUri); diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index 32411e9d93..8be2cfba63 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -352,10 +352,10 @@ SQLite and DuckDB files on this PC - Import a connections file + Import connections - Connections exported from TablePro. Passwords are not in the file, so each one asks on its first connect. + From a TablePro connections file, or from another app on this PC. Try the sample database @@ -4293,6 +4293,336 @@ New fingerprint: {2} The change was stopped. It may have run in part, so the objects are read again. + + Import from file... + + + Import from another app... + + + Import from another app... + + + Import from another app + + + Import from {0} + + + Choose the app to import from + + + Looking for apps on this PC... + + + TablePro couldn't look for other apps on this PC. + + + Choose an export file to import + + + Not found on this PC + + + 1 connection found + + + {0} connections found + + + 1 saved query + + + {0} saved queries + + + Import passwords + + + Import saved queries + + + Saved passwords are decrypted while reading + + + Read from the password file of {0} when it keeps one there + + + {0} keeps passwords in the system's store, and Windows doesn't let TablePro read it + + + Scripts import with the connection they run on. Scripts with a default name start unchecked. + + + Query consoles import with their data source. Consoles with a default name start unchecked. + + + {0} keeps saved queries apart from its connections, and TablePro keeps each with a connection + + + The {0} export file has no saved queries + + + Continue + + + Import + + + Reading connections from {0}... + + + The files of {0} aren't where it keeps them. + + + {0} has no saved connections to import. + + + The connections of {0} couldn't be read. Its files may be from a version TablePro doesn't know. + + + Your saved connections couldn't be read, so nothing was imported. + + + The connections couldn't be read. + + + Passwords stay where {0} keeps them, which Windows doesn't let TablePro read. Enter them when you connect. + + + Some passwords weren't read. Enter them when you connect. + + + Connections + + + Saved queries + + + If the connection is already there + + + Add + + + Add as copy + + + Replace + + + Keep existing, add queries + + + Matches “{0}” + + + TablePro can't open {0} connections + + + SSH private key not found: {0} + + + Jump host key not found: {0} + + + CA certificate not found: {0} + + + Client certificate not found: {0} + + + Client key not found: {0} + + + SSL {0} becomes {1} + + + Its TLS settings couldn't be read, so it would connect without TLS + + + SSL {0} is on because the other app encrypts this connection by default + + + SSL {0} isn't kept: this engine connects without TLS + + + CA certificate {0} isn't kept: {1} + + + The client certificate isn't kept: {0} + + + The SSH tunnel isn't kept: a database file opens on this PC + + + SSH key {0} isn't kept + + + Jump host {0} isn't kept + + + Jump host {0} signs in through the SSH agent or the SSH config + + + The key {1} of jump host {0} isn't kept + + + Not kept: {0} + + + Disabled + + + Preferred + + + Required + + + Verify CA + + + Verify identity + + + this engine doesn't take one + + + the SSL mode doesn't use it + + + its path isn't a full path + + + a certificate needs its key, and a key its certificate + + + On {0} + + + Not imported: TablePro keeps each saved query with a connection + + + Not imported: its connection isn't imported + + + Not imported: larger than a saved query can be + + + Not imported: its name is longer than a saved query's can be + + + Another query of this name is imported for its connection + + + {0} of 1 connection selected + + + {0} of {1} connections selected + + + {0} of 1 saved query selected + + + {0} of {1} saved queries selected + + + Importing... + + + Imported 1 connection. + + + Imported {0} connections. + + + Added 1 saved query. + + + Added {0} saved queries. + + + 1 saved query couldn't be added. + + + {0} saved queries couldn't be added. + + + 1 password couldn't be kept in Credential Manager. + + + {0} passwords couldn't be kept in Credential Manager. + + + Nothing was imported. + + + The saved connections changed while you were deciding. Import again. + + + Nothing was imported. + + + Preview SQL + + + Running the query will discard all unsaved changes. + + + Switching the database will discard all unsaved changes. + + + Rows of this result can't be duplicated, since some values were read as text that may not name them exactly. + + + The save may have been written. Discard the changes to read the rows again before you save again. + + + The last save may have been written. Discard the changes to read the rows again before you save. + + + Only the rows of one SELECT can be edited. + + + Rows from more than one table, a subquery or a CTE can't be edited. + + + Grouped, distinct or computed rows can't be edited. + + + Only rows read straight from a table can be edited. + + + The result leaves out part of the table's primary key, so its rows can't be edited. + + + Rows of a table without a primary key can't be edited. + + + These rows can't be edited here, because their key can't be read back exactly. + + + The table changed since the query ran. Run it again to edit its rows. + + + Rows can be edited when the run returns one result. + + + Rows read inside an open transaction can't be edited here. + + + The server doesn't say whether a transaction is open, so these rows can't be edited here. + + + Rows from another database than the connection's can't be edited here. + + + The table's columns couldn't be read, so its rows can't be edited. + + + Run the query again to edit its rows. + New from URL diff --git a/windows/src/TablePro.App/Views/HomeView.xaml b/windows/src/TablePro.App/Views/HomeView.xaml index ff27f7f67a..65fc1819cb 100644 --- a/windows/src/TablePro.App/Views/HomeView.xaml +++ b/windows/src/TablePro.App/Views/HomeView.xaml @@ -51,7 +51,14 @@ - + + + + + + + + @@ -106,8 +113,14 @@ - + + + + + + + diff --git a/windows/src/TablePro.App/Views/HomeView.xaml.cs b/windows/src/TablePro.App/Views/HomeView.xaml.cs index 460325d1ad..54b9075de3 100644 --- a/windows/src/TablePro.App/Views/HomeView.xaml.cs +++ b/windows/src/TablePro.App/Views/HomeView.xaml.cs @@ -1167,6 +1167,12 @@ private static bool InPopup(DependencyObject? element, XamlRoot root) private async void OnImport(object sender, RoutedEventArgs e) => await _shell.ImportAsync().ConfigureAwait(true); + private async void OnImportFromApp(object sender, RoutedEventArgs e) => + await _shell.ImportFromAppAsync().ConfigureAwait(true); + + private void OnImportCard(object sender, RoutedEventArgs e) => + FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender); + 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); diff --git a/windows/src/TablePro.App/Views/IShell.cs b/windows/src/TablePro.App/Views/IShell.cs index bf344d842c..7a661f8310 100644 --- a/windows/src/TablePro.App/Views/IShell.cs +++ b/windows/src/TablePro.App/Views/IShell.cs @@ -18,6 +18,8 @@ internal interface IShell Task ImportAsync(); + Task ImportFromAppAsync(); + Task OpenSampleAsync(); void ShowSettings(); diff --git a/windows/src/TablePro.App/Views/ImportFromAppDialog.cs b/windows/src/TablePro.App/Views/ImportFromAppDialog.cs new file mode 100644 index 0000000000..0817726d24 --- /dev/null +++ b/windows/src/TablePro.App/Views/ImportFromAppDialog.cs @@ -0,0 +1,835 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using Microsoft.Windows.Storage.Pickers; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.Interop; + +namespace TablePro.App.Views; + +// Another app's saved connections and queries, as the macOS Import from Other App sheet brings them in. +internal static class ImportFromAppDialog +{ + private const double DialogWidth = 680; + private const double ConnectionsHeight = 320; + private const double QueriesHeight = 180; + private const double ResolutionWidth = 220; + private const double NoteIndent = 28; + + // Null when cancelled before Import, or another dialog holds the window. + public static async Task RunAsync(FrameworkElement owner, Workbench workbench) + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(workbench); + if (WindowDialogs.IsOpen(owner.XamlRoot)) + { + return null; + } + + var importer = new CoreForeignImporter(workbench.Core, ForeignAppDirs.ForCurrentUser()); + using var sheet = new Sheet(owner, workbench, importer); + return await sheet.ShowAsync().ConfigureAwait(true); + } + + public static string Describe(ForeignImportEnding ending) + { + ArgumentNullException.ThrowIfNull(ending); + return string.Join(' ', ending.Sentences + .Select(sentence => Sentence(sentence, ending.Error)) + .Where(text => text.Length > 0)); + } + + public static InfoBarSeverity Severity(ForeignImportEnding ending) + { + ArgumentNullException.ThrowIfNull(ending); + return ending switch + { + { Outdated: true } or { Partial: true } => InfoBarSeverity.Warning, + { Error: not null } => InfoBarSeverity.Error, + { Nothing: true } => InfoBarSeverity.Informational, + _ => InfoBarSeverity.Success, + }; + } + + private static string Sentence(ForeignImportSentence sentence, CoreError? error) => sentence.Part switch + { + ForeignImportPart.Nothing => Strings.Get("ImportAppDone_Nothing"), + ForeignImportPart.Outdated => Strings.Get("ImportAppDone_Outdated"), + ForeignImportPart.Failed when error is not null => + $"{Strings.Get("ImportAppDone_Failed")} {Strings.Error(error)}", + ForeignImportPart.Failed => Strings.Get("ImportAppDone_Failed"), + _ when sentence.Count == 1 => Strings.Get($"ImportAppDone_{sentence.Part}One"), + _ => Strings.Format($"ImportAppDone_{sentence.Part}Many", sentence.Count), + }; + + // 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 Style Strong => (Style)Application.Current.Resources["BodyStrongTextBlockStyle"]; + + private static TextBlock Secondary(string text, double indent = 0) => new() + { + Text = text, + Style = Caption, + TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(indent, 0, 0, 0), + Visibility = text.Length > 0 ? Visibility.Visible : Visibility.Collapsed, + }; + + 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; + } + + private static string SourceText(ForeignSource source) + { + switch (ForeignImportForm.NoteFor(source)) + { + case ForeignSourceNote.PicksFile: + return Strings.Get("ImportAppSourceFile"); + case ForeignSourceNote.NotFound: + return Strings.Get("ImportAppSourceNotFound"); + } + + var connections = source.Connections == 1 + ? Strings.Get("ImportAppSourceConnectionsOne") + : Strings.Format("ImportAppSourceConnectionsMany", source.Connections); + if (source.SavedQueries == 0) + { + return connections; + } + + var queries = source.SavedQueries == 1 + ? Strings.Get("ImportAppSourceQueriesOne") + : Strings.Format("ImportAppSourceQueriesMany", source.SavedQueries); + return $"{connections} · {queries}"; + } + + private static string ResolutionText(ForeignResolution resolution) => resolution switch + { + ForeignResolution.AddCopy => Strings.Get("ImportAppResolution_AddCopy"), + ForeignResolution.Replace => Strings.Get("ImportAppResolution_Replace"), + ForeignResolution.KeepExisting => Strings.Get("ImportAppResolution_KeepExisting"), + _ => Strings.Get("ImportAppResolution_Add"), + }; + + private static string NoteText(ForeignRowNote note) => note switch + { + ForeignRowNote.UnsupportedEngine unsupported => + Strings.Format("ImportAppNote_UnsupportedEngine", unsupported.Engine), + ForeignRowNote.SshKeyMissing missing => Strings.Format("ImportAppNote_SshKeyMissing", missing.Path), + ForeignRowNote.JumpHostKeyMissing missing => Strings.Format("ImportAppNote_JumpHostKeyMissing", missing.Path), + ForeignRowNote.CaCertificateMissing missing => + Strings.Format("ImportAppNote_CaCertificateMissing", missing.Path), + ForeignRowNote.ClientCertificateMissing missing => + Strings.Format("ImportAppNote_ClientCertificateMissing", missing.Path), + ForeignRowNote.ClientKeyMissing missing => Strings.Format("ImportAppNote_ClientKeyMissing", missing.Path), + ForeignRowNote.TlsModeChanged changed => Strings.Format( + "ImportAppNote_TlsModeChanged", + SslName(changed.From), + Strings.Get("TlsMode_" + changed.To)), + ForeignRowNote.TlsSettingsNotRead => Strings.Get("ImportAppNote_TlsSettingsNotRead"), + ForeignRowNote.TlsFromDriverDefault from => + Strings.Format("ImportAppNote_TlsFromDriverDefault", SslName(from.Mode)), + ForeignRowNote.TlsNotKept dropped => Strings.Format("ImportAppNote_TlsNotKept", SslName(dropped.From)), + ForeignRowNote.CaFileNotKept dropped => + Strings.Format("ImportAppNote_CaFileNotKept", dropped.Path, ReasonText(dropped.Reason)), + ForeignRowNote.ClientIdentityNotKept dropped => + Strings.Format("ImportAppNote_ClientIdentityNotKept", ReasonText(dropped.Reason)), + ForeignRowNote.SshNotKept => Strings.Get("ImportAppNote_SshNotKept"), + ForeignRowNote.SshKeyNotKept dropped => Strings.Format("ImportAppNote_SshKeyNotKept", dropped.Path), + ForeignRowNote.JumpHostNotKept dropped => Strings.Format("ImportAppNote_JumpHostNotKept", dropped.Host), + ForeignRowNote.JumpHostPasswordNotKept dropped => + Strings.Format("ImportAppNote_JumpHostPasswordNotKept", dropped.Host), + ForeignRowNote.JumpHostKeyNotKept dropped => + Strings.Format("ImportAppNote_JumpHostKeyNotKept", dropped.Host, dropped.Path), + ForeignRowNote.FieldsNotKept dropped => + Strings.Format("ImportAppNote_FieldsNotKept", string.Join(", ", dropped.Fields)), + _ => string.Empty, + }; + + private static string SslName(ForeignSslMode mode) => Strings.Get("ImportAppSsl_" + mode); + + private static string ReasonText(TlsFileReason reason) => Strings.Get("ImportAppFileReason_" + reason); + + private static string QueryText(ForeignQueryLine line) => line.Availability switch + { + null or ForeignQueryAvailability.Available => line.Row.ConnectionName is { } connection + ? Strings.Format("ImportAppQueryOn", connection) + : string.Empty, + { } availability => Strings.Get("ImportAppQuery_" + availability), + }; + + private static string SummaryText(ForeignImportSummary summary) + { + var connections = summary.Connections == 1 + ? Strings.Format("ImportAppSummaryConnectionsOne", summary.SelectedConnections) + : Strings.Format("ImportAppSummaryConnectionsMany", summary.SelectedConnections, summary.Connections); + if (summary.Queries == 0) + { + return connections; + } + + var queries = summary.Queries == 1 + ? Strings.Format("ImportAppSummaryQueriesOne", summary.IncludedQueries) + : Strings.Format("ImportAppSummaryQueriesMany", summary.IncludedQueries, summary.Queries); + return $"{connections}\n{queries}"; + } + + // Offered is what the box lists, which a Replace another row takes changes. + private sealed class ConnectionRow(string reference, CheckBox check, ComboBox? resolution) + { + public string Reference => reference; + + public CheckBox Check => check; + + public ComboBox? Resolution => resolution; + + public IReadOnlyList Offered { get; set; } = []; + } + + private sealed record QueryRow(string Reference, CheckBox Check, TextBlock Note); + + // One dialog from the app to the review; each step stays in it, and Import closes it once the write is done. + private sealed class Sheet : IDisposable + { + private readonly FrameworkElement _owner; + private readonly Workbench _workbench; + private readonly ForeignImportForm _form; + private readonly ContentDialog _dialog; + private readonly CancellationTokenSource _closed = new(); + + // The reads and the import run on the form, which is disposed once they end. + private readonly List _pending = []; + + private readonly StackPanel _choosePage = new() { Spacing = 16 }; + private readonly StackPanel _looking = new() { Orientation = Orientation.Horizontal, Spacing = 12 }; + private readonly RadioButtons _sources = new(); + private readonly CheckBox _passwords = new(); + private readonly TextBlock _passwordsNote = Secondary(string.Empty, NoteIndent); + private readonly CheckBox _queries = new(); + private readonly TextBlock _queriesNote = Secondary(string.Empty, NoteIndent); + private readonly InfoBar _failure = new() { IsClosable = false, Severity = InfoBarSeverity.Error }; + + private readonly StackPanel _readingPage = new() { Orientation = Orientation.Horizontal, Spacing = 12 }; + private readonly TextBlock _readingText = new() { TextWrapping = TextWrapping.Wrap }; + + private readonly StackPanel _reviewPage = new() { Spacing = 12 }; + private readonly InfoBar _passwordNotice = new() { IsClosable = false, Severity = InfoBarSeverity.Warning }; + private readonly ListView _connectionList = new() { SelectionMode = ListViewSelectionMode.None }; + private readonly TextBlock _queriesHeader = new() { Style = Strong }; + private readonly ListView _queryList = new() { SelectionMode = ListViewSelectionMode.None }; + private readonly TextBlock _summary = new() { TextWrapping = TextWrapping.Wrap }; + private readonly List _connectionRows = []; + private readonly List _queryRows = []; + + private ForeignImportEnding? _ending; + private bool _picking; + + // Set while the boxes are set from the form, whose events then are not the user's. + private bool _filling; + + public Sheet(FrameworkElement owner, Workbench workbench, IForeignImporter importer) + { + _owner = owner; + _workbench = workbench; + _form = new ForeignImportForm(importer); + LayOutChoose(); + LayOutReading(); + LayOutReview(); + _dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = Strings.Get("ImportAppTitle"), + Content = _choosePage, + PrimaryButtonText = Strings.Get("ImportAppContinue"), + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Primary, + IsPrimaryButtonEnabled = false, + }; + // ContentDialog caps its width at 548 by default, too narrow for a row and its resolution. + _dialog.Resources["ContentDialogMaxWidth"] = DialogWidth; + AutomationProperties.SetAutomationId(_dialog, "ImportFromAppDialog"); + _dialog.PrimaryButtonClick += OnPrimary; + _dialog.Closing += OnClosing; + } + + // The ending once Import ran, refused or not, else null. + public async Task ShowAsync() + { + Track(LoadAsync()); + await WindowDialogs.ShowAsync(_dialog, _owner).ConfigureAwait(true); + await _closed.CancelAsync().ConfigureAwait(true); + await Task.WhenAll(_pending).ConfigureAwait(true); + return _ending; + } + + public void Dispose() + { + _form.Dispose(); + _closed.Dispose(); + } + + private void LayOutChoose() + { + _looking.Children.Add(new ProgressRing { IsActive = true, Width = 20, Height = 20 }); + _looking.Children.Add(new TextBlock + { + Text = Strings.Get("ImportAppLooking"), + VerticalAlignment = VerticalAlignment.Center, + }); + _choosePage.Children.Add(_looking); + + _sources.Header = Strings.Get("ImportAppSourcesHeader"); + Named(_sources, "ImportAppSources", Strings.Get("ImportAppSourcesHeader")); + _sources.SelectionChanged += (_, _) => OnSourceChosen(); + _choosePage.Children.Add(_sources); + + _choosePage.Children.Add(Option(_passwords, _passwordsNote, "ImportAppPasswords")); + _passwords.Checked += (_, _) => OnOption(); + _passwords.Unchecked += (_, _) => OnOption(); + _choosePage.Children.Add(Option(_queries, _queriesNote, "ImportAppQueries")); + _queries.Checked += (_, _) => OnOption(); + _queries.Unchecked += (_, _) => OnOption(); + + _choosePage.Children.Add(Named(_failure, "ImportAppFailure")); + } + + private static StackPanel Option(CheckBox box, TextBlock note, string name) + { + box.Content = Strings.Get(name); + Named(box, name, Strings.Get(name)); + var panel = new StackPanel { Spacing = 2 }; + panel.Children.Add(box); + panel.Children.Add(Named(note, name + "Note")); + return panel; + } + + private void LayOutReading() + { + _readingPage.Children.Add(new ProgressRing { IsActive = true, Width = 20, Height = 20 }); + _readingText.VerticalAlignment = VerticalAlignment.Center; + _readingPage.Children.Add(Named(_readingText, "ImportAppReading")); + } + + private void LayOutReview() + { + _reviewPage.Children.Add(Named(_passwordNotice, "ImportAppPasswordNotice")); + var connections = Strings.Get("ImportAppConnectionsHeader"); + _reviewPage.Children.Add(new TextBlock { Text = connections, Style = Strong }); + _connectionList.MaxHeight = ConnectionsHeight; + _reviewPage.Children.Add(Named(_connectionList, "ImportAppConnections", connections)); + _queriesHeader.Text = Strings.Get("ImportAppQueriesHeader"); + _reviewPage.Children.Add(_queriesHeader); + _queryList.MaxHeight = QueriesHeight; + _reviewPage.Children.Add(Named(_queryList, "ImportAppQueryList", Strings.Get("ImportAppQueriesHeader"))); + _reviewPage.Children.Add(Named(_summary, "ImportAppSummary")); + } + + private void Track(Task task) + { + _pending.RemoveAll(each => each.IsCompleted); + _pending.Add(task); + } + + private async Task LoadAsync() + { + Show(); + await _form.LoadAsync().ConfigureAwait(true); + FillSources(); + Show(); + } + + private void FillSources() + { + _filling = true; + try + { + foreach (var source in _form.Sources) + { + var subtitle = SourceText(source); + var content = new StackPanel(); + content.Children.Add(new TextBlock { Text = source.Name }); + content.Children.Add(Secondary(subtitle)); + var button = Named( + new RadioButton { Content = content, IsEnabled = source.IsAvailable, Tag = source.App }, + "ImportAppSource_" + source.App, + source.Name); + AutomationProperties.SetHelpText(button, subtitle); + _sources.Items.Add(button); + } + + _sources.SelectedIndex = _form.Chosen is { } chosen + ? _form.Sources.ToList().FindIndex(source => source.App == chosen.App) + : -1; + } + finally + { + _filling = false; + } + } + + private void OnSourceChosen() + { + if (_filling || _sources.SelectedItem is not RadioButton { Tag: ForeignApp app }) + { + return; + } + + _form.Choose(app); + Show(); + } + + private void OnOption() + { + if (_filling) + { + return; + } + + _form.SetPasswords(_passwords.IsChecked == true); + _form.SetQueries(_queries.IsChecked == true); + } + + private void Show() + { + switch (_form.Step) + { + case ForeignImportStep.Loading: + case ForeignImportStep.Choosing: + ShowChoose(); + break; + case ForeignImportStep.Reading: + _dialog.Content = _readingPage; + _dialog.PrimaryButtonText = string.Empty; + _readingText.Text = Strings.Format("ImportAppReading", AppName); + break; + default: + _dialog.Title = Strings.Format("ImportAppReviewTitle", AppName); + _dialog.Content = _reviewPage; + _dialog.PrimaryButtonText = Strings.Get("ImportAppAction"); + RefreshReview(); + break; + } + } + + private string AppName => _form.Chosen?.Name ?? string.Empty; + + private void ShowChoose() + { + var loading = _form.Step == ForeignImportStep.Loading; + _dialog.Title = Strings.Get("ImportAppTitle"); + _dialog.Content = _choosePage; + _dialog.PrimaryButtonText = Strings.Get("ImportAppContinue"); + _dialog.IsPrimaryButtonEnabled = _form.CanContinue && !_picking; + _looking.Visibility = loading ? Visibility.Visible : Visibility.Collapsed; + _sources.Visibility = loading || _form.Sources.Count == 0 ? Visibility.Collapsed : Visibility.Visible; + + var passwords = _form.Passwords; + var queries = _form.Queries; + _filling = true; + try + { + _passwords.IsEnabled = passwords.Offered; + _passwords.IsChecked = passwords.Checked; + _queries.IsEnabled = queries.Offered; + _queries.IsChecked = queries.Checked; + } + finally + { + _filling = false; + } + + _passwordsNote.Text = _form.Chosen is null + ? string.Empty + : Strings.Format("ImportAppPasswords_" + passwords.Note, AppName); + _queriesNote.Text = _form.Chosen is null + ? string.Empty + : Strings.Format("ImportAppQueries_" + queries.Support, AppName); + _passwordsNote.Visibility = _passwordsNote.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + _queriesNote.Visibility = _queriesNote.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + AutomationProperties.SetHelpText(_passwords, _passwordsNote.Text); + AutomationProperties.SetHelpText(_queries, _queriesNote.Text); + + var failure = _form.Failure is { } read ? FailureText(read) + : _form.SourcesError is not null ? Strings.Get("ImportAppSourcesFailed") + : null; + ShowMessage(_failure, failure); + } + + private string FailureText(ForeignReadFailure failure) => failure.Kind switch + { + ForeignReadFailureKind.Library or ForeignReadFailureKind.Other => + Strings.Get("ImportAppRead_" + failure.Kind), + _ => Strings.Format( + "ImportAppRead_" + failure.Kind, + _form.Sources.FirstOrDefault(source => source.App == failure.App)?.Name ?? AppName), + }; + + private static void ShowMessage(InfoBar bar, string? text) + { + if (text is null) + { + bar.IsOpen = false; + return; + } + + if (bar.IsOpen && bar.Message == text) + { + return; + } + + bar.Message = text; + AutomationProperties.SetName(bar, text); + // Narrator reads an InfoBar when it opens, not when its text changes. + bar.IsOpen = false; + bar.IsOpen = true; + } + + private void OnPrimary(ContentDialog sender, ContentDialogButtonClickEventArgs args) + { + args.Cancel = true; + switch (_form.Step) + { + case ForeignImportStep.Choosing: + Track(ContinueAsync()); + break; + case ForeignImportStep.Reviewing: + Track(ImportAsync()); + break; + } + } + + // The write cannot stop halfway, so the dialog stays until it ends; a read is cancelled with it. + private void OnClosing(ContentDialog sender, ContentDialogClosingEventArgs args) + { + if (_form.Step == ForeignImportStep.Importing) + { + args.Cancel = true; + return; + } + + _closed.Cancel(); + } + + private async Task ContinueAsync() + { + if (_picking || !_form.CanContinue || _form.Chosen is not { } source) + { + return; + } + + string? file = null; + if (source.PicksFile) + { + _picking = true; + _dialog.IsPrimaryButtonEnabled = false; + try + { + file = await PickFileAsync(source).ConfigureAwait(true); + } + finally + { + _picking = false; + } + + if (file is null || _closed.IsCancellationRequested) + { + Show(); + return; + } + } + + var reading = _form.ReadAsync(file, _closed.Token); + Show(); + if (await reading.ConfigureAwait(true)) + { + BuildReview(); + } + + if (!_closed.IsCancellationRequested) + { + Show(); + } + } + + // The picker belongs to the window the dialog is in. + private async Task PickFileAsync(ForeignSource source) + { + if (_owner.XamlRoot is not { } root) + { + return null; + } + + var picker = new FileOpenPicker(root.ContentIslandEnvironment.AppWindowId) + { + SuggestedStartLocation = PickerLocationId.DocumentsLibrary, + }; + foreach (var extension in source.FileExtensions) + { + picker.FileTypeFilter.Add("." + extension.TrimStart('.')); + } + + var result = await picker.PickSingleFileAsync(); + return result?.Path; + } + + private async Task ImportAsync() + { + if (!_form.CanImport) + { + return; + } + + var importing = _form.ImportAsync(); + _dialog.IsPrimaryButtonEnabled = false; + _connectionList.IsEnabled = false; + _queryList.IsEnabled = false; + _summary.Text = Strings.Get("ImportAppImporting"); + _ending = await importing.ConfigureAwait(true); + _dialog.Hide(); + } + + private void BuildReview() + { + _connectionList.Items.Clear(); + _connectionRows.Clear(); + _queryList.Items.Clear(); + _queryRows.Clear(); + foreach (var line in _form.Connections) + { + _connectionList.Items.Add(ConnectionItem(line)); + } + + foreach (var line in _form.SavedQueries) + { + _queryList.Items.Add(QueryItem(line)); + } + + var queries = _form.SavedQueries.Count > 0 ? Visibility.Visible : Visibility.Collapsed; + _queriesHeader.Visibility = queries; + _queryList.Visibility = queries; + ShowMessage(_passwordNotice, _form.PasswordOutcome switch + { + ForeignPasswordOutcome.LeftBehind => Strings.Format("ImportAppPasswordsLeftBehind", AppName), + ForeignPasswordOutcome.Stopped => Strings.Get("ImportAppPasswordsStopped"), + _ => null, + }); + } + + private ListViewItem ConnectionItem(ForeignConnectionLine line) + { + var lines = ConnectionLines(line.Row); + var text = new StackPanel(); + text.Children.Add(new TextBlock { Text = line.Row.Name, TextTrimming = TextTrimming.CharacterEllipsis }); + text.Children.Add(Secondary(string.Join('\n', lines))); + var check = Named( + new CheckBox + { + Content = text, + IsEnabled = line.Selectable, + HorizontalAlignment = HorizontalAlignment.Stretch, + }, + "ImportAppRow_" + line.Reference, + line.Row.Name); + AutomationProperties.SetHelpText(check, string.Join(". ", lines)); + + var grid = new Grid { ColumnSpacing = 12, Padding = new Thickness(0, 4, 0, 4) }; + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + grid.Children.Add(check); + + ComboBox? resolution = null; + if (line.Row.Duplicate is not null) + { + resolution = Named( + new ComboBox { Width = ResolutionWidth, VerticalAlignment = VerticalAlignment.Top }, + "ImportAppResolution_" + line.Reference, + Strings.Get("ImportAppResolution")); + ToolTipService.SetToolTip(resolution, Strings.Get("ImportAppResolution")); + Grid.SetColumn(resolution, 1); + grid.Children.Add(resolution); + } + + var row = new ConnectionRow(line.Reference, check, resolution); + check.Checked += (_, _) => OnSelected(row, true); + check.Unchecked += (_, _) => OnSelected(row, false); + if (resolution is not null) + { + resolution.SelectionChanged += (_, _) => OnResolved(row); + } + + _connectionRows.Add(row); + return Item(grid, line.Row.Name); + } + + private ListViewItem QueryItem(ForeignQueryLine line) + { + var note = Secondary(QueryText(line)); + var text = new StackPanel(); + text.Children.Add(new TextBlock { Text = line.Row.Name, TextTrimming = TextTrimming.CharacterEllipsis }); + text.Children.Add(note); + var check = Named( + new CheckBox { Content = text, HorizontalAlignment = HorizontalAlignment.Stretch }, + "ImportAppQuery_" + line.Reference, + line.Row.Name); + var row = new QueryRow(line.Reference, check, note); + check.Checked += (_, _) => OnIncluded(row, true); + check.Unchecked += (_, _) => OnIncluded(row, false); + _queryRows.Add(row); + return Item(check, line.Row.Name); + } + + private static ListViewItem Item(UIElement content, string name) + { + var item = new ListViewItem + { + Content = content, + HorizontalContentAlignment = HorizontalAlignment.Stretch, + }; + AutomationProperties.SetName(item, name); + return item; + } + + // Where it connects, where it lands, what it matches and what it loses, a line each. + private List ConnectionLines(ForeignConnectionRow row) + { + List lines = [row.Connection is { } saved ? Describe(saved) : row.Engine]; + if (row.GroupPath.Count > 0) + { + lines.Add(string.Join(" / ", row.GroupPath)); + } + + if (row.Duplicate is { } existing) + { + lines.Add(Strings.Format("ImportAppMatches", existing.Name)); + } + + lines.AddRange(row.Notes.Select(NoteText).Where(note => note.Length > 0)); + return lines; + } + + // As the Connections page words a connection. + private string Describe(SavedConnection saved) + { + var engine = _workbench.EngineName(saved.EngineId); + return $"{engine} {ConnectionSearch.Describe(saved, _workbench.IsFileEngine(saved.EngineId))}"; + } + + private void OnSelected(ConnectionRow row, bool selected) + { + if (_filling) + { + return; + } + + _form.SetSelected(row.Reference, selected); + RefreshReview(); + } + + private void OnResolved(ConnectionRow row) + { + if (_filling || row.Resolution is not { SelectedIndex: >= 0 } box || box.SelectedIndex >= row.Offered.Count) + { + return; + } + + _form.Resolve(row.Reference, row.Offered[box.SelectedIndex]); + RefreshReview(); + } + + // Even an unchanged answer is drawn again, so a box always shows what the import takes. + private void OnIncluded(QueryRow row, bool included) + { + if (_filling) + { + return; + } + + _form.SetIncluded(row.Reference, included); + RefreshReview(); + } + + // A change can move another row: a Replace one row takes leaves the others, and a query follows its connection. + private void RefreshReview() + { + _filling = true; + try + { + foreach (var (row, line) in _connectionRows.Zip(_form.Connections)) + { + if (row.Check.IsChecked != line.Selected) + { + row.Check.IsChecked = line.Selected; + } + + if (row.Resolution is { } box) + { + Resolutions(row, box, line); + } + } + + foreach (var (row, line) in _queryRows.Zip(_form.SavedQueries)) + { + if (row.Check.IsChecked != line.Included) + { + row.Check.IsChecked = line.Included; + } + + row.Check.IsEnabled = line.Importable; + row.Note.Text = QueryText(line); + row.Note.Visibility = row.Note.Text.Length > 0 ? Visibility.Visible : Visibility.Collapsed; + AutomationProperties.SetHelpText(row.Check, row.Note.Text); + } + } + finally + { + _filling = false; + } + + var importing = _form.Step == ForeignImportStep.Importing; + _summary.Text = importing ? Strings.Get("ImportAppImporting") : SummaryText(_form.Summary); + _dialog.IsPrimaryButtonEnabled = _form.CanImport; + } + + private static void Resolutions(ConnectionRow row, ComboBox box, ForeignConnectionLine line) + { + if (!row.Offered.SequenceEqual(line.Offered)) + { + box.Items.Clear(); + foreach (var offered in line.Offered) + { + box.Items.Add(ResolutionText(offered)); + } + + row.Offered = line.Offered; + } + + var index = line.Resolution is { } chosen ? IndexOf(line.Offered, chosen) : -1; + box.SelectedIndex = index >= 0 ? index : Math.Min(0, line.Offered.Count - 1); + box.Visibility = line.ShowsResolution ? Visibility.Visible : Visibility.Collapsed; + box.IsEnabled = line.CanResolve; + } + + private static int IndexOf(IReadOnlyList offered, ForeignResolution chosen) + { + for (var index = 0; index < offered.Count; index++) + { + if (offered[index] == chosen) + { + return index; + } + } + + return -1; + } + } +} diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml b/windows/src/TablePro.App/Views/QueryTabView.xaml index 3913ee24e7..1c839909ea 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml @@ -42,6 +42,11 @@ + + + + + diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs index a7c116e02c..af0940f9e1 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs @@ -9,16 +9,21 @@ using TablePro.App.Model; using TablePro.App.Services; using TablePro.DataGrid; +using TablePro.DataGrid.Model; using TablePro.Editor; using TablePro.Interop; namespace TablePro.App.Views; -// The editor over the run's results; the run, the close and the transaction are QueryTab's. -public sealed partial class QueryTabView : UserControl, ITabContent, IQueryTabView, IQueryFileView, IShareSource, IExportSource +// The editor over the run's results; the run, the close, the transaction and the result's edits are QueryTab's. +public sealed partial class QueryTabView + : UserControl, ITabContent, IQueryTabView, IQueryFileView, IResultEditView, IShareSource, IExportSource { private readonly QueryTab _model; private EditTarget _target; + + // What the results pane last said, which the status shows again once a save of the rows ends. + private string _resultsStatus = string.Empty; private bool _listingDatabases; private bool _editQueued; private bool _closed; @@ -41,6 +46,12 @@ internal QueryTabView( var engineId = share.Session.EngineId; var restoring = filePath is not null && onDisk is null; InitializeComponent(); + Results.ShowsEdits = true; + var grid = Results.GridView; + grid.DefaultText = Strings.Get("GridDefaultText"); + grid.EditedStatus = Strings.Get("GridEditedStatus"); + grid.NewRowStatus = Strings.Get("GridNewRowStatus"); + grid.DeletedStatus = Strings.Get("GridDeletedStatus"); SqlText.Text = onDisk?.Text ?? sql ?? string.Empty; SqlText.Lexer = new CoreSqlLexer(Grammars.For(engineId)); DisplaySettings.Follow(SqlText); @@ -56,18 +67,32 @@ internal QueryTabView( this, filePath, onDisk, - restoring: restoring); + restoring: restoring, + resultEdits: this); AutomationProperties.SetName(SqlText, Strings.Format("EditorName", _model.Title)); ShowDatabase(); _model.StateChanged += (_, _) => OnModelStateChanged(); _model.FileSaved += (_, path) => FileSaved?.Invoke(this, path); - Results.StatusChanged += (_, status) => StatusText.Text = status; + Results.StatusChanged += (_, status) => + { + _resultsStatus = status; + StatusText.Text = status; + }; Results.SortRequested += async (_, sort) => await _model.SortAsync(sort).ConfigureAwait(true); Results.ResultPicked += (_, _) => _model.ResultPicked(); SqlText.GotFocus += (_, _) => _target = EditTarget.Editor; - Results.GridView.GotFocus += (_, _) => _target = EditTarget.Grid; + grid.GotFocus += (_, _) => + { + _target = EditTarget.Grid; + EditStateMayHaveChanged(); + }; + // The cell editor takes focus as it opens and gives it back as it closes, so Save and the closes follow it. + grid.LostFocus += (_, _) => EditStateMayHaveChanged(); Results.MessagesBox.GotFocus += (_, _) => _target = EditTarget.Messages; - Results.GridView.ContextRequested += OnGridContextRequested; + grid.ContextRequested += OnGridContextRequested; + grid.CellEditStarting += OnCellEditStarting; + grid.CellEditCommitting += OnCellEditCommitting; + grid.DeleteRequested += (_, _) => DeleteRows(); SqlText.ContextMenuOpening += OnEditorMenuOpening; SqlText.TextChanged += OnTextChanged; SqlText.FilesDropped += (_, paths) => OpenFilesRequested?.Invoke(this, paths); @@ -83,6 +108,8 @@ internal QueryTabView( { LoadRestoredFile(fileStamp, fileUnsaved); } + + UpdateEditing(); } private async void LoadRestoredFile(SqlFileStamp? stamp, bool unsaved) => @@ -139,6 +166,9 @@ private async void LoadRestoredFile(SqlFileStamp? stamp, bool unsaved) => internal ResultsPane ResultsView => Results; + // A share sends the rows as the server holds them, so it waits for the result's edits to be saved or dropped. + internal bool HasPendingRows => _model.HasPendingRows; + // The SQL whose results the grid shows. internal string? LastStatement => _model.LastStatement; @@ -174,8 +204,8 @@ private async void LoadRestoredFile(SqlFileStamp? stamp, bool unsaved) => public Task CloseAsync() => _model.CloseAsync(); - // Ctrl+S: to its file, Save As when it has none or the file is gone. - public Task SaveAsync() => _model.SaveAsync(); + // Ctrl+S: the result's rows while the grid has focus and they edit, else the file, as Save As when there is none. + public Task SaveAsync() => GridIsTarget && _model.EditsResult ? _model.SaveRowsAsync() : _model.SaveAsync(); public Task SaveAsAsync() => _model.SaveAsAsync(); @@ -218,7 +248,7 @@ void IQueryTabView.ShowTransaction(TransactionState state, bool changed, bool ca void IQueryTabView.ShowRunning(bool running) { - RunButton.IsEnabled = !running; + RunButton.IsEnabled = !running && !_model.IsSavingRows; StopButton.IsEnabled = running; } @@ -360,6 +390,55 @@ failure is SqlFileEncodingException encoding Task IQueryFileView.ShowReloadFailedAsync(string path, Exception failure) => ShowFileFailedAsync(Strings.Format("FileReloadFailedTitle", Path.GetFileName(path)), failure.Message); + bool IResultEditView.HasOpenEdit => Results.GridView.IsEditing; + + void IResultEditView.ShowEdits() => UpdateEditing(); + + void IResultEditView.ShowSaving(bool saving) + { + RunButton.IsEnabled = !saving && !_model.IsRunning; + StatusText.Text = saving ? Strings.Get("StatusSaving") : _resultsStatus; + } + + void IResultEditView.ShowEditRefusal(EditRefusal refusal) => ShowRefusal(refusal); + + void IResultEditView.ShowSaveCancelled() => StatusText.Text = Strings.Get("SaveCancelled"); + + bool IResultEditView.CommitOpenEdit() => Results.GridView.CommitEdit(); + + void IResultEditView.FocusRow(int row) + { + var grid = Results.GridView; + var column = Math.Max(0, grid.FocusedColumn); + grid.FocusCell(row, column); + grid.ScrollIntoView(row, column); + } + + Task IResultEditView.ConfirmDiscardForReplaceAsync(ResultReplacement reason) => + RowEditDialogs.ConfirmReloadAsync(Owner, Strings.Get(reason switch + { + ResultReplacement.Sort => "ReloadDiscardSort", + ResultReplacement.Database => "ResultEditDiscardDatabase", + _ => "ResultEditDiscardRun", + })); + + Task IResultEditView.ConfirmDiscardAsync() => RowEditDialogs.ConfirmDiscardAsync(Owner); + + Task IResultEditView.AskSaveBeforeCloseAsync(string tab, bool offerSave) => + RowEditDialogs.AskSaveBeforeCloseAsync(Owner, tab, offerSave); + + Task IResultEditView.ConfirmDeleteAsync(string table, int rows) => + RowEditDialogs.ConfirmDeleteAsync(Owner, table, rows); + + Task IResultEditView.ConfirmSaveAsync(string connection, IReadOnlyList statements) => + RowEditDialogs.ConfirmSaveAsync(Owner, connection, statements); + + Task IResultEditView.ShowPreviewAsync(IReadOnlyList statements, CoreError? failure) => + RowEditDialogs.ShowPreviewAsync(Owner, statements, failure is null ? null : Strings.Error(failure)); + + Task IResultEditView.ShowSaveFailedAsync(CoreError failure, bool incomplete) => + RowEditDialogs.ShowSaveFailedAsync(Owner, Strings.Error(failure), incomplete, "ResultEditSaveUnknown"); + private static string EncodingName(SqlFileEncoding encoding) => Strings.Get(encoding switch { SqlFileEncoding.Utf16LittleEndian => "SqlFileEncodingUtf16LittleEndian", @@ -389,6 +468,7 @@ private void OnModelStateChanged() { AutomationProperties.SetName(SqlText, Strings.Format("EditorName", _model.Title)); ShowDatabase(); + UpdateEditing(); StateChanged?.Invoke(this, EventArgs.Empty); } @@ -506,20 +586,246 @@ private async void OnFileBarAction(object sender, RoutedEventArgs e) // Built when asked for, since a menu keeps the window it first opened in and a tab can move to another. private void OnGridContextRequested(UIElement sender, ContextRequestedEventArgs args) { - args.Handled = true; var grid = Results.GridView; + // The editor's TextBox shows its own menu; a right-click on another cell keeps the edit first. + if (grid.IsEditing && (grid.IsInEditor(args.OriginalSource) || !grid.CommitEdit())) + { + return; + } + + args.Handled = true; // Rows still arriving would be exported or shared as if they were all of them. var finished = !IsRunning && Results.ShownSet is { IsFinished: true }; var menu = new MenuFlyout(); + if (_model.EditsResult) + { + AddEditItems(menu, grid.FocusedRow, grid.FocusedColumn); + } + menu.Items.Add(GridMenus.Copy(grid)); menu.Items.Add(GridMenus.ViewValue(Results)); menu.Items.Add(new MenuFlyoutSeparator()); menu.Items.Add(GridMenus.Item("GridMenuExport", finished, () => ExportRequested?.Invoke(this, EventArgs.Empty))); menu.Items.Add(GridMenus.Item( - "ShareResultCommand", finished, () => ShareRequested?.Invoke(this, ShareKind.Result), Symbol.Share)); + "ShareResultCommand", + finished && !HasPendingRows, + () => ShareRequested?.Invoke(this, ShareKind.Result), + Symbol.Share)); GridMenus.Show(menu, grid, args); } + // As a table tab's menu: a row marked for delete offers only to keep it, as macOS does. + private void AddEditItems(MenuFlyout menu, int row, int column) + { + if (Results.GridView.RowCount > 0 && _model.IsDeleted(row)) + { + menu.Items.Add(GridMenus.Item( + "GridMenuUndoDelete", _model.CanEditResult, () => ShowRefusal(_model.RestoreRows(SelectedRows())))); + } + else + { + var setValue = new MenuFlyoutSubItem + { + Text = Strings.Get("GridMenuSetValue"), + IsEnabled = _model.CanEditResult, + }; + setValue.Items.Add(ValueItem("GridMenuEmpty", row, column, CellValueKind.Empty)); + setValue.Items.Add(ValueItem("GridMenuNull", row, column, CellValueKind.Null)); + setValue.Items.Add(ValueItem("GridMenuDefault", row, column, CellValueKind.Default)); + menu.Items.Add(setValue); + menu.Items.Add(new MenuFlyoutSeparator()); + menu.Items.Add(GridMenus.Item("GridMenuAddRow", _model.CanEditResult, AddRow)); + menu.Items.Add(GridMenus.Item("GridMenuDuplicate", CanChangeRows, DuplicateRows)); + menu.Items.Add(GridMenus.Item("GridMenuDelete", CanChangeRows, DeleteRows)); + } + + menu.Items.Add(new MenuFlyoutSeparator()); + } + + private MenuFlyoutItem ValueItem(string text, int row, int column, CellValueKind kind) => + GridMenus.Item( + text, _model.CanSetValue(row, column, kind), () => ShowRefusal(_model.SetValue(row, column, kind))); + + public bool CanDiscardRows => _model.CanDiscardRows; + + public bool CanPreviewRows => _model.CanPreviewRows; + + public bool CanAddRow => _model.CanEditResult; + + // Duplicate and Delete act on the rows the selection touches. + public bool CanChangeRows => _model.CanEditResult && Results.GridView.RowCount > 0; + + public Task DiscardRowsAsync() => _model.DiscardRowsAsync(); + + public Task PreviewRowsAsync() => _model.PreviewRowsAsync(); + + // The open edit is kept first, and the new row's editor opens on the first column the server does not fill. + public void AddRow() + { + var grid = Results.GridView; + if (!grid.CommitEdit()) + { + return; + } + + if (_model.AddRow(out var row) is { } refusal) + { + ShowRefusal(refusal); + return; + } + + grid.FocusCell(row, _model.FirstColumnToFill); + grid.BeginEdit(); + } + + public void DuplicateRows() + { + var grid = Results.GridView; + if (!grid.CommitEdit()) + { + return; + } + + if (_model.DuplicateRows(SelectedRows(), out var last) is { } refusal) + { + ShowRefusal(refusal); + return; + } + + if (last >= 0) + { + var column = Math.Max(0, grid.FocusedColumn); + grid.FocusCell(last, column); + grid.ScrollIntoView(last, column); + } + } + + public void DeleteRows() + { + if (Results.GridView.CommitEdit()) + { + ShowRefusal(_model.DeleteRows(SelectedRows())); + } + } + + private List SelectedRows() + { + var range = Results.GridView.SelectionRange; + return range.IsEmpty ? [] : [.. Enumerable.Range(range.FirstRow, range.RowCount)]; + } + + // An editor opening or closing counts as a change for Save and the menus. + private void EditStateMayHaveChanged() + { + if (_closed) + { + return; + } + + UpdateEditing(); + StateChanged?.Invoke(this, EventArgs.Empty); + } + + // The grid swaps its edits only when they moved, since EditsChanged reads every cell again. + private void UpdateEditing() + { + var grid = Results.GridView; + if (grid.Data is EditedGridData edited) + { + var edits = _model.ResultEdits?.Snapshot() ?? GridEdits.None; + if (!ReferenceEquals(edited.Edits, edits)) + { + edited.Edits = edits; + grid.EditsChanged(); + } + } + + grid.IsEditable = _model.ResultAcceptsEdits; + var shown = _model.EditsResult ? Visibility.Visible : Visibility.Collapsed; + EditSeparator.Visibility = shown; + SaveChangesButton.Visibility = shown; + DiscardChangesButton.Visibility = shown; + PreviewSqlButton.Visibility = shown; + SaveChangesButton.IsEnabled = _model.CanSaveRows; + DiscardChangesButton.IsEnabled = _model.CanDiscardRows; + PreviewSqlButton.IsEnabled = _model.CanPreviewRows; + } + + private void OnCellEditStarting(object? sender, GridEditStartingEventArgs e) + { + if (_model.StartEdit(e.Row, e.Column, out var text) is { } refusal) + { + e.Cancel = true; + ShowRefusal(refusal); + return; + } + + e.Text = text; + } + + // A refusal keeps the editor open with the reason on it; a focus loss closes the editor, so the status says it too. + private void OnCellEditCommitting(object? sender, GridEditCommittingEventArgs e) + { + if (_model.CommitEdit(e.Row, e.Column, e.Text) is { } refusal) + { + var text = RefusalText(refusal) ?? Strings.Get("EditCellReadOnly"); + e.Error = text; + StatusText.Text = text; + } + } + + // The status is a polite live region, so a refusal is read out where the user is. + private void ShowRefusal(EditRefusal? refusal) + { + if (refusal is not null && RefusalText(refusal) is { } text) + { + StatusText.Text = text; + } + } + + private static string? RefusalText(EditRefusal refusal) => refusal switch + { + EditRefusal.TableLocked locked => LockText(locked.Lock), + EditRefusal.ResultBlocked blocked => BlockText(blocked.Block), + EditRefusal.CellLocked => Strings.Get("EditCellReadOnly"), + EditRefusal.SaveBlocked => Strings.Get("ResultEditSaveBlocked"), + EditRefusal.NotCopyable => Strings.Get("ResultEditNotCopyable"), + EditRefusal.Invalid invalid => Strings.Error(invalid.Failure), + _ => null, + }; + + private static string LockText(EditLock locked) => Strings.Get(locked switch + { + EditLock.ReadOnlyConnection => "EditLockReadOnly", + EditLock.NoPrimaryKey => "ResultEditNoPrimaryKey", + EditLock.KeyUnreadable => "ResultEditKeyUnreadable", + EditLock.NotOneSelect => "ResultEditNotOneSelect", + EditLock.MoreThanOneTable => "ResultEditMoreThanOneTable", + EditLock.Collapsed => "ResultEditCollapsed", + EditLock.Untraced => "ResultEditUntraced", + EditLock.KeyNotShown => "ResultEditKeyNotShown", + _ => "ResultEditColumnsChanged", + }); + + private static string BlockText(ResultEditBlock block) => Strings.Get(block switch + { + ResultEditBlock.SeveralResults => "ResultEditSeveralResults", + ResultEditBlock.OpenTransaction => "ResultEditOpenTransaction", + ResultEditBlock.UnknownTransaction => "ResultEditUnknownTransaction", + ResultEditBlock.OtherDatabase => "ResultEditOtherDatabase", + ResultEditBlock.ColumnsUnread => "ResultEditColumnsUnread", + _ => "ResultEditRunAgain", + }); + + private async void OnSaveChanges(object sender, RoutedEventArgs e) => + await _model.SaveRowsAsync().ConfigureAwait(true); + + private async void OnDiscardChanges(object sender, RoutedEventArgs e) => + await _model.DiscardRowsAsync().ConfigureAwait(true); + + private async void OnPreviewSql(object sender, RoutedEventArgs e) => + await _model.PreviewRowsAsync().ConfigureAwait(true); + private void OnEditorMenuOpening(object? sender, IList items) { var share = new MenuFlyoutItem diff --git a/windows/src/TablePro.App/Views/RowEditDialogs.cs b/windows/src/TablePro.App/Views/RowEditDialogs.cs index b91dd90c32..8dc3a26314 100644 --- a/windows/src/TablePro.App/Views/RowEditDialogs.cs +++ b/windows/src/TablePro.App/Views/RowEditDialogs.cs @@ -112,13 +112,15 @@ public static async Task ShowPreviewAsync(FrameworkElement owner, IReadOnlyList< }); } - public static async Task ShowSaveFailedAsync(FrameworkElement owner, string message, bool incomplete) + // Unknown names how the rows are read again: a table tab's Refresh, a query result's Discard. + public static async Task ShowSaveFailedAsync( + FrameworkElement owner, string message, bool incomplete, string unknown = "SaveUnknownMessage") { var content = new StackPanel { Spacing = 12 }; content.Children.Add(new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, IsTextSelectionEnabled = true }); content.Children.Add(new TextBlock { - Text = Strings.Get(incomplete ? "SaveUnknownMessage" : "SaveFailedPending"), + Text = Strings.Get(incomplete ? unknown : "SaveFailedPending"), TextWrapping = TextWrapping.Wrap, }); await ShowAsync(owner, new ContentDialog diff --git a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs index d09e0c9765..4d108cd2df 100644 --- a/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs +++ b/windows/src/TablePro.App/Views/WorkspaceView.xaml.cs @@ -1081,7 +1081,7 @@ private async void OnShareRequested(object? sender, ShareKind kind) => (QueryTabView query, ShareKind.Query) => query.QueryToShare is var sql && !string.IsNullOrWhiteSpace(sql) ? ShareSubject.Query(sql, query.Title, dialect) : null, - (QueryTabView { IsRunning: false } query, ShareKind.Result) + (QueryTabView { IsRunning: false, HasPendingRows: false } query, ShareKind.Result) when query.ResultsView.ShownSet is { IsFinished: true } rows => ShareSubject.Result(query.LastStatement ?? string.Empty, query.Title, dialect, rows, query.ResultsView.Columns), (TableTabView { IsRunning: false, HasUnsavedChanges: false } table, ShareKind.Result) diff --git a/windows/src/TablePro.Interop/DatabaseSession.cs b/windows/src/TablePro.Interop/DatabaseSession.cs index 06357fe284..b895fd5dfe 100644 --- a/windows/src/TablePro.Interop/DatabaseSession.cs +++ b/windows/src/TablePro.Interop/DatabaseSession.cs @@ -243,6 +243,22 @@ public async Task OpenTableEditorAsync( return new TableEditor(editor); } + // A query result's rows as a save sees them; Lock says why not when the result is not one keyed table's rows. + // Rows is the run's only set, read outside a transaction in the session's database, which the caller checks. + public async Task OpenResultEditorAsync( + string sql, + ResultSet rows, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(sql); + ArgumentNullException.ThrowIfNull(rows); + var editor = await CoreCall.RunAsync( + token => _session.ResultEditor(sql, rows.Handle, token), + cancellationToken) + .ConfigureAwait(false); + return new TableEditor(editor); + } + // The table's foreign keys and the other tables' keys that point at it, read in one operation. public async Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken = default) { diff --git a/windows/src/TablePro.Interop/ForeignImport.cs b/windows/src/TablePro.Interop/ForeignImport.cs new file mode 100644 index 0000000000..0f2bb5e8b2 --- /dev/null +++ b/windows/src/TablePro.Interop/ForeignImport.cs @@ -0,0 +1,300 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +public enum ForeignApp +{ + TablePlus, + SequelAce, + DBeaver, + DataGrip, + BeekeeperStudio, + Navicat, + Dbx, +} + +// Where other apps keep their files: the profile folder, %APPDATA% and %LOCALAPPDATA%. +public sealed record ForeignAppDirs(string Home, string Config, string Data) +{ + public static ForeignAppDirs ForCurrentUser() => new( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); +} + +public enum ForeignPasswordSource +{ + // The system's own store, which another app reads only on macOS; DataGrip can keep them in a KeePass file instead. + Keychain, + // Its own files under a fixed key, decrypted while reading. + AppFiles, +} + +public enum ForeignSavedQuerySupport +{ + // Kept apart from the connections, while TablePro keeps each saved query with a connection. + GlobalFolder, + // Scripts import with the connection they run on; one with a default name starts unchecked. + Scripts, + // Query consoles import with their data source; one with a default name starts unchecked. + Consoles, + NotInExport, +} + +// FileExtensions is set for an app imported from an export file the user picks, which is always available. +public sealed record ForeignSource( + ForeignApp App, + string Name, + bool IsAvailable, + long Connections, + long SavedQueries, + IReadOnlyList FileExtensions, + ForeignPasswordSource Passwords, + ForeignSavedQuerySupport SavedQuerySupport) +{ + public bool PicksFile => FileExtensions.Count > 0; +} + +public sealed record ForeignImportRequest(bool IncludePasswords, bool IncludeSavedQueries); + +public enum ForeignPasswordOutcome +{ + NotRequested, + Read, + // A store was locked or would not open for this user, so the rest were not read. + Stopped, + // The app keeps them where Windows does not let another app read. + LeftBehind, +} + +public enum ForeignSslMode +{ + Disabled, + Preferred, + Required, + VerifyCa, + VerifyIdentity, +} + +public enum TlsFileReason +{ + EngineLacks, + ModeLacks, + RelativePath, + Incomplete, +} + +// What the review says about a connection row. Paths are as the other app wrote them. +public abstract record ForeignRowNote +{ + private ForeignRowNote() + { + } + + public sealed record UnsupportedEngine(string Engine) : ForeignRowNote; + + public sealed record SshKeyMissing(string Path) : ForeignRowNote; + + public sealed record JumpHostKeyMissing(string Path) : ForeignRowNote; + + public sealed record CaCertificateMissing(string Path) : ForeignRowNote; + + public sealed record ClientCertificateMissing(string Path) : ForeignRowNote; + + public sealed record ClientKeyMissing(string Path) : ForeignRowNote; + + public sealed record TlsModeChanged(ForeignSslMode From, TlsMode To) : ForeignRowNote; + + public sealed record TlsSettingsNotRead : ForeignRowNote; + + public sealed record TlsFromDriverDefault(ForeignSslMode Mode) : ForeignRowNote; + + public sealed record TlsNotKept(ForeignSslMode From) : ForeignRowNote; + + public sealed record CaFileNotKept(string Path, TlsFileReason Reason) : ForeignRowNote; + + public sealed record ClientIdentityNotKept(TlsFileReason Reason) : ForeignRowNote; + + public sealed record SshNotKept : ForeignRowNote; + + public sealed record SshKeyNotKept(string Path) : ForeignRowNote; + + public sealed record JumpHostNotKept(string Host) : ForeignRowNote; + + public sealed record JumpHostPasswordNotKept(string Host) : ForeignRowNote; + + public sealed record JumpHostKeyNotKept(string Host, string Path) : ForeignRowNote; + + public sealed record FieldsNotKept(IReadOnlyList Fields) : ForeignRowNote; +} + +public sealed record ExistingConnection(Guid Id, string Name); + +// Connection is the row as it would be saved, null when no engine here opens it; such a row cannot be checked. +public sealed record ForeignConnectionRow( + string Reference, + string Name, + string Engine, + SavedConnection? Connection, + IReadOnlyList GroupPath, + ExistingConnection? Duplicate, + IReadOnlyList Notes, + int SavedQueryCount, + bool CarriesPasswords); + +// Connection is the reference of the connection row it runs on. +public sealed record ForeignQueryRow( + string Reference, + string Name, + string? Connection, + string? ConnectionName, + long ByteCount); + +// What a row does when a saved connection matches it. +public abstract record ForeignResolution +{ + private ForeignResolution() + { + } + + public sealed record Add : ForeignResolution + { + public static Add Instance { get; } = new(); + } + + public sealed record AddCopy : ForeignResolution + { + public static AddCopy Instance { get; } = new(); + } + + // Keeps the saved connection's id and passwords; offered only when both connect the same way. + public sealed record Replace(Guid Id) : ForeignResolution; + + // Writes nothing, so the row's saved queries land on the saved connection. + public sealed record KeepExisting(Guid Id) : ForeignResolution; +} + +// Resolution is kept across an uncheck; Offered leaves out a Replace another checked row took. +public sealed record ForeignConnectionChoice( + string Reference, + bool Selected, + ForeignResolution? Resolution, + IReadOnlyList Offered); + +public enum ForeignQueryAvailability +{ + Available, + // An earlier row takes the same name on the same connection. + AddedByAnotherRow, + TooLarge, + NameTooLong, + // Its connection is not imported, or its Replace went to another row. + ConnectionSkipped, + // The other app filed it under no connection. + NoConnection, +} + +public sealed record ForeignQueryChoice(string Reference, ForeignQueryAvailability Availability, bool Included); + +// Importable is false when the checks write nothing. +public sealed record ForeignImportChoices( + IReadOnlyList Connections, + IReadOnlyList Queries, + bool Importable); + +// PasswordsNotKept: refused by Credential Manager, so those connections ask when they connect. +public sealed record ForeignImportOutcome( + int Connections, + int Replaced, + int PasswordsNotKept, + int QueriesAdded, + int QueriesAlreadySaved, + int QueriesFailed); + +// Another app's connections and saved queries, read once and checked against the library as it was then. +public sealed class ForeignImportReview : IDisposable +{ + private readonly Native.ForeignImportReview _review; + + internal ForeignImportReview(Native.ForeignImportReview review) + { + _review = review; + App = Mapping.ForeignApp(review.App()); + Passwords = Mapping.Outcome(review.Passwords()); + Connections = [.. review.Connections().Select(Mapping.ForeignRow)]; + SavedQueries = [.. review.SavedQueries().Select(query => new ForeignQueryRow( + query.Reference, + query.Name, + query.Connection, + query.ConnectionName, + Mapping.Count(query.ByteCount)))]; + } + + public ForeignApp App { get; } + + public ForeignPasswordOutcome Passwords { get; } + + public IReadOnlyList Connections { get; } + + public IReadOnlyList SavedQueries { get; } + + // Worked out again from the checks, so read it after each change. + public ForeignImportChoices Choices() + { + var choices = CoreCall.Run(_review.Choices); + return new ForeignImportChoices( + [.. choices.Connections.Select(choice => new ForeignConnectionChoice( + choice.Reference, + choice.Selected, + choice.Resolution is { } resolution ? Mapping.Resolution(resolution) : null, + [.. choice.Offered.Select(Mapping.Resolution)]))], + [.. choices.Queries.Select(query => new ForeignQueryChoice( + query.Reference, + Mapping.Availability(query.Availability), + query.Included))], + choices.Importable); + } + + public void SetSelected(string reference, bool selected) + { + ArgumentNullException.ThrowIfNull(reference); + CoreCall.Run(() => + { + _review.SetSelected(reference, selected); + return true; + }); + } + + // False when the row does not offer it, or another checked row took that Replace. + public bool Resolve(string reference, ForeignResolution resolution) + { + ArgumentNullException.ThrowIfNull(reference); + ArgumentNullException.ThrowIfNull(resolution); + return CoreCall.Run(() => _review.Resolve(reference, Mapping.Resolution(resolution))); + } + + public void SetIncluded(string reference, bool included) + { + ArgumentNullException.ThrowIfNull(reference); + CoreCall.Run(() => + { + _review.SetIncluded(reference, included); + return true; + }); + } + + // Once; storage.import_outdated when the library changed since the read, with nothing written. + public async Task ApplyAsync() + { + var outcome = await CoreCall.RunAsync(() => _review.Apply()).ConfigureAwait(false); + return new ForeignImportOutcome( + checked((int)outcome.Connections), + checked((int)outcome.Replaced), + checked((int)outcome.PasswordsNotKept), + checked((int)outcome.QueriesAdded), + checked((int)outcome.QueriesAlreadySaved), + checked((int)outcome.QueriesFailed)); + } + + public void Dispose() => _review.Dispose(); +} diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 7171f9819a..d468686fe0 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -1283,6 +1283,36 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1744,6 +1774,28 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_core_test_connection(ulong @ptr,RustBuffer @record,RustBuffer @secrets,RustBuffer @prompter,RustBuffer @cancel ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_core_foreign_sources(ulong @ptr,RustBuffer @dirs + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_core_read_foreign(ulong @ptr,RustBuffer @app,RustBuffer @dirs,RustBuffer @file,RustBuffer @request,RustBuffer @cancel + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -1964,6 +2016,127 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_favouritestore_tables(ulong @ptr,RustBuffer @connectionId ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_clone_foreignimportreview(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void uniffi_tablepro_ffi_fn_free_foreignimportreview(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_foreignimportreview_app(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_foreignimportreview_apply(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_foreignimportreview_choices(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_foreignimportreview_connections(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_foreignimportreview_passwords(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + sbyte uniffi_tablepro_ffi_fn_method_foreignimportreview_resolve(ulong @ptr,RustBuffer @reference,RustBuffer @resolution,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_foreignimportreview_saved_queries(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void uniffi_tablepro_ffi_fn_method_foreignimportreview_set_included(ulong @ptr,RustBuffer @reference,sbyte @included,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void uniffi_tablepro_ffi_fn_method_foreignimportreview_set_selected(ulong @ptr,RustBuffer @reference,sbyte @selected,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2811,6 +2984,17 @@ public static extern RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_columns(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + sbyte uniffi_tablepro_ffi_fn_method_tableeditor_copies_exactly(ulong @ptr,ulong @rows,ulong @row,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2855,6 +3039,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_tableeditor_plan(ulong @ptr,ulong @rows,RustBuffer @edits,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_tableeditor_table(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3438,6 +3633,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(ulong @ptr,RustBuffer @scope,RustBuffer @cancel ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_databasesession_result_editor(ulong @ptr,RustBuffer @sql,ulong @rows,RustBuffer @cancel + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4703,6 +4909,28 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_core_test_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_core_foreign_sources( + ); + + #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_core_read_foreign( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4854,7 +5082,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_app( ); #if NET8_0_OR_GREATER @@ -4865,7 +5093,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_method_foreignimportreview_apply( ); #if NET8_0_OR_GREATER @@ -4876,7 +5104,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_export( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_choices( ); #if NET8_0_OR_GREATER @@ -4887,7 +5115,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_connections( ); #if NET8_0_OR_GREATER @@ -4898,7 +5126,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_method_foreignimportreview_passwords( ); #if NET8_0_OR_GREATER @@ -4909,7 +5137,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_method_foreignimportreview_resolve( ); #if NET8_0_OR_GREATER @@ -4920,7 +5148,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_saved_queries( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_saved_queries( ); #if NET8_0_OR_GREATER @@ -4931,7 +5159,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_method_foreignimportreview_set_included( ); #if NET8_0_OR_GREATER @@ -4942,7 +5170,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_set_pinned( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_selected( ); #if NET8_0_OR_GREATER @@ -4953,7 +5181,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_columns( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear( ); #if NET8_0_OR_GREATER @@ -4964,7 +5192,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_plan( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete( ); #if NET8_0_OR_GREATER @@ -4975,7 +5203,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_preview( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_export( ); #if NET8_0_OR_GREATER @@ -4986,7 +5214,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_run( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites( ); #if NET8_0_OR_GREATER @@ -4997,7 +5225,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_suggest_mapping( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_prune( ); #if NET8_0_OR_GREATER @@ -5008,7 +5236,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_method_queryhistorystore_record( ); #if NET8_0_OR_GREATER @@ -5019,7 +5247,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_queryhistorystore_saved_queries( ); #if NET8_0_OR_GREATER @@ -5030,7 +5258,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_queryhistorystore_search( ); #if NET8_0_OR_GREATER @@ -5041,7 +5269,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_queryhistorystore_set_pinned( ); #if NET8_0_OR_GREATER @@ -5052,7 +5280,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_csvimport_columns( ); #if NET8_0_OR_GREATER @@ -5063,7 +5291,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_csvimport_plan( ); #if NET8_0_OR_GREATER @@ -5074,7 +5302,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_csvimport_preview( ); #if NET8_0_OR_GREATER @@ -5085,7 +5313,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_csvimport_run( ); #if NET8_0_OR_GREATER @@ -5096,7 +5324,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_csvimport_suggest_mapping( ); #if NET8_0_OR_GREATER @@ -5107,7 +5335,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_keyreader_key( ); #if NET8_0_OR_GREATER @@ -5118,7 +5346,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_keyreader_read_more( ); #if NET8_0_OR_GREATER @@ -5129,7 +5357,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_duplicate( + ushort uniffi_tablepro_ffi_checksum_method_keyreader_rows( ); #if NET8_0_OR_GREATER @@ -5140,7 +5368,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_export_file( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_apply_cloud_pull( ); #if NET8_0_OR_GREATER @@ -5151,7 +5379,106 @@ 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_connectionlibrary_cloud_edits( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_add_favorites( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_group( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_tag( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_group( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_duplicate( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_export_file( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_import_file( ); #if NET8_0_OR_GREATER @@ -5517,6 +5844,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_tableeditor_columns( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_copies_exactly( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -5561,6 +5899,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_tableeditor_plan( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_table( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -6078,6 +6427,17 @@ public static extern 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_result_editor( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -6632,6 +6992,18 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_core_test_connection` checksum `24848`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_core_foreign_sources(); + if (checksum != 52035) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_core_foreign_sources` checksum `52035`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_core_read_foreign(); + if (checksum != 19189) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_core_read_foreign` checksum `19189`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_core_forget_changed_host_key(); if (checksum != 14861) { @@ -6710,6 +7082,60 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_favouritestore_tables` checksum `53725`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_app(); + if (checksum != 35608) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_app` checksum `35608`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_apply(); + if (checksum != 47598) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_apply` checksum `47598`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_choices(); + if (checksum != 15799) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_choices` checksum `15799`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_connections(); + if (checksum != 4892) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_connections` checksum `4892`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_passwords(); + if (checksum != 12275) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_passwords` checksum `12275`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_resolve(); + if (checksum != 14594) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_resolve` checksum `14594`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_saved_queries(); + if (checksum != 50147) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_saved_queries` checksum `50147`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_included(); + if (checksum != 21478) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_included` checksum `21478`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_selected(); + if (checksum != 39617) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_selected` checksum `39617`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear(); if (checksum != 34195) { @@ -7076,6 +7502,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_columns` checksum `6588`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_copies_exactly(); + if (checksum != 55910) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_copies_exactly` checksum `55910`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start(); if (checksum != 21277) { @@ -7100,6 +7532,12 @@ static void uniffiCheckApiChecksums() { 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_tableeditor_table(); + if (checksum != 44578) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tableeditor_table` checksum `44578`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryrun_cancel(); if (checksum != 58442) { @@ -7382,6 +7820,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects` checksum `16631`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_result_editor(); + if (checksum != 60737) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_result_editor` checksum `60737`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_schemas(); if (checksum != 64032) { @@ -9144,6 +9588,10 @@ internal interface ICore { /// Task TestConnection(ConnectionRecord @record, ConnectionSecrets @secrets, HostPrompter? @prompter, CancelToken? @cancel); /// + Task ForeignSources(ForeignAppDirsArg @dirs); + /// + Task ReadForeign(ForeignAppTag @app, ForeignAppDirsArg @dirs, string? @file, ForeignImportRequest @request, CancelToken? @cancel); + /// Task ForgetChangedHostKey(ConnectionRecord @record, string @host, string @knownHosts); } internal class Core : ICore, IDisposable { @@ -9363,6 +9811,50 @@ public async Task TestConnection(ConnectionRecord @record, ConnectionSecrets @se ); } + /// + public async Task ForeignSources(ForeignAppDirsArg @dirs) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_foreign_sources(thisPtr, FfiConverterTypeForeignAppDirsArg.INSTANCE.Lower(@dirs)); + }), + // 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) => FfiConverterSequenceTypeForeignSourceInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ReadForeign(ForeignAppTag @app, ForeignAppDirsArg @dirs, string? @file, ForeignImportRequest @request, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_read_foreign(thisPtr, FfiConverterTypeForeignAppTag.INSTANCE.Lower(@app), FfiConverterTypeForeignAppDirsArg.INSTANCE.Lower(@dirs), FfiConverterOptionalString.INSTANCE.Lower(@file), FfiConverterTypeForeignImportRequest.INSTANCE.Lower(@request), 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) => FfiConverterTypeForeignImportReview.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task ForgetChangedHostKey(ConnectionRecord @record, string @host, string @knownHosts) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future @@ -9680,6 +10172,8 @@ internal interface IDatabaseSession { /// Task RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel); /// + Task ResultEditor(string @sql, ResultSet @rows, CancelToken? @cancel); + /// Task Schemas(CancelToken? @cancel); bool SetSafeMode(SafeModeTag @level); /// @@ -10247,6 +10741,28 @@ public async Task RefreshObjects(ObjectScopeArg @scope, CancelTok ); } + /// + public async Task ResultEditor(string @sql, ResultSet @rows, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_result_editor(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterTypeResultSet.INSTANCE.Lower(@rows), 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) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// public async Task Schemas(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( @@ -10818,34 +11334,41 @@ public override void Write(FavouriteStore value, BigEndianStream stream) { -internal interface IKeyReader { - string Key(); +internal interface IForeignImportReview { + ForeignAppTag App(); /// - Task ReadMore(CancelToken? @cancel); - ResultSet? Rows(); + Task Apply(); + ForeignImportChoices Choices(); + ForeignConnectionRow[] Connections(); + PasswordOutcomeTag Passwords(); + /// + bool Resolve(string @reference, ResolutionTag @resolution); + ForeignQueryRow[] SavedQueries(); + void SetIncluded(string @reference, bool @included); + void SetSelected(string @reference, bool @selected); } -internal class KeyReader : IKeyReader, IDisposable { +internal class ForeignImportReview : IForeignImportReview, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public KeyReader(ulong pointer) { + public ForeignImportReview(ulong pointer) { this.pointer = pointer; } - ~KeyReader() { + ~ForeignImportReview() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_keyreader(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_foreignimportreview(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_keyreader(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_foreignimportreview(this.pointer, ref status); }); } @@ -10913,20 +11436,20 @@ internal T CallWithPointer(Func func) } - public string Key() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + public ForeignAppTag App() { + return CallWithPointer(thisPtr => FfiConverterTypeForeignAppTag.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_key(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_app(thisPtr, ref _status) ))); } /// - public async Task ReadMore(CancelToken? @cancel) { + public async Task Apply() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_read_more(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_apply(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -10937,21 +11460,235 @@ public string Key() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterOptionalTypeKeyWindowInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeForeignImportOutcome.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public ResultSet? Rows() { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeResultSet.INSTANCE.Lift( + public ForeignImportChoices Choices() { + return CallWithPointer(thisPtr => FfiConverterTypeForeignImportChoices.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_rows(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_choices(thisPtr, ref _status) ))); } - + public ForeignConnectionRow[] Connections() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeForeignConnectionRow.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_connections(thisPtr, ref _status) +))); + } + + + public PasswordOutcomeTag Passwords() { + return CallWithPointer(thisPtr => FfiConverterTypePasswordOutcomeTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_passwords(thisPtr, ref _status) +))); + } + + + /// + public bool Resolve(string @reference, ResolutionTag @resolution) { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_resolve(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterTypeResolutionTag.INSTANCE.Lower(@resolution), ref _status) +))); + } + + + public ForeignQueryRow[] SavedQueries() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeForeignQueryRow.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_saved_queries(thisPtr, ref _status) +))); + } + + + public void SetIncluded(string @reference, bool @included) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_set_included(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterBoolean.INSTANCE.Lower(@included), ref _status) +)); + } + + + + public void SetSelected(string @reference, bool @selected) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_set_selected(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterBoolean.INSTANCE.Lower(@selected), ref _status) +)); + } + + + + + +} +class FfiConverterTypeForeignImportReview: FfiConverter { + public static FfiConverterTypeForeignImportReview INSTANCE = new FfiConverterTypeForeignImportReview(); + + + public override ulong Lower(ForeignImportReview value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override ForeignImportReview Lift(ulong value) { + return new ForeignImportReview(value); + } + + public override ForeignImportReview Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(ForeignImportReview value) { + return 8; + } + + public override void Write(ForeignImportReview value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IKeyReader { + string Key(); + /// + Task ReadMore(CancelToken? @cancel); + ResultSet? Rows(); +} +internal class KeyReader : IKeyReader, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public KeyReader(ulong pointer) { + this.pointer = pointer; + } + + ~KeyReader() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_keyreader(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_keyreader(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 string Key() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_key(thisPtr, ref _status) +))); + } + + + /// + public async Task ReadMore(CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_read_more(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) => FfiConverterOptionalTypeKeyWindowInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public ResultSet? Rows() { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeResultSet.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_rows(thisPtr, ref _status) +))); + } + + + } class FfiConverterTypeKeyReader: FfiConverter { @@ -12678,12 +13415,14 @@ internal interface ITableEditor { /// void Check(uint @column, CellEdit @edit, bool @newRow); EditColumnInfo[] Columns(); + bool CopiesExactly(ResultSet @rows, ulong @row); /// EditStart EditStart(ResultSet @rows, ulong @row, uint @column); EditLock? Lock(); EditLock? LockFor(ResultSet @rows); /// RowSave Plan(ResultSet @rows, RowEdit[] @edits); + TableName? Table(); } internal class TableEditor : ITableEditor, IDisposable { protected ulong pointer; @@ -12792,6 +13531,14 @@ public EditColumnInfo[] Columns() { } + public bool CopiesExactly(ResultSet @rows, ulong @row) { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_copies_exactly(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt64.INSTANCE.Lower(@row), ref _status) +))); + } + + /// public EditStart EditStart(ResultSet @rows, ulong @row, uint @column) { return CallWithPointer(thisPtr => FfiConverterTypeEditStart.INSTANCE.Lift( @@ -12826,6 +13573,14 @@ public RowSave Plan(ResultSet @rows, RowEdit[] @edits) { } + public TableName? Table() { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeTableName.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_tableeditor_table(thisPtr, ref _status) +))); + } + + } @@ -14514,6 +15269,36 @@ public override void Write(ErrorInfo value, BigEndianStream stream) { +internal record ExistingConnectionInfo ( + string Id, + string Name +) { +} + +class FfiConverterTypeExistingConnectionInfo: FfiConverterRustBuffer { + public static FfiConverterTypeExistingConnectionInfo INSTANCE = new FfiConverterTypeExistingConnectionInfo(); + + public override ExistingConnectionInfo Read(BigEndianStream stream) { + return new ExistingConnectionInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ExistingConnectionInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name); + } + + public override void Write(ExistingConnectionInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + } +} + + + internal record FavouriteDatabaseInfo ( string Database, DatabaseEnvironmentTag Environment @@ -14714,57 +15499,427 @@ public override void Write(FilterRuleArg value, BigEndianStream stream) { -internal record GroupRecord ( - string Id, - string Name, - string? ParentId, - uint Order, - string? Color +internal record ForeignAppDirsArg ( + string Home, + string Config, + string Data ) { } -class FfiConverterTypeGroupRecord: FfiConverterRustBuffer { - public static FfiConverterTypeGroupRecord INSTANCE = new FfiConverterTypeGroupRecord(); +class FfiConverterTypeForeignAppDirsArg: FfiConverterRustBuffer { + public static FfiConverterTypeForeignAppDirsArg INSTANCE = new FfiConverterTypeForeignAppDirsArg(); - public override GroupRecord Read(BigEndianStream stream) { - return new GroupRecord( - Id: FfiConverterString.INSTANCE.Read(stream), - Name: FfiConverterString.INSTANCE.Read(stream), - ParentId: FfiConverterOptionalString.INSTANCE.Read(stream), - Order: FfiConverterUInt32.INSTANCE.Read(stream), - Color: FfiConverterOptionalString.INSTANCE.Read(stream) + public override ForeignAppDirsArg Read(BigEndianStream stream) { + return new ForeignAppDirsArg( + Home: FfiConverterString.INSTANCE.Read(stream), + Config: FfiConverterString.INSTANCE.Read(stream), + Data: FfiConverterString.INSTANCE.Read(stream) ); } - public override int AllocationSize(GroupRecord value) { + public override int AllocationSize(ForeignAppDirsArg value) { return 0 - + FfiConverterString.INSTANCE.AllocationSize(value.Id) - + FfiConverterString.INSTANCE.AllocationSize(value.Name) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ParentId) - + FfiConverterUInt32.INSTANCE.AllocationSize(value.Order) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Color); + + FfiConverterString.INSTANCE.AllocationSize(value.Home) + + FfiConverterString.INSTANCE.AllocationSize(value.Config) + + FfiConverterString.INSTANCE.AllocationSize(value.Data); } - public override void Write(GroupRecord value, BigEndianStream stream) { - FfiConverterString.INSTANCE.Write(value.Id, stream); - FfiConverterString.INSTANCE.Write(value.Name, stream); - FfiConverterOptionalString.INSTANCE.Write(value.ParentId, stream); - FfiConverterUInt32.INSTANCE.Write(value.Order, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Color, stream); + public override void Write(ForeignAppDirsArg value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Home, stream); + FfiConverterString.INSTANCE.Write(value.Config, stream); + FfiConverterString.INSTANCE.Write(value.Data, stream); } } -internal record HistoryCursorArg ( - bool Pinned, - long ExecutedAtSecs, - long Id +internal record ForeignConnectionChoice ( + string Reference, + bool Selected, + ResolutionTag? Resolution, + ResolutionTag[] Offered ) { } -class FfiConverterTypeHistoryCursorArg: FfiConverterRustBuffer { - public static FfiConverterTypeHistoryCursorArg INSTANCE = new FfiConverterTypeHistoryCursorArg(); +class FfiConverterTypeForeignConnectionChoice: FfiConverterRustBuffer { + public static FfiConverterTypeForeignConnectionChoice INSTANCE = new FfiConverterTypeForeignConnectionChoice(); + + public override ForeignConnectionChoice Read(BigEndianStream stream) { + return new ForeignConnectionChoice( + Reference: FfiConverterString.INSTANCE.Read(stream), + Selected: FfiConverterBoolean.INSTANCE.Read(stream), + Resolution: FfiConverterOptionalTypeResolutionTag.INSTANCE.Read(stream), + Offered: FfiConverterSequenceTypeResolutionTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignConnectionChoice value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Reference) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Selected) + + FfiConverterOptionalTypeResolutionTag.INSTANCE.AllocationSize(value.Resolution) + + FfiConverterSequenceTypeResolutionTag.INSTANCE.AllocationSize(value.Offered); + } + + public override void Write(ForeignConnectionChoice value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Reference, stream); + FfiConverterBoolean.INSTANCE.Write(value.Selected, stream); + FfiConverterOptionalTypeResolutionTag.INSTANCE.Write(value.Resolution, stream); + FfiConverterSequenceTypeResolutionTag.INSTANCE.Write(value.Offered, stream); + } +} + + + +internal record ForeignConnectionRow ( + string Reference, + string Name, + string Engine, + ConnectionRecord? Connection, + string[] GroupPath, + ExistingConnectionInfo? Duplicate, + RowNoteInfo[] Notes, + uint SavedQueryCount, + bool CarriesPasswords +) { +} + +class FfiConverterTypeForeignConnectionRow: FfiConverterRustBuffer { + public static FfiConverterTypeForeignConnectionRow INSTANCE = new FfiConverterTypeForeignConnectionRow(); + + public override ForeignConnectionRow Read(BigEndianStream stream) { + return new ForeignConnectionRow( + Reference: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + Engine: FfiConverterString.INSTANCE.Read(stream), + Connection: FfiConverterOptionalTypeConnectionRecord.INSTANCE.Read(stream), + GroupPath: FfiConverterSequenceString.INSTANCE.Read(stream), + Duplicate: FfiConverterOptionalTypeExistingConnectionInfo.INSTANCE.Read(stream), + Notes: FfiConverterSequenceTypeRowNoteInfo.INSTANCE.Read(stream), + SavedQueryCount: FfiConverterUInt32.INSTANCE.Read(stream), + CarriesPasswords: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignConnectionRow value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Reference) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.Engine) + + FfiConverterOptionalTypeConnectionRecord.INSTANCE.AllocationSize(value.Connection) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.GroupPath) + + FfiConverterOptionalTypeExistingConnectionInfo.INSTANCE.AllocationSize(value.Duplicate) + + FfiConverterSequenceTypeRowNoteInfo.INSTANCE.AllocationSize(value.Notes) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.SavedQueryCount) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.CarriesPasswords); + } + + public override void Write(ForeignConnectionRow value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Reference, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.Engine, stream); + FfiConverterOptionalTypeConnectionRecord.INSTANCE.Write(value.Connection, stream); + FfiConverterSequenceString.INSTANCE.Write(value.GroupPath, stream); + FfiConverterOptionalTypeExistingConnectionInfo.INSTANCE.Write(value.Duplicate, stream); + FfiConverterSequenceTypeRowNoteInfo.INSTANCE.Write(value.Notes, stream); + FfiConverterUInt32.INSTANCE.Write(value.SavedQueryCount, stream); + FfiConverterBoolean.INSTANCE.Write(value.CarriesPasswords, stream); + } +} + + + +internal record ForeignImportChoices ( + ForeignConnectionChoice[] Connections, + ForeignQueryChoice[] Queries, + bool Importable +) { +} + +class FfiConverterTypeForeignImportChoices: FfiConverterRustBuffer { + public static FfiConverterTypeForeignImportChoices INSTANCE = new FfiConverterTypeForeignImportChoices(); + + public override ForeignImportChoices Read(BigEndianStream stream) { + return new ForeignImportChoices( + Connections: FfiConverterSequenceTypeForeignConnectionChoice.INSTANCE.Read(stream), + Queries: FfiConverterSequenceTypeForeignQueryChoice.INSTANCE.Read(stream), + Importable: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignImportChoices value) { + return 0 + + FfiConverterSequenceTypeForeignConnectionChoice.INSTANCE.AllocationSize(value.Connections) + + FfiConverterSequenceTypeForeignQueryChoice.INSTANCE.AllocationSize(value.Queries) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Importable); + } + + public override void Write(ForeignImportChoices value, BigEndianStream stream) { + FfiConverterSequenceTypeForeignConnectionChoice.INSTANCE.Write(value.Connections, stream); + FfiConverterSequenceTypeForeignQueryChoice.INSTANCE.Write(value.Queries, stream); + FfiConverterBoolean.INSTANCE.Write(value.Importable, stream); + } +} + + + +internal record ForeignImportOutcome ( + uint Connections, + uint Replaced, + uint PasswordsNotKept, + uint QueriesAdded, + uint QueriesAlreadySaved, + uint QueriesFailed +) { +} + +class FfiConverterTypeForeignImportOutcome: FfiConverterRustBuffer { + public static FfiConverterTypeForeignImportOutcome INSTANCE = new FfiConverterTypeForeignImportOutcome(); + + public override ForeignImportOutcome Read(BigEndianStream stream) { + return new ForeignImportOutcome( + Connections: FfiConverterUInt32.INSTANCE.Read(stream), + Replaced: FfiConverterUInt32.INSTANCE.Read(stream), + PasswordsNotKept: FfiConverterUInt32.INSTANCE.Read(stream), + QueriesAdded: FfiConverterUInt32.INSTANCE.Read(stream), + QueriesAlreadySaved: FfiConverterUInt32.INSTANCE.Read(stream), + QueriesFailed: FfiConverterUInt32.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignImportOutcome value) { + return 0 + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Connections) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Replaced) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.PasswordsNotKept) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.QueriesAdded) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.QueriesAlreadySaved) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.QueriesFailed); + } + + public override void Write(ForeignImportOutcome value, BigEndianStream stream) { + FfiConverterUInt32.INSTANCE.Write(value.Connections, stream); + FfiConverterUInt32.INSTANCE.Write(value.Replaced, stream); + FfiConverterUInt32.INSTANCE.Write(value.PasswordsNotKept, stream); + FfiConverterUInt32.INSTANCE.Write(value.QueriesAdded, stream); + FfiConverterUInt32.INSTANCE.Write(value.QueriesAlreadySaved, stream); + FfiConverterUInt32.INSTANCE.Write(value.QueriesFailed, stream); + } +} + + + +internal record ForeignImportRequest ( + bool IncludePasswords, + bool IncludeSavedQueries +) { +} + +class FfiConverterTypeForeignImportRequest: FfiConverterRustBuffer { + public static FfiConverterTypeForeignImportRequest INSTANCE = new FfiConverterTypeForeignImportRequest(); + + public override ForeignImportRequest Read(BigEndianStream stream) { + return new ForeignImportRequest( + IncludePasswords: FfiConverterBoolean.INSTANCE.Read(stream), + IncludeSavedQueries: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignImportRequest value) { + return 0 + + FfiConverterBoolean.INSTANCE.AllocationSize(value.IncludePasswords) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.IncludeSavedQueries); + } + + public override void Write(ForeignImportRequest value, BigEndianStream stream) { + FfiConverterBoolean.INSTANCE.Write(value.IncludePasswords, stream); + FfiConverterBoolean.INSTANCE.Write(value.IncludeSavedQueries, stream); + } +} + + + +internal record ForeignQueryChoice ( + string Reference, + QueryAvailabilityTag Availability, + bool Included +) { +} + +class FfiConverterTypeForeignQueryChoice: FfiConverterRustBuffer { + public static FfiConverterTypeForeignQueryChoice INSTANCE = new FfiConverterTypeForeignQueryChoice(); + + public override ForeignQueryChoice Read(BigEndianStream stream) { + return new ForeignQueryChoice( + Reference: FfiConverterString.INSTANCE.Read(stream), + Availability: FfiConverterTypeQueryAvailabilityTag.INSTANCE.Read(stream), + Included: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignQueryChoice value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Reference) + + FfiConverterTypeQueryAvailabilityTag.INSTANCE.AllocationSize(value.Availability) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Included); + } + + public override void Write(ForeignQueryChoice value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Reference, stream); + FfiConverterTypeQueryAvailabilityTag.INSTANCE.Write(value.Availability, stream); + FfiConverterBoolean.INSTANCE.Write(value.Included, stream); + } +} + + + +internal record ForeignQueryRow ( + string Reference, + string Name, + string? Connection, + string? ConnectionName, + ulong ByteCount +) { +} + +class FfiConverterTypeForeignQueryRow: FfiConverterRustBuffer { + public static FfiConverterTypeForeignQueryRow INSTANCE = new FfiConverterTypeForeignQueryRow(); + + public override ForeignQueryRow Read(BigEndianStream stream) { + return new ForeignQueryRow( + Reference: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + Connection: FfiConverterOptionalString.INSTANCE.Read(stream), + ConnectionName: FfiConverterOptionalString.INSTANCE.Read(stream), + ByteCount: FfiConverterUInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignQueryRow value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Reference) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Connection) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ConnectionName) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.ByteCount); + } + + public override void Write(ForeignQueryRow value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Reference, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Connection, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ConnectionName, stream); + FfiConverterUInt64.INSTANCE.Write(value.ByteCount, stream); + } +} + + + +internal record ForeignSourceInfo ( + ForeignAppTag App, + string Name, + bool Available, + ulong Connections, + ulong SavedQueries, + string[] FileExtensions, + PasswordSourceTag Passwords, + SavedQuerySupportTag SavedQuerySupport +) { +} + +class FfiConverterTypeForeignSourceInfo: FfiConverterRustBuffer { + public static FfiConverterTypeForeignSourceInfo INSTANCE = new FfiConverterTypeForeignSourceInfo(); + + public override ForeignSourceInfo Read(BigEndianStream stream) { + return new ForeignSourceInfo( + App: FfiConverterTypeForeignAppTag.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + Available: FfiConverterBoolean.INSTANCE.Read(stream), + Connections: FfiConverterUInt64.INSTANCE.Read(stream), + SavedQueries: FfiConverterUInt64.INSTANCE.Read(stream), + FileExtensions: FfiConverterSequenceString.INSTANCE.Read(stream), + Passwords: FfiConverterTypePasswordSourceTag.INSTANCE.Read(stream), + SavedQuerySupport: FfiConverterTypeSavedQuerySupportTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ForeignSourceInfo value) { + return 0 + + FfiConverterTypeForeignAppTag.INSTANCE.AllocationSize(value.App) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Available) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.Connections) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.SavedQueries) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.FileExtensions) + + FfiConverterTypePasswordSourceTag.INSTANCE.AllocationSize(value.Passwords) + + FfiConverterTypeSavedQuerySupportTag.INSTANCE.AllocationSize(value.SavedQuerySupport); + } + + public override void Write(ForeignSourceInfo value, BigEndianStream stream) { + FfiConverterTypeForeignAppTag.INSTANCE.Write(value.App, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterBoolean.INSTANCE.Write(value.Available, stream); + FfiConverterUInt64.INSTANCE.Write(value.Connections, stream); + FfiConverterUInt64.INSTANCE.Write(value.SavedQueries, stream); + FfiConverterSequenceString.INSTANCE.Write(value.FileExtensions, stream); + FfiConverterTypePasswordSourceTag.INSTANCE.Write(value.Passwords, stream); + FfiConverterTypeSavedQuerySupportTag.INSTANCE.Write(value.SavedQuerySupport, stream); + } +} + + + +internal record GroupRecord ( + string Id, + string Name, + string? ParentId, + uint Order, + string? Color +) { +} + +class FfiConverterTypeGroupRecord: FfiConverterRustBuffer { + public static FfiConverterTypeGroupRecord INSTANCE = new FfiConverterTypeGroupRecord(); + + public override GroupRecord Read(BigEndianStream stream) { + return new GroupRecord( + Id: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + ParentId: FfiConverterOptionalString.INSTANCE.Read(stream), + Order: FfiConverterUInt32.INSTANCE.Read(stream), + Color: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(GroupRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ParentId) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Order) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Color); + } + + public override void Write(GroupRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ParentId, stream); + FfiConverterUInt32.INSTANCE.Write(value.Order, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Color, stream); + } +} + + + +internal record HistoryCursorArg ( + bool Pinned, + long ExecutedAtSecs, + long Id +) { +} + +class FfiConverterTypeHistoryCursorArg: FfiConverterRustBuffer { + public static FfiConverterTypeHistoryCursorArg INSTANCE = new FfiConverterTypeHistoryCursorArg(); public override HistoryCursorArg Read(BigEndianStream stream) { return new HistoryCursorArg( @@ -17852,6 +19007,21 @@ string Column public record ColumnsChanged: EditLock {} + public record NotOneSelect: EditLock {} + + + public record MoreThanOneTable: EditLock {} + + + public record Collapsed: EditLock {} + + + public record Untraced: EditLock {} + + + public record KeyNotShown: EditLock {} + + } @@ -17875,6 +19045,21 @@ public override EditLock Read(BigEndianStream stream) { case 4: return new EditLock.ColumnsChanged( ); + case 5: + return new EditLock.NotOneSelect( + ); + case 6: + return new EditLock.MoreThanOneTable( + ); + case 7: + return new EditLock.Collapsed( + ); + case 8: + return new EditLock.Untraced( + ); + case 9: + return new EditLock.KeyNotShown( + ); default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditLock.Read()", value)); } @@ -17891,6 +19076,16 @@ public override int AllocationSize(EditLock value) { + FfiConverterString.INSTANCE.AllocationSize(variant_value.Column); case EditLock.ColumnsChanged variant_value: return 4; + case EditLock.NotOneSelect variant_value: + return 4; + case EditLock.MoreThanOneTable variant_value: + return 4; + case EditLock.Collapsed variant_value: + return 4; + case EditLock.Untraced variant_value: + return 4; + case EditLock.KeyNotShown variant_value: + return 4; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditLock.AllocationSize()", value)); } @@ -17911,6 +19106,21 @@ public override void Write(EditLock value, BigEndianStream stream) { case EditLock.ColumnsChanged variant_value: stream.WriteInt(4); break; + case EditLock.NotOneSelect variant_value: + stream.WriteInt(5); + break; + case EditLock.MoreThanOneTable variant_value: + stream.WriteInt(6); + break; + case EditLock.Collapsed variant_value: + stream.WriteInt(7); + break; + case EditLock.Untraced variant_value: + stream.WriteInt(8); + break; + case EditLock.KeyNotShown variant_value: + stream.WriteInt(9); + break; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEditLock.Write()", value)); } @@ -18572,32 +19782,47 @@ public override void Write(FollowedReference value, BigEndianStream stream) { -internal enum HistoryExportFormat: int { - Sql, - Csv +internal enum ForeignAppTag: int { + TablePlus, + SequelAce, + DBeaver, + DataGrip, + BeekeeperStudio, + Navicat, + Dbx } -class FfiConverterTypeHistoryExportFormat: FfiConverterRustBuffer { - public static FfiConverterTypeHistoryExportFormat INSTANCE = new FfiConverterTypeHistoryExportFormat(); +class FfiConverterTypeForeignAppTag: FfiConverterRustBuffer { + public static FfiConverterTypeForeignAppTag INSTANCE = new FfiConverterTypeForeignAppTag(); - public override HistoryExportFormat Read(BigEndianStream stream) { + public override ForeignAppTag 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)); + case 1: return ForeignAppTag.TablePlus; + case 2: return ForeignAppTag.SequelAce; + case 3: return ForeignAppTag.DBeaver; + case 4: return ForeignAppTag.DataGrip; + case 5: return ForeignAppTag.BeekeeperStudio; + case 6: return ForeignAppTag.Navicat; + case 7: return ForeignAppTag.Dbx; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeForeignAppTag.Read()", value)); } } - public override int AllocationSize(HistoryExportFormat value) { + public override int AllocationSize(ForeignAppTag value) { return 4; } - public override void Write(HistoryExportFormat value, BigEndianStream stream) { + public override void Write(ForeignAppTag 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)); + case ForeignAppTag.TablePlus: stream.WriteInt(1); break; + case ForeignAppTag.SequelAce: stream.WriteInt(2); break; + case ForeignAppTag.DBeaver: stream.WriteInt(3); break; + case ForeignAppTag.DataGrip: stream.WriteInt(4); break; + case ForeignAppTag.BeekeeperStudio: stream.WriteInt(5); break; + case ForeignAppTag.Navicat: stream.WriteInt(6); break; + case ForeignAppTag.Dbx: stream.WriteInt(7); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeForeignAppTag.Write()", value)); } } } @@ -18608,38 +19833,119 @@ public override void Write(HistoryExportFormat value, BigEndianStream stream) { -internal record HistoryOutcomeTag { - - public record Succeeded: HistoryOutcomeTag {} - - - public record Failed ( - string Message - ) : HistoryOutcomeTag {} - - public record Cancelled: HistoryOutcomeTag {} - - - - +internal enum ForeignSslModeTag: int { + Disabled, + Preferred, + Required, + VerifyCa, + VerifyIdentity } -class FfiConverterTypeHistoryOutcomeTag : FfiConverterRustBuffer{ - public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeHistoryOutcomeTag(); +class FfiConverterTypeForeignSslModeTag: FfiConverterRustBuffer { + public static FfiConverterTypeForeignSslModeTag INSTANCE = new FfiConverterTypeForeignSslModeTag(); - public override HistoryOutcomeTag Read(BigEndianStream stream) { + public override ForeignSslModeTag Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { - case 1: - return new HistoryOutcomeTag.Succeeded( - ); - case 2: - return new HistoryOutcomeTag.Failed( - FfiConverterString.INSTANCE.Read(stream) - ); - case 3: - return new HistoryOutcomeTag.Cancelled( - ); + case 1: return ForeignSslModeTag.Disabled; + case 2: return ForeignSslModeTag.Preferred; + case 3: return ForeignSslModeTag.Required; + case 4: return ForeignSslModeTag.VerifyCa; + case 5: return ForeignSslModeTag.VerifyIdentity; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeForeignSslModeTag.Read()", value)); + } + } + + public override int AllocationSize(ForeignSslModeTag value) { + return 4; + } + + public override void Write(ForeignSslModeTag value, BigEndianStream stream) { + switch (value) { + case ForeignSslModeTag.Disabled: stream.WriteInt(1); break; + case ForeignSslModeTag.Preferred: stream.WriteInt(2); break; + case ForeignSslModeTag.Required: stream.WriteInt(3); break; + case ForeignSslModeTag.VerifyCa: stream.WriteInt(4); break; + case ForeignSslModeTag.VerifyIdentity: stream.WriteInt(5); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeForeignSslModeTag.Write()", value)); + } + } +} + + + + + + + +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 {} + + + public record Failed ( + string Message + ) : HistoryOutcomeTag {} + + public record Cancelled: HistoryOutcomeTag {} + + + + +} + +class FfiConverterTypeHistoryOutcomeTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeHistoryOutcomeTag(); + + public override HistoryOutcomeTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new HistoryOutcomeTag.Succeeded( + ); + case 2: + return new HistoryOutcomeTag.Failed( + FfiConverterString.INSTANCE.Read(stream) + ); + case 3: + return new HistoryOutcomeTag.Cancelled( + ); default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeHistoryOutcomeTag.Read()", value)); } @@ -19250,6 +20556,84 @@ public override void Write(ObjectScopeArg value, BigEndianStream stream) { +internal enum PasswordOutcomeTag: int { + NotRequested, + Read, + Stopped, + LeftInKeychain +} + +class FfiConverterTypePasswordOutcomeTag: FfiConverterRustBuffer { + public static FfiConverterTypePasswordOutcomeTag INSTANCE = new FfiConverterTypePasswordOutcomeTag(); + + public override PasswordOutcomeTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return PasswordOutcomeTag.NotRequested; + case 2: return PasswordOutcomeTag.Read; + case 3: return PasswordOutcomeTag.Stopped; + case 4: return PasswordOutcomeTag.LeftInKeychain; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePasswordOutcomeTag.Read()", value)); + } + } + + public override int AllocationSize(PasswordOutcomeTag value) { + return 4; + } + + public override void Write(PasswordOutcomeTag value, BigEndianStream stream) { + switch (value) { + case PasswordOutcomeTag.NotRequested: stream.WriteInt(1); break; + case PasswordOutcomeTag.Read: stream.WriteInt(2); break; + case PasswordOutcomeTag.Stopped: stream.WriteInt(3); break; + case PasswordOutcomeTag.LeftInKeychain: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePasswordOutcomeTag.Write()", value)); + } + } +} + + + + + + + +internal enum PasswordSourceTag: int { + Keychain, + AppFiles +} + +class FfiConverterTypePasswordSourceTag: FfiConverterRustBuffer { + public static FfiConverterTypePasswordSourceTag INSTANCE = new FfiConverterTypePasswordSourceTag(); + + public override PasswordSourceTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return PasswordSourceTag.Keychain; + case 2: return PasswordSourceTag.AppFiles; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePasswordSourceTag.Read()", value)); + } + } + + public override int AllocationSize(PasswordSourceTag value) { + return 4; + } + + public override void Write(PasswordSourceTag value, BigEndianStream stream) { + switch (value) { + case PasswordSourceTag.Keychain: stream.WriteInt(1); break; + case PasswordSourceTag.AppFiles: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePasswordSourceTag.Write()", value)); + } + } +} + + + + + + + internal record PromptAnswer { public record Submitted ( @@ -19548,6 +20932,54 @@ public override void Write(PromptReasonTag value, BigEndianStream stream) { +internal enum QueryAvailabilityTag: int { + Available, + AddedByAnotherRow, + TooLarge, + NameTooLong, + ConnectionSkipped, + NoConnection +} + +class FfiConverterTypeQueryAvailabilityTag: FfiConverterRustBuffer { + public static FfiConverterTypeQueryAvailabilityTag INSTANCE = new FfiConverterTypeQueryAvailabilityTag(); + + public override QueryAvailabilityTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return QueryAvailabilityTag.Available; + case 2: return QueryAvailabilityTag.AddedByAnotherRow; + case 3: return QueryAvailabilityTag.TooLarge; + case 4: return QueryAvailabilityTag.NameTooLong; + case 5: return QueryAvailabilityTag.ConnectionSkipped; + case 6: return QueryAvailabilityTag.NoConnection; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeQueryAvailabilityTag.Read()", value)); + } + } + + public override int AllocationSize(QueryAvailabilityTag value) { + return 4; + } + + public override void Write(QueryAvailabilityTag value, BigEndianStream stream) { + switch (value) { + case QueryAvailabilityTag.Available: stream.WriteInt(1); break; + case QueryAvailabilityTag.AddedByAnotherRow: stream.WriteInt(2); break; + case QueryAvailabilityTag.TooLarge: stream.WriteInt(3); break; + case QueryAvailabilityTag.NameTooLong: stream.WriteInt(4); break; + case QueryAvailabilityTag.ConnectionSkipped: stream.WriteInt(5); break; + case QueryAvailabilityTag.NoConnection: stream.WriteInt(6); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeQueryAvailabilityTag.Write()", value)); + } + } +} + + + + + + + internal record ReferenceRefusal { public record UnevenKey ( @@ -19714,6 +21146,96 @@ public override void Write(ReplicationArg value, BigEndianStream stream) { +internal record ResolutionTag { + + public record Add: ResolutionTag {} + + + public record AddCopy: ResolutionTag {} + + + public record Replace ( + string Id + ) : ResolutionTag {} + + public record KeepExisting ( + string Id + ) : ResolutionTag {} + + + +} + +class FfiConverterTypeResolutionTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeResolutionTag(); + + public override ResolutionTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new ResolutionTag.Add( + ); + case 2: + return new ResolutionTag.AddCopy( + ); + case 3: + return new ResolutionTag.Replace( + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new ResolutionTag.KeepExisting( + FfiConverterString.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResolutionTag.Read()", value)); + } + } + + public override int AllocationSize(ResolutionTag value) { + switch (value) { + case ResolutionTag.Add variant_value: + return 4; + case ResolutionTag.AddCopy variant_value: + return 4; + case ResolutionTag.Replace variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Id); + case ResolutionTag.KeepExisting variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Id); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResolutionTag.AllocationSize()", value)); + } + } + + public override void Write(ResolutionTag value, BigEndianStream stream) { + switch (value) { + case ResolutionTag.Add variant_value: + stream.WriteInt(1); + break; + case ResolutionTag.AddCopy variant_value: + stream.WriteInt(2); + break; + case ResolutionTag.Replace variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Id, stream); + break; + case ResolutionTag.KeepExisting variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.Id, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResolutionTag.Write()", value)); + } + } +} + + + + + + + internal record RowEdit { public record Update ( @@ -19880,48 +21402,360 @@ public override void Write(RowEstimate value, BigEndianStream stream) { -internal record RowSaveOutcome { +internal record RowNoteInfo { - public record Saved ( - ulong? Rows - ) : RowSaveOutcome {} + public record UnsupportedEngine ( + string Engine + ) : RowNoteInfo {} - public record RolledBack ( - BoxedErrorInfo Error, - uint? Edit - ) : RowSaveOutcome {} + public record SshKeyMissing ( + string Path + ) : RowNoteInfo {} - public record Unknown ( - BoxedErrorInfo Error, - uint? Edit - ) : RowSaveOutcome {} + public record JumpHostKeyMissing ( + string Path + ) : RowNoteInfo {} + + public record CaCertificateMissing ( + string Path + ) : RowNoteInfo {} + + public record ClientCertificateMissing ( + string Path + ) : RowNoteInfo {} + + public record ClientKeyMissing ( + string Path + ) : RowNoteInfo {} + + public record TlsModeChanged ( + ForeignSslModeTag From, + TlsModeTag To + ) : RowNoteInfo {} + + public record TlsSettingsNotRead: RowNoteInfo {} + + + public record TlsFromDriverDefault ( + ForeignSslModeTag Mode + ) : RowNoteInfo {} + + public record TlsNotKept ( + ForeignSslModeTag From + ) : RowNoteInfo {} + + public record CaFileNotKept ( + string Path, + TlsFileReasonTag Reason + ) : RowNoteInfo {} + + public record ClientIdentityNotKept ( + TlsFileReasonTag Reason + ) : RowNoteInfo {} + + public record SshNotKept: RowNoteInfo {} + + + public record SshKeyNotKept ( + string Path + ) : RowNoteInfo {} + + public record JumpHostNotKept ( + string Host + ) : RowNoteInfo {} + + public record JumpHostPasswordNotKept ( + string Host + ) : RowNoteInfo {} + + public record JumpHostKeyNotKept ( + string Host, + string Path + ) : RowNoteInfo {} + + public record FieldsNotKept ( + string[] Fields + ) : RowNoteInfo {} } -class FfiConverterTypeRowSaveOutcome : FfiConverterRustBuffer{ - public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeRowSaveOutcome(); +class FfiConverterTypeRowNoteInfo : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeRowNoteInfo(); - public override RowSaveOutcome Read(BigEndianStream stream) { + public override RowNoteInfo Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { case 1: - return new RowSaveOutcome.Saved( - FfiConverterOptionalUInt64.INSTANCE.Read(stream) + return new RowNoteInfo.UnsupportedEngine( + FfiConverterString.INSTANCE.Read(stream) ); case 2: - return new RowSaveOutcome.RolledBack( - FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), - FfiConverterOptionalUInt32.INSTANCE.Read(stream) + return new RowNoteInfo.SshKeyMissing( + FfiConverterString.INSTANCE.Read(stream) ); case 3: - return new RowSaveOutcome.Unknown( - FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), - FfiConverterOptionalUInt32.INSTANCE.Read(stream) + return new RowNoteInfo.JumpHostKeyMissing( + FfiConverterString.INSTANCE.Read(stream) ); - default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowSaveOutcome.Read()", value)); + case 4: + return new RowNoteInfo.CaCertificateMissing( + FfiConverterString.INSTANCE.Read(stream) + ); + case 5: + return new RowNoteInfo.ClientCertificateMissing( + FfiConverterString.INSTANCE.Read(stream) + ); + case 6: + return new RowNoteInfo.ClientKeyMissing( + FfiConverterString.INSTANCE.Read(stream) + ); + case 7: + return new RowNoteInfo.TlsModeChanged( + FfiConverterTypeForeignSslModeTag.INSTANCE.Read(stream), + FfiConverterTypeTlsModeTag.INSTANCE.Read(stream) + ); + case 8: + return new RowNoteInfo.TlsSettingsNotRead( + ); + case 9: + return new RowNoteInfo.TlsFromDriverDefault( + FfiConverterTypeForeignSslModeTag.INSTANCE.Read(stream) + ); + case 10: + return new RowNoteInfo.TlsNotKept( + FfiConverterTypeForeignSslModeTag.INSTANCE.Read(stream) + ); + case 11: + return new RowNoteInfo.CaFileNotKept( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterTypeTlsFileReasonTag.INSTANCE.Read(stream) + ); + case 12: + return new RowNoteInfo.ClientIdentityNotKept( + FfiConverterTypeTlsFileReasonTag.INSTANCE.Read(stream) + ); + case 13: + return new RowNoteInfo.SshNotKept( + ); + case 14: + return new RowNoteInfo.SshKeyNotKept( + FfiConverterString.INSTANCE.Read(stream) + ); + case 15: + return new RowNoteInfo.JumpHostNotKept( + FfiConverterString.INSTANCE.Read(stream) + ); + case 16: + return new RowNoteInfo.JumpHostPasswordNotKept( + FfiConverterString.INSTANCE.Read(stream) + ); + case 17: + return new RowNoteInfo.JumpHostKeyNotKept( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 18: + return new RowNoteInfo.FieldsNotKept( + FfiConverterSequenceString.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowNoteInfo.Read()", value)); + } + } + + public override int AllocationSize(RowNoteInfo value) { + switch (value) { + case RowNoteInfo.UnsupportedEngine variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Engine); + case RowNoteInfo.SshKeyMissing variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.JumpHostKeyMissing variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.CaCertificateMissing variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.ClientCertificateMissing variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.ClientKeyMissing variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.TlsModeChanged variant_value: + return 4 + + FfiConverterTypeForeignSslModeTag.INSTANCE.AllocationSize(variant_value.From) + + FfiConverterTypeTlsModeTag.INSTANCE.AllocationSize(variant_value.To); + case RowNoteInfo.TlsSettingsNotRead variant_value: + return 4; + case RowNoteInfo.TlsFromDriverDefault variant_value: + return 4 + + FfiConverterTypeForeignSslModeTag.INSTANCE.AllocationSize(variant_value.Mode); + case RowNoteInfo.TlsNotKept variant_value: + return 4 + + FfiConverterTypeForeignSslModeTag.INSTANCE.AllocationSize(variant_value.From); + case RowNoteInfo.CaFileNotKept variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path) + + FfiConverterTypeTlsFileReasonTag.INSTANCE.AllocationSize(variant_value.Reason); + case RowNoteInfo.ClientIdentityNotKept variant_value: + return 4 + + FfiConverterTypeTlsFileReasonTag.INSTANCE.AllocationSize(variant_value.Reason); + case RowNoteInfo.SshNotKept variant_value: + return 4; + case RowNoteInfo.SshKeyNotKept variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.JumpHostNotKept variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Host); + case RowNoteInfo.JumpHostPasswordNotKept variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Host); + case RowNoteInfo.JumpHostKeyNotKept variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Host) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Path); + case RowNoteInfo.FieldsNotKept variant_value: + return 4 + + FfiConverterSequenceString.INSTANCE.AllocationSize(variant_value.Fields); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowNoteInfo.AllocationSize()", value)); + } + } + + public override void Write(RowNoteInfo value, BigEndianStream stream) { + switch (value) { + case RowNoteInfo.UnsupportedEngine variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.Engine, stream); + break; + case RowNoteInfo.SshKeyMissing variant_value: + stream.WriteInt(2); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.JumpHostKeyMissing variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.CaCertificateMissing variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.ClientCertificateMissing variant_value: + stream.WriteInt(5); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.ClientKeyMissing variant_value: + stream.WriteInt(6); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.TlsModeChanged variant_value: + stream.WriteInt(7); + FfiConverterTypeForeignSslModeTag.INSTANCE.Write(variant_value.From, stream); + FfiConverterTypeTlsModeTag.INSTANCE.Write(variant_value.To, stream); + break; + case RowNoteInfo.TlsSettingsNotRead variant_value: + stream.WriteInt(8); + break; + case RowNoteInfo.TlsFromDriverDefault variant_value: + stream.WriteInt(9); + FfiConverterTypeForeignSslModeTag.INSTANCE.Write(variant_value.Mode, stream); + break; + case RowNoteInfo.TlsNotKept variant_value: + stream.WriteInt(10); + FfiConverterTypeForeignSslModeTag.INSTANCE.Write(variant_value.From, stream); + break; + case RowNoteInfo.CaFileNotKept variant_value: + stream.WriteInt(11); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + FfiConverterTypeTlsFileReasonTag.INSTANCE.Write(variant_value.Reason, stream); + break; + case RowNoteInfo.ClientIdentityNotKept variant_value: + stream.WriteInt(12); + FfiConverterTypeTlsFileReasonTag.INSTANCE.Write(variant_value.Reason, stream); + break; + case RowNoteInfo.SshNotKept variant_value: + stream.WriteInt(13); + break; + case RowNoteInfo.SshKeyNotKept variant_value: + stream.WriteInt(14); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.JumpHostNotKept variant_value: + stream.WriteInt(15); + FfiConverterString.INSTANCE.Write(variant_value.Host, stream); + break; + case RowNoteInfo.JumpHostPasswordNotKept variant_value: + stream.WriteInt(16); + FfiConverterString.INSTANCE.Write(variant_value.Host, stream); + break; + case RowNoteInfo.JumpHostKeyNotKept variant_value: + stream.WriteInt(17); + FfiConverterString.INSTANCE.Write(variant_value.Host, stream); + FfiConverterString.INSTANCE.Write(variant_value.Path, stream); + break; + case RowNoteInfo.FieldsNotKept variant_value: + stream.WriteInt(18); + FfiConverterSequenceString.INSTANCE.Write(variant_value.Fields, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowNoteInfo.Write()", value)); + } + } +} + + + + + + + +internal record RowSaveOutcome { + + public record Saved ( + ulong? Rows + ) : RowSaveOutcome {} + + public record RolledBack ( + BoxedErrorInfo Error, + uint? Edit + ) : RowSaveOutcome {} + + public record Unknown ( + BoxedErrorInfo Error, + uint? Edit + ) : RowSaveOutcome {} + + + +} + +class FfiConverterTypeRowSaveOutcome : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeRowSaveOutcome(); + + public override RowSaveOutcome Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new RowSaveOutcome.Saved( + FfiConverterOptionalUInt64.INSTANCE.Read(stream) + ); + case 2: + return new RowSaveOutcome.RolledBack( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterOptionalUInt32.INSTANCE.Read(stream) + ); + case 3: + return new RowSaveOutcome.Unknown( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream), + FfiConverterOptionalUInt32.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeRowSaveOutcome.Read()", value)); } } @@ -20403,6 +22237,48 @@ public override void Write(SaveGate value, BigEndianStream stream) { +internal enum SavedQuerySupportTag: int { + GlobalFolder, + Scripts, + Consoles, + NotInExport +} + +class FfiConverterTypeSavedQuerySupportTag: FfiConverterRustBuffer { + public static FfiConverterTypeSavedQuerySupportTag INSTANCE = new FfiConverterTypeSavedQuerySupportTag(); + + public override SavedQuerySupportTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SavedQuerySupportTag.GlobalFolder; + case 2: return SavedQuerySupportTag.Scripts; + case 3: return SavedQuerySupportTag.Consoles; + case 4: return SavedQuerySupportTag.NotInExport; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSavedQuerySupportTag.Read()", value)); + } + } + + public override int AllocationSize(SavedQuerySupportTag value) { + return 4; + } + + public override void Write(SavedQuerySupportTag value, BigEndianStream stream) { + switch (value) { + case SavedQuerySupportTag.GlobalFolder: stream.WriteInt(1); break; + case SavedQuerySupportTag.Scripts: stream.WriteInt(2); break; + case SavedQuerySupportTag.Consoles: stream.WriteInt(3); break; + case SavedQuerySupportTag.NotInExport: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSavedQuerySupportTag.Write()", value)); + } + } +} + + + + + + + internal enum SecretHitKindTag: int { AwsAccessKey, PrivateKey, @@ -21118,6 +22994,48 @@ public override void Write(TlsFailureTag value, BigEndianStream stream) { +internal enum TlsFileReasonTag: int { + EngineLacks, + ModeLacks, + RelativePath, + Incomplete +} + +class FfiConverterTypeTlsFileReasonTag: FfiConverterRustBuffer { + public static FfiConverterTypeTlsFileReasonTag INSTANCE = new FfiConverterTypeTlsFileReasonTag(); + + public override TlsFileReasonTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return TlsFileReasonTag.EngineLacks; + case 2: return TlsFileReasonTag.ModeLacks; + case 3: return TlsFileReasonTag.RelativePath; + case 4: return TlsFileReasonTag.Incomplete; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeTlsFileReasonTag.Read()", value)); + } + } + + public override int AllocationSize(TlsFileReasonTag value) { + return 4; + } + + public override void Write(TlsFileReasonTag value, BigEndianStream stream) { + switch (value) { + case TlsFileReasonTag.EngineLacks: stream.WriteInt(1); break; + case TlsFileReasonTag.ModeLacks: stream.WriteInt(2); break; + case TlsFileReasonTag.RelativePath: stream.WriteInt(3); break; + case TlsFileReasonTag.Incomplete: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeTlsFileReasonTag.Write()", value)); + } + } +} + + + + + + + internal enum TlsModeTag: int { Disable, Prefer, @@ -22619,6 +24537,68 @@ public override void Write(ColumnSort? value, BigEndianStream stream) { +class FfiConverterOptionalTypeConnectionRecord: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeConnectionRecord INSTANCE = new FfiConverterOptionalTypeConnectionRecord(); + + public override ConnectionRecord? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeConnectionRecord.INSTANCE.Read(stream); + } + + public override int AllocationSize(ConnectionRecord? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeConnectionRecord.INSTANCE.AllocationSize((ConnectionRecord)value); + } + } + + public override void Write(ConnectionRecord? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeConnectionRecord.INSTANCE.Write((ConnectionRecord)value, stream); + } + } +} + + + + +class FfiConverterOptionalTypeExistingConnectionInfo: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeExistingConnectionInfo INSTANCE = new FfiConverterOptionalTypeExistingConnectionInfo(); + + public override ExistingConnectionInfo? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeExistingConnectionInfo.INSTANCE.Read(stream); + } + + public override int AllocationSize(ExistingConnectionInfo? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeExistingConnectionInfo.INSTANCE.AllocationSize((ExistingConnectionInfo)value); + } + } + + public override void Write(ExistingConnectionInfo? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeExistingConnectionInfo.INSTANCE.Write((ExistingConnectionInfo)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeHistoryCursorArg: FfiConverterRustBuffer { public static FfiConverterOptionalTypeHistoryCursorArg INSTANCE = new FfiConverterOptionalTypeHistoryCursorArg(); @@ -23115,6 +25095,37 @@ public override void Write(ReplicationArg? value, BigEndianStream stream) { +class FfiConverterOptionalTypeResolutionTag: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeResolutionTag INSTANCE = new FfiConverterOptionalTypeResolutionTag(); + + public override ResolutionTag? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeResolutionTag.INSTANCE.Read(stream); + } + + public override int AllocationSize(ResolutionTag? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeResolutionTag.INSTANCE.AllocationSize((ResolutionTag)value); + } + } + + public override void Write(ResolutionTag? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeResolutionTag.INSTANCE.Write((ResolutionTag)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeSecretKindTag: FfiConverterRustBuffer { public static FfiConverterOptionalTypeSecretKindTag INSTANCE = new FfiConverterOptionalTypeSecretKindTag(); @@ -23595,7 +25606,237 @@ public override CharacterSetInfo[] Read(BigEndianStream stream) { return result; } - public override int AllocationSize(CharacterSetInfo[] value) { + public override int AllocationSize(CharacterSetInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCharacterSetInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CharacterSetInfo[] 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 = FfiConverterTypeCharacterSetInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeCloudConnectionFields: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudConnectionFields INSTANCE = new FfiConverterSequenceTypeCloudConnectionFields(); + + public override CloudConnectionFields[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudConnectionFields[length]; + var readFn = FfiConverterTypeCloudConnectionFields.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudConnectionFields[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudConnectionFields.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudConnectionFields[] 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 = FfiConverterTypeCloudConnectionFields.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeCloudGroupFields: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudGroupFields INSTANCE = new FfiConverterSequenceTypeCloudGroupFields(); + + public override CloudGroupFields[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudGroupFields[length]; + var readFn = FfiConverterTypeCloudGroupFields.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudGroupFields[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudGroupFields.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudGroupFields[] 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 = FfiConverterTypeCloudGroupFields.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeColumnEntry: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeColumnEntry INSTANCE = new FfiConverterSequenceTypeColumnEntry(); + + 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 FfiConverterSequenceTypeDataCenterReplicas: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeDataCenterReplicas INSTANCE = new FfiConverterSequenceTypeDataCenterReplicas(); + + public override DataCenterReplicas[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new DataCenterReplicas[length]; + var readFn = FfiConverterTypeDataCenterReplicas.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(DataCenterReplicas[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23603,12 +25844,12 @@ public override int AllocationSize(CharacterSetInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeCharacterSetInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeDataCenterReplicas.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(CharacterSetInfo[] value, BigEndianStream stream) { + public override void Write(DataCenterReplicas[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -23616,7 +25857,7 @@ public override void Write(CharacterSetInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeCharacterSetInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeDataCenterReplicas.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23624,24 +25865,24 @@ public override void Write(CharacterSetInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeCloudConnectionFields: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeCloudConnectionFields INSTANCE = new FfiConverterSequenceTypeCloudConnectionFields(); +class FfiConverterSequenceTypeDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeDeviceInfo INSTANCE = new FfiConverterSequenceTypeDeviceInfo(); - public override CloudConnectionFields[] Read(BigEndianStream stream) { + public override DeviceInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new CloudConnectionFields[length]; - var readFn = FfiConverterTypeCloudConnectionFields.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(CloudConnectionFields[] value) { + public override int AllocationSize(DeviceInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23649,12 +25890,12 @@ public override int AllocationSize(CloudConnectionFields[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeCloudConnectionFields.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeDeviceInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(CloudConnectionFields[] 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); @@ -23662,7 +25903,7 @@ public override void Write(CloudConnectionFields[] value, BigEndianStream stream } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeCloudConnectionFields.INSTANCE.Write; + var writerFn = FfiConverterTypeDeviceInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23670,24 +25911,24 @@ public override void Write(CloudConnectionFields[] value, BigEndianStream stream -class FfiConverterSequenceTypeCloudGroupFields: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeCloudGroupFields INSTANCE = new FfiConverterSequenceTypeCloudGroupFields(); +class FfiConverterSequenceTypeDriverInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeDriverInfo INSTANCE = new FfiConverterSequenceTypeDriverInfo(); - public override CloudGroupFields[] Read(BigEndianStream stream) { + public override DriverInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new CloudGroupFields[length]; - var readFn = FfiConverterTypeCloudGroupFields.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(CloudGroupFields[] value) { + public override int AllocationSize(DriverInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23695,12 +25936,12 @@ public override int AllocationSize(CloudGroupFields[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeCloudGroupFields.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeDriverInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(CloudGroupFields[] 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); @@ -23708,7 +25949,7 @@ public override void Write(CloudGroupFields[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeCloudGroupFields.INSTANCE.Write; + var writerFn = FfiConverterTypeDriverInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23716,24 +25957,24 @@ public override void Write(CloudGroupFields[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeColumnEntry: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeColumnEntry INSTANCE = new FfiConverterSequenceTypeColumnEntry(); +class FfiConverterSequenceTypeEditColumnInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeEditColumnInfo INSTANCE = new FfiConverterSequenceTypeEditColumnInfo(); - public override ColumnEntry[] Read(BigEndianStream stream) { + public override EditColumnInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new ColumnEntry[length]; - var readFn = FfiConverterTypeColumnEntry.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(ColumnEntry[] value) { + public override int AllocationSize(EditColumnInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23741,12 +25982,12 @@ public override int AllocationSize(ColumnEntry[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeColumnEntry.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeEditColumnInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(ColumnEntry[] 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); @@ -23754,7 +25995,7 @@ public override void Write(ColumnEntry[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeColumnEntry.INSTANCE.Write; + var writerFn = FfiConverterTypeEditColumnInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23762,24 +26003,24 @@ public override void Write(ColumnEntry[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeConnectionRecord: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeConnectionRecord INSTANCE = new FfiConverterSequenceTypeConnectionRecord(); +class FfiConverterSequenceTypeFavouriteDatabaseInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteDatabaseInfo INSTANCE = new FfiConverterSequenceTypeFavouriteDatabaseInfo(); - public override ConnectionRecord[] Read(BigEndianStream stream) { + public override FavouriteDatabaseInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new ConnectionRecord[length]; - var readFn = FfiConverterTypeConnectionRecord.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(ConnectionRecord[] value) { + public override int AllocationSize(FavouriteDatabaseInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23787,12 +26028,12 @@ public override int AllocationSize(ConnectionRecord[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeConnectionRecord.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(ConnectionRecord[] 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); @@ -23800,7 +26041,7 @@ public override void Write(ConnectionRecord[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeConnectionRecord.INSTANCE.Write; + var writerFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23808,24 +26049,24 @@ public override void Write(ConnectionRecord[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeDataCenterReplicas: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeDataCenterReplicas INSTANCE = new FfiConverterSequenceTypeDataCenterReplicas(); +class FfiConverterSequenceTypeFavouriteTableInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFavouriteTableInfo INSTANCE = new FfiConverterSequenceTypeFavouriteTableInfo(); - public override DataCenterReplicas[] Read(BigEndianStream stream) { + public override FavouriteTableInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new DataCenterReplicas[length]; - var readFn = FfiConverterTypeDataCenterReplicas.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(DataCenterReplicas[] value) { + public override int AllocationSize(FavouriteTableInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23833,12 +26074,12 @@ public override int AllocationSize(DataCenterReplicas[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeDataCenterReplicas.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(DataCenterReplicas[] 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); @@ -23846,7 +26087,7 @@ public override void Write(DataCenterReplicas[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeDataCenterReplicas.INSTANCE.Write; + var writerFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23854,24 +26095,24 @@ public override void Write(DataCenterReplicas[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeDeviceInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeDeviceInfo INSTANCE = new FfiConverterSequenceTypeDeviceInfo(); +class FfiConverterSequenceTypeFilterColumn: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFilterColumn INSTANCE = new FfiConverterSequenceTypeFilterColumn(); - public override DeviceInfo[] Read(BigEndianStream stream) { + public override FilterColumn[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new DeviceInfo[length]; - var readFn = FfiConverterTypeDeviceInfo.INSTANCE.Read; + var result = new FilterColumn[length]; + var readFn = FfiConverterTypeFilterColumn.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(FilterColumn[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23879,12 +26120,12 @@ public override int AllocationSize(DeviceInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeDeviceInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeFilterColumn.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(DeviceInfo[] value, BigEndianStream stream) { + public override void Write(FilterColumn[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -23892,7 +26133,7 @@ public override void Write(DeviceInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeDeviceInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeFilterColumn.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23900,24 +26141,24 @@ public override void Write(DeviceInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeDriverInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeDriverInfo INSTANCE = new FfiConverterSequenceTypeDriverInfo(); +class FfiConverterSequenceTypeFilterRuleArg: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeFilterRuleArg INSTANCE = new FfiConverterSequenceTypeFilterRuleArg(); - public override DriverInfo[] Read(BigEndianStream stream) { + public override FilterRuleArg[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new DriverInfo[length]; - var readFn = FfiConverterTypeDriverInfo.INSTANCE.Read; + var result = new FilterRuleArg[length]; + var readFn = FfiConverterTypeFilterRuleArg.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(FilterRuleArg[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23925,12 +26166,12 @@ public override int AllocationSize(DriverInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeDriverInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeFilterRuleArg.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(DriverInfo[] value, BigEndianStream stream) { + public override void Write(FilterRuleArg[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -23938,7 +26179,7 @@ public override void Write(DriverInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeDriverInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeFilterRuleArg.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23946,24 +26187,24 @@ public override void Write(DriverInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeEditColumnInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeEditColumnInfo INSTANCE = new FfiConverterSequenceTypeEditColumnInfo(); +class FfiConverterSequenceTypeForeignConnectionChoice: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeForeignConnectionChoice INSTANCE = new FfiConverterSequenceTypeForeignConnectionChoice(); - public override EditColumnInfo[] Read(BigEndianStream stream) { + public override ForeignConnectionChoice[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new EditColumnInfo[length]; - var readFn = FfiConverterTypeEditColumnInfo.INSTANCE.Read; + var result = new ForeignConnectionChoice[length]; + var readFn = FfiConverterTypeForeignConnectionChoice.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(ForeignConnectionChoice[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -23971,12 +26212,12 @@ public override int AllocationSize(EditColumnInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeEditColumnInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeForeignConnectionChoice.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(EditColumnInfo[] value, BigEndianStream stream) { + public override void Write(ForeignConnectionChoice[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -23984,7 +26225,7 @@ public override void Write(EditColumnInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeEditColumnInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeForeignConnectionChoice.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -23992,24 +26233,24 @@ public override void Write(EditColumnInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeFavouriteDatabaseInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeFavouriteDatabaseInfo INSTANCE = new FfiConverterSequenceTypeFavouriteDatabaseInfo(); +class FfiConverterSequenceTypeForeignConnectionRow: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeForeignConnectionRow INSTANCE = new FfiConverterSequenceTypeForeignConnectionRow(); - public override FavouriteDatabaseInfo[] Read(BigEndianStream stream) { + public override ForeignConnectionRow[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new FavouriteDatabaseInfo[length]; - var readFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.Read; + var result = new ForeignConnectionRow[length]; + var readFn = FfiConverterTypeForeignConnectionRow.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(FavouriteDatabaseInfo[] value) { + public override int AllocationSize(ForeignConnectionRow[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -24017,12 +26258,12 @@ public override int AllocationSize(FavouriteDatabaseInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeForeignConnectionRow.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(FavouriteDatabaseInfo[] value, BigEndianStream stream) { + public override void Write(ForeignConnectionRow[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -24030,7 +26271,7 @@ public override void Write(FavouriteDatabaseInfo[] value, BigEndianStream stream } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeFavouriteDatabaseInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeForeignConnectionRow.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -24038,24 +26279,24 @@ public override void Write(FavouriteDatabaseInfo[] value, BigEndianStream stream -class FfiConverterSequenceTypeFavouriteTableInfo: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeFavouriteTableInfo INSTANCE = new FfiConverterSequenceTypeFavouriteTableInfo(); +class FfiConverterSequenceTypeForeignQueryChoice: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeForeignQueryChoice INSTANCE = new FfiConverterSequenceTypeForeignQueryChoice(); - public override FavouriteTableInfo[] Read(BigEndianStream stream) { + public override ForeignQueryChoice[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new FavouriteTableInfo[length]; - var readFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.Read; + var result = new ForeignQueryChoice[length]; + var readFn = FfiConverterTypeForeignQueryChoice.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(FavouriteTableInfo[] value) { + public override int AllocationSize(ForeignQueryChoice[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -24063,12 +26304,12 @@ public override int AllocationSize(FavouriteTableInfo[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeForeignQueryChoice.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(FavouriteTableInfo[] value, BigEndianStream stream) { + public override void Write(ForeignQueryChoice[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -24076,7 +26317,7 @@ public override void Write(FavouriteTableInfo[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeFavouriteTableInfo.INSTANCE.Write; + var writerFn = FfiConverterTypeForeignQueryChoice.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -24084,24 +26325,24 @@ public override void Write(FavouriteTableInfo[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeFilterColumn: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeFilterColumn INSTANCE = new FfiConverterSequenceTypeFilterColumn(); +class FfiConverterSequenceTypeForeignQueryRow: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeForeignQueryRow INSTANCE = new FfiConverterSequenceTypeForeignQueryRow(); - public override FilterColumn[] Read(BigEndianStream stream) { + public override ForeignQueryRow[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new FilterColumn[length]; - var readFn = FfiConverterTypeFilterColumn.INSTANCE.Read; + var result = new ForeignQueryRow[length]; + var readFn = FfiConverterTypeForeignQueryRow.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(FilterColumn[] value) { + public override int AllocationSize(ForeignQueryRow[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -24109,12 +26350,12 @@ public override int AllocationSize(FilterColumn[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeFilterColumn.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeForeignQueryRow.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(FilterColumn[] value, BigEndianStream stream) { + public override void Write(ForeignQueryRow[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -24122,7 +26363,7 @@ public override void Write(FilterColumn[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeFilterColumn.INSTANCE.Write; + var writerFn = FfiConverterTypeForeignQueryRow.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -24130,24 +26371,24 @@ public override void Write(FilterColumn[] value, BigEndianStream stream) { -class FfiConverterSequenceTypeFilterRuleArg: FfiConverterRustBuffer { - public static FfiConverterSequenceTypeFilterRuleArg INSTANCE = new FfiConverterSequenceTypeFilterRuleArg(); +class FfiConverterSequenceTypeForeignSourceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeForeignSourceInfo INSTANCE = new FfiConverterSequenceTypeForeignSourceInfo(); - public override FilterRuleArg[] Read(BigEndianStream stream) { + public override ForeignSourceInfo[] Read(BigEndianStream stream) { var length = stream.ReadInt(); if (length == 0) { return []; } - var result = new FilterRuleArg[length]; - var readFn = FfiConverterTypeFilterRuleArg.INSTANCE.Read; + var result = new ForeignSourceInfo[length]; + var readFn = FfiConverterTypeForeignSourceInfo.INSTANCE.Read; for (int i = 0; i < length; i++) { result[i] = readFn(stream); } return result; } - public override int AllocationSize(FilterRuleArg[] value) { + public override int AllocationSize(ForeignSourceInfo[] value) { var sizeForLength = 4; // details/1-empty-list-as-default-method-parameter.md @@ -24155,12 +26396,12 @@ public override int AllocationSize(FilterRuleArg[] value) { return sizeForLength; } - var allocationSizeFn = FfiConverterTypeFilterRuleArg.INSTANCE.AllocationSize; + var allocationSizeFn = FfiConverterTypeForeignSourceInfo.INSTANCE.AllocationSize; var sizeForItems = value.Sum(item => allocationSizeFn(item)); return sizeForLength + sizeForItems; } - public override void Write(FilterRuleArg[] value, BigEndianStream stream) { + public override void Write(ForeignSourceInfo[] value, BigEndianStream stream) { // details/1-empty-list-as-default-method-parameter.md if (value == null) { stream.WriteInt(0); @@ -24168,7 +26409,7 @@ public override void Write(FilterRuleArg[] value, BigEndianStream stream) { } stream.WriteInt(value.Length); - var writerFn = FfiConverterTypeFilterRuleArg.INSTANCE.Write; + var writerFn = FfiConverterTypeForeignSourceInfo.INSTANCE.Write; value.ForEach(item => writerFn(item, stream)); } } @@ -25372,6 +27613,52 @@ public override void Write(FilterOpTag[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeResolutionTag: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeResolutionTag INSTANCE = new FfiConverterSequenceTypeResolutionTag(); + + public override ResolutionTag[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ResolutionTag[length]; + var readFn = FfiConverterTypeResolutionTag.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ResolutionTag[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeResolutionTag.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ResolutionTag[] 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 = FfiConverterTypeResolutionTag.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeRowEdit: FfiConverterRustBuffer { public static FfiConverterSequenceTypeRowEdit INSTANCE = new FfiConverterSequenceTypeRowEdit(); @@ -25418,6 +27705,52 @@ public override void Write(RowEdit[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeRowNoteInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeRowNoteInfo INSTANCE = new FfiConverterSequenceTypeRowNoteInfo(); + + public override RowNoteInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new RowNoteInfo[length]; + var readFn = FfiConverterTypeRowNoteInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(RowNoteInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeRowNoteInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(RowNoteInfo[] 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 = FfiConverterTypeRowNoteInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeRunEvent: FfiConverterRustBuffer { public static FfiConverterSequenceTypeRunEvent INSTANCE = new FfiConverterSequenceTypeRunEvent(); diff --git a/windows/src/TablePro.Interop/Mapping.ForeignImport.cs b/windows/src/TablePro.Interop/Mapping.ForeignImport.cs new file mode 100644 index 0000000000..bbd9a1fa8c --- /dev/null +++ b/windows/src/TablePro.Interop/Mapping.ForeignImport.cs @@ -0,0 +1,138 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +internal static partial class Mapping +{ + public static ForeignApp ForeignApp(Native.ForeignAppTag app) => app switch + { + Native.ForeignAppTag.TablePlus => Interop.ForeignApp.TablePlus, + Native.ForeignAppTag.SequelAce => Interop.ForeignApp.SequelAce, + Native.ForeignAppTag.DBeaver => Interop.ForeignApp.DBeaver, + Native.ForeignAppTag.DataGrip => Interop.ForeignApp.DataGrip, + Native.ForeignAppTag.BeekeeperStudio => Interop.ForeignApp.BeekeeperStudio, + Native.ForeignAppTag.Navicat => Interop.ForeignApp.Navicat, + _ => Interop.ForeignApp.Dbx, + }; + + public static Native.ForeignAppTag ForeignApp(ForeignApp app) => app switch + { + Interop.ForeignApp.TablePlus => Native.ForeignAppTag.TablePlus, + Interop.ForeignApp.SequelAce => Native.ForeignAppTag.SequelAce, + Interop.ForeignApp.DBeaver => Native.ForeignAppTag.DBeaver, + Interop.ForeignApp.DataGrip => Native.ForeignAppTag.DataGrip, + Interop.ForeignApp.BeekeeperStudio => Native.ForeignAppTag.BeekeeperStudio, + Interop.ForeignApp.Navicat => Native.ForeignAppTag.Navicat, + _ => Native.ForeignAppTag.Dbx, + }; + + public static Native.ForeignAppDirsArg Dirs(ForeignAppDirs dirs) => new(dirs.Home, dirs.Config, dirs.Data); + + public static ForeignSource Source(Native.ForeignSourceInfo source) => new( + ForeignApp(source.App), + source.Name, + source.Available, + Count(source.Connections), + Count(source.SavedQueries), + [.. source.FileExtensions], + source.Passwords == Native.PasswordSourceTag.AppFiles + ? ForeignPasswordSource.AppFiles + : ForeignPasswordSource.Keychain, + source.SavedQuerySupport switch + { + Native.SavedQuerySupportTag.GlobalFolder => ForeignSavedQuerySupport.GlobalFolder, + Native.SavedQuerySupportTag.Scripts => ForeignSavedQuerySupport.Scripts, + Native.SavedQuerySupportTag.Consoles => ForeignSavedQuerySupport.Consoles, + _ => ForeignSavedQuerySupport.NotInExport, + }); + + public static ForeignPasswordOutcome Outcome(Native.PasswordOutcomeTag outcome) => outcome switch + { + Native.PasswordOutcomeTag.NotRequested => ForeignPasswordOutcome.NotRequested, + Native.PasswordOutcomeTag.Read => ForeignPasswordOutcome.Read, + Native.PasswordOutcomeTag.Stopped => ForeignPasswordOutcome.Stopped, + _ => ForeignPasswordOutcome.LeftBehind, + }; + + public static ForeignConnectionRow ForeignRow(Native.ForeignConnectionRow row) => new( + row.Reference, + row.Name, + row.Engine, + row.Connection is { } connection ? Connection(connection) : null, + [.. row.GroupPath], + row.Duplicate is { } duplicate ? new ExistingConnection(Guid.Parse(duplicate.Id), duplicate.Name) : null, + [.. row.Notes.Select(Note)], + checked((int)row.SavedQueryCount), + row.CarriesPasswords); + + public static ForeignResolution Resolution(Native.ResolutionTag resolution) => resolution switch + { + Native.ResolutionTag.Replace replace => new ForeignResolution.Replace(Guid.Parse(replace.Id)), + Native.ResolutionTag.KeepExisting keep => new ForeignResolution.KeepExisting(Guid.Parse(keep.Id)), + Native.ResolutionTag.AddCopy => ForeignResolution.AddCopy.Instance, + _ => ForeignResolution.Add.Instance, + }; + + public static Native.ResolutionTag Resolution(ForeignResolution resolution) => resolution switch + { + ForeignResolution.Replace replace => new Native.ResolutionTag.Replace(replace.Id.ToString()), + ForeignResolution.KeepExisting keep => new Native.ResolutionTag.KeepExisting(keep.Id.ToString()), + ForeignResolution.AddCopy => new Native.ResolutionTag.AddCopy(), + _ => new Native.ResolutionTag.Add(), + }; + + public static ForeignQueryAvailability Availability(Native.QueryAvailabilityTag availability) => availability switch + { + Native.QueryAvailabilityTag.Available => ForeignQueryAvailability.Available, + Native.QueryAvailabilityTag.AddedByAnotherRow => ForeignQueryAvailability.AddedByAnotherRow, + Native.QueryAvailabilityTag.TooLarge => ForeignQueryAvailability.TooLarge, + Native.QueryAvailabilityTag.NameTooLong => ForeignQueryAvailability.NameTooLong, + Native.QueryAvailabilityTag.ConnectionSkipped => ForeignQueryAvailability.ConnectionSkipped, + _ => ForeignQueryAvailability.NoConnection, + }; + + private static ForeignRowNote Note(Native.RowNoteInfo note) => note switch + { + Native.RowNoteInfo.UnsupportedEngine unsupported => new ForeignRowNote.UnsupportedEngine(unsupported.Engine), + Native.RowNoteInfo.SshKeyMissing missing => new ForeignRowNote.SshKeyMissing(missing.Path), + Native.RowNoteInfo.JumpHostKeyMissing missing => new ForeignRowNote.JumpHostKeyMissing(missing.Path), + Native.RowNoteInfo.CaCertificateMissing missing => new ForeignRowNote.CaCertificateMissing(missing.Path), + Native.RowNoteInfo.ClientCertificateMissing missing => + new ForeignRowNote.ClientCertificateMissing(missing.Path), + Native.RowNoteInfo.ClientKeyMissing missing => new ForeignRowNote.ClientKeyMissing(missing.Path), + Native.RowNoteInfo.TlsModeChanged changed => + new ForeignRowNote.TlsModeChanged(SslMode(changed.From), Tls(changed.To)), + Native.RowNoteInfo.TlsSettingsNotRead => new ForeignRowNote.TlsSettingsNotRead(), + Native.RowNoteInfo.TlsFromDriverDefault from => new ForeignRowNote.TlsFromDriverDefault(SslMode(from.Mode)), + Native.RowNoteInfo.TlsNotKept dropped => new ForeignRowNote.TlsNotKept(SslMode(dropped.From)), + Native.RowNoteInfo.CaFileNotKept dropped => + new ForeignRowNote.CaFileNotKept(dropped.Path, FileReason(dropped.Reason)), + Native.RowNoteInfo.ClientIdentityNotKept dropped => + new ForeignRowNote.ClientIdentityNotKept(FileReason(dropped.Reason)), + Native.RowNoteInfo.SshNotKept => new ForeignRowNote.SshNotKept(), + Native.RowNoteInfo.SshKeyNotKept dropped => new ForeignRowNote.SshKeyNotKept(dropped.Path), + Native.RowNoteInfo.JumpHostNotKept dropped => new ForeignRowNote.JumpHostNotKept(dropped.Host), + Native.RowNoteInfo.JumpHostPasswordNotKept dropped => new ForeignRowNote.JumpHostPasswordNotKept(dropped.Host), + Native.RowNoteInfo.JumpHostKeyNotKept dropped => + new ForeignRowNote.JumpHostKeyNotKept(dropped.Host, dropped.Path), + Native.RowNoteInfo.FieldsNotKept dropped => new ForeignRowNote.FieldsNotKept([.. dropped.Fields]), + _ => throw new InvalidOperationException("The core reported a note this build does not know."), + }; + + private static ForeignSslMode SslMode(Native.ForeignSslModeTag mode) => mode switch + { + Native.ForeignSslModeTag.Disabled => ForeignSslMode.Disabled, + Native.ForeignSslModeTag.Preferred => ForeignSslMode.Preferred, + Native.ForeignSslModeTag.Required => ForeignSslMode.Required, + Native.ForeignSslModeTag.VerifyCa => ForeignSslMode.VerifyCa, + _ => ForeignSslMode.VerifyIdentity, + }; + + private static TlsFileReason FileReason(Native.TlsFileReasonTag reason) => reason switch + { + Native.TlsFileReasonTag.EngineLacks => TlsFileReason.EngineLacks, + Native.TlsFileReasonTag.ModeLacks => TlsFileReason.ModeLacks, + Native.TlsFileReasonTag.RelativePath => TlsFileReason.RelativePath, + _ => TlsFileReason.Incomplete, + }; +} diff --git a/windows/src/TablePro.Interop/Mapping.cs b/windows/src/TablePro.Interop/Mapping.cs index 21df0311a0..ff910aefeb 100644 --- a/windows/src/TablePro.Interop/Mapping.cs +++ b/windows/src/TablePro.Interop/Mapping.cs @@ -532,7 +532,7 @@ [.. snapshot.Recent.Select(Guid.Parse)]) _ => Native.TlsModeTag.VerifyFull, }; - private static TlsMode Tls(Native.TlsModeTag mode) => mode switch + public static TlsMode Tls(Native.TlsModeTag mode) => mode switch { Native.TlsModeTag.Disable => TlsMode.Disable, Native.TlsModeTag.Prefer => TlsMode.Prefer, @@ -596,6 +596,11 @@ private static List Columns(Native.ResultColumnInfo[] columns) => Native.EditLock.ReadOnlyConnection => EditLock.ReadOnlyConnection, Native.EditLock.NoPrimaryKey => EditLock.NoPrimaryKey, Native.EditLock.KeyUnreadable => EditLock.KeyUnreadable, + Native.EditLock.NotOneSelect => EditLock.NotOneSelect, + Native.EditLock.MoreThanOneTable => EditLock.MoreThanOneTable, + Native.EditLock.Collapsed => EditLock.Collapsed, + Native.EditLock.Untraced => EditLock.Untraced, + Native.EditLock.KeyNotShown => EditLock.KeyNotShown, _ => EditLock.ColumnsChanged, }; diff --git a/windows/src/TablePro.Interop/RowEdits.cs b/windows/src/TablePro.Interop/RowEdits.cs index 13b660bb40..7f91c2c55c 100644 --- a/windows/src/TablePro.Interop/RowEdits.cs +++ b/windows/src/TablePro.Interop/RowEdits.cs @@ -1,12 +1,22 @@ namespace TablePro.Interop; -// Why no row of a table, or of a page, can be changed. +// Why no row of a table, a page or a query result can be changed. public enum EditLock { ReadOnlyConnection, NoPrimaryKey, KeyUnreadable, ColumnsChanged, + // A query result's statement is not one SELECT. + NotOneSelect, + // A join, a subquery or a CTE. + MoreThanOneTable, + // DISTINCT, GROUP BY or a function in the select list. + Collapsed, + // No column traced to the statement's table: a view, a temporary table, or an engine that says nothing. + Untraced, + // The result leaves out part of the table's primary key. + KeyNotShown, } // An empty text means what the core's parse says for the column: the empty string, the server's default, or NULL. diff --git a/windows/src/TablePro.Interop/TableEditor.cs b/windows/src/TablePro.Interop/TableEditor.cs index e13b486caf..124266baf0 100644 --- a/windows/src/TablePro.Interop/TableEditor.cs +++ b/windows/src/TablePro.Interop/TableEditor.cs @@ -33,6 +33,17 @@ internal TableEditor(Native.TableEditor editor) public IReadOnlyList Columns { get; } + // The table a save writes; null while a query result is locked. + public TableName? Table => _editor.Table() is { } table ? new TableName(table.Schema, table.Name) : null; + + // A query result row whose values read as the server's text for a float, a time or money does not copy exactly. + public bool CopiesExactly(ResultSet rows, long row) + { + ArgumentNullException.ThrowIfNull(rows); + ArgumentOutOfRangeException.ThrowIfNegative(row); + return CoreCall.Run(() => _editor.CopiesExactly(rows.Handle, checked((ulong)row))); + } + public EditStart GetEditStart(ResultSet rows, long row, int column) { ArgumentNullException.ThrowIfNull(rows); diff --git a/windows/src/TablePro.Interop/TableProCore.cs b/windows/src/TablePro.Interop/TableProCore.cs index 607b6eef29..b29f48ddf5 100644 --- a/windows/src/TablePro.Interop/TableProCore.cs +++ b/windows/src/TablePro.Interop/TableProCore.cs @@ -56,6 +56,32 @@ public static void CheckJumpHosts(string list) CoreCall.Run(() => Native.CoreMethods.CheckJumpHosts(list)); } + // The other apps Windows has, each looked for where it keeps its files; nothing is decrypted yet. + public async Task> GetForeignSourcesAsync(ForeignAppDirs dirs) + { + ArgumentNullException.ThrowIfNull(dirs); + var sources = await CoreCall.RunAsync(() => _core.ForeignSources(Mapping.Dirs(dirs))).ConfigureAwait(false); + return [.. sources.Select(Mapping.Source)]; + } + + // File is the export the user picked, for an app imported from one. Throws foreign_import.* codes. + public async Task ReadForeignAsync( + ForeignApp app, + ForeignAppDirs dirs, + string? file, + ForeignImportRequest request, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(dirs); + ArgumentNullException.ThrowIfNull(request); + var native = new Native.ForeignImportRequest(request.IncludePasswords, request.IncludeSavedQueries); + var review = await CoreCall.RunAsync( + token => _core.ReadForeign(Mapping.ForeignApp(app), Mapping.Dirs(dirs), file, native, token), + cancellationToken) + .ConfigureAwait(false); + return new ForeignImportReview(review); + } + // Opened once per core and shared. Throws TableProException with code ffi.no_storage without a storage directory. public async Task OpenHistoryAsync(CancellationToken cancellationToken = default) { diff --git a/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs b/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs index 8f1ad46928..227144c652 100644 --- a/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs +++ b/windows/tests/TablePro.App.Model.Tests/DefinitionTabTests.cs @@ -286,4 +286,7 @@ public Task OpenTableEditorAsync( bool refresh, CancellationToken cancellationToken) => throw new NotSupportedException(); + + public Task OpenResultEditorAsync(string sql, ResultSet? rows, CancellationToken cancellationToken) => + throw new NotSupportedException(); } diff --git a/windows/tests/TablePro.App.Model.Tests/ForeignImportFormTests.cs b/windows/tests/TablePro.App.Model.Tests/ForeignImportFormTests.cs new file mode 100644 index 0000000000..d2a1a3037e --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/ForeignImportFormTests.cs @@ -0,0 +1,528 @@ +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class ForeignImportFormTests +{ + private static readonly Guid Saved = Guid.Parse("8c1d7f3e-4b0a-4d6e-9a51-2f6c0e7b9d10"); + + [Theory] + [InlineData(ForeignApp.DBeaver, true, ForeignPasswordNote.DecryptedWhileReading, true)] + [InlineData(ForeignApp.DataGrip, true, ForeignPasswordNote.PasswordFile, true)] + [InlineData(ForeignApp.Dbx, false, ForeignPasswordNote.SystemStore, true)] + [InlineData(ForeignApp.TablePlus, false, ForeignPasswordNote.SystemStore, false)] + [InlineData(ForeignApp.Navicat, true, ForeignPasswordNote.DecryptedWhileReading, false)] + public async Task TheOptionsFollowWhereTheChosenAppKeepsItsPasswordsAndQueries( + ForeignApp app, bool passwords, ForeignPasswordNote note, bool queries) + { + var form = await Loaded(new FakeImporter(Sources(tablePlusFound: true))); + + Assert.True(form.Choose(app)); + + Assert.Equal(new ForeignPasswordOption(passwords, passwords, note), form.Passwords); + Assert.Equal(queries, form.Queries.Offered); + Assert.Equal(queries, form.Queries.Checked); + Assert.Equal(form.Sources.Single(source => source.App == app).SavedQuerySupport, form.Queries.Support); + } + + [Fact] + public async Task TheFirstAppFoundIsChosenAndOneNotFoundCannotBe() + { + var form = await Loaded(new FakeImporter(Sources())); + + Assert.Equal(ForeignImportStep.Choosing, form.Step); + Assert.Equal(ForeignApp.DBeaver, form.Chosen?.App); + Assert.False(form.Choose(ForeignApp.TablePlus)); + Assert.False(form.Choose(ForeignApp.BeekeeperStudio)); + Assert.Equal(ForeignApp.DBeaver, form.Chosen?.App); + Assert.True(form.CanContinue); + Assert.Equal( + [ + ForeignSourceNote.NotFound, + ForeignSourceNote.Found, + ForeignSourceNote.Found, + ForeignSourceNote.NotFound, + ForeignSourceNote.PicksFile, + ForeignSourceNote.Found, + ], + form.Sources.Select(ForeignImportForm.NoteFor)); + } + + [Fact] + public async Task AppsThatCannotBeLookedForLeaveAnEmptyListAndNothingToContinue() + { + var importer = new FakeImporter(Sources()) { SourcesFailure = Error("storage.io") }; + + var form = await Loaded(importer); + + Assert.Empty(form.Sources); + Assert.Equal("storage.io", form.SourcesError?.Code); + Assert.Null(form.Chosen); + Assert.False(form.CanContinue); + Assert.False(form.Passwords.Offered); + Assert.False(form.Queries.Offered); + } + + [Fact] + public async Task AKeychainAppIsStillAskedForPasswordsSoTheReviewSaysTheyStayedBehind() + { + var importer = new FakeImporter(Sources(tablePlusFound: true)) { Review = Review() }; + var form = await Loaded(importer); + + form.Choose(ForeignApp.TablePlus); + form.SetPasswords(false); + await form.ReadAsync(null, TestContext.Current.CancellationToken); + + var read = Assert.Single(importer.Reads); + Assert.Equal(ForeignApp.TablePlus, read.App); + Assert.Null(read.File); + Assert.Equal(new ForeignImportRequest(true, false), read.Request); + } + + [Fact] + public async Task TheBoxesKeepTheirAnswersWhileAnAppThatCannotHonourThemIsChosen() + { + var importer = new FakeImporter(Sources()) { Review = Review() }; + var form = await Loaded(importer); + + form.SetPasswords(false); + form.SetQueries(false); + form.Choose(ForeignApp.Navicat); + form.SetQueries(true); + form.Choose(ForeignApp.DBeaver); + + Assert.False(form.Passwords.Checked); + Assert.False(form.Queries.Checked); + Assert.Equal(new ForeignImportRequest(false, false), form.Request()); + form.SetPasswords(true); + Assert.Equal(new ForeignImportRequest(true, false), form.Request()); + } + + [Fact] + public async Task AnAppReadFromAnExportNeedsTheFileAndOthersNeverTakeOne() + { + var importer = new FakeImporter(Sources()) { Review = Review() }; + var form = await Loaded(importer); + var token = TestContext.Current.CancellationToken; + + form.Choose(ForeignApp.Navicat); + Assert.False(await form.ReadAsync(null, token)); + Assert.Empty(importer.Reads); + Assert.True(await form.ReadAsync(@"C:\exports\connections.ncx", token)); + + var second = await Loaded(importer); + Assert.True(await second.ReadAsync(@"C:\exports\connections.ncx", token)); + + Assert.Equal<(ForeignApp, string?, ForeignImportRequest)>( + [ + (ForeignApp.Navicat, @"C:\exports\connections.ncx", new ForeignImportRequest(true, false)), + (ForeignApp.DBeaver, null, new ForeignImportRequest(true, true)), + ], + importer.Reads); + } + + [Fact] + public async Task AReviewListsEachRowWithItsChecksAndASummary() + { + var form = await Read(Review()); + + Assert.Equal(ForeignImportStep.Reviewing, form.Step); + Assert.Equal(ForeignApp.DBeaver, form.ReviewedApp); + Assert.Equal(ForeignPasswordOutcome.Read, form.PasswordOutcome); + Assert.Equal([true, false, false], form.Connections.Select(line => line.Selected)); + Assert.Equal([true, true, false], form.Connections.Select(line => line.Selectable)); + Assert.Equal( + [ForeignQueryAvailability.Available, ForeignQueryAvailability.ConnectionSkipped], + form.SavedQueries.Select(line => line.Availability)); + Assert.Equal(new ForeignImportSummary(1, 3, 1, 2), form.Summary); + Assert.True(form.CanImport); + } + + [Fact] + public async Task AMatchedRowAsksHowToResolveOnlyWhileItIsChecked() + { + var form = await Read(Review()); + var before = form.Connections[1]; + + form.SetSelected("billing", true); + var chosen = form.Connections[1]; + var replaced = form.Resolve("billing", new ForeignResolution.Replace(Saved)); + + Assert.False(before.ShowsResolution); + Assert.False(before.CanResolve); + Assert.True(chosen.ShowsResolution); + Assert.True(chosen.CanResolve); + Assert.Equal( + [ForeignResolution.AddCopy.Instance, new ForeignResolution.Replace(Saved)], + chosen.Offered); + Assert.Equal(ForeignResolution.AddCopy.Instance, chosen.Resolution); + Assert.True(replaced); + Assert.Equal(new ForeignResolution.Replace(Saved), form.Connections[1].Resolution); + Assert.False(form.Connections[0].ShowsResolution); + } + + [Fact] + public async Task EachCheckIsCountedAgainAndAQueryFollowsItsConnection() + { + var form = await Read(Review()); + + form.SetSelected("billing", true); + Assert.Equal(new ForeignImportSummary(2, 3, 2, 2), form.Summary); + + form.SetIncluded("query-1", false); + Assert.Equal(new ForeignImportSummary(2, 3, 1, 2), form.Summary); + + form.SetSelected("orders", false); + form.SetSelected("billing", false); + Assert.Equal(new ForeignImportSummary(0, 3, 0, 2), form.Summary); + Assert.False(form.SavedQueries[1].Importable); + Assert.False(form.CanImport); + Assert.Null(await form.ImportAsync()); + } + + [Theory] + [InlineData("foreign_import.file_not_found", ForeignReadFailureKind.NotFound)] + [InlineData("foreign_import.nothing_found", ForeignReadFailureKind.NothingFound)] + [InlineData("foreign_import.unreadable", ForeignReadFailureKind.Unreadable)] + [InlineData("foreign_import.parse", ForeignReadFailureKind.Unreadable)] + [InlineData("foreign_import.unsupported_format", ForeignReadFailureKind.Unreadable)] + [InlineData("storage.corrupt", ForeignReadFailureKind.Library)] + [InlineData("ffi.panicked", ForeignReadFailureKind.Other)] + public async Task AFailedReadReturnsToTheAppsWithWhyAndAnotherAppClearsIt(string code, ForeignReadFailureKind kind) + { + var failure = Error(code); + var form = await Loaded(new FakeImporter(Sources()) { Failure = failure }); + + Assert.False(await form.ReadAsync(null, TestContext.Current.CancellationToken)); + + Assert.Equal(ForeignImportStep.Choosing, form.Step); + Assert.Equal(new ForeignReadFailure(ForeignApp.DBeaver, kind, failure), form.Failure); + form.Choose(ForeignApp.DataGrip); + Assert.Null(form.Failure); + } + + [Fact] + public async Task ACancelledReadReturnsToTheAppsWithNoFailure() + { + var form = await Loaded(new FakeImporter(Sources()) { Cancels = true }); + + Assert.False(await form.ReadAsync(null, TestContext.Current.CancellationToken)); + + Assert.Equal(ForeignImportStep.Choosing, form.Step); + Assert.Null(form.Failure); + } + + [Fact] + public async Task AReadThatLandsAfterTheDialogClosedIsLetGo() + { + var pending = new TaskCompletionSource(); + var form = await Loaded(new FakeImporter(Sources()) { Pending = pending }); + var review = Review(); + + var reading = form.ReadAsync(null, TestContext.Current.CancellationToken); + Assert.Equal(ForeignImportStep.Reading, form.Step); + form.Dispose(); + pending.SetResult(review); + + Assert.False(await reading); + Assert.True(review.Disposed); + Assert.Empty(form.Connections); + } + + [Fact] + public async Task AnImportSaysWhatLandedAndWhatDidNotInOrder() + { + var review = Review(); + review.Outcome = new ForeignImportOutcome(2, 1, 1, 3, 0, 1); + var form = await Read(review); + + var ending = await form.ImportAsync(); + + Assert.NotNull(ending); + Assert.Equal( + [ + new ForeignImportSentence(ForeignImportPart.Connections, 2), + new ForeignImportSentence(ForeignImportPart.QueriesAdded, 3), + new ForeignImportSentence(ForeignImportPart.QueriesNotAdded, 1), + new ForeignImportSentence(ForeignImportPart.PasswordsNotKept, 1), + ], + ending.Sentences); + Assert.True(ending.Wrote); + Assert.True(ending.Partial); + Assert.False(ending.Nothing); + Assert.Equal(1, review.Applies); + Assert.Equal(ForeignImportStep.Done, form.Step); + Assert.False(form.CanImport); + Assert.Null(await form.ImportAsync()); + } + + [Fact] + public async Task AnImportThatWroteNothingSaysSo() + { + var form = await Read(Review()); + + var ending = await form.ImportAsync(); + + Assert.Equal([new ForeignImportSentence(ForeignImportPart.Nothing)], ending?.Sentences); + Assert.True(ending?.Nothing); + Assert.False(ending?.Partial); + } + + [Fact] + public async Task ALibraryChangedWhileDecidingRefusesAndAsksToImportAgain() + { + var review = Review(); + review.Refusal = Error(ForeignImportEnding.OutdatedCode); + var form = await Read(review); + + var ending = await form.ImportAsync(); + + Assert.NotNull(ending); + Assert.Equal([new ForeignImportSentence(ForeignImportPart.Outdated)], ending.Sentences); + Assert.True(ending.Outdated); + Assert.False(ending.Wrote); + Assert.Equal(ForeignImportStep.Done, form.Step); + } + + [Fact] + public async Task AnotherRefusalCarriesItsError() + { + var review = Review(); + review.Refusal = Error("storage.io"); + var form = await Read(review); + + var ending = await form.ImportAsync(); + + Assert.Equal([new ForeignImportSentence(ForeignImportPart.Failed)], ending?.Sentences); + Assert.Equal("storage.io", ending?.Error?.Code); + Assert.False(ending?.Outdated); + } + + private static async Task Loaded(FakeImporter importer) + { + var form = new ForeignImportForm(importer); + await form.LoadAsync(); + return form; + } + + private static async Task Read(FakeReview review) + { + var form = await Loaded(new FakeImporter(Sources()) { Review = review }); + Assert.True(await form.ReadAsync(null, TestContext.Current.CancellationToken)); + return form; + } + + private static CoreError Error(string code) => new(code, [code], code, null, null); + + // The apps the core lists on Windows, in its order. + private static IReadOnlyList Sources(bool tablePlusFound = false) => + [ + Source( + ForeignApp.TablePlus, + tablePlusFound, + ForeignPasswordSource.Keychain, + ForeignSavedQuerySupport.GlobalFolder), + Source(ForeignApp.DBeaver, true, ForeignPasswordSource.AppFiles, ForeignSavedQuerySupport.Scripts), + Source(ForeignApp.DataGrip, true, ForeignPasswordSource.Keychain, ForeignSavedQuerySupport.Consoles), + Source( + ForeignApp.BeekeeperStudio, + false, + ForeignPasswordSource.AppFiles, + ForeignSavedQuerySupport.GlobalFolder), + new ForeignSource( + ForeignApp.Navicat, + "Navicat", + true, + 0, + 0, + ["ncx"], + ForeignPasswordSource.AppFiles, + ForeignSavedQuerySupport.NotInExport), + Source(ForeignApp.Dbx, true, ForeignPasswordSource.Keychain, ForeignSavedQuerySupport.Scripts), + ]; + + private static ForeignSource Source( + ForeignApp app, + bool found, + ForeignPasswordSource passwords, + ForeignSavedQuerySupport queries) => + new(app, app.ToString(), found, found ? 2 : 0, found ? 1 : 0, [], passwords, queries); + + // Orders imports, billing matches a saved connection, ledger is an engine no driver opens. + private static FakeReview Review() => new( + [ + Row("orders", "Orders", "postgres"), + Row("billing", "Billing", "mysql") with { Duplicate = new ExistingConnection(Saved, "billing") }, + Row("ledger", "Ledger", "oracle") with + { + Connection = null, + Notes = [new ForeignRowNote.UnsupportedEngine("Oracle")], + }, + ], + [ + new ForeignQueryRow("query-1", "Daily orders", "orders", "Orders", 24), + new ForeignQueryRow("query-2", "Invoices", "billing", "Billing", 31), + ]); + + private static ForeignConnectionRow Row(string reference, string name, string engine) => new( + reference, + name, + engine, + new SavedConnection( + null, name, engine, $"{reference}.example.com", 5432, reference, "deploy", TlsSettings.Disabled), + [], + null, + [], + 1, + false); +} + +internal sealed class FakeImporter(IReadOnlyList sources) : IForeignImporter +{ + public List<(ForeignApp App, string? File, ForeignImportRequest Request)> Reads { get; } = []; + + public FakeReview? Review { get; init; } + + public CoreError? SourcesFailure { get; init; } + + public CoreError? Failure { get; init; } + + public bool Cancels { get; init; } + + public TaskCompletionSource? Pending { get; init; } + + public Task> GetSourcesAsync() => SourcesFailure is { } failure + ? Task.FromException>(new TableProException(failure)) + : Task.FromResult(sources); + + public Task ReadAsync( + ForeignApp app, + string? file, + ForeignImportRequest request, + CancellationToken cancellationToken) + { + Reads.Add((app, file, request)); + if (Pending is { } pending) + { + return pending.Task; + } + + if (Failure is { } failure) + { + return Task.FromException(new TableProException(failure)); + } + + if (Cancels) + { + return Task.FromCanceled(new CancellationToken(canceled: true)); + } + + return Task.FromResult(Review ?? throw new InvalidOperationException("No review to read.")); + } +} + +// The core's rules in small: a matched or unopenable row starts unchecked, and a query imports with its connection. +internal sealed class FakeReview : IForeignReview +{ + private readonly HashSet _selected; + private readonly HashSet _excluded = []; + private readonly Dictionary _resolutions = []; + + public FakeReview(IReadOnlyList connections, IReadOnlyList queries) + { + Connections = connections; + SavedQueries = queries; + _selected = [.. connections + .Where(row => row.Connection is not null && row.Duplicate is null) + .Select(row => row.Reference)]; + } + + public ForeignApp App => ForeignApp.DBeaver; + + public ForeignPasswordOutcome Passwords => ForeignPasswordOutcome.Read; + + public IReadOnlyList Connections { get; } + + public IReadOnlyList SavedQueries { get; } + + public ForeignImportOutcome Outcome { get; set; } = new(0, 0, 0, 0, 0, 0); + + public CoreError? Refusal { get; set; } + + public int Applies { get; private set; } + + public bool Disposed { get; private set; } + + public ForeignImportChoices Choices() + { + List connections = [.. Connections.Select(row => new ForeignConnectionChoice( + row.Reference, + _selected.Contains(row.Reference), + _resolutions.GetValueOrDefault(row.Reference) ?? Offered(row)[0], + Offered(row)))]; + List queries = [.. SavedQueries.Select(query => + { + var availability = query.Connection is null ? ForeignQueryAvailability.NoConnection + : _selected.Contains(query.Connection) ? ForeignQueryAvailability.Available + : ForeignQueryAvailability.ConnectionSkipped; + return new ForeignQueryChoice( + query.Reference, + availability, + availability == ForeignQueryAvailability.Available && !_excluded.Contains(query.Reference)); + })]; + return new ForeignImportChoices( + connections, + queries, + connections.Any(choice => choice.Selected) || queries.Any(choice => choice.Included)); + } + + public void SetSelected(string reference, bool selected) + { + if (selected) + { + _selected.Add(reference); + } + else + { + _selected.Remove(reference); + } + } + + public bool Resolve(string reference, ForeignResolution resolution) + { + if (Connections.FirstOrDefault(row => row.Reference == reference) is not { } row + || !Offered(row).Contains(resolution)) + { + return false; + } + + _resolutions[reference] = resolution; + return true; + } + + public void SetIncluded(string reference, bool included) + { + if (included) + { + _excluded.Remove(reference); + } + else + { + _excluded.Add(reference); + } + } + + public Task ApplyAsync() + { + Applies++; + return Refusal is { } refusal + ? Task.FromException(new TableProException(refusal)) + : Task.FromResult(Outcome); + } + + public void Dispose() => Disposed = true; + + private static List Offered(ForeignConnectionRow row) => row.Duplicate is { } existing + ? [ForeignResolution.AddCopy.Instance, new ForeignResolution.Replace(existing.Id)] + : [ForeignResolution.Add.Instance]; +} diff --git a/windows/tests/TablePro.App.Model.Tests/QueryTabEditingTests.cs b/windows/tests/TablePro.App.Model.Tests/QueryTabEditingTests.cs new file mode 100644 index 0000000000..3272a7c9d4 --- /dev/null +++ b/windows/tests/TablePro.App.Model.Tests/QueryTabEditingTests.cs @@ -0,0 +1,377 @@ +using TablePro.DataGrid.Model; +using TablePro.Interop; + +namespace TablePro.App.Model.Tests; + +public sealed class QueryTabEditingTests +{ + private readonly FakeSession _session = new() { Script = _ => FakeRun.Rows(3) }; + private readonly FakeQueryView _view = new(); + private readonly FakeResults _results = new(); + private readonly FakeResultEditView _edits = new(); + private readonly FakeHistoryRecorder _history = new(); + private readonly QueryTab _tab; + + public QueryTabEditingTests() + { + _tab = Tab(null); + } + + private FakeTableEditor Editor => _session.ResultEditor; + + [Fact] + public async Task AnEditedResultSavesAndItsStatementRunsAgainOutsideTheHistory() + { + await _tab.RunAsync(); + + Assert.True(_tab.CanEditResult); + Assert.Equal(["select * from Artist"], _session.ResultEditorOpens); + Assert.Null(_tab.StartEdit(1, 1, out var stored)); + Assert.Equal("r1c1", stored); + Assert.Null(_tab.CommitEdit(1, 1, "Accept II")); + Assert.True(_tab.HasUnsavedChanges); + Assert.True(_tab.CanSaveRows); + + Assert.True(await _tab.SaveRowsAsync()); + + var save = Assert.Single(Editor.Saves); + Assert.Equal(1, save.Runs); + Assert.True(save.Confirmed); + Assert.IsType(Assert.Single(Assert.Single(Editor.Plans))); + Assert.Equal(["select * from Artist", "select * from Artist"], Assert.Single(_session.Editors).Runs); + Assert.Equal(2, _session.ResultEditorOpens.Count); + Assert.Single(_history.Runs); + Assert.Equal(["saving", "saved"], _edits.Shown); + Assert.False(_tab.HasUnsavedChanges); + Assert.True(_tab.CanEditResult); + } + + [Fact] + public async Task ARunWithSeveralResultsIsRefusedBeforeTheCoreIsAsked() + { + _session.Script = _ => FakeRun.Script(); + + await _tab.RunAsync(); + + Assert.True(_tab.ResultAcceptsEdits); + Assert.False(_tab.CanEditResult); + Assert.False(_tab.EditsResult); + Assert.Equal(new EditRefusal.ResultBlocked(ResultEditBlock.SeveralResults), _tab.StartEdit(0, 1, out _)); + Assert.Equal(new EditRefusal.ResultBlocked(ResultEditBlock.SeveralResults), _tab.AddRow(out _)); + Assert.Empty(_session.ResultEditorOpens); + } + + [Theory] + [InlineData(TransactionState.InTransaction, ResultEditBlock.OpenTransaction)] + [InlineData(TransactionState.Failed, ResultEditBlock.OpenTransaction)] + [InlineData(TransactionState.Unknown, ResultEditBlock.UnknownTransaction)] + public async Task ARunThatLeavesATransactionOpenOrUnsaidIsRefused(TransactionState state, ResultEditBlock block) + { + _session.Script = _ => FakeRun.Rows(3, state); + + await _tab.RunAsync(); + + Assert.Equal(new EditRefusal.ResultBlocked(block), _tab.StartEdit(0, 1, out _)); + Assert.Empty(_session.ResultEditorOpens); + } + + [Fact] + public async Task ATabInAnotherDatabaseThanTheConnectionsIsRefused() + { + _session.Database = "app"; + var tab = Tab("shop"); + + await tab.RunAsync(); + + Assert.Equal(new EditRefusal.ResultBlocked(ResultEditBlock.OtherDatabase), tab.StartEdit(0, 1, out _)); + Assert.Empty(_session.ResultEditorOpens); + } + + [Fact] + public async Task ATypedUseThatMovedTheEditorIsRefused() + { + _session.Database = "app"; + await _tab.RunAsync(); + Assert.True(_tab.CanEditResult); + var editor = Assert.Single(_session.Editors); + editor.Database = "shop"; + + await _tab.RunAsync(); + + Assert.Equal(new EditRefusal.ResultBlocked(ResultEditBlock.OtherDatabase), _tab.StartEdit(0, 1, out _)); + Assert.Single(_session.ResultEditorOpens); + } + + [Fact] + public async Task CommitRunsNoStatementWhoseRowsCouldEdit() + { + _session.Script = _ => FakeRun.Rows(3, TransactionState.InTransaction); + await _tab.RunAsync(); + _session.Script = _ => FakeRun.Rows(3); + + await _tab.CommitAsync(); + + Assert.Equal(new EditRefusal.ResultBlocked(ResultEditBlock.RunAgain), _tab.StartEdit(0, 1, out _)); + Assert.Empty(_session.ResultEditorOpens); + } + + [Fact] + public async Task ALockFromTheCoreIsTheRefusal() + { + Editor.Lock = EditLock.Collapsed; + Editor.PageLock = EditLock.Collapsed; + + await _tab.RunAsync(); + + Assert.Equal(new EditRefusal.TableLocked(EditLock.Collapsed), _tab.StartEdit(0, 1, out _)); + Assert.Equal(new EditRefusal.TableLocked(EditLock.Collapsed), _tab.DeleteRows([0])); + Assert.False(_tab.CanEditResult); + Assert.False(_tab.EditsResult); + Assert.Equal(["select * from Artist"], _session.ResultEditorOpens); + } + + [Fact] + public async Task AResultWhoseTableCannotBeReadIsRefused() + { + _session.ResultEditorFailure = Errors.Of("catalog.columns_unavailable"); + + await _tab.RunAsync(); + + Assert.Equal(new EditRefusal.ResultBlocked(ResultEditBlock.ColumnsUnread), _tab.StartEdit(0, 1, out _)); + Assert.Null(_tab.ResultEdits); + } + + [Fact] + public async Task ARunASortOrADatabaseSwitchAsksFirstAndANoKeepsTheEdits() + { + _session.Sorted = (sql, columns, column, _) => $"{sql} order by {columns[column]}"; + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + _edits.DiscardsForReplace = false; + + await _tab.RunAsync(); + await _tab.SortAsync(new GridSort(1, SortDirection.Ascending)); + await _tab.PickDatabaseAsync("shop"); + + var editor = Assert.Single(_session.Editors); + Assert.Equal( + [ResultReplacement.Run, ResultReplacement.Sort, ResultReplacement.Database], + _edits.ReplacesAsked); + Assert.Single(editor.Runs); + Assert.Empty(editor.Databases); + Assert.Equal(GridSort.None, _results.Sort); + Assert.True(_tab.HasUnsavedChanges); + Assert.True(_tab.CanSaveRows); + + _edits.DiscardsForReplace = true; + await _tab.RunAsync(); + + Assert.Equal(2, editor.Runs.Count); + Assert.False(_tab.HasUnsavedChanges); + Assert.True(_tab.CanEditResult); + } + + [Fact] + public async Task AnUnknownOutcomeBlocksSaveUntilDiscardWhichRunsTheStatementAgain() + { + Editor.Outcome = () => new RowSaveOutcome.Unknown(Errors.Of("driver.commit_outcome_unknown"), 0); + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + + Assert.False(await _tab.SaveRowsAsync()); + + Assert.True(Assert.Single(_edits.Failures).Incomplete); + Assert.Equal(0, Assert.Single(_edits.Focused)); + Assert.True(_tab.HasUnsavedChanges); + Assert.False(_tab.CanSaveRows); + Assert.False(await _tab.SaveRowsAsync()); + Assert.IsType(Assert.Single(_edits.Refusals)); + Assert.Single(Editor.Saves); + var editor = Assert.Single(_session.Editors); + Assert.Single(editor.Runs); + + await _tab.DiscardRowsAsync(); + + Assert.Equal(2, editor.Runs.Count); + Assert.False(_tab.HasUnsavedChanges); + Assert.Null(_tab.CommitEdit(0, 1, "again")); + Assert.True(_tab.CanSaveRows); + } + + [Fact] + public async Task DeletesAreAskedAboutAndConfirmWritesShowsTheStatementsFirst() + { + Editor.Verdict = SaveGate.Confirm; + await _tab.RunAsync(); + _tab.DeleteRows([1, 2]); + _edits.ConfirmsSave = false; + + Assert.False(await _tab.SaveRowsAsync()); + + Assert.Equal(2, Assert.Single(_edits.DeletesAsked)); + Assert.Equal(["DELETE", "DELETE"], Assert.Single(_edits.SavesAsked).Select(statement => statement.Sql)); + Assert.Contains("save cancelled", _edits.Shown); + Assert.Equal(0, Assert.Single(Editor.Saves).Runs); + Assert.True(_tab.HasUnsavedChanges); + } + + [Fact] + public async Task ACloseAsksAboutPendingRowsAndSavesThenReadsThem() + { + await _tab.RunAsync(); + + Assert.True(await _tab.ConfirmCloseAsync(offerSave: true)); + Assert.Equal(0, _edits.ClosesAsked); + + _tab.CommitEdit(0, 1, "changed"); + _edits.CloseAnswer = SaveBeforeClose.Cancel; + Assert.False(await _tab.ConfirmCloseAsync(offerSave: true)); + _edits.CloseAnswer = SaveBeforeClose.DontSave; + Assert.True(await _tab.ConfirmCloseAsync(offerSave: false)); + Assert.False(_edits.OffersSave); + Assert.True(_tab.HasUnsavedChanges); + + _edits.CloseAnswer = SaveBeforeClose.Save; + Assert.True(await _tab.ConfirmCloseAsync(offerSave: true)); + + // Another tab's Cancel can keep this one open, so the rows show what the save wrote. + Assert.True(_edits.OffersSave); + Assert.Equal(1, Assert.Single(Editor.Saves).Runs); + Assert.Equal(2, Assert.Single(_session.Editors).Runs.Count); + Assert.False(_tab.HasUnsavedChanges); + Assert.Equal(3, _edits.ClosesAsked); + } + + [Fact] + public async Task AHeldSortTellsTheViewTheRowsTakeEditsAgainOnceItEnds() + { + _session.Sorted = (_, _, _, _) => null; + await _tab.RunAsync(); + var shown = _edits.EditsShown; + + await _tab.SortAsync(new GridSort(1, SortDirection.Ascending)); + + Assert.True(_edits.EditsShown > shown); + Assert.True(_tab.ResultAcceptsEdits); + } + + [Fact] + public async Task AHeldSortAfterAnUnknownOutcomeKeepsSaveBlocked() + { + Editor.Outcome = () => new RowSaveOutcome.Unknown(Errors.Of("driver.commit_outcome_unknown"), 0); + await _tab.RunAsync(); + _tab.CommitEdit(0, 1, "changed"); + Assert.False(await _tab.SaveRowsAsync()); + + await _tab.SortAsync(new GridSort(1, SortDirection.Ascending)); + Assert.Null(_tab.CommitEdit(0, 1, "again")); + + Assert.False(_tab.CanSaveRows); + Assert.False(await _tab.SaveRowsAsync()); + Assert.IsType(Assert.Single(_edits.Refusals)); + Assert.Single(Editor.Saves); + } + + [Fact] + public async Task ASaveReadsTheRowsAgainAndSortsThemAsTheyWereShown() + { + await _tab.RunAsync(); + await _tab.SortAsync(new GridSort(1, SortDirection.Descending)); + _tab.CommitEdit(0, 1, "changed"); + + Assert.True(await _tab.SaveRowsAsync()); + + Assert.Equal(2, Assert.Single(_session.Editors).Runs.Count); + Assert.Equal(2, _results.Shown.Count(shown => shown == "sort held")); + Assert.Equal(new GridSort(1, SortDirection.Descending), _results.Sort); + } + + [Fact] + public async Task ARowWhoseValuesWouldNotCopyExactlyIsNotDuplicated() + { + Editor.Copies = row => row != 1; + await _tab.RunAsync(); + + Assert.Equal(EditRefusal.NotCopyable.Instance, _tab.DuplicateRows([0, 1], out var none)); + Assert.Null(_tab.DuplicateRows([0], out var last)); + + Assert.Equal(-1, none); + Assert.Equal(3, last); + Assert.Equal(1, _tab.ResultEdits!.AddedRows); + } + + [Fact] + public async Task RowsSavedForACloseTheFileThenKeepsOpenAreReadAgain() + { + var directory = Directory.CreateTempSubdirectory("tablepro-result-close-").FullName; + try + { + var path = Path.Combine(directory, "report.sql"); + File.WriteAllText(path, "select * from Artist"); + var read = SqlFile.Read(path); + _view.WholeText = read.Text; + var files = new NoPickFiles(); + var tab = new QueryTab( + "report.sql", + _session, + _view, + _results, + DataModel.Relational, + () => new AppSettings(), + _history, + files: files, + filePath: path, + onDisk: read, + resultEdits: _edits); + await tab.RunAsync(); + tab.CommitEdit(0, 1, "changed"); + _view.WholeText = "select * from Artist where 1 = 1"; + tab.TextEdited(); + File.Delete(path); + + Assert.False(await tab.ConfirmCloseAsync(offerSave: true)); + + Assert.Equal(1, Assert.Single(Editor.Saves).Runs); + Assert.Equal(2, Assert.Single(_session.Editors).Runs.Count); + Assert.False(tab.HasPendingRows); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private QueryTab Tab(string? database) => new( + "Query 1", + _session, + _view, + _results, + DataModel.Relational, + () => new AppSettings(), + _history, + database, + resultEdits: _edits); + + // The file is gone and Save As is dismissed, so its save fails. + private sealed class NoPickFiles : IQueryFileView + { + public void ReplaceText(string text) + { + } + + public Task PickSavePathAsync(string suggestedName, string? folder) => Task.FromResult(null); + + public Task AskSaveBeforeCloseAsync(string tab, bool offerSave) => + Task.FromResult(SaveBeforeClose.Save); + + public Task AskSaveOverChangeAsync(string path) => Task.FromResult(SaveOverChange.Cancel); + + public void ShowDiskChange(DiskChange change) + { + } + + public Task ShowSaveFailedAsync(string path, Exception failure) => Task.CompletedTask; + + public Task ShowReloadFailedAsync(string path, Exception failure) => Task.CompletedTask; + } +} diff --git a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs index e17b55a763..fbb30b0c6d 100644 --- a/windows/tests/TablePro.App.Model.Tests/TabFakes.cs +++ b/windows/tests/TablePro.App.Model.Tests/TabFakes.cs @@ -351,6 +351,22 @@ public async Task OpenTableEditorAsync( return TableEditorFailure is { } failure ? throw new TableProException(failure) : TableEditor; } + // Every result editor open gives this one, so a test sets it up before the run. + public FakeTableEditor ResultEditor { get; } = new(); + + public CoreError? ResultEditorFailure { get; set; } + + // The statement each result editor was opened on. + public List ResultEditorOpens { get; } = []; + + public Task OpenResultEditorAsync(string sql, ResultSet? rows, CancellationToken cancellationToken) + { + ResultEditorOpens.Add(sql); + return ResultEditorFailure is { } failure + ? Task.FromException(new TableProException(failure)) + : Task.FromResult(ResultEditor); + } + public Task ReadTableKeysAsync(TableName table, CancellationToken cancellationToken) { if (KeysFailure is { } failure) @@ -823,6 +839,8 @@ internal sealed class FakeTableEditor : ITableEditor { public EditLock? Lock { get; set; } + public TableName? Table { get; set; } = new(null, "Artist"); + public EditLock? PageLock { get; set; } // Artist's key is filled by the server, so a new row leaves it as Default, and its name takes any text. @@ -879,6 +897,10 @@ internal sealed class FakeTableEditor : ITableEditor public EditStart GetEditStart(ResultSet? rows, long row, int column) => Start(row, column); + public Func Copies { get; set; } = _ => true; + + public bool CopiesExactly(ResultSet? rows, long row) => Copies(row); + public IReadOnlyList GetStoredValues(ResultSet? rows, int column, long firstRow, int rowCount) => [.. Enumerable.Range(0, rowCount).Select(row => Values(firstRow + row, column))]; @@ -941,6 +963,110 @@ public async Task RunAsync(bool confirmed, CancellationToken can public void Dispose() => Disposals++; } +// A query tab's result view, which answers each question as the test set it and keeps what it was asked. +internal sealed class FakeResultEditView : IResultEditView +{ + public List Shown { get; } = []; + + public List ReplacesAsked { get; } = []; + + public List DeletesAsked { get; } = []; + + public List> SavesAsked { get; } = []; + + public List<(IReadOnlyList Statements, CoreError? Failure)> Previews { get; } = []; + + public List<(CoreError Failure, bool Incomplete)> Failures { get; } = []; + + public List Refusals { get; } = []; + + public List Focused { get; } = []; + + public bool HasOpenEdit { get; set; } + + public bool CommitsOpenEdit { get; set; } = true; + + // What keeping the open editor's text does, as the grid raises CellEditCommitting. + public Action? OnCommit { get; set; } + + public bool DiscardsForReplace { get; set; } = true; + + public bool Discards { get; set; } = true; + + public SaveBeforeClose CloseAnswer { get; set; } = SaveBeforeClose.Save; + + public bool? OffersSave { get; private set; } + + public int ClosesAsked { get; private set; } + + public bool ConfirmsDelete { get; set; } = true; + + public bool ConfirmsSave { get; set; } = true; + + public int EditsShown { get; private set; } + + public void ShowEdits() => EditsShown++; + + public void ShowSaving(bool saving) => Shown.Add(saving ? "saving" : "saved"); + + public void ShowEditRefusal(EditRefusal refusal) => Refusals.Add(refusal); + + public void ShowSaveCancelled() => Shown.Add("save cancelled"); + + public bool CommitOpenEdit() + { + if (!CommitsOpenEdit || !HasOpenEdit) + { + return CommitsOpenEdit; + } + + HasOpenEdit = false; + OnCommit?.Invoke(); + return true; + } + + public void FocusRow(int row) => Focused.Add(row); + + public Task ConfirmDiscardForReplaceAsync(ResultReplacement reason) + { + ReplacesAsked.Add(reason); + return Task.FromResult(DiscardsForReplace); + } + + public Task ConfirmDiscardAsync() => Task.FromResult(Discards); + + public Task AskSaveBeforeCloseAsync(string tab, bool offerSave) + { + ClosesAsked++; + OffersSave = offerSave; + return Task.FromResult(CloseAnswer); + } + + public Task ConfirmDeleteAsync(string table, int rows) + { + DeletesAsked.Add(rows); + return Task.FromResult(ConfirmsDelete); + } + + public Task ConfirmSaveAsync(string connection, IReadOnlyList statements) + { + SavesAsked.Add(statements); + return Task.FromResult(ConfirmsSave); + } + + public Task ShowPreviewAsync(IReadOnlyList statements, CoreError? failure) + { + Previews.Add((statements, failure)); + return Task.CompletedTask; + } + + public Task ShowSaveFailedAsync(CoreError failure, bool incomplete) + { + Failures.Add((failure, incomplete)); + return Task.CompletedTask; + } +} + internal static class Errors { public static CoreError Of(string code, SecretKind? secret = null, HostKeyFailure? hostKey = null) => diff --git a/windows/tests/TablePro.App.UITests/ImportFromAppTests.cs b/windows/tests/TablePro.App.UITests/ImportFromAppTests.cs new file mode 100644 index 0000000000..849e26a6eb --- /dev/null +++ b/windows/tests/TablePro.App.UITests/ImportFromAppTests.cs @@ -0,0 +1,67 @@ +using FlaUI.Core.AutomationElements; +using FlaUI.Core.Tools; + +namespace TablePro.App.UITests; + +public sealed partial class ShellTests +{ + // Two connections as Navicat exports them, without their passwords. + private const string NavicatExport = """ + + + + + + """; + + [Theory] + [MemberData(nameof(Themes))] + public void ANavicatExportImportsItsConnectionsIntoTheLibrary(string theme) + { + using var app = AppSession.Launch(theme); + var file = Path.Combine(app.DataFolder, "connections.ncx"); + File.WriteAllText(file, NavicatExport); + + app.Click(app.Find("ImportButton"), () => app.TryFind("ImportFromAppMenuItem") is not null); + app.Click(app.Find("ImportFromAppMenuItem"), () => app.TryFind("ImportAppSource_Navicat") is not null); + var navicat = app.Find("ImportAppSource_Navicat"); + app.Click(navicat, () => navicat.AsRadioButton().IsChecked); + Assert.True(app.Find("ImportAppPasswords").AsCheckBox().IsChecked); + Assert.False(app.Find("ImportAppQueries").IsEnabled); + + // A click, not UIA's Invoke, which would wait on the picker Continue opens. + app.Click(app.Find("PrimaryButton")); + OpenInFileDialog(app, file); + + var orders = app.Find("ImportAppRow_row-0"); + var analytics = app.Find("ImportAppRow_row-1"); + Assert.Equal("Orders", orders.Name); + Assert.Equal("Analytics", analytics.Name); + Assert.True(orders.AsCheckBox().IsChecked); + Assert.True(analytics.AsCheckBox().IsChecked); + Assert.Equal( + "2 of 2 connections selected", + AppSession.WaitForText(app.Find("ImportAppSummary"), text => text == "2 of 2 connections selected")); + app.Screenshot("112-import-from-app-review"); + + app.PressDialogButton("Import"); + Assert.True(Retry.WhileFalse( + () => app.TryFind("ImportAppSummary") is null, + AppSession.Wait, + throwOnTimeout: false).Success); + + var tree = app.Find("ConnectionTree"); + app.FindByNamePrefix("Orders,", tree); + app.FindByNamePrefix("Analytics,", tree); + Assert.True(Retry.WhileFalse( + () => app.TryFind("HomeMessageBar")?.FindAllDescendants().Any(element => + element.Properties.Name.ValueOrDefault == "Imported 2 connections.") == true, + AppSession.Wait, + throwOnTimeout: false).Success); + app.Screenshot("113-import-from-app-done"); + } +} diff --git a/windows/tests/TablePro.App.UITests/ResultEditingTests.cs b/windows/tests/TablePro.App.UITests/ResultEditingTests.cs new file mode 100644 index 0000000000..f63483abdc --- /dev/null +++ b/windows/tests/TablePro.App.UITests/ResultEditingTests.cs @@ -0,0 +1,80 @@ +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 AQueryResultOfOneKeyedTableEditsAndRunsAgainOnceSaved(string theme) + { + const string Renamed = "AC/DC (from a query)"; + using var app = AppSession.Launch(theme); + + app.Click(app.Find("SampleCard"), () => app.TryFind("Rail_Chinook (Sample)") is not null); + app.FindByName("Artist", app.Find("ObjectTree")); + app.TypeInto("Query 1", "SELECT ArtistId, Name FROM Artist"); + app.Chord( + () => AppSession.TextOf(app.Find("QueryStatus")).StartsWith("Rows: 275", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, + VirtualKeyShort.ENTER); + var grid = app.Find("ResultsGrid"); + Assert.Equal("AC/DC", app.WaitForCell(grid, 0, 1, value => value == "AC/DC")); + + // Once the core has opened the result's editor, F2 edits the cell as on a table tab and Enter keeps it pending. + app.Click(CellOf(grid, 0, 1)); + app.Chord(() => GridEditor(grid) is not null, VirtualKeyShort.F2); + Keyboard.Type(Renamed); + app.Chord(() => GridEditor(grid) is null, VirtualKeyShort.RETURN); + Assert.Equal(Renamed, app.WaitForCell(grid, 0, 1, value => value == Renamed)); + Assert.Equal("edited", ItemStatusOf(grid, 0, 1)); + Assert.True(Retry.WhileFalse( + () => app.TryFind("ResultSaveChangesButton") is { IsEnabled: true }, + AppSession.Wait, + throwOnTimeout: false).Success); + app.Screenshot("114-result-edit-pending"); + + // Ctrl+S in the grid saves the rows, never the file; Confirm writes shows the statements first. + app.Chord( + () => app.TryFind("SaveReviewStatements") is not null || ItemStatusOf(grid, 0, 1).Length == 0, + VirtualKeyShort.CONTROL, + VirtualKeyShort.KEY_S); + if (app.TryFind("SaveReviewStatements") is not null) + { + app.PressDialogButton(); + } + + // The statement runs again, so the cell holds what the table holds now, with nothing pending. + Assert.Equal( + Renamed, + app.WaitForCell(grid, 0, 1, value => value == Renamed && ItemStatusOf(grid, 0, 1).Length == 0)); + Assert.False(app.Find("ResultSaveChangesButton").IsEnabled); + } + + [Theory] + [MemberData(nameof(Themes))] + public void AGroupedResultSaysWhyItsRowsDoNotEdit(string theme) + { + const string Reason = "Grouped, distinct or computed rows can't be edited."; + 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", "SELECT GenreId, COUNT(*) AS Tracks FROM Track GROUP BY GenreId"); + app.Chord( + () => AppSession.TextOf(app.Find("QueryStatus")).StartsWith("Rows: ", StringComparison.Ordinal), + VirtualKeyShort.CONTROL, + VirtualKeyShort.ENTER); + var grid = app.Find("ResultsGrid"); + app.WaitForCell(grid, 0, 1, value => value.Length > 0); + + // The grid takes the edit only to refuse it, and the status says why. + app.Click(CellOf(grid, 0, 1)); + app.Chord(() => AppSession.TextOf(app.Find("QueryStatus")) == Reason, VirtualKeyShort.F2); + + Assert.Null(GridEditor(grid)); + Assert.True(app.TryFind("ResultSaveChangesButton") is null or { IsOffscreen: true }); + } +} diff --git a/windows/tests/TablePro.Interop.Tests/ForeignImportTests.cs b/windows/tests/TablePro.Interop.Tests/ForeignImportTests.cs new file mode 100644 index 0000000000..57c9577322 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/ForeignImportTests.cs @@ -0,0 +1,135 @@ +using System.Security.Cryptography; +using System.Text; + +namespace TablePro.Interop.Tests; + +public sealed class ForeignImportTests : IDisposable +{ + // DBeaver encrypts every project's credentials with this one key. + private static readonly byte[] DBeaverKey = + [0xBA, 0xBB, 0x4A, 0x9F, 0x77, 0x4A, 0xB8, 0x53, 0xC9, 0x6C, 0x2D, 0x65, 0x3D, 0xFE, 0x54, 0x4A]; + + private readonly string _directory = Directory.CreateTempSubdirectory("tablepro-foreign-").FullName; + private readonly MemorySecretStore _secrets = new(); + private readonly TableProCore _core; + private readonly ForeignAppDirs _dirs; + + public ForeignImportTests() + { + _core = TableProCore.Create(new HostConfiguration("test", Path.Combine(_directory, "storage")), _secrets); + _dirs = new ForeignAppDirs(_directory, Path.Combine(_directory, "config"), Path.Combine(_directory, "data")); + } + + 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 ADBeaverConnectionLandsWithItsPasswordAndItsScriptOnce() + { + WriteDBeaver(); + + var sources = await _core.GetForeignSourcesAsync(_dirs); + using var review = await _core.ReadForeignAsync( + ForeignApp.DBeaver, _dirs, null, new ForeignImportRequest(true, true), TestContext.Current.CancellationToken); + var choices = review.Choices(); + var outcome = await review.ApplyAsync(); + var again = await Assert.ThrowsAsync(review.ApplyAsync); + var saved = (await _core.Library.GetSnapshotAsync()).Connections.Single(); + + var dbeaver = sources.Single(source => source.App == ForeignApp.DBeaver); + Assert.True(dbeaver.IsAvailable); + Assert.Equal((1, 1), (dbeaver.Connections, dbeaver.SavedQueries)); + Assert.True(sources.Single(source => source.App == ForeignApp.Navicat).PicksFile); + Assert.Equal(ForeignPasswordOutcome.Read, review.Passwords); + Assert.Equal("Windows PG", review.Connections[0].Name); + Assert.Equal("windows.example.com", review.Connections[0].Connection?.Host); + Assert.True(choices.Connections[0].Selected); + Assert.Equal(ForeignResolution.Add.Instance, choices.Connections[0].Resolution); + Assert.Equal(ForeignQueryAvailability.Available, choices.Queries[0].Availability); + Assert.Equal(new ForeignImportOutcome(1, 0, 0, 1, 0, 0), outcome); + Assert.Equal("foreign_import.applied", again.Code); + Assert.Equal("Windows PG", saved.Name); + Assert.Equal("windows-pass", _secrets.Load(saved.Id!.Value, SecretKind.DatabasePassword)); + } + + [Fact] + public async Task ASecondReadMatchesTheSavedConnectionAndAnUncheckedRowWritesNothing() + { + WriteDBeaver(); + var cancellationToken = TestContext.Current.CancellationToken; + using (var first = await _core.ReadForeignAsync( + ForeignApp.DBeaver, _dirs, null, new ForeignImportRequest(true, false), cancellationToken)) + { + await first.ApplyAsync(); + } + + var id = (await _core.Library.GetSnapshotAsync()).Connections.Single().Id!.Value; + using var review = await _core.ReadForeignAsync( + ForeignApp.DBeaver, _dirs, null, new ForeignImportRequest(true, false), cancellationToken); + var before = review.Choices(); + review.SetSelected("windows", true); + var offered = review.Choices().Connections[0].Offered; + var replaced = review.Resolve("windows", new ForeignResolution.Replace(id)); + var outcome = await review.ApplyAsync(); + + Assert.Equal(new ExistingConnection(id, "Windows PG"), review.Connections[0].Duplicate); + Assert.False(before.Connections[0].Selected); + Assert.False(before.Importable); + Assert.Equal([ForeignResolution.AddCopy.Instance, new ForeignResolution.Replace(id)], offered); + Assert.True(replaced); + Assert.Equal(new ForeignImportOutcome(1, 1, 0, 0, 0, 0), outcome); + Assert.Single((await _core.Library.GetSnapshotAsync()).Connections); + } + + [Fact] + public async Task AnAppWithNothingToReadFailsWithItsCode() + { + var failure = await Assert.ThrowsAsync(() => + _core.ReadForeignAsync( + ForeignApp.DBeaver, _dirs, null, new ForeignImportRequest(true, true), TestContext.Current.CancellationToken)); + + Assert.Equal("foreign_import.file_not_found", failure.Code); + } + + // DBeaver's workspace where it keeps it on the platform the test runs on. + private void WriteDBeaver() + { + var root = OperatingSystem.IsMacOS() ? Path.Combine(_directory, "Library") + : OperatingSystem.IsWindows() ? _dirs.Config + : _dirs.Data; + var project = Path.Combine(root, "DBeaverData", "workspace6", "General"); + var metadata = Path.Combine(project, ".dbeaver"); + Directory.CreateDirectory(metadata); + Directory.CreateDirectory(Path.Combine(project, "Scripts")); + File.WriteAllText(Path.Combine(metadata, "data-sources.json"), """ + {"connections": {"windows": {"provider": "postgresql", "name": "Windows PG", + "configuration": {"host": "windows.example.com", "port": "5432", "database": "app"}}}} + """); + File.WriteAllBytes( + Path.Combine(metadata, "credentials-config.json"), + Encrypt("""{"windows": {"#connection": {"user": "winuser", "password": "windows-pass"}}}""")); + File.WriteAllText( + Path.Combine(metadata, "project-metadata.json"), + """{"resources":{"Scripts/Report.sql":{"default-datasource":"windows"}}}"""); + File.WriteAllText(Path.Combine(project, "Scripts", "Report.sql"), "select 42;"); + } + + private static byte[] Encrypt(string json) + { + using var aes = Aes.Create(); + aes.Key = DBeaverKey; + aes.GenerateIV(); + var cipher = aes.EncryptCbc(Encoding.UTF8.GetBytes(json), aes.IV, PaddingMode.PKCS7); + return [.. aes.IV, .. cipher]; + } +} diff --git a/windows/tests/TablePro.Interop.Tests/ResultEditTests.cs b/windows/tests/TablePro.Interop.Tests/ResultEditTests.cs new file mode 100644 index 0000000000..952207aebb --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/ResultEditTests.cs @@ -0,0 +1,57 @@ +namespace TablePro.Interop.Tests; + +public sealed class ResultEditTests +{ + [Fact] + public async Task AResultOfOneKeyedTableSavesItsEditsByTheResultsOwnColumns() + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + const string sql = "SELECT note, id FROM people ORDER BY id"; + using var run = database.Editor.Run(sql, cancellationToken: cancellationToken); + Assert.IsType(await run.Completion); + using var rows = run.GetResultSet(0) ?? throw new InvalidOperationException("The run held no set."); + using var editor = await database.Session.OpenResultEditorAsync(sql, rows, cancellationToken); + var copies = editor.CopiesExactly(rows, 0); + + using var save = editor.Plan(rows, + [ + new RowEdit.Update(0, [new CellChange(0, new CellEdit.Text("first"))]), + new RowEdit.Delete(2), + ]); + var outcome = await save.RunAsync(confirmed: false, cancellationToken); + using var after = database.Editor.Run("SELECT coalesce(note, 'NULL') FROM people ORDER BY id", cancellationToken: cancellationToken); + Assert.IsType(await after.Completion); + using var notes = after.GetResultSet(0) ?? throw new InvalidOperationException("The read held no set."); + + Assert.Null(editor.Lock); + Assert.True(copies); + Assert.Equal(new TableName(null, "people"), editor.Table); + Assert.Equal(["note", "id"], editor.Columns.Select(column => column.Name)); + Assert.True(editor.Columns[0].Editable); + Assert.True(editor.Columns[1].PrimaryKey); + Assert.Equal(new RowSaveOutcome.Saved(2), outcome); + Assert.Equal(2, notes.RowCount); + Assert.Equal("first", notes.GetCellText(0, 0)); + } + + [Theory] + [InlineData("SELECT p.id, q.name FROM people p JOIN people q ON q.id = p.id", EditLock.MoreThanOneTable)] + [InlineData("SELECT DISTINCT id, name FROM people", EditLock.Collapsed)] + [InlineData("SELECT name FROM people", EditLock.KeyNotShown)] + [InlineData("PRAGMA table_info(people)", EditLock.NotOneSelect)] + public async Task AResultThatIsNotOneKeyedTablesRowsSaysWhy(string sql, EditLock expected) + { + var cancellationToken = TestContext.Current.CancellationToken; + await using var database = await SqliteDatabase.CreateAsync(); + using var run = database.Editor.Run(sql, cancellationToken: cancellationToken); + Assert.IsType(await run.Completion); + using var rows = run.GetResultSet(0) ?? throw new InvalidOperationException("The run held no set."); + + using var editor = await database.Session.OpenResultEditorAsync(sql, rows, cancellationToken); + + Assert.Equal(expected, editor.Lock); + Assert.Null(editor.Table); + Assert.Empty(editor.Columns); + } +}