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(kingbase): execute CTE DML through statement path
t8y22fa2c1bba4de
diff --git a/agents/drivers/kingbase-go/main.go b/agents/drivers/kingbase-go/main.goindex 7e2c471abc..1fa03be35b 100644--- a/agents/drivers/kingbase-go/main.go+++ b/agents/drivers/kingbase-go/main.go@@ -658,6 +658,7 @@ func (s *server) executeQueryPage(opts queryOptions, pageSize int) (queryPageRess.endOperation(cancel)return queryPageResult{}, err}+ columns = nonNilStrings(columns)maxRows := opts.MaxRowsif maxRows <= 0 {maxRows = defaultMaxRows@@ -767,6 +768,7 @@ func readRows(rows *sql.Rows, maxRows int) (queryResult, error) {if err != nil {return queryResult{}, err}+ columns = nonNilStrings(columns)result := queryResult{Columns: columns, ColumnTypes: columnTypeNames(rows), Rows: make([][]any, 0, min(maxRows, 1024))}for rows.Next() {if len(result.Rows) >= maxRows {@@ -1516,8 +1518,329 @@ func trimStatementSQL(sqlText string) string {}func isQuerySQL(sqlText string) bool {- lower := strings.ToLower(strings.TrimSpace(sqlText))- return strings.HasPrefix(lower, "select") || strings.HasPrefix(lower, "with") || strings.HasPrefix(lower, "show") || strings.HasPrefix(lower, "explain")+ keyword, next := sqlKeywordAt(sqlText, 0)+ if keyword == "with" {+ terminal, terminalEnd := withTerminalKeyword(sqlText, next)+ if terminal == "" || !isStatementKeyword(terminal) {+ return true+ }+ keyword = terminal+ next = terminalEnd+ }+ if keyword == "select" || keyword == "show" || keyword == "explain" || keyword == "values" || keyword == "table" {+ return true+ }+ return isDMLKeyword(keyword) && hasTopLevelSQLKeyword(sqlText, next, "returning")+}++func withTerminalKeyword(sqlText string, index int) (string, int) {+ if keyword, next := sqlKeywordAt(sqlText, index); keyword == "recursive" {+ index = next+ }++ for {+ index = skipSQLTrivia(sqlText, index)+ index = skipSQLIdentifier(sqlText, index)+ if index < 0 {+ return "", index+ }++ index = skipSQLTrivia(sqlText, index)+ if index < len(sqlText) && sqlText[index] == '(' {+ index = skipSQLParenthesized(sqlText, index)+ if index < 0 {+ return "", index+ }+ }++ keyword, next := sqlKeywordAt(sqlText, index)+ if keyword != "as" {+ return "", index+ }+ index = next++ if keyword, next = sqlKeywordAt(sqlText, index); keyword == "not" {+ index = next+ keyword, next = sqlKeywordAt(sqlText, index)+ if keyword != "materialized" {+ return "", index+ }+ index = next+ } else if keyword == "materialized" {+ index = next+ }++ index = skipSQLTrivia(sqlText, index)+ if index >= len(sqlText) || sqlText[index] != '(' {+ return "", index+ }+ index = skipSQLParenthesized(sqlText, index)+ if index < 0 {+ return "", index+ }++ index = skipSQLTrivia(sqlText, index)+ if index < len(sqlText) && sqlText[index] == ',' {+ index+++ continue+ }+ keyword, next = sqlKeywordAt(sqlText, index)+ return keyword, next+ }+}++func hasTopLevelSQLKeyword(sqlText string, index int, target string) bool {+ depth := 0+ for index < len(sqlText) {+ switch sqlText[index] {+ case '\'':+ index = skipSQLQuoted(sqlText, index, '\'')+ if index < 0 {+ return false+ }+ continue+ case '"':+ index = skipSQLQuoted(sqlText, index, '"')+ if index < 0 {+ return false+ }+ continue+ case '$':+ if next := skipSQLDollarQuoted(sqlText, index); next != index {+ if next < 0 {+ return false+ }+ index = next+ continue+ }+ case '-':+ if index+1 < len(sqlText) && sqlText[index+1] == '-' {+ index = skipSQLLineComment(sqlText, index+2)+ continue+ }+ case '/':+ if index+1 < len(sqlText) && sqlText[index+1] == '*' {+ index = skipSQLBlockComment(sqlText, index)+ if index < 0 {+ return false+ }+ continue+ }+ case '(':+ depth+++ case ')':+ depth = max(depth-1, 0)+ default:+ if depth == 0 && isSQLWordStartByte(sqlText[index]) {+ keyword, next := sqlKeywordAt(sqlText, index)+ if keyword == target {+ return true+ }+ index = next+ continue+ }+ }+ index+++ }+ return false+}++func isDMLKeyword(keyword string) bool {+ return keyword == "insert" || keyword == "update" || keyword == "delete" || keyword == "merge"+}++func isStatementKeyword(keyword string) bool {+ return isDMLKeyword(keyword) || keyword == "select" || keyword == "values" || keyword == "table"+}++func sqlKeywordAt(sqlText string, index int) (string, int) {+ index = skipSQLTrivia(sqlText, index)+ if index >= len(sqlText) || !isSQLWordStartByte(sqlText[index]) {+ return "", index+ }+ start := index+ for index < len(sqlText) && isSQLIdentifierByte(sqlText[index]) {+ index+++ }+ return strings.ToLower(sqlText[start:index]), index+}++func skipSQLIdentifier(sqlText string, index int) int {+ index = skipSQLTrivia(sqlText, index)+ if index >= len(sqlText) {+ return -1+ }+ if sqlText[index] == '"' {+ return skipSQLQuoted(sqlText, index, '"')+ }+ start := index+ for index < len(sqlText) && isSQLIdentifierByte(sqlText[index]) {+ index+++ }+ if start == index {+ return -1+ }+ return index+}++func skipSQLParenthesized(sqlText string, index int) int {+ if index >= len(sqlText) || sqlText[index] != '(' {+ return -1+ }+ depth := 0+ for index < len(sqlText) {+ switch sqlText[index] {+ case '\'':+ index = skipSQLQuoted(sqlText, index, '\'')+ if index < 0 {+ return -1+ }+ continue+ case '"':+ index = skipSQLQuoted(sqlText, index, '"')+ if index < 0 {+ return -1+ }+ continue+ case '$':+ if next := skipSQLDollarQuoted(sqlText, index); next != index {+ if next < 0 {+ return -1+ }+ index = next+ continue+ }+ case '-':+ if index+1 < len(sqlText) && sqlText[index+1] == '-' {+ index = skipSQLLineComment(sqlText, index+2)+ continue+ }+ case '/':+ if index+1 < len(sqlText) && sqlText[index+1] == '*' {+ index = skipSQLBlockComment(sqlText, index)+ if index < 0 {+ return -1+ }+ continue+ }+ case '(':+ depth+++ case ')':+ depth--+ if depth == 0 {+ return index + 1+ }+ }+ index+++ }+ return -1+}++func skipSQLTrivia(sqlText string, index int) int {+ for index < len(sqlText) {+ if isSQLSpace(sqlText[index]) {+ index+++ continue+ }+ if index+1 < len(sqlText) && sqlText[index] == '-' && sqlText[index+1] == '-' {+ index = skipSQLLineComment(sqlText, index+2)+ continue+ }+ if index+1 < len(sqlText) && sqlText[index] == '/' && sqlText[index+1] == '*' {+ index = skipSQLBlockComment(sqlText, index)+ if index < 0 {+ return len(sqlText)+ }+ continue+ }+ break+ }+ return index+}++func skipSQLLineComment(sqlText string, index int) int {+ for index < len(sqlText) && sqlText[index] != '\n' {+ index+++ }+ return index+}++func skipSQLBlockComment(sqlText string, index int) int {+ depth := 0+ for index+1 < len(sqlText) {+ if sqlText[index] == '/' && sqlText[index+1] == '*' {+ depth+++ index += 2+ continue+ }+ if sqlText[index] == '*' && sqlText[index+1] == '/' {+ depth--+ index += 2+ if depth == 0 {+ return index+ }+ continue+ }+ index+++ }+ return -1+}++func skipSQLQuoted(sqlText string, index int, quote byte) int {+ index+++ for index < len(sqlText) {+ if sqlText[index] == '\\' && quote == '\'' && index+1 < len(sqlText) {+ index += 2+ continue+ }+ if sqlText[index] == quote {+ if index+1 < len(sqlText) && sqlText[index+1] == quote {+ index += 2+ continue+ }+ return index + 1+ }+ index+++ }+ return -1+}++func skipSQLDollarQuoted(sqlText string, index int) int {+ endTag := index + 1+ for endTag < len(sqlText) && isSQLDollarTagByte(sqlText[endTag]) {+ endTag+++ }+ if endTag >= len(sqlText) || sqlText[endTag] != '$' {+ return index+ }+ tag := sqlText[index : endTag+1]+ if end := strings.Index(sqlText[endTag+1:], tag); end >= 0 {+ return endTag + 1 + end + len(tag)+ }+ return -1+}++func nonNilStrings(values []string) []string {+ if values == nil {+ return []string{}+ }+ return values+}++func isSQLSpace(value byte) bool {+ return value == ' ' || value == '\t' || value == '\r' || value == '\n' || value == '\f'+}++func isSQLWordStartByte(value byte) bool {+ return value >= 'a' && value <= 'z' || value >= 'A' && value <= 'Z' || value == '_'+}++func isSQLIdentifierByte(value byte) bool {+ return isSQLWordStartByte(value) || value >= '0' && value <= '9' || value == '$' || value >= 0x80+}++func isSQLDollarTagByte(value byte) bool {+ return isSQLWordStartByte(value) || value >= '0' && value <= '9'}func quoteIdentifier(value string) string {diff --git a/agents/drivers/kingbase-go/main_test.go b/agents/drivers/kingbase-go/main_test.goindex 5ba754082b..2bb60b2af9 100644--- a/agents/drivers/kingbase-go/main_test.go+++ b/agents/drivers/kingbase-go/main_test.go@@ -2448,6 +2448,91 @@ func TestExecuteStatementAppliesSchemaOnSamePoolConnection(t *testing.T) {}}+func TestExecuteRecursiveCteUpdateUsesExecProtocol(t *testing.T) {+ db, state := openFakeDB(t, 0)+ server := newServer()+ server.db = db+ sqlText := `WITH RECURSIVE category_path AS (+ -- 基础:根节点(parent_id = 0),path = 自身 id+ SELECT+ id,+ CAST(id AS VARCHAR(255)) AS path+ FROM system_industry_category+ WHERE deleted = 0+ AND parent_id = 0+ UNION ALL+ -- 递归:子节点 path = 父节点 path + ',' + 当前 id+ SELECT+ sic.id,+ CAST(CONCAT(cp.path, ',', sic.id) AS VARCHAR(255)) AS path+ FROM system_industry_category sic+ INNER JOIN category_path cp ON sic.parent_id = cp.id+ WHERE sic.deleted = 0+ )+ UPDATE manage_merchant m+ SET industry_id = cp.path+ FROM category_path cp+ WHERE m.industry_leaf_id = cp.id+ AND m.deleted = 0+ AND m.industry_id IS NULL+ AND m.industry_leaf_id IS NOT NULL`++ result, err := server.executeQuery(queryOptions{SQL: sqlText})+ if err != nil {+ t.Fatal(err)+ }+ if result.AffectedRows != 1 {+ t.Fatalf("unexpected affected rows: %d", result.AffectedRows)+ }+ if result.Columns == nil || result.ColumnTypes == nil || result.Rows == nil {+ t.Fatalf("query result arrays must not be nil: %#v", result)+ }++ state.mu.Lock()+ defer state.mu.Unlock()+ if len(state.execStatements) == 0 || state.execStatements[len(state.execStatements)-1] != sqlText {+ t.Fatalf("recursive CTE update must use ExecContext: %v", state.execStatements)+ }+ if state.queryCtx != nil {+ t.Fatal("recursive CTE update must not use QueryContext")+ }+}++func TestIsQuerySQLUsesCteTerminalStatement(t *testing.T) {+ tests := []struct {+ name string+ sql string+ query bool+ }{+ {name: "recursive select", sql: `WITH RECURSIVE tree AS (SELECT 1) SELECT * FROM tree`, query: true},+ {name: "recursive update", sql: `WITH RECURSIVE tree AS (SELECT 1) UPDATE target SET value = tree.value FROM tree`, query: false},+ {name: "multiple ctes insert", sql: `WITH source AS (SELECT 1), ready AS (SELECT * FROM source) INSERT INTO target SELECT * FROM ready`, query: false},+ {name: "data modifying cte returns rows", sql: `WITH changed AS (UPDATE target SET value = 1 RETURNING id) SELECT * FROM changed`, query: true},+ {name: "cte update returning rows", sql: `WITH source AS (SELECT 1 AS id) UPDATE target SET value = source.id FROM source RETURNING target.id`, query: true},+ {name: "cte values", sql: `WITH source AS (SELECT 1) VALUES (1)`, query: true},+ {name: "recursive search clause keeps query path", sql: `WITH RECURSIVE tree AS (SELECT 1) SEARCH DEPTH FIRST BY id SET ordercol SELECT * FROM tree`, query: true},+ {name: "plain update returning rows", sql: `UPDATE target SET value = 1 RETURNING id`, query: true},+ {name: "nested returning identifier is ignored", sql: `UPDATE target SET value = (SELECT returning FROM source)`, query: false},+ {name: "returning prefix identifier is ignored", sql: `UPDATE target SET returning2 = 1`, query: false},+ {name: "comments and nested syntax", sql: "/* lead */ WITH source(id) AS NOT MATERIALIZED (SELECT (1 + 2), '-- )'::text)\nDELETE FROM target USING source", query: false},+ {name: "malformed cte keeps legacy query path", sql: `WITH source AS SELECT 1`, query: true},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := isQuerySQL(test.sql); got != test.query {+ t.Fatalf("unexpected query classification: got %v, want %v", got, test.query)+ }+ })+ }+}++func TestNonNilStringsNormalizesProtocolArrays(t *testing.T) {+ if values := nonNilStrings(nil); values == nil || len(values) != 0 {+ t.Fatalf("nil protocol array was not normalized: %#v", values)+ }+}+func TestPagedQueryKeepsContextUntilSessionCloses(t *testing.T) {db, state := openFakeDB(t, 3)server := newServer()