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: support pg view in SDL differ (#17429)
rebelicee8f9b30a9cfe
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex 5f7f33906a..ec59a78e9e 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -176,6 +176,8 @@ type ViewDiff struct {ViewName stringOldView *storepb.ViewMetadataNewView *storepb.ViewMetadata+ OldASTNode any // AST node for old view+ NewASTNode any // AST node for new view}// MaterializedViewDiff represents changes to a materialized view.@@ -327,6 +329,8 @@ func addNewSchemaObjects(diff *MetadataDiff, schemaName string, schema *model.ScSchemaName: schemaName,ViewName: viewName,NewView: view.GetProto(),+ OldASTNode: nil,+ NewASTNode: nil,})}}@@ -1447,6 +1451,8 @@ func compareViews(engine storepb.Engine, diff *MetadataDiff, schemaName string,SchemaName: schemaName,ViewName: viewName,OldView: oldView.GetProto(),+ OldASTNode: nil,+ NewASTNode: nil,})}}@@ -1466,6 +1472,8 @@ func compareViews(engine storepb.Engine, diff *MetadataDiff, schemaName string,SchemaName: schemaName,ViewName: viewName,NewView: newView.GetProto(),+ OldASTNode: nil,+ NewASTNode: nil,})} else if !oldView.GetProto().GetSkipDump() {// Use engine-specific comparison@@ -1479,6 +1487,8 @@ func compareViews(engine storepb.Engine, diff *MetadataDiff, schemaName string,ViewName: viewName,OldView: oldView.GetProto(),NewView: newView.GetProto(),+ OldASTNode: nil,+ NewASTNode: nil,})}} else if len(changes) > 0 {@@ -1498,6 +1508,8 @@ func compareViews(engine storepb.Engine, diff *MetadataDiff, schemaName string,ViewName: viewName,OldView: oldView.GetProto(),NewView: newView.GetProto(),+ OldASTNode: nil,+ NewASTNode: nil,})}// TODO: Handle non-recreating changes like comment updatesdiff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex 24561161f3..40fd5505a2 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -52,6 +52,9 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previ// Process index changes (standalone CREATE INDEX statements)processStandaloneIndexChanges(currentChunks, previousChunks, diff)+ // Process view changes+ processViewChanges(currentChunks, previousChunks, diff)+return diff, nil}@@ -199,7 +202,7 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren// Process current table chunks to find created and modified tablesfor identifier, currentChunk := range currentChunks.Tables {- schemaName, tableName := parseTableIdentifier(currentChunk.Identifier)+ schemaName, tableName := parseIdentifier(currentChunk.Identifier)if previousChunk, exists := previousChunks.Tables[identifier]; exists {// Table exists in both - check if modified@@ -263,7 +266,7 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currenfor identifier, previousChunk := range previousChunks.Tables {if _, exists := currentChunks.Tables[identifier]; !exists {// Table was dropped- schemaName, tableName := parseTableIdentifier(previousChunk.Identifier)+ schemaName, tableName := parseIdentifier(previousChunk.Identifier)oldASTNode, ok := previousChunk.ASTNode.(*parser.CreatestmtContext)if !ok {return errors.Errorf("expected CreatestmtContext for dropped table %s", previousChunk.Identifier)@@ -408,7 +411,7 @@ func extractColumnMetadata(columnDef parser.IColumnDefContext) *storepb.ColumnMe}// parseTableIdentifier parses a table identifier and returns schema name and table name-func parseTableIdentifier(identifier string) (schemaName, tableName string) {+func parseIdentifier(identifier string) (schemaName, objectName string) {parts := strings.Split(identifier, ".")if len(parts) == 2 {return parts[0], parts[1]@@ -1183,3 +1186,68 @@ func getOrCreateTableDiff(diff *schema.MetadataDiff, tableName string, affectedTaffectedTables[tableName] = newTableDiffreturn newTableDiff}++// processViewChanges analyzes view changes between current and previous chunks+// Following the text-first comparison pattern for performance optimization+func processViewChanges(currentChunks, previousChunks *schema.SDLChunks, diff *schema.MetadataDiff) {+ // Process current views to find created and modified views+ for 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)+ if currentText != previousText {+ // View was modified - use drop and recreate pattern (PostgreSQL standard)+ schemaName, viewName := parseIdentifier(identifier)+ diff.ViewChanges = append(diff.ViewChanges, &schema.ViewDiff{+ Action: schema.MetadataDiffActionDrop,+ SchemaName: schemaName,+ ViewName: viewName,+ OldView: nil, // Will be populated when SDL drift detection is implemented+ NewView: nil, // Will be populated when SDL drift detection is implemented+ OldASTNode: previousChunk.ASTNode,+ NewASTNode: nil,+ })+ diff.ViewChanges = append(diff.ViewChanges, &schema.ViewDiff{+ Action: schema.MetadataDiffActionCreate,+ SchemaName: schemaName,+ ViewName: viewName,+ OldView: nil, // Will be populated when SDL drift detection is implemented+ NewView: nil, // Will be populated when SDL drift detection is implemented+ OldASTNode: nil,+ NewASTNode: currentChunk.ASTNode,+ })+ }+ // If text is identical, skip - no changes detected+ } else {+ // New view+ schemaName, viewName := parseIdentifier(identifier)+ diff.ViewChanges = append(diff.ViewChanges, &schema.ViewDiff{+ Action: schema.MetadataDiffActionCreate,+ SchemaName: schemaName,+ ViewName: viewName,+ OldView: nil,+ NewView: nil, // Will be populated when SDL drift detection is implemented+ OldASTNode: nil,+ NewASTNode: currentChunk.ASTNode,+ })+ }+ }++ // Process previous views to find dropped ones+ for identifier, previousChunk := range previousChunks.Views {+ if _, exists := currentChunks.Views[identifier]; !exists {+ // View was dropped+ schemaName, viewName := parseIdentifier(identifier)+ diff.ViewChanges = append(diff.ViewChanges, &schema.ViewDiff{+ Action: schema.MetadataDiffActionDrop,+ SchemaName: schemaName,+ ViewName: viewName,+ OldView: nil, // Will be populated when SDL drift detection is implemented+ NewView: nil,+ OldASTNode: previousChunk.ASTNode,+ NewASTNode: nil,+ })+ }+ }+}diff --git a/backend/plugin/schema/pg/view_sdl_diff_test.go b/backend/plugin/schema/pg/view_sdl_diff_test.gonew file mode 100644index 0000000000..8feb832692--- /dev/null+++ b/backend/plugin/schema/pg/view_sdl_diff_test.go@@ -0,0 +1,247 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/plugin/schema"+)++func TestViewSDLDiff(t *testing.T) {+ tests := []struct {+ name string+ previousSDL string+ currentSDL string+ expectedViewChanges int+ expectedActions []schema.MetadataDiffAction+ }{+ {+ name: "Create new view",+ previousSDL: ``,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE VIEW active_users AS+ SELECT id, name+ FROM users+ WHERE active = true;+ `,+ expectedViewChanges: 1,+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ {+ name: "Drop view",+ previousSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE VIEW active_users AS+ SELECT id, name+ FROM users+ WHERE active = true;+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );+ `,+ expectedViewChanges: 1,+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop},+ },+ {+ name: "Modify view (drop and recreate)",+ previousSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL,+ active BOOLEAN DEFAULT true+ );++ CREATE VIEW active_users AS+ SELECT id, name+ FROM users+ WHERE active = true;+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL,+ active BOOLEAN DEFAULT true+ );++ CREATE VIEW active_users AS+ SELECT id, name, 'active' as status+ FROM users+ WHERE active = true;+ `,+ expectedViewChanges: 2, // Drop + Create+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop, schema.MetadataDiffActionCreate},+ },+ {+ name: "No changes to view",+ previousSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE VIEW active_users AS+ SELECT id, name+ FROM users+ WHERE active = true;+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE VIEW active_users AS+ SELECT id, name+ FROM users+ WHERE active = true;+ `,+ expectedViewChanges: 0,+ expectedActions: []schema.MetadataDiffAction{},+ },+ {+ name: "Multiple views with different changes",+ previousSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE VIEW all_users AS+ SELECT * FROM users;++ CREATE VIEW active_users AS+ SELECT id, name FROM users WHERE active = true;+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255) NOT NULL+ );++ CREATE VIEW all_users AS+ SELECT * FROM users;++ CREATE VIEW admin_users AS+ SELECT id, name FROM users WHERE role = 'admin';+ `,+ expectedViewChanges: 2, // Drop active_users + Create admin_users+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate, schema.MetadataDiffActionDrop},+ },+ {+ name: "Schema-qualified view names",+ previousSDL: `+ CREATE SCHEMA test_schema;+ CREATE TABLE test_schema.products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255)+ );+ `,+ currentSDL: `+ CREATE SCHEMA test_schema;+ CREATE TABLE test_schema.products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(255)+ );++ CREATE VIEW test_schema.product_summary AS+ SELECT id, name FROM test_schema.products;+ `,+ expectedViewChanges: 1,+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ assert.Equal(t, tt.expectedViewChanges, len(diff.ViewChanges),+ "Expected %d view changes, got %d", tt.expectedViewChanges, len(diff.ViewChanges))++ // Check that the actions match expectations+ var actualActions []schema.MetadataDiffAction+ for _, viewDiff := range diff.ViewChanges {+ actualActions = append(actualActions, viewDiff.Action)+ }++ // Handle nil vs empty slice comparison+ if len(tt.expectedActions) == 0 && len(actualActions) == 0 {+ // Both are effectively empty - test passes+ t.Log("Both expected and actual actions are empty")+ } else {+ assert.ElementsMatch(t, tt.expectedActions, actualActions,+ "Expected actions %v, got %v", tt.expectedActions, actualActions)+ }++ // Verify AST nodes are properly set+ for i, viewDiff := range diff.ViewChanges {+ switch viewDiff.Action {+ case schema.MetadataDiffActionCreate:+ assert.NotNil(t, viewDiff.NewASTNode,+ "View diff %d should have NewASTNode for CREATE action", i)+ assert.Nil(t, viewDiff.OldASTNode,+ "View diff %d should not have OldASTNode for CREATE action", i)+ case schema.MetadataDiffActionDrop:+ assert.NotNil(t, viewDiff.OldASTNode,+ "View diff %d should have OldASTNode for DROP action", i)+ assert.Nil(t, viewDiff.NewASTNode,+ "View diff %d should not have NewASTNode for DROP action", i)+ default:+ t.Errorf("Unexpected action %v for view diff %d", viewDiff.Action, i)+ }+ }+ })+ }+}++func TestIdentifierParsing(t *testing.T) {+ tests := []struct {+ name string+ identifier string+ expectedSchema string+ expectedView string+ }{+ {+ name: "Simple view name",+ identifier: "my_view",+ expectedSchema: "public",+ expectedView: "my_view",+ },+ {+ name: "Schema-qualified view name",+ identifier: "test_schema.my_view",+ expectedSchema: "test_schema",+ expectedView: "my_view",+ },+ {+ name: "Public schema explicit",+ identifier: "public.user_summary",+ expectedSchema: "public",+ expectedView: "user_summary",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ schema, view := parseIdentifier(tt.identifier)+ assert.Equal(t, tt.expectedSchema, schema)+ assert.Equal(t, tt.expectedView, view)+ })+ }+}