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
fix(dameng): normalise dexp/dimp PARFILE paths and surface the real failure (#12872)
弈秋8a11c99410c9
diff --git a/apps/desktop/src/i18n/locales/damengDump.ts b/apps/desktop/src/i18n/locales/damengDump.tsindex b39ba8ed37..de38f4189d 100644--- a/apps/desktop/src/i18n/locales/damengDump.ts+++ b/apps/desktop/src/i18n/locales/damengDump.ts@@ -41,7 +41,7 @@ export const damengDumpEn = {toolNotFound: "Dameng client tools (dexp/dimp) were not found in the configured bin directory.",connectionRequired: "Native dexp/dimp dump is only available for Dameng connections.",passwordMissing: "The connection has no stored password; reconnect and enter the password first.",- useridInvalid: "The connection's username or password contains / or {'@'}, which the dexp/dimp USERID argument cannot encode; the task was not started.",+ useridInvalid: "The connection's username or password contains /, {'@'} or a space, which the dexp/dimp USERID argument cannot encode; the task was not started.",},};@@ -88,7 +88,7 @@ export const damengDumpZhCN = {toolNotFound: "在配置的 bin 目录中未找到达梦客户端工具(dexp/dimp)。",connectionRequired: "原生 dexp/dimp 导出仅支持达梦连接。",passwordMissing: "该连接没有保存密码,请先重新连接并输入密码。",- useridInvalid: "连接的用户名或密码包含 / 或 {'@'},无法编码进 dexp/dimp 的 USERID 参数;任务未启动。",+ useridInvalid: "连接的用户名或密码包含 /、{'@'} 或空格,无法编码进 dexp/dimp 的 USERID 参数;任务未启动。",},};@@ -135,7 +135,7 @@ export const damengDumpEs = {toolNotFound: "No se encontraron las herramientas del cliente de Dameng (dexp/dimp) en el directorio bin configurado.",connectionRequired: "La exportación nativa dexp/dimp solo está disponible para conexiones de Dameng.",passwordMissing: "La conexión no tiene contraseña guardada; reconéctese e introduzca la contraseña primero.",- useridInvalid: "El nombre de usuario o la contraseña de la conexión contiene / o {'@'}, que el argumento USERID de dexp/dimp no puede codificar; la tarea no se inició.",+ useridInvalid: "El nombre de usuario o la contraseña de la conexión contiene /, {'@'} o un espacio, que el argumento USERID de dexp/dimp no puede codificar; la tarea no se inició.",},};@@ -182,7 +182,7 @@ export const damengDumpIt = {toolNotFound: "Strumenti del client Dameng (dexp/dimp) non trovati nella directory bin configurata.",connectionRequired: "L'esportazione nativa dexp/dimp è disponibile solo per le connessioni Dameng.",passwordMissing: "La connessione non ha una password salvata; riconnettiti e inserisci prima la password.",- useridInvalid: "Il nome utente o la password della connessione contiene / o {'@'}, che l'argomento USERID di dexp/dimp non può codificare; l'attività non è stata avviata.",+ useridInvalid: "Il nome utente o la password della connessione contiene /, {'@'} o uno spazio, che l'argomento USERID di dexp/dimp non può codificare; l'attività non è stata avviata.",},};@@ -229,7 +229,7 @@ export const damengDumpJa = {toolNotFound: "設定された bin ディレクトリに Dameng クライアントツール(dexp/dimp)が見つかりません。",connectionRequired: "ネイティブ dexp/dimp エクスポートは Dameng 接続でのみ利用できます。",passwordMissing: "接続に保存されたパスワードがありません。先に再接続してパスワードを入力してください。",- useridInvalid: "接続のユーザー名またはパスワードに / または {'@'} が含まれており、dexp/dimp の USERID 引数としてエンコードできません。タスクは開始されませんでした。",+ useridInvalid: "接続のユーザー名またはパスワードに /、{'@'} またはスペースが含まれており、dexp/dimp の USERID 引数としてエンコードできません。タスクは開始されませんでした。",},};@@ -276,7 +276,7 @@ export const damengDumpKo = {toolNotFound: "구성된 bin 디렉터리에서 Dameng 클라이언트 도구(dexp/dimp)를 찾을 수 없습니다.",connectionRequired: "네이티브 dexp/dimp 내보내기는 Dameng 연결에서만 사용할 수 있습니다.",passwordMissing: "연결에 저장된 비밀번호가 없습니다. 먼저 다시 연결하여 비밀번호를 입력하세요.",- useridInvalid: "연결의 사용자 이름 또는 비밀번호에 / 또는 {'@'}가 포함되어 있어 dexp/dimp의 USERID 인수로 인코딩할 수 없습니다. 작업이 시작되지 않았습니다.",+ useridInvalid: "연결의 사용자 이름 또는 비밀번호에 /, {'@'} 또는 공백이 포함되어 있어 dexp/dimp의 USERID 인수로 인코딩할 수 없습니다. 작업이 시작되지 않았습니다.",},};@@ -323,7 +323,7 @@ export const damengDumpPtBR = {toolNotFound: "Ferramentas do cliente Dameng (dexp/dimp) não foram encontradas no diretório bin configurado.",connectionRequired: "A exportação nativa dexp/dimp está disponível apenas para conexões Dameng.",passwordMissing: "A conexão não tem senha salva; reconecte-se e insira a senha primeiro.",- useridInvalid: "O nome de usuário ou a senha da conexão contém / ou {'@'}, que o argumento USERID do dexp/dimp não consegue codificar; a tarefa não foi iniciada.",+ useridInvalid: "O nome de usuário ou a senha da conexão contém /, {'@'} ou um espaço, que o argumento USERID do dexp/dimp não consegue codificar; a tarefa não foi iniciada.",},};@@ -370,6 +370,6 @@ export const damengDumpZhTW = {toolNotFound: "在設定的 bin 目錄中未找到達夢用戶端工具(dexp/dimp)。",connectionRequired: "原生 dexp/dimp 匯出僅支援達夢連線。",passwordMissing: "該連線沒有儲存密碼,請先重新連線並輸入密碼。",- useridInvalid: "連線的使用者名稱或密碼包含 / 或 {'@'},無法編碼進 dexp/dimp 的 USERID 參數;任務未啟動。",+ useridInvalid: "連線的使用者名稱或密碼包含 /、{'@'} 或空格,無法編碼進 dexp/dimp 的 USERID 參數;任務未啟動。",},};diff --git a/crates/dbx-core/src/data/dameng_dump.rs b/crates/dbx-core/src/data/dameng_dump.rsindex 7416f1a491..fa6e069c9a 100644--- a/crates/dbx-core/src/data/dameng_dump.rs+++ b/crates/dbx-core/src/data/dameng_dump.rs@@ -20,8 +20,8 @@ use tokio::io::AsyncReadExt;pub use dbx_sql::dameng_dump::DamengDumpKind as DamengDumpKindReexport;use dbx_sql::dameng_dump::{- build_command, build_parfile_contents, parse_dump_log, userid_field_error, DamengDumpKind, DamengDumpOutcome,- DamengDumpRequest,+ build_command, build_parfile_contents, failure_message, parse_dump_log, userid_field_error, DamengDumpKind,+ DamengDumpOutcome, DamengDumpRequest,};use crate::connection::AppState;@@ -181,14 +181,17 @@ fn prepare_import_source(file_path: &Path) -> Result<(), String> {}/// Run the tool once and return the combined diagnostic text (log file-/// preferred, console capture as fallback).+/// preferred, console capture as fallback) plus the process exit status.+///+/// The exit status is the only signal left when the tool dies before writing its log —+/// the case the old code collapsed into "did not report success" (#12837).async fn run_tool_and_collect(argv: &[String],log_path: &Path,out_path: &Path,err_path: &Path,task_id: &str,-) -> Result<String, String> {+) -> Result<(String, Option<i32>), String> {if argv.is_empty() {return Err("Empty dexp/dimp command".to_string());}@@ -224,12 +227,17 @@ async fn run_tool_and_collect(if cancelled {return Err(EXPORT_CANCELLED_ERROR.to_string());}+ let exit_code = match child.try_wait() {+ Ok(Some(status)) => status.code(),+ Ok(None) => None,+ Err(error) => return Err(format!("Failed to read '{}' exit status: {error}", argv[0])),+ };// Prefer the tool's own log (the parse target); fall back to console// capture for early failures (missing lib, bad args) that never reach it.let log_text = tokio::fs::read_to_string(log_path).await.unwrap_or_default();if !log_text.trim().is_empty() {- return Ok(log_text);+ return Ok((log_text, exit_code));}let mut console = String::new();let mut out_file = tokio::fs::File::open(out_path).await.ok();@@ -247,7 +255,7 @@ async fn run_tool_and_collect(console.push_str(&err_text);}}- Ok(console)+ Ok((console, exit_code))}fn remove_if_exists(path: &Path) {@@ -308,13 +316,14 @@ pub async fn run_dameng_dump_task(return Err(error);}// A `/` or `@` in the user or password would be read as a USERID field- // separator by the tool and surface as a bogus host / connection error;- // reject it up front instead of launching.+ // separator by the tool, and a space would end the token early; both surface as a+ // bogus host / connection error, so reject them up front instead of launching.if let Some(field) = userid_field_error(&config.username, &config.password) {let error = tagged(DAMENG_USERID_INVALID_TAG,&format!(- "The connection's {field} contains '/' or '@', which the dexp/dimp USERID argument cannot encode; the task was not started."+ "The connection's {field} contains '/', '@' or a space, which the dexp/dimp USERID argument \+ cannot encode; the task was not started."),);emit(DamengDumpStatus::Error, false, false, None, Some(error.clone()));@@ -403,8 +412,8 @@ pub async fn run_dameng_dump_task(remove_if_exists(&out_path);remove_if_exists(&err_path);- let text = match run_result {- Ok(text) => text,+ let (text, exit_code) = match run_result {+ Ok(pair) => pair,Err(error) if error == EXPORT_CANCELLED_ERROR => {remove_if_exists(&log_path);if let Some(temp_path) = &export_temp_path {@@ -444,13 +453,11 @@ pub async fn run_dameng_dump_task(if let Some(temp_path) = &export_temp_path {remove_if_exists(temp_path);}- let error = outcome- .error- .clone()- .or_else(|| {- Some(text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("dexp/dimp failed").trim().to_string())- })- .unwrap_or_else(|| "dexp/dimp failed".to_string());+ // `parse_dump_log`'s generic fallback hides why the run stopped, so the log/console+ // tail and the exit status travel with the message. See #12837: on Windows the tool+ // rejected the quoted, back-slash PARFILE values before writing its log, leaving the+ // user with a sentence that named no parameter and no path.+ let error = failure_message(&outcome, exit_code, &text);emit(DamengDumpStatus::Error, false, outcome.warnings, outcome.elapsed_seconds.clone(), Some(error.clone()));Err(error)}@@ -574,7 +581,9 @@ mod tests {let mut argv = vec![tool.to_string_lossy().into_owned()];argv.extend(tool_args);- let text = run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "fake-task").await.unwrap();+ let (text, exit_code) =+ run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "fake-task").await.unwrap();+ assert_eq!(exit_code, Some(0), "a success run reports a clean exit");let outcome = parse_dump_log(&text, DamengDumpKind::Export);assert!(outcome.success, "should parse the fake success log: {outcome:?}");if expect_elapsed {@@ -610,10 +619,52 @@ mod tests {let mut argv = vec![tool.to_string_lossy().into_owned()];argv.extend(tool_args);- let text = run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "fake-fail-task").await.unwrap();+ let (text, exit_code) =+ run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "fake-fail-task").await.unwrap();+ assert_eq!(exit_code, Some(1), "the exit status is reported even without a log");let outcome = parse_dump_log(&text, DamengDumpKind::Export);assert!(!outcome.success);assert!(outcome.error.as_deref().unwrap_or_default().contains("DMException"), "got: {outcome:?}");let _ = std::fs::remove_dir_all(&dir);}++ /// The #12837 shape: the tool rejects its parameters and exits non-zero with an+ /// unrecognised-parameter line on stderr, writing no log at all. The exit status plus+ /// `failure_message` must carry the cause — a bare "did not report success" would not.+ #[tokio::test]+ async fn run_tool_and_collect_carries_exit_code_for_silent_failure() {+ let dir = std::env::temp_dir().join(format!("dbx-dameng-silent-fail-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let log_path = dir.join("never-written.log");+ let out_path = dir.join("run.out");+ let err_path = dir.join("run.err");++ #[cfg(windows)]+ let (tool, tool_args) = {+ let tool = dir.join("reject.bat");+ std::fs::write(&tool, "@echo off\r\necho unrecognized parameter TABLESPACE 1>&2\r\nexit /b 2\r\n").unwrap();+ (tool, vec![])+ };+ #[cfg(not(windows))]+ let (tool, tool_args) = {+ use std::os::unix::fs::PermissionsExt;+ let tool = dir.join("reject.sh");+ std::fs::write(&tool, "#!/bin/sh\necho 'unrecognized parameter TABLESPACE' >&2\nexit 2\n").unwrap();+ std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();+ (tool, vec![])+ };++ let mut argv = vec![tool.to_string_lossy().into_owned()];+ argv.extend(tool_args);+ let (text, exit_code) =+ run_tool_and_collect(&argv, &log_path, &out_path, &err_path, "silent-task").await.unwrap();+ assert_eq!(exit_code, Some(2));++ let outcome = parse_dump_log(&text, DamengDumpKind::Export);+ assert!(!outcome.success);+ let message = failure_message(&outcome, exit_code, &text);+ assert!(message.contains("exit code 2"), "got: {message}");+ assert!(message.contains("unrecognized parameter TABLESPACE"), "got: {message}");+ let _ = std::fs::remove_dir_all(&dir);+ }}diff --git a/crates/dbx-sql/src/dameng_dump.rs b/crates/dbx-sql/src/dameng_dump.rsindex 02fa197cfb..9aa6a2406c 100644--- a/crates/dbx-sql/src/dameng_dump.rs+++ b/crates/dbx-sql/src/dameng_dump.rs@@ -46,29 +46,65 @@ pub struct DamengDumpRequest {pub table_exists_action: Option<String>,}+/// A bounded trailing slice of a tool's output, for appending to a failure message.+///+/// The tool's own log is preferred when it exists, but a parameter error stops the run+/// before the LOG file is written; the console capture then carries the only copy of the+/// real reason. Either way the tail is what matters — dexp prints its cause last.+pub fn diagnostic_tail(text: &str, max_chars: usize) -> String {+ let trimmed = text.trim_end_matches(['\n', '\r']);+ if trimmed.len() <= max_chars {+ return trimmed.to_string();+ }+ let floor = trimmed.len() - max_chars;+ let start = floor + trimmed[floor..].find('\n').map_or(0, |i| i + 1);+ trimmed[start..].to_string()+}+/// The `USERID` token, always the first argument: `USERID=<user>/<password>@<host>:<port>`./// Password is NOT URL-escaped; Dameng accepts it verbatim. A `/` or `@` inside the user or-/// password would be parsed as a field separator (the tool parses up to the first `@`), so-/// callers must reject those up front via [`userid_field_error`] instead of launching.+/// password would be parsed as a field separator (the tool parses up to the first `@`), and a+/// space would end the token early, so callers must reject those up front via+/// [`userid_field_error`] instead of launching.pub fn userid_token(user: &str, password: &str, host: &str, port: u16) -> String {format!("USERID={user}/{password}@{host}:{port}")}/// Returns the field name whose value cannot be encoded in the `USERID` token-/// (`/` separates user/password, `@` starts the host part), or `None` if both-/// are safe to pass.+/// (`/` separates user/password, `@` starts the host part, a space ends the token),+/// or `None` if both are safe to pass.pub fn userid_field_error(user: &str, password: &str) -> Option<&'static str> {- [(user, "username"), (password, "password")]- .into_iter()- .find_map(|(field, name)| (field.contains('/') || field.contains('@')).then_some(name))+ [(user, "username"), (password, "password")].into_iter().find_map(|(field, name)| {+ (field.contains('/') || field.contains('@') || field.contains(char::is_whitespace)).then_some(name)+ })+}++/// Render a file/log path for a PARFILE line.+///+/// Dameng's PARFILE parser treats a value verbatim: its own documentation lists `"` and `\`+/// among the characters a FILE/LOG name may not contain, and the documented form is+/// `FILE=db_str.dmp` (no quotes, forward slashes). Emitting the raw Windows path therefore+/// breaks in two ways at once — the surrounding quotes are read as part of the file name, and+/// a Drive letter's `\` can be consumed as an escape. Both failures happen before the tool+/// writes its LOG file, so the caller only sees an empty log and cannot tell why.+///+/// Normalising to forward slashes removes the escape problem (both Windows and the tool accept+/// them), and quotes are kept only when a space makes the value ambiguous.+fn parfile_path_value(path: &str) -> String {+ let normalized = path.replace('\\', "/");+ if normalized.contains(' ') {+ format!("\"{normalized}\"")+ } else {+ normalized+ }}/// Contents of the PARFILE: the non-sensitive parameters, one `KEY=value` per line.-/// File/log paths are double-quoted so spaces and Windows backslashes survive.+/// File/log paths are normalised to forward slashes (see [`parfile_path_value`]).pub fn build_parfile_contents(req: &DamengDumpRequest) -> String {let mut lines: Vec<String> = Vec::new();- lines.push(format!("FILE=\"{}\"", req.file_path));- lines.push(format!("LOG=\"{}\"", req.log_path));+ lines.push(format!("FILE={}", parfile_path_value(&req.file_path)));+ lines.push(format!("LOG={}", parfile_path_value(&req.log_path)));if !req.schemas.is_empty() {lines.push(format!("SCHEMAS={}", req.schemas.join(",")));}@@ -105,6 +141,35 @@ pub fn build_command(req: &DamengDumpRequest, parfile_path: &str) -> Vec<String>]}+/// Build the message the user sees for a run that did not report success.+///+/// `parse_dump_log` can only classify the text it was handed. Two cases leave it without a+/// usable classification: the tool stops before writing its log file (log and console are+/// both empty or generic), or it writes a log whose tail carries no recognised marker. The+/// exit status and the raw output are the only evidence left, so both are folded in here —+/// a bare "did not report success" tells the user nothing about which parameter upset dexp.+pub fn failure_message(outcome: &DamengDumpOutcome, exit_code: Option<i32>, text: &str) -> String {+ let mut message = outcome.error.clone().unwrap_or_else(|| "dexp/dimp did not report success".to_string());++ if let Some(code) = exit_code {+ if code != 0 {+ message.push_str(&format!(" (exit code {code})"));+ }+ }++ let tail = diagnostic_tail(text, DIAGNOSTIC_TAIL_MAX_CHARS);+ if !tail.is_empty() && !message.contains(&tail) {+ message.push_str("\n\n dexp/dimp output:\n");+ message.push_str(&tail);+ }++ message+}++/// How much of the tool's output to attach to a failure message. dexp is chatty on success+/// and quiet on failure, so a small slice still carries the cause while keeping the UI sane.+const DIAGNOSTIC_TAIL_MAX_CHARS: usize = 4000;+#[derive(Debug, Clone, PartialEq, Eq)]pub struct DamengDumpOutcome {pub success: bool,@@ -195,7 +260,79 @@ mod tests {#[test]fn export_parfile_matches_real_invocation() {let par = build_parfile_contents(&req(DamengDumpKind::Export));- assert_eq!(par, "FILE=\"/tmp/dbx_dcss.dmp\"\nLOG=\"/tmp/dbx_dcss.log\"\nSCHEMAS=DCSS\nTABLESPACE=N\nDROP=N\n");+ assert_eq!(par, "FILE=/tmp/dbx_dcss.dmp\nLOG=/tmp/dbx_dcss.log\nSCHEMAS=DCSS\nTABLESPACE=N\nDROP=N\n");+ }++ #[test]+ fn export_parfile_normalises_windows_paths() {+ let mut r = req(DamengDumpKind::Export);+ r.file_path = r"C:\Users\dbx\dump.dcss.dmp".to_string();+ r.log_path = r"C:\Users\dbx\AppData\Local\Temp\dbx-dameng-dump\task.log".to_string();+ let par = build_parfile_contents(&r);+ // Backslashes become forward slashes and the quotes are dropped: `"` is on Dameng's+ // list of characters a FILE/LOG name may not contain (#12837).+ assert!(par.contains(r"FILE=C:/Users/dbx/dump.dcss.dmp"), "got: {par}");+ assert!(par.contains("LOG=C:/Users/dbx/AppData/Local/Temp/dbx-dameng-dump/task.log"), "got: {par}");+ assert!(!par.contains('"'), "no quotes: {par}");+ }++ #[test]+ fn export_parfile_quotes_only_when_a_space_needs_it() {+ let mut r = req(DamengDumpKind::Export);+ r.file_path = r"C:\Users\John Smith\dump.dmp".to_string();+ let par = build_parfile_contents(&r);+ assert!(par.contains(r#"FILE="C:/Users/John Smith/dump.dmp""#), "got: {par}");+ assert!(!par.contains('\\'), "no backslashes survive: {par}");+ }++ #[test]+ fn import_parfile_normalises_paths_too() {+ let mut r = req(DamengDumpKind::Import);+ r.file_path = r"D:\dumps\dcss.dmp".to_string();+ let par = build_parfile_contents(&r);+ assert!(par.contains("FILE=D:/dumps/dcss.dmp"), "got: {par}");+ }++ #[test]+ fn userid_field_error_rejects_whitespace() {+ assert_eq!(userid_field_error("SYSDBA", "Pass word01"), Some("password"));+ assert_eq!(userid_field_error("SYSDBA", "Dameng+123"), None);+ }++ #[test]+ fn diagnostic_tail_keeps_the_cause_and_stays_bounded() {+ // trailing newlines go, the whole text comes back when it fits+ assert_eq!(diagnostic_tail("a\nb\n", 10), "a\nb");+ assert_eq!(diagnostic_tail("a\nb", 3), "a\nb");+ // a zero budget asks for nothing+ assert_eq!(diagnostic_tail("a\nb", 0), "");+ let long = (0..100).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");+ let tail = diagnostic_tail(&long, 20);+ assert!(tail.len() <= 24, "bounded: {tail}");+ assert!(tail.ends_with("line 99"), "keeps the cause: {tail}");+ assert!(tail.starts_with("line "), "cuts on a line boundary: {tail}");+ }++ #[test]+ fn failure_message_carries_exit_code_and_raw_output() {+ // The #12837 shape: an empty log plus an unrecognised-parameter line on the console.+ let empty_parse = parse_dump_log("", DamengDumpKind::Export);+ assert!(!empty_parse.success);+ let message =+ failure_message(&empty_parse, Some(3), "dexp: unrecognized parameter TABLESPACE\nusage: dexp ...");+ assert!(message.contains("(exit code 3)"), "got: {message}");+ assert!(message.contains("unrecognized parameter TABLESPACE"), "got: {message}");+ assert!(message.contains("dexp/dimp output:"), "got: {message}");+ }++ #[test]+ fn failure_message_stays_quiet_on_success_parse() {+ let log = "dexp V8\n成功终止导出, 没有出现警告\n";+ let outcome = parse_dump_log(log, DamengDumpKind::Export);+ assert!(outcome.success);+ // Not called on the success path, but it must not fabricate output for a parsed log.+ let message = failure_message(&outcome, Some(0), log);+ assert!(!message.contains("exit code"), "got: {message}");}#[test]