25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat: migrate storage from JSON files to SQLite
t8y2f9a9945f1faf
diff --git a/Cargo.lock b/Cargo.lockindex 1cad4596c7..dd0821a06a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -405,30 +405,6 @@ dependencies = ["regex-syntax",]-[[package]]-name = "async-broadcast"-version = "0.7.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"-dependencies = [- "event-listener",- "event-listener-strategy",- "futures-core",- "pin-project-lite",-]--[[package]]-name = "async-channel"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"-dependencies = [- "concurrent-queue",- "event-listener-strategy",- "futures-core",- "pin-project-lite",-]-[[package]]name = "async-compression"version = "0.4.42"@@ -441,35 +417,6 @@ dependencies = ["tokio",]-[[package]]-name = "async-io"-version = "2.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"-dependencies = [- "autocfg",- "cfg-if",- "concurrent-queue",- "futures-io",- "futures-lite",- "parking",- "polling",- "rustix 1.1.4",- "slab",- "windows-sys 0.61.2",-]--[[package]]-name = "async-lock"-version = "3.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"-dependencies = [- "event-listener",- "event-listener-strategy",- "pin-project-lite",-]-[[package]]name = "async-native-tls"version = "0.4.0"@@ -482,53 +429,6 @@ dependencies = ["url",]-[[package]]-name = "async-process"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"-dependencies = [- "async-channel",- "async-io",- "async-lock",- "async-signal",- "async-task",- "blocking",- "cfg-if",- "event-listener",- "futures-lite",- "rustix 1.1.4",-]--[[package]]-name = "async-recursion"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.117",-]--[[package]]-name = "async-signal"-version = "0.2.14"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"-dependencies = [- "async-io",- "async-lock",- "atomic-waker",- "cfg-if",- "futures-core",- "futures-io",- "rustix 1.1.4",- "signal-hook-registry",- "slab",- "windows-sys 0.61.2",-]-[[package]]name = "async-stream"version = "0.3.6"@@ -551,12 +451,6 @@ dependencies = ["syn 2.0.117",]-[[package]]-name = "async-task"-version = "4.7.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"-[[package]]name = "async-trait"version = "0.1.89"@@ -841,19 +735,6 @@ dependencies = ["objc2",]-[[package]]-name = "blocking"-version = "1.6.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"-dependencies = [- "async-channel",- "async-task",- "futures-io",- "futures-lite",- "piper",-]-[[package]]name = "blowfish"version = "0.9.1"@@ -1727,24 +1608,6 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "dbus-secret-service"-version = "4.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"-dependencies = [- "aes 0.8.4",- "block-padding 0.3.3",- "cbc 0.1.2",- "dbus",- "fastrand",- "hkdf 0.12.4",- "num",- "once_cell",- "sha2 0.10.9",- "zeroize",-]-[[package]]name = "dbx"version = "0.4.0"@@ -1756,7 +1619,6 @@ dependencies = ["dbx-core","duckdb","futures",- "keyring","log","mongodb","oracle-rs",@@ -2222,12 +2084,6 @@ dependencies = ["cfg-if",]-[[package]]-name = "endi"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"-[[package]]name = "enum-as-inner"version = "0.6.1"@@ -2259,7 +2115,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"dependencies = ["enumflags2_derive",- "serde",][[package]]@@ -2355,16 +2210,6 @@ dependencies = ["pin-project-lite",]-[[package]]-name = "event-listener-strategy"-version = "0.5.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"-dependencies = [- "event-listener",- "pin-project-lite",-]-[[package]]name = "fallible-iterator"version = "0.3.0"@@ -2602,19 +2447,6 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"-[[package]]-name = "futures-lite"-version = "2.6.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"-dependencies = [- "fastrand",- "futures-core",- "futures-io",- "parking",- "pin-project-lite",-]-[[package]]name = "futures-macro"version = "0.3.32"@@ -3072,12 +2904,6 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"-[[package]]-name = "hermit-abi"-version = "0.5.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"-[[package]]name = "hex"version = "0.4.3"@@ -3842,23 +3668,6 @@ dependencies = ["unicode-segmentation",]-[[package]]-name = "keyring"-version = "3.6.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"-dependencies = [- "byteorder",- "dbus-secret-service",- "linux-keyutils",- "log",- "secret-service",- "security-framework 2.11.1",- "security-framework 3.7.0",- "windows-sys 0.60.2",- "zeroize",-]-[[package]]name = "lazy_static"version = "1.5.0"@@ -4026,16 +3835,6 @@ dependencies = ["vcpkg",]-[[package]]-name = "linux-keyutils"-version = "0.2.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "83270a18e9f90d0707c41e9f35efada77b64c0e6f3f1810e71c8368a864d5590"-dependencies = [- "bitflags 2.11.1",- "libc",-]-[[package]]name = "linux-raw-sys"version = "0.4.15"@@ -4390,7 +4189,7 @@ dependencies = ["openssl-probe","openssl-sys","schannel",- "security-framework 3.7.0",+ "security-framework","security-framework-sys","tempfile",]@@ -4425,19 +4224,6 @@ version = "1.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"-[[package]]-name = "nix"-version = "0.29.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"-dependencies = [- "bitflags 2.11.1",- "cfg-if",- "cfg_aliases",- "libc",- "memoffset",-]-[[package]]name = "nix"version = "0.31.2"@@ -4450,20 +4236,6 @@ dependencies = ["libc",]-[[package]]-name = "num"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"-dependencies = [- "num-bigint",- "num-complex",- "num-integer",- "num-iter",- "num-rational",- "num-traits",-]-[[package]]name = "num-bigint"version = "0.4.6"@@ -4526,17 +4298,6 @@ dependencies = ["num-traits",]-[[package]]-name = "num-rational"-version = "0.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"-dependencies = [- "num-bigint",- "num-integer",- "num-traits",-]-[[package]]name = "num-traits"version = "0.2.19"@@ -4902,16 +4663,6 @@ dependencies = ["webpki-roots 0.26.11",]-[[package]]-name = "ordered-stream"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"-dependencies = [- "futures-core",- "pin-project-lite",-]-[[package]]name = "os_pipe"version = "1.2.3"@@ -5212,17 +4963,6 @@ version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"-[[package]]-name = "piper"-version = "0.2.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"-dependencies = [- "atomic-waker",- "fastrand",- "futures-io",-]-[[package]]name = "pkcs1"version = "0.7.5"@@ -5351,20 +5091,6 @@ dependencies = ["miniz_oxide",]-[[package]]-name = "polling"-version = "3.11.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"-dependencies = [- "cfg-if",- "concurrent-queue",- "hermit-abi",- "pin-project-lite",- "rustix 1.1.4",- "windows-sys 0.61.2",-]-[[package]]name = "poly1305"version = "0.8.0"@@ -6208,7 +5934,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "36140e8a20297bc2e8338807c3d9ca911f7fa49d7539cbcd6d48d3befd70efd8"dependencies = ["log",- "nix 0.31.2",+ "nix","ssh-encoding","windows-sys 0.61.2",]@@ -6339,7 +6065,7 @@ dependencies = ["openssl-probe","rustls-pki-types","schannel",- "security-framework 3.7.0",+ "security-framework",][[package]]@@ -6376,7 +6102,7 @@ dependencies = ["rustls-native-certs","rustls-platform-verifier-android","rustls-webpki",- "security-framework 3.7.0",+ "security-framework","security-framework-sys","webpki-root-certs","windows-sys 0.61.2",@@ -6549,38 +6275,6 @@ dependencies = ["zeroize",]-[[package]]-name = "secret-service"-version = "4.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"-dependencies = [- "aes 0.8.4",- "cbc 0.1.2",- "futures-util",- "generic-array 0.14.7",- "hkdf 0.12.4",- "num",- "once_cell",- "rand 0.8.6",- "serde",- "sha2 0.10.9",- "zbus",-]--[[package]]-name = "security-framework"-version = "2.11.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"-dependencies = [- "bitflags 2.11.1",- "core-foundation 0.9.4",- "core-foundation-sys",- "libc",- "security-framework-sys",-]-[[package]]name = "security-framework"version = "3.7.0"@@ -7327,12 +7021,6 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"-[[package]]-name = "static_assertions"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"-[[package]]name = "string_cache"version = "0.9.0"@@ -8430,17 +8118,6 @@ version = "1.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"-[[package]]-name = "uds_windows"-version = "1.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"-dependencies = [- "memoffset",- "tempfile",- "windows-sys 0.61.2",-]-[[package]]name = "unic-char-property"version = "0.9.0"@@ -9789,16 +9466,6 @@ dependencies = ["rustix 1.1.4",]-[[package]]-name = "xdg-home"-version = "1.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"-dependencies = [- "libc",- "windows-sys 0.59.0",-]-[[package]]name = "yoke"version = "0.8.2"@@ -9822,62 +9489,6 @@ dependencies = ["synstructure",]-[[package]]-name = "zbus"-version = "4.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"-dependencies = [- "async-broadcast",- "async-process",- "async-recursion",- "async-trait",- "enumflags2",- "event-listener",- "futures-core",- "futures-sink",- "futures-util",- "hex",- "nix 0.29.0",- "ordered-stream",- "rand 0.8.6",- "serde",- "serde_repr",- "sha1 0.10.6",- "static_assertions",- "tracing",- "uds_windows",- "windows-sys 0.52.0",- "xdg-home",- "zbus_macros",- "zbus_names",- "zvariant",-]--[[package]]-name = "zbus_macros"-version = "4.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"-dependencies = [- "proc-macro-crate 3.5.0",- "proc-macro2",- "quote",- "syn 2.0.117",- "zvariant_utils",-]--[[package]]-name = "zbus_names"-version = "3.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"-dependencies = [- "serde",- "static_assertions",- "zvariant",-]-[[package]]name = "zerocopy"version = "0.8.48"@@ -9924,20 +9535,6 @@ name = "zeroize"version = "1.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"-dependencies = [- "zeroize_derive",-]--[[package]]-name = "zeroize_derive"-version = "1.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.117",-][[package]]name = "zerotrie"@@ -10023,40 +9620,3 @@ dependencies = ["log","simd-adler32",]--[[package]]-name = "zvariant"-version = "4.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"-dependencies = [- "endi",- "enumflags2",- "serde",- "static_assertions",- "zvariant_derive",-]--[[package]]-name = "zvariant_derive"-version = "4.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"-dependencies = [- "proc-macro-crate 3.5.0",- "proc-macro2",- "quote",- "syn 2.0.117",- "zvariant_utils",-]--[[package]]-name = "zvariant_utils"-version = "2.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.117",-]diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rsindex 94d889db3a..214e1dea1c 100644--- a/crates/dbx-core/src/connection.rs+++ b/crates/dbx-core/src/connection.rs@@ -6,6 +6,7 @@ use crate::db;use crate::db::ssh_tunnel::TunnelManager;use crate::models::connection::{ConnectionConfig, DatabaseType};use crate::query_cancel::RunningQueries;+use crate::storage::Storage;pub fn expand_tilde(path: &str) -> String {if path == "~" || path.starts_with("~/") {@@ -34,15 +35,17 @@ pub struct AppState {pub configs: Mutex<HashMap<String, ConnectionConfig>>,pub running_queries: RunningQueries,pub tunnels: TunnelManager,+ pub storage: Storage,}impl AppState {- pub fn new() -> Self {+ pub fn new(storage: Storage) -> Self {Self {connections: Mutex::new(HashMap::new()),configs: Mutex::new(HashMap::new()),running_queries: RunningQueries::default(),tunnels: TunnelManager::new(),+ storage,}}diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex 7d76510284..20b1d6c76e 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -10,6 +10,7 @@ pub mod query_cancel;pub mod redis_ops;pub mod schema;pub mod sql;+pub mod storage;pub mod table_import;pub mod transfer;pub mod types;diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rsnew file mode 100644index 0000000000..0284a71c7c--- /dev/null+++ b/crates/dbx-core/src/storage.rs@@ -0,0 +1,693 @@+use std::path::Path;+use std::str::FromStr;++use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};++use crate::ai::{AiChatMessage, AiConfig, AiConversation};+use crate::history::HistoryEntry;+use crate::models::connection::ConnectionConfig;++pub struct Storage {+ db: SqlitePool,+}++const SCHEMA_STATEMENTS: &[&str] = &[+ "CREATE TABLE IF NOT EXISTS connections (+ id TEXT PRIMARY KEY,+ config_json TEXT NOT NULL+ )",+ "CREATE TABLE IF NOT EXISTS connection_secrets (+ connection_id TEXT NOT NULL,+ key TEXT NOT NULL,+ secret TEXT NOT NULL,+ PRIMARY KEY (connection_id, key)+ )",+ "CREATE TABLE IF NOT EXISTS history (+ id TEXT PRIMARY KEY,+ connection_name TEXT NOT NULL DEFAULT '',+ database TEXT NOT NULL DEFAULT '',+ sql_text TEXT NOT NULL DEFAULT '',+ executed_at TEXT NOT NULL DEFAULT '',+ execution_time_ms INTEGER NOT NULL DEFAULT 0,+ success INTEGER NOT NULL DEFAULT 1,+ error TEXT+ )",+ "CREATE TABLE IF NOT EXISTS ai_config (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ config_json TEXT NOT NULL+ )",+ "CREATE TABLE IF NOT EXISTS ai_conversations (+ id TEXT PRIMARY KEY,+ title TEXT NOT NULL DEFAULT '',+ connection_name TEXT NOT NULL DEFAULT '',+ database TEXT NOT NULL DEFAULT '',+ messages_json TEXT NOT NULL DEFAULT '[]',+ created_at TEXT NOT NULL DEFAULT '',+ updated_at TEXT NOT NULL DEFAULT ''+ )",+ "CREATE TABLE IF NOT EXISTS sidebar_layout (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ layout_json TEXT NOT NULL+ )",+];++// ---------------------------------------------------------------------------+// Construction / schema+// ---------------------------------------------------------------------------++impl Storage {+ pub async fn open(db_path: &Path) -> Result<Self, String> {+ let url = format!("sqlite:{}?mode=rwc", db_path.display());+ let options = SqliteConnectOptions::from_str(&url)+ .map_err(|e| e.to_string())?+ .create_if_missing(true);+ let pool = SqlitePoolOptions::new()+ .max_connections(5)+ .connect_with(options)+ .await+ .map_err(|e| e.to_string())?;++ for statement in SCHEMA_STATEMENTS {+ sqlx::query(statement)+ .execute(&pool)+ .await+ .map_err(|e| e.to_string())?;+ }++ Ok(Self { db: pool })+ }+}++// ---------------------------------------------------------------------------+// History+// ---------------------------------------------------------------------------++#[derive(sqlx::FromRow)]+struct HistoryRow {+ id: String,+ connection_name: String,+ database: String,+ sql_text: String,+ executed_at: String,+ execution_time_ms: i64,+ success: bool,+ error: Option<String>,+}++impl Storage {+ pub async fn save_history_entry(&self, entry: &HistoryEntry) -> Result<(), String> {+ sqlx::query(+ "INSERT OR REPLACE INTO history \+ (id, connection_name, database, sql_text, executed_at, execution_time_ms, success, error) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&entry.id)+ .bind(&entry.connection_name)+ .bind(&entry.database)+ .bind(&entry.sql)+ .bind(&entry.executed_at)+ .bind(entry.execution_time_ms as i64)+ .bind(entry.success)+ .bind(&entry.error)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ // Keep at most MAX_HISTORY entries+ sqlx::query(+ "DELETE FROM history WHERE id NOT IN \+ (SELECT id FROM history ORDER BY executed_at DESC LIMIT 1000)",+ )+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ Ok(())+ }++ pub async fn load_history_entries(+ &self,+ limit: usize,+ offset: usize,+ ) -> Result<Vec<HistoryEntry>, String> {+ let rows: Vec<HistoryRow> = sqlx::query_as(+ "SELECT id, connection_name, database, sql_text, executed_at, \+ execution_time_ms, success, error \+ FROM history ORDER BY executed_at DESC LIMIT ? OFFSET ?",+ )+ .bind(limit as i64)+ .bind(offset as i64)+ .fetch_all(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ Ok(rows+ .into_iter()+ .map(|r| HistoryEntry {+ id: r.id,+ connection_name: r.connection_name,+ database: r.database,+ sql: r.sql_text,+ executed_at: r.executed_at,+ execution_time_ms: r.execution_time_ms as u128,+ success: r.success,+ error: r.error,+ })+ .collect())+ }++ pub async fn clear_history(&self) -> Result<(), String> {+ sqlx::query("DELETE FROM history")+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }++ pub async fn delete_history_entry(&self, id: &str) -> Result<(), String> {+ sqlx::query("DELETE FROM history WHERE id = ?")+ .bind(id)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }+}++// ---------------------------------------------------------------------------+// AI Config+// ---------------------------------------------------------------------------++impl Storage {+ pub async fn save_ai_config(&self, config: &AiConfig) -> Result<(), String> {+ let json = serde_json::to_string(config).map_err(|e| e.to_string())?;+ sqlx::query("INSERT OR REPLACE INTO ai_config (id, config_json) VALUES (1, ?)")+ .bind(&json)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }++ pub async fn load_ai_config(&self) -> Result<Option<AiConfig>, String> {+ let row: Option<(String,)> =+ sqlx::query_as("SELECT config_json FROM ai_config WHERE id = 1")+ .fetch_optional(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ match row {+ Some((json,)) => serde_json::from_str(&json)+ .map(Some)+ .map_err(|e| e.to_string()),+ None => Ok(None),+ }+ }+}++// ---------------------------------------------------------------------------+// AI Conversations+// ---------------------------------------------------------------------------++#[derive(sqlx::FromRow)]+struct AiConversationRow {+ id: String,+ title: String,+ connection_name: String,+ database: String,+ messages_json: String,+ created_at: String,+ updated_at: String,+}++impl Storage {+ pub async fn save_ai_conversation(&self, conv: &AiConversation) -> Result<(), String> {+ let messages_json =+ serde_json::to_string(&conv.messages).map_err(|e| e.to_string())?;+ sqlx::query(+ "INSERT OR REPLACE INTO ai_conversations \+ (id, title, connection_name, database, messages_json, created_at, updated_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&conv.id)+ .bind(&conv.title)+ .bind(&conv.connection_name)+ .bind(&conv.database)+ .bind(&messages_json)+ .bind(&conv.created_at)+ .bind(&conv.updated_at)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ // Keep at most 50 conversations+ sqlx::query(+ "DELETE FROM ai_conversations WHERE id NOT IN \+ (SELECT id FROM ai_conversations ORDER BY updated_at DESC LIMIT 50)",+ )+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ Ok(())+ }++ pub async fn load_ai_conversations(&self) -> Result<Vec<AiConversation>, String> {+ let rows: Vec<AiConversationRow> = sqlx::query_as(+ "SELECT id, title, connection_name, database, messages_json, \+ created_at, updated_at \+ FROM ai_conversations ORDER BY updated_at DESC",+ )+ .fetch_all(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ rows.into_iter()+ .map(|r| {+ let messages: Vec<AiChatMessage> =+ serde_json::from_str(&r.messages_json).map_err(|e| e.to_string())?;+ Ok(AiConversation {+ id: r.id,+ title: r.title,+ connection_name: r.connection_name,+ database: r.database,+ messages,+ created_at: r.created_at,+ updated_at: r.updated_at,+ })+ })+ .collect()+ }++ pub async fn delete_ai_conversation(&self, id: &str) -> Result<(), String> {+ sqlx::query("DELETE FROM ai_conversations WHERE id = ?")+ .bind(id)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }+}++// ---------------------------------------------------------------------------+// Connections (with inline secrets)+// ---------------------------------------------------------------------------++impl Storage {+ pub async fn save_connections(&self, configs: &[ConnectionConfig]) -> Result<(), String> {+ let mut tx = self.db.begin().await.map_err(|e| e.to_string())?;++ sqlx::query("DELETE FROM connections")+ .execute(&mut *tx)+ .await+ .map_err(|e| e.to_string())?;++ for config in configs {+ // Store config without secrets+ let mut sanitized = config.clone();+ sanitized.password = String::new();+ sanitized.ssh_password = String::new();+ sanitized.ssh_key_passphrase = String::new();+ sanitized.connection_string = None;+ let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;++ sqlx::query("INSERT INTO connections (id, config_json) VALUES (?, ?)")+ .bind(&config.id)+ .bind(&json)+ .execute(&mut *tx)+ .await+ .map_err(|e| e.to_string())?;++ // Store secrets+ persist_secret_in_tx(&mut tx, &config.id, "password", &config.password).await?;+ persist_secret_in_tx(&mut tx, &config.id, "ssh_password", &config.ssh_password)+ .await?;+ persist_secret_in_tx(+ &mut tx,+ &config.id,+ "ssh_key_passphrase",+ &config.ssh_key_passphrase,+ )+ .await?;+ if let Some(cs) = &config.connection_string {+ persist_secret_in_tx(&mut tx, &config.id, "connection_string", cs).await?;+ } else {+ sqlx::query(+ "DELETE FROM connection_secrets WHERE connection_id = ? AND key = ?",+ )+ .bind(&config.id)+ .bind("connection_string")+ .execute(&mut *tx)+ .await+ .map_err(|e| e.to_string())?;+ }+ }++ // Remove secrets for connections that no longer exist+ if configs.is_empty() {+ sqlx::query("DELETE FROM connection_secrets")+ .execute(&mut *tx)+ .await+ .map_err(|e| e.to_string())?;+ } else {+ let placeholders: Vec<&str> = configs.iter().map(|_| "?").collect();+ let sql = format!(+ "DELETE FROM connection_secrets WHERE connection_id NOT IN ({})",+ placeholders.join(",")+ );+ let mut query = sqlx::query(&sql);+ for config in configs {+ query = query.bind(&config.id);+ }+ query+ .execute(&mut *tx)+ .await+ .map_err(|e| e.to_string())?;+ }++ tx.commit().await.map_err(|e| e.to_string())?;+ Ok(())+ }++ pub async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {+ let rows: Vec<(String, String)> =+ sqlx::query_as("SELECT id, config_json FROM connections")+ .fetch_all(&self.db)+ .await+ .map_err(|e| e.to_string())?;++ let mut configs = Vec::new();+ for (id, json) in rows {+ let mut config: ConnectionConfig =+ serde_json::from_str(&json).map_err(|e| e.to_string())?;+ config.password = self+ .get_secret(&id, "password")+ .await?+ .unwrap_or_default();+ config.ssh_password = self+ .get_secret(&id, "ssh_password")+ .await?+ .unwrap_or_default();+ config.ssh_key_passphrase = self+ .get_secret(&id, "ssh_key_passphrase")+ .await?+ .unwrap_or_default();+ config.connection_string = self.get_secret(&id, "connection_string").await?;+ configs.push(config);+ }+ Ok(configs)+ }+}++// ---------------------------------------------------------------------------+// Secrets+// ---------------------------------------------------------------------------++impl Storage {+ pub async fn get_secret(+ &self,+ connection_id: &str,+ key: &str,+ ) -> Result<Option<String>, String> {+ let row: Option<(String,)> = sqlx::query_as(+ "SELECT secret FROM connection_secrets WHERE connection_id = ? AND key = ?",+ )+ .bind(connection_id)+ .bind(key)+ .fetch_optional(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(row.map(|(s,)| s))+ }++ pub async fn set_secret(+ &self,+ connection_id: &str,+ key: &str,+ secret: &str,+ ) -> Result<(), String> {+ sqlx::query(+ "INSERT OR REPLACE INTO connection_secrets (connection_id, key, secret) \+ VALUES (?, ?, ?)",+ )+ .bind(connection_id)+ .bind(key)+ .bind(secret)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }++ pub async fn delete_secret(+ &self,+ connection_id: &str,+ key: &str,+ ) -> Result<(), String> {+ sqlx::query("DELETE FROM connection_secrets WHERE connection_id = ? AND key = ?")+ .bind(connection_id)+ .bind(key)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }+}++// ---------------------------------------------------------------------------+// Layout+// ---------------------------------------------------------------------------++impl Storage {+ pub async fn save_sidebar_layout(+ &self,+ layout: &serde_json::Value,+ ) -> Result<(), String> {+ let json = serde_json::to_string(layout).map_err(|e| e.to_string())?;+ sqlx::query("INSERT OR REPLACE INTO sidebar_layout (id, layout_json) VALUES (1, ?)")+ .bind(&json)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ Ok(())+ }++ pub async fn load_sidebar_layout(&self) -> Result<Option<serde_json::Value>, String> {+ let row: Option<(String,)> =+ sqlx::query_as("SELECT layout_json FROM sidebar_layout WHERE id = 1")+ .fetch_optional(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ match row {+ Some((json,)) => serde_json::from_str(&json)+ .map(Some)+ .map_err(|e| e.to_string()),+ None => Ok(None),+ }+ }+}++// ---------------------------------------------------------------------------+// JSON migration+// ---------------------------------------------------------------------------++impl Storage {+ pub async fn migrate_from_json(&self, data_dir: &Path) -> Result<(), String> {+ self.migrate_connections_json(data_dir).await?;+ self.migrate_secrets_json(data_dir).await?;+ self.migrate_history_json(data_dir).await?;+ self.migrate_ai_config_json(data_dir).await?;+ self.migrate_ai_conversations_json(data_dir).await?;+ self.migrate_sidebar_layout_json(data_dir).await?;+ Ok(())+ }++ async fn migrate_connections_json(&self, data_dir: &Path) -> Result<(), String> {+ let path = data_dir.join("connections.json");+ if !path.exists() {+ return Ok(());+ }+ let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let configs: Vec<ConnectionConfig> = serde_json::from_str(&json).unwrap_or_default();+ for config in &configs {+ let config_json =+ serde_json::to_string(config).map_err(|e| e.to_string())?;+ sqlx::query("INSERT OR IGNORE INTO connections (id, config_json) VALUES (?, ?)")+ .bind(&config.id)+ .bind(&config_json)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ }+ std::fs::rename(&path, data_dir.join("connections.json.bak")).ok();+ Ok(())+ }++ async fn migrate_secrets_json(&self, data_dir: &Path) -> Result<(), String> {+ let path = data_dir.join("secrets.json");+ if !path.exists() {+ return Ok(());+ }+ let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let secrets: std::collections::HashMap<String, String> =+ serde_json::from_str(&json).unwrap_or_default();+ for (key, secret) in &secrets {+ // key format: "connection:{id}:{field}"+ let parts: Vec<&str> = key.splitn(3, ':').collect();+ if parts.len() == 3 && parts[0] == "connection" {+ sqlx::query(+ "INSERT OR IGNORE INTO connection_secrets \+ (connection_id, key, secret) VALUES (?, ?, ?)",+ )+ .bind(parts[1])+ .bind(parts[2])+ .bind(secret)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ }+ }+ std::fs::rename(&path, data_dir.join("secrets.json.bak")).ok();+ Ok(())+ }++ async fn migrate_history_json(&self, data_dir: &Path) -> Result<(), String> {+ let path = data_dir.join("query_history.json");+ if !path.exists() {+ return Ok(());+ }+ let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let entries: Vec<HistoryEntry> = serde_json::from_str(&json).unwrap_or_default();+ for entry in &entries {+ sqlx::query(+ "INSERT OR IGNORE INTO history \+ (id, connection_name, database, sql_text, executed_at, \+ execution_time_ms, success, error) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&entry.id)+ .bind(&entry.connection_name)+ .bind(&entry.database)+ .bind(&entry.sql)+ .bind(&entry.executed_at)+ .bind(entry.execution_time_ms as i64)+ .bind(entry.success)+ .bind(&entry.error)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ }+ std::fs::rename(&path, data_dir.join("query_history.json.bak")).ok();+ Ok(())+ }++ async fn migrate_ai_config_json(&self, data_dir: &Path) -> Result<(), String> {+ let path = data_dir.join("ai_config.json");+ if !path.exists() {+ return Ok(());+ }+ let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ // Only migrate if the table is empty+ let count: (i64,) =+ sqlx::query_as("SELECT COUNT(*) FROM ai_config")+ .fetch_one(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ if count.0 == 0 {+ sqlx::query("INSERT OR IGNORE INTO ai_config (id, config_json) VALUES (1, ?)")+ .bind(&json)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ }+ std::fs::rename(&path, data_dir.join("ai_config.json.bak")).ok();+ Ok(())+ }++ async fn migrate_ai_conversations_json(&self, data_dir: &Path) -> Result<(), String> {+ let path = data_dir.join("ai_conversations.json");+ if !path.exists() {+ return Ok(());+ }+ let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let conversations: Vec<AiConversation> =+ serde_json::from_str(&json).unwrap_or_default();+ for conv in &conversations {+ let messages_json =+ serde_json::to_string(&conv.messages).map_err(|e| e.to_string())?;+ sqlx::query(+ "INSERT OR IGNORE INTO ai_conversations \+ (id, title, connection_name, database, messages_json, \+ created_at, updated_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&conv.id)+ .bind(&conv.title)+ .bind(&conv.connection_name)+ .bind(&conv.database)+ .bind(&messages_json)+ .bind(&conv.created_at)+ .bind(&conv.updated_at)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ }+ std::fs::rename(&path, data_dir.join("ai_conversations.json.bak")).ok();+ Ok(())+ }++ async fn migrate_sidebar_layout_json(&self, data_dir: &Path) -> Result<(), String> {+ let path = data_dir.join("sidebar_layout.json");+ if !path.exists() {+ return Ok(());+ }+ let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;+ let count: (i64,) =+ sqlx::query_as("SELECT COUNT(*) FROM sidebar_layout")+ .fetch_one(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ if count.0 == 0 {+ sqlx::query(+ "INSERT OR IGNORE INTO sidebar_layout (id, layout_json) VALUES (1, ?)",+ )+ .bind(&json)+ .execute(&self.db)+ .await+ .map_err(|e| e.to_string())?;+ }+ std::fs::rename(&path, data_dir.join("sidebar_layout.json.bak")).ok();+ Ok(())+ }+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++async fn persist_secret_in_tx(+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,+ connection_id: &str,+ key: &str,+ secret: &str,+) -> Result<(), String> {+ if secret.is_empty() {+ sqlx::query("DELETE FROM connection_secrets WHERE connection_id = ? AND key = ?")+ .bind(connection_id)+ .bind(key)+ .execute(&mut **tx)+ .await+ .map_err(|e| e.to_string())?;+ } else {+ sqlx::query(+ "INSERT OR REPLACE INTO connection_secrets \+ (connection_id, key, secret) VALUES (?, ?, ?)",+ )+ .bind(connection_id)+ .bind(key)+ .bind(secret)+ .execute(&mut **tx)+ .await+ .map_err(|e| e.to_string())?;+ }+ Ok(())+}diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 36d4119de1..4df4c2afdf 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -44,7 +44,6 @@ mongodb = "3.2.5"oracle-rs = "0.1"percent-encoding = "2"russh = "0.60"-keyring = { version = "3.6.3", features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }csv = "1.4.0"calamine = "0.30.1"dbx-core = { path = "../crates/dbx-core" }diff --git a/src-tauri/src/commands/ai.rs b/src-tauri/src/commands/ai.rsindex c0ce529789..66aebe5e08 100644--- a/src-tauri/src/commands/ai.rs+++ b/src-tauri/src/commands/ai.rs@@ -1,32 +1,27 @@-use tauri::{AppHandle, Emitter, Manager};+use std::sync::Arc;+use tauri::{Emitter, AppHandle, State};+use super::connection::AppState;pub use dbx_core::ai::*;-fn ai_config_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {- let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;- Ok(dir.join("ai_config.json"))-}--fn conversations_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {- let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;- Ok(dir.join("ai_conversations.json"))-}-#[tauri::command]pub async fn ai_test_connection(config: AiConfig) -> Result<String, String> {dbx_core::ai::test_connection_core(&config).await}#[tauri::command]-pub async fn save_ai_config(app: AppHandle, config: AiConfig) -> Result<(), String> {- dbx_core::ai::save_config(&ai_config_file(&app)?, &config)+pub async fn save_ai_config(+ state: State<'_, Arc<AppState>>,+ config: AiConfig,+) -> Result<(), String> {+ state.storage.save_ai_config(&config).await}#[tauri::command]-pub async fn load_ai_config(app: AppHandle) -> Result<Option<AiConfig>, String> {- dbx_core::ai::load_config(&ai_config_file(&app)?)+pub async fn load_ai_config(+ state: State<'_, Arc<AppState>>,+) -> Result<Option<AiConfig>, String> {+ state.storage.load_ai_config().await}#[tauri::command]@@ -58,18 +53,23 @@ pub async fn ai_cancel_stream(session_id: String) -> Result<bool, String> {#[tauri::command]pub async fn save_ai_conversation(- app: AppHandle,+ state: State<'_, Arc<AppState>>,conversation: AiConversation,) -> Result<(), String> {- dbx_core::ai::save_conversation(&conversations_file(&app)?, conversation)+ state.storage.save_ai_conversation(&conversation).await}#[tauri::command]-pub async fn load_ai_conversations(app: AppHandle) -> Result<Vec<AiConversation>, String> {- dbx_core::ai::load_conversations(&conversations_file(&app)?)+pub async fn load_ai_conversations(+ state: State<'_, Arc<AppState>>,+) -> Result<Vec<AiConversation>, String> {+ state.storage.load_ai_conversations().await}#[tauri::command]-pub async fn delete_ai_conversation(app: AppHandle, id: String) -> Result<(), String> {- dbx_core::ai::delete_conversation(&conversations_file(&app)?, &id)+pub async fn delete_ai_conversation(+ state: State<'_, Arc<AppState>>,+ id: String,+) -> Result<(), String> {+ state.storage.delete_ai_conversation(&id).await}diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rsindex d3bb73b40e..555aa1e792 100644--- a/src-tauri/src/commands/connection.rs+++ b/src-tauri/src/commands/connection.rs@@ -1,9 +1,5 @@use std::sync::Arc;-use tauri::{AppHandle, Manager, State};--use crate::commands::connection_secrets::{- create_secret_store, load_connections_from_file, save_connections_to_file,-};+use tauri::State;pub use dbx_core::connection::{connection_url_for_endpoint, expand_tilde, redacted_connection_url_for_endpoint, AppState,@@ -12,54 +8,34 @@ pub use dbx_core::connection::{use dbx_core::db;use dbx_core::models::connection::{ConnectionConfig, DatabaseType};-fn connections_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {- let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;- Ok(dir.join("connections.json"))-}--fn sidebar_layout_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {- let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;- Ok(dir.join("sidebar_layout.json"))-}-#[tauri::command]pub async fn save_connections(- app: AppHandle,+ state: State<'_, Arc<AppState>>,configs: Vec<ConnectionConfig>,) -> Result<(), String> {- let path = connections_file(&app)?;- let store = create_secret_store(&app);- save_connections_to_file(&path, &configs, &*store)+ state.storage.save_connections(&configs).await}#[tauri::command]-pub async fn load_connections(app: AppHandle) -> Result<Vec<ConnectionConfig>, String> {- let path = connections_file(&app)?;- let store = create_secret_store(&app);- load_connections_from_file(&path, &*store)+pub async fn load_connections(+ state: State<'_, Arc<AppState>>,+) -> Result<Vec<ConnectionConfig>, String> {+ state.storage.load_connections().await}#[tauri::command]pub async fn save_sidebar_layout(- app: AppHandle,+ state: State<'_, Arc<AppState>>,layout: serde_json::Value,) -> Result<(), String> {- let path = sidebar_layout_file(&app)?;- let json = serde_json::to_string_pretty(&layout).map_err(|e| e.to_string())?;- std::fs::write(&path, json).map_err(|e| e.to_string())+ state.storage.save_sidebar_layout(&layout).await}#[tauri::command]-pub async fn load_sidebar_layout(app: AppHandle) -> Result<Option<serde_json::Value>, String> {- let path = sidebar_layout_file(&app)?;- if !path.exists() {- return Ok(None);- }- let content = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;- let value: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;- Ok(Some(value))+pub async fn load_sidebar_layout(+ state: State<'_, Arc<AppState>>,+) -> Result<Option<serde_json::Value>, String> {+ state.storage.load_sidebar_layout().await}#[tauri::command]diff --git a/src-tauri/src/commands/connection_secrets.rs b/src-tauri/src/commands/connection_secrets.rsindex 409d1048dd..5ad5e1c7d0 100644--- a/src-tauri/src/commands/connection_secrets.rs+++ b/src-tauri/src/commands/connection_secrets.rs@@ -1,57 +1 @@-use tauri::{AppHandle, Manager};--// Re-export core types and functions-pub(super) use dbx_core::connection_secrets::{- save_connections_to_file, load_connections_from_file,- ConnectionSecretStore, FileSecretStore,- secret_account,-};--const KEYRING_SERVICE: &str = "dev.dbx.connections";--pub(super) struct KeyringConnectionSecretStore;--impl ConnectionSecretStore for KeyringConnectionSecretStore {- fn set_secret(&self, connection_id: &str, key: &str, secret: &str) -> Result<(), String> {- let entry = keyring_entry(connection_id, key, "create")?;- entry- .set_password(secret)- .map_err(|err| keyring_error("store", connection_id, key, err))- }-- fn get_secret(&self, connection_id: &str, key: &str) -> Result<Option<String>, String> {- let entry = keyring_entry(connection_id, key, "create")?;- match entry.get_password() {- Ok(secret) => Ok(Some(secret)),- Err(keyring::Error::NoEntry) => Ok(None),- Err(err) => Err(keyring_error("read", connection_id, key, err)),- }- }-- fn delete_secret(&self, connection_id: &str, key: &str) -> Result<(), String> {- let entry = keyring_entry(connection_id, key, "create")?;- match entry.delete_credential() {- Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),- Err(err) => Err(keyring_error("delete", connection_id, key, err)),- }- }-}--pub(super) fn create_secret_store(app: &AppHandle) -> Box<dyn ConnectionSecretStore> {- if cfg!(debug_assertions) {- let dir = app.path().app_data_dir().expect("failed to resolve app data dir");- std::fs::create_dir_all(&dir).ok();- Box::new(FileSecretStore::new(dir.join("secrets.json")))- } else {- Box::new(KeyringConnectionSecretStore)- }-}--fn keyring_entry(connection_id: &str, key: &str, action: &str) -> Result<keyring::Entry, String> {- keyring::Entry::new(KEYRING_SERVICE, &secret_account(connection_id, key))- .map_err(|err| keyring_error(action, connection_id, key, err))-}--fn keyring_error(action: &str, connection_id: &str, key: &str, err: keyring::Error) -> String {- format!("Failed to {action} saved {key} for connection {connection_id}: {err}")-}+// Legacy module — no longer used. All storage now goes through dbx_core::storage::Storage (SQLite).diff --git a/src-tauri/src/commands/history.rs b/src-tauri/src/commands/history.rsindex fbb603e5d8..b0e6b045bb 100644--- a/src-tauri/src/commands/history.rs+++ b/src-tauri/src/commands/history.rs@@ -1,37 +1,35 @@-use tauri::{AppHandle, Manager};+use std::sync::Arc;+use tauri::State;+use super::connection::AppState;pub use dbx_core::history::HistoryEntry;-fn history_file(app: &AppHandle) -> Result<std::path::PathBuf, String> {- let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;- Ok(dir.join("query_history.json"))-}-#[tauri::command]-pub async fn save_history(app: AppHandle, entry: HistoryEntry) -> Result<(), String> {- let path = history_file(&app)?;- dbx_core::history::save_history_entry(&path, entry)+pub async fn save_history(+ state: State<'_, Arc<AppState>>,+ entry: HistoryEntry,+) -> Result<(), String> {+ state.storage.save_history_entry(&entry).await}#[tauri::command]pub async fn load_history(- app: AppHandle,+ state: State<'_, Arc<AppState>>,limit: usize,offset: usize,) -> Result<Vec<HistoryEntry>, String> {- let path = history_file(&app)?;- dbx_core::history::load_history_entries(&path, limit, offset)+ state.storage.load_history_entries(limit, offset).await}#[tauri::command]-pub async fn clear_history(app: AppHandle) -> Result<(), String> {- let path = history_file(&app)?;- dbx_core::history::clear_history_entries(&path)+pub async fn clear_history(state: State<'_, Arc<AppState>>) -> Result<(), String> {+ state.storage.clear_history().await}#[tauri::command]-pub async fn delete_history_entry(app: AppHandle, id: String) -> Result<(), String> {- let path = history_file(&app)?;- dbx_core::history::delete_history_entry_by_id(&path, &id)+pub async fn delete_history_entry(+ state: State<'_, Arc<AppState>>,+ id: String,+) -> Result<(), String> {+ state.storage.delete_history_entry(&id).await}diff --git a/src-tauri/src/commands/mcp_bridge.rs b/src-tauri/src/commands/mcp_bridge.rsindex 20c8f08571..dcd9e9ceb7 100644--- a/src-tauri/src/commands/mcp_bridge.rs+++ b/src-tauri/src/commands/mcp_bridge.rs@@ -1,11 +1,10 @@use serde::{Deserialize, Serialize};use std::sync::Arc;-use tauri::{AppHandle, Emitter, Manager};+use tauri::{Emitter, AppHandle, Manager};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpListener;use super::connection::AppState;-use super::connection_secrets::{create_secret_store, load_connections_from_file};const BIND_ADDR: &str = "127.0.0.1:0";@@ -39,7 +38,7 @@ pub struct McpExecuteQueryEvent {pub sql: String,}-pub fn start(app_handle: AppHandle, _state: Arc<AppState>) {+pub fn start(app_handle: AppHandle, state: Arc<AppState>) {tauri::async_runtime::spawn(async move {let listener = match TcpListener::bind(BIND_ADDR).await {Ok(l) => l,@@ -60,6 +59,7 @@ pub fn start(app_handle: AppHandle, _state: Arc<AppState>) {Err(_) => continue,};let app = app_handle.clone();+ let st = state.clone();tokio::spawn(async move {let mut buf = vec![0u8; 16384];let n = match stream.read(&mut buf).await {@@ -71,9 +71,9 @@ pub fn start(app_handle: AppHandle, _state: Arc<AppState>) {let first_line = request.lines().next().unwrap_or("");if first_line.starts_with("POST /open-table") {- handle_open_table(&app, body, &mut stream).await;+ handle_open_table(&app, &st, body, &mut stream).await;} else if first_line.starts_with("POST /execute-query") {- handle_execute_query(&app, body, &mut stream).await;+ handle_execute_query(&app, &st, body, &mut stream).await;} else {let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n").await;}@@ -82,13 +82,6 @@ pub fn start(app_handle: AppHandle, _state: Arc<AppState>) {});}-fn load_configs_from_disk(app: &AppHandle) -> Result<Vec<crate::models::connection::ConnectionConfig>, String> {- let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;- let path = dir.join("connections.json");- let store = create_secret_store(app);- load_connections_from_file(&path, &*store)-}-fn find_config_by_name<'a>(configs: &'a [crate::models::connection::ConnectionConfig], name: &str) -> Option<&'a crate::models::connection::ConnectionConfig> {configs.iter().find(|c| c.name.eq_ignore_ascii_case(name))}@@ -98,12 +91,12 @@ async fn respond(stream: &mut tokio::net::TcpStream, status: &str, body: &str) {let _ = stream.write_all(resp.as_bytes()).await;}-async fn handle_open_table(app: &AppHandle, body: &str, stream: &mut tokio::net::TcpStream) {+async fn handle_open_table(app: &AppHandle, state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {let req: OpenTableRequest = match serde_json::from_str(body) {Ok(r) => r,Err(_) => { respond(stream, "400 Bad Request", "").await; return; }};- let configs = match load_configs_from_disk(app) {+ let configs = match state.storage.load_connections().await {Ok(c) => c,Err(_) => { respond(stream, "500 Internal Server Error", "").await; return; }};@@ -120,12 +113,12 @@ async fn handle_open_table(app: &AppHandle, body: &str, stream: &mut tokio::net:respond(stream, "200 OK", "ok").await;}-async fn handle_execute_query(app: &AppHandle, body: &str, stream: &mut tokio::net::TcpStream) {+async fn handle_execute_query(app: &AppHandle, state: &Arc<AppState>, body: &str, stream: &mut tokio::net::TcpStream) {let req: ExecuteQueryRequest = match serde_json::from_str(body) {Ok(r) => r,Err(_) => { respond(stream, "400 Bad Request", "").await; return; }};- let configs = match load_configs_from_disk(app) {+ let configs = match state.storage.load_connections().await {Ok(c) => c,Err(_) => { respond(stream, "500 Internal Server Error", "").await; return; }};diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex e9a8bd2daf..d4cbef3d59 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -1,5 +1,6 @@pub mod ai;pub mod connection;+#[allow(dead_code, unused_imports)]mod connection_secrets;pub mod history;pub mod mcp_bridge;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 4208ff6548..ca342e3083 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -3,6 +3,7 @@ mod db;mod models;use commands::connection::AppState;+use dbx_core::storage::Storage;use std::sync::Arc;use tauri::{Manager, RunEvent};@@ -12,15 +13,12 @@ pub fn run() {.install_default().expect("Failed to install rustls crypto provider");- let state = Arc::new(AppState::new());-tauri::Builder::default().plugin(tauri_plugin_dialog::init()).plugin(tauri_plugin_fs::init()).plugin(tauri_plugin_shell::init()).plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_process::init())- .manage(state).setup(|app| {if cfg!(debug_assertions) {app.handle().plugin(@@ -29,9 +27,28 @@ pub fn run() {.build(),)?;}++ let data_dir = app+ .path()+ .app_data_dir()+ .map_err(|e| e.to_string())+ .expect("Failed to resolve app data dir");+ std::fs::create_dir_all(&data_dir).expect("Failed to create data dir");+ let db_path = data_dir.join("dbx.db");++ let storage = tauri::async_runtime::block_on(async {+ let s = Storage::open(&db_path).await.expect("Failed to open storage");+ s.migrate_from_json(&data_dir)+ .await+ .expect("Failed to migrate JSON data");+ s+ });++ let state = Arc::new(AppState::new(storage));+ app.manage(state.clone());+let app_handle = app.handle().clone();- let state: tauri::State<Arc<AppState>> = app.state();- commands::mcp_bridge::start(app_handle, state.inner().clone());+ commands::mcp_bridge::start(app_handle, state);Ok(())}).on_window_event(|window, event| {diff --git a/src-web/src/main.rs b/src-web/src/main.rsindex 54630b9b6d..c7c414d08c 100644--- a/src-web/src/main.rs+++ b/src-web/src/main.rs@@ -12,6 +12,7 @@ use axum::middleware;use axum::routing::{delete, get, post};use axum::Router;use dbx_core::connection::AppState;+use dbx_core::storage::Storage;use sha2::{Digest, Sha256};use tokio::sync::RwLock;use tower_http::cors::{Any, CorsLayer};@@ -26,8 +27,6 @@ async fn main() {.install_default().expect("Failed to install rustls crypto provider");- let app_state = Arc::new(AppState::new());-// Data directorylet data_dir = std::env::var("DBX_DATA_DIR").map(std::path::PathBuf::from)@@ -37,6 +36,18 @@ async fn main() {});std::fs::create_dir_all(&data_dir).expect("Failed to create data directory");+ let app_state = {+ let db_path = data_dir.join("dbx.db");+ let storage = Storage::open(&db_path)+ .await+ .expect("Failed to open storage");+ storage+ .migrate_from_json(&data_dir)+ .await+ .expect("Failed to migrate JSON data");+ Arc::new(AppState::new(storage))+ };+// Password hashlet password_hash = std::env::var("DBX_PASSWORD").ok().map(|pw| {let mut hasher = Sha256::new();diff --git a/src-web/src/routes/ai.rs b/src-web/src/routes/ai.rsindex 2ce7635c65..56d0181d51 100644--- a/src-web/src/routes/ai.rs+++ b/src-web/src/routes/ai.rs@@ -62,16 +62,24 @@ pub async fn save_ai_config(State(state): State<Arc<WebState>>,Json(body): Json<SaveAiConfigRequest>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("ai_config.json");- dbx_core::ai::save_config(&path, &body.config).map_err(AppError)?;+ state+ .app+ .storage+ .save_ai_config(&body.config)+ .await+ .map_err(AppError)?;Ok(Json(()))}pub async fn load_ai_config(State(state): State<Arc<WebState>>,) -> Result<Json<Option<AiConfig>>, AppError> {- let path = state.data_dir.join("ai_config.json");- let config = dbx_core::ai::load_config(&path).map_err(AppError)?;+ let config = state+ .app+ .storage+ .load_ai_config()+ .await+ .map_err(AppError)?;Ok(Json(config))}@@ -83,16 +91,24 @@ pub async fn save_ai_conversation(State(state): State<Arc<WebState>>,Json(body): Json<SaveAiConversationRequest>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("ai_conversations.json");- dbx_core::ai::save_conversation(&path, body.conversation).map_err(AppError)?;+ state+ .app+ .storage+ .save_ai_conversation(&body.conversation)+ .await+ .map_err(AppError)?;Ok(Json(()))}pub async fn load_ai_conversations(State(state): State<Arc<WebState>>,) -> Result<Json<Vec<AiConversation>>, AppError> {- let path = state.data_dir.join("ai_conversations.json");- let conversations = dbx_core::ai::load_conversations(&path).map_err(AppError)?;+ let conversations = state+ .app+ .storage+ .load_ai_conversations()+ .await+ .map_err(AppError)?;Ok(Json(conversations))}@@ -100,8 +116,12 @@ pub async fn delete_ai_conversation(State(state): State<Arc<WebState>>,Path(id): Path<String>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("ai_conversations.json");- dbx_core::ai::delete_conversation(&path, &id).map_err(AppError)?;+ state+ .app+ .storage+ .delete_ai_conversation(&id)+ .await+ .map_err(AppError)?;Ok(Json(()))}diff --git a/src-web/src/routes/connection.rs b/src-web/src/routes/connection.rsindex 72e2f87b7c..86ae4f6915 100644--- a/src-web/src/routes/connection.rs+++ b/src-web/src/routes/connection.rs@@ -2,9 +2,6 @@ use std::sync::Arc;use axum::extract::State;use axum::Json;-use dbx_core::connection_secrets::{- load_connections_from_file, save_connections_to_file, FileSecretStore,-};use dbx_core::models::connection::ConnectionConfig;use serde::Deserialize;@@ -105,19 +102,23 @@ pub async fn save_connections(State(state): State<Arc<WebState>>,Json(body): Json<SaveConnectionsRequest>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("connections.json");- let secret_path = state.data_dir.join("secrets.json");- let store = FileSecretStore::new(secret_path);- save_connections_to_file(&path, &body.configs, &store).map_err(AppError)?;+ state+ .app+ .storage+ .save_connections(&body.configs)+ .await+ .map_err(AppError)?;Ok(Json(()))}pub async fn load_connections(State(state): State<Arc<WebState>>,) -> Result<Json<Vec<ConnectionConfig>>, AppError> {- let path = state.data_dir.join("connections.json");- let secret_path = state.data_dir.join("secrets.json");- let store = FileSecretStore::new(secret_path);- let configs = load_connections_from_file(&path, &store).map_err(AppError)?;+ let configs = state+ .app+ .storage+ .load_connections()+ .await+ .map_err(AppError)?;Ok(Json(configs))}diff --git a/src-web/src/routes/history.rs b/src-web/src/routes/history.rsindex bad30c8654..82370edf5e 100644--- a/src-web/src/routes/history.rs+++ b/src-web/src/routes/history.rs@@ -2,7 +2,7 @@ use std::sync::Arc;use axum::extract::{Path, Query, State};use axum::Json;-use dbx_core::history::{self, HistoryEntry};+use dbx_core::history::HistoryEntry;use serde::Deserialize;use crate::error::AppError;@@ -24,8 +24,12 @@ pub async fn save_history(State(state): State<Arc<WebState>>,Json(body): Json<SaveHistoryRequest>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("query_history.json");- history::save_history_entry(&path, body.entry).map_err(AppError)?;+ state+ .app+ .storage+ .save_history_entry(&body.entry)+ .await+ .map_err(AppError)?;Ok(Json(()))}@@ -33,16 +37,19 @@ pub async fn load_history(State(state): State<Arc<WebState>>,Query(q): Query<HistoryQuery>,) -> Result<Json<Vec<HistoryEntry>>, AppError> {- let path = state.data_dir.join("query_history.json");let limit = q.limit.unwrap_or(100);let offset = q.offset.unwrap_or(0);- let entries = history::load_history_entries(&path, limit, offset).map_err(AppError)?;+ let entries = state+ .app+ .storage+ .load_history_entries(limit, offset)+ .await+ .map_err(AppError)?;Ok(Json(entries))}pub async fn clear_history(State(state): State<Arc<WebState>>) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("query_history.json");- history::clear_history_entries(&path).map_err(AppError)?;+ state.app.storage.clear_history().await.map_err(AppError)?;Ok(Json(()))}@@ -50,7 +57,11 @@ pub async fn delete_history_entry(State(state): State<Arc<WebState>>,Path(id): Path<String>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("query_history.json");- history::delete_history_entry_by_id(&path, &id).map_err(AppError)?;+ state+ .app+ .storage+ .delete_history_entry(&id)+ .await+ .map_err(AppError)?;Ok(Json(()))}diff --git a/src-web/src/routes/layout.rs b/src-web/src/routes/layout.rsindex 00f7aedcd9..76eb04aa46 100644--- a/src-web/src/routes/layout.rs+++ b/src-web/src/routes/layout.rs@@ -17,21 +17,23 @@ pub async fn save_sidebar_layout(State(state): State<Arc<WebState>>,Json(body): Json<SaveLayoutRequest>,) -> Result<Json<()>, AppError> {- let path = state.data_dir.join("sidebar_layout.json");- let json = serde_json::to_string_pretty(&body.layout).map_err(|e| AppError(e.to_string()))?;- std::fs::write(&path, json).map_err(|e| AppError(e.to_string()))?;+ state+ .app+ .storage+ .save_sidebar_layout(&body.layout)+ .await+ .map_err(AppError)?;Ok(Json(()))}pub async fn load_sidebar_layout(State(state): State<Arc<WebState>>,) -> Result<Json<serde_json::Value>, AppError> {- let path = state.data_dir.join("sidebar_layout.json");- if !path.exists() {- return Ok(Json(serde_json::json!(null)));- }- let json = std::fs::read_to_string(&path).map_err(|e| AppError(e.to_string()))?;- let layout: serde_json::Value =- serde_json::from_str(&json).map_err(|e| AppError(e.to_string()))?;- Ok(Json(layout))+ let layout = state+ .app+ .storage+ .load_sidebar_layout()+ .await+ .map_err(AppError)?;+ Ok(Json(layout.unwrap_or(serde_json::json!(null))))}