Skip to content

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

feat: mysql get database metadata (#16710)

rebelicedb7d31c492f4
diff --git a/backend/plugin/schema/tidb/get_database_metadata.go b/backend/plugin/schema/tidb/get_database_metadata.go
new file mode 100644
index 0000000000..d9247a8508
--- /dev/null
+++ b/backend/plugin/schema/tidb/get_database_metadata.go
@@ -0,0 +1,779 @@
+package tidb
+
+import (
+ "fmt"
+ "regexp"
+ "slices"
+ "strings"
+
+ "github.com/pingcap/tidb/pkg/parser"
+ "github.com/pingcap/tidb/pkg/parser/ast"
+ "github.com/pingcap/tidb/pkg/parser/model"
+ "github.com/pingcap/tidb/pkg/parser/mysql"
+ "github.com/pingcap/tidb/pkg/types"
+ "github.com/pkg/errors"
+
+ // Register pingcap parser driver.
+ _ "github.com/pingcap/tidb/pkg/types/parser_driver"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func init() {
+ schema.RegisterGetDatabaseMetadata(storepb.Engine_TIDB, GetDatabaseMetadata)
+}
+
+// GetDatabaseMetadata parses the database schema text and returns the metadata using TiDB's parser.
+func GetDatabaseMetadata(schemaText string) (*storepb.DatabaseSchemaMetadata, error) {
+ // Use TiDB's parser to parse the SQL
+ p := parser.New()
+ p.EnableWindowFunc(true)
+ mode, err := mysql.GetSQLMode(mysql.DefaultSQLMode)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get SQL mode")
+ }
+ mode = mysql.DelSQLMode(mode, mysql.ModeNoZeroDate)
+ mode = mysql.DelSQLMode(mode, mysql.ModeNoZeroInDate)
+ p.SetSQLMode(mode)
+
+ stmts, _, err := p.Parse(schemaText, "", "")
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to parse schema")
+ }
+
+ extractor := &metadataExtractor{
+ schemas: make(map[string]*storepb.SchemaMetadata),
+ tables: make(map[tableKey]*storepb.TableMetadata),
+ views: make(map[viewKey]*storepb.ViewMetadata),
+ functions: make(map[functionKey]*storepb.FunctionMetadata),
+ result: &storepb.DatabaseSchemaMetadata{
+ Name: "",
+ },
+ }
+
+ // Process each statement
+ for _, stmt := range stmts {
+ err := extractor.processStatement(stmt)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ // Build the final metadata structure
+ defaultSchema := &storepb.SchemaMetadata{
+ Name: "",
+ }
+
+ // Add tables to schema
+ var tables []*storepb.TableMetadata
+ for _, table := range extractor.tables {
+ tables = append(tables, table)
+ }
+ slices.SortFunc(tables, func(a, b *storepb.TableMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+ defaultSchema.Tables = tables
+
+ // Add views to schema
+ var views []*storepb.ViewMetadata
+ for _, view := range extractor.views {
+ views = append(views, view)
+ }
+ slices.SortFunc(views, func(a, b *storepb.ViewMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+ defaultSchema.Views = views
+
+ // Add functions to schema
+ var functions []*storepb.FunctionMetadata
+ for _, function := range extractor.functions {
+ functions = append(functions, function)
+ }
+ slices.SortFunc(functions, func(a, b *storepb.FunctionMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+ defaultSchema.Functions = functions
+
+ extractor.result.Schemas = []*storepb.SchemaMetadata{defaultSchema}
+
+ return extractor.result, nil
+}
+
+type tableKey struct {
+ schema string
+ name string
+}
+
+type viewKey struct {
+ schema string
+ name string
+}
+
+type functionKey struct {
+ schema string // nolint:unused
+ name string // nolint:unused
+}
+
+type metadataExtractor struct {
+ schemas map[string]*storepb.SchemaMetadata
+ tables map[tableKey]*storepb.TableMetadata
+ views map[viewKey]*storepb.ViewMetadata
+ functions map[functionKey]*storepb.FunctionMetadata
+
+ result *storepb.DatabaseSchemaMetadata
+}
+
+func (m *metadataExtractor) processStatement(stmt ast.StmtNode) error {
+ switch node := stmt.(type) {
+ case *ast.CreateTableStmt:
+ return m.processCreateTable(node)
+ case *ast.CreateViewStmt:
+ return m.processCreateView(node)
+ case *ast.CreateDatabaseStmt:
+ return m.processCreateDatabase(node)
+ // Add more statement types as needed
+ default:
+ // Ignore unsupported statement types
+ return nil
+ }
+}
+
+func (m *metadataExtractor) processCreateDatabase(stmt *ast.CreateDatabaseStmt) error {
+ dbName := stmt.Name.O
+ m.result.Name = dbName
+
+ // Extract character set and collation from options
+ for _, option := range stmt.Options {
+ switch option.Tp {
+ case ast.DatabaseOptionCharset:
+ m.result.CharacterSet = option.Value
+ case ast.DatabaseOptionCollate:
+ m.result.Collation = option.Value
+ }
+ }
+
+ return nil
+}
+
+func (m *metadataExtractor) processCreateTable(stmt *ast.CreateTableStmt) error {
+ tableName := stmt.Table.Name.O
+ schemaName := ""
+ if stmt.Table.Schema.O != "" {
+ schemaName = stmt.Table.Schema.O
+ }
+
+ table := &storepb.TableMetadata{
+ Name: tableName,
+ Engine: "InnoDB", // Default for TiDB
+ Comment: "",
+ }
+
+ // Process columns
+ for i, col := range stmt.Cols {
+ column := &storepb.ColumnMetadata{
+ Name: col.Name.Name.O,
+ Position: int32(i + 1),
+ Nullable: true, // Default, will be overridden by constraints
+ }
+
+ // Process column type
+ column.Type = m.getColumnType(col.Tp)
+
+ // Process column options
+ for _, option := range col.Options {
+ switch option.Tp {
+ case ast.ColumnOptionNotNull:
+ column.Nullable = false
+ case ast.ColumnOptionNull:
+ column.Nullable = true
+ case ast.ColumnOptionAutoIncrement:
+ column.DefaultExpression = "AUTO_INCREMENT"
+ case ast.ColumnOptionDefaultValue:
+ if defaultValue := m.getDefaultValue(option.Expr); defaultValue != "" {
+ column.DefaultExpression = defaultValue
+ }
+ case ast.ColumnOptionComment:
+ // Handle comment - extract from various expression types
+ if comment := m.extractCommentFromExpr(option.Expr); comment != "" {
+ column.Comment = comment
+ column.UserComment = comment
+ }
+ case ast.ColumnOptionOnUpdate:
+ if onUpdate := m.getExpressionValue(option.Expr); onUpdate != "" {
+ column.OnUpdate = onUpdate
+ }
+ case ast.ColumnOptionGenerated:
+ // Handle generated columns
+ m.processGeneratedColumn(option, column)
+ case ast.ColumnOptionPrimaryKey:
+ // Mark column as primary key
+ column.Nullable = false
+ // We'll handle creating the PRIMARY index after processing all columns
+ case ast.ColumnOptionUniqKey:
+ // Handle unique constraint at column level
+ // We'll handle creating unique indexes after processing all columns
+ }
+ }
+
+ table.Columns = append(table.Columns, column)
+ }
+
+ // Create indexes for column-level constraints
+ m.processColumnLevelConstraints(stmt, table)
+
+ // Process table-level constraints
+ for _, constraint := range stmt.Constraints {
+ switch constraint.Tp {
+ case ast.ConstraintPrimaryKey:
+ index := &storepb.IndexMetadata{
+ Name: "PRIMARY",
+ Primary: true,
+ Unique: true,
+ Visible: true,
+ Type: "BTREE",
+ Expressions: m.getColumnNames(constraint.Keys),
+ }
+ table.Indexes = append(table.Indexes, index)
+
+ case ast.ConstraintKey, ast.ConstraintIndex:
+ index := &storepb.IndexMetadata{
+ Name: constraint.Name,
+ Primary: false,
+ Unique: false,
+ Visible: true,
+ Type: m.getIndexType(constraint),
+ Expressions: m.getColumnNames(constraint.Keys),
+ }
+ table.Indexes = append(table.Indexes, index)
+
+ case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
+ index := &storepb.IndexMetadata{
+ Name: constraint.Name,
+ Primary: false,
+ Unique: true,
+ Visible: true,
+ Type: m.getIndexType(constraint),
+ Expressions: m.getColumnNames(constraint.Keys),
+ }
+ table.Indexes = append(table.Indexes, index)
+
+ case ast.ConstraintForeignKey:
+ fk := &storepb.ForeignKeyMetadata{
+ Name: constraint.Name,
+ Columns: m.getColumnNames(constraint.Keys),
+ ReferencedTable: constraint.Refer.Table.Name.O,
+ ReferencedColumns: m.getColumnNames(constraint.Refer.IndexPartSpecifications),
+ }
+
+ // Handle schema-qualified table references
+ if constraint.Refer.Table.Schema.O != "" {
+ fk.ReferencedSchema = constraint.Refer.Table.Schema.O
+ }
+
+ // Handle ON DELETE and ON UPDATE actions
+ if constraint.Refer.OnDelete != nil {
+ fk.OnDelete = m.getReferenceAction(constraint.Refer.OnDelete.ReferOpt)
+ } else {
+ fk.OnDelete = "NO ACTION" // Default for TiDB/MySQL
+ }
+ if constraint.Refer.OnUpdate != nil {
+ fk.OnUpdate = m.getReferenceAction(constraint.Refer.OnUpdate.ReferOpt)
+ } else {
+ fk.OnUpdate = "NO ACTION" // Default for TiDB/MySQL
+ }
+
+ table.ForeignKeys = append(table.ForeignKeys, fk)
+
+ case ast.ConstraintCheck:
+ // Handle check constraints
+ m.processCheckConstraint(constraint, table)
+ }
+ }
+
+ // Process table options
+ for _, option := range stmt.Options {
+ switch option.Tp {
+ case ast.TableOptionEngine:
+ table.Engine = option.StrValue
+ case ast.TableOptionCharset:
+ table.Charset = option.StrValue
+ case ast.TableOptionCollate:
+ table.Collation = option.StrValue
+ case ast.TableOptionComment:
+ table.Comment = option.StrValue
+ table.UserComment = option.StrValue
+ // Check for TiDB-specific features in the comment
+ m.processTiDBTableComment(option.StrValue, table)
+ case ast.TableOptionAutoIncrement:
+ // Handle AUTO_INCREMENT starting value
+ // Store auto increment value in comment for now
+ // as TableMetadata doesn't have AutoIncrementValue field
+ _ = option.UintValue // Acknowledge the value is available
+ case ast.TableOptionRowFormat:
+ // Handle row format (DYNAMIC, COMPACT, etc.)
+ // Store in comment for now as TableMetadata doesn't have RowFormat field
+ }
+ }
+
+ // Handle TiDB-specific AUTO_RANDOM
+ m.processAutoRandom(stmt, table)
+
+ // Ensure foreign key indexes exist (after all other indexes have been processed)
+ m.ensureForeignKeyIndexes(table)
+
+ key := tableKey{schema: schemaName, name: tableName}
+ m.tables[key] = table
+
+ return nil
+}
+
+func (m *metadataExtractor) processCreateView(stmt *ast.CreateViewStmt) error {
+ viewName := stmt.ViewName.Name.O
+ schemaName := ""
+ if stmt.ViewName.Schema.O != "" {
+ schemaName = stmt.ViewName.Schema.O
+ }
+
+ view := &storepb.ViewMetadata{
+ Name: viewName,
+ Definition: m.extractViewDefinition(stmt),
+ Comment: "",
+ }
+
+ key := viewKey{schema: schemaName, name: viewName}
+ m.views[key] = view
+
+ return nil
+}
+
+// Helper methods
+
+func (*metadataExtractor) getColumnType(tp *types.FieldType) string {
+ if tp == nil {
+ return ""
+ }
+
+ // Get base type name first
+ var baseType string
+ switch tp.GetType() {
+ case mysql.TypeTiny:
+ baseType = "tinyint"
+ case mysql.TypeShort:
+ baseType = "smallint"
+ case mysql.TypeInt24:
+ baseType = "mediumint"
+ case mysql.TypeLong:
+ baseType = "int"
+ case mysql.TypeLonglong:
+ baseType = "bigint"
+ case mysql.TypeFloat:
+ baseType = "float"
+ case mysql.TypeDouble:
+ baseType = "double"
+ case mysql.TypeNewDecimal:
+ baseType = "decimal"
+ case mysql.TypeDate:
+ baseType = "date"
+ case mysql.TypeTimestamp:
+ baseType = "timestamp"
+ case mysql.TypeDatetime:
+ baseType = "datetime"
+ case mysql.TypeYear:
+ baseType = "year"
+ case mysql.TypeVarchar, mysql.TypeVarString:
+ if tp.GetCharset() == "binary" {
+ baseType = "varbinary"
+ } else {
+ baseType = "varchar"
+ }
+ case mysql.TypeString:
+ if tp.GetCharset() == "binary" {
+ baseType = "binary"
+ } else {
+ baseType = "char"
+ }
+ case mysql.TypeTinyBlob:
+ if tp.GetCharset() == "binary" {
+ baseType = "tinyblob"
+ } else {
+ baseType = "tinytext"
+ }
+ case mysql.TypeBlob:
+ if tp.GetCharset() == "binary" {
+ baseType = "blob"
+ } else {
+ baseType = "text"
+ }
+ case mysql.TypeMediumBlob:
+ if tp.GetCharset() == "binary" {
+ baseType = "mediumblob"
+ } else {
+ baseType = "mediumtext"
+ }
+ case mysql.TypeLongBlob:
+ if tp.GetCharset() == "binary" {
+ baseType = "longblob"
+ } else {
+ baseType = "longtext"
+ }
+ case mysql.TypeJSON:
+ baseType = "json"
+ case mysql.TypeEnum, mysql.TypeSet:
+ // For ENUM and SET types, use the full string representation
+ // as it includes the value list: enum('a','b','c') or set('x','y','z')
+ fullType := strings.ToLower(tp.String())
+ return fullType
+ case mysql.TypeBit:
+ baseType = "bit"
+ default:
+ // Fall back to string representation - preserve full type including precision/length
+ fullType := strings.ToLower(tp.String())
+
+ // Normalize common type variations for TiDB compatibility (preserve precision/length)
+ if strings.HasPrefix(fullType, "integer") {
+ return strings.Replace(fullType, "integer", "int", 1)
+ }
+ if strings.HasPrefix(fullType, "numeric") {
+ return strings.Replace(fullType, "numeric", "decimal", 1)
+ }
+ if fullType == "boolean" || fullType == "bool" {
+ return "tinyint(1)"
+ }
+
+ return fullType
+ }
+
+ // Add length/precision information for applicable types
+ if tp.GetFlen() > 0 {
+ switch tp.GetType() {
+ case mysql.TypeVarchar, mysql.TypeVarString, mysql.TypeString:
+ // VARCHAR(n), CHAR(n)
+ return fmt.Sprintf("%s(%d)", baseType, tp.GetFlen())
+ case mysql.TypeNewDecimal:
+ // DECIMAL(precision, scale)
+ if tp.GetDecimal() > 0 {
+ return fmt.Sprintf("%s(%d,%d)", baseType, tp.GetFlen(), tp.GetDecimal())
+ }
+ return fmt.Sprintf("%s(%d)", baseType, tp.GetFlen())
+ case mysql.TypeFloat, mysql.TypeDouble:
+ // FLOAT(precision), DOUBLE(precision)
+ if tp.GetDecimal() > 0 {
+ return fmt.Sprintf("%s(%d,%d)", baseType, tp.GetFlen(), tp.GetDecimal())
+ }
+ case mysql.TypeBit:
+ // BIT(n)
+ return fmt.Sprintf("%s(%d)", baseType, tp.GetFlen())
+ case mysql.TypeTiny:
+ // TINYINT(n) - special case for BOOLEAN which becomes TINYINT(1)
+ return fmt.Sprintf("%s(%d)", baseType, tp.GetFlen())
+ case mysql.TypeYear:
+ // YEAR(4) - MySQL/TiDB YEAR type
+ return fmt.Sprintf("%s(%d)", baseType, tp.GetFlen())
+ }
+ }
+
+ // Special cases for types that should always include length even if GetFlen() returns 0
+ if tp.GetType() == mysql.TypeYear {
+ return "year(4)" // YEAR is always YEAR(4) in MySQL/TiDB
+ }
+
+ return baseType
+}
+
+func (*metadataExtractor) getDefaultValue(expr ast.ExprNode) string {
+ if expr == nil {
+ return ""
+ }
+
+ switch node := expr.(type) {
+ case *ast.FuncCallExpr:
+ return node.FnName.O
+ default:
+ // For other expression types, return the text representation
+ if textNode, ok := expr.(interface{ Text() string }); ok {
+ text := textNode.Text()
+ // Clean up common default value formats
+ text = strings.Trim(text, "'\"")
+ if strings.HasPrefix(text, "_utf8mb4") {
+ // Remove charset prefix
+ if idx := strings.Index(text, "'"); idx != -1 {
+ text = text[idx+1:]
+ text = strings.TrimSuffix(text, "'")
+ }
+ }
+ return text
+ }
+ }
+ return ""
+}
+
+func (*metadataExtractor) getExpressionValue(expr ast.ExprNode) string {
+ if expr == nil {
+ return ""
+ }
+
+ switch node := expr.(type) {
+ case *ast.FuncCallExpr:
+ return node.FnName.O
+ default:
+ // For other expression types, return the text representation
+ if textNode, ok := expr.(interface{ Text() string }); ok {
+ return textNode.Text()
+ }
+ }
+ return ""
+}
+
+func (*metadataExtractor) getColumnNames(keys []*ast.IndexPartSpecification) []string {
+ if keys == nil {
+ return nil
+ }
+
+ var names []string
+ for _, key := range keys {
+ if key.Column != nil {
+ names = append(names, key.Column.Name.O)
+ }
+ }
+ return names
+}
+
+func (*metadataExtractor) getReferenceAction(action model.ReferOptionType) string {
+ switch action {
+ case model.ReferOptionCascade:
+ return "CASCADE"
+ case model.ReferOptionSetNull:
+ return "SET NULL"
+ case model.ReferOptionRestrict:
+ return "RESTRICT"
+ case model.ReferOptionNoAction:
+ return "NO ACTION"
+ case model.ReferOptionSetDefault:
+ return "SET DEFAULT"
+ default:
+ return ""
+ }
+}
+
+func (m *metadataExtractor) processTiDBTableComment(comment string, table *storepb.TableMetadata) {
+ // Process TiDB-specific table comment features like PK_AUTO_RANDOM_BITS
+ pkAutoRandomBitsRegex := regexp.MustCompile(`PK_AUTO_RANDOM_BITS=(\d+)`)
+ if matches := pkAutoRandomBitsRegex.FindStringSubmatch(comment); len(matches) > 1 {
+ // Find the primary key column and set AUTO_RANDOM
+ for _, col := range table.Columns {
+ if m.isPrimaryKeyColumn(col, table) {
+ bits := matches[1]
+ col.DefaultExpression = fmt.Sprintf("AUTO_RANDOM(%s)", bits)
+ break
+ }
+ }
+ }
+}
+
+func (*metadataExtractor) processAutoRandom(_ *ast.CreateTableStmt, _ *storepb.TableMetadata) {
+ // TiDB's AUTO_RANDOM is typically stored in table comments or special constraints
+ // This is a simplified implementation - full AUTO_RANDOM support would require
+ // parsing TiDB-specific syntax extensions
+}
+
+func (*metadataExtractor) isPrimaryKeyColumn(column *storepb.ColumnMetadata, table *storepb.TableMetadata) bool {
+ for _, index := range table.Indexes {
+ if index.Primary {
+ for _, expr := range index.Expressions {
+ if expr == column.Name {
+ return true
+ }
+ }
+ }
+ }
+ return false
+}
+
+// Helper methods for enhanced functionality
+
+func (*metadataExtractor) extractCommentFromExpr(expr ast.ExprNode) string {
+ if expr == nil {
+ return ""
+ }
+
+ // For all expression types, try to get text representation
+ if textNode, ok := expr.(interface{ Text() string }); ok {
+ text := textNode.Text()
+ // Remove quotes from string literals
+ if (strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'")) ||
+ (strings.HasPrefix(text, "\"") && strings.HasSuffix(text, "\"")) {
+ return text[1 : len(text)-1]
+ }
+ return text
+ }
+ return ""
+}
+
+func (*metadataExtractor) processGeneratedColumn(option *ast.ColumnOption, column *storepb.ColumnMetadata) {
+ if option.Expr != nil {
+ // Extract the generation expression
+ var generationExpr string
+ if textNode, ok := option.Expr.(interface{ Text() string }); ok {
+ generationExpr = textNode.Text()
+ }
+
+ // Store generation information in the type or comment
+ if option.Stored {
+ column.Type = column.Type + " GENERATED ALWAYS AS (" + generationExpr + ") STORED"
+ } else {
+ column.Type = column.Type + " GENERATED ALWAYS AS (" + generationExpr + ") VIRTUAL"
+ }
+ }
+}
+
+func (*metadataExtractor) getIndexType(constraint *ast.Constraint) string {
+ // Default to BTREE for most indexes
+ indexType := "BTREE"
+
+ // Check for specific index types in TiDB
+ if constraint.Option != nil {
+ if constraint.Option.Tp == model.IndexTypeHash {
+ indexType = "HASH"
+ } else if constraint.Option.Comment != "" {
+ // Check for FULLTEXT or SPATIAL in comments
+ comment := strings.ToUpper(constraint.Option.Comment)
+ if strings.Contains(comment, "FULLTEXT") {
+ indexType = "FULLTEXT"
+ } else if strings.Contains(comment, "SPATIAL") {
+ indexType = "SPATIAL"
+ }
+ }
+ }
+
+ return indexType
+}
+
+func (*metadataExtractor) processCheckConstraint(constraint *ast.Constraint, table *storepb.TableMetadata) {
+ // TiDB check constraints are handled differently
+ // For now, skip processing as the AST structure may not have ExprInCheck
+ // In a full implementation, we would need to check the constraint structure
+ _ = constraint
+ _ = table
+}
+
+func (*metadataExtractor) extractViewDefinition(stmt *ast.CreateViewStmt) string {
+ if stmt.Select == nil {
+ return "SELECT ..."
+ }
+
+ // For a complete implementation, we would need to reconstruct the SELECT statement
+ // This is a simplified version that returns a placeholder
+ // In a production implementation, you would use the AST to reconstruct the full SELECT
+ if textNode, ok := stmt.Select.(interface{ Text() string }); ok {
+ return textNode.Text()
+ }
+
+ return "SELECT ..."
+}
+
+// processColumnLevelConstraints creates indexes for column-level PRIMARY KEY and UNIQUE constraints
+func (*metadataExtractor) processColumnLevelConstraints(stmt *ast.CreateTableStmt, table *storepb.TableMetadata) {
+ var primaryKeyColumns []string
+ var uniqueConstraints []struct {
+ columnName string
+ indexName string
+ }
+
+ // Find columns with PRIMARY KEY or UNIQUE constraints
+ for i, col := range stmt.Cols {
+ columnName := col.Name.Name.O
+
+ for _, option := range col.Options {
+ switch option.Tp {
+ case ast.ColumnOptionPrimaryKey:
+ primaryKeyColumns = append(primaryKeyColumns, columnName)
+ // Mark the column as not nullable
+ table.Columns[i].Nullable = false
+
+ case ast.ColumnOptionUniqKey:
+ uniqueConstraints = append(uniqueConstraints, struct {
+ columnName string
+ indexName string
+ }{
+ columnName: columnName,
+ indexName: columnName, // Use column name as index name for single-column unique
+ })
+ }
+ }
+ }
+
+ // Create PRIMARY index if we have primary key columns
+ if len(primaryKeyColumns) > 0 {
+ index := &storepb.IndexMetadata{
+ Name: "PRIMARY",
+ Primary: true,
+ Unique: true,
+ Visible: true,
+ Type: "BTREE",
+ Expressions: primaryKeyColumns,
+ }
+ table.Indexes = append(table.Indexes, index)
+ }
+
+ // Create UNIQUE indexes for column-level unique constraints
+ for _, unique := range uniqueConstraints {
+ index := &storepb.IndexMetadata{
+ Name: unique.indexName,
+ Primary: false,
+ Unique: true,
+ Visible: true,
+ Type: "BTREE",
+ Expressions: []string{unique.columnName},
+ }
+ table.Indexes = append(table.Indexes, index)
+ }
+}
+
+// ensureForeignKeyIndexes creates indexes for all foreign key columns if they don't already exist
+func (m *metadataExtractor) ensureForeignKeyIndexes(table *storepb.TableMetadata) {
+ for _, fk := range table.ForeignKeys {
+ m.ensureForeignKeyIndex(fk, table)
+ }
+}
+
+// ensureForeignKeyIndex creates an index for foreign key columns if one doesn't already exist
+func (*metadataExtractor) ensureForeignKeyIndex(fk *storepb.ForeignKeyMetadata, table *storepb.TableMetadata) {
+ // Check if an index already exists that covers the foreign key columns
+ fkColumns := fk.Columns
+
+ for _, existingIndex := range table.Indexes {
+ // Check if this index starts with the foreign key columns
+ if len(existingIndex.Expressions) >= len(fkColumns) {
+ match := true
+ for i, fkCol := range fkColumns {
+ if i >= len(existingIndex.Expressions) || existingIndex.Expressions[i] != fkCol {
+ match = false
+ break
+ }
+ }
+ if match {
+ // An index already exists that covers these columns
+ return
+ }
+ }
+ }
+
+ // No suitable index exists, create one
+ indexName := fk.Name
+ if indexName == "" {
+ // Generate a name based on the columns
+ indexName = strings.Join(fkColumns, "_")
+ }
+
+ index := &storepb.IndexMetadata{
+ Name: indexName,
+ Primary: false,
+ Unique: false,
+ Visible: true,
+ Type: "BTREE",
+ Expressions: fkColumns,
+ }
+
+ table.Indexes = append(table.Indexes, index)
+}
diff --git a/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.go
new file mode 100644
index 0000000000..b6c054f078
--- /dev/null
+++ b/backend/plugin/schema/tidb/get_database_metadata_testcontainer_test.go
@@ -0,0 +1,480 @@
+package tidb
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ tidbdb "github.com/bytebase/bytebase/backend/plugin/db/tidb"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+// TestGetDatabaseMetadataWithTestcontainer tests the get_database_metadata function
+// by comparing its output with the metadata retrieved from a real TiDB instance.
+func TestGetDatabaseMetadataWithTestcontainer(t *testing.T) {
+ ctx := context.Background()
+
+ // Start TiDB container
+ container, err := testcontainer.GetTiDBContainer(ctx)
+ require.NoError(t, err)
+ defer container.Close(ctx)
+
+ // Create test database
+ _, err = container.GetDB().Exec("CREATE DATABASE IF NOT EXISTS test_db")
+ require.NoError(t, err)
+
+ host := container.GetHost()
+ port := container.GetPort()
+
+ // Create TiDB driver for metadata sync
+ driver := &tidbdb.Driver{}
+ config := db.ConnectionConfig{
+ DataSource: &storepb.DataSource{
+ Type: storepb.DataSourceType_ADMIN,
+ Username: "root",
+ Host: host,
+ Port: port,
+ Database: "test_db",
+ },
+ Password: "",
+ ConnectionContext: db.ConnectionContext{
+ EngineVersion: "8.0",
+ DatabaseName: "test_db",
+ },
+ }
+
+ openedDriver, err := driver.Open(ctx, storepb.Engine_TIDB, config)
+ require.NoError(t, err)
+ defer openedDriver.Close(ctx)
+
+ // Cast to TiDB driver for SyncDBSchema
+ tidbDriver, ok := openedDriver.(*tidbdb.Driver)
+ require.True(t, ok, "failed to cast to tidb.Driver")
+
+ // Test cases with various TiDB features
+ testCases := []struct {
+ name string
+ ddl string
+ }{
+ {
+ name: "basic_tables_with_constraints",
+ ddl: `
+CREATE TABLE users (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ username VARCHAR(50) NOT NULL UNIQUE,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
+);
+
+CREATE TABLE posts (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ user_id BIGINT NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ published BOOLEAN DEFAULT false,
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ INDEX idx_user_id (user_id),
+ INDEX idx_published (published)
+);
+`,
+ },
+ {
+ name: "table_with_various_data_types",
+ ddl: `
+CREATE TABLE data_types_test (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ tiny_int_col TINYINT,
+ small_int_col SMALLINT,
+ medium_int_col MEDIUMINT,
+ int_col INT,
+ big_int_col BIGINT,
+ decimal_col DECIMAL(10, 2),
+ float_col FLOAT,
+ double_col DOUBLE,
+ bit_col BIT(8),
+ char_col CHAR(10),
+ varchar_col VARCHAR(100),
+ binary_col BINARY(10),
+ varbinary_col VARBINARY(100),
+ tinytext_col TINYTEXT,
+ text_col TEXT,
+ mediumtext_col MEDIUMTEXT,
+ longtext_col LONGTEXT,
+ tinyblob_col TINYBLOB,
+ blob_col BLOB,
+ mediumblob_col MEDIUMBLOB,
+ longblob_col LONGBLOB,
+ date_col DATE,
+ time_col TIME,
+ datetime_col DATETIME,
+ timestamp_col TIMESTAMP,
+ year_col YEAR,
+ json_col JSON,
+ enum_col ENUM('small', 'medium', 'large'),
+ set_col SET('a', 'b', 'c')
+);
+`,
+ },
+ {
+ name: "table_with_foreign_keys",
+ ddl: `
+CREATE TABLE departments (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+);
+
+CREATE TABLE employees (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ dept_id INT,
+ manager_id INT,
+ CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE RESTRICT,
+ CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id) ON DELETE SET NULL
+);
+`,
+ },
+ {
+ name: "views_and_comments",
+ ddl: `
+CREATE TABLE orders (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ customer_name VARCHAR(100) COMMENT 'Customer full name',
+ amount DECIMAL(10,2) COMMENT 'Order amount in USD',
+ status VARCHAR(20) DEFAULT 'pending'
+) COMMENT='Order management table';
+
+CREATE VIEW active_orders AS
+SELECT id, customer_name, amount
+FROM orders
+WHERE status = 'active';
+`,
+ },
+ {
+ name: "indexes_and_constraints",
+ ddl: `
+CREATE TABLE products (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ price DECIMAL(10,2) NOT NULL,
+ category VARCHAR(50),
+ tags JSON,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ INDEX idx_name (name),
+ INDEX idx_price_category (price, category),
+ UNIQUE INDEX idx_unique_name (name),
+ FULLTEXT INDEX idx_description (description)
+);
+`,
+ },
+ {
+ name: "tidb_auto_random",
+ ddl: `
+CREATE TABLE auto_random_test (
+ id BIGINT /*T![auto_rand] AUTO_RANDOM(5) */ PRIMARY KEY,
+ name VARCHAR(100),
+ data JSON
+) COMMENT='PK_AUTO_RANDOM_BITS=5';
+`,
+ },
+ {
+ name: "complex_table_options",
+ ddl: `
+CREATE TABLE table_options_test (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ data TEXT
+) ENGINE=InnoDB
+ DEFAULT CHARSET=utf8mb4
+ COLLATE=utf8mb4_general_ci
+ AUTO_INCREMENT=1000
+ COMMENT='Table with various TiDB options';
+`,
+ },
+ {
+ name: "self_referencing_foreign_keys",
+ ddl: `
+CREATE TABLE categories (
+ id INT AUTO_INCREMENT PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ parent_id INT,
+ CONSTRAINT fk_parent FOREIGN KEY (parent_id) REFERENCES categories(id) ON DELETE CASCADE
+);
+`,
+ },
+ {
+ name: "tidb_clustered_index",
+ ddl: `
+CREATE TABLE clustered_test (
+ id INT PRIMARY KEY CLUSTERED,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100)
+);
+
+CREATE TABLE non_clustered_test (
+ id INT PRIMARY KEY NONCLUSTERED,
+ name VARCHAR(100) NOT NULL,
+ data TEXT
+);
+`,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Clean up any existing objects from previous tests
+ _, err := container.GetDB().ExecContext(ctx, "DROP DATABASE IF EXISTS test_db")
+ require.NoError(t, err)
+ _, err = container.GetDB().ExecContext(ctx, "CREATE DATABASE test_db")
+ require.NoError(t, err)
+
+ // Execute DDL using the driver
+ _, err = openedDriver.Execute(ctx, tc.ddl, db.ExecuteOptions{})
+ require.NoError(t, err)
+
+ // Get metadata from live database using driver
+ dbMetadata, err := tidbDriver.SyncDBSchema(ctx)
+ require.NoError(t, err)
+
+ // Get metadata from parser
+ parsedMetadata, err := GetDatabaseMetadata(tc.ddl)
+ require.NoError(t, err)
+
+ // Compare metadata
+ compareMetadata(t, dbMetadata, parsedMetadata, tc.name)
+ })
+ }
+}
+
+// compareMetadata compares the metadata from the live database with the parsed metadata
+func compareMetadata(t *testing.T, dbMeta, parsedMeta *storepb.DatabaseSchemaMetadata, testName string) {
+ // Normalize both metadata for comparison
+ normalizeParserMetadata(dbMeta)
+ normalizeParserMetadata(parsedMeta)
+
+ // For TiDB, we only have one schema
+ require.Equal(t, 1, len(parsedMeta.Schemas), "parsed metadata should have exactly one schema")
+
+ dbSchema := dbMeta.Schemas[0]
+ parsedSchema := parsedMeta.Schemas[0]
+
+ // Compare tables
+ require.Equal(t, len(dbSchema.Tables), len(parsedSchema.Tables),
+ "mismatch in number of tables for test %s", testName)
+
+ // Create a map for easier lookup
+ dbTableMap := make(map[string]*storepb.TableMetadata)
+ for _, table := range dbSchema.Tables {
+ dbTableMap[table.Name] = table
+ }
+
+ for _, parsedTable := range parsedSchema.Tables {
+ dbTable, exists := dbTableMap[parsedTable.Name]
+ require.True(t, exists, "table %s not found in database metadata", parsedTable.Name)
+
+ // Compare basic table properties
+ require.Equal(t, dbTable.Engine, parsedTable.Engine,
+ "engine mismatch for table %s", parsedTable.Name)
+
+ // Compare columns
+ compareColumns(t, dbTable.Columns, parsedTable.Columns, parsedTable.Name)
+
+ // Compare indexes
+ compareIndexes(t, dbTable.Indexes, parsedTable.Indexes, parsedTable.Name)
+
+ // Compare foreign keys
+ compareForeignKeys(t, dbTable.ForeignKeys, parsedTable.ForeignKeys, parsedTable.Name)
+ }
+
+ // Compare views
+ compareViews(t, dbSchema.Views, parsedSchema.Views)
+}
+
+func compareColumns(t *testing.T, dbColumns, parsedColumns []*storepb.ColumnMetadata, tableName string) {
+ require.Equal(t, len(dbColumns), len(parsedColumns),
+ "column count mismatch for table %s", tableName)
+
+ // Create a map for easier lookup
+ dbColumnMap := make(map[string]*storepb.ColumnMetadata)
+ for _, col := range dbColumns {
+ dbColumnMap[col.Name] = col
+ }
+
+ for _, parsedCol := range parsedColumns {
+ dbCol, exists := dbColumnMap[parsedCol.Name]
+ require.True(t, exists, "column %s not found in database metadata for table %s", parsedCol.Name, tableName)
+
+ // Compare basic column properties
+ require.Equal(t, dbCol.Type, parsedCol.Type,
+ "type mismatch for column %s.%s", tableName, parsedCol.Name)
+ require.Equal(t, dbCol.Nullable, parsedCol.Nullable,
+ "nullable mismatch for column %s.%s", tableName, parsedCol.Name)
+ require.Equal(t, dbCol.Position, parsedCol.Position,
+ "position mismatch for column %s.%s", tableName, parsedCol.Name)
+
+ // Compare default expressions (with normalization)
+ normalizeDefaultExpression(dbCol)
+ normalizeDefaultExpression(parsedCol)
+ require.Equal(t, dbCol.DefaultExpression, parsedCol.DefaultExpression,
+ "default expression mismatch for column %s.%s", tableName, parsedCol.Name)
+ }
+}
+
+func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetadata, tableName string) {
+ require.Equal(t, len(dbIndexes), len(parsedIndexes),
+ "index count mismatch for table %s", tableName)
+
+ // Create a map for easier lookup
+ dbIndexMap := make(map[string]*storepb.IndexMetadata)
+ for _, idx := range dbIndexes {
+ dbIndexMap[idx.Name] = idx
+ }
+
+ for _, parsedIdx := range parsedIndexes {
+ dbIdx, exists := dbIndexMap[parsedIdx.Name]
+ require.True(t, exists, "index %s not found in database metadata for table %s", parsedIdx.Name, tableName)
+
+ require.Equal(t, dbIdx.Primary, parsedIdx.Primary,
+ "primary flag mismatch for index %s.%s", tableName, parsedIdx.Name)
+ require.Equal(t, dbIdx.Unique, parsedIdx.Unique,
+ "unique flag mismatch for index %s.%s", tableName, parsedIdx.Name)
+ require.Equal(t, dbIdx.Expressions, parsedIdx.Expressions,
+ "expressions mismatch for index %s.%s", tableName, parsedIdx.Name)
+
+ // Type comparison with normalization
+ require.Equal(t, normalizeIndexType(dbIdx.Type), normalizeIndexType(parsedIdx.Type),
+ "type mismatch for index %s.%s", tableName, parsedIdx.Name)
+ }
+}
+
+func compareForeignKeys(t *testing.T, dbFKs, parsedFKs []*storepb.ForeignKeyMetadata, tableName string) {
+ require.Equal(t, len(dbFKs), len(parsedFKs),
+ "foreign key count mismatch for table %s", tableName)
+
+ // Create a map for easier lookup
+ dbFKMap := make(map[string]*storepb.ForeignKeyMetadata)
+ for _, fk := range dbFKs {
+ dbFKMap[fk.Name] = fk
+ }
+
+ for _, parsedFK := range parsedFKs {
+ dbFK, exists := dbFKMap[parsedFK.Name]
+ require.True(t, exists, "foreign key %s not found in database metadata for table %s", parsedFK.Name, tableName)
+
+ require.Equal(t, dbFK.Columns, parsedFK.Columns,
+ "columns mismatch for foreign key %s.%s", tableName, parsedFK.Name)
+ require.Equal(t, dbFK.ReferencedTable, parsedFK.ReferencedTable,
+ "referenced table mismatch for foreign key %s.%s", tableName, parsedFK.Name)
+ require.Equal(t, dbFK.ReferencedColumns, parsedFK.ReferencedColumns,
+ "referenced columns mismatch for foreign key %s.%s", tableName, parsedFK.Name)
+ require.Equal(t, dbFK.OnDelete, parsedFK.OnDelete,
+ "on delete mismatch for foreign key %s.%s", tableName, parsedFK.Name)
+ require.Equal(t, dbFK.OnUpdate, parsedFK.OnUpdate,
+ "on update mismatch for foreign key %s.%s", tableName, parsedFK.Name)
+ }
+}
+
+func compareViews(t *testing.T, dbViews, parsedViews []*storepb.ViewMetadata) {
+ require.Equal(t, len(dbViews), len(parsedViews), "view count mismatch")
+
+ // Create a map for easier lookup
+ dbViewMap := make(map[string]*storepb.ViewMetadata)
+ for _, view := range dbViews {
+ dbViewMap[view.Name] = view
+ }
+
+ for _, parsedView := range parsedViews {
+ dbView, exists := dbViewMap[parsedView.Name]
+ require.True(t, exists, "view %s not found in database metadata", parsedView.Name)
+
+ // View definitions might have formatting differences, so we do a basic check
+ require.NotEmpty(t, parsedView.Definition, "parsed view definition should not be empty for %s", parsedView.Name)
+ require.Contains(t, strings.ToLower(parsedView.Definition), "select",
+ "parsed view definition should contain SELECT for %s", parsedView.Name)
+
+ // Also check that database view has definition
+ require.NotEmpty(t, dbView.Definition, "database view definition should not be empty for %s", dbView.Name)
+ }
+}
+
+// normalizeParserMetadata normalizes metadata for comparison between parser and database
+func normalizeParserMetadata(metadata *storepb.DatabaseSchemaMetadata) {
+ if metadata == nil {
+ return
+ }
+
+ for _, schema := range metadata.Schemas {
+ for _, table := range schema.Tables {
+ // Normalize charset and collation since they may vary
+ table.Charset = ""
+ table.Collation = ""
+
+ for _, col := range table.Columns {
+ // Normalize default expressions
+ normalizeDefaultExpression(col)
+
+ // Clear comment fields that may not match exactly
+ if col.Comment == "" {
+ col.UserComment = ""
+ }
+ }
+
+ for _, idx := range table.Indexes {
+ // Normalize index types
+ idx.Type = normalizeIndexType(idx.Type)
+ }
+
+ for _, fk := range table.ForeignKeys {
+ // Ensure consistent foreign key actions
+ if fk.OnDelete == "" {
+ fk.OnDelete = "NO ACTION"
+ }
+ if fk.OnUpdate == "" {
+ fk.OnUpdate = "NO ACTION"
+ }
+ }
+ }
+ }
+}
+
+func normalizeDefaultExpression(col *storepb.ColumnMetadata) {
+ if col.DefaultExpression == "" {
+ return
+ }
+
+ // Normalize common default value formats
+ expr := col.DefaultExpression
+
+ // Remove charset prefixes
+ if strings.HasPrefix(expr, "_utf8mb4") {
+ if idx := strings.Index(expr, "'"); idx != -1 {
+ expr = expr[idx:]
+ }
+ }
+
+ // Remove quotes from string literals
+ expr = strings.Trim(expr, "'\"")
+
+ // Normalize boolean values
+ if expr == "0" && col.Type == "tinyint" {
+ expr = "false"
+ }
+ if expr == "1" && col.Type == "tinyint" {
+ expr = "true"
+ }
+
+ col.DefaultExpression = expr
+}
+
+func normalizeIndexType(indexType string) string {
+ // TiDB always uses BTREE for most indexes
+ if indexType == "" {
+ return "BTREE"
+ }
+ return strings.ToUpper(indexType)
+}