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(xugu): recover data transfer after agent timeout (#12832)

Elias24e1926b676c
diff --git a/agents/drivers/xugu/main.go b/agents/drivers/xugu/main.go
index b1dac4ce8b..a5cacfc7b3 100644
--- a/agents/drivers/xugu/main.go
+++ b/agents/drivers/xugu/main.go
@@ -4794,11 +4794,21 @@ func renderXuguTableDDL(schema, table string, columns []columnInfo, metadata xug
// any FK whose parent is not yet visible) during CREATE, matching DBeaver's
// xugu-metadata exporter which always emits ALTER for F/PK/CHECK extras.
var foreignKeys []xuguConstraintInfo
+ var deferredPrimaryKeys []xuguConstraintInfo
+ deferLargeObjectPrimaryKeys := metadata.CopyNum > 0 && xuguTableHasLargeObjectColumn(columns)
for _, constraint := range constraints {
if strings.EqualFold(strings.TrimSpace(constraint.Type), "F") {
foreignKeys = append(foreignKeys, constraint)
continue
}
+ // On XuguDB, a CREATE TABLE combining a LOB column, an inline primary
+ // key, and explicit COPY NUMBER can remain blocked. Emit the same named
+ // key immediately after CREATE TABLE so the transfer does not lose its
+ // constraint semantics while avoiding that inline path.
+ if deferLargeObjectPrimaryKeys && strings.EqualFold(strings.TrimSpace(constraint.Type), "P") {
+ deferredPrimaryKeys = append(deferredPrimaryKeys, constraint)
+ continue
+ }
// Xugu exposes the implicit unique key that it creates for every
// IDENTITY column through ALL_CONSTRAINTS. Re-emitting it as an
// explicit UNIQUE clause makes CREATE TABLE fail with E5170 because
@@ -4832,6 +4842,12 @@ func renderXuguTableDDL(schema, table string, columns []columnInfo, metadata xug
builder.WriteString("\nCOMMENT ")
builder.WriteString(quoteStringLiteral(strings.TrimSpace(metadata.Comment)))
}
+ for _, constraint := range deferredPrimaryKeys {
+ if item := renderXuguConstraintAlterDDL(schema, table, constraint); item != "" {
+ builder.WriteString(";\n\n")
+ builder.WriteString(item)
+ }
+ }
for _, constraint := range foreignKeys {
if item := renderXuguForeignKeyAlterDDL(schema, table, constraint); item != "" {
builder.WriteString(";\n\n")
@@ -4854,6 +4870,20 @@ func renderXuguTableDDL(schema, table string, columns []columnInfo, metadata xug
return terminateDDLScript(builder.String())
}
+func xuguTableHasLargeObjectColumn(columns []columnInfo) bool {
+ for _, column := range columns {
+ dataType := strings.ToUpper(strings.TrimSpace(column.DataType))
+ if separator := strings.IndexAny(dataType, " (["); separator >= 0 {
+ dataType = dataType[:separator]
+ }
+ switch dataType {
+ case "BLOB", "CLOB", "NCLOB", "JSON", "XML":
+ return true
+ }
+ }
+ return false
+}
+
func shouldSkipXuguIdentityUniqueConstraint(constraint xuguConstraintInfo, identities map[string]xuguIdentityInfo) bool {
if !strings.EqualFold(strings.TrimSpace(constraint.Type), "U") || len(identities) == 0 {
return false
@@ -4890,6 +4920,14 @@ func renderXuguConstraintDDL(constraint xuguConstraintInfo) string {
}
}
+func renderXuguConstraintAlterDDL(schema, table string, constraint xuguConstraintInfo) string {
+ item := renderXuguConstraintDDL(constraint)
+ if item == "" {
+ return ""
+ }
+ return "ALTER TABLE " + quoteIdentifier(schema) + "." + quoteIdentifier(table) + " ADD " + item
+}
+
// renderXuguForeignKeyAlterDDL emits FK constraints after CREATE TABLE. Self-
// referencing trees (e.g. SHOP_CATEGORIES.PARENT_ID -> CATEGORY_ID) fail when
// declared inline because the table does not exist yet during CREATE validation.
diff --git a/agents/drivers/xugu/main_test.go b/agents/drivers/xugu/main_test.go
index 9dd2e95a81..e181fb4bc8 100644
--- a/agents/drivers/xugu/main_test.go
+++ b/agents/drivers/xugu/main_test.go
@@ -1927,6 +1927,65 @@ func TestRenderXuguTableDDLPreservesProgrammableTableMetadata(t *testing.T) {
}
}
+func TestRenderXuguTableDDLDefersPrimaryKeyForCopyNumberLobTable(t *testing.T) {
+ ddl := renderXuguTableDDL(
+ "APP", "LOB_TABLE",
+ []columnInfo{
+ {Name: "ID", DataType: "INTEGER", IsNullable: false},
+ {Name: "BLOB_C", DataType: "BLOB", IsNullable: true},
+ {Name: "CLOB_C", DataType: "CLOB", IsNullable: true},
+ {Name: "JSON_C", DataType: "JSON", IsNullable: true},
+ {Name: "XML_C", DataType: "XML", IsNullable: true},
+ },
+ xuguTableMetadata{CopyNum: 3},
+ nil,
+ []xuguConstraintInfo{{Name: "PK_LOB_TABLE", Type: "P", Definition: `"ID"`, Enabled: true}},
+ nil, nil,
+ )
+
+ if strings.Contains(strings.Split(ddl, "ALTER TABLE")[0], `CONSTRAINT "PK_LOB_TABLE" PRIMARY KEY`) {
+ t.Fatalf("primary key must not be inline for a LOB table with explicit COPY NUMBER:\n%s", ddl)
+ }
+ if !strings.Contains(ddl, "COPY NUMBER 3;\n\nALTER TABLE \"APP\".\"LOB_TABLE\" ADD CONSTRAINT \"PK_LOB_TABLE\" PRIMARY KEY (\"ID\")") {
+ t.Fatalf("the original named primary key must follow CREATE TABLE:\n%s", ddl)
+ }
+ if !strings.HasSuffix(strings.TrimSpace(ddl), ";") {
+ t.Fatalf("standalone table DDL must end with a statement terminator:\n%s", ddl)
+ }
+}
+
+func TestRenderXuguTableDDLLeavesOtherPrimaryKeysInline(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ metadata xuguTableMetadata
+ columns []columnInfo
+ }{
+ {
+ name: "copy number without a large-object column",
+ metadata: xuguTableMetadata{CopyNum: 3},
+ columns: []columnInfo{{Name: "ID", DataType: "INTEGER"}},
+ },
+ {
+ name: "large-object column without explicit copy number",
+ metadata: xuguTableMetadata{},
+ columns: []columnInfo{{Name: "ID", DataType: "INTEGER"}, {Name: "BODY", DataType: "CLOB"}},
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ ddl := renderXuguTableDDL(
+ "APP", "T", test.columns, test.metadata, nil,
+ []xuguConstraintInfo{{Name: "PK_T", Type: "P", Definition: `"ID"`, Enabled: true}}, nil, nil,
+ )
+ if !strings.Contains(ddl, `CONSTRAINT "PK_T" PRIMARY KEY ("ID")`) {
+ t.Fatalf("primary key must remain inline outside the verified Xugu case:\n%s", ddl)
+ }
+ if strings.Contains(ddl, `ALTER TABLE "APP"."T" ADD CONSTRAINT "PK_T" PRIMARY KEY`) {
+ t.Fatalf("primary key must not be deferred outside the verified Xugu case:\n%s", ddl)
+ }
+ })
+ }
+}
+
func TestRenderXuguTableDDLSkipsImplicitIdentityUniqueConstraint(t *testing.T) {
ddl := renderXuguTableDDL(
"AppSchema", "tbIdentityAndDefaults",
diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rs
index eef99fd477..d2947c7730 100644
--- a/crates/dbx-core/src/data/transfer.rs
+++ b/crates/dbx-core/src/data/transfer.rs
@@ -8557,6 +8557,11 @@ fn should_prepare_fresh_agent_transfer_session(db_type: Option<DatabaseType>, er
if !db_type.is_some_and(|db_type| crate::database_capabilities::is_agent_type(&db_type)) {
return false;
}
+ let xugu_local_timeout = db_type == Some(DatabaseType::Xugu)
+ && error.trim_start().to_ascii_lowercase().starts_with("agent rpc call timed out ");
+ if xugu_local_timeout {
+ return true;
+ }
matches!(
crate::db::agent_driver::try_agent_error_from_legacy(error),
Some(crate::db::agent_driver::AgentCallError::Structured { context, .. })
@@ -8565,6 +8570,10 @@ fn should_prepare_fresh_agent_transfer_session(db_type: Option<DatabaseType>, er
)
}
+fn should_reconnect_missing_xugu_transfer_metadata_pool(db_type: Option<DatabaseType>, pool_missing: bool) -> bool {
+ pool_missing && db_type == Some(DatabaseType::Xugu)
+}
+
/// Whether a discarded transfer pool has to be replaced before the next statement runs.
///
/// Every error that reaches the `Discard` arm tears the pool down: the failed statement
@@ -8953,13 +8962,24 @@ fn effective_transfer_database_type(config: &ConnectionConfig) -> DatabaseType {
pub async fn get_columns_for_transfer(
state: &AppState,
pool_key: &str,
- _connection_id: &str,
+ connection_id: &str,
database: &str,
schema: &str,
table: &str,
catalog: Option<&str>,
) -> Result<Vec<db::ColumnInfo>, String> {
- let pool_handle = state.pool_handle(pool_key).await;
+ let mut pool_handle = state.pool_handle(pool_key).await;
+ if pool_handle.is_none() {
+ let db_type = get_db_type(state, connection_id).await.ok();
+ if should_reconnect_missing_xugu_transfer_metadata_pool(db_type, true) {
+ // A timed-out Xugu Agent operation can invalidate its session and, when
+ // the shared Agent runtime is replaced, detach sibling source/target
+ // sessions too. Recreate only the missing Xugu transfer pool before
+ // asking the Agent for the next table's columns.
+ ensure_transfer_statement_pool(state, pool_key).await?;
+ pool_handle = state.pool_handle(pool_key).await;
+ }
+ }
#[cfg(feature = "duckdb-sidecar")]
if let Some(PoolKind::DuckDbWorker(client)) = pool_handle.as_ref() {
@@ -22750,7 +22770,7 @@ SELECT 1 FROM dual"#
}
#[test]
- fn fresh_transfer_session_preparation_is_scoped_to_structured_agent_quarantine() {
+ fn fresh_transfer_session_preparation_is_scoped_to_agent_quarantine_and_xugu_timeout() {
let quarantine = "Agent RPC error (-1): lost\nDBX_AGENT_ERROR_DATA:{\"contractVersion\":1,\"category\":\"connection\",\"retryable\":false,\"sessionDisposition\":\"quarantine\",\"stage\":\"execute\",\"operationOutcome\":\"unknown\"}";
let keep = "Agent RPC error (-1): syntax error\nDBX_AGENT_ERROR_DATA:{\"contractVersion\":1,\"category\":\"sql\",\"retryable\":false,\"sessionDisposition\":\"keep\",\"stage\":\"execute\",\"operationOutcome\":\"unknown\"}";
let replace_runtime = "Agent RPC error (-1): exhausted\nDBX_AGENT_ERROR_DATA:{\"contractVersion\":1,\"category\":\"resource\",\"retryable\":false,\"sessionDisposition\":\"replace_runtime\",\"stage\":\"execute\",\"operationOutcome\":\"unknown\"}";
@@ -22764,6 +22784,36 @@ SELECT 1 FROM dual"#
Some(DatabaseType::OceanbaseOracle),
"Agent RPC error (-1): legacy connection error"
));
+ assert!(should_prepare_fresh_agent_transfer_session(
+ Some(DatabaseType::Xugu),
+ "Agent RPC call timed out at execute"
+ ));
+ assert_eq!(
+ transfer_pool_error_action(
+ TransferExecutionSafety::WriteNoReplay,
+ Some(DatabaseType::Xugu),
+ "Agent RPC call timed out at execute"
+ ),
+ PoolErrorAction::Discard,
+ "a local Xugu RPC timeout must discard the uncertain session without replaying the write"
+ );
+ assert!(!should_prepare_fresh_agent_transfer_session(
+ Some(DatabaseType::OceanbaseOracle),
+ "Agent RPC call timed out at execute"
+ ));
+ assert!(!should_prepare_fresh_agent_transfer_session(
+ Some(DatabaseType::Xugu),
+ "Agent RPC error (-1): SQL execution failed"
+ ));
+ }
+
+ #[test]
+ fn transfer_metadata_pool_recovery_is_scoped_to_missing_xugu_pools() {
+ assert!(should_reconnect_missing_xugu_transfer_metadata_pool(Some(DatabaseType::Xugu), true));
+ assert!(!should_reconnect_missing_xugu_transfer_metadata_pool(Some(DatabaseType::Xugu), false));
+ assert!(!should_reconnect_missing_xugu_transfer_metadata_pool(Some(DatabaseType::Postgres), true));
+ assert!(!should_reconnect_missing_xugu_transfer_metadata_pool(Some(DatabaseType::Oracle), true));
+ assert!(!should_reconnect_missing_xugu_transfer_metadata_pool(None, true));
}
#[test]