From 318764d9f8fb94b8d1ccb55ee0eb96424337c917 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sun, 15 Nov 2026 12:23:07 +0300 Subject: [PATCH] feat(tauri): persist SQLite connection profiles locally (#1879) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a LocalDb-equivalent ProfileStore under app data, wire save/load/delete commands, and hydrate SERVERS on boot so Save survives restart (no plaintext secrets — SQLite path only; keyring remains #1878). --- apps/tauri/src-tauri/Cargo.lock | 138 ++++++- apps/tauri/src-tauri/Cargo.toml | 1 + apps/tauri/src-tauri/src/commands.rs | 92 ++++- .../tauri/src-tauri/src/connection/manager.rs | 35 +- .../src-tauri/src/connection/smoke_slice.rs | 1 + apps/tauri/src-tauri/src/connection/sqlite.rs | 15 +- .../src/connection/sqlite_object_tree.rs | 1 + apps/tauri/src-tauri/src/lib.rs | 15 + apps/tauri/src-tauri/src/profiles/mod.rs | 6 + apps/tauri/src-tauri/src/profiles/store.rs | 371 ++++++++++++++++++ apps/tauri/src/App.vue | 1 + apps/tauri/src/api/connection.ts | 52 ++- apps/tauri/src/stores/connections.ts | 170 +++++++- apps/tauri/src/stores/objectTree.ts | 1 + apps/tauri/src/ui/ConnectionsPanel.vue | 8 +- 15 files changed, 869 insertions(+), 38 deletions(-) create mode 100644 apps/tauri/src-tauri/src/profiles/mod.rs create mode 100644 apps/tauri/src-tauri/src/profiles/store.rs diff --git a/apps/tauri/src-tauri/Cargo.lock b/apps/tauri/src-tauri/Cargo.lock index ec663386..9c74f817 100644 --- a/apps/tauri/src-tauri/Cargo.lock +++ b/apps/tauri/src-tauri/Cargo.lock @@ -735,13 +735,34 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys 0.4.1", +] + [[package]] name = "dirs" version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" dependencies = [ - "dirs-sys", + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", ] [[package]] @@ -752,7 +773,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users", + "redox_users 0.5.3", "windows-sys 0.61.2", ] @@ -1257,6 +1278,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -2785,6 +2817,7 @@ dependencies = [ name = "querya_desktop_tauri" version = "0.1.0" dependencies = [ + "dirs 5.0.1", "rusqlite", "serde", "serde_json", @@ -2840,6 +2873,17 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + [[package]] name = "redox_users" version = "0.5.3" @@ -3604,7 +3648,7 @@ dependencies = [ "anyhow", "bytes", "cookie", - "dirs", + "dirs 7.0.0", "dunce", "embed_plist", "getrandom 0.3.4", @@ -3654,7 +3698,7 @@ checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614" dependencies = [ "anyhow", "cargo_toml", - "dirs", + "dirs 7.0.0", "glob", "heck 0.5.0", "json-patch", @@ -4203,7 +4247,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" dependencies = [ "crossbeam-channel", - "dirs", + "dirs 7.0.0", "libappindicator", "muda", "objc2", @@ -4727,7 +4771,16 @@ version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" dependencies = [ - "windows-targets", + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", ] [[package]] @@ -4745,13 +4798,28 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", ] [[package]] @@ -4778,42 +4846,84 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_i686_gnu" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "winnow" version = "0.5.40" @@ -4864,7 +4974,7 @@ dependencies = [ "block2", "cookie", "crossbeam-channel", - "dirs", + "dirs 7.0.0", "dom_query 0.29.0", "dpi", "dunce", diff --git a/apps/tauri/src-tauri/Cargo.toml b/apps/tauri/src-tauri/Cargo.toml index 0f087046..060eec3d 100644 --- a/apps/tauri/src-tauri/Cargo.toml +++ b/apps/tauri/src-tauri/Cargo.toml @@ -20,6 +20,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" uuid = { version = "1", features = ["v4", "serde"] } rusqlite = { version = "0.32", features = ["bundled"] } +dirs = "5" [profile.release] codegen-units = 1 diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index 61d41b52..952f387c 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -2,15 +2,105 @@ use crate::connection::{ ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, SchemaObject, SchemaObjectKind, SqlObjectKind, SqlObjectNode, SqliteOverview, TableSchema, }; +use crate::profiles::{ConnectionProfile, ProfileStore, ProfileStoreError}; use tauri::ipc::Channel; use tauri::State; #[tauri::command] pub fn db_connect_sqlite( path: String, + id: Option, registry: State<'_, ConnectionRegistry>, ) -> Result { - registry.connect(ConnectionConfig::Sqlite { path }) + registry.connect(ConnectionConfig::Sqlite { path, id }) +} + +#[tauri::command] +pub fn profiles_list( + store: State<'_, ProfileStore>, +) -> Result, ProfileStoreError> { + store.list() +} + +#[tauri::command] +pub fn profiles_upsert( + profile: ConnectionProfile, + store: State<'_, ProfileStore>, +) -> Result { + let mut profile = profile; + if profile.created_at.trim().is_empty() { + profile = ConnectionProfile { + created_at: profile.updated_at.clone(), + ..profile + }; + } + profile.touch(); + store.upsert(&profile)?; + Ok(profile) +} + +#[tauri::command] +pub fn profiles_delete( + id: String, + store: State<'_, ProfileStore>, +) -> Result { + store.delete(&id) +} + +/// Save (or update) a SQLite profile and open a live session under the same id. +#[tauri::command] +pub fn profiles_connect_sqlite( + name: String, + path: String, + folder_id: Option, + id: Option, + store: State<'_, ProfileStore>, + registry: State<'_, ConnectionRegistry>, +) -> Result { + let display_name = { + let t = name.trim(); + if t.is_empty() { + path.clone() + } else { + t.to_owned() + } + }; + + let mut profile = match id.filter(|s| !s.trim().is_empty()) { + Some(existing_id) => store + .get(&existing_id) + .map_err(|e| ConnectionError::io(e.to_string()))? + .map(|mut p| { + p.name = display_name.clone(); + p.path = Some(path.clone()); + p.folder_id = folder_id.clone(); + p.driver = "sqlite".into(); + p + }) + .unwrap_or_else(|| { + let mut p = ConnectionProfile::new_sqlite(display_name.clone(), path.clone()); + p.id = existing_id; + p.folder_id = folder_id.clone(); + p + }), + None => { + let mut p = ConnectionProfile::new_sqlite(display_name, path.clone()); + p.folder_id = folder_id; + p + } + }; + profile.touch(); + store + .upsert(&profile) + .map_err(|e| ConnectionError::io(e.to_string()))?; + + if !registry.is_connected(&ConnectionId::from(profile.id.as_str())) { + registry.connect(ConnectionConfig::Sqlite { + path, + id: Some(profile.id.clone()), + })?; + } + Ok(profile) } #[tauri::command] diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs index d082fc24..1c105b8a 100644 --- a/apps/tauri/src-tauri/src/connection/manager.rs +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -15,6 +15,9 @@ pub enum ConnectionConfig { Sqlite { /// Absolute or relative path to a `.db` / `.sqlite` file. path: String, + /// Stable profile id — when set, the live session reuses this id. + #[serde(default)] + id: Option, }, /// Stub until the Postgres adapter epic wires connect. Postgres { @@ -82,8 +85,13 @@ impl ConnectionRegistry { /// Registry with SQLite opener wired (PG/MySQL return UnsupportedDriver). pub fn with_builtin_drivers() -> Self { Self::with_opener(|config| match config { - ConnectionConfig::Sqlite { path } => { - let session = super::sqlite::open_sqlite(path)?; + ConnectionConfig::Sqlite { path, id } => { + let session = match id { + Some(id) if !id.trim().is_empty() => { + super::sqlite::open_sqlite_with_id(path, ConnectionId::from(id)) + } + _ => super::sqlite::open_sqlite(path), + }?; Ok(Arc::new(session) as SessionArc) } other => Err(ConnectionError::UnsupportedDriver { @@ -258,6 +266,7 @@ mod tests { let id = reg .connect(ConnectionConfig::Sqlite { path: "/tmp/x.db".into(), + id: None, }) .unwrap(); assert_eq!(id.as_str(), "s1"); @@ -269,6 +278,27 @@ mod tests { assert!(matches!(err, ConnectionError::NotFound { .. })); } + #[test] + fn registry_connect_reuses_stable_id() { + let reg = ConnectionRegistry::with_opener(|cfg| match cfg { + ConnectionConfig::Sqlite { + id: Some(id), .. + } => Ok(Arc::new(FakeSession { + id: ConnectionId::from(id), + driver: DriverKind::Sqlite, + }) as SessionArc), + _ => panic!("expected sqlite with id"), + }); + let id = reg + .connect(ConnectionConfig::Sqlite { + path: "/tmp/x.db".into(), + id: Some("profile-stable".into()), + }) + .unwrap(); + assert_eq!(id.as_str(), "profile-stable"); + reg.disconnect(&id).unwrap(); + } + #[test] fn registry_postgres_is_unsupported_for_now() { let reg = ConnectionRegistry::with_builtin_drivers(); @@ -306,6 +336,7 @@ mod tests { let id = reg .connect(ConnectionConfig::Sqlite { path: path.to_string_lossy().into(), + id: None, }) .unwrap(); let mut events = Vec::new(); diff --git a/apps/tauri/src-tauri/src/connection/smoke_slice.rs b/apps/tauri/src-tauri/src/connection/smoke_slice.rs index 19e2f47c..4c5df1da 100644 --- a/apps/tauri/src-tauri/src/connection/smoke_slice.rs +++ b/apps/tauri/src-tauri/src/connection/smoke_slice.rs @@ -23,6 +23,7 @@ fn connect_introspect_query_fixture() { let id = reg .connect(ConnectionConfig::Sqlite { path: path.to_string_lossy().into_owned(), + id: None, }) .expect("connect fixture"); diff --git a/apps/tauri/src-tauri/src/connection/sqlite.rs b/apps/tauri/src-tauri/src/connection/sqlite.rs index 2ec6ad46..bbee0805 100644 --- a/apps/tauri/src-tauri/src/connection/sqlite.rs +++ b/apps/tauri/src-tauri/src/connection/sqlite.rs @@ -109,10 +109,21 @@ impl ConnectionSession for SqliteSession { /// Open a SQLite database file and return a live session. pub fn open_sqlite(path: impl AsRef) -> ConnectionResult { + open_sqlite_with_id(path, ConnectionId::new()) +} + +/// Open SQLite with a stable session id (saved profile id). +pub fn open_sqlite_with_id( + path: impl AsRef, + id: ConnectionId, +) -> ConnectionResult { let path = path.as_ref().trim(); if path.is_empty() { return Err(ConnectionError::invalid_config("sqlite path is empty")); } + if id.as_str().trim().is_empty() { + return Err(ConnectionError::invalid_config("connection id is empty")); + } let p = Path::new(path); if let Some(parent) = p.parent() { @@ -128,7 +139,7 @@ pub fn open_sqlite(path: impl AsRef) -> ConnectionResult { conn.query_row("SELECT 1", [], |_| Ok(()))?; Ok(SqliteSession { - id: ConnectionId::new(), + id, path: path.to_owned(), conn: Arc::new(Mutex::new(Some(conn))), }) @@ -176,6 +187,7 @@ mod tests { let id = reg .connect(ConnectionConfig::Sqlite { path: path_str.clone(), + id: None, }) .expect("connect"); assert!(reg.is_connected(&id)); @@ -200,6 +212,7 @@ mod tests { let id = reg .connect(ConnectionConfig::Sqlite { path: path_str, + id: None, }) .expect("connect"); let schemas = reg diff --git a/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs b/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs index 4f5ef907..94bb3984 100644 --- a/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs +++ b/apps/tauri/src-tauri/src/connection/sqlite_object_tree.rs @@ -148,6 +148,7 @@ mod tests { let id = reg .connect(ConnectionConfig::Sqlite { path: path.to_string_lossy().into(), + id: None, }) .unwrap(); diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index 9f70eb0b..efab3052 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -1,15 +1,18 @@ mod commands; mod connection; +mod profiles; pub use connection::{ ColumnMeta, ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, DriverKind, ObjectTreeProvider, QueryEvent, SchemaObject, SchemaObjectKind, SqlObjectKind, SqlObjectNode, SqliteOverview, TableSchema, }; +pub use profiles::{ConnectionProfile, ProfileStore, ProfileStoreError}; use commands::{ db_connect_sqlite, db_describe_object, db_disconnect, db_execute_query, db_is_connected, db_list_children, db_list_columns, db_list_schemas, db_list_tables, db_sqlite_overview, + profiles_connect_sqlite, profiles_delete, profiles_list, profiles_upsert, }; #[tauri::command] @@ -39,6 +42,14 @@ pub fn run() { .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_dialog::init()) .manage(ConnectionRegistry::new()) + .setup(|app| { + use tauri::Manager; + let store = ProfileStore::open_default().map_err(|e| { + std::io::Error::other(format!("open profile store: {e}")) + })?; + app.manage(store); + Ok(()) + }) .invoke_handler(tauri::generate_handler![ app_info, host_platform, @@ -52,6 +63,10 @@ pub fn run() { db_describe_object, db_sqlite_overview, db_execute_query, + profiles_list, + profiles_upsert, + profiles_delete, + profiles_connect_sqlite, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/apps/tauri/src-tauri/src/profiles/mod.rs b/apps/tauri/src-tauri/src/profiles/mod.rs new file mode 100644 index 00000000..1bc26aaf --- /dev/null +++ b/apps/tauri/src-tauri/src/profiles/mod.rs @@ -0,0 +1,6 @@ +//! Local connection profiles (Flutter LocalDb `connections` table equivalent). +//! Secrets never land here — keyring is #1878 / #1847. + +mod store; + +pub use store::{ConnectionProfile, ProfileStore, ProfileStoreError}; diff --git a/apps/tauri/src-tauri/src/profiles/store.rs b/apps/tauri/src-tauri/src/profiles/store.rs new file mode 100644 index 00000000..563b3f8c --- /dev/null +++ b/apps/tauri/src-tauri/src/profiles/store.rs @@ -0,0 +1,371 @@ +//! App-data SQLite for connection metadata (no passwords / connection strings). + +use rusqlite::{params, Connection, OptionalExtension}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{SystemTime, UNIX_EPOCH}; +use uuid::Uuid; + +const SCHEMA_VERSION: i32 = 1; + +/// Persisted connection profile — mirrors Flutter `ConnectionRow` non-secret fields. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ConnectionProfile { + pub id: String, + /// Driver family: `sqlite` | `postgres` | `mysql` (… later). + pub driver: String, + pub name: String, + /// SQLite file path (absolute). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub port: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub username: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub database_name: Option, + /// SERVERS folder id (frontend string id; not a LocalDb integer). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder_id: Option, + pub sort_order: i64, + pub created_at: String, + pub updated_at: String, +} + +impl ConnectionProfile { + pub fn new_sqlite(name: impl Into, path: impl Into) -> Self { + let now = now_rfc3339(); + Self { + id: Uuid::new_v4().to_string(), + driver: "sqlite".into(), + name: name.into(), + path: Some(path.into()), + host: None, + port: None, + username: None, + database_name: None, + folder_id: None, + sort_order: 0, + created_at: now.clone(), + updated_at: now, + } + } + + pub fn touch(&mut self) { + self.updated_at = now_rfc3339(); + } +} + +#[derive(Debug)] +pub enum ProfileStoreError { + Io(String), + Db(String), + Invalid(String), +} + +impl std::fmt::Display for ProfileStoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(m) | Self::Db(m) | Self::Invalid(m) => f.write_str(m), + } + } +} + +impl std::error::Error for ProfileStoreError {} + +impl From for ProfileStoreError { + fn from(value: rusqlite::Error) -> Self { + Self::Db(value.to_string()) + } +} + +impl From for ProfileStoreError { + fn from(value: std::io::Error) -> Self { + Self::Io(value.to_string()) + } +} + +impl serde::Serialize for ProfileStoreError { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(&self.to_string()) + } +} + +/// LocalDb-equivalent profile store. Open once; share via Tauri `State`. +pub struct ProfileStore { + conn: Mutex, + path: PathBuf, +} + +impl ProfileStore { + /// Default on-disk location: `{data_dir}/querya_desktop/querya.db` + /// (Flutter LocalDb folder name; Tauri-only file until shared migration). + pub fn default_path() -> PathBuf { + let base = dirs::data_dir().unwrap_or_else(std::env::temp_dir); + base.join("querya_desktop").join("querya.db") + } + + pub fn open_default() -> Result { + Self::open(Self::default_path()) + } + + pub fn open(path: impl AsRef) -> Result { + let path = path.as_ref().to_path_buf(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let conn = Connection::open(&path)?; + conn.execute_batch( + "PRAGMA foreign_keys = ON; + PRAGMA journal_mode = WAL; + PRAGMA busy_timeout = 5000; + PRAGMA synchronous = NORMAL;", + )?; + migrate(&conn)?; + Ok(Self { + conn: Mutex::new(conn), + path, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn list(&self) -> Result, ProfileStoreError> { + let conn = self.lock()?; + let mut stmt = conn.prepare( + "SELECT id, driver, name, path, host, port, username, database_name, + folder_id, sort_order, created_at, updated_at + FROM connections + ORDER BY sort_order ASC, name ASC", + )?; + let rows = stmt.query_map([], row_to_profile)?; + let mut out = Vec::new(); + for row in rows { + out.push(row?); + } + Ok(out) + } + + pub fn get(&self, id: &str) -> Result, ProfileStoreError> { + let conn = self.lock()?; + conn.query_row( + "SELECT id, driver, name, path, host, port, username, database_name, + folder_id, sort_order, created_at, updated_at + FROM connections WHERE id = ?1", + params![id], + row_to_profile, + ) + .optional() + .map_err(Into::into) + } + + /// Insert or replace. Never writes password / connection_string columns. + pub fn upsert(&self, profile: &ConnectionProfile) -> Result<(), ProfileStoreError> { + if profile.id.trim().is_empty() { + return Err(ProfileStoreError::Invalid("profile id is empty".into())); + } + if profile.name.trim().is_empty() { + return Err(ProfileStoreError::Invalid("profile name is empty".into())); + } + if profile.driver.trim().is_empty() { + return Err(ProfileStoreError::Invalid("profile driver is empty".into())); + } + let conn = self.lock()?; + conn.execute( + "INSERT INTO connections ( + id, driver, name, path, host, port, username, database_name, + folder_id, sort_order, created_at, updated_at, + password, connection_string + ) VALUES ( + ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, + ?9, ?10, ?11, ?12, + NULL, NULL + ) + ON CONFLICT(id) DO UPDATE SET + driver = excluded.driver, + name = excluded.name, + path = excluded.path, + host = excluded.host, + port = excluded.port, + username = excluded.username, + database_name = excluded.database_name, + folder_id = excluded.folder_id, + sort_order = excluded.sort_order, + updated_at = excluded.updated_at, + password = NULL, + connection_string = NULL", + params![ + profile.id, + profile.driver, + profile.name, + profile.path, + profile.host, + profile.port, + profile.username, + profile.database_name, + profile.folder_id, + profile.sort_order, + profile.created_at, + profile.updated_at, + ], + )?; + Ok(()) + } + + pub fn delete(&self, id: &str) -> Result { + let conn = self.lock()?; + let n = conn.execute("DELETE FROM connections WHERE id = ?1", params![id])?; + Ok(n > 0) + } + + fn lock(&self) -> Result, ProfileStoreError> { + self.conn + .lock() + .map_err(|_| ProfileStoreError::Io("profile store lock poisoned".into())) + } +} + +fn migrate(conn: &Connection) -> Result<(), ProfileStoreError> { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY NOT NULL + );", + )?; + let current: i32 = conn + .query_row( + "SELECT COALESCE(MAX(version), 0) FROM schema_migrations", + [], + |r| r.get(0), + ) + .unwrap_or(0); + + if current < 1 { + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS connections ( + id TEXT PRIMARY KEY NOT NULL, + driver TEXT NOT NULL, + name TEXT NOT NULL, + path TEXT, + host TEXT, + port INTEGER, + username TEXT, + database_name TEXT, + folder_id TEXT, + sort_order INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + -- Reserved for schema parity with Flutter; always NULL (secrets → keyring). + password TEXT, + connection_string TEXT + ); + CREATE INDEX IF NOT EXISTS idx_connections_sort + ON connections (sort_order ASC, name ASC);", + )?; + conn.execute( + "INSERT INTO schema_migrations (version) VALUES (?1)", + params![SCHEMA_VERSION], + )?; + } + Ok(()) +} + +fn row_to_profile(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(ConnectionProfile { + id: row.get(0)?, + driver: row.get(1)?, + name: row.get(2)?, + path: row.get(3)?, + host: row.get(4)?, + port: row.get(5)?, + username: row.get(6)?, + database_name: row.get(7)?, + folder_id: row.get(8)?, + sort_order: row.get(9)?, + created_at: row.get(10)?, + updated_at: row.get(11)?, + }) +} + +fn now_rfc3339() -> String { + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + // Compact UTC stamp is enough for sort/debug; full chrono not required yet. + format!("{secs}") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn temp_store() -> (ProfileStore, PathBuf) { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!("querya_profiles_test_{nanos}.db")); + let store = ProfileStore::open(&path).expect("open"); + (store, path) + } + + #[test] + fn upsert_list_get_delete_round_trip() { + let (store, path) = temp_store(); + let mut p = ConnectionProfile::new_sqlite("shop", "/tmp/shop.db"); + p.folder_id = Some("folder-1".into()); + store.upsert(&p).unwrap(); + + let listed = store.list().unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].name, "shop"); + assert_eq!(listed[0].path.as_deref(), Some("/tmp/shop.db")); + assert_eq!(listed[0].folder_id.as_deref(), Some("folder-1")); + + let got = store.get(&p.id).unwrap().expect("present"); + assert_eq!(got.id, p.id); + + // Secrets columns must stay NULL even if someone tries to poke the row. + { + let conn = Connection::open(&path).unwrap(); + let (pw, cs): (Option, Option) = conn + .query_row( + "SELECT password, connection_string FROM connections WHERE id = ?1", + params![p.id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert!(pw.is_none()); + assert!(cs.is_none()); + } + + p.name = "shop-renamed".into(); + p.touch(); + store.upsert(&p).unwrap(); + assert_eq!(store.get(&p.id).unwrap().unwrap().name, "shop-renamed"); + + assert!(store.delete(&p.id).unwrap()); + assert!(store.list().unwrap().is_empty()); + assert!(!store.delete(&p.id).unwrap()); + let _ = std::fs::remove_file(&path); + } + + #[test] + fn rejects_empty_name() { + let (store, path) = temp_store(); + let mut p = ConnectionProfile::new_sqlite("x", "/tmp/x.db"); + p.name = " ".into(); + let err = store.upsert(&p).unwrap_err(); + assert!(matches!(err, ProfileStoreError::Invalid(_))); + let _ = std::fs::remove_file(&path); + } +} diff --git a/apps/tauri/src/App.vue b/apps/tauri/src/App.vue index e13a15d5..7ef6dcbe 100644 --- a/apps/tauri/src/App.vue +++ b/apps/tauri/src/App.vue @@ -191,6 +191,7 @@ onMounted(async () => { status.setQueryMetrics({ message: `${info.name} ${info.version} · UI core · ${info.stack}${info.os ? ` · ${info.os}` : ""}`, }); + await connections.hydrate(); } catch { status.setQueryMetrics({ message: "IPC unavailable" }); } finally { diff --git a/apps/tauri/src/api/connection.ts b/apps/tauri/src/api/connection.ts index a025e39c..2954f096 100644 --- a/apps/tauri/src/api/connection.ts +++ b/apps/tauri/src/api/connection.ts @@ -44,8 +44,56 @@ export type TableSchema = { primary_keys: string[]; }; -export async function dbConnectSqlite(path: string): Promise { - return invoke("db_connect_sqlite", { path }); +/** Flutter LocalDb connection row (non-secret fields only). */ +export type ConnectionProfile = { + id: string; + driver: string; + name: string; + path?: string | null; + host?: string | null; + port?: number | null; + username?: string | null; + database_name?: string | null; + folder_id?: string | null; + sort_order: number; + created_at: string; + updated_at: string; +}; + +export async function dbConnectSqlite( + path: string, + id?: string | null, +): Promise { + return invoke("db_connect_sqlite", { path, id: id ?? null }); +} + +export async function profilesList(): Promise { + return invoke("profiles_list"); +} + +export async function profilesUpsert( + profile: ConnectionProfile, +): Promise { + return invoke("profiles_upsert", { profile }); +} + +export async function profilesDelete(id: string): Promise { + return invoke("profiles_delete", { id }); +} + +/** Persist SQLite profile + open live session under the same id. */ +export async function profilesConnectSqlite(opts: { + name: string; + path: string; + folderId?: string | null; + id?: string | null; +}): Promise { + return invoke("profiles_connect_sqlite", { + name: opts.name, + path: opts.path, + folderId: opts.folderId ?? null, + id: opts.id ?? null, + }); } export async function dbDisconnect(id: string): Promise { diff --git a/apps/tauri/src/stores/connections.ts b/apps/tauri/src/stores/connections.ts index 3a3b0bcf..f3af8c71 100644 --- a/apps/tauri/src/stores/connections.ts +++ b/apps/tauri/src/stores/connections.ts @@ -1,9 +1,13 @@ import { defineStore } from "pinia"; import { reactive, ref } from "vue"; import { - dbConnectSqlite, dbDisconnect, formatConnectionError, + profilesConnectSqlite, + profilesDelete, + profilesList, + profilesUpsert, + type ConnectionProfile, } from "../api/connection"; import { DEMO_CONNECTION } from "../mock/demoCatalog"; import { useFoldersStore } from "./folders"; @@ -19,6 +23,8 @@ export type LiveConnection = { mock?: boolean; /** Optional SERVERS folder id. */ folderId?: string | null; + /** Live rusqlite session open in the registry. */ + connected?: boolean; }; function fileName(path: string): string { @@ -26,11 +32,40 @@ function fileName(path: string): string { return parts[parts.length - 1] || path; } +function fromProfile(p: ConnectionProfile, connected = false): LiveConnection | null { + if (p.driver !== "sqlite") return null; + const path = p.path?.trim(); + if (!path) return null; + return { + id: p.id, + driver: "sqlite", + name: p.name, + path, + folderId: p.folder_id ?? null, + connected, + }; +} + +function toProfile(conn: LiveConnection): ConnectionProfile { + const now = String(Math.floor(Date.now() / 1000)); + return { + id: conn.id, + driver: "sqlite", + name: conn.name, + path: conn.path, + folder_id: conn.folderId ?? null, + sort_order: 0, + created_at: now, + updated_at: now, + }; +} + /** Saved / live sessions shown in SERVERS (Flutter connections list). */ export const useConnectionsStore = defineStore("connections", () => { const items = ref([]); /** Incremental index — not rebuilt on every upsert. */ const byId = reactive(new Map()); + const hydrated = ref(false); function upsert(conn: LiveConnection) { const list = items.value; @@ -47,6 +82,31 @@ export const useConnectionsStore = defineStore("connections", () => { if (i >= 0) list.splice(i, 1); } + /** Load saved profiles into SERVERS (not connected until ensureConnected). */ + async function hydrate() { + if (hydrated.value) return; + const status = useShellStatusStore(); + try { + const profiles = await profilesList(); + for (const p of profiles) { + const conn = fromProfile(p, false); + if (conn && !byId.has(conn.id)) upsert(conn); + } + hydrated.value = true; + if (items.value.length > 0) { + status.setQueryMetrics({ + message: `${items.value.length} saved connection${items.value.length === 1 ? "" : "s"}`, + busy: false, + }); + } + } catch (err) { + status.setQueryMetrics({ + message: formatConnectionError(err), + busy: false, + }); + } + } + /** Flutter-style Demo — full UI without opening a real file. */ function launchDemo() { const nav = useShellNavStore(); @@ -60,6 +120,7 @@ export const useConnectionsStore = defineStore("connections", () => { path: DEMO_CONNECTION.path, mock: true, folderId: samples.id, + connected: true, }; upsert(conn); folders.setExpanded(samples.id, true); @@ -75,27 +136,34 @@ export const useConnectionsStore = defineStore("connections", () => { async function connectSqlite( path: string, - opts?: { folderId?: string | null; name?: string }, + opts?: { folderId?: string | null; name?: string; id?: string | null }, ) { const status = useShellStatusStore(); const nav = useShellNavStore(); + const name = opts?.name?.trim() || fileName(path); status.setQueryMetrics({ busy: true, message: `Opening ${fileName(path)}…`, }); try { - const id = await dbConnectSqlite(path); - const conn: LiveConnection = { - id, - driver: "sqlite", - name: opts?.name?.trim() || fileName(path), + const profile = await profilesConnectSqlite({ + name, path, folderId: opts?.folderId ?? null, + id: opts?.id ?? null, + }); + const conn: LiveConnection = { + id: profile.id, + driver: "sqlite", + name: profile.name, + path: profile.path ?? path, + folderId: profile.folder_id ?? opts?.folderId ?? null, + connected: true, }; upsert(conn); - nav.setExpanded(id, true); - nav.selectConnection(id); - status.setConnection(conn.name, path); + nav.setExpanded(conn.id, true); + nav.selectConnection(conn.id); + status.setConnection(conn.name, conn.path); status.setQueryMetrics({ busy: false, message: `Connected · ${conn.name}`, @@ -108,12 +176,57 @@ export const useConnectionsStore = defineStore("connections", () => { } } + /** Open live session for a saved (or already listed) profile. */ + async function ensureConnected(id: string) { + const conn = byId.get(id); + if (!conn || conn.mock) return conn ?? null; + if (conn.connected) return conn; + return connectSqlite(conn.path, { + name: conn.name, + folderId: conn.folderId, + id: conn.id, + }); + } + async function disconnect(id: string) { const status = useShellStatusStore(); const nav = useShellNavStore(); const conn = byId.get(id); try { - if (conn && !conn.mock) await dbDisconnect(id); + if (conn && !conn.mock && conn.connected) await dbDisconnect(id); + } finally { + if (conn && !conn.mock) { + conn.connected = false; + byId.set(id, conn); + } else { + remove(id); + } + if (nav.selectedConnectionId === id) { + status.setConnection(conn?.name ?? null, conn?.path ?? null); + status.setQueryMetrics({ + message: conn ? `Disconnected · ${conn.name}` : "No connection", + busy: false, + }); + } + } + } + + /** Remove from SERVERS + LocalDb (Flutter "Remove connection"). */ + async function removeConnection(id: string) { + const status = useShellStatusStore(); + const nav = useShellNavStore(); + const conn = byId.get(id); + try { + if (conn && !conn.mock) { + if (conn.connected) { + try { + await dbDisconnect(id); + } catch { + /* already closed */ + } + } + await profilesDelete(id); + } } finally { remove(id); if (nav.selectedConnectionId === id) { @@ -129,11 +242,18 @@ export const useConnectionsStore = defineStore("connections", () => { } } - function select(id: string) { - const conn = byId.get(id); - if (!conn) return; + async function select(id: string) { const nav = useShellNavStore(); const status = useShellStatusStore(); + let conn = byId.get(id); + if (!conn) return; + if (!conn.mock && !conn.connected) { + try { + conn = (await ensureConnected(id)) ?? conn; + } catch { + return; + } + } nav.selectConnection(id); status.setConnection(conn.name, conn.mock ? "Demo (offline)" : conn.path); status.setQueryMetrics({ @@ -144,25 +264,43 @@ export const useConnectionsStore = defineStore("connections", () => { }); } - function moveToFolder(connectionId: string, folderId: string | null) { + async function moveToFolder(connectionId: string, folderId: string | null) { const conn = byId.get(connectionId); if (!conn) return; conn.folderId = folderId; + byId.set(connectionId, conn); + if (conn.mock) return; + try { + await profilesUpsert(toProfile(conn)); + } catch (err) { + const status = useShellStatusStore(); + status.setQueryMetrics({ + message: formatConnectionError(err), + busy: false, + }); + } } /** Detach all connections from a folder (Flutter: folder delete keeps connections). */ function detachFolder(folderId: string) { for (const c of items.value) { - if (c.folderId === folderId) c.folderId = null; + if (c.folderId === folderId) { + c.folderId = null; + if (!c.mock) void profilesUpsert(toProfile(c)); + } } } return { items, byId, + hydrated, + hydrate, launchDemo, connectSqlite, + ensureConnected, disconnect, + removeConnection, select, moveToFolder, detachFolder, diff --git a/apps/tauri/src/stores/objectTree.ts b/apps/tauri/src/stores/objectTree.ts index 14597601..254d7040 100644 --- a/apps/tauri/src/stores/objectTree.ts +++ b/apps/tauri/src/stores/objectTree.ts @@ -129,6 +129,7 @@ export const useObjectTreeStore = defineStore("objectTree", () => { st.loading = true; st.error = null; try { + await useConnectionsStore().ensureConnected(connId); st.roots = toUi(await fetchChildren(connId, null)); const [only] = st.roots; if (st.roots.length === 1 && only?.expandable) { diff --git a/apps/tauri/src/ui/ConnectionsPanel.vue b/apps/tauri/src/ui/ConnectionsPanel.vue index 7d1a6655..fd2ce39a 100644 --- a/apps/tauri/src/ui/ConnectionsPanel.vue +++ b/apps/tauri/src/ui/ConnectionsPanel.vue @@ -88,6 +88,7 @@ const ctxItems = computed(() => { ]; return [ { id: "disconnect", label: "Disconnect" }, + { id: "remove", label: "Remove connection" }, { id: "move", label: "Move to folder", @@ -188,6 +189,9 @@ function onCtxSelect(id: string) { } else if (id === "disconnect" && t.type === "connection") { void connections.disconnect(t.connectionId); tree.drop(t.connectionId); + } else if (id === "remove" && t.type === "connection") { + void connections.removeConnection(t.connectionId); + tree.drop(t.connectionId); } else if (id === "move-root" && t.type === "connection") { connections.moveToFolder(t.connectionId, null); } else if (id.startsWith("move:") && t.type === "connection") { @@ -315,7 +319,7 @@ onUnmounted(() => { class="conn-x" :aria-label="`Remove ${c.name}`" @click.stop=" - connections.disconnect(c.id); + connections.removeConnection(c.id); tree.drop(c.id); " > @@ -414,7 +418,7 @@ onUnmounted(() => { class="conn-x" :aria-label="`Remove ${c.name}`" @click.stop=" - connections.disconnect(c.id); + connections.removeConnection(c.id); tree.drop(c.id); " >