Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: introduce new sdl diff framework and support CREATE/DROP table (#17402)
rebelice7599a1e9ef24
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex cc5025610b..f9cc29b1ec 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -4,6 +4,8 @@ import ("slices""strings"+ parser "github.com/bytebase/parser/postgresql"+"github.com/bytebase/bytebase/backend/common"storepb "github.com/bytebase/bytebase/backend/generated-go/store""github.com/bytebase/bytebase/backend/store/model"@@ -68,6 +70,10 @@ type TableDiff struct {OldTable *storepb.TableMetadataNewTable *storepb.TableMetadata+ // AST nodes for DDL analysis and generation+ OldASTNode *parser.CreatestmtContext // Previous user CREATE TABLE AST node+ NewASTNode *parser.CreatestmtContext // Current user CREATE TABLE AST node+// Column changesColumnChanges []*ColumnDiffdiff --git a/backend/plugin/schema/pg/chunk_extraction_test.go b/backend/plugin/schema/pg/chunk_extraction_test.gonew file mode 100644index 0000000000..df08261a79--- /dev/null+++ b/backend/plugin/schema/pg/chunk_extraction_test.go@@ -0,0 +1,274 @@+package pg++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ parser "github.com/bytebase/parser/postgresql"++ "github.com/bytebase/bytebase/backend/plugin/schema"+)++func TestChunkSDLTextExtraction(t *testing.T) {+ testCases := []struct {+ name string+ sdlText string+ expectedResults map[string]string // chunk type:identifier -> expected text+ }{+ {+ name: "Single table extraction",+ sdlText: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+);`,+ expectedResults: map[string]string{+ "TABLE:users": `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+)`,+ },+ },+ {+ name: "Multiple statements extraction",+ sdlText: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+);++CREATE INDEX idx_users_name ON users(name);++CREATE SEQUENCE user_seq START 1;`,+ expectedResults: map[string]string{+ "TABLE:users": `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+)`,+ "INDEX:idx_users_name": `CREATE INDEX idx_users_name ON users(name)`,+ "SEQUENCE:user_seq": `CREATE SEQUENCE user_seq START 1`,+ },+ },+ {+ name: "Function extraction",+ sdlText: `CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql;`,+ expectedResults: map[string]string{+ "FUNCTION:get_user_count": `CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ {+ name: "View with qualified name",+ sdlText: `CREATE VIEW public.active_users AS+SELECT * FROM users WHERE active = true;`,+ expectedResults: map[string]string{+ "VIEW:public.active_users": `CREATE VIEW public.active_users AS+SELECT * FROM users WHERE active = true`,+ },+ },+ {+ name: "Complex mixed statements",+ sdlText: `CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL,+ price DECIMAL(10,2)+);++CREATE VIEW product_summary AS+SELECT id, name, price+FROM products+WHERE price > 0;++CREATE INDEX idx_products_price ON products(price);++CREATE FUNCTION calculate_discount(amount DECIMAL) RETURNS DECIMAL AS $$+BEGIN+ RETURN amount * 0.9;+END;+$$ LANGUAGE plpgsql;++CREATE SEQUENCE product_seq START 100;`,+ expectedResults: map[string]string{+ "TABLE:products": `CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL,+ price DECIMAL(10,2)+)`,+ "VIEW:product_summary": `CREATE VIEW product_summary AS+SELECT id, name, price+FROM products+WHERE price > 0`,+ "INDEX:idx_products_price": `CREATE INDEX idx_products_price ON products(price)`,+ "FUNCTION:calculate_discount": `CREATE FUNCTION calculate_discount(amount DECIMAL) RETURNS DECIMAL AS $$+BEGIN+ RETURN amount * 0.9;+END;+$$ LANGUAGE plpgsql`,+ "SEQUENCE:product_seq": `CREATE SEQUENCE product_seq START 100`,+ },+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ // Extract chunks from SDL text+ chunks, err := ChunkSDLText(tc.sdlText)+ require.NoError(t, err, "Should successfully chunk SDL text")+ require.NotNil(t, chunks, "Chunks should not be nil")+ require.NotNil(t, chunks.Tokens, "Token stream should not be nil")++ // Build a map of all chunks with type:identifier keys+ allChunks := make(map[string]*schema.SDLChunk)+ for id, chunk := range chunks.Tables {+ allChunks["TABLE:"+id] = chunk+ }+ for id, chunk := range chunks.Views {+ allChunks["VIEW:"+id] = chunk+ }+ for id, chunk := range chunks.Functions {+ allChunks["FUNCTION:"+id] = chunk+ }+ for id, chunk := range chunks.Indexes {+ allChunks["INDEX:"+id] = chunk+ }+ for id, chunk := range chunks.Sequences {+ allChunks["SEQUENCE:"+id] = chunk+ }++ // Verify we have the expected number of chunks+ assert.Equal(t, len(tc.expectedResults), len(allChunks),+ "Expected %d chunks, got %d", len(tc.expectedResults), len(allChunks))++ // Verify each expected chunk+ for expectedKey, expectedText := range tc.expectedResults {+ chunk, exists := allChunks[expectedKey]+ require.True(t, exists, "Expected chunk with key %s not found", expectedKey)++ // Verify chunk has required fields+ assert.NotEmpty(t, chunk.Identifier, "Chunk identifier should not be empty")+ assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil")++ // Extract text using GetText method and compare+ actualText := chunk.GetText(chunks.Tokens)+ require.NotEmpty(t, actualText, "GetText should return non-empty text")++ // Normalize whitespace for comparison+ actualTextNormalized := strings.TrimSpace(actualText)+ expectedTextNormalized := strings.TrimSpace(expectedText)++ assert.Equal(t, expectedTextNormalized, actualTextNormalized,+ "Text mismatch for chunk %s.\nExpected:\n%s\nActual:\n%s",+ expectedKey, expectedTextNormalized, actualTextNormalized)++ // Verify AST node type matches chunk type+ switch {+ case strings.HasPrefix(expectedKey, "TABLE:"):+ _, ok := chunk.ASTNode.(*parser.CreatestmtContext)+ assert.True(t, ok, "TABLE chunk should have CreatestmtContext AST node")+ case strings.HasPrefix(expectedKey, "INDEX:"):+ _, ok := chunk.ASTNode.(*parser.IndexstmtContext)+ assert.True(t, ok, "INDEX chunk should have IndexstmtContext AST node")+ case strings.HasPrefix(expectedKey, "SEQUENCE:"):+ _, ok := chunk.ASTNode.(*parser.CreateseqstmtContext)+ assert.True(t, ok, "SEQUENCE chunk should have CreateseqstmtContext AST node")+ case strings.HasPrefix(expectedKey, "FUNCTION:"):+ _, ok := chunk.ASTNode.(*parser.CreatefunctionstmtContext)+ assert.True(t, ok, "FUNCTION chunk should have CreatefunctionstmtContext AST node")+ case strings.HasPrefix(expectedKey, "VIEW:"):+ _, ok := chunk.ASTNode.(*parser.ViewstmtContext)+ assert.True(t, ok, "VIEW chunk should have ViewstmtContext AST node")+ default:+ assert.Fail(t, "Unknown chunk type: %s", expectedKey)+ }+ }+ })+ }+}++func TestChunkSDLTextEdgeCases(t *testing.T) {+ testCases := []struct {+ name string+ sdlText string+ expectedChunks int+ shouldError bool+ }{+ {+ name: "Empty SDL text",+ sdlText: "",+ expectedChunks: 0,+ shouldError: false,+ },+ {+ name: "Whitespace only",+ sdlText: " \n\t ",+ expectedChunks: 0,+ shouldError: false,+ },+ {+ name: "CREATE INDEX without name (should be skipped)",+ sdlText: `CREATE TABLE users (id SERIAL);+CREATE INDEX ON users(id);`,+ expectedChunks: 1, // Only table, index without name is skipped+ shouldError: false,+ },+ {+ name: "Schema-qualified identifiers",+ sdlText: `CREATE TABLE public.users (id SERIAL);+CREATE TABLE admin.settings (key VARCHAR);`,+ expectedChunks: 2,+ shouldError: false,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ chunks, err := ChunkSDLText(tc.sdlText)++ if tc.shouldError {+ assert.Error(t, err, "Should return error")+ return+ }++ require.NoError(t, err, "Should not return error")+ require.NotNil(t, chunks, "Chunks should not be nil")++ // Count total chunks+ totalChunks := len(chunks.Tables) + len(chunks.Views) + len(chunks.Functions) ++ len(chunks.Indexes) + len(chunks.Sequences)++ assert.Equal(t, tc.expectedChunks, totalChunks,+ "Expected %d chunks, got %d", tc.expectedChunks, totalChunks)+ })+ }+}++func TestChunkGetTextMethod(t *testing.T) {+ sdlText := `CREATE TABLE test_table (+ id INTEGER PRIMARY KEY,+ data TEXT+);`++ chunks, err := ChunkSDLText(sdlText)+ require.NoError(t, err)+ require.Contains(t, chunks.Tables, "test_table")++ chunk := chunks.Tables["test_table"]++ // Test GetText method+ text := chunk.GetText(chunks.Tokens)+ assert.NotEmpty(t, text, "GetText should return non-empty text")+ assert.Contains(t, text, "CREATE TABLE test_table", "Text should contain table creation")+ assert.Contains(t, text, "id INTEGER PRIMARY KEY", "Text should contain column definition")++ // Test with nil tokens (should handle gracefully)+ emptyText := chunk.GetText(nil)+ assert.Empty(t, emptyText, "GetText with nil tokens should return empty string")+}diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.gonew file mode 100644index 0000000000..e21a68543e--- /dev/null+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -0,0 +1,261 @@+package pg++import (+ "strings"++ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ parser "github.com/bytebase/parser/postgresql"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"+ "github.com/bytebase/bytebase/backend/plugin/schema"+ "github.com/bytebase/bytebase/backend/store/model"+)++func init() {+ schema.RegisterGetSDLDiff(storepb.Engine_POSTGRES, GetSDLDiff)+ schema.RegisterGetSDLDiff(storepb.Engine_COCKROACHDB, GetSDLDiff)+}++func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseSchema) (*schema.MetadataDiff, error) {+ currentChunks, err := ChunkSDLText(currentSDLText)+ if err != nil {+ return nil, errors.Wrap(err, "failed to chunk current SDL text")+ }++ previousChunks, err := ChunkSDLText(previousUserSDLText)+ if err != nil {+ return nil, errors.Wrap(err, "failed to chunk previous SDL text")+ }++ // Initialize MetadataDiff+ diff := &schema.MetadataDiff{+ DatabaseName: "",+ SchemaChanges: []*schema.SchemaDiff{},+ TableChanges: []*schema.TableDiff{},+ ViewChanges: []*schema.ViewDiff{},+ MaterializedViewChanges: []*schema.MaterializedViewDiff{},+ FunctionChanges: []*schema.FunctionDiff{},+ ProcedureChanges: []*schema.ProcedureDiff{},+ SequenceChanges: []*schema.SequenceDiff{},+ EnumTypeChanges: []*schema.EnumTypeDiff{},+ }++ // Process table changes+ err = processTableChanges(currentChunks, previousChunks, currentSchema, previousSchema, diff)+ if err != nil {+ return nil, errors.Wrap(err, "failed to process table changes")+ }++ return diff, nil+}++func ChunkSDLText(sdlText string) (*schema.SDLChunks, error) {+ if strings.TrimSpace(sdlText) == "" {+ return &schema.SDLChunks{+ Tables: make(map[string]*schema.SDLChunk),+ Views: make(map[string]*schema.SDLChunk),+ Functions: make(map[string]*schema.SDLChunk),+ Indexes: make(map[string]*schema.SDLChunk),+ Sequences: make(map[string]*schema.SDLChunk),+ Tokens: nil,+ }, nil+ }++ parseResult, err := pgparser.ParsePostgreSQL(sdlText)+ if err != nil {+ return nil, errors.Wrap(err, "failed to parse SDL text")+ }++ extractor := &sdlChunkExtractor{+ sdlText: sdlText,+ chunks: &schema.SDLChunks{+ Tables: make(map[string]*schema.SDLChunk),+ Views: make(map[string]*schema.SDLChunk),+ Functions: make(map[string]*schema.SDLChunk),+ Indexes: make(map[string]*schema.SDLChunk),+ Sequences: make(map[string]*schema.SDLChunk),+ Tokens: parseResult.Tokens,+ },+ tokens: parseResult.Tokens,+ }++ antlr.ParseTreeWalkerDefault.Walk(extractor, parseResult.Tree)++ return extractor.chunks, nil+}++type sdlChunkExtractor struct {+ *parser.BasePostgreSQLParserListener+ sdlText string+ chunks *schema.SDLChunks+ tokens *antlr.CommonTokenStream+}++func (l *sdlChunkExtractor) EnterCreatestmt(ctx *parser.CreatestmtContext) {+ if ctx.Qualified_name(0) == nil {+ return+ }++ identifier := pgparser.NormalizePostgreSQLQualifiedName(ctx.Qualified_name(0))+ identifierStr := strings.Join(identifier, ".")++ chunk := &schema.SDLChunk{+ Identifier: identifierStr,+ ASTNode: ctx,+ }++ l.chunks.Tables[identifierStr] = chunk+}++func (l *sdlChunkExtractor) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext) {+ if ctx.Qualified_name() == nil {+ return+ }++ identifier := pgparser.NormalizePostgreSQLQualifiedName(ctx.Qualified_name())+ identifierStr := strings.Join(identifier, ".")++ chunk := &schema.SDLChunk{+ Identifier: identifierStr,+ ASTNode: ctx,+ }++ l.chunks.Sequences[identifierStr] = chunk+}++func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {+ funcNameCtx := ctx.Func_name()+ if funcNameCtx == nil {+ return+ }++ // Extract function name directly from the text+ funcName := funcNameCtx.GetText()+ if funcName == "" {+ return+ }++ chunk := &schema.SDLChunk{+ Identifier: funcName,+ ASTNode: ctx,+ }++ l.chunks.Functions[funcName] = chunk+}++func (l *sdlChunkExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {+ // Check if this is CREATE INDEX+ if ctx.CREATE() == nil || ctx.INDEX() == nil {+ return+ }++ // Extract index name+ var indexName string+ if name := ctx.Name(); name != nil {+ indexName = pgparser.NormalizePostgreSQLName(name)+ }++ // If no explicit name, we skip it as PostgreSQL will generate one+ if indexName == "" {+ return+ }++ chunk := &schema.SDLChunk{+ Identifier: indexName,+ ASTNode: ctx,+ }++ l.chunks.Indexes[indexName] = chunk+}++func (l *sdlChunkExtractor) EnterViewstmt(ctx *parser.ViewstmtContext) {+ if ctx.Qualified_name() == nil {+ return+ }++ identifier := pgparser.NormalizePostgreSQLQualifiedName(ctx.Qualified_name())+ identifierStr := strings.Join(identifier, ".")++ chunk := &schema.SDLChunk{+ Identifier: identifierStr,+ ASTNode: ctx,+ }++ l.chunks.Views[identifierStr] = chunk+}++// processTableChanges processes changes to tables by comparing SDL chunks+// nolint:unparam+func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema, diff *schema.MetadataDiff) error {+ // TODO: currentSchema and previousSchema will be used later for SDL drift detection+ _ = currentSchema+ _ = previousSchema++ // Process current table chunks to find created and modified tables+ for identifier, currentChunk := range currentChunks.Tables {+ schemaName, tableName := parseTableIdentifier(currentChunk.Identifier)++ if previousChunk, exists := previousChunks.Tables[identifier]; exists {+ // Table exists in both - check if modified+ currentText := currentChunk.GetText(currentChunks.Tokens)+ previousText := previousChunk.GetText(previousChunks.Tokens)+ if currentText != previousText {+ // Table was modified+ tableDiff := &schema.TableDiff{+ Action: schema.MetadataDiffActionAlter,+ SchemaName: schemaName,+ TableName: tableName,+ OldTable: nil, // Will be populated when SDL drift detection is implemented+ NewTable: nil, // Will be populated when SDL drift detection is implemented+ OldASTNode: previousChunk.ASTNode.(*parser.CreatestmtContext),+ NewASTNode: currentChunk.ASTNode.(*parser.CreatestmtContext),+ }+ diff.TableChanges = append(diff.TableChanges, tableDiff)+ }+ } else {+ // New table+ tableDiff := &schema.TableDiff{+ Action: schema.MetadataDiffActionCreate,+ SchemaName: schemaName,+ TableName: tableName,+ OldTable: nil,+ NewTable: nil, // Will be populated when SDL drift detection is implemented+ OldASTNode: nil,+ NewASTNode: currentChunk.ASTNode.(*parser.CreatestmtContext),+ }+ diff.TableChanges = append(diff.TableChanges, tableDiff)+ }+ }++ // Process previous table chunks to find dropped tables+ for identifier, previousChunk := range previousChunks.Tables {+ if _, exists := currentChunks.Tables[identifier]; !exists {+ // Table was dropped+ schemaName, tableName := parseTableIdentifier(previousChunk.Identifier)+ tableDiff := &schema.TableDiff{+ Action: schema.MetadataDiffActionDrop,+ SchemaName: schemaName,+ TableName: tableName,+ OldTable: nil, // Will be populated when SDL drift detection is implemented+ NewTable: nil,+ OldASTNode: previousChunk.ASTNode.(*parser.CreatestmtContext),+ NewASTNode: nil,+ }+ diff.TableChanges = append(diff.TableChanges, tableDiff)+ }+ }++ return nil+}++// parseTableIdentifier parses a table identifier and returns schema name and table name+func parseTableIdentifier(identifier string) (schemaName, tableName string) {+ parts := strings.Split(identifier, ".")+ if len(parts) == 2 {+ return parts[0], parts[1]+ }+ return "public", identifier+}diff --git a/backend/plugin/schema/pg/sdl_diff_table_test.go b/backend/plugin/schema/pg/sdl_diff_table_test.gonew file mode 100644index 0000000000..8b261efc9d--- /dev/null+++ b/backend/plugin/schema/pg/sdl_diff_table_test.go@@ -0,0 +1,167 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/plugin/schema"+)++func TestTableDiffScenarios(t *testing.T) {+ testCases := []struct {+ name string+ currentSDL string+ previousSDL string+ expectedCreateCount int+ expectedAlterCount int+ expectedDropCount int+ expectedTableNames []string+ }{+ {+ name: "Create new table",+ currentSDL: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );`,+ previousSDL: "",+ expectedCreateCount: 1,+ expectedAlterCount: 0,+ expectedDropCount: 0,+ expectedTableNames: []string{"users"},+ },+ {+ name: "Drop existing table",+ currentSDL: "",+ previousSDL: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );`,+ expectedCreateCount: 0,+ expectedAlterCount: 0,+ expectedDropCount: 1,+ expectedTableNames: []string{"users"},+ },+ {+ name: "Modify existing table",+ currentSDL: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL,+ email VARCHAR(255)+ );`,+ previousSDL: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );`,+ expectedCreateCount: 0,+ expectedAlterCount: 1,+ expectedDropCount: 0,+ expectedTableNames: []string{"users"},+ },+ {+ name: "Mixed operations",+ currentSDL: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL,+ email VARCHAR(255)+ );++ CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );`,+ previousSDL: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE TABLE old_table (+ id SERIAL PRIMARY KEY+ );`,+ expectedCreateCount: 1, // products+ expectedAlterCount: 1, // users+ expectedDropCount: 1, // old_table+ expectedTableNames: []string{"users", "products", "old_table"},+ },+ {+ name: "Schema qualified tables",+ currentSDL: `CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE TABLE admin.settings (+ key VARCHAR(255) PRIMARY KEY,+ value TEXT+ );`,+ previousSDL: `CREATE TABLE public.users (+ id SERIAL PRIMARY KEY+ );`,+ expectedCreateCount: 1, // admin.settings+ expectedAlterCount: 1, // public.users+ expectedDropCount: 0,+ expectedTableNames: []string{"users", "settings"},+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil, nil)+ require.NoError(t, err)++ // Count different action types+ createCount := 0+ alterCount := 0+ dropCount := 0++ for _, change := range diff.TableChanges {+ switch change.Action {+ case schema.MetadataDiffActionCreate:+ createCount+++ case schema.MetadataDiffActionAlter:+ alterCount+++ case schema.MetadataDiffActionDrop:+ dropCount+++ default:+ // Should not reach here with valid actions+ }+ }++ assert.Equal(t, tc.expectedCreateCount, createCount, "CREATE count mismatch")+ assert.Equal(t, tc.expectedAlterCount, alterCount, "ALTER count mismatch")+ assert.Equal(t, tc.expectedDropCount, dropCount, "DROP count mismatch")++ // Verify table names+ actualTableNames := make([]string, len(diff.TableChanges))+ for i, change := range diff.TableChanges {+ actualTableNames[i] = change.TableName+ }++ assert.ElementsMatch(t, tc.expectedTableNames, actualTableNames, "Table names mismatch")++ // Verify schema names are set correctly+ for _, change := range diff.TableChanges {+ assert.NotEmpty(t, change.SchemaName, "Schema name should not be empty")+ }++ // Verify AST nodes are populated correctly+ for _, change := range diff.TableChanges {+ switch change.Action {+ case schema.MetadataDiffActionCreate:+ assert.Nil(t, change.OldASTNode, "CREATE action should have nil OldASTNode")+ assert.NotNil(t, change.NewASTNode, "CREATE action should have NewASTNode")+ case schema.MetadataDiffActionAlter:+ assert.NotNil(t, change.OldASTNode, "ALTER action should have OldASTNode")+ assert.NotNil(t, change.NewASTNode, "ALTER action should have NewASTNode")+ assert.NotEqual(t, change.OldASTNode, change.NewASTNode, "ALTER action should have different OldASTNode and NewASTNode")+ case schema.MetadataDiffActionDrop:+ assert.NotNil(t, change.OldASTNode, "DROP action should have OldASTNode")+ assert.Nil(t, change.NewASTNode, "DROP action should have nil NewASTNode")+ default:+ // Should not reach here with valid actions+ }+ }+ })+ }+}diff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.goindex bb2ee75551..2386155f50 100644--- a/backend/plugin/schema/schema.go+++ b/backend/plugin/schema/schema.go@@ -7,6 +7,7 @@ import ("github.com/pkg/errors"storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store/model")var (@@ -21,6 +22,7 @@ var (getSequenceDefinitions = make(map[storepb.Engine]getSequenceDefinition)getDatabaseMetadataMap = make(map[storepb.Engine]getDatabaseMetadata)generateMigrations = make(map[storepb.Engine]generateMigration)+ getSDLDiffs = make(map[storepb.Engine]getSDLDiff))type getDatabaseDefinition func(GetDefinitionContext, *storepb.DatabaseSchemaMetadata) (string, error)@@ -33,6 +35,7 @@ type getProcedureDefinition func(string, *storepb.ProcedureMetadata) (string, ertype getSequenceDefinition func(string, *storepb.SequenceMetadata) (string, error)type getDatabaseMetadata func(string) (*storepb.DatabaseSchemaMetadata, error)type generateMigration func(*MetadataDiff) (string, error)+type getSDLDiff func(currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseSchema) (*MetadataDiff, error)type GetDefinitionContext struct {SkipBackupSchema bool@@ -208,3 +211,20 @@ func GenerateMigration(engine storepb.Engine, diff *MetadataDiff) (string, error}return f(diff)}++func RegisterGetSDLDiff(engine storepb.Engine, f getSDLDiff) {+ mux.Lock()+ defer mux.Unlock()+ if _, dup := getSDLDiffs[engine]; dup {+ panic(fmt.Sprintf("Register called twice %s", engine))+ }+ getSDLDiffs[engine] = f+}++func GetSDLDiff(engine storepb.Engine, currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseSchema) (*MetadataDiff, error) {+ f, ok := getSDLDiffs[engine]+ if !ok {+ return nil, errors.Errorf("engine %s is not supported", engine)+ }+ return f(currentSDLText, previousUserSDLText, currentSchema, previousSchema)+}diff --git a/backend/plugin/schema/sdl_differ.go b/backend/plugin/schema/sdl_differ.gonew file mode 100644index 0000000000..653df515d0--- /dev/null+++ b/backend/plugin/schema/sdl_differ.go@@ -0,0 +1,43 @@+package schema++import (+ "github.com/antlr4-go/antlr/v4"+)++type SDLChunk struct {+ Identifier string+ ASTNode antlr.ParserRuleContext // The parsed AST node for this chunk+}++// GetText extracts text from the AST node using the provided token stream+func (c *SDLChunk) GetText(tokens *antlr.CommonTokenStream) string {+ if c.ASTNode == nil || tokens == nil {+ return ""+ }++ start := c.ASTNode.GetStart()+ stop := c.ASTNode.GetStop()++ if start == nil || stop == nil {+ return ""+ }++ return tokens.GetTextFromTokens(start, stop)+}++type SDLChunks struct {+ Tables map[string]*SDLChunk // key: table name/identifier+ Views map[string]*SDLChunk // key: view name/identifier+ Functions map[string]*SDLChunk // key: function name/identifier+ Indexes map[string]*SDLChunk // key: index name/identifier+ Sequences map[string]*SDLChunk // key: sequence name/identifier+ Tokens *antlr.CommonTokenStream // Token stream for extracting text from AST nodes+}++type SDLDiff struct {+ CurrentChunks *SDLChunks+ PreviousChunks *SDLChunks+ Added []*SDLChunk+ Removed []*SDLChunk+ Modified []*SDLChunk+}