Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(cli): 修复 headless 查询安全与 limit 下推

Illuminated20202f23df967580
diff --git a/crates/dbx-cli/src/commands.rs b/crates/dbx-cli/src/commands.rs
index f44b5a8f97..9756891f7c 100644
--- a/crates/dbx-cli/src/commands.rs
+++ b/crates/dbx-cli/src/commands.rs
@@ -1,4 +1,4 @@
-use dbx_core::cli::{fail, ok, CliEnvelope, CliErrorCode, CliSource};
+use dbx_core::cli::{fail, fail_safe, ok, CliEnvelope, CliErrorCode, CliSource};
const DEFAULT_RESULT_LIMIT: u32 = 50;
const MAX_RESULT_LIMIT: u32 = 1000;
@@ -188,12 +188,13 @@ fn redact_uri_credentials(value: &str) -> String {
async fn load_headless_connections(
) -> Result<Vec<dbx_core::models::connection::ConnectionConfig>, CliEnvelope<serde_json::Value>> {
- let state = open_state().await.map_err(|err| fail(CliSource::Headless, CliErrorCode::InternalError, err, false))?;
+ let state =
+ open_state().await.map_err(|err| fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false))?;
state
.storage
.load_connections()
.await
- .map_err(|err| fail(CliSource::Headless, CliErrorCode::InternalError, err, false))
+ .map_err(|err| fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false))
}
async fn find_connection(
@@ -231,11 +232,13 @@ async fn state_with_connection(
match config.db_type {
dbx_core::models::connection::DatabaseType::Sqlite => {
- let pool = dbx_core::db::sqlite::connect_path(&config.host).await?;
+ let path = dbx_core::connection::expand_tilde(&config.host);
+ let pool = dbx_core::db::sqlite::connect_path(&path).await?;
state.connections.lock().await.insert(config.id.clone(), dbx_core::connection::PoolKind::Sqlite(pool));
}
dbx_core::models::connection::DatabaseType::DuckDb => {
- let pool = dbx_core::db::duckdb_driver::connect_path(&config.host)?;
+ let path = dbx_core::connection::expand_tilde(&config.host);
+ let pool = dbx_core::db::duckdb_driver::connect_path(&path)?;
state.connections.lock().await.insert(config.id.clone(), dbx_core::connection::PoolKind::DuckDb(pool));
}
_ => {
@@ -311,12 +314,12 @@ async fn schema_snapshot(args: &[String]) -> CliEnvelope<serde_json::Value> {
};
let state = match state_with_connection(config.clone()).await {
Ok(state) => state,
- Err(err) => return fail(CliSource::Headless, CliErrorCode::InternalError, err, false),
+ Err(err) => return fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false),
};
match dbx_core::schema_snapshot::snapshot(&state, &config.id, option_value(args, "--db"), None).await {
Ok(snapshot) => ok(CliSource::Headless, serde_json::to_value(snapshot).unwrap()),
- Err(err) => fail(CliSource::Headless, CliErrorCode::InternalError, err, false),
+ Err(err) => fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false),
}
}
@@ -357,19 +360,21 @@ async fn safe_query(args: &[String]) -> CliEnvelope<serde_json::Value> {
}
let state = match state_with_connection(config.clone()).await {
Ok(state) => state,
- Err(err) => return fail(CliSource::Headless, CliErrorCode::InternalError, err, false),
+ Err(err) => return fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false),
};
let database = option_value(args, "--db").or(config.database.as_deref()).unwrap_or("");
- match dbx_core::query::execute_sql_statement(&state, &config.id, database, sql, None, None).await {
+ match dbx_core::query::execute_sql_statement_with_row_limit(&state, &config.id, database, sql, None, None, limit)
+ .await
+ {
Ok(result) => ok(
CliSource::Headless,
serde_json::json!({
"risk": risk,
- "result": limit_query_result(result, limit),
+ "result": result,
}),
),
- Err(err) => fail(CliSource::Headless, CliErrorCode::InternalError, err, false),
+ Err(err) => fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false),
}
}
@@ -377,14 +382,6 @@ fn blocked_query(code: CliErrorCode, risk: &dbx_core::sql_safety::RiskMetadata)
fail(CliSource::Headless, code, serde_json::to_string(risk).unwrap(), true)
}
-fn limit_query_result(mut result: dbx_core::db::QueryResult, limit: usize) -> dbx_core::db::QueryResult {
- if result.rows.len() > limit {
- result.rows.truncate(limit);
- result.truncated = true;
- }
- result
-}
-
async fn handoff(args: &[String]) -> CliEnvelope<serde_json::Value> {
if let Err(err) = reject_unexpected_positionals(args, "handoff", None) {
return err;
@@ -431,7 +428,7 @@ async fn handoff(args: &[String]) -> CliEnvelope<serde_json::Value> {
match queue_handoff(&item).await {
Ok(()) => ok(CliSource::Headless, serde_json::json!({ "id": item.id, "status": "queued" })),
- Err(err) => fail(CliSource::Headless, CliErrorCode::InternalError, err, false),
+ Err(err) => fail_safe(CliSource::Headless, CliErrorCode::InternalError, err, false),
}
}
@@ -595,6 +592,26 @@ mod tests {
pool.close().await;
}
+ async fn create_large_sqlite_fixture(path: &std::path::Path, row_count: usize) {
+ std::fs::File::create(path).unwrap();
+ let pool = dbx_core::db::sqlite::connect_path(&path.display().to_string()).await.unwrap();
+ dbx_core::db::sqlite::execute_query(
+ &pool,
+ "CREATE TABLE numbers (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
+ )
+ .await
+ .unwrap();
+ for id in 1..=row_count {
+ dbx_core::db::sqlite::execute_query(
+ &pool,
+ &format!("INSERT INTO numbers (id, value) VALUES ({id}, 'value-{id}')"),
+ )
+ .await
+ .unwrap();
+ }
+ pool.close().await;
+ }
+
fn success_data(env: CliEnvelope<serde_json::Value>) -> serde_json::Value {
match env {
CliEnvelope::Success { source, data, .. } => {
@@ -954,6 +971,130 @@ mod tests {
std::env::remove_var("DBX_APP_DATA_DIR");
}
+ #[tokio::test]
+ async fn safe_query_expands_tilde_for_sqlite_connection_path() {
+ let _guard = ENV_LOCK.lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let home = dir.path().join("home");
+ std::fs::create_dir_all(&home).unwrap();
+ let data_path = home.join("fixture.sqlite");
+ create_sqlite_fixture(&data_path).await;
+ let previous_home = std::env::var_os("HOME");
+ std::env::set_var("HOME", &home);
+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());
+ let mut config = embedded_fixture("sqlite-id", "local-sqlite", DatabaseType::Sqlite, &data_path);
+ config.host = "~/fixture.sqlite".to_string();
+ seed_connections(dir.path(), &[config]).await;
+
+ let data = success_data(
+ dispatch(vec![
+ "safe-query".into(),
+ "--conn".into(),
+ "local-sqlite".into(),
+ "--sql".into(),
+ "SELECT COUNT(*) FROM users".into(),
+ "--format".into(),
+ "json".into(),
+ ])
+ .await,
+ );
+
+ assert_eq!(data["result"]["rows"], serde_json::json!([[2]]));
+
+ std::env::remove_var("DBX_APP_DATA_DIR");
+ if let Some(previous_home) = previous_home {
+ std::env::set_var("HOME", previous_home);
+ } else {
+ std::env::remove_var("HOME");
+ }
+ }
+
+ #[tokio::test]
+ async fn safe_query_large_sqlite_result_set_respects_limit() {
+ let _guard = ENV_LOCK.lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let data_path = dir.path().join("large.sqlite");
+ create_large_sqlite_fixture(&data_path, 200).await;
+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());
+ seed_connections(
+ dir.path(),
+ &[embedded_fixture("sqlite-id", "local-sqlite", DatabaseType::Sqlite, &data_path)],
+ )
+ .await;
+
+ let data = success_data(
+ dispatch(vec![
+ "safe-query".into(),
+ "--conn".into(),
+ "sqlite-id".into(),
+ "--sql".into(),
+ "SELECT id, value FROM numbers ORDER BY id".into(),
+ "--limit".into(),
+ "7".into(),
+ "--format".into(),
+ "json".into(),
+ ])
+ .await,
+ );
+
+ let rows = data["result"]["rows"].as_array().expect("rows should be an array");
+ assert!(rows.len() <= 7, "safe-query returned {} rows for limit 7", rows.len());
+ assert_eq!(rows.len(), 7);
+ assert_eq!(data["result"]["truncated"], true);
+
+ std::env::remove_var("DBX_APP_DATA_DIR");
+ }
+
+ #[tokio::test]
+ async fn schema_snapshot_and_safe_query_sanitize_internal_error_envelopes() {
+ let _guard = ENV_LOCK.lock().unwrap();
+ let dir = tempfile::tempdir().unwrap();
+ let private_path = dir.path().join("private").join("missing.sqlite");
+ std::env::set_var("DBX_APP_DATA_DIR", dir.path());
+ seed_connections(
+ dir.path(),
+ &[embedded_fixture("sqlite-id", "local-sqlite", DatabaseType::Sqlite, &private_path)],
+ )
+ .await;
+
+ let cases = [
+ dispatch(vec![
+ "schema".into(),
+ "snapshot".into(),
+ "--conn".into(),
+ "sqlite-id".into(),
+ "--format".into(),
+ "json".into(),
+ ])
+ .await,
+ dispatch(vec![
+ "safe-query".into(),
+ "--conn".into(),
+ "sqlite-id".into(),
+ "--sql".into(),
+ "SELECT 1".into(),
+ "--format".into(),
+ "json".into(),
+ ])
+ .await,
+ ];
+
+ for env in cases {
+ match env {
+ CliEnvelope::Failure { error, .. } => {
+ let message = error.message;
+ assert!(!message.contains(dir.path().to_str().unwrap()));
+ assert!(!message.contains("missing.sqlite"));
+ assert!(!message.contains("Database file does not exist"));
+ assert!(!message.contains("SQLite connection failed"));
+ }
+ CliEnvelope::Success { .. } => panic!("expected sanitized failure envelope"),
+ }
+ }
+
+ std::env::remove_var("DBX_APP_DATA_DIR");
+ }
+
#[tokio::test]
async fn safe_query_blocks_non_read_sql_with_structured_risk_errors() {
let _guard = ENV_LOCK.lock().unwrap();
diff --git a/crates/dbx-core/src/cli.rs b/crates/dbx-core/src/cli.rs
index dec7434300..6296e925a7 100644
--- a/crates/dbx-core/src/cli.rs
+++ b/crates/dbx-core/src/cli.rs
@@ -116,8 +116,12 @@ where
let source = source.ok_or_else(|| de::Error::missing_field("source"))?;
match (ok, has_data, has_error) {
- (true, true, false) => Ok(CliEnvelope::Success { ok, source, data: data.expect("data presence was checked") }),
- (false, false, true) => Ok(CliEnvelope::Failure { ok, source, error: error.expect("error presence was checked") }),
+ (true, true, false) => {
+ Ok(CliEnvelope::Success { ok, source, data: data.expect("data presence was checked") })
+ }
+ (false, false, true) => {
+ Ok(CliEnvelope::Failure { ok, source, error: error.expect("error presence was checked") })
+ }
(true, _, _) => Err(de::Error::custom("ok=true requires data without error")),
(false, _, _) => Err(de::Error::custom("ok=false requires error without data")),
}
@@ -172,6 +176,31 @@ pub fn fail<T>(source: CliSource, code: CliErrorCode, message: impl Into<String>
CliEnvelope::Failure { ok: false, source, error: CliError { code, message: message.into(), recoverable } }
}
+pub fn fail_safe<T>(
+ source: CliSource,
+ fallback_code: CliErrorCode,
+ message: impl AsRef<str>,
+ recoverable: bool,
+) -> CliEnvelope<T> {
+ let (code, message) = map_safe_error(fallback_code, message.as_ref());
+ fail(source, code, message, recoverable)
+}
+
+pub fn map_safe_error(fallback_code: CliErrorCode, message: &str) -> (CliErrorCode, String) {
+ let lower = message.to_ascii_lowercase();
+ if lower.contains("timed out") || lower.contains("timeout") {
+ return (CliErrorCode::Timeout, "Operation timed out.".to_string());
+ }
+ if lower.contains("connection config not found") || lower == "connection not found" {
+ return (CliErrorCode::ConnectionNotFound, "Connection not found.".to_string());
+ }
+ if lower.contains("unsupported database") || lower.contains("unsupported database type") {
+ return (CliErrorCode::UnsupportedDatabaseType, "Unsupported database type.".to_string());
+ }
+
+ (fallback_code, "Operation failed. See DBX logs for details.".to_string())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -279,4 +308,38 @@ mod tests {
assert!(err.to_string().contains("ok=true requires data without error"));
}
+
+ #[test]
+ fn maps_timeout_errors_without_leaking_internal_details() {
+ let (code, message) = map_safe_error(
+ CliErrorCode::InternalError,
+ "Query timed out after 30 seconds while reading /Users/alice/private.sqlite",
+ );
+
+ assert_eq!(code, CliErrorCode::Timeout);
+ assert_eq!(message, "Operation timed out.");
+ assert!(!message.contains("/Users/alice"));
+ }
+
+ #[test]
+ fn sanitizes_paths_uri_credentials_and_driver_details() {
+ let (code, message) = map_safe_error(
+ CliErrorCode::InternalError,
+ "SQLite connection failed: Database file does not exist: /Users/alice/private.sqlite; url=mysql://root:secret@localhost/db",
+ );
+
+ assert_eq!(code, CliErrorCode::InternalError);
+ assert_eq!(message, "Operation failed. See DBX logs for details.");
+ assert!(!message.contains("/Users/alice"));
+ assert!(!message.contains("root:secret"));
+ assert!(!message.contains("SQLite connection failed"));
+ }
+
+ #[test]
+ fn maps_connection_not_found_to_public_error_code() {
+ let (code, message) = map_safe_error(CliErrorCode::InternalError, "Connection config not found");
+
+ assert_eq!(code, CliErrorCode::ConnectionNotFound);
+ assert_eq!(message, "Connection not found.");
+ }
}
diff --git a/crates/dbx-core/src/db/sqlite.rs b/crates/dbx-core/src/db/sqlite.rs
index a5b9ef618a..f2d668820c 100644
--- a/crates/dbx-core/src/db/sqlite.rs
+++ b/crates/dbx-core/src/db/sqlite.rs
@@ -162,7 +162,16 @@ pub async fn list_triggers(pool: &SqlitePool, _schema: &str, table: &str) -> Res
}
pub async fn execute_query(pool: &SqlitePool, sql: &str) -> Result<QueryResult, String> {
+ execute_query_with_row_limit(pool, sql, crate::query::MAX_ROWS).await
+}
+
+pub async fn execute_query_with_row_limit(
+ pool: &SqlitePool,
+ sql: &str,
+ row_limit: usize,
+) -> Result<QueryResult, String> {
let start = Instant::now();
+ let row_limit = row_limit.max(1);
if starts_with_executable_sql_keyword(sql, &["SELECT", "PRAGMA", "EXPLAIN", "WITH"]) {
let desc = pool.describe(sql).await.map_err(|e| e.to_string())?;
@@ -191,14 +200,14 @@ pub async fn execute_query(pool: &SqlitePool, sql: &str) -> Result<QueryResult,
})
.collect(),
);
- if result_rows.len() > crate::query::MAX_ROWS {
+ if result_rows.len() > row_limit {
break;
}
}
- let truncated = result_rows.len() > crate::query::MAX_ROWS;
+ let truncated = result_rows.len() > row_limit;
if truncated {
- result_rows.truncate(crate::query::MAX_ROWS);
+ result_rows.truncate(row_limit);
}
Ok(QueryResult {
diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rs
index 56f9c9a289..df0807c419 100644
--- a/crates/dbx-core/src/query.rs
+++ b/crates/dbx-core/src/query.rs
@@ -12,7 +12,16 @@ pub const MAX_ROWS: usize = 10000;
pub const QUERY_CANCELED: &str = "Query canceled";
pub fn duckdb_execute(con: &duckdb::Connection, sql: &str) -> Result<db::QueryResult, String> {
+ duckdb_execute_with_row_limit(con, sql, MAX_ROWS)
+}
+
+pub fn duckdb_execute_with_row_limit(
+ con: &duckdb::Connection,
+ sql: &str,
+ row_limit: usize,
+) -> Result<db::QueryResult, String> {
let start = std::time::Instant::now();
+ let row_limit = row_limit.max(1);
if starts_with_executable_sql_keyword(sql, &["SELECT", "SHOW", "DESCRIBE", "EXPLAIN", "WITH", "PRAGMA"]) {
let mut stmt = con.prepare(sql).map_err(|e| e.to_string())?;
@@ -25,9 +34,6 @@ pub fn duckdb_execute(con: &duckdb::Connection, sql: &str) -> Result<db::QueryRe
let mut result_rows = Vec::new();
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
- if result_rows.len() >= MAX_ROWS {
- break;
- }
let vals: Vec<serde_json::Value> = (0..col_count)
.map(|i| {
row.get::<_, String>(i)
@@ -45,9 +51,15 @@ pub fn duckdb_execute(con: &duckdb::Connection, sql: &str) -> Result<db::QueryRe
})
.collect();
result_rows.push(vals);
+ if result_rows.len() > row_limit {
+ break;
+ }
}
- let truncated = result_rows.len() >= MAX_ROWS;
+ let truncated = result_rows.len() > row_limit;
+ if truncated {
+ result_rows.truncate(row_limit);
+ }
Ok(db::QueryResult {
columns,
rows: result_rows,
@@ -67,9 +79,14 @@ pub fn duckdb_execute(con: &duckdb::Connection, sql: &str) -> Result<db::QueryRe
}
}
-pub fn truncate_result(mut result: db::QueryResult) -> db::QueryResult {
- if result.rows.len() > MAX_ROWS {
- result.rows.truncate(MAX_ROWS);
+pub fn truncate_result(result: db::QueryResult) -> db::QueryResult {
+ truncate_result_with_row_limit(result, MAX_ROWS)
+}
+
+pub fn truncate_result_with_row_limit(mut result: db::QueryResult, row_limit: usize) -> db::QueryResult {
+ let row_limit = row_limit.max(1);
+ if result.rows.len() > row_limit {
+ result.rows.truncate(row_limit);
result.truncated = true;
}
result
@@ -142,6 +159,18 @@ pub async fn do_execute(
schema: Option<&str>,
cancel_token: Option<CancellationToken>,
) -> Result<db::QueryResult, String> {
+ do_execute_with_row_limit(state, pool_key, sql, schema, cancel_token, MAX_ROWS).await
+}
+
+pub async fn do_execute_with_row_limit(
+ state: &AppState,
+ pool_key: &str,
+ sql: &str,
+ schema: Option<&str>,
+ cancel_token: Option<CancellationToken>,
+ row_limit: usize,
+) -> Result<db::QueryResult, String> {
+ let row_limit = row_limit.max(1);
let connections = state.connections.read().await;
let pool = connections.get(pool_key).ok_or("Connection not found")?;
@@ -153,7 +182,7 @@ pub async fn do_execute(
wait_for_query(cancel_token, async move {
let task = tokio::task::spawn_blocking(move || {
let con = con.lock().map_err(|e| e.to_string())?;
- duckdb_execute(&con, &sql)
+ duckdb_execute_with_row_limit(&con, &sql, row_limit)
});
task.await.map_err(|e| e.to_string())?
})
@@ -178,7 +207,7 @@ pub async fn do_execute(
PoolKind::Sqlite(p) => {
let p = p.clone();
drop(connections);
- wait_for_query(cancel_token, db::sqlite::execute_query(&p, sql)).await
+ wait_for_query(cancel_token, db::sqlite::execute_query_with_row_limit(&p, sql, row_limit)).await
}
PoolKind::ClickHouse(client) => {
let client = client.clone();
@@ -186,7 +215,7 @@ pub async fn do_execute(
drop(connections);
wait_for_query(cancel_token, db::clickhouse_driver::execute_query(&client, &database, sql))
.await
- .map(truncate_result)
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
PoolKind::SqlServer(client) => {
let client = client.clone();
@@ -199,7 +228,9 @@ pub async fn do_execute(
},
None => client.lock().await,
};
- wait_for_query(cancel_token, db::sqlserver::execute_query(&mut client, sql)).await.map(truncate_result)
+ wait_for_query(cancel_token, db::sqlserver::execute_query(&mut client, sql))
+ .await
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
PoolKind::Oracle(pool) => {
let client = pool.client();
@@ -218,9 +249,11 @@ pub async fn do_execute(
if let Some(schema) = schema {
wait_for_query(cancel_token, db::oracle_driver::execute_query_with_schema(&*client, &schema, sql))
.await
- .map(truncate_result)
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
} else {
- wait_for_query(cancel_token, db::oracle_driver::execute_query(&*client, sql)).await.map(truncate_result)
+ wait_for_query(cancel_token, db::oracle_driver::execute_query(&*client, sql))
+ .await
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
}
PoolKind::Elasticsearch(client) => {
@@ -229,7 +262,7 @@ pub async fn do_execute(
drop(connections);
wait_for_query(cancel_token, db::elasticsearch_driver::execute_rest_query(&client, &sql))
.await
- .map(truncate_result)
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
PoolKind::Redis(_) => Err("Use Redis-specific commands".to_string()),
PoolKind::MongoDb(_) => Err("Use MongoDB-specific commands".to_string()),
@@ -250,7 +283,7 @@ pub async fn do_execute(
task.await.map_err(|e| e.to_string())?
})
.await
- .map(truncate_result)
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
PoolKind::Gaussdb(client) => {
let client = client.clone();
@@ -261,7 +294,7 @@ pub async fn do_execute(
db::gaussdb_driver::execute_query(&mut client, &sql).await
})
.await
- .map(truncate_result)
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
PoolKind::ExternalTabular(ext_pool) => {
if !starts_with_executable_sql_keyword(sql, &["SELECT", "WITH", "SHOW", "DESCRIBE", "EXPLAIN", "PRAGMA"]) {
@@ -273,7 +306,7 @@ pub async fn do_execute(
wait_for_query(cancel_token, async move {
let task = tokio::task::spawn_blocking(move || {
let con = con.lock().map_err(|e| e.to_string())?;
- duckdb_execute(&con, &sql)
+ duckdb_execute_with_row_limit(&con, &sql, row_limit)
});
task.await.map_err(|e| e.to_string())?
})
@@ -294,7 +327,7 @@ pub async fn do_execute(
session.invoke::<db::QueryResult>("executeQuery", params).await
})
.await
- .map(truncate_result)
+ .map(|result| truncate_result_with_row_limit(result, row_limit))
}
}
}
@@ -307,6 +340,19 @@ pub async fn execute_sql_statement(
schema: Option<&str>,
cancel_token: Option<CancellationToken>,
) -> Result<db::QueryResult, String> {
+ execute_sql_statement_with_row_limit(state, connection_id, database, sql, schema, cancel_token, MAX_ROWS).await
+}
+
+pub async fn execute_sql_statement_with_row_limit(
+ state: &AppState,
+ connection_id: &str,
+ database: &str,
+ sql: &str,
+ schema: Option<&str>,
+ cancel_token: Option<CancellationToken>,
+ row_limit: usize,
+) -> Result<db::QueryResult, String> {
+ let row_limit = row_limit.max(1);
let pool_key = if database.is_empty() {
connection_id.to_string()
} else {
@@ -317,13 +363,13 @@ pub async fn execute_sql_statement(
return Err(canceled_error());
}
- let result = do_execute(state, &pool_key, sql, schema, cancel_token.clone()).await;
+ let result = do_execute_with_row_limit(state, &pool_key, sql, schema, cancel_token.clone(), row_limit).await;
match &result {
Err(e) if is_connection_error(e) && !is_canceled(&cancel_token) => {
let db_opt = if database.is_empty() { None } else { Some(database) };
let new_key = state.reconnect_pool(connection_id, db_opt).await?;
- do_execute(state, &new_key, sql, schema, cancel_token).await
+ do_execute_with_row_limit(state, &new_key, sql, schema, cancel_token, row_limit).await
}
_ => result,
}
@@ -746,6 +792,9 @@ async fn exec_tx_none_inner(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::connection::AppState;
+ use crate::models::connection::{ConnectionConfig, DatabaseType};
+ use crate::storage::Storage;
#[tokio::test]
async fn wait_for_query_returns_cancelled_when_token_is_cancelled() {
@@ -816,4 +865,87 @@ mod tests {
assert!(!is_connection_error("syntax error at position 5"));
assert!(!is_connection_error("os error 13"));
}
+
+ fn sqlite_config(path: &std::path::Path) -> ConnectionConfig {
+ ConnectionConfig {
+ id: "sqlite-id".to_string(),
+ name: "local-sqlite".to_string(),
+ db_type: DatabaseType::Sqlite,
+ driver_profile: None,
+ driver_label: None,
+ url_params: None,
+ host: path.display().to_string(),
+ port: 0,
+ username: String::new(),
+ password: String::new(),
+ database: None,
+ color: None,
+ ssh_enabled: false,
+ ssh_host: String::new(),
+ ssh_port: 22,
+ ssh_user: String::new(),
+ ssh_password: String::new(),
+ ssh_key_path: String::new(),
+ ssh_key_passphrase: String::new(),
+ ssh_expose_lan: false,
+ ssh_connect_timeout_secs: crate::models::connection::default_ssh_connect_timeout_secs(),
+ proxy_enabled: false,
+ proxy_type: crate::models::connection::ProxyType::Socks5,
+ proxy_host: String::new(),
+ proxy_port: 1080,
+ proxy_username: String::new(),
+ proxy_password: String::new(),
+ ssl: false,
+ sysdba: false,
+ connection_string: None,
+ external_config: None,
+ jdbc_driver_class: None,
+ jdbc_driver_paths: Vec::new(),
+ }
+ }
+
+ async fn sqlite_state_with_rows(row_count: usize) -> (AppState, std::path::PathBuf, std::path::PathBuf) {
+ let unique = uuid::Uuid::new_v4();
+ let data_path = std::env::temp_dir().join(format!("dbx-query-data-{unique}.sqlite"));
+ let storage_path = std::env::temp_dir().join(format!("dbx-query-storage-{unique}.sqlite"));
+ std::fs::File::create(&data_path).unwrap();
+ let pool = db::sqlite::connect_path(&data_path.display().to_string()).await.unwrap();
+ db::sqlite::execute_query(&pool, "CREATE TABLE numbers (id INTEGER PRIMARY KEY)").await.unwrap();
+ for id in 1..=row_count {
+ sqlx::query("INSERT INTO numbers (id) VALUES (?)").bind(id as i64).execute(&pool).await.unwrap();
+ }
+ pool.close().await;
+
+ let storage = Storage::open(&storage_path).await.unwrap();
+ let state = AppState::new(storage);
+ let config = sqlite_config(&data_path);
+ state.configs.write().await.insert(config.id.clone(), config);
+ let pool = db::sqlite::connect_path(&data_path.display().to_string()).await.unwrap();
+ state.connections.write().await.insert("sqlite-id".to_string(), PoolKind::Sqlite(pool));
+ (state, data_path, storage_path)
+ }
+
+ #[tokio::test]
+ async fn execute_sql_statement_with_row_limit_caps_sqlite_rows() {
+ let (state, data_path, storage_path) = sqlite_state_with_rows(200).await;
+
+ let result = execute_sql_statement_with_row_limit(
+ &state,
+ "sqlite-id",
+ "",
+ "SELECT id FROM numbers ORDER BY id",
+ None,
+ None,
+ 7,
+ )
+ .await
+ .unwrap();
+
+ assert!(result.rows.len() <= 7);
+ assert_eq!(result.rows.len(), 7);
+ assert!(result.truncated);
+
+ let _ = std::fs::remove_file(data_path);
+ let _ = std::fs::remove_file(storage_path);
+ }
}