fix(cli): distinguish missing connections table from failed store open

This commit is contained in:
zipg authored and GitHub committed 2026-09-26 13:42:51 +08:00
1 parent 4ac59ddf3c
commit 9dc7e1982c
2 files changed
+75 -2

No files matched your search

+21 -2
View File
@@ -4,6 +4,7 @@ use dbx_core::{
models::connection::{ConnectionConfig, DatabaseType}, models::connection::{ConnectionConfig, DatabaseType},
production_safety::{is_production_database, targets_production_database}, production_safety::{is_production_database, targets_production_database},
sql_risk::{classify_sql_risk_for_database, SqlRisk}, sql_risk::{classify_sql_risk_for_database, SqlRisk},
storage::Storage,
types::{ColumnInfo, QueryMessage, QueryResult, TableInfo}, types::{ColumnInfo, QueryMessage, QueryResult, TableInfo},
}; };
use dbx_mcp::{ use dbx_mcp::{
@@ -889,12 +890,30 @@ async fn diagnostics() -> Diagnostics {
Ok(connections) => (true, connections, None), Ok(connections) => (true, connections, None),
Err(error) => (false, Vec::new(), Some(error)), Err(error) => (false, Vec::new(), Some(error)),
}; };
// Opening the store can fail for reasons that say nothing about the
// schema: a headless CLI cannot read a keychain-only encryption key, an
// unfinished data-security upgrade blocks writes, and so on. Probing the
// table directly keeps "table missing" apart from "connection loading
// failed"; when the probe itself cannot read the file, keep the previous
// load-based answer instead of inventing one.
let (connections_table_exists, connection_row_count) = if db_path_exists {
match Storage::open_unmigrated(&db_path).await {
Ok(storage) => match storage.stored_connection_count().await {
Ok(Some(count)) => (true, count as usize),
Ok(None) => (false, 0),
Err(_) => (load_connections_ok, connections.len()),
},
Err(_) => (load_connections_ok, connections.len()),
}
} else {
(false, 0)
};
Diagnostics { Diagnostics {
app_data_dir: app_data_dir.display().to_string(), app_data_dir: app_data_dir.display().to_string(),
db_path: db_path.display().to_string(), db_path: db_path.display().to_string(),
db_path_exists, db_path_exists,
connections_table_exists: load_connections_ok, connections_table_exists,
connection_row_count: connections.len(), connection_row_count,
load_connections_ok, load_connections_ok,
loaded_connection_count: connections.len(), loaded_connection_count: connections.len(),
load_connections_error: error, load_connections_error: error,
@@ -6189,6 +6189,32 @@ impl Storage {
.await .await
} }
/// Counts the stored `connections` rows without decrypting secrets or
/// running the data-security upgrade. Diagnostics use it to report the
/// table state truthfully even when the store cannot be fully opened (for
/// example a headless CLI that cannot read the OS keychain key), so a
/// failed open is never misreported as a missing table. `None` means the
/// opened schema has no `connections` table at all.
pub async fn stored_connection_count(&self) -> Result<Option<u64>, String> {
self.with_conn(|conn| {
let exists: bool = conn
.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'connections')",
[],
|row| row.get(0),
)
.map_err(|error| error.to_string())?;
if !exists {
return Ok(None);
}
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM connections", [], |row| row.get(0))
.map_err(|error| error.to_string())?;
Ok(Some(count.max(0) as u64))
})
.await
}
pub async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> { pub async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
let rows: Vec<(String, String)> = self let rows: Vec<(String, String)> = self
.with_conn(|conn| { .with_conn(|conn| {
@@ -13066,4 +13092,32 @@ mod tests {
let valid = serde_json::json!({"backupPaths": ["/tmp/dbx-secret-migration-a"]}); let valid = serde_json::json!({"backupPaths": ["/tmp/dbx-secret-migration-a"]});
assert_eq!(super::migration_backup_paths(&valid).unwrap(), vec!["/tmp/dbx-secret-migration-a"]); assert_eq!(super::migration_backup_paths(&valid).unwrap(), vec!["/tmp/dbx-secret-migration-a"]);
} }
#[tokio::test]
async fn stored_connection_count_reads_the_table_without_loading_secrets() {
let dir = tempfile::tempdir().unwrap();
let storage = crate::persistence::test_storage::open_unmigrated(&dir.path().join("dbx.db")).await.unwrap();
assert_eq!(storage.stored_connection_count().await.unwrap(), Some(0));
storage
.with_conn(|conn| {
conn.execute("INSERT INTO connections (id, config_json) VALUES ('a', '{}'), ('b', '{}')", [])
.map_err(|error| error.to_string())?;
Ok(())
})
.await
.unwrap();
assert_eq!(storage.stored_connection_count().await.unwrap(), Some(2));
// `None` is what lets `dbx doctor` tell a missing table apart from a
// table it could not load.
storage
.with_conn(|conn| {
conn.execute("DROP TABLE connections", []).map_err(|error| error.to_string())?;
Ok(())
})
.await
.unwrap();
assert_eq!(storage.stored_connection_count().await.unwrap(), None);
}
} }