Skip to content

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

feat: generate migration for AST only diff (#17436)

rebeliced464756c7e32
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
index 6a1e644e30..dfb0f866b6 100644
--- a/backend/plugin/schema/pg/generate_migration.go
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -1,6 +1,7 @@
package pg
import (
+ "context"
"fmt"
"slices"
"strconv"
@@ -8,11 +9,14 @@ import (
"github.com/antlr4-go/antlr/v4"
pgparser "github.com/bytebase/parser/postgresql"
+ "github.com/pkg/errors"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ pgpluginparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
"github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/plugin/schema/pg/ast"
+ "github.com/bytebase/bytebase/backend/store/model"
)
func init() {
@@ -77,7 +81,7 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
}
// Build dependency graph for all objects being dropped or altered
- graph := parserbase.NewGraph()
+ graph := base.NewGraph()
// Maps to store different object types
viewMap := make(map[string]*schema.ViewDiff)
@@ -139,13 +143,23 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
// Add dependency edges
// For views depending on tables/views
for viewID, viewDiff := range viewMap {
+ var dependencies []*storepb.DependencyColumn
+
if viewDiff.OldView != nil {
- for _, dep := range viewDiff.OldView.DependencyColumns {
- depID := getMigrationObjectID(dep.Schema, dep.Table)
- if allObjects[depID] {
- // Edge from dependent to dependency (view depends on table/view)
- graph.AddEdge(viewID, depID)
- }
+ // Use metadata if available
+ dependencies = viewDiff.OldView.DependencyColumns
+ } else if viewDiff.OldASTNode != nil {
+ // Extract dependencies from AST node for AST-only mode
+ // For simplicity, we use an empty schema metadata since we can't build full metadata in migration context
+ // This will only work for simple dependencies within the same database
+ dependencies = getViewDependenciesFromAST(viewDiff.OldASTNode, viewDiff.SchemaName, &storepb.DatabaseSchemaMetadata{})
+ }
+
+ for _, dep := range dependencies {
+ depID := getMigrationObjectID(dep.Schema, dep.Table)
+ if allObjects[depID] {
+ // Edge from dependent to dependency (view depends on table/view)
+ graph.AddEdge(viewID, depID)
}
}
}
@@ -491,7 +505,7 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
}
// Build dependency graph for all objects being created or altered
- graph := parserbase.NewGraph()
+ graph := base.NewGraph()
// Maps to store different object types
viewMap := make(map[string]*schema.ViewDiff)
@@ -558,12 +572,22 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
// For views depending on tables/views
for viewID, viewDiff := range viewMap {
+ var dependencies []*storepb.DependencyColumn
+
if viewDiff.NewView != nil {
- for _, dep := range viewDiff.NewView.DependencyColumns {
- depID := getMigrationObjectID(dep.Schema, dep.Table)
- // Edge from dependency to dependent (table/view to view)
- graph.AddEdge(depID, viewID)
- }
+ // Use metadata if available
+ dependencies = viewDiff.NewView.DependencyColumns
+ } else if viewDiff.NewASTNode != nil {
+ // Extract dependencies from AST node for AST-only mode
+ // For simplicity, we use an empty schema metadata since we can't build full metadata in migration context
+ // This will only work for simple dependencies within the same database
+ dependencies = getViewDependenciesFromAST(viewDiff.NewASTNode, viewDiff.SchemaName, &storepb.DatabaseSchemaMetadata{})
+ }
+
+ for _, dep := range dependencies {
+ depID := getMigrationObjectID(dep.Schema, dep.Table)
+ // Edge from dependency to dependent (table/view to view)
+ graph.AddEdge(depID, viewID)
}
}
@@ -634,8 +658,17 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
for _, viewDiff := range viewMap {
switch viewDiff.Action {
case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:
- if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {
- return err
+ // Support AST-only mode: if metadata is nil but AST node exists, use AST
+ if viewDiff.NewView != nil {
+ if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {
+ return err
+ }
+ } else if viewDiff.NewASTNode != nil {
+ if err := writeMigrationViewFromAST(buf, viewDiff.NewASTNode); err != nil {
+ return err
+ }
+ } else {
+ return errors.Errorf("view diff for %s.%s has neither metadata nor AST node", viewDiff.SchemaName, viewDiff.ViewName)
}
default:
// No action needed
@@ -732,8 +765,17 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error
} else if viewDiff, ok := viewMap[objID]; ok {
switch viewDiff.Action {
case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:
- if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {
- return err
+ // Support AST-only mode: if metadata is nil but AST node exists, use AST
+ if viewDiff.NewView != nil {
+ if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {
+ return err
+ }
+ } else if viewDiff.NewASTNode != nil {
+ if err := writeMigrationViewFromAST(buf, viewDiff.NewASTNode); err != nil {
+ return err
+ }
+ } else {
+ return errors.Errorf("view diff for %s.%s has neither metadata nor AST node", viewDiff.SchemaName, viewDiff.ViewName)
}
default:
// No action needed for other operations
@@ -1546,6 +1588,49 @@ func writeMigrationSequenceOwnership(out *strings.Builder, schema string, seq *s
return nil
}
+// writeView writes a CREATE VIEW statement from AST node or metadata
+func writeMigrationViewFromAST(out *strings.Builder, astNode any) error {
+ if astNode == nil {
+ return errors.New("AST node is nil")
+ }
+
+ // Extract the original SQL text from the AST node
+ var viewSQL string
+
+ // Try to cast to PostgreSQL ViewstmtContext first
+ if ctx, ok := astNode.(*pgparser.ViewstmtContext); ok {
+ // First try to get text using token stream
+ if tokenStream := ctx.GetParser().GetTokenStream(); tokenStream != nil {
+ start := ctx.GetStart()
+ stop := ctx.GetStop()
+ if start != nil && stop != nil {
+ viewSQL = tokenStream.GetTextFromTokens(start, stop)
+ }
+ }
+
+ // Fallback to GetText() if token stream approach failed
+ if viewSQL == "" {
+ viewSQL = ctx.GetText()
+ }
+ } else {
+ // Generic fallback - try to get text directly
+ if tree, ok := astNode.(interface{ GetText() string }); ok {
+ viewSQL = tree.GetText()
+ }
+ }
+
+ if viewSQL != "" {
+ _, _ = out.WriteString(viewSQL)
+ if !strings.HasSuffix(strings.TrimSpace(viewSQL), ";") {
+ _, _ = out.WriteString(`;`)
+ }
+ _, _ = out.WriteString("\n\n")
+ return nil
+ }
+
+ return errors.New("failed to extract SQL from AST node")
+}
+
// writeView writes a CREATE VIEW statement
func writeMigrationView(out *strings.Builder, schema string, view *storepb.ViewMetadata) error {
_, _ = out.WriteString(`CREATE VIEW "`)
@@ -2312,3 +2397,87 @@ func (v *CreateOrReplaceVisitor) hasOrReplace(ctx *pgparser.CreatefunctionstmtCo
return false
}
+
+// getViewDependenciesFromAST extracts view dependencies from AST node
+// This reuses the same logic as getViewDependencies from get_database_metadata.go
+func getViewDependenciesFromAST(astNode any, schemaName string, fullSchemaMetadata *storepb.DatabaseSchemaMetadata) []*storepb.DependencyColumn {
+ if astNode == nil {
+ return []*storepb.DependencyColumn{}
+ }
+
+ // Extract the SELECT statement from the VIEW AST node
+ var selectStatement string
+
+ if ctx, ok := astNode.(*pgparser.ViewstmtContext); ok {
+ // Extract the SELECT statement from the ViewstmtContext
+ if ctx.Selectstmt() != nil {
+ // Try to get text using token stream first
+ if tokenStream := ctx.GetParser().GetTokenStream(); tokenStream != nil {
+ start := ctx.Selectstmt().GetStart()
+ stop := ctx.Selectstmt().GetStop()
+ if start != nil && stop != nil {
+ selectStatement = tokenStream.GetTextFromTokens(start, stop)
+ }
+ }
+
+ // Fallback to GetText() if token stream approach failed
+ if selectStatement == "" {
+ selectStatement = ctx.Selectstmt().GetText()
+ }
+ }
+ }
+
+ if selectStatement == "" {
+ return []*storepb.DependencyColumn{}
+ }
+
+ // Use the same dependency extraction logic as getViewDependencies
+ queryStatement := strings.TrimSpace(selectStatement)
+
+ // Use GetQuerySpan with the full schema metadata so it can resolve table/view references
+ span, err := pgpluginparser.GetQuerySpan(
+ context.Background(),
+ base.GetQuerySpanContext{
+ GetDatabaseMetadataFunc: func(_ context.Context, _, databaseName string) (string, *model.DatabaseMetadata, error) {
+ // Return the full schema metadata so GetQuerySpan can resolve references
+ dbMetadata := model.NewDatabaseMetadata(fullSchemaMetadata, false, false)
+ return databaseName, dbMetadata, nil
+ },
+ ListDatabaseNamesFunc: func(_ context.Context, _ string) ([]string, error) {
+ // Return empty list - we don't need actual database names for dependency extraction
+ return []string{}, nil
+ },
+ },
+ queryStatement,
+ "", // database
+ schemaName,
+ false, // case sensitive
+ )
+
+ // If error parsing query span, return empty dependencies
+ if err != nil {
+ return []*storepb.DependencyColumn{} // nolint:nilerr
+ }
+
+ // Collect unique dependencies
+ dependencyMap := make(map[string]*storepb.DependencyColumn)
+ for sourceColumn := range span.SourceColumns {
+ // Create dependency key in format: schema.table
+ key := fmt.Sprintf("%s.%s", sourceColumn.Schema, sourceColumn.Table)
+ if _, exists := dependencyMap[key]; !exists {
+ dependencyMap[key] = &storepb.DependencyColumn{
+ Schema: sourceColumn.Schema,
+ Table: sourceColumn.Table,
+ Column: "*", // Use wildcard since we're tracking table-level dependencies
+ }
+ }
+ }
+
+ // Convert map to slice
+ var dependencies []*storepb.DependencyColumn
+ for _, dep := range dependencyMap {
+ dependencies = append(dependencies, dep)
+ }
+
+ return dependencies
+}
diff --git a/backend/plugin/schema/pg/view_migration_integration_test.go b/backend/plugin/schema/pg/view_migration_integration_test.go
new file mode 100644
index 0000000000..37afb266a2
--- /dev/null
+++ b/backend/plugin/schema/pg/view_migration_integration_test.go
@@ -0,0 +1,268 @@
+package pg
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+func TestViewSDLDiffAndMigrationIntegration(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedMigration string
+ }{
+ {
+ name: "Create new view",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+ `,
+ expectedMigration: `CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+
+`,
+ },
+ {
+ name: "Drop view",
+ previousSDL: `
+ CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+ `,
+ currentSDL: ``,
+ expectedMigration: `DROP VIEW IF EXISTS "public"."active_users";
+`,
+ },
+ {
+ name: "Modify view (drop and recreate)",
+ previousSDL: `
+ CREATE VIEW active_users AS
+ SELECT 1 as id, 'test' as name;
+ `,
+ currentSDL: `
+ CREATE VIEW active_users AS
+ SELECT 2 as id, 'updated' as name, 'extra' as email;
+ `,
+ expectedMigration: `DROP VIEW IF EXISTS "public"."active_users";
+
+CREATE VIEW active_users AS
+ SELECT 2 as id, 'updated' as name, 'extra' as email;
+
+`,
+ },
+ {
+ name: "Schema-qualified view",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE VIEW test_schema.expensive_products AS
+ SELECT 1 as id, 'product' as name, 150.00 as price;
+ `,
+ expectedMigration: `CREATE VIEW test_schema.expensive_products AS
+ SELECT 1 as id, 'product' as name, 150.00 as price;
+
+`,
+ },
+ {
+ name: "Multiple view changes",
+ previousSDL: `
+ CREATE VIEW user_summary AS
+ SELECT 1 as id, 'user' as name;
+
+ CREATE VIEW order_summary AS
+ SELECT 1 as id, 100.00 as amount;
+ `,
+ currentSDL: `
+ CREATE VIEW user_summary AS
+ SELECT 2 as id, 'updated_user' as name, 'active' as status;
+
+ CREATE VIEW order_analytics AS
+ SELECT 1 as user_id, 500.00 as total_amount;
+ `,
+ expectedMigration: `DROP VIEW IF EXISTS "public"."order_summary";
+DROP VIEW IF EXISTS "public"."user_summary";
+
+CREATE VIEW order_analytics AS
+ SELECT 1 as user_id, 500.00 as total_amount;
+
+CREATE VIEW user_summary AS
+ SELECT 2 as id, 'updated_user' as name, 'active' as status;
+
+`,
+ },
+ {
+ name: "View with dependencies (AST-only mode)",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE VIEW dependent_view AS
+ SELECT id, name, 'derived' as type FROM base_view;
+
+ CREATE VIEW base_view AS
+ SELECT 1 as id, 'base' as name;
+ `,
+ expectedMigration: `CREATE VIEW base_view AS
+ SELECT 1 as id, 'base' as name;
+
+CREATE VIEW dependent_view AS
+ SELECT id, name, 'derived' as type FROM base_view;
+
+`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Step 1: Get SDL diff using AST-only mode (no metadata extraction)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Step 2: Verify that diff contains view changes with AST nodes
+ if len(diff.ViewChanges) > 0 {
+ for _, viewDiff := range diff.ViewChanges {
+ switch viewDiff.Action {
+ case schema.MetadataDiffActionCreate:
+ assert.NotNil(t, viewDiff.NewASTNode,
+ "Create action should have NewASTNode")
+ assert.Nil(t, viewDiff.OldASTNode,
+ "Create action should not have OldASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, viewDiff.NewView,
+ "AST-only mode should not have metadata")
+ case schema.MetadataDiffActionDrop:
+ assert.NotNil(t, viewDiff.OldASTNode,
+ "Drop action should have OldASTNode")
+ assert.Nil(t, viewDiff.NewASTNode,
+ "Drop action should not have NewASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, viewDiff.OldView,
+ "AST-only mode should not have metadata")
+ default:
+ // Other actions like MetadataDiffActionAlter
+ t.Logf("Encountered view action: %v", viewDiff.Action)
+ }
+ }
+ }
+
+ // Step 3: Generate migration SQL using AST nodes
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+
+ // Step 4: Verify the generated migration matches expectations
+ assert.Equal(t, tt.expectedMigration, migrationSQL,
+ "Generated migration SQL should match expected output")
+
+ // Step 5: Verify the migration is valid PostgreSQL SQL
+ // We can do a basic check to ensure it contains expected keywords
+ if tt.expectedMigration != "" {
+ if contains(tt.expectedMigration, "CREATE VIEW") {
+ assert.Contains(t, migrationSQL, "CREATE VIEW",
+ "Migration should contain CREATE VIEW statement")
+ }
+ if contains(tt.expectedMigration, "DROP VIEW") {
+ assert.Contains(t, migrationSQL, "DROP VIEW",
+ "Migration should contain DROP VIEW statement")
+ }
+ }
+ })
+ }
+}
+
+func TestViewMigrationASTOnlyModeValidation(t *testing.T) {
+ // Test that ensures AST-only mode works correctly without any metadata extraction
+ previousSDL := ``
+ currentSDL := `
+ CREATE VIEW product_view AS SELECT 1 as id, 'product' as name;
+ `
+
+ // Get diff without metadata extraction
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Should have exactly one view change
+ assert.Len(t, diff.ViewChanges, 1)
+ viewDiff := diff.ViewChanges[0]
+
+ // Verify AST-only mode properties
+ assert.Equal(t, schema.MetadataDiffActionCreate, viewDiff.Action)
+ assert.Equal(t, "public", viewDiff.SchemaName)
+ assert.Equal(t, "product_view", viewDiff.ViewName)
+
+ // Critical assertion: No metadata should be present (AST-only mode)
+ assert.Nil(t, viewDiff.NewView, "AST-only mode should not extract metadata")
+ assert.Nil(t, viewDiff.OldView, "AST-only mode should not extract metadata")
+
+ // But AST nodes should be present
+ assert.NotNil(t, viewDiff.NewASTNode, "AST node should be present for CREATE action")
+ assert.Nil(t, viewDiff.OldASTNode, "No old AST node for CREATE action")
+
+ // Generate migration should work with AST nodes only
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+ assert.Contains(t, migrationSQL, "CREATE VIEW product_view AS SELECT 1 as id, 'product' as name")
+}
+
+func TestViewDependencyHandlingInAST(t *testing.T) {
+ // Test that verifies dependency extraction works in AST-only mode
+ // This test creates two views where one depends on the other
+ previousSDL := ``
+ currentSDL := `
+ -- Create a base view first
+ CREATE VIEW base_data AS
+ SELECT 1 as id, 'item1' as name, 100 as value;
+
+ -- Create a dependent view that references the base view
+ CREATE VIEW summary_report AS
+ SELECT b.name, b.value, b.value * 2 as doubled_value
+ FROM base_data b
+ WHERE b.value > 50;
+ `
+
+ // Get diff without metadata extraction (AST-only mode)
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Should have exactly two view changes (CREATE actions)
+ assert.Len(t, diff.ViewChanges, 2)
+
+ // Verify both views are CREATE actions with AST nodes
+ createCount := 0
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionCreate {
+ createCount++
+ // Verify AST-only mode properties
+ assert.NotNil(t, viewDiff.NewASTNode, "AST node should be present for CREATE action")
+ assert.Nil(t, viewDiff.OldASTNode, "No old AST node for CREATE action")
+ assert.Nil(t, viewDiff.NewView, "AST-only mode should not extract metadata")
+ }
+ }
+ assert.Equal(t, 2, createCount, "Should have two CREATE actions")
+
+ // Generate migration SQL - this should work with dependency resolution
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+ assert.NotEmpty(t, migrationSQL, "Migration SQL should not be empty")
+
+ // Verify the migration contains both views
+ assert.Contains(t, migrationSQL, "CREATE VIEW base_data AS")
+ assert.Contains(t, migrationSQL, "CREATE VIEW summary_report AS")
+
+ // The important test: base_data should be created before summary_report
+ // due to dependency resolution
+ baseIndex := strings.Index(migrationSQL, "CREATE VIEW base_data AS")
+ summaryIndex := strings.Index(migrationSQL, "CREATE VIEW summary_report AS")
+ assert.True(t, baseIndex < summaryIndex && baseIndex >= 0 && summaryIndex >= 0,
+ "base_data should be created before summary_report due to dependency ordering. Migration SQL:\n%s", migrationSQL)
+}
+
+// Helper function to check if a string contains a substring
+func contains(s, substr string) bool {
+ return strings.Contains(s, substr)
+}