Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: fix some bugs for sdl (#17875)
rebelice9e8e04fd7b13
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex c7526847bb..611d96f776 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -98,7 +98,7 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previprocessSequenceChanges(currentChunks, previousChunks, currentDBSDLChunks, diff)// Process comment changes (must be after all object changes are processed)- processCommentChanges(currentChunks, previousChunks, diff)+ processCommentChanges(currentChunks, previousChunks, currentDBSDLChunks, diff)return diff, nil}@@ -2911,9 +2911,10 @@ func columnsEqual(a, b *storepb.ColumnMetadata) bool {// currentDatabaseSDLChunks stores pre-computed SDL chunks from current database metadata// for performance optimization during usability checkstype currentDatabaseSDLChunks struct {- chunks map[string]string // maps chunk identifier to normalized SDL text from current database metadata- columns map[string]string // maps "schema.table.column" to normalized column SDL text- constraints map[string]string // maps "schema.table.constraint" to normalized constraint SDL text+ chunks map[string]string // maps chunk identifier to normalized SDL text (without comments) from current database metadata+ comments map[string][]string // maps chunk identifier to normalized comment texts+ columns map[string]string // maps "schema.table.column" to normalized column SDL text+ constraints map[string]string // maps "schema.table.constraint" to normalized constraint SDL text}// buildCurrentDatabaseSDLChunks pre-computes SDL chunks from the current database schema@@ -2922,6 +2923,7 @@ type currentDatabaseSDLChunks struct {func buildCurrentDatabaseSDLChunks(currentSchema *model.DatabaseSchema) (*currentDatabaseSDLChunks, error) {sdlChunks := ¤tDatabaseSDLChunks{chunks: make(map[string]string),+ comments: make(map[string][]string),columns: make(map[string]string),constraints: make(map[string]string),}@@ -2944,8 +2946,14 @@ func buildCurrentDatabaseSDLChunks(currentSchema *model.DatabaseSchema) (*curren}// Populate SDL chunks with normalized chunk texts from current database metadata+ // Use GetTextWithoutComments() to focus on structural changes only, not comment formatting differencesfor identifier, chunk := range currentSDLChunks.Tables {- sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetText())+ sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetTextWithoutComments())+ // Store comment text for usability check+ commentText := extractCommentTextFromChunk(chunk)+ if commentText != "" {+ sdlChunks.comments[identifier] = []string{commentText}+ }// Extract column and constraint SDL texts for fine-grained usability checksif err := extractColumnAndConstraintSDLTexts(chunk, identifier, sdlChunks); err != nil {@@ -2955,16 +2963,36 @@ func buildCurrentDatabaseSDLChunks(currentSchema *model.DatabaseSchema) (*curren}}for identifier, chunk := range currentSDLChunks.Views {- sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetText())+ sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetTextWithoutComments())+ // Store comment text for usability check+ commentText := extractCommentTextFromChunk(chunk)+ if commentText != "" {+ sdlChunks.comments[identifier] = []string{commentText}+ }}for identifier, chunk := range currentSDLChunks.Functions {- sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetText())+ sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetTextWithoutComments())+ // Store comment text for usability check+ commentText := extractCommentTextFromChunk(chunk)+ if commentText != "" {+ sdlChunks.comments[identifier] = []string{commentText}+ }}for identifier, chunk := range currentSDLChunks.Sequences {- sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetText())+ sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetTextWithoutComments())+ // Store comment text for usability check+ commentText := extractCommentTextFromChunk(chunk)+ if commentText != "" {+ sdlChunks.comments[identifier] = []string{commentText}+ }}for identifier, chunk := range currentSDLChunks.Indexes {- sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetText())+ sdlChunks.chunks[identifier] = strings.TrimSpace(chunk.GetTextWithoutComments())+ // Store comment text for usability check+ commentText := extractCommentTextFromChunk(chunk)+ if commentText != "" {+ sdlChunks.comments[identifier] = []string{commentText}+ }}return sdlChunks, nil@@ -3048,6 +3076,32 @@ func (sdlChunks *currentDatabaseSDLChunks) shouldSkipChunkDiffForUsability(chunkreturn normalizedChunkText == currentDatabaseSDLText}+// shouldSkipCommentDiff checks if a comment should skip diff comparison+// by comparing against the pre-computed comment texts from current database metadata+func shouldSkipCommentDiff(commentText string, objectIdentifier string, sdlChunks *currentDatabaseSDLChunks) bool {+ if sdlChunks == nil || len(sdlChunks.comments) == 0 {+ return false+ }++ // Get the corresponding comment text from current database metadata+ currentDatabaseComments, exists := sdlChunks.comments[objectIdentifier]+ if !exists || len(currentDatabaseComments) == 0 {+ return false+ }++ // Normalize current comment text for comparison+ normalizedCommentText := strings.TrimSpace(commentText)++ // Check if comment matches any of the database comments (typically just one)+ for _, dbComment := range currentDatabaseComments {+ if normalizedCommentText == strings.TrimSpace(dbComment) {+ return true+ }+ }++ return false+}+// shouldSkipColumnDiffForUsability checks if a column should skip diff comparison// by comparing against the pre-computed column SDL texts from current database metadatafunc (sdlChunks *currentDatabaseSDLChunks) shouldSkipColumnDiffForUsability(columnText string, schemaName, tableName, columnName string) bool {@@ -4759,18 +4813,18 @@ func (e *sequenceExtractor) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext)// processCommentChanges processes comment changes for all database objects// It must be called after all object changes have been processed to determine// which objects were created or dropped (those should not generate comment diffs)-func processCommentChanges(currentChunks, previousChunks *schema.SDLChunks, diff *schema.MetadataDiff) {+func processCommentChanges(currentChunks, previousChunks *schema.SDLChunks, currentDBSDLChunks *currentDatabaseSDLChunks, diff *schema.MetadataDiff) {// Build sets of created and dropped objects to avoid generating comment diffs for themcreatedObjects := buildCreatedObjectsSet(diff)droppedObjects := buildDroppedObjectsSet(diff)// Process object-level comments- processObjectComments(currentChunks.Tables, previousChunks.Tables, schema.CommentObjectTypeTable, createdObjects, droppedObjects, diff)- processObjectComments(currentChunks.Views, previousChunks.Views, schema.CommentObjectTypeView, createdObjects, droppedObjects, diff)- processObjectComments(currentChunks.Functions, previousChunks.Functions, schema.CommentObjectTypeFunction, createdObjects, droppedObjects, diff)- processObjectComments(currentChunks.Sequences, previousChunks.Sequences, schema.CommentObjectTypeSequence, createdObjects, droppedObjects, diff)- processObjectComments(currentChunks.Indexes, previousChunks.Indexes, schema.CommentObjectTypeIndex, createdObjects, droppedObjects, diff)- processObjectComments(currentChunks.Schemas, previousChunks.Schemas, schema.CommentObjectTypeSchema, createdObjects, droppedObjects, diff)+ processObjectComments(currentChunks.Tables, previousChunks.Tables, schema.CommentObjectTypeTable, createdObjects, droppedObjects, currentDBSDLChunks, diff)+ processObjectComments(currentChunks.Views, previousChunks.Views, schema.CommentObjectTypeView, createdObjects, droppedObjects, currentDBSDLChunks, diff)+ processObjectComments(currentChunks.Functions, previousChunks.Functions, schema.CommentObjectTypeFunction, createdObjects, droppedObjects, currentDBSDLChunks, diff)+ processObjectComments(currentChunks.Sequences, previousChunks.Sequences, schema.CommentObjectTypeSequence, createdObjects, droppedObjects, currentDBSDLChunks, diff)+ processObjectComments(currentChunks.Indexes, previousChunks.Indexes, schema.CommentObjectTypeIndex, createdObjects, droppedObjects, currentDBSDLChunks, diff)+ processObjectComments(currentChunks.Schemas, previousChunks.Schemas, schema.CommentObjectTypeSchema, createdObjects, droppedObjects, currentDBSDLChunks, diff)// Process column commentsprocessColumnComments(currentChunks, previousChunks, createdObjects, droppedObjects, diff)@@ -4849,7 +4903,7 @@ func buildDroppedObjectsSet(diff *schema.MetadataDiff) map[string]bool {// processObjectComments processes comment changes for a specific object type// droppedObjects is intentionally unused because we only process objects in currentMap,// and dropped objects won't appear there.-func processObjectComments(currentMap, previousMap map[string]*schema.SDLChunk, objectType schema.CommentObjectType, createdObjects, _ map[string]bool, diff *schema.MetadataDiff) {+func processObjectComments(currentMap, previousMap map[string]*schema.SDLChunk, objectType schema.CommentObjectType, createdObjects, _ map[string]bool, currentDBSDLChunks *currentDatabaseSDLChunks, diff *schema.MetadataDiff) {// Process all objects in current chunksfor identifier, currentChunk := range currentMap {// Skip if object was created (comment will be in CREATE statement)@@ -4867,8 +4921,12 @@ func processObjectComments(currentMap, previousMap map[string]*schema.SDLChunk,currentCommentText := extractCommentTextFromChunk(currentChunk)previousCommentText := extractCommentTextFromChunk(previousChunk)- // If comments are different, generate a CommentDiff+ // If comments are different, check usability before generating a CommentDiffif currentCommentText != previousCommentText {+ // Apply usability check: skip comment diff if current comment matches database metadata+ if currentDBSDLChunks != nil && shouldSkipCommentDiff(currentCommentText, identifier, currentDBSDLChunks) {+ continue+ }var schemaName, objectName string// For SCHEMA objects, identifier is just the schema namediff --git a/backend/plugin/schema/pg/get_sdl_diff_test.go b/backend/plugin/schema/pg/get_sdl_diff_test.goindex b7820d1578..e9769de5ee 100644--- a/backend/plugin/schema/pg/get_sdl_diff_test.go+++ b/backend/plugin/schema/pg/get_sdl_diff_test.go@@ -1208,6 +1208,75 @@ func TestShouldSkipChunkDiffForUsability(t *testing.T) {},}+ // Create a schema with table comment for testing comment-related scenarios+ testSchemaWithComment := model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "products",+ Comment: "Product catalog table",+ Columns: []*storepb.ColumnMetadata{+ {+ Name: "id",+ Type: "integer",+ Nullable: false,+ },+ {+ Name: "name",+ Type: "text",+ Nullable: false,+ },+ },+ Indexes: []*storepb.IndexMetadata{+ {+ Name: "products_pkey",+ Unique: true,+ Primary: true,+ KeyLength: []int64{},+ Expressions: []string{"id"},+ },+ },+ },+ },+ },+ },+ },+ nil,+ nil,+ storepb.Engine_POSTGRES,+ false,+ )++ // Additional tests for comment-related scenarios+ commentTests := []struct {+ name string+ chunkText string+ chunkID string+ currentSchema *model.DatabaseSchema+ expectedSkip bool+ description string+ }{+ {+ name: "table_with_same_structure_but_comment_format_differs_should_skip",+ chunkText: `CREATE TABLE "public"."products" (+ "id" integer NOT NULL,+ "name" text NOT NULL,+ CONSTRAINT "products_pkey" PRIMARY KEY (id)+)`,+ chunkID: "public.products",+ currentSchema: testSchemaWithComment,+ expectedSkip: true,+ description: "Table structure is identical (both from database and user SDL). In real usage, GetTextWithoutComments() is called before shouldSkipChunkDiffForUsability, so COMMENT is already excluded. This test verifies that identical structure should skip diff.",+ },+ }++ // Combine original tests with comment tests+ tests = append(tests, commentTests...)+for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {t.Logf("Test description: %s", tt.description)diff --git a/backend/plugin/schema/pg/usability_check_test.go b/backend/plugin/schema/pg/usability_check_test.gonew file mode 100644index 0000000000..e7b8763ce4--- /dev/null+++ b/backend/plugin/schema/pg/usability_check_test.go@@ -0,0 +1,646 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+ "github.com/bytebase/bytebase/backend/store/model"+)++// TestUsabilityCheck_TableScenarios tests all usability check scenarios for tables+func TestUsabilityCheck_TableScenarios(t *testing.T) {+ tests := []struct {+ name string+ currentSDL string+ previousSDL string+ currentSchema *model.DatabaseSchema+ expectTableDiff bool+ expectCommentDiff bool+ description string+ }{+ {+ name: "scenario_1_same_structure_same_comment_should_skip_both",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++COMMENT ON TABLE "public"."users" IS 'User information table';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text NOT NULL+);++COMMENT ON TABLE "public"."users" IS 'User table description';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Comment: "User information table",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: true},+ },+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectTableDiff: false,+ expectCommentDiff: false,+ description: "Structure matches database, comment matches database → skip both diffs",+ },+ {+ name: "scenario_2_same_structure_different_comment_should_skip_structure_only",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++COMMENT ON TABLE "public"."users" IS 'Updated user table description';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text NOT NULL+);++COMMENT ON TABLE "public"."users" IS 'Old user table description';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Comment: "User information table",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: true},+ },+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectTableDiff: false,+ expectCommentDiff: true,+ description: "Structure matches database → skip structure diff, comment differs → generate comment diff",+ },+ {+ name: "scenario_3_different_structure_same_comment_should_skip_comment_only",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text,+ "email" varchar(255)+);++COMMENT ON TABLE "public"."users" IS 'User information table';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++COMMENT ON TABLE "public"."users" IS 'Old user table';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Comment: "User information table",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: true},+ },+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectTableDiff: true,+ expectCommentDiff: false,+ description: "Structure differs → generate structure diff, comment matches database → skip comment diff",+ },+ {+ name: "scenario_4_different_structure_different_comment_should_generate_both",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text,+ "email" varchar(255)+);++COMMENT ON TABLE "public"."users" IS 'Updated user information';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++COMMENT ON TABLE "public"."users" IS 'Old user table';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Comment: "User information table",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: true},+ },+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectTableDiff: true,+ expectCommentDiff: true,+ description: "Structure differs → generate structure diff, comment differs → generate comment diff",+ },+ {+ name: "add_comment_to_existing_table",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++COMMENT ON TABLE "public"."users" IS 'Newly added comment';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Comment: "",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: true},+ },+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectTableDiff: false,+ expectCommentDiff: true,+ description: "Adding comment to table without comment in database → skip structure, generate comment diff",+ },+ {+ name: "remove_comment_from_table",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++COMMENT ON TABLE "public"."users" IS 'To be removed';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "users",+ Comment: "User table",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer", Nullable: false},+ {Name: "name", Type: "text", Nullable: true},+ },+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectTableDiff: false,+ expectCommentDiff: true,+ description: "Removing comment while structure matches database → skip structure, generate comment diff",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Logf("Description: %s", tt.description)++ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Check table diff+ hasTableDiff := len(diff.TableChanges) > 0+ require.Equal(t, tt.expectTableDiff, hasTableDiff,+ "Expected table diff=%v but got=%v. TableChanges count: %d",+ tt.expectTableDiff, hasTableDiff, len(diff.TableChanges))++ // Check comment diff+ hasCommentDiff := false+ for _, commentDiff := range diff.CommentChanges {+ if commentDiff.ObjectType == schema.CommentObjectTypeTable &&+ commentDiff.ObjectName == "users" {+ hasCommentDiff = true+ break+ }+ }+ require.Equal(t, tt.expectCommentDiff, hasCommentDiff,+ "Expected comment diff=%v but got=%v. CommentChanges count: %d",+ tt.expectCommentDiff, hasCommentDiff, len(diff.CommentChanges))++ if t.Failed() {+ t.Log("Full diff result:")+ t.Logf(" TableChanges: %d", len(diff.TableChanges))+ for i, tc := range diff.TableChanges {+ t.Logf(" [%d] %s.%s (Action: %s)", i, tc.SchemaName, tc.TableName, tc.Action)+ }+ t.Logf(" CommentChanges: %d", len(diff.CommentChanges))+ for i, cc := range diff.CommentChanges {+ t.Logf(" [%d] %s.%s (Type: %s, Action: %s)",+ i, cc.SchemaName, cc.ObjectName, cc.ObjectType, cc.Action)+ }+ }+ })+ }+}++// TestUsabilityCheck_ViewScenarios tests usability check for views+func TestUsabilityCheck_ViewScenarios(t *testing.T) {+ tests := []struct {+ name string+ currentSDL string+ previousSDL string+ currentSchema *model.DatabaseSchema+ expectViewDiff bool+ expectCommentDiff bool+ description string+ }{+ {+ name: "view_same_definition_same_comment_skip_both",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++CREATE VIEW "public"."active_users" AS SELECT * FROM users WHERE id > 0;++COMMENT ON VIEW "public"."active_users" IS 'View of active users';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++CREATE VIEW "public"."active_users" AS SELECT * FROM users WHERE id < 0;++COMMENT ON VIEW "public"."active_users" IS 'View of all users';+`,+ 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: true},+ },+ },+ },+ Views: []*storepb.ViewMetadata{+ {+ Name: "active_users",+ Definition: "SELECT * FROM users WHERE id > 0",+ Comment: "View of active users",+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectViewDiff: false,+ expectCommentDiff: false,+ description: "View definition and comment match database → skip both",+ },+ {+ name: "view_same_definition_different_comment_skip_view_only",+ currentSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++CREATE VIEW "public"."active_users" AS SELECT * FROM users WHERE id > 0;++COMMENT ON VIEW "public"."active_users" IS 'Updated view comment';+`,+ previousSDL: `+CREATE TABLE "public"."users" (+ "id" integer NOT NULL,+ "name" text+);++CREATE VIEW "public"."active_users" AS SELECT * FROM users;++COMMENT ON VIEW "public"."active_users" IS 'Old view comment';+`,+ 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: true},+ },+ },+ },+ Views: []*storepb.ViewMetadata{+ {+ Name: "active_users",+ Definition: "SELECT * FROM users WHERE id > 0",+ Comment: "View of active users",+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectViewDiff: false,+ expectCommentDiff: true,+ description: "View definition matches database, comment differs → skip view diff, generate comment diff",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Logf("Description: %s", tt.description)++ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Check view diff+ hasViewDiff := len(diff.ViewChanges) > 0+ require.Equal(t, tt.expectViewDiff, hasViewDiff,+ "Expected view diff=%v but got=%v. ViewChanges count: %d",+ tt.expectViewDiff, hasViewDiff, len(diff.ViewChanges))++ // Check comment diff+ hasCommentDiff := false+ for _, commentDiff := range diff.CommentChanges {+ if commentDiff.ObjectType == schema.CommentObjectTypeView &&+ commentDiff.ObjectName == "active_users" {+ hasCommentDiff = true+ break+ }+ }+ require.Equal(t, tt.expectCommentDiff, hasCommentDiff,+ "Expected comment diff=%v but got=%v. CommentChanges count: %d",+ tt.expectCommentDiff, hasCommentDiff, len(diff.CommentChanges))+ })+ }+}++// TestUsabilityCheck_FunctionScenarios tests usability check for functions+func TestUsabilityCheck_FunctionScenarios(t *testing.T) {+ tests := []struct {+ name string+ currentSDL string+ previousSDL string+ currentSchema *model.DatabaseSchema+ expectFunctionDiff bool+ expectCommentDiff bool+ description string+ }{+ {+ name: "function_same_body_same_comment_skip_both",+ currentSDL: `+CREATE FUNCTION "public"."add_numbers"(a integer, b integer) RETURNS integer+ LANGUAGE plpgsql+ AS $$+BEGIN+ RETURN a + b;+END;+$$;++COMMENT ON FUNCTION "public"."add_numbers"(a integer, b integer) IS 'Adds two numbers';+`,+ previousSDL: `+CREATE FUNCTION "public"."add_numbers"(a integer, b integer) RETURNS integer+ LANGUAGE plpgsql+ AS $$+BEGIN+ RETURN a - b;+END;+$$;++COMMENT ON FUNCTION "public"."add_numbers"(a integer, b integer) IS 'Old comment';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Functions: []*storepb.FunctionMetadata{+ {+ Name: "add_numbers",+ Signature: `add_numbers(a integer, b integer)`,+ Definition: `CREATE FUNCTION "public"."add_numbers"(a integer, b integer) RETURNS integer+ LANGUAGE plpgsql+ AS $$+BEGIN+ RETURN a + b;+END;+$$`,+ Comment: "Adds two numbers",+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectFunctionDiff: false,+ expectCommentDiff: false,+ description: "Function body and comment match database → skip both",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Logf("Description: %s", tt.description)++ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Check function diff+ hasFunctionDiff := len(diff.FunctionChanges) > 0+ require.Equal(t, tt.expectFunctionDiff, hasFunctionDiff,+ "Expected function diff=%v but got=%v. FunctionChanges count: %d",+ tt.expectFunctionDiff, hasFunctionDiff, len(diff.FunctionChanges))++ // Check comment diff+ hasCommentDiff := false+ for _, commentDiff := range diff.CommentChanges {+ if commentDiff.ObjectType == schema.CommentObjectTypeFunction &&+ commentDiff.ObjectName == "add_numbers" {+ hasCommentDiff = true+ break+ }+ }+ require.Equal(t, tt.expectCommentDiff, hasCommentDiff,+ "Expected comment diff=%v but got=%v",+ tt.expectCommentDiff, hasCommentDiff)+ })+ }+}++// TestUsabilityCheck_SequenceScenarios tests usability check for sequences+func TestUsabilityCheck_SequenceScenarios(t *testing.T) {+ tests := []struct {+ name string+ currentSDL string+ previousSDL string+ currentSchema *model.DatabaseSchema+ expectSequenceDiff bool+ expectCommentDiff bool+ description string+ }{+ {+ name: "sequence_same_config_same_comment_skip_both",+ currentSDL: `+CREATE SEQUENCE "public"."user_id_seq" START WITH 1 INCREMENT BY 1 NO CYCLE;++COMMENT ON SEQUENCE "public"."user_id_seq" IS 'User ID sequence';+`,+ previousSDL: `+CREATE SEQUENCE "public"."user_id_seq" START WITH 100 INCREMENT BY 2 NO CYCLE;++COMMENT ON SEQUENCE "public"."user_id_seq" IS 'Old sequence comment';+`,+ currentSchema: model.NewDatabaseSchema(+ &storepb.DatabaseSchemaMetadata{+ Name: "test_db",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Sequences: []*storepb.SequenceMetadata{+ {+ Name: "user_id_seq",+ Start: "1",+ Increment: "1",+ Comment: "User ID sequence",+ },+ },+ },+ },+ },+ nil, nil, storepb.Engine_POSTGRES, false,+ ),+ expectSequenceDiff: false,+ expectCommentDiff: false,+ description: "Sequence config and comment match database → skip both",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Logf("Description: %s", tt.description)++ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, tt.currentSchema, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Check sequence diff+ hasSequenceDiff := len(diff.SequenceChanges) > 0+ require.Equal(t, tt.expectSequenceDiff, hasSequenceDiff,+ "Expected sequence diff=%v but got=%v",+ tt.expectSequenceDiff, hasSequenceDiff)++ // Check comment diff+ hasCommentDiff := false+ for _, commentDiff := range diff.CommentChanges {+ if commentDiff.ObjectType == schema.CommentObjectTypeSequence &&+ commentDiff.ObjectName == "user_id_seq" {+ hasCommentDiff = true+ break+ }+ }+ require.Equal(t, tt.expectCommentDiff, hasCommentDiff,+ "Expected comment diff=%v but got=%v",+ tt.expectCommentDiff, hasCommentDiff)+ })+ }+}