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 function, procedure and sequence drift in SDL workflow (#17513)
rebelicef35e12b1f3d8
diff --git a/backend/plugin/schema/pg/function_rewrite_test.go b/backend/plugin/schema/pg/function_rewrite_test.gonew file mode 100644index 0000000000..76235487b5--- /dev/null+++ b/backend/plugin/schema/pg/function_rewrite_test.go@@ -0,0 +1,526 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ parser "github.com/bytebase/parser/postgresql"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+)++// TestFunctionRewriteOperations tests the ANTLR TokenStreamRewriter functionality+// for standalone CREATE FUNCTION operations including add, modify, delete+func TestFunctionRewriteOperations(t *testing.T) {+ testCases := []struct {+ name string+ originalSDL string+ currentFunctions []*storepb.FunctionMetadata+ previousFunctions []*storepb.FunctionMetadata+ expectedFunctionCount int+ description string+ }{+ {+ name: "Add new standalone function",+ originalSDL: `CREATE TABLE users (+ id INTEGER NOT NULL,+ email VARCHAR(255) NOT NULL+);`,+ currentFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_user_count",+ Definition: `CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ previousFunctions: []*storepb.FunctionMetadata{},+ expectedFunctionCount: 1,+ description: "Should add new standalone function to chunks",+ },+ {+ name: "Add function with complex signature",+ originalSDL: `CREATE TABLE orders (+ id INTEGER NOT NULL,+ amount DECIMAL(10,2) NOT NULL+);`,+ currentFunctions: []*storepb.FunctionMetadata{+ {+ Name: "calculate_total",+ Definition: `CREATE OR REPLACE FUNCTION calculate_total(+ p_start_date DATE,+ p_end_date DATE,+ p_discount_rate DECIMAL DEFAULT 0.0+)+RETURNS DECIMAL(10,2) AS $$+BEGIN+ RETURN (+ SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)+ FROM orders+ WHERE created_at::DATE BETWEEN p_start_date AND p_end_date+ );+END;+$$ LANGUAGE plpgsql`,+ },+ },+ previousFunctions: []*storepb.FunctionMetadata{},+ expectedFunctionCount: 1,+ description: "Should add new function with complex signature to chunks",+ },+ {+ name: "Drop standalone function",+ originalSDL: `CREATE TABLE users (+ id INTEGER NOT NULL,+ email VARCHAR(255) NOT NULL+);++CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql;`,+ currentFunctions: []*storepb.FunctionMetadata{},+ previousFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_user_count",+ Definition: `CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ expectedFunctionCount: 0,+ description: "Should remove standalone function from chunks",+ },+ {+ name: "Modify function (change definition)",+ originalSDL: `CREATE TABLE users (+ id INTEGER NOT NULL,+ email VARCHAR(255) NOT NULL,+ active BOOLEAN DEFAULT true+);++CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql;`,+ currentFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_user_count",+ Definition: `CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users WHERE active = true);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ previousFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_user_count",+ Definition: `CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ expectedFunctionCount: 1,+ description: "Should modify existing function when definition changes",+ },+ {+ name: "Multiple function operations",+ originalSDL: `CREATE TABLE orders (+ id INTEGER NOT NULL,+ customer_id INTEGER,+ total DECIMAL(10,2),+ status VARCHAR(20)+);++CREATE OR REPLACE FUNCTION get_order_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM orders);+END;+$$ LANGUAGE plpgsql;`,+ currentFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_total_amount",+ Definition: `CREATE OR REPLACE FUNCTION get_total_amount()+RETURNS DECIMAL(10,2) AS $$+BEGIN+ RETURN (SELECT SUM(total) FROM orders);+END;+$$ LANGUAGE plpgsql`,+ },+ {+ Name: "get_active_orders",+ Definition: `CREATE OR REPLACE FUNCTION get_active_orders()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM orders WHERE status = 'active');+END;+$$ LANGUAGE plpgsql`,+ },+ },+ previousFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_order_count",+ Definition: `CREATE OR REPLACE FUNCTION get_order_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM orders);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ expectedFunctionCount: 2,+ description: "Should handle multiple function operations (drop old, add new)",+ },+ {+ name: "Schema-qualified function names",+ originalSDL: `CREATE SCHEMA test_schema;+CREATE TABLE test_schema.products (+ id INTEGER NOT NULL,+ name VARCHAR(255)+);`,+ currentFunctions: []*storepb.FunctionMetadata{+ {+ Name: "get_product_count",+ Definition: `CREATE OR REPLACE FUNCTION test_schema.get_product_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM test_schema.products);+END;+$$ LANGUAGE plpgsql`,+ },+ },+ previousFunctions: []*storepb.FunctionMetadata{},+ expectedFunctionCount: 1,+ description: "Should handle schema-qualified function names",+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ // Parse the original SDL to create chunks+ chunks, err := ChunkSDLText(tc.originalSDL)+ require.NoError(t, err, "Failed to parse original SDL")++ // Create function maps for simulation+ currentFunctions := make(map[string]*storepb.FunctionMetadata)+ previousFunctions := make(map[string]*storepb.FunctionMetadata)++ for _, fn := range tc.currentFunctions {+ key := formatFunctionKey("public", fn)+ currentFunctions[key] = fn+ }++ for _, fn := range tc.previousFunctions {+ key := formatFunctionKey("public", fn)+ previousFunctions[key] = fn+ }++ // Apply function changes directly to test the core logic+ err = applyFunctionChangesInternal(chunks, currentFunctions, previousFunctions)+ require.NoError(t, err, "Failed to apply function changes")++ // Verify the expected number of functions+ assert.Len(t, chunks.Functions, tc.expectedFunctionCount,+ "Expected %d functions, got %d", tc.expectedFunctionCount, len(chunks.Functions))++ // Verify each current function is present+ for key, fn := range currentFunctions {+ chunk, exists := chunks.Functions[key]+ assert.True(t, exists, "Expected function %s not found in chunks", key)+ if exists {+ assert.NotNil(t, chunk.ASTNode, "Function chunk should have AST node")+ // Verify we can get text from the chunk using the proper extraction function+ if functionAST, ok := chunk.ASTNode.(*parser.CreatefunctionstmtContext); ok {+ text := extractFunctionTextFromAST(functionAST)+ assert.NotEmpty(t, text, "Function chunk should have non-empty text")+ assert.Contains(t, text, "CREATE", "Function text should contain CREATE")+ assert.Contains(t, text, "FUNCTION", "Function text should contain FUNCTION")+ assert.Contains(t, text, fn.Name, "Function text should contain function name")+ }+ }+ }++ // Verify previous functions that shouldn't exist are removed+ for key := range previousFunctions {+ if _, stillExists := currentFunctions[key]; !stillExists {+ _, exists := chunks.Functions[key]+ assert.False(t, exists, "Function %s should have been removed from chunks", key)+ }+ }++ t.Logf("Test case '%s' passed: %s", tc.name, tc.description)+ })+ }+}++// applyFunctionChangesInternal is a test helper that directly applies function changes to chunks+func applyFunctionChangesInternal(chunks *schema.SDLChunks, currentFunctions, previousFunctions map[string]*storepb.FunctionMetadata) error {+ if chunks == nil {+ return nil+ }++ // Process function additions: create new function chunks+ for functionKey, currentFunction := range currentFunctions {+ if _, exists := previousFunctions[functionKey]; !exists {+ // New function - create a chunk for it+ err := createFunctionChunk(chunks, currentFunction, functionKey)+ if err != nil {+ return err+ }+ }+ }++ // Process function modifications: update existing chunks+ for functionKey, currentFunction := range currentFunctions {+ if previousFunction, exists := previousFunctions[functionKey]; exists {+ // Function exists in both - check if it needs modification+ err := updateFunctionChunkIfNeeded(chunks, currentFunction, previousFunction, functionKey)+ if err != nil {+ return err+ }+ }+ }++ // Process function deletions: remove dropped function chunks+ for functionKey := range previousFunctions {+ if _, exists := currentFunctions[functionKey]; !exists {+ // Function was dropped - remove it from chunks+ deleteFunctionChunk(chunks, functionKey)+ }+ }++ return nil+}++// TestGenerateCreateFunctionSDL tests the SDL generation for CREATE FUNCTION statements+func TestGenerateCreateFunctionSDL(t *testing.T) {+ testCases := []struct {+ name string+ function *storepb.FunctionMetadata+ expectedSDL string+ }{+ {+ name: "Simple function",+ function: &storepb.FunctionMetadata{+ Name: "get_user_count",+ Definition: `CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql`,+ },+ expectedSDL: `CREATE OR REPLACE FUNCTION get_user_count()+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM users);+END;+$$ LANGUAGE plpgsql`,+ },+ {+ name: "Function with parameters",+ function: &storepb.FunctionMetadata{+ Name: "calculate_total",+ Definition: `CREATE OR REPLACE FUNCTION calculate_total(+ p_start_date DATE,+ p_end_date DATE,+ p_discount_rate DECIMAL DEFAULT 0.0+)+RETURNS DECIMAL(10,2) AS $$+BEGIN+ RETURN (+ SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)+ FROM orders+ WHERE created_at::DATE BETWEEN p_start_date AND p_end_date+ );+END;+$$ LANGUAGE plpgsql`,+ },+ expectedSDL: `CREATE OR REPLACE FUNCTION calculate_total(+ p_start_date DATE,+ p_end_date DATE,+ p_discount_rate DECIMAL DEFAULT 0.0+)+RETURNS DECIMAL(10,2) AS $$+BEGIN+ RETURN (+ SELECT COALESCE(SUM(amount * (1 - p_discount_rate)), 0)+ FROM orders+ WHERE created_at::DATE BETWEEN p_start_date AND p_end_date+ );+END;+$$ LANGUAGE plpgsql`,+ },+ {+ name: "Function with trailing semicolon",+ function: &storepb.FunctionMetadata{+ Name: "simple_func",+ Definition: `CREATE OR REPLACE FUNCTION simple_func()+RETURNS TEXT AS $$+BEGIN+ RETURN 'hello';+END;+$$ LANGUAGE plpgsql;`,+ },+ expectedSDL: `CREATE OR REPLACE FUNCTION simple_func()+RETURNS TEXT AS $$+BEGIN+ RETURN 'hello';+END;+$$ LANGUAGE plpgsql`,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ result := generateCreateFunctionSDL(tc.function)+ assert.Equal(t, tc.expectedSDL, result)+ })+ }+}++// TestFunctionDefinitionsEqual tests the function comparison logic+func TestFunctionDefinitionsEqual(t *testing.T) {+ testCases := []struct {+ name string+ function1 *storepb.FunctionMetadata+ function2 *storepb.FunctionMetadata+ expected bool+ }{+ {+ name: "Identical functions",+ function1: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ function2: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ expected: true,+ },+ {+ name: "Different names",+ function1: &storepb.FunctionMetadata{+ Name: "test_func1",+ Definition: `CREATE OR REPLACE FUNCTION test_func1()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ function2: &storepb.FunctionMetadata{+ Name: "test_func2",+ Definition: `CREATE OR REPLACE FUNCTION test_func2()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ expected: false,+ },+ {+ name: "Different definitions",+ function1: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ function2: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 2;+END;+$$ LANGUAGE plpgsql`,+ },+ expected: false,+ },+ {+ name: "Same definition with different trailing semicolons",+ function1: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ function2: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql;`,+ },+ expected: true,+ },+ {+ name: "Same definition with different whitespace",+ function1: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: `CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql`,+ },+ function2: &storepb.FunctionMetadata{+ Name: "test_func",+ Definition: ` CREATE OR REPLACE FUNCTION test_func()+RETURNS INTEGER AS $$+BEGIN+ RETURN 1;+END;+$$ LANGUAGE plpgsql `,+ },+ expected: true,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ result := functionDefinitionsEqual(tc.function1, tc.function2)+ assert.Equal(t, tc.expected, result)+ })+ }+}diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex b5507043ed..7880bd26aa 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -183,26 +183,24 @@ func (l *sdlChunkExtractor) EnterCreatefunctionstmt(ctx *parser.Createfunctionst}// Parse schema and function name directly from parts- var schemaName, functionName string+ var schemaName stringif len(funcNameParts) == 2 {// Schema qualified: schema.function_nameschemaName = funcNameParts[0]- functionName = funcNameParts[1]} else if len(funcNameParts) == 1 {// Unqualified: function_name (assume public schema)schemaName = "public"- functionName = funcNameParts[0]} else {// Unexpected formatreturn}- if functionName == "" {+ // Use the unified function signature extraction+ signature := extractFunctionSignatureFromAST(ctx)+ if signature == "" {return}- // Generate function signature with parameter types- signature := ExtractFunctionSignature(ctx, functionName)schemaQualifiedSignature := schemaName + "." + signaturechunk := &schema.SDLChunk{@@ -1687,6 +1685,18 @@ func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchemareturn errors.Wrap(err, "failed to apply standalone index changes")}+ // Process function changes: apply minimal changes to function chunks+ err = applyFunctionChangesToChunks(previousChunks, currentSchema, previousSchema)+ if err != nil {+ return errors.Wrap(err, "failed to apply function changes")+ }++ // Process sequence changes: apply minimal changes to sequence chunks+ err = applySequenceChangesToChunks(previousChunks, currentSchema, previousSchema)+ if err != nil {+ return errors.Wrap(err, "failed to apply sequence changes")+ }+return nil}@@ -2884,3 +2894,627 @@ func (e *indexExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {*e.result = ctx}}++// applyFunctionChangesToChunks applies minimal changes to CREATE FUNCTION chunks+// This handles creation, modification, and deletion of function statements+func applyFunctionChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema) error {+ if currentSchema == nil || previousSchema == nil || previousChunks == nil {+ return nil+ }++ // Get function differences by comparing schema metadata+ currentMetadata := currentSchema.GetMetadata()+ previousMetadata := previousSchema.GetMetadata()+ if currentMetadata == nil || previousMetadata == nil {+ return nil+ }++ // Build function maps for current and previous schemas+ currentFunctions := make(map[string]*storepb.FunctionMetadata)+ previousFunctions := make(map[string]*storepb.FunctionMetadata)++ // Collect all functions from current schema+ for _, schema := range currentMetadata.Schemas {+ for _, function := range schema.Functions {+ functionKey := formatFunctionKey(schema.Name, function)+ currentFunctions[functionKey] = function+ }+ }++ // Collect all functions from previous schema+ for _, schema := range previousMetadata.Schemas {+ for _, function := range schema.Functions {+ functionKey := formatFunctionKey(schema.Name, function)+ previousFunctions[functionKey] = function+ }+ }++ // Process function additions: create new function chunks+ for functionKey, currentFunction := range currentFunctions {+ if _, exists := previousFunctions[functionKey]; !exists {+ // New function - create a chunk for it+ err := createFunctionChunk(previousChunks, currentFunction, functionKey)+ if err != nil {+ return errors.Wrapf(err, "failed to create function chunk for %s", functionKey)+ }+ }+ }++ // Process function modifications: update existing chunks+ for functionKey, currentFunction := range currentFunctions {+ if previousFunction, exists := previousFunctions[functionKey]; exists {+ // Function exists in both - check if it needs modification+ err := updateFunctionChunkIfNeeded(previousChunks, currentFunction, previousFunction, functionKey)+ if err != nil {+ return errors.Wrapf(err, "failed to update function chunk for %s", functionKey)+ }+ }+ }++ // Process function deletions: remove dropped function chunks+ for functionKey := range previousFunctions {+ if _, exists := currentFunctions[functionKey]; !exists {+ // Function was dropped - remove it from chunks+ deleteFunctionChunk(previousChunks, functionKey)+ }+ }++ return nil+}++// formatFunctionKey creates a consistent key for function identification using the full signature+func formatFunctionKey(schemaName string, function *storepb.FunctionMetadata) string {+ if schemaName == "" {+ schemaName = "public"+ }++ // Extract the function signature from the definition+ signature := extractFunctionSignatureFromDefinition(function)+ if signature == "" {+ // Fallback to just the function name if signature extraction fails+ signature = function.Name + "()"+ }++ return schemaName + "." + signature+}++// extractFunctionSignatureFromDefinition extracts the function signature from its definition+func extractFunctionSignatureFromDefinition(function *storepb.FunctionMetadata) string {+ if function == nil || function.Definition == "" {+ return ""+ }++ // Parse the function definition to extract signature+ parseResult, err := pgparser.ParsePostgreSQL(function.Definition)+ if err != nil {+ return ""+ }++ tree := parseResult.Tree++ // Extract the CREATE FUNCTION node using a walker+ var result *parser.CreatefunctionstmtContext+ extractor := &functionExtractor{result: &result}+ antlr.NewParseTreeWalker().Walk(extractor, tree)++ if result == nil {+ return ""+ }++ // Use the unified function signature extraction+ return extractFunctionSignatureFromAST(result)+}++// extractFunctionSignatureFromAST extracts function signature from CREATE FUNCTION AST node+// This is the unified function used by both chunk extraction and function comparison+func extractFunctionSignatureFromAST(ctx *parser.CreatefunctionstmtContext) string {+ if ctx == nil {+ return ""+ }++ funcNameCtx := ctx.Func_name()+ if funcNameCtx == nil {+ return ""+ }++ // Extract function name using proper normalization+ funcNameParts := pgparser.NormalizePostgreSQLFuncName(funcNameCtx)+ if len(funcNameParts) == 0 {+ return ""+ }++ // Get the function name (without schema)+ var functionName string+ if len(funcNameParts) == 2 {+ // Schema qualified: schema.function_name+ functionName = funcNameParts[1]+ } else if len(funcNameParts) == 1 {+ // Unqualified: function_name+ functionName = funcNameParts[0]+ } else {+ // Unexpected format+ return ""+ }++ if functionName == "" {+ return ""+ }++ // Use the existing ExtractFunctionSignature function+ return ExtractFunctionSignature(ctx, functionName)+}++// createFunctionChunk creates a new CREATE FUNCTION chunk and adds it to the chunks+func createFunctionChunk(chunks *schema.SDLChunks, function *storepb.FunctionMetadata, functionKey string) error {+ if function == nil || chunks == nil {+ return nil+ }++ // Generate function SDL using the existing writeFunctionSDL function+ sdl := generateCreateFunctionSDL(function)+ if sdl == "" {+ return errors.Errorf("failed to generate SDL for function %s", functionKey)+ }++ // Parse the SDL to get the AST node+ astNode, err := extractFunctionASTFromSDL(sdl)+ if err != nil {+ return errors.Wrapf(err, "failed to extract AST from generated function SDL for %s", functionKey)+ }++ // Create the chunk+ chunk := &schema.SDLChunk{+ Identifier: functionKey,+ ASTNode: astNode,+ }++ // Ensure Functions map is initialized+ if chunks.Functions == nil {+ chunks.Functions = make(map[string]*schema.SDLChunk)+ }++ chunks.Functions[functionKey] = chunk+ return nil+}++// updateFunctionChunkIfNeeded updates a function chunk if the definition has changed+func updateFunctionChunkIfNeeded(chunks *schema.SDLChunks, currentFunction, previousFunction *storepb.FunctionMetadata, functionKey string) error {+ if currentFunction == nil || previousFunction == nil || chunks == nil {+ return nil+ }++ // Check if function definitions are different+ if !functionDefinitionsEqual(currentFunction, previousFunction) {+ // Function was modified - update the chunk+ err := updateFunctionChunk(chunks, currentFunction, functionKey)+ if err != nil {+ return errors.Wrapf(err, "failed to update function chunk for %s", functionKey)+ }+ }++ return nil+}++// updateFunctionChunk updates an existing function chunk with new definition+func updateFunctionChunk(chunks *schema.SDLChunks, function *storepb.FunctionMetadata, functionKey string) error {+ if function == nil || chunks == nil {+ return nil+ }++ // Generate new function SDL+ sdl := generateCreateFunctionSDL(function)+ if sdl == "" {+ return errors.Errorf("failed to generate SDL for function %s", functionKey)+ }++ // Parse the SDL to get the AST node+ astNode, err := extractFunctionASTFromSDL(sdl)+ if err != nil {+ return errors.Wrapf(err, "failed to extract AST from generated function SDL for %s", functionKey)+ }++ // Update the existing chunk+ if chunk := chunks.Functions[functionKey]; chunk != nil {+ chunk.ASTNode = astNode+ } else {+ // Create new chunk if it doesn't exist+ chunk := &schema.SDLChunk{+ Identifier: functionKey,+ ASTNode: astNode,+ }+ chunks.Functions[functionKey] = chunk+ }++ return nil+}++// deleteFunctionChunk removes a function chunk from the chunks+func deleteFunctionChunk(chunks *schema.SDLChunks, functionKey string) {+ if chunks != nil && chunks.Functions != nil {+ delete(chunks.Functions, functionKey)+ }+}++// generateCreateFunctionSDL generates SDL for a CREATE FUNCTION statement+func generateCreateFunctionSDL(function *storepb.FunctionMetadata) string {+ if function == nil {+ return ""+ }++ var buf strings.Builder+ // Use the existing writeFunctionSDL function+ if err := writeFunctionSDL(&buf, "", function); err != nil {+ return ""+ }++ return buf.String()+}++// extractFunctionTextFromAST extracts normalized text from function AST node using token stream+func extractFunctionTextFromAST(functionAST *parser.CreatefunctionstmtContext) string {+ if functionAST == nil {+ return ""+ }++ // Get tokens from the parser+ if parser := functionAST.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := functionAST.GetStart()+ stop := functionAST.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }++ // Fallback to GetText() if tokens are not available+ return functionAST.GetText()+}++// functionDefinitionsEqual compares two function definitions to see if they are equivalent+func functionDefinitionsEqual(function1, function2 *storepb.FunctionMetadata) bool {+ if function1 == nil && function2 == nil {+ return true+ }+ if function1 == nil || function2 == nil {+ return false+ }++ // Compare function names+ if function1.Name != function2.Name {+ return false+ }++ // Compare function definitions (most important comparison)+ definition1 := strings.TrimSpace(function1.Definition)+ definition2 := strings.TrimSpace(function2.Definition)++ // Normalize definitions for comparison+ definition1 = strings.TrimSuffix(definition1, ";")+ definition2 = strings.TrimSuffix(definition2, ";")++ return definition1 == definition2+}++// extractFunctionASTFromSDL parses a function SDL and extracts the CREATE FUNCTION AST node+func extractFunctionASTFromSDL(sdl string) (antlr.ParserRuleContext, error) {+ if sdl == "" {+ return nil, errors.New("empty SDL provided")+ }++ // Parse the SDL to get AST+ parseResult, err := pgparser.ParsePostgreSQL(sdl)+ if err != nil {+ return nil, errors.Wrap(err, "failed to parse function SDL")+ }++ tree := parseResult.Tree++ // Extract the CREATE FUNCTION node using a walker+ var result *parser.CreatefunctionstmtContext+ extractor := &functionExtractor{result: &result}+ antlr.NewParseTreeWalker().Walk(extractor, tree)++ if result == nil {+ return nil, errors.New("no CREATE FUNCTION statement found in SDL")+ }++ return result, nil+}++// functionExtractor is a walker to extract CREATE FUNCTION AST nodes+type functionExtractor struct {+ parser.BasePostgreSQLParserListener+ result **parser.CreatefunctionstmtContext+}++func (e *functionExtractor) EnterCreatefunctionstmt(ctx *parser.CreatefunctionstmtContext) {+ if e.result != nil && *e.result == nil {+ *e.result = ctx+ }+}++// applySequenceChangesToChunks applies minimal changes to CREATE SEQUENCE chunks+// This handles creation, modification, and deletion of sequence statements+func applySequenceChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema) error {+ if currentSchema == nil || previousSchema == nil || previousChunks == nil {+ return nil+ }++ // Get sequence differences by comparing schema metadata+ currentMetadata := currentSchema.GetMetadata()+ previousMetadata := previousSchema.GetMetadata()+ if currentMetadata == nil || previousMetadata == nil {+ return nil+ }++ // Build sequence maps for current and previous schemas+ currentSequences := make(map[string]*storepb.SequenceMetadata)+ previousSequences := make(map[string]*storepb.SequenceMetadata)++ // Collect all sequences from current schema+ for _, schema := range currentMetadata.Schemas {+ for _, sequence := range schema.Sequences {+ sequenceKey := formatSequenceKey(schema.Name, sequence.Name)+ currentSequences[sequenceKey] = sequence+ }+ }++ // Collect all sequences from previous schema+ for _, schema := range previousMetadata.Schemas {+ for _, sequence := range schema.Sequences {+ sequenceKey := formatSequenceKey(schema.Name, sequence.Name)+ previousSequences[sequenceKey] = sequence+ }+ }++ // Process sequence additions: create new sequence chunks+ for sequenceKey, currentSequence := range currentSequences {+ if _, exists := previousSequences[sequenceKey]; !exists {+ // New sequence - create a chunk for it+ err := createSequenceChunk(previousChunks, currentSequence, sequenceKey)+ if err != nil {+ return errors.Wrapf(err, "failed to create sequence chunk for %s", sequenceKey)+ }+ }+ }++ // Process sequence modifications: update existing chunks+ for sequenceKey, currentSequence := range currentSequences {+ if previousSequence, exists := previousSequences[sequenceKey]; exists {+ // Sequence exists in both - check if it needs modification+ err := updateSequenceChunkIfNeeded(previousChunks, currentSequence, previousSequence, sequenceKey)+ if err != nil {+ return errors.Wrapf(err, "failed to update sequence chunk for %s", sequenceKey)+ }+ }+ }++ // Process sequence deletions: remove dropped sequence chunks+ for sequenceKey := range previousSequences {+ if _, exists := currentSequences[sequenceKey]; !exists {+ // Sequence was dropped - remove it from chunks+ deleteSequenceChunk(previousChunks, sequenceKey)+ }+ }++ return nil+}++// formatSequenceKey creates a consistent key for sequence identification+func formatSequenceKey(schemaName, sequenceName string) string {+ if schemaName == "" {+ schemaName = "public"+ }+ return schemaName + "." + sequenceName+}++// extractSchemaFromSequenceKey extracts the schema name from a sequence key+func extractSchemaFromSequenceKey(sequenceKey string) string {+ parts := strings.SplitN(sequenceKey, ".", 2)+ if len(parts) >= 1 {+ return parts[0]+ }+ return "public"+}++// createSequenceChunk creates a new CREATE SEQUENCE chunk and adds it to the chunks+func createSequenceChunk(chunks *schema.SDLChunks, sequence *storepb.SequenceMetadata, sequenceKey string) error {+ if sequence == nil || chunks == nil {+ return nil+ }++ // Generate sequence SDL using the existing writeSequenceSDL function+ schemaName := extractSchemaFromSequenceKey(sequenceKey)+ sdl := generateCreateSequenceSDL(schemaName, sequence)+ if sdl == "" {+ return errors.Errorf("failed to generate SDL for sequence %s", sequenceKey)+ }++ // Parse the SDL to get the AST node+ astNode, err := extractSequenceASTFromSDL(sdl)+ if err != nil {+ return errors.Wrapf(err, "failed to extract AST from generated sequence SDL for %s", sequenceKey)+ }++ // Create the chunk+ chunk := &schema.SDLChunk{+ Identifier: sequenceKey,+ ASTNode: astNode,+ }++ // Ensure Sequences map is initialized+ if chunks.Sequences == nil {+ chunks.Sequences = make(map[string]*schema.SDLChunk)+ }++ chunks.Sequences[sequenceKey] = chunk+ return nil+}++// updateSequenceChunkIfNeeded updates a sequence chunk if the definition has changed+func updateSequenceChunkIfNeeded(chunks *schema.SDLChunks, currentSequence, previousSequence *storepb.SequenceMetadata, sequenceKey string) error {+ if currentSequence == nil || previousSequence == nil || chunks == nil {+ return nil+ }++ // Check if sequence definitions are different+ if !sequenceDefinitionsEqual(currentSequence, previousSequence) {+ // Sequence was modified - update the chunk+ err := updateSequenceChunk(chunks, currentSequence, sequenceKey)+ if err != nil {+ return errors.Wrapf(err, "failed to update sequence chunk for %s", sequenceKey)+ }+ }++ return nil+}++// updateSequenceChunk updates an existing sequence chunk with new definition+func updateSequenceChunk(chunks *schema.SDLChunks, sequence *storepb.SequenceMetadata, sequenceKey string) error {+ if sequence == nil || chunks == nil {+ return nil+ }++ // Generate new sequence SDL+ schemaName := extractSchemaFromSequenceKey(sequenceKey)+ sdl := generateCreateSequenceSDL(schemaName, sequence)+ if sdl == "" {+ return errors.Errorf("failed to generate SDL for sequence %s", sequenceKey)+ }++ // Parse the SDL to get the AST node+ astNode, err := extractSequenceASTFromSDL(sdl)+ if err != nil {+ return errors.Wrapf(err, "failed to extract AST from generated sequence SDL for %s", sequenceKey)+ }++ // Update the existing chunk+ if chunk := chunks.Sequences[sequenceKey]; chunk != nil {+ chunk.ASTNode = astNode+ } else {+ // Create new chunk if it doesn't exist+ chunk := &schema.SDLChunk{+ Identifier: sequenceKey,+ ASTNode: astNode,+ }+ chunks.Sequences[sequenceKey] = chunk+ }++ return nil+}++// deleteSequenceChunk removes a sequence chunk from the chunks+func deleteSequenceChunk(chunks *schema.SDLChunks, sequenceKey string) {+ if chunks != nil && chunks.Sequences != nil {+ delete(chunks.Sequences, sequenceKey)+ }+}++// generateCreateSequenceSDL generates SDL for a CREATE SEQUENCE statement+func generateCreateSequenceSDL(schemaName string, sequence *storepb.SequenceMetadata) string {+ if sequence == nil {+ return ""+ }++ if schemaName == "" {+ schemaName = "public"+ }++ var buf strings.Builder+ // Use the existing writeSequenceSDL function+ if err := writeSequenceSDL(&buf, schemaName, sequence); err != nil {+ return ""+ }++ return buf.String()+}++// sequenceDefinitionsEqual compares two sequence definitions to see if they are equivalent+func sequenceDefinitionsEqual(sequence1, sequence2 *storepb.SequenceMetadata) bool {+ if sequence1 == nil && sequence2 == nil {+ return true+ }+ if sequence1 == nil || sequence2 == nil {+ return false+ }++ // Compare sequence names+ if sequence1.Name != sequence2.Name {+ return false+ }++ // Compare sequence parameters+ if sequence1.DataType != sequence2.DataType ||+ sequence1.Start != sequence2.Start ||+ sequence1.Increment != sequence2.Increment ||+ sequence1.MaxValue != sequence2.MaxValue ||+ sequence1.MinValue != sequence2.MinValue ||+ sequence1.CacheSize != sequence2.CacheSize ||+ sequence1.Cycle != sequence2.Cycle ||+ sequence1.OwnerTable != sequence2.OwnerTable ||+ sequence1.OwnerColumn != sequence2.OwnerColumn {+ return false+ }++ return true+}++// extractSequenceASTFromSDL parses a sequence SDL and extracts the CREATE SEQUENCE AST node+func extractSequenceASTFromSDL(sdl string) (antlr.ParserRuleContext, error) {+ if sdl == "" {+ return nil, errors.New("empty SDL provided")+ }++ // Parse the SDL to get AST+ parseResult, err := pgparser.ParsePostgreSQL(sdl)+ if err != nil {+ return nil, errors.Wrap(err, "failed to parse sequence SDL")+ }++ tree := parseResult.Tree++ // Extract the CREATE SEQUENCE node using a walker+ var result *parser.CreateseqstmtContext+ extractor := &sequenceExtractor{result: &result}+ antlr.NewParseTreeWalker().Walk(extractor, tree)++ if result == nil {+ return nil, errors.New("no CREATE SEQUENCE statement found in SDL")+ }++ return result, nil+}++// extractSequenceTextFromAST extracts normalized text from sequence AST node using token stream+func extractSequenceTextFromAST(sequenceAST *parser.CreateseqstmtContext) string {+ if sequenceAST == nil {+ return ""+ }++ // Get tokens from the parser+ if parser := sequenceAST.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := sequenceAST.GetStart()+ stop := sequenceAST.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }++ // Fallback to GetText() if tokens are not available+ return sequenceAST.GetText()+}++// sequenceExtractor is a walker to extract CREATE SEQUENCE AST nodes+type sequenceExtractor struct {+ parser.BasePostgreSQLParserListener+ result **parser.CreateseqstmtContext+}++func (e *sequenceExtractor) EnterCreateseqstmt(ctx *parser.CreateseqstmtContext) {+ if e.result != nil && *e.result == nil {+ *e.result = ctx+ }+}diff --git a/backend/plugin/schema/pg/sequence_rewrite_test.go b/backend/plugin/schema/pg/sequence_rewrite_test.gonew file mode 100644index 0000000000..cc0cfe2a47--- /dev/null+++ b/backend/plugin/schema/pg/sequence_rewrite_test.go@@ -0,0 +1,500 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ parser "github.com/bytebase/parser/postgresql"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+)++// TestSequenceRewriteOperations tests the ANTLR TokenStreamRewriter functionality+// for standalone CREATE SEQUENCE operations including add, modify, delete+func TestSequenceRewriteOperations(t *testing.T) {+ testCases := []struct {+ name string+ originalSDL string+ currentSequences []*storepb.SequenceMetadata+ previousSequences []*storepb.SequenceMetadata+ expectedSequenceCount int+ description string+ }{+ {+ name: "Add new standalone sequence",+ originalSDL: `CREATE TABLE users (+ id INTEGER NOT NULL,+ email VARCHAR(255) NOT NULL+);`,+ currentSequences: []*storepb.SequenceMetadata{+ {+ Name: "user_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ },+ previousSequences: []*storepb.SequenceMetadata{},+ expectedSequenceCount: 1,+ description: "Should add new standalone sequence to chunks",+ },+ {+ name: "Add sequence with complex options",+ originalSDL: `CREATE TABLE orders (+ id BIGINT NOT NULL,+ amount DECIMAL(10,2) NOT NULL+);`,+ currentSequences: []*storepb.SequenceMetadata{+ {+ Name: "order_id_seq",+ DataType: "bigint",+ Start: "1000000",+ Increment: "1",+ MinValue: "1",+ MaxValue: "9223372036854775807",+ CacheSize: "50",+ Cycle: false,+ OwnerTable: "orders",+ OwnerColumn: "id",+ },+ },+ previousSequences: []*storepb.SequenceMetadata{},+ expectedSequenceCount: 1,+ description: "Should add new sequence with complex options to chunks",+ },+ {+ name: "Drop standalone sequence",+ originalSDL: `CREATE TABLE users (+ id INTEGER NOT NULL,+ email VARCHAR(255) NOT NULL+);++CREATE SEQUENCE user_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;`,+ currentSequences: []*storepb.SequenceMetadata{},+ previousSequences: []*storepb.SequenceMetadata{+ {+ Name: "user_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ },+ expectedSequenceCount: 0,+ description: "Should remove standalone sequence from chunks",+ },+ {+ name: "Modify sequence (change parameters)",+ originalSDL: `CREATE TABLE users (+ id INTEGER NOT NULL,+ email VARCHAR(255) NOT NULL+);++CREATE SEQUENCE user_seq+ START WITH 1+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;`,+ currentSequences: []*storepb.SequenceMetadata{+ {+ Name: "user_seq",+ DataType: "bigint",+ Start: "10",+ Increment: "2",+ MinValue: "",+ MaxValue: "",+ CacheSize: "5",+ Cycle: false,+ },+ },+ previousSequences: []*storepb.SequenceMetadata{+ {+ Name: "user_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ },+ expectedSequenceCount: 1,+ description: "Should modify existing sequence when parameters change",+ },+ {+ name: "Multiple sequence operations",+ originalSDL: `CREATE TABLE orders (+ id INTEGER NOT NULL,+ customer_id INTEGER,+ total DECIMAL(10,2),+ status VARCHAR(20)+);++CREATE SEQUENCE order_seq+ START WITH 100+ INCREMENT BY 1;`,+ currentSequences: []*storepb.SequenceMetadata{+ {+ Name: "order_total_seq",+ DataType: "bigint",+ Start: "1000",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ {+ Name: "customer_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "10",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ },+ previousSequences: []*storepb.SequenceMetadata{+ {+ Name: "order_seq",+ DataType: "bigint",+ Start: "100",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ },+ expectedSequenceCount: 2,+ description: "Should handle multiple sequence operations (drop old, add new)",+ },+ {+ name: "Schema-qualified sequence names",+ originalSDL: `CREATE SCHEMA test_schema;+CREATE TABLE test_schema.products (+ id INTEGER NOT NULL,+ name VARCHAR(255)+);`,+ currentSequences: []*storepb.SequenceMetadata{+ {+ Name: "product_id_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ OwnerTable: "products",+ OwnerColumn: "id",+ },+ },+ previousSequences: []*storepb.SequenceMetadata{},+ expectedSequenceCount: 1,+ description: "Should handle schema-qualified sequence names",+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ // Parse the original SDL to create chunks+ chunks, err := ChunkSDLText(tc.originalSDL)+ require.NoError(t, err, "Failed to parse original SDL")++ // Create sequence maps for simulation+ currentSequences := make(map[string]*storepb.SequenceMetadata)+ previousSequences := make(map[string]*storepb.SequenceMetadata)++ for _, seq := range tc.currentSequences {+ key := formatSequenceKey("public", seq.Name)+ currentSequences[key] = seq+ }++ for _, seq := range tc.previousSequences {+ key := formatSequenceKey("public", seq.Name)+ previousSequences[key] = seq+ }++ // Apply sequence changes directly to test the core logic+ err = applySequenceChangesInternal(chunks, currentSequences, previousSequences)+ require.NoError(t, err, "Failed to apply sequence changes")++ // Verify the expected number of sequences+ assert.Len(t, chunks.Sequences, tc.expectedSequenceCount,+ "Expected %d sequences, got %d", tc.expectedSequenceCount, len(chunks.Sequences))++ // Verify each current sequence is present+ for key, seq := range currentSequences {+ chunk, exists := chunks.Sequences[key]+ assert.True(t, exists, "Expected sequence %s not found in chunks", key)+ if exists {+ assert.NotNil(t, chunk.ASTNode, "Sequence chunk should have AST node")+ // Verify we can get text from the chunk using the proper extraction function+ if sequenceAST, ok := chunk.ASTNode.(*parser.CreateseqstmtContext); ok {+ text := extractSequenceTextFromAST(sequenceAST)+ assert.NotEmpty(t, text, "Sequence chunk should have non-empty text")+ assert.Contains(t, text, "CREATE", "Sequence text should contain CREATE")+ assert.Contains(t, text, "SEQUENCE", "Sequence text should contain SEQUENCE")+ assert.Contains(t, text, seq.Name, "Sequence text should contain sequence name")+ }+ }+ }++ // Verify previous sequences that shouldn't exist are removed+ for key := range previousSequences {+ if _, stillExists := currentSequences[key]; !stillExists {+ _, exists := chunks.Sequences[key]+ assert.False(t, exists, "Sequence %s should have been removed from chunks", key)+ }+ }++ t.Logf("Test case '%s' passed: %s", tc.name, tc.description)+ })+ }+}++// applySequenceChangesInternal is a test helper that directly applies sequence changes to chunks+func applySequenceChangesInternal(chunks *schema.SDLChunks, currentSequences, previousSequences map[string]*storepb.SequenceMetadata) error {+ if chunks == nil {+ return nil+ }++ // Process sequence additions: create new sequence chunks+ for sequenceKey, currentSequence := range currentSequences {+ if _, exists := previousSequences[sequenceKey]; !exists {+ // New sequence - create a chunk for it+ err := createSequenceChunk(chunks, currentSequence, sequenceKey)+ if err != nil {+ return err+ }+ }+ }++ // Process sequence modifications: update existing chunks+ for sequenceKey, currentSequence := range currentSequences {+ if previousSequence, exists := previousSequences[sequenceKey]; exists {+ // Sequence exists in both - check if it needs modification+ err := updateSequenceChunkIfNeeded(chunks, currentSequence, previousSequence, sequenceKey)+ if err != nil {+ return err+ }+ }+ }++ // Process sequence deletions: remove dropped sequence chunks+ for sequenceKey := range previousSequences {+ if _, exists := currentSequences[sequenceKey]; !exists {+ // Sequence was dropped - remove it from chunks+ deleteSequenceChunk(chunks, sequenceKey)+ }+ }++ return nil+}++// TestGenerateCreateSequenceSDL tests the SDL generation for CREATE SEQUENCE statements+func TestGenerateCreateSequenceSDL(t *testing.T) {+ testCases := []struct {+ name string+ sequence *storepb.SequenceMetadata+ expectedSDL string+ }{+ {+ name: "Simple sequence",+ sequence: &storepb.SequenceMetadata{+ Name: "user_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ },+ expectedSDL: `CREATE SEQUENCE "user_seq" START WITH 1 INCREMENT BY 1 CACHE 1`,+ },+ {+ name: "Sequence with complex options",+ sequence: &storepb.SequenceMetadata{+ Name: "order_id_seq",+ DataType: "bigint",+ Start: "1000000",+ Increment: "1",+ MinValue: "1",+ MaxValue: "9223372036854775807",+ CacheSize: "50",+ Cycle: false,+ },+ expectedSDL: `CREATE SEQUENCE "order_id_seq" START WITH 1000000 INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 50`,+ },+ {+ name: "Sequence with owner",+ sequence: &storepb.SequenceMetadata{+ Name: "product_id_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ MinValue: "",+ MaxValue: "",+ CacheSize: "1",+ Cycle: false,+ OwnerTable: "products",+ OwnerColumn: "id",+ },+ expectedSDL: `CREATE SEQUENCE "product_id_seq" START WITH 1 INCREMENT BY 1 CACHE 1 OWNED BY "products"."id"`,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ result := generateCreateSequenceSDL("public", tc.sequence)+ // Note: The exact format may vary depending on the writeSequenceSDL implementation+ // We mainly check that it generates some reasonable SDL+ assert.NotEmpty(t, result, "Should generate non-empty SDL")+ assert.Contains(t, result, "CREATE", "Should contain CREATE")+ assert.Contains(t, result, "SEQUENCE", "Should contain SEQUENCE")+ assert.Contains(t, result, tc.sequence.Name, "Should contain sequence name")+ })+ }+}++// TestSequenceDefinitionsEqual tests the sequence comparison logic+func TestSequenceDefinitionsEqual(t *testing.T) {+ testCases := []struct {+ name string+ sequence1 *storepb.SequenceMetadata+ sequence2 *storepb.SequenceMetadata+ expected bool+ }{+ {+ name: "Identical sequences",+ sequence1: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ sequence2: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ expected: true,+ },+ {+ name: "Different names",+ sequence1: &storepb.SequenceMetadata{+ Name: "test_seq1",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ sequence2: &storepb.SequenceMetadata{+ Name: "test_seq2",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ expected: false,+ },+ {+ name: "Different start values",+ sequence1: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ sequence2: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "10",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ expected: false,+ },+ {+ name: "Different increment values",+ sequence1: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ },+ sequence2: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "2",+ CacheSize: "1",+ Cycle: false,+ },+ expected: false,+ },+ {+ name: "Different owner information",+ sequence1: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ OwnerTable: "table1",+ OwnerColumn: "id",+ },+ sequence2: &storepb.SequenceMetadata{+ Name: "test_seq",+ DataType: "bigint",+ Start: "1",+ Increment: "1",+ CacheSize: "1",+ Cycle: false,+ OwnerTable: "table2",+ OwnerColumn: "id",+ },+ expected: false,+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ result := sequenceDefinitionsEqual(tc.sequence1, tc.sequence2)+ assert.Equal(t, tc.expected, result)+ })+ }+}