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(kingbase): preserve identity columns in table DDL

t8y2857a3acb903c
diff --git a/agents/drivers/kingbase-go/kingbase_metadata.go b/agents/drivers/kingbase-go/kingbase_metadata.go
index 8e080d1086..f0cf89b4f5 100644
--- a/agents/drivers/kingbase-go/kingbase_metadata.go
+++ b/agents/drivers/kingbase-go/kingbase_metadata.go
@@ -454,13 +454,14 @@ func (s *server) queryCatalogColumns(
catalog, prefix, expression string,
) ([]columnInfo, error) {
query := fmt.Sprintf(`SELECT a.attname, format_type(a.atttypid, a.atttypmod), NOT a.attnotnull,
-%s(ad.adbin, ad.adrelid), col_description(a.attrelid, a.attnum),
-CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 THEN ((a.atttypmod - 4) >> 16) & 65535 END,
-CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 THEN (a.atttypmod - 4) & 65535 END,
-CASE WHEN t.typname IN ('varchar','bpchar') AND a.atttypmod > 0 THEN a.atttypmod - 4 END
-FROM %s.%s_attribute a JOIN %s.%s_type t ON t.oid = a.atttypid
-JOIN %s.%s_class c ON c.oid = a.attrelid JOIN %s.%s_namespace n ON n.oid = c.relnamespace
-LEFT JOIN %s.%s_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
+ %s(ad.adbin, ad.adrelid), col_description(a.attrelid, a.attnum),
+ CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 THEN ((a.atttypmod - 4) >> 16) & 65535 END,
+ CASE WHEN t.typname = 'numeric' AND a.atttypmod > 0 THEN (a.atttypmod - 4) & 65535 END,
+ CASE WHEN t.typname IN ('varchar','bpchar') AND a.atttypmod > 0 THEN a.atttypmod - 4 END,
+ a.attidentity
+ FROM %s.%s_attribute a JOIN %s.%s_type t ON t.oid = a.atttypid
+ JOIN %s.%s_class c ON c.oid = a.attrelid JOIN %s.%s_namespace n ON n.oid = c.relnamespace
+ LEFT JOIN %s.%s_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
WHERE n.nspname = %s AND c.relname = %s AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`, expression, catalog, prefix, catalog, prefix, catalog, prefix, catalog, prefix, catalog, prefix, quoteLiteral(schema), quoteLiteral(table))
rows, err := s.metadataQuery(query)
if err != nil {
@@ -471,12 +472,12 @@ WHERE n.nspname = %s AND c.relname = %s AND a.attnum > 0 AND NOT a.attisdropped
for rows.Next() {
var name, dataType string
var nullable bool
- var defaultValue, comment sql.NullString
+ var defaultValue, comment, identity sql.NullString
var precision, scale, length sql.NullInt64
- if err := rows.Scan(&name, &dataType, &nullable, &defaultValue, &comment, &precision, &scale, &length); err != nil {
+ if err := rows.Scan(&name, &dataType, &nullable, &defaultValue, &comment, &precision, &scale, &length, &identity); err != nil {
return nil, err
}
- result = append(result, columnInfo{Name: name, DataType: dataType, IsNullable: nullable, ColumnDefault: nullStringPtr(defaultValue), IsPrimaryKey: primary[strings.ToLower(name)], Comment: nullStringPtr(comment), NumericPrecision: nullIntPtr(precision), NumericScale: nullIntPtr(scale), CharacterMaximumLength: nullIntPtr(length)})
+ result = append(result, columnInfo{Name: name, DataType: dataType, IsNullable: nullable, ColumnDefault: nullStringPtr(defaultValue), IsPrimaryKey: primary[strings.ToLower(name)], Extra: kingbaseIdentityClause(identity.String), Comment: nullStringPtr(comment), NumericPrecision: nullIntPtr(precision), NumericScale: nullIntPtr(scale), CharacterMaximumLength: nullIntPtr(length)})
}
if err := rows.Err(); err != nil {
return nil, err
@@ -674,14 +675,7 @@ func (s *server) getTableDDL(schema, table string) (string, error) {
definitions := make([]string, 0, len(columns)+1)
primary := []string{}
for _, column := range columns {
- definition := quoteIdentifier(column.Name) + " " + column.DataType
- if !column.IsNullable {
- definition += " NOT NULL"
- }
- if column.ColumnDefault != nil && *column.ColumnDefault != "" {
- definition += " DEFAULT " + *column.ColumnDefault
- }
- definitions = append(definitions, definition)
+ definitions = append(definitions, columnDDLDefinition(column))
if column.IsPrimaryKey {
primary = append(primary, quoteIdentifier(column.Name))
}
@@ -692,6 +686,35 @@ func (s *server) getTableDDL(schema, table string) (string, error) {
return "CREATE TABLE " + quoteIdentifier(effective) + "." + quoteIdentifier(table) + " (\n " + strings.Join(definitions, ",\n ") + "\n);", nil
}
+func columnDDLDefinition(column columnInfo) string {
+ definition := quoteIdentifier(column.Name) + " " + column.DataType
+ if column.Extra != nil && *column.Extra != "" {
+ // Identity clauses belong immediately after the data type in both
+ // PostgreSQL-compatible and SQL Server-compatible Kingbase modes.
+ definition += " " + *column.Extra
+ }
+ if !column.IsNullable {
+ definition += " NOT NULL"
+ }
+ if column.ColumnDefault != nil && *column.ColumnDefault != "" {
+ definition += " DEFAULT " + *column.ColumnDefault
+ }
+ return definition
+}
+
+func kingbaseIdentityClause(code string) *string {
+ var clause string
+ switch strings.ToLower(strings.TrimSpace(code)) {
+ case "a":
+ clause = "GENERATED ALWAYS AS IDENTITY"
+ case "d":
+ clause = "GENERATED BY DEFAULT AS IDENTITY"
+ default:
+ return nil
+ }
+ return &clause
+}
+
func (s *server) getExplainInfo(sqlText string) (string, error) {
rows, err := s.metadataQuery("EXPLAIN " + trimStatementSQL(sqlText))
if err != nil {
diff --git a/agents/drivers/kingbase-go/main_test.go b/agents/drivers/kingbase-go/main_test.go
index dcb30a9fc3..47f2bead85 100644
--- a/agents/drivers/kingbase-go/main_test.go
+++ b/agents/drivers/kingbase-go/main_test.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"database/sql/driver"
+ "encoding/json"
"errors"
"io"
"strings"
@@ -140,8 +141,8 @@ func (connection *fallbackConn) QueryContext(_ context.Context, query string, _
}
if strings.Contains(query, "pg_get_expr(") {
return &valueRows{
- columns: []string{"column_name", "data_type", "is_nullable", "column_default", "column_comment", "numeric_precision", "numeric_scale", "character_maximum_length"},
- rows: [][]driver.Value{{"id", "integer", false, "nextval('orders_id_seq'::regclass)", nil, int64(32), int64(0), nil}},
+ columns: []string{"column_name", "data_type", "is_nullable", "column_default", "column_comment", "numeric_precision", "numeric_scale", "character_maximum_length", "attidentity"},
+ rows: [][]driver.Value{{"id", "integer", false, nil, nil, int64(32), int64(0), nil, "d"}},
}, nil
}
return nil, errors.New("unexpected query: " + query)
@@ -337,7 +338,7 @@ func TestColumnsFallbackToPgGetExprAndCacheChoice(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if len(columns) != 1 || columns[0].ColumnDefault == nil || *columns[0].ColumnDefault != "nextval('orders_id_seq'::regclass)" {
+ if len(columns) != 1 || columns[0].Extra == nil || *columns[0].Extra != "GENERATED BY DEFAULT AS IDENTITY" {
t.Fatalf("unexpected columns: %#v", columns)
}
}
@@ -355,12 +356,82 @@ func TestColumnsFallbackToPgGetExprAndCacheChoice(t *testing.T) {
!strings.Contains(query, "col_description(a.attrelid, a.attnum)") {
t.Fatalf("catalog columns must use PostgreSQL column comments: %s", query)
}
+ if strings.Contains(query, "pg_get_expr(") && !strings.Contains(query, "a.attidentity") {
+ t.Fatalf("catalog columns must include identity metadata: %s", query)
+ }
}
if sysCalls != 1 || pgCalls != 2 {
t.Fatalf("fallback choice was not cached: sys=%d pg=%d queries=%v", sysCalls, pgCalls, state.queries)
}
}
+func TestKingbaseIdentityClausesAreExposedAndRendered(t *testing.T) {
+ tests := []struct {
+ name string
+ code string
+ expected string
+ }{
+ {name: "always", code: "a", expected: "GENERATED ALWAYS AS IDENTITY"},
+ {name: "by default", code: "d", expected: "GENERATED BY DEFAULT AS IDENTITY"},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ extra := kingbaseIdentityClause(test.code)
+ if extra == nil || *extra != test.expected {
+ t.Fatalf("unexpected identity clause for %q: %#v", test.code, extra)
+ }
+ definition := columnDDLDefinition(columnInfo{Name: "id", DataType: "integer", IsNullable: false, Extra: extra})
+ expected := `"id" integer ` + test.expected + " NOT NULL"
+ if definition != expected {
+ t.Fatalf("unexpected column DDL: %s", definition)
+ }
+ payload, err := json.Marshal(columnInfo{Name: "id", DataType: "integer", Extra: extra})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(payload), `"extra":"`+test.expected+`"`) {
+ t.Fatalf("identity clause missing from protocol payload: %s", payload)
+ }
+ })
+ }
+}
+
+func TestTableDDLIncludesCatalogIdentityClause(t *testing.T) {
+ registerExpressionFallbackDriver.Do(func() { sql.Register("kingbase-expression-fallback-test", fallbackDriver{}) })
+ expressionFallbackState.Store(&fallbackDriverState{})
+ db, err := sql.Open("kingbase-expression-fallback-test", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { _ = db.Close() })
+ server := newServer()
+ server.db = db
+
+ ddl, err := server.getTableDDL("public", "orders")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(ddl, `"id" integer GENERATED BY DEFAULT AS IDENTITY NOT NULL`) {
+ t.Fatalf("identity clause missing from table DDL: %s", ddl)
+ }
+}
+
+func TestColumnDDLDefinitionPreservesCompatibilityExtras(t *testing.T) {
+ identity := "IDENTITY(1,1)"
+ defaultValue := "0"
+ if definition := columnDDLDefinition(columnInfo{Name: "id", DataType: "integer", IsNullable: false, Extra: &identity}); definition != `"id" integer IDENTITY(1,1) NOT NULL` {
+ t.Fatalf("unexpected SQL Server-compatible DDL: %s", definition)
+ }
+ if definition := columnDDLDefinition(columnInfo{Name: "count", DataType: "integer", IsNullable: true, ColumnDefault: &defaultValue}); definition != `"count" integer DEFAULT 0` {
+ t.Fatalf("unexpected regular column DDL: %s", definition)
+ }
+ if extra := kingbaseIdentityClause(""); extra != nil {
+ t.Fatalf("non-identity column must not expose an extra clause: %#v", extra)
+ }
+}
+
func TestMySQLCompatColumnsUsePostgresColumnComments(t *testing.T) {
registerExpressionFallbackDriver.Do(func() { sql.Register("kingbase-expression-fallback-test", fallbackDriver{}) })
state := &fallbackDriverState{}
@@ -382,6 +453,9 @@ func TestMySQLCompatColumnsUsePostgresColumnComments(t *testing.T) {
if len(columns) != 1 || columns[0].Comment == nil || *columns[0].Comment != "primary key" {
t.Fatalf("unexpected columns: %#v", columns)
}
+ if columns[0].Extra != nil {
+ t.Fatalf("MySQL-compatible metadata must not infer PostgreSQL identity: %#v", columns[0].Extra)
+ }
state.mu.Lock()
defer state.mu.Unlock()