Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(flashback): get table columns from schema (#3336)

Yilong Lic73c08b6d764
diff --git a/plugin/db/mysql/rollback.go b/plugin/db/mysql/rollback.go
index adae10ba84..ace7c79956 100644
--- a/plugin/db/mysql/rollback.go
+++ b/plugin/db/mysql/rollback.go
@@ -5,7 +5,14 @@ import (
"regexp"
"strings"
+ // Register pingcap parser driver.
+ _ "github.com/pingcap/tidb/types/parser_driver"
+
+ "github.com/pingcap/tidb/parser"
+ "github.com/pingcap/tidb/parser/ast"
"github.com/pkg/errors"
+
+ bbparser "github.com/bytebase/bytebase/plugin/parser"
)
var (
@@ -35,6 +42,30 @@ func (txn BinlogTransaction) GetRollbackSQL(tables map[string][]string) (string,
return strings.Join(sqlList, "\n"), nil
}
+// GetTableColumns parses the schema to get the table columns map.
+// This is used to generate rollback SQL from the binlog events.
+func GetTableColumns(schema string) (map[string][]string, error) {
+ _, supportStmts, err := bbparser.ExtractTiDBUnsupportStmts(schema)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to extract TiDB unsupported statements from old statements %q", schema)
+ }
+ nodes, _, err := parser.New().Parse(supportStmts, "", "")
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse old statement %q", schema)
+ }
+ tableMap := make(map[string][]string)
+ for _, node := range nodes {
+ if stmt, ok := node.(*ast.CreateTableStmt); ok {
+ var columnNames []string
+ for _, col := range stmt.Cols {
+ columnNames = append(columnNames, col.Name.Name.O)
+ }
+ tableMap[stmt.Table.Name.O] = columnNames
+ }
+ }
+ return tableMap, nil
+}
+
func (e *BinlogEvent) getRollbackSQL(tables map[string][]string) (string, error) {
// 1. Remove the "### " prefix of each line.
// mysqlbinlog output is separated by "\n", ref https://sourcegraph.com/github.com/mysql/mysql-server@a246bad76b9271cb4333634e954040a970222e0a/-/blob/sql/log_event.cc?L2398
diff --git a/plugin/db/mysql/rollback_test.go b/plugin/db/mysql/rollback_test.go
index b1f8299f35..180e4195a6 100644
--- a/plugin/db/mysql/rollback_test.go
+++ b/plugin/db/mysql/rollback_test.go
@@ -230,3 +230,43 @@ SET
})
}
}
+
+func TestGetTableColumns(t *testing.T) {
+ tests := []struct {
+ name string
+ schema string
+ tableMap map[string][]string
+ err bool
+ }{
+ {
+ name: "multiple tables",
+ schema: `
+CREATE TABLE user (
+ id INT PRIMARY KEY,
+ name VARCHAR(20)
+);
+CREATE TABLE balance (
+ id INT PRIMARY KEY,
+ user_id INT REFERENCES user(id),
+ balance INT
+);`,
+ tableMap: map[string][]string{
+ "user": {"id", "name"},
+ "balance": {"id", "user_id", "balance"},
+ },
+ err: false,
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ a := require.New(t)
+ tableMap, err := GetTableColumns(test.schema)
+ if test.err {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ a.Equal(test.tableMap, tableMap)
+ }
+ })
+ }
+}