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: handle table drift in SDL workflow (#17502)
rebelice257fe45135d8
diff --git a/backend/plugin/schema/pg/chunk_extraction_test.go b/backend/plugin/schema/pg/chunk_extraction_test.goindex ff3cfb34bc..54fb94523b 100644--- a/backend/plugin/schema/pg/chunk_extraction_test.go+++ b/backend/plugin/schema/pg/chunk_extraction_test.go@@ -4,11 +4,13 @@ import ("strings""testing"+ "github.com/antlr4-go/antlr/v4""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"parser "github.com/bytebase/parser/postgresql"+ pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg""github.com/bytebase/bytebase/backend/plugin/schema")@@ -25,7 +27,7 @@ func TestChunkSDLTextExtraction(t *testing.T) {name VARCHAR(255) NOT NULL);`,expectedResults: map[string]string{- "TABLE:users": `CREATE TABLE users (+ "TABLE:public.users": `CREATE TABLE users (id SERIAL PRIMARY KEY,name VARCHAR(255) NOT NULL)`,@@ -42,12 +44,12 @@ CREATE INDEX idx_users_name ON users(name);CREATE SEQUENCE user_seq START 1;`,expectedResults: map[string]string{- "TABLE:users": `CREATE TABLE users (+ "TABLE:public.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`,+ "INDEX:public.idx_users_name": `CREATE INDEX idx_users_name ON users(name)`,+ "SEQUENCE:public.user_seq": `CREATE SEQUENCE user_seq START 1`,},},{@@ -58,7 +60,7 @@ BEGINEND;$$ LANGUAGE plpgsql;`,expectedResults: map[string]string{- "FUNCTION:get_user_count()": `CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$+ "FUNCTION:public.get_user_count()": `CREATE FUNCTION get_user_count() RETURNS INTEGER AS $$BEGINRETURN (SELECT COUNT(*) FROM users);END;@@ -97,22 +99,22 @@ $$ LANGUAGE plpgsql;CREATE SEQUENCE product_seq START 100;`,expectedResults: map[string]string{- "TABLE:products": `CREATE TABLE products (+ "TABLE:public.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+ "VIEW:public.product_summary": `CREATE VIEW product_summary ASSELECT id, name, priceFROM productsWHERE price > 0`,- "INDEX:idx_products_price": `CREATE INDEX idx_products_price ON products(price)`,- "FUNCTION:calculate_discount(amount numeric)": `CREATE FUNCTION calculate_discount(amount DECIMAL) RETURNS DECIMAL AS $$+ "INDEX:public.idx_products_price": `CREATE INDEX idx_products_price ON products(price)`,+ "FUNCTION:public.calculate_discount(amount numeric)": `CREATE FUNCTION calculate_discount(amount DECIMAL) RETURNS DECIMAL AS $$BEGINRETURN amount * 0.9;END;$$ LANGUAGE plpgsql`,- "SEQUENCE:product_seq": `CREATE SEQUENCE product_seq START 100`,+ "SEQUENCE:public.product_seq": `CREATE SEQUENCE product_seq START 100`,},},}@@ -123,7 +125,7 @@ $$ LANGUAGE plpgsql`,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")+ // Token stream is no longer stored in chunks, obtained from AST nodes directly// Build a map of all chunks with type:identifier keysallChunks := make(map[string]*schema.SDLChunk)@@ -157,7 +159,7 @@ $$ LANGUAGE plpgsql`,assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil")// Extract text using GetText method and compare- actualText := chunk.GetText(chunks.Tokens)+ actualText := chunk.GetText()require.NotEmpty(t, actualText, "GetText should return non-empty text")// Normalize whitespace for comparison@@ -258,17 +260,97 @@ func TestChunkGetTextMethod(t *testing.T) {chunks, err := ChunkSDLText(sdlText)require.NoError(t, err)- require.Contains(t, chunks.Tables, "test_table")+ require.Contains(t, chunks.Tables, "public.test_table")- chunk := chunks.Tables["test_table"]+ chunk := chunks.Tables["public.test_table"]// Test GetText method- text := chunk.GetText(chunks.Tokens)+ text := chunk.GetText()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")+ // Test that GetText works with the new token-less approach+ // (This test is no longer relevant since we get tokens from AST directly)+}++func TestChunkKeyFormats(t *testing.T) {+ sdlText := `CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);+CREATE TABLE admin.users (id SERIAL, role TEXT);+CREATE SEQUENCE user_seq;+CREATE SEQUENCE admin.admin_seq;+CREATE VIEW user_view AS SELECT * FROM users;+CREATE VIEW admin.admin_view AS SELECT * FROM admin.users;+CREATE INDEX idx_users_name ON users(name);`++ chunks, err := ChunkSDLText(sdlText)+ require.NoError(t, err)+ require.NotNil(t, chunks)++ // Check that all chunk keys use schema.objectName format+ expectedTableKeys := []string{"public.users", "admin.users"}+ expectedSequenceKeys := []string{"public.user_seq", "admin.admin_seq"}+ expectedViewKeys := []string{"public.user_view", "admin.admin_view"}+ expectedIndexKeys := []string{"public.idx_users_name"}++ // Verify table chunk keys+ require.Equal(t, len(expectedTableKeys), len(chunks.Tables))+ for _, key := range expectedTableKeys {+ _, exists := chunks.Tables[key]+ require.True(t, exists, "Expected table key %s not found", key)+ }++ // Verify sequence chunk keys+ require.Equal(t, len(expectedSequenceKeys), len(chunks.Sequences))+ for _, key := range expectedSequenceKeys {+ _, exists := chunks.Sequences[key]+ require.True(t, exists, "Expected sequence key %s not found", key)+ }++ // Verify view chunk keys+ require.Equal(t, len(expectedViewKeys), len(chunks.Views))+ for _, key := range expectedViewKeys {+ _, exists := chunks.Views[key]+ require.True(t, exists, "Expected view key %s not found", key)+ }++ // Verify index chunk keys+ require.Equal(t, len(expectedIndexKeys), len(chunks.Indexes))+ for _, key := range expectedIndexKeys {+ _, exists := chunks.Indexes[key]+ require.True(t, exists, "Expected index key %s not found", key)+ }+}++// TestNewTableASTParsing tests that new tables created during drift detection+// have proper AST nodes that can generate correct text+func TestNewTableASTParsing(t *testing.T) {+ // Test the createTableExtractor functionality+ tableSDL := `CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text NOT NULL+);`++ parseResult, err := pgparser.ParsePostgreSQL(tableSDL)+ require.NoError(t, err)++ // Extract the CREATE TABLE AST node+ var createTableNode *parser.CreatestmtContext+ antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{+ result: &createTableNode,+ }, parseResult.Tree)++ require.NotNil(t, createTableNode, "Should extract CREATE TABLE AST node")++ // Create chunk with the AST node+ chunk := &schema.SDLChunk{+ Identifier: "public.users",+ ASTNode: createTableNode,+ }++ // Verify we can extract text from the AST node+ text := chunk.GetText()+ require.NotEmpty(t, text)+ require.Contains(t, strings.ToUpper(text), "CREATE TABLE")+ require.Contains(t, text, "users")}diff --git a/backend/plugin/schema/pg/column_sdl_diff_test.go b/backend/plugin/schema/pg/column_sdl_diff_test.goindex f45a6eb621..2b1a290a03 100644--- a/backend/plugin/schema/pg/column_sdl_diff_test.go+++ b/backend/plugin/schema/pg/column_sdl_diff_test.go@@ -700,9 +700,9 @@ func TestColumnMetadataExtraction(t *testing.T) {t.Run(tc.name, func(t *testing.T) {chunks, err := ChunkSDLText(tc.sdlText)require.NoError(t, err)- require.Contains(t, chunks.Tables, "test")+ require.Contains(t, chunks.Tables, "public.test")- testChunk := chunks.Tables["test"]+ testChunk := chunks.Tables["public.test"]createStmt, ok := testChunk.ASTNode.(*parser.CreatestmtContext)require.True(t, ok, "Should be a CreatestmtContext")diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex 26095218b9..ac1370e7c6 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -40,6 +40,14 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previreturn nil, errors.Wrap(err, "failed to chunk previous SDL text")}+ // Check for drift scenario: when both schemas are provided, apply minimal changes to previousChunks+ if currentSchema != nil && previousSchema != nil {+ err = applyMinimalChangesToChunks(previousChunks, currentSchema, previousSchema)+ if err != nil {+ return nil, errors.Wrap(err, "failed to apply minimal changes to SDL chunks")+ }+ }+// Initialize MetadataDiffdiff := &schema.MetadataDiff{DatabaseName: "",@@ -82,7 +90,6 @@ func ChunkSDLText(sdlText string) (*schema.SDLChunks, error) {Functions: make(map[string]*schema.SDLChunk),Indexes: make(map[string]*schema.SDLChunk),Sequences: make(map[string]*schema.SDLChunk),- Tokens: nil,}, nil}@@ -99,7 +106,6 @@ func ChunkSDLText(sdlText string) (*schema.SDLChunks, error) {Functions: make(map[string]*schema.SDLChunk),Indexes: make(map[string]*schema.SDLChunk),Sequences: make(map[string]*schema.SDLChunk),- Tokens: parseResult.Tokens,},tokens: parseResult.Tokens,}@@ -124,12 +130,20 @@ func (l *sdlChunkExtractor) EnterCreatestmt(ctx *parser.CreatestmtContext) {identifier := pgparser.NormalizePostgreSQLQualifiedName(ctx.Qualified_name(0))identifierStr := strings.Join(identifier, ".")+ // Ensure schema.tableName format+ var schemaQualifiedName string+ if strings.Contains(identifierStr, ".") {+ schemaQualifiedName = identifierStr+ } else {+ schemaQualifiedName = "public." + identifierStr+ }+chunk := &schema.SDLChunk{- Identifier: identifierStr,+ Identifier: schemaQualifiedName,ASTNode: ctx,}- l.chunks.Tables[identifierStr] = chunk+ l.chunks.Tables[schemaQualifiedName] = chunk}func (l *sdlChunkExtractor) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext) {@@ -140,12 +154,20 @@ func (l *sdlChunkExtractor) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext)identifier := pgparser.NormalizePostgreSQLQualifiedName(ctx.Qualified_name())identifierStr := strings.Join(identifier, ".")+ // Ensure schema.sequenceName format+ var schemaQualifiedName string+ if strings.Contains(identifierStr, ".") {+ schemaQualifiedName = identifierStr+ } else {+ schemaQualifiedName = "public." + identifierStr+ }+chunk := &schema.SDLChunk{- Identifier: identifierStr,+ Identifier: schemaQualifiedName,ASTNode: ctx,}- l.chunks.Sequences[identifierStr] = chunk+ l.chunks.Sequences[schemaQualifiedName] = chunk}func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {@@ -160,18 +182,35 @@ func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionstreturn}- // Join the parts to create the function name (schema.function_name or function_name)- funcName := strings.Join(funcNameParts, ".")+ // Parse schema and function name directly from parts+ var schemaName, functionName string+ if len(funcNameParts) == 2 {+ // Schema qualified: schema.function_name+ schemaName = funcNameParts[0]+ functionName = funcNameParts[1]+ } else if len(funcNameParts) == 1 {+ // Unqualified: function_name (assume public schema)+ schemaName = "public"+ functionName = funcNameParts[0]+ } else {+ // Unexpected format+ return+ }- // Extract function signature for proper identification- funcSignature := ExtractFunctionSignature(ctx, funcName)+ if functionName == "" {+ return+ }++ // Generate function signature with parameter types+ signature := ExtractFunctionSignature(ctx, functionName)+ schemaQualifiedSignature := schemaName + "." + signaturechunk := &schema.SDLChunk{- Identifier: funcSignature, // Use signature instead of name+ Identifier: schemaQualifiedSignature,ASTNode: ctx,}- l.chunks.Functions[funcSignature] = chunk+ l.chunks.Functions[schemaQualifiedSignature] = chunk}func (l *sdlChunkExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {@@ -191,12 +230,20 @@ func (l *sdlChunkExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {return}+ // Ensure schema.indexName format+ var schemaQualifiedName string+ if strings.Contains(indexName, ".") {+ schemaQualifiedName = indexName+ } else {+ schemaQualifiedName = "public." + indexName+ }+chunk := &schema.SDLChunk{- Identifier: indexName,+ Identifier: schemaQualifiedName,ASTNode: ctx,}- l.chunks.Indexes[indexName] = chunk+ l.chunks.Indexes[schemaQualifiedName] = chunk}func (l *sdlChunkExtractor) EnterViewstmt(ctx *parser.ViewstmtContext) {@@ -207,12 +254,20 @@ func (l *sdlChunkExtractor) EnterViewstmt(ctx *parser.ViewstmtContext) {identifier := pgparser.NormalizePostgreSQLQualifiedName(ctx.Qualified_name())identifierStr := strings.Join(identifier, ".")+ // Ensure schema.viewName format+ var schemaQualifiedName string+ if strings.Contains(identifierStr, ".") {+ schemaQualifiedName = identifierStr+ } else {+ schemaQualifiedName = "public." + identifierStr+ }+chunk := &schema.SDLChunk{- Identifier: identifierStr,+ Identifier: schemaQualifiedName,ASTNode: ctx,}- l.chunks.Views[identifierStr] = chunk+ l.chunks.Views[schemaQualifiedName] = chunk}// processTableChanges processes changes to tables by comparing SDL chunks@@ -228,8 +283,8 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currenif previousChunk, exists := previousChunks.Tables[identifier]; exists {// Table exists in both - check if modified- currentText := currentChunk.GetText(currentChunks.Tokens)- previousText := previousChunk.GetText(previousChunks.Tokens)+ currentText := currentChunk.GetText()+ previousText := previousChunk.GetText()if currentText != previousText {// Table was modified - process column changesoldASTNode, ok := previousChunk.ASTNode.(*parser.CreatestmtContext)@@ -265,22 +320,38 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren}} else {// New table- newASTNode, ok := currentChunk.ASTNode.(*parser.CreatestmtContext)- if !ok {- return errors.Errorf("expected CreatestmtContext for new table %s", currentChunk.Identifier)- }+ // Handle generated chunks (from drift detection) that don't have AST nodes+ if currentChunk.ASTNode == nil {+ // This is a generated chunk, create a simplified diff entry+ tableDiff := &schema.TableDiff{+ Action: schema.MetadataDiffActionCreate,+ SchemaName: schemaName,+ TableName: tableName,+ OldTable: nil,+ NewTable: nil,+ OldASTNode: nil,+ NewASTNode: nil, // No AST node for generated content+ ColumnChanges: []*schema.ColumnDiff{}, // Empty - table creation automatically creates all columns+ }+ diff.TableChanges = append(diff.TableChanges, tableDiff)+ } else {+ newASTNode, ok := currentChunk.ASTNode.(*parser.CreatestmtContext)+ if !ok {+ return errors.Errorf("expected CreatestmtContext for new table %s", currentChunk.Identifier)+ }- 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: newASTNode,- ColumnChanges: []*schema.ColumnDiff{}, // Empty - table creation automatically creates all columns+ 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: newASTNode,+ ColumnChanges: []*schema.ColumnDiff{}, // Empty - table creation automatically creates all columns+ }+ diff.TableChanges = append(diff.TableChanges, tableDiff)}- diff.TableChanges = append(diff.TableChanges, tableDiff)}}@@ -289,6 +360,14 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currenif _, exists := currentChunks.Tables[identifier]; !exists {// Table was droppedschemaName, tableName := parseIdentifier(previousChunk.Identifier)++ // Handle generated chunks (from drift detection) that don't have AST nodes+ if previousChunk.ASTNode == nil {+ // This is a generated chunk that was removed, skip it in the diff+ // It means this table was added during drift detection but doesn't exist in current SDL+ continue+ }+oldASTNode, ok := previousChunk.ASTNode.(*parser.CreatestmtContext)if !ok {return errors.Errorf("expected CreatestmtContext for dropped table %s", previousChunk.Identifier)@@ -460,7 +539,7 @@ func extractColumnMetadata(columnDef parser.IColumnDefContext) *storepb.ColumnMe}}-// parseTableIdentifier parses a table identifier and returns schema name and table name+// parseIdentifier parses a table identifier and returns schema name and table namefunc parseIdentifier(identifier string) (schemaName, objectName string) {parts := strings.Split(identifier, ".")if len(parts) == 2 {@@ -469,6 +548,16 @@ func parseIdentifier(identifier string) (schemaName, objectName string) {return "public", identifier}+// createTableExtractor extracts CREATE TABLE AST node from parse tree+type createTableExtractor struct {+ *parser.BasePostgreSQLParserListener+ result **parser.CreatestmtContext+}++func (e *createTableExtractor) EnterCreatestmt(ctx *parser.CreatestmtContext) {+ *e.result = ctx+}+// getColumnText extracts the text representation of a column definitionfunc getColumnText(columnAST parser.IColumnDefContext) string {if columnAST == nil {@@ -1298,8 +1387,8 @@ func processViewChanges(currentChunks, previousChunks *schema.SDLChunks, diff *sfor identifier, currentChunk := range currentChunks.Views {if previousChunk, exists := previousChunks.Views[identifier]; exists {// View exists in both - check if modified by comparing text first- currentText := currentChunk.GetText(currentChunks.Tokens)- previousText := previousChunk.GetText(previousChunks.Tokens)+ currentText := currentChunk.GetText()+ previousText := previousChunk.GetText()if currentText != previousText {// View was modified - use drop and recreate pattern (PostgreSQL standard)schemaName, viewName := parseIdentifier(identifier)@@ -1363,8 +1452,8 @@ func processFunctionChanges(currentChunks, previousChunks *schema.SDLChunks, diffor identifier, currentChunk := range currentChunks.Functions {if previousChunk, exists := previousChunks.Functions[identifier]; exists {// Function exists in both - check if modified by comparing text first- currentText := currentChunk.GetText(currentChunks.Tokens)- previousText := previousChunk.GetText(previousChunks.Tokens)+ currentText := currentChunk.GetText()+ previousText := previousChunk.GetText()if currentText != previousText {// Function was modified - use CREATE OR REPLACE (AST-only mode)schemaName, functionName := parseIdentifier(identifier)@@ -1419,8 +1508,8 @@ func processSequenceChanges(currentChunks, previousChunks *schema.SDLChunks, diffor identifier, currentChunk := range currentChunks.Sequences {if previousChunk, exists := previousChunks.Sequences[identifier]; exists {// Sequence exists in both - check if modified by comparing text first- currentText := currentChunk.GetText(currentChunks.Tokens)- previousText := previousChunk.GetText(previousChunks.Tokens)+ currentText := currentChunk.GetText()+ previousText := previousChunk.GetText()if currentText != previousText {// Sequence was modified - use drop and recreate pattern (PostgreSQL standard)schemaName, sequenceName := parseIdentifier(identifier)@@ -1477,6 +1566,108 @@ func processSequenceChanges(currentChunks, previousChunks *schema.SDLChunks, dif}}+// applyMinimalChangesToChunks applies minimal changes to the previous SDL chunks based on schema differences+// This implements the minimal change principle for drift scenarios by directly manipulating chunks+func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema) error {+ if currentSchema == nil || previousSchema == nil || previousChunks == nil {+ return nil+ }++ // Get table differences between schemas+ currentMetadata := currentSchema.GetMetadata()+ previousMetadata := previousSchema.GetMetadata()+ if currentMetadata == nil || previousMetadata == nil {+ return nil+ }++ // Create maps for efficient table lookup using full schema.table identifier+ currentTables := make(map[string]*storepb.TableMetadata)+ previousTables := make(map[string]*storepb.TableMetadata)++ // Build current tables map with proper schema qualification+ for _, schema := range currentMetadata.Schemas {+ schemaName := schema.Name+ if schemaName == "" {+ schemaName = "public" // Default schema for PostgreSQL+ }+ for _, table := range schema.Tables {+ tableKey := schemaName + "." + table.Name+ currentTables[tableKey] = table+ }+ }++ // Build previous tables map with proper schema qualification+ for _, schema := range previousMetadata.Schemas {+ schemaName := schema.Name+ if schemaName == "" {+ schemaName = "public" // Default schema for PostgreSQL+ }+ for _, table := range schema.Tables {+ tableKey := schemaName + "." + table.Name+ previousTables[tableKey] = table+ }+ }++ // Build existing chunk keys mapping for table operations+ existingChunkKeys := make(map[string]string) // schema.table -> chunk key+ for chunkKey := range previousChunks.Tables {+ existingChunkKeys[chunkKey] = chunkKey+ }++ // Process table additions: add new tables to chunks+ for tableKey, currentTable := range currentTables {+ if _, exists := previousTables[tableKey]; !exists {+ // Table was added - generate SDL for the new table and parse it to AST+ var buf strings.Builder+ schemaName, _ := parseIdentifier(tableKey)+ err := writeCreateTableSDL(&buf, schemaName, currentTable)+ if err != nil {+ return errors.Wrapf(err, "failed to generate SDL for new table %s", tableKey)+ }+ tableSDL := buf.String()++ // Parse the generated SDL to create AST node+ parseResult, err := pgparser.ParsePostgreSQL(tableSDL)+ if err != nil {+ return errors.Wrapf(err, "failed to parse generated SDL for new table %s", tableKey)+ }++ // Extract the CREATE TABLE AST node+ var createTableNode *parser.CreatestmtContext+ antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{+ result: &createTableNode,+ }, parseResult.Tree)++ if createTableNode == nil {+ return errors.Errorf("failed to extract CREATE TABLE AST node for new table %s", tableKey)+ }++ // Always use schema.table format for all table identifiers+ chunkKey := tableKey++ // Add the new table chunk with proper AST node+ previousChunks.Tables[chunkKey] = &schema.SDLChunk{+ Identifier: chunkKey,+ ASTNode: createTableNode,+ }+ }+ }++ // Process table deletions: remove dropped tables from chunks+ for tableKey := range previousTables {+ if _, exists := currentTables[tableKey]; !exists {+ // Table was dropped - find the corresponding chunk key and remove it+ if existingKey, exists := existingChunkKeys[tableKey]; exists {+ delete(previousChunks.Tables, existingKey)+ }+ // If no mapping exists, the table was not in the original chunks,+ // so there's nothing to delete - this is the expected behavior+ }+ }++ return nil+}+// convertDatabaseSchemaToSDL converts a model.DatabaseSchema to SDL format string// This is used in initialization scenarios where previousUserSDLText is emptyfunc convertDatabaseSchemaToSDL(dbSchema *model.DatabaseSchema) (string, error) {diff --git a/backend/plugin/schema/pg/get_sdl_diff_test.go b/backend/plugin/schema/pg/get_sdl_diff_test.goindex f9b88cecc6..32e79a9f79 100644--- a/backend/plugin/schema/pg/get_sdl_diff_test.go+++ b/backend/plugin/schema/pg/get_sdl_diff_test.go@@ -1,6 +1,7 @@package pgimport (+ "strings""testing""github.com/stretchr/testify/require"@@ -67,7 +68,7 @@ func TestGetSDLDiff_InitializationScenario(t *testing.T) {),previousSchema: nil,expectedDiffEmpty: false, // Diff may be generated due to format differences- expectedTableChanges: 2, // May have changes due to format differences+ expectedTableChanges: 1, // One table creationexpectedViewChanges: 0,expectedFunctionChanges: 0,expectedSequenceChanges: 0,@@ -123,7 +124,7 @@ func TestGetSDLDiff_InitializationScenario(t *testing.T) {),previousSchema: nil,expectedDiffEmpty: false, // Diff may be generated due to format differences- expectedTableChanges: 2, // May have changes due to format differences+ expectedTableChanges: 1, // One table creationexpectedViewChanges: 0,expectedFunctionChanges: 0,expectedSequenceChanges: 0,@@ -242,3 +243,242 @@ func TestConvertDatabaseSchemaToSDL(t *testing.T) {})}}++// TestGetSDLDiff_MinimalChangesScenario tests the minimal changes functionality+// This is a basic test to verify that the drift detection logic is invoked+func TestGetSDLDiff_MinimalChangesScenario(t *testing.T) {+ currentSDLText := "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL);"+ previousUserSDLText := `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name TEXT NOT NULL+ );`++ currentSchema := model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: false},+ },+ },+ {+ Name: "posts", // This table exists in current schema but not in previous+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "title", Type: "text", Nullable: false},+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ )++ previousSchema := model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: false},+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ )++ // Test that the function runs without error when schemas are provided+ diff, err := GetSDLDiff(currentSDLText, previousUserSDLText, currentSchema, previousSchema)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // We don't assert specific outcomes here because the main goal is to test+ // that the minimal changes logic is invoked and doesn't crash+ t.Logf("Generated %d table changes", len(diff.TableChanges))+ for i, change := range diff.TableChanges {+ t.Logf("Change %d: %s %s", i+1, change.Action, change.TableName)+ }+}++func TestApplyMinimalChangesToChunks(t *testing.T) {+ tests := []struct {+ name string+ previousUserSDLText string+ currentSchema *model.DatabaseSchema+ previousSchema *model.DatabaseSchema+ expectedTables []string+ }{+ {+ name: "add_new_table_to_existing_chunks",+ previousUserSDLText: `CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name TEXT NOT NULL+ );`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: false},+ },+ },+ {+ Name: "posts",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "title", Type: "text", Nullable: false},+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ ),+ previousSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: false},+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ ),+ expectedTables: []string{"public.users", "public.posts"},+ },+ {+ name: "multi_schema_with_same_table_names",+ previousUserSDLText: `CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ name TEXT NOT NULL+ );`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: false},+ },+ },+ },+ },+ {+ Name: "admin",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users", // Same table name but different schema+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "role", Type: "text", Nullable: false},+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ ),+ previousSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: false},+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ ),+ expectedTables: []string{"public.users", "admin.users"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ // Parse the SDL text into chunks+ previousChunks, err := ChunkSDLText(tt.previousUserSDLText)+ require.NoError(t, err)++ // Apply minimal changes to chunks+ err = applyMinimalChangesToChunks(previousChunks, tt.currentSchema, tt.previousSchema)+ require.NoError(t, err)++ // Check that all expected tables are present in the chunks+ require.Equal(t, len(tt.expectedTables), len(previousChunks.Tables))+ for _, expectedTable := range tt.expectedTables {+ chunk, exists := previousChunks.Tables[expectedTable]+ require.True(t, exists, "Expected table %s not found in chunks", expectedTable)++ // Check that we can get text from the chunk+ text := chunk.GetText()+ require.NotEmpty(t, text)+ require.Contains(t, strings.ToUpper(text), "CREATE TABLE")+ }+ })+ }+}diff --git a/backend/plugin/schema/sdl_differ.go b/backend/plugin/schema/sdl_differ.goindex 653df515d0..81aa67470e 100644--- a/backend/plugin/schema/sdl_differ.go+++ b/backend/plugin/schema/sdl_differ.go@@ -9,29 +9,41 @@ type SDLChunk struct {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 {+// GetText extracts text from the AST node using its own token stream+func (c *SDLChunk) GetText() string {+ if c.ASTNode == nil {return ""}- start := c.ASTNode.GetStart()- stop := c.ASTNode.GetStop()+ // Check for interfaces that have the required methods+ type parserContext interface {+ GetParser() antlr.Parser+ GetStart() antlr.Token+ GetStop() antlr.Token+ }- if start == nil || stop == nil {- return ""+ if ruleContext, ok := c.ASTNode.(parserContext); ok {+ if parser := ruleContext.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := ruleContext.GetStart()+ stop := ruleContext.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }}- return tokens.GetTextFromTokens(start, stop)+ // Fallback to node's GetText method+ return c.ASTNode.GetText()}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+ 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}type SDLDiff struct {