Skip to content

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

chore: mysqlv2 walkthrough (#9400)

zll60060709f5898ea
diff --git a/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml b/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml
new file mode 100644
index 0000000000..5b7e33ae8e
--- /dev/null
+++ b/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml
@@ -0,0 +1,36 @@
+- statement: |-
+ CREATE TABLE t1(
+ col1 CHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_i,
+ col2 INT
+ );
+ ignore_case_sensitive: false
+ want: |-
+ {
+ "name": "test",
+ "schemas": [
+ {
+ "tables": [
+ {
+ "name": "t1",
+ "columns": [
+ {
+ "name": "col1",
+ "position": 1,
+ "nullable": true,
+ "type": "char",
+ "characterSet": "utf8mb4",
+ "collation": "utf8mb4_unicode_i"
+ },
+ {
+ "name": "col2",
+ "position": 2,
+ "nullable": true,
+ "type": "int"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ err: null
diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.go
index 98b92dc5c6..7d128fe335 100644
--- a/backend/plugin/advisor/catalog/walk_through.go
+++ b/backend/plugin/advisor/catalog/walk_through.go
@@ -222,6 +222,10 @@ func (d *DatabaseState) WalkThrough(stmt string) error {
d.usable = false
}
return nil
+ // only for mysqlv2 test.
+ case storepb.Engine_ENGINE_UNSPECIFIED:
+ err := d.mysqlV2WalkThrough(stmt)
+ return err
default:
return &WalkThroughError{
Type: ErrorTypeUnsupported,
diff --git a/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go b/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go
new file mode 100644
index 0000000000..cb8a312e09
--- /dev/null
+++ b/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go
@@ -0,0 +1,183 @@
+package catalog
+
+import (
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ mysql "github.com/bytebase/mysql-parser"
+
+ mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
+)
+
+func (d *DatabaseState) mysqlV2WalkThrough(stmt string) error {
+ // We define the Catalog as Database -> Schema -> Table. The Schema is only for PostgreSQL.
+ // So we use a Schema whose name is empty for other engines, such as MySQL.
+ // If there is no empty-string-name schema, create it to avoid corner cases.
+ if _, exists := d.schemaSet[""]; !exists {
+ d.createSchema("")
+ }
+
+ nodeList, err := mysqlparser.ParseMySQL(stmt + ";")
+ if err != nil {
+ return NewParseError(err.Error())
+ }
+ for _, node := range nodeList {
+ if err := d.mysqlV2ChangeState(node); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+type mysqlV2Listener struct {
+ *mysql.BaseMySQLParserListener
+
+ baseLine int
+ databaseState *DatabaseState
+ err *WalkThroughError
+}
+
+func (d *DatabaseState) mysqlV2ChangeState(in *mysqlparser.ParseResult) (err *WalkThroughError) {
+ defer func() {
+ if err == nil {
+ return
+ }
+ if err.Line == 0 {
+ err.Line = in.BaseLine
+ }
+ }()
+
+ if d.deleted {
+ return &WalkThroughError{
+ Type: ErrorTypeDatabaseIsDeleted,
+ Content: fmt.Sprintf("Database `%s` is deleted", d.name),
+ }
+ }
+
+ listener := &mysqlV2Listener{
+ baseLine: in.BaseLine,
+ databaseState: d,
+ }
+ antlr.ParseTreeWalkerDefault.Walk(listener, in.Tree)
+ if listener.err != nil {
+ return listener.err
+ }
+ return nil
+}
+
+// EnterCreateTable is called when production createTable is entered.
+func (l *mysqlV2Listener) EnterCreateTable(ctx *mysql.CreateTableContext) {
+ if ctx.TableName() == nil {
+ return
+ }
+ databaseName, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
+ if databaseName != "" && !l.databaseState.isCurrentDatabase(databaseName) {
+ l.err = &WalkThroughError{
+ Type: ErrorTypeAccessOtherDatabase,
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.name),
+ }
+ return
+ }
+
+ schema, exists := l.databaseState.schemaSet[""]
+ if !exists {
+ schema = l.databaseState.createSchema("")
+ }
+ if _, exists = schema.getTable(tableName); exists {
+ if ctx.IfNotExists() != nil {
+ return
+ }
+ l.err = &WalkThroughError{
+ Type: ErrorTypeTableExists,
+ Content: fmt.Sprintf("Table `%s` already exists", tableName),
+ }
+ return
+ }
+
+ table := &TableState{
+ name: tableName,
+ engine: newEmptyStringPointer(),
+ collation: newEmptyStringPointer(),
+ comment: newEmptyStringPointer(),
+ columnSet: make(columnStateMap),
+ indexSet: make(IndexStateMap),
+ }
+ schema.tableSet[table.name] = table
+
+ if ctx.TableElementList() == nil {
+ return
+ }
+
+ for _, tableElement := range ctx.TableElementList().AllTableElement() {
+ switch {
+ // handle column
+ case tableElement.ColumnDefinition() != nil:
+ if tableElement.ColumnDefinition().FieldDefinition() == nil {
+ continue
+ }
+ if err := table.mysqlV2CreateColumn(l.databaseState.ctx, tableElement.ColumnDefinition()); err != nil {
+ err.Line = l.baseLine + tableElement.GetStart().GetLine()
+ l.err = err
+ return
+ }
+ default:
+ }
+ }
+}
+
+func (t *TableState) mysqlV2CreateColumn(_ *FinderContext, columnDef mysql.IColumnDefinitionContext) *WalkThroughError {
+ if columnDef.ColumnName() == nil || columnDef.FieldDefinition() == nil {
+ // todo: add more error info
+ return nil
+ }
+ _, _, columnName := mysqlparser.NormalizeMySQLColumnName(columnDef.ColumnName())
+ if _, exists := t.columnSet[columnName]; exists {
+ return &WalkThroughError{
+ Type: ErrorTypeColumnExists,
+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, t.name),
+ }
+ }
+
+ // todo: handle position.
+ pos := len(t.columnSet) + 1
+ columnType := ""
+ characterSet := ""
+ collation := ""
+ // todo: use fail-open pattern.
+ if columnDef.FieldDefinition() != nil && columnDef.FieldDefinition().DataType() != nil {
+ columnType = mysqlparser.NormalizeMySQLDataType(columnDef.FieldDefinition().DataType(), true /* compact */)
+ characterSet = mysqlparser.GetCharSetName(columnDef.FieldDefinition().DataType())
+ collation = mysqlparser.GetCollationName(columnDef.FieldDefinition())
+ }
+
+ vTrue := true
+ col := &ColumnState{
+ name: columnName,
+ position: &pos,
+ defaultValue: nil,
+ nullable: &vTrue,
+ columnType: newStringPointer(columnType),
+ characterSet: newStringPointer(characterSet),
+ collation: newStringPointer(collation),
+ comment: newEmptyStringPointer(),
+ }
+ setNullDefault := false
+
+ if col.nullable != nil && !*col.nullable && setNullDefault {
+ return &WalkThroughError{
+ Type: ErrorTypeSetNullDefaultForNotNullColumn,
+ // Content comes from MySQL Error content.
+ Content: fmt.Sprintf("Invalid default value for column `%s`", col.name),
+ }
+ }
+
+ for _, attribute := range columnDef.FieldDefinition().AllColumnAttribute() {
+ if attribute == nil {
+ continue
+ }
+ }
+
+ t.columnSet[col.name] = col
+ return nil
+}
diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.go
index 507738aa29..d0a9a4dc05 100644
--- a/backend/plugin/advisor/catalog/walk_through_test.go
+++ b/backend/plugin/advisor/catalog/walk_through_test.go
@@ -42,6 +42,20 @@ func TestMySQLWalkThrough(t *testing.T) {
}
}
+func TestMySQLV2WalkThrough(t *testing.T) {
+ originDatabase := &storepb.DatabaseSchemaMetadata{
+ Name: "test",
+ }
+
+ tests := []string{
+ "mysqlv2_walk_through",
+ }
+
+ for _, test := range tests {
+ runWalkThroughTest(t, test, storepb.Engine_ENGINE_UNSPECIFIED, originDatabase, false /* record */)
+ }
+}
+
func TestMySQLWalkThroughForIncomplete(t *testing.T) {
tests := []string{
"mysql_walk_through_for_incomplete",
diff --git a/backend/plugin/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.go
index 3504d3761a..1195918085 100644
--- a/backend/plugin/parser/mysql/normalize.go
+++ b/backend/plugin/parser/mysql/normalize.go
@@ -300,3 +300,22 @@ func NormalizeMySQLDataType(ctx parser.IDataTypeContext, compact bool) string {
return strings.ToLower(ctx.GetType_().GetText())
}
}
+
+// GetCharSetName get charset name from DataTypeContext.
+func GetCharSetName(ctx parser.IDataTypeContext) string {
+ if ctx.CharsetWithOptBinary() == nil {
+ return ""
+ }
+ charset := NormalizeMySQLCharsetName(ctx.CharsetWithOptBinary().CharsetName())
+ return charset
+}
+
+// GetCollationName get collation name from FieldDefinitionContext.
+func GetCollationName(ctx parser.IFieldDefinitionContext) string {
+ for _, attr := range ctx.AllColumnAttribute() {
+ if attr != nil && attr.Collate() != nil && attr.Collate().CollationName() != nil {
+ return NormalizeMySQLCollationName(attr.Collate().CollationName())
+ }
+ }
+ return ""
+}