fix(agent): load all sheets from Excel files in data analysis (#1007)

DuckDB's st_read (spatial) only reads the first layer/sheet of a .xlsx
workbook, so every sheet beyond Sheet1 was silently dropped from the
DuckDB table the Data Analysis tool builds. Users trying to analyse
multi-sheet workbooks could only see the first sheet.

Switch to DuckDB's dedicated 'excel' extension (read_xlsx) for the
actual data load, enumerate sheets via the spatial extension's
st_read_meta, and UNION ALL BY NAME the rows of every sheet into one
table. A synthetic __sheet_name column records the source so the LLM
can still filter/aggregate per sheet; schema drift between sheets is
tolerated via UNION BY NAME. If enumeration fails (older DuckDB, local
filesystem errors, …) we fall back to reading the first sheet so the
tool stays usable.

- Install & LOAD the 'excel' extension alongside 'spatial' both at
  startup (internal/container) and in the offline prefetch binary
  (cmd/download/duckdb).
- Harden sheet/path handling against single quotes.
- Update the tool description so the agent knows about __sheet_name.
- Add unit tests for the CREATE TABLE SQL builder covering 0 / 1 / N
  sheets and quote escaping.

Refs: https://github.com/Tencent/WeKnora/issues/1007
This commit is contained in:
wizardchen
2026-04-24 19:32:51 +08:00
committed by lyingbug
parent beca2b89a3
commit 11811f9bf8
4 changed files with 231 additions and 37 deletions
+11 -10
View File
@@ -1132,16 +1132,17 @@ func NewDuckDB() (*sql.DB, error) {
return nil, fmt.Errorf("failed to open duckdb: %w", err)
}
// Try to install and load spatial extension
installSQL := "INSTALL spatial;"
if _, err := sqlDB.ExecContext(context.Background(), installSQL); err != nil {
logger.Warnf(context.Background(), "[DuckDB] Failed to install spatial extension: %v", err)
}
// Try to load spatial extension
loadSQL := "LOAD spatial;"
if _, err := sqlDB.ExecContext(context.Background(), loadSQL); err != nil {
logger.Warnf(context.Background(), "[DuckDB] Failed to load spatial extension: %v", err)
// Try to install and load required extensions.
// - spatial: used for st_read_meta() to enumerate layer (sheet) names from .xlsx/.xls
// - excel: used for read_xlsx() which gives proper type inference per sheet
bgCtx := context.Background()
for _, ext := range []string{"spatial", "excel"} {
if _, err := sqlDB.ExecContext(bgCtx, fmt.Sprintf("INSTALL %s;", ext)); err != nil {
logger.Warnf(bgCtx, "[DuckDB] Failed to install %s extension: %v", ext, err)
}
if _, err := sqlDB.ExecContext(bgCtx, fmt.Sprintf("LOAD %s;", ext)); err != nil {
logger.Warnf(bgCtx, "[DuckDB] Failed to load %s extension: %v", ext, err)
}
}
return sqlDB, nil