Skip to content

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

feat: generate migration for pg (#16540)

rebelicee3986fdb8375
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.go
index 0f4124b5ad..9edf815ed4 100644
--- a/backend/plugin/schema/differ.go
+++ b/backend/plugin/schema/differ.go
@@ -39,6 +39,9 @@ type MetadataDiff struct {
// Sequence changes
SequenceChanges []*SequenceDiff
+
+ // Enum type changes
+ EnumTypeChanges []*EnumTypeDiff
}
// nolint
@@ -154,6 +157,15 @@ type SequenceDiff struct {
NewSequence *storepb.SequenceMetadata
}
+// EnumTypeDiff represents changes to an enum type.
+type EnumTypeDiff struct {
+ Action MetadataDiffAction
+ SchemaName string
+ EnumTypeName string
+ OldEnumType *storepb.EnumTypeMetadata
+ NewEnumType *storepb.EnumTypeMetadata
+}
+
// GetDatabaseSchemaDiff compares two model.DatabaseSchema instances and returns the differences.
func GetDatabaseSchemaDiff(oldSchema, newSchema *model.DatabaseSchema) (*MetadataDiff, error) {
if oldSchema == nil || newSchema == nil {
@@ -293,6 +305,18 @@ func addNewSchemaObjects(diff *MetadataDiff, schemaName string, schema *model.Sc
})
}
}
+
+ // Add all enum types
+ for _, enumProto := range schemaProto.EnumTypes {
+ if !enumProto.GetSkipDump() {
+ diff.EnumTypeChanges = append(diff.EnumTypeChanges, &EnumTypeDiff{
+ Action: MetadataDiffActionCreate,
+ SchemaName: schemaName,
+ EnumTypeName: enumProto.Name,
+ NewEnumType: enumProto,
+ })
+ }
+ }
}
// compareSchemaObjects compares objects between two schemas.
@@ -354,6 +378,9 @@ func compareSchemaObjects(diff *MetadataDiff, schemaName string, oldSchema, newS
// Compare sequences
compareSequences(diff, schemaName, oldSchema, newSchema)
+
+ // Compare enum types
+ compareEnumTypes(diff, schemaName, oldSchema, newSchema)
}
// compareTableDetails compares the details of two tables.
@@ -1008,3 +1035,50 @@ func compareSequences(diff *MetadataDiff, schemaName string, oldSchema, newSchem
}
}
}
+
+// compareEnumTypes compares enum types between two schemas.
+func compareEnumTypes(diff *MetadataDiff, schemaName string, oldSchema, newSchema *model.SchemaMetadata) {
+ oldSchemaProto := oldSchema.GetProto()
+ newSchemaProto := newSchema.GetProto()
+
+ // Build maps of enum types
+ oldEnumMap := make(map[string]*storepb.EnumTypeMetadata)
+ for _, enum := range oldSchemaProto.EnumTypes {
+ if !enum.GetSkipDump() {
+ oldEnumMap[enum.Name] = enum
+ }
+ }
+
+ newEnumMap := make(map[string]*storepb.EnumTypeMetadata)
+ for _, enum := range newSchemaProto.EnumTypes {
+ if !enum.GetSkipDump() {
+ newEnumMap[enum.Name] = enum
+ }
+ }
+
+ // Check for dropped enum types
+ for enumName, oldEnum := range oldEnumMap {
+ if _, exists := newEnumMap[enumName]; !exists {
+ diff.EnumTypeChanges = append(diff.EnumTypeChanges, &EnumTypeDiff{
+ Action: MetadataDiffActionDrop,
+ SchemaName: schemaName,
+ EnumTypeName: enumName,
+ OldEnumType: oldEnum,
+ })
+ }
+ }
+
+ // Check for new enum types
+ for enumName, newEnum := range newEnumMap {
+ if _, exists := oldEnumMap[enumName]; !exists {
+ diff.EnumTypeChanges = append(diff.EnumTypeChanges, &EnumTypeDiff{
+ Action: MetadataDiffActionCreate,
+ SchemaName: schemaName,
+ EnumTypeName: enumName,
+ NewEnumType: newEnum,
+ })
+ }
+ // Note: We don't support ALTER enum types yet
+ // PostgreSQL doesn't allow modifying enum values easily
+ }
+}
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml b/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml
index 8de3917acb..231c2d0ba8 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml
@@ -109,12 +109,13 @@
SELECT id, name FROM [dbo].[departments];
GO
CREATE VIEW [dbo].[v_employees] AS
- SELECT id, name, dept_id FROM [dbo].[employees];
+ SELECT e.id, e.name, e.dept_id, d.name as dept_name
+ FROM [dbo].[employees] e
+ LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
GO
CREATE VIEW [dbo].[v_employee_dept] AS
- SELECT e.id, e.name, d.name as dept_name
- FROM [dbo].[v_employees] e
- LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
+ SELECT id, name, dept_name
+ FROM [dbo].[v_employees];
GO
newSchema: |
CREATE TABLE [dbo].[departments] (
@@ -134,12 +135,13 @@
SELECT id, name, location FROM [dbo].[departments];
GO
CREATE VIEW [dbo].[v_employees] AS
- SELECT id, name, dept_id, salary FROM [dbo].[employees];
+ SELECT e.id, e.name, e.dept_id, e.salary, d.name as dept_name, d.location
+ FROM [dbo].[employees] e
+ LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
GO
CREATE VIEW [dbo].[v_employee_dept] AS
- SELECT e.id, e.name, e.salary, d.name as dept_name, d.location
- FROM [dbo].[v_employees] e
- LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
+ SELECT id, name, salary, dept_name, location
+ FROM [dbo].[v_employees];
GO
CREATE VIEW [dbo].[v_dept_summary] AS
SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
@@ -164,12 +166,13 @@
SELECT id, name, location FROM [dbo].[departments];
GO
CREATE VIEW [dbo].[v_employees] AS
- SELECT id, name, dept_id, salary FROM [dbo].[employees];
+ SELECT e.id, e.name, e.dept_id, e.salary, d.name as dept_name, d.location
+ FROM [dbo].[employees] e
+ LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
GO
CREATE VIEW [dbo].[v_employee_dept] AS
- SELECT e.id, e.name, e.salary, d.name as dept_name, d.location
- FROM [dbo].[v_employees] e
- LEFT JOIN [dbo].[v_departments] d ON e.dept_id = d.id;
+ SELECT id, name, salary, dept_name, location
+ FROM [dbo].[v_employees];
GO
CREATE VIEW [dbo].[v_dept_summary] AS
SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
new file mode 100644
index 0000000000..aedf1570ad
--- /dev/null
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -0,0 +1,1583 @@
+package pg
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+
+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func init() {
+ schema.RegisterGenerateMigration(storepb.Engine_POSTGRES, generateMigration)
+}
+
+func generateMigration(diff *schema.MetadataDiff) (string, error) {
+ var buf strings.Builder
+
+ // Safe order for migrations:
+ // 1. Drop dependent objects first (in reverse dependency order)
+ // - Use topological sort to drop in safe order
+ // 2. Create/Alter objects (in dependency order)
+ // - Use topological sort to create in safe order
+
+ // Phase 1: Drop dependent objects using topological sort
+ if err := dropObjectsInOrder(diff, &buf); err != nil {
+ return "", err
+ }
+
+ // Only add blank line if we have drops AND we're about to create something
+ dropPhaseHasContent := buf.Len() > 0
+ createPhaseWillHaveContent := hasCreateOrAlterObjects(diff)
+
+ if dropPhaseHasContent && createPhaseWillHaveContent {
+ _, _ = buf.WriteString("\n")
+ }
+
+ // Phase 2: Create/Alter objects using topological sort
+ if err := createObjectsInOrder(diff, &buf); err != nil {
+ return "", err
+ }
+
+ return buf.String(), nil
+}
+
+// dropObjectsInOrder drops all objects in reverse topological order (most dependent first)
+func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {
+ // First, drop all triggers that might depend on functions we're about to drop
+ // This is necessary because PostgreSQL doesn't allow dropping functions that are used by triggers
+ functionsBeingDropped := make(map[string]bool)
+ for _, funcDiff := range diff.FunctionChanges {
+ if funcDiff.Action == schema.MetadataDiffActionDrop {
+ funcName := strings.ToLower(funcDiff.FunctionName)
+ functionsBeingDropped[funcName] = true
+ }
+ }
+
+ // Drop triggers that might depend on functions being dropped
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action != schema.MetadataDiffActionDrop && tableDiff.OldTable != nil {
+ for _, trigger := range tableDiff.OldTable.Triggers {
+ // Check if trigger body references any function being dropped
+ triggerBody := strings.ToLower(trigger.Body)
+ for funcName := range functionsBeingDropped {
+ if strings.Contains(triggerBody, funcName) {
+ if err := writeDropTrigger(buf, tableDiff.SchemaName, tableDiff.TableName, trigger.Name); err != nil {
+ return err
+ }
+ break
+ }
+ }
+ }
+ }
+ }
+
+ // Build dependency graph for all objects being dropped or altered
+ graph := parserbase.NewGraph()
+
+ // Maps to store different object types
+ viewMap := make(map[string]*schema.ViewDiff)
+ materializedViewMap := make(map[string]*schema.MaterializedViewDiff)
+ tableMap := make(map[string]*schema.TableDiff)
+ functionMap := make(map[string]*schema.FunctionDiff)
+
+ // Track all object IDs for dependency resolution
+ allObjects := make(map[string]bool)
+
+ // Collect schemas being dropped to ensure their objects are dropped first
+ schemasBeingDropped := make(map[string]bool)
+ for _, schemaDiff := range diff.SchemaChanges {
+ if schemaDiff.Action == schema.MetadataDiffActionDrop {
+ schemasBeingDropped[schemaDiff.SchemaName] = true
+ }
+ }
+
+ // Add views to graph
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionDrop || viewDiff.Action == schema.MetadataDiffActionAlter {
+ viewID := getMigrationObjectID(viewDiff.SchemaName, viewDiff.ViewName)
+ graph.AddNode(viewID)
+ viewMap[viewID] = viewDiff
+ allObjects[viewID] = true
+ }
+ }
+
+ // Add materialized views to graph
+ for _, mvDiff := range diff.MaterializedViewChanges {
+ if mvDiff.Action == schema.MetadataDiffActionDrop || mvDiff.Action == schema.MetadataDiffActionAlter {
+ mvID := getMigrationObjectID(mvDiff.SchemaName, mvDiff.MaterializedViewName)
+ graph.AddNode(mvID)
+ materializedViewMap[mvID] = mvDiff
+ allObjects[mvID] = true
+ }
+ }
+
+ // Add functions to graph
+ for _, funcDiff := range diff.FunctionChanges {
+ if funcDiff.Action == schema.MetadataDiffActionDrop {
+ funcID := getMigrationObjectID(funcDiff.SchemaName, funcDiff.FunctionName)
+ graph.AddNode(funcID)
+ functionMap[funcID] = funcDiff
+ allObjects[funcID] = true
+ }
+ }
+
+ // Add tables to graph
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionDrop {
+ tableID := getMigrationObjectID(tableDiff.SchemaName, tableDiff.TableName)
+ graph.AddNode(tableID)
+ tableMap[tableID] = tableDiff
+ allObjects[tableID] = true
+ }
+ }
+
+ // Add dependency edges
+ // For views depending on tables/views
+ for viewID, viewDiff := range viewMap {
+ 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)
+ }
+ }
+ }
+ }
+
+ // For materialized views depending on tables/views
+ for mvID, mvDiff := range materializedViewMap {
+ if mvDiff.OldMaterializedView != nil {
+ for _, dep := range mvDiff.OldMaterializedView.DependencyColumns {
+ depID := getMigrationObjectID(dep.Schema, dep.Table)
+ if allObjects[depID] {
+ // Edge from dependent to dependency
+ graph.AddEdge(mvID, depID)
+ }
+ }
+ }
+ }
+
+ // For functions depending on tables
+ for funcID, funcDiff := range functionMap {
+ if funcDiff.OldFunction != nil {
+ for _, dep := range funcDiff.OldFunction.DependencyTables {
+ depID := getMigrationObjectID(dep.Schema, dep.Table)
+ if allObjects[depID] {
+ // Edge from function to table
+ graph.AddEdge(funcID, depID)
+ }
+ }
+ }
+ }
+
+ // For tables with foreign keys depending on other tables
+ for tableID, tableDiff := range tableMap {
+ if tableDiff.OldTable != nil {
+ for _, fk := range tableDiff.OldTable.ForeignKeys {
+ depID := getMigrationObjectID(fk.ReferencedSchema, fk.ReferencedTable)
+ if allObjects[depID] && depID != tableID {
+ // Edge from table with FK to referenced table
+ graph.AddEdge(tableID, depID)
+ }
+ }
+ }
+ }
+
+ // Get topological order
+ orderedList, err := graph.TopologicalSort()
+ if err != nil {
+ // If there's a cycle, fall back to a safe order
+ // First drop foreign keys from ALTER operations that might reference tables being dropped
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ for _, fkDiff := range tableDiff.ForeignKeyChanges {
+ if fkDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.OldForeignKey.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+
+ // Drop triggers
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionDrop && tableDiff.OldTable != nil {
+ for _, trigger := range tableDiff.OldTable.Triggers {
+ if err := writeDropTrigger(buf, tableDiff.SchemaName, tableDiff.TableName, trigger.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ // Drop foreign keys from tables being dropped
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionDrop && tableDiff.OldTable != nil {
+ for _, fk := range tableDiff.OldTable.ForeignKeys {
+ if err := writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ // Drop views
+ for _, viewDiff := range viewMap {
+ if err := writeDropView(buf, viewDiff.SchemaName, viewDiff.ViewName); err != nil {
+ return err
+ }
+ }
+
+ // Drop materialized views
+ for _, mvDiff := range materializedViewMap {
+ if err := writeDropMaterializedView(buf, mvDiff.SchemaName, mvDiff.MaterializedViewName); err != nil {
+ return err
+ }
+ }
+
+ // Drop functions
+ for _, funcDiff := range functionMap {
+ if err := writeDropFunction(buf, funcDiff.SchemaName, funcDiff.FunctionName); err != nil {
+ return err
+ }
+ }
+
+ // Drop tables
+ for _, tableDiff := range tableMap {
+ if err := writeDropTable(buf, tableDiff.SchemaName, tableDiff.TableName); err != nil {
+ return err
+ }
+ }
+
+ // Handle remaining ALTER table operations (constraints, indexes, columns)
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ // Drop check constraints
+ for _, checkDiff := range tableDiff.CheckConstraintChanges {
+ if checkDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.OldCheckConstraint.Name); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Drop indexes
+ for _, indexDiff := range tableDiff.IndexChanges {
+ if indexDiff.Action == schema.MetadataDiffActionDrop {
+ if indexDiff.OldIndex.IsConstraint {
+ if err := writeDropConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.OldIndex.Name); err != nil {
+ return err
+ }
+ } else {
+ if err := writeDropIndex(buf, tableDiff.SchemaName, indexDiff.OldIndex.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ // Drop columns
+ for _, colDiff := range tableDiff.ColumnChanges {
+ if colDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldColumn.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+ } else {
+ // First, handle ALTER table drops (foreign keys that might reference tables being dropped)
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ // Drop foreign keys first
+ for _, fkDiff := range tableDiff.ForeignKeyChanges {
+ if fkDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.OldForeignKey.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+
+ // Drop in topological order (most dependent first)
+ for _, objID := range orderedList {
+ // Drop triggers for tables being dropped
+ if tableDiff, ok := tableMap[objID]; ok && tableDiff.OldTable != nil {
+ for _, trigger := range tableDiff.OldTable.Triggers {
+ if err := writeDropTrigger(buf, tableDiff.SchemaName, tableDiff.TableName, trigger.Name); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Drop the object itself
+ if viewDiff, ok := viewMap[objID]; ok {
+ if err := writeDropView(buf, viewDiff.SchemaName, viewDiff.ViewName); err != nil {
+ return err
+ }
+ } else if mvDiff, ok := materializedViewMap[objID]; ok {
+ if err := writeDropMaterializedView(buf, mvDiff.SchemaName, mvDiff.MaterializedViewName); err != nil {
+ return err
+ }
+ } else if funcDiff, ok := functionMap[objID]; ok {
+ if err := writeDropFunction(buf, funcDiff.SchemaName, funcDiff.FunctionName); err != nil {
+ return err
+ }
+ } else if tableDiff, ok := tableMap[objID]; ok {
+ // Drop foreign keys before table
+ if tableDiff.OldTable != nil {
+ for _, fk := range tableDiff.OldTable.ForeignKeys {
+ if err := writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk.Name); err != nil {
+ return err
+ }
+ }
+ }
+ if err := writeDropTable(buf, tableDiff.SchemaName, tableDiff.TableName); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Handle remaining ALTER table drops (constraints, indexes, columns)
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ // Drop check constraints
+ for _, checkDiff := range tableDiff.CheckConstraintChanges {
+ if checkDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.OldCheckConstraint.Name); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Drop indexes
+ for _, indexDiff := range tableDiff.IndexChanges {
+ if indexDiff.Action == schema.MetadataDiffActionDrop {
+ if indexDiff.OldIndex.IsConstraint {
+ if err := writeDropConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.OldIndex.Name); err != nil {
+ return err
+ }
+ } else {
+ if err := writeDropIndex(buf, tableDiff.SchemaName, indexDiff.OldIndex.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ // Drop columns
+ for _, colDiff := range tableDiff.ColumnChanges {
+ if colDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.OldColumn.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Drop enum types
+ for _, enumDiff := range diff.EnumTypeChanges {
+ if enumDiff.Action == schema.MetadataDiffActionDrop {
+ if err := writeDropType(buf, enumDiff.SchemaName, enumDiff.EnumTypeName); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Drop sequences - prioritize sequences in schemas being dropped
+ var sequencesInDroppedSchemas []string
+ var otherSequences []string
+
+ for _, seqDiff := range diff.SequenceChanges {
+ if seqDiff.Action == schema.MetadataDiffActionDrop {
+ seqInfo := fmt.Sprintf("%s.%s", seqDiff.SchemaName, seqDiff.SequenceName)
+ if schemasBeingDropped[seqDiff.SchemaName] {
+ sequencesInDroppedSchemas = append(sequencesInDroppedSchemas, seqInfo)
+ } else {
+ otherSequences = append(otherSequences, seqInfo)
+ }
+ }
+ }
+
+ // Drop sequences in schemas being dropped first
+ for _, seqInfo := range sequencesInDroppedSchemas {
+ parts := strings.Split(seqInfo, ".")
+ if err := writeDropSequence(buf, parts[0], parts[1]); err != nil {
+ return err
+ }
+ }
+
+ // Then drop other sequences
+ for _, seqInfo := range otherSequences {
+ parts := strings.Split(seqInfo, ".")
+ if err := writeDropSequence(buf, parts[0], parts[1]); err != nil {
+ return err
+ }
+ }
+
+ // Drop schemas (must be empty)
+ for _, schemaDiff := range diff.SchemaChanges {
+ if schemaDiff.Action == schema.MetadataDiffActionDrop {
+ // Skip dropping pg_catalog and public schemas as they are system schemas
+ if schemaDiff.SchemaName == "pg_catalog" || schemaDiff.SchemaName == "public" {
+ continue
+ }
+
+ // Before dropping a schema, we need to drop all objects inside it
+ // This handles cases where the diff doesn't include objects within a schema being dropped
+ if schemaDiff.OldSchema != nil {
+ // Drop all objects in the schema in the correct order
+
+ // Drop views first (they might depend on tables)
+ for _, view := range schemaDiff.OldSchema.Views {
+ if err := writeDropView(buf, schemaDiff.SchemaName, view.Name); err != nil {
+ return err
+ }
+ }
+
+ // Drop materialized views
+ for _, mv := range schemaDiff.OldSchema.MaterializedViews {
+ if err := writeDropMaterializedView(buf, schemaDiff.SchemaName, mv.Name); err != nil {
+ return err
+ }
+ }
+
+ // Drop functions
+ for _, fn := range schemaDiff.OldSchema.Functions {
+ if err := writeDropFunction(buf, schemaDiff.SchemaName, fn.Name); err != nil {
+ return err
+ }
+ }
+
+ // Drop tables (this will handle foreign keys internally)
+ for _, table := range schemaDiff.OldSchema.Tables {
+ // Drop triggers first
+ for _, trigger := range table.Triggers {
+ if err := writeDropTrigger(buf, schemaDiff.SchemaName, table.Name, trigger.Name); err != nil {
+ return err
+ }
+ }
+
+ // Drop the table
+ if err := writeDropTable(buf, schemaDiff.SchemaName, table.Name); err != nil {
+ return err
+ }
+ }
+
+ // Drop sequences
+ for _, seq := range schemaDiff.OldSchema.Sequences {
+ if err := writeDropSequence(buf, schemaDiff.SchemaName, seq.Name); err != nil {
+ return err
+ }
+ }
+
+ // Drop types (enums)
+ for _, enum := range schemaDiff.OldSchema.EnumTypes {
+ if err := writeDropType(buf, schemaDiff.SchemaName, enum.Name); err != nil {
+ return err
+ }
+ }
+ }
+
+ if err := writeDropSchema(buf, schemaDiff.SchemaName); err != nil {
+ return err
+ }
+ } else if schemaDiff.Action == schema.MetadataDiffActionAlter {
+ // Handle ALTER schema - check for enum types that need to be dropped
+ // This handles cases where enum types are added to an existing schema
+ if schemaDiff.OldSchema != nil && schemaDiff.NewSchema != nil {
+ // Build a map of new enum types
+ newEnumMap := make(map[string]bool)
+ for _, enum := range schemaDiff.NewSchema.EnumTypes {
+ newEnumMap[enum.Name] = true
+ }
+
+ // Drop enum types that exist in old but not in new
+ for _, enum := range schemaDiff.OldSchema.EnumTypes {
+ if !newEnumMap[enum.Name] {
+ if err := writeDropType(buf, schemaDiff.SchemaName, enum.Name); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// createObjectsInOrder creates all objects in topological order (dependencies first)
+func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {
+ // First create schemas (they don't have dependencies)
+ var schemasToCreate []string
+ for _, schemaDiff := range diff.SchemaChanges {
+ if schemaDiff.Action == schema.MetadataDiffActionCreate {
+ // Skip creating pg_catalog and public schemas as they already exist by default
+ if schemaDiff.SchemaName != "pg_catalog" && schemaDiff.SchemaName != "public" {
+ schemasToCreate = append(schemasToCreate, schemaDiff.SchemaName)
+ }
+ }
+ }
+ slices.Sort(schemasToCreate)
+ for _, schemaName := range schemasToCreate {
+ if err := writeCreateSchema(buf, schemaName); err != nil {
+ return err
+ }
+ }
+
+ // Add blank line after schema creation only if we have schemas and more content follows
+ if len(schemasToCreate) > 0 && (hasCreateOrAlterTables(diff) || hasCreateViewsOrFunctions(diff)) {
+ _, _ = buf.WriteString("\n")
+ }
+
+ // Create enum types (before tables as they might be used in column definitions)
+ for _, enumDiff := range diff.EnumTypeChanges {
+ if enumDiff.Action == schema.MetadataDiffActionCreate {
+ if err := writeCreateEnumType(buf, enumDiff.SchemaName, enumDiff.NewEnumType); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Create sequences (before tables as they might be used in column defaults)
+ for _, seqDiff := range diff.SequenceChanges {
+ if seqDiff.Action == schema.MetadataDiffActionCreate {
+ if err := writeMigrationCreateSequence(buf, seqDiff.SchemaName, seqDiff.NewSequence); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Build dependency graph for all objects being created or altered
+ graph := parserbase.NewGraph()
+
+ // Maps to store different object types
+ viewMap := make(map[string]*schema.ViewDiff)
+ materializedViewMap := make(map[string]*schema.MaterializedViewDiff)
+ tableMap := make(map[string]*schema.TableDiff)
+ functionMap := make(map[string]*schema.FunctionDiff)
+
+ // Track all object IDs for dependency resolution
+ allObjects := make(map[string]bool)
+
+ // Add tables to graph
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionCreate {
+ tableID := getMigrationObjectID(tableDiff.SchemaName, tableDiff.TableName)
+ graph.AddNode(tableID)
+ tableMap[tableID] = tableDiff
+ allObjects[tableID] = true
+ }
+ }
+
+ // Add views to graph
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionCreate || viewDiff.Action == schema.MetadataDiffActionAlter {
+ viewID := getMigrationObjectID(viewDiff.SchemaName, viewDiff.ViewName)
+ graph.AddNode(viewID)
+ viewMap[viewID] = viewDiff
+ allObjects[viewID] = true
+ }
+ }
+
+ // Add materialized views to graph
+ for _, mvDiff := range diff.MaterializedViewChanges {
+ if mvDiff.Action == schema.MetadataDiffActionCreate || mvDiff.Action == schema.MetadataDiffActionAlter {
+ mvID := getMigrationObjectID(mvDiff.SchemaName, mvDiff.MaterializedViewName)
+ graph.AddNode(mvID)
+ materializedViewMap[mvID] = mvDiff
+ allObjects[mvID] = true
+ }
+ }
+
+ // Add functions to graph
+ for _, funcDiff := range diff.FunctionChanges {
+ if funcDiff.Action == schema.MetadataDiffActionCreate || funcDiff.Action == schema.MetadataDiffActionAlter {
+ funcID := getMigrationObjectID(funcDiff.SchemaName, funcDiff.FunctionName)
+ graph.AddNode(funcID)
+ functionMap[funcID] = funcDiff
+ allObjects[funcID] = true
+ }
+ }
+
+ // Add dependency edges
+ // For tables with foreign keys depending on other tables
+ for tableID, tableDiff := range tableMap {
+ if tableDiff.NewTable != nil {
+ for _, fk := range tableDiff.NewTable.ForeignKeys {
+ depID := getMigrationObjectID(fk.ReferencedSchema, fk.ReferencedTable)
+ if depID != tableID {
+ // Edge from dependency to dependent (referenced table to table with FK)
+ graph.AddEdge(depID, tableID)
+ }
+ }
+ }
+ }
+
+ // For views depending on tables/views
+ for viewID, viewDiff := range viewMap {
+ 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)
+ }
+ }
+ }
+
+ // For materialized views depending on tables/views
+ for mvID, mvDiff := range materializedViewMap {
+ if mvDiff.NewMaterializedView != nil {
+ for _, dep := range mvDiff.NewMaterializedView.DependencyColumns {
+ depID := getMigrationObjectID(dep.Schema, dep.Table)
+ // Edge from dependency to dependent
+ graph.AddEdge(depID, mvID)
+ }
+ }
+ }
+
+ // For functions depending on tables
+ for funcID, funcDiff := range functionMap {
+ if funcDiff.NewFunction != nil {
+ for _, dep := range funcDiff.NewFunction.DependencyTables {
+ depID := getMigrationObjectID(dep.Schema, dep.Table)
+ // Edge from table to function
+ graph.AddEdge(depID, funcID)
+ }
+ }
+ }
+
+ // Get topological order
+ orderedList, err := graph.TopologicalSort()
+ if err != nil {
+ // If there's a cycle, fall back to a safe order
+ // Create tables first (without foreign keys)
+ for _, tableDiff := range tableMap {
+ createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable, false)
+ if err != nil {
+ return err
+ }
+ _, _ = buf.WriteString(createTableSQL)
+ if createTableSQL != "" {
+ _, _ = buf.WriteString("\n")
+ }
+ }
+
+ // Create views
+ for _, viewDiff := range viewMap {
+ if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {
+ return err
+ }
+ }
+
+ // Create materialized views
+ for _, mvDiff := range materializedViewMap {
+ if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {
+ return err
+ }
+ }
+
+ // Create functions
+ for _, funcDiff := range functionMap {
+ if err := writeFunctionDiff(buf, funcDiff); err != nil {
+ return err
+ }
+ }
+
+ // Add foreign keys
+ for _, tableDiff := range tableMap {
+ if tableDiff.NewTable != nil {
+ for _, fk := range tableDiff.NewTable.ForeignKeys {
+ if err := writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ } else {
+ // Create in topological order (dependencies first)
+ for _, objID := range orderedList {
+ if tableDiff, ok := tableMap[objID]; ok {
+ // Create table without foreign keys
+ createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable, false)
+ if err != nil {
+ return err
+ }
+ _, _ = buf.WriteString(createTableSQL)
+ if createTableSQL != "" {
+ _, _ = buf.WriteString("\n")
+ }
+ } else if viewDiff, ok := viewMap[objID]; ok {
+ if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {
+ return err
+ }
+ } else if mvDiff, ok := materializedViewMap[objID]; ok {
+ if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {
+ return err
+ }
+ } else if funcDiff, ok := functionMap[objID]; ok {
+ if err := writeFunctionDiff(buf, funcDiff); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Add foreign keys after all tables are created
+ for _, tableDiff := range tableMap {
+ if tableDiff.NewTable != nil {
+ for _, fk := range tableDiff.NewTable.ForeignKeys {
+ if err := writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ }
+
+ // Handle ALTER table operations
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionAlter {
+ alterTableSQL, err := generateAlterTable(tableDiff)
+ if err != nil {
+ return err
+ }
+ _, _ = buf.WriteString(alterTableSQL)
+ if alterTableSQL != "" {
+ _, _ = buf.WriteString("\n")
+ }
+ }
+ }
+
+ return nil
+}
+
+func generateCreateTable(schemaName, tableName string, table *storepb.TableMetadata, includeForeignKeys bool) (string, error) {
+ var buf strings.Builder
+
+ if err := writeMigrationCreateTable(&buf, schemaName, tableName, table.Columns, table.CheckConstraints); err != nil {
+ return "", err
+ }
+
+ // Add partitioning clause if needed
+ if len(table.Partitions) > 0 {
+ if err := writeMigrationPartitionClause(&buf, table.Partitions[0]); err != nil {
+ return "", err
+ }
+ }
+
+ if _, err := buf.WriteString(";\n"); err != nil {
+ return "", err
+ }
+
+ // Add constraints (primary key, unique)
+ for _, index := range table.Indexes {
+ if index.Primary {
+ if err := writeMigrationPrimaryKey(&buf, schemaName, tableName, index); err != nil {
+ return "", err
+ }
+ } else if index.Unique && index.IsConstraint {
+ if err := writeMigrationUniqueKey(&buf, schemaName, tableName, index); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ // Add non-constraint indexes
+ for _, index := range table.Indexes {
+ if !index.IsConstraint {
+ if err := writeMigrationIndex(&buf, schemaName, tableName, index); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ // Optionally add foreign keys
+ if includeForeignKeys && table != nil {
+ for _, fk := range table.ForeignKeys {
+ if err := writeMigrationForeignKey(&buf, schemaName, tableName, fk); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ return buf.String(), nil
+}
+
+func generateAlterTable(tableDiff *schema.TableDiff) (string, error) {
+ var buf strings.Builder
+
+ // Add columns first (other operations might depend on them)
+ for _, colDiff := range tableDiff.ColumnChanges {
+ if colDiff.Action == schema.MetadataDiffActionCreate {
+ if err := writeAddColumn(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ // Alter columns
+ for _, colDiff := range tableDiff.ColumnChanges {
+ if colDiff.Action == schema.MetadataDiffActionAlter {
+ alterColSQL, err := generateAlterColumn(tableDiff.SchemaName, tableDiff.TableName, colDiff)
+ if err != nil {
+ return "", err
+ }
+ _, _ = buf.WriteString(alterColSQL)
+ }
+ }
+
+ // Add indexes
+ for _, indexDiff := range tableDiff.IndexChanges {
+ if indexDiff.Action == schema.MetadataDiffActionCreate {
+ if indexDiff.NewIndex.IsConstraint {
+ // Add constraint (primary key or unique constraint)
+ if indexDiff.NewIndex.Primary {
+ if err := writeMigrationPrimaryKey(&buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex); err != nil {
+ return "", err
+ }
+ } else if indexDiff.NewIndex.Unique {
+ if err := writeMigrationUniqueKey(&buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex); err != nil {
+ return "", err
+ }
+ }
+ } else {
+ if err := writeMigrationIndex(&buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex); err != nil {
+ return "", err
+ }
+ }
+ }
+ }
+
+ // Add check constraints
+ for _, checkDiff := range tableDiff.CheckConstraintChanges {
+ if checkDiff.Action == schema.MetadataDiffActionCreate {
+ if err := writeAddCheckConstraint(&buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.NewCheckConstraint); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ // Add foreign keys last (they depend on other tables/columns)
+ for _, fkDiff := range tableDiff.ForeignKeyChanges {
+ if fkDiff.Action == schema.MetadataDiffActionCreate {
+ if err := writeMigrationForeignKey(&buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.NewForeignKey); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ return buf.String(), nil
+}
+
+func generateAlterColumn(schemaName, tableName string, colDiff *schema.ColumnDiff) (string, error) {
+ var buf strings.Builder
+
+ // In PostgreSQL, we need to handle different aspects of column changes separately
+
+ // If type changed, alter the column type
+ if colDiff.OldColumn.Type != colDiff.NewColumn.Type {
+ if err := writeAlterColumnType(&buf, schemaName, tableName, colDiff.NewColumn.Name, colDiff.NewColumn.Type); err != nil {
+ return "", err
+ }
+ }
+
+ // If nullability changed
+ if colDiff.OldColumn.Nullable != colDiff.NewColumn.Nullable {
+ if colDiff.NewColumn.Nullable {
+ if err := writeAlterColumnDropNotNull(&buf, schemaName, tableName, colDiff.NewColumn.Name); err != nil {
+ return "", err
+ }
+ } else {
+ if err := writeAlterColumnSetNotNull(&buf, schemaName, tableName, colDiff.NewColumn.Name); err != nil {
+ return "", err
+ }
+ }
+ }
+
+ // Handle default value changes
+ oldHasDefault := hasDefaultValue(colDiff.OldColumn)
+ newHasDefault := hasDefaultValue(colDiff.NewColumn)
+ if oldHasDefault || newHasDefault {
+ if !defaultValuesEqual(colDiff.OldColumn, colDiff.NewColumn) {
+ // First drop the old default if it exists
+ if oldHasDefault {
+ if err := writeAlterColumnDropDefault(&buf, schemaName, tableName, colDiff.OldColumn.Name); err != nil {
+ return "", err
+ }
+ }
+
+ // Add new default if needed
+ if newHasDefault {
+ defaultExpr := getDefaultExpression(colDiff.NewColumn)
+ if err := writeAlterColumnSetDefault(&buf, schemaName, tableName, colDiff.NewColumn.Name, defaultExpr); err != nil {
+ return "", err
+ }
+ }
+ }
+ }
+
+ return buf.String(), nil
+}
+
+// hasDefaultValue checks if a column has any default value
+func hasDefaultValue(column *storepb.ColumnMetadata) bool {
+ if column == nil {
+ return false
+ }
+ return column.GetDefaultExpression() != "" ||
+ (column.GetDefault() != nil && column.GetDefault().Value != "") ||
+ column.GetDefaultNull()
+}
+
+// defaultValuesEqual checks if two columns have the same default value
+func defaultValuesEqual(col1, col2 *storepb.ColumnMetadata) bool {
+ if col1 == nil || col2 == nil {
+ return col1 == col2
+ }
+
+ // Check default expression
+ if col1.GetDefaultExpression() != col2.GetDefaultExpression() {
+ return false
+ }
+
+ // Check default value
+ def1 := col1.GetDefault()
+ def2 := col2.GetDefault()
+ if (def1 == nil) != (def2 == nil) {
+ return false
+ }
+ if def1 != nil && def1.Value != def2.Value {
+ return false
+ }
+
+ // Check default null
+ if col1.GetDefaultNull() != col2.GetDefaultNull() {
+ return false
+ }
+
+ return true
+}
+
+// getDefaultExpression returns the SQL expression for a column's default value
+func getDefaultExpression(column *storepb.ColumnMetadata) string {
+ if column == nil {
+ return ""
+ }
+
+ if expr := column.GetDefaultExpression(); expr != "" {
+ return expr
+ }
+
+ if def := column.GetDefault(); def != nil && def.Value != "" {
+ // Quote string literals
+ return fmt.Sprintf("'%s'", def.Value)
+ }
+
+ if column.GetDefaultNull() {
+ return "NULL"
+ }
+
+ return ""
+}
+
+// Write functions for various DDL statements
+
+func writeDropTrigger(out *strings.Builder, schema, table, trigger string) error {
+ _, _ = out.WriteString(`DROP TRIGGER IF EXISTS "`)
+ _, _ = out.WriteString(trigger)
+ _, _ = out.WriteString(`" ON "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropForeignKey(out *strings.Builder, schema, table, constraint string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" DROP CONSTRAINT IF EXISTS "`)
+ _, _ = out.WriteString(constraint)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropFunction(out *strings.Builder, schema, function string) error {
+ _, _ = out.WriteString(`DROP FUNCTION IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(function)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropView(out *strings.Builder, schema, view string) error {
+ _, _ = out.WriteString(`DROP VIEW IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(view)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropMaterializedView(out *strings.Builder, schema, view string) error {
+ _, _ = out.WriteString(`DROP MATERIALIZED VIEW IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(view)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropCheckConstraint(out *strings.Builder, schema, table, constraint string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" DROP CONSTRAINT IF EXISTS "`)
+ _, _ = out.WriteString(constraint)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropConstraint(out *strings.Builder, schema, table, constraint string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" DROP CONSTRAINT IF EXISTS "`)
+ _, _ = out.WriteString(constraint)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropIndex(out *strings.Builder, schema, index string) error {
+ _, _ = out.WriteString(`DROP INDEX IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(index)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropColumn(out *strings.Builder, schema, table, column string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" DROP COLUMN IF EXISTS "`)
+ _, _ = out.WriteString(column)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropTable(out *strings.Builder, schema, table string) error {
+ _, _ = out.WriteString(`DROP TABLE IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropSequence(out *strings.Builder, schema, sequence string) error {
+ _, _ = out.WriteString(`DROP SEQUENCE IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(sequence)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropSchema(out *strings.Builder, schema string) error {
+ _, _ = out.WriteString(`DROP SCHEMA IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeDropType(out *strings.Builder, schema, typeName string) error {
+ _, _ = out.WriteString(`DROP TYPE IF EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(typeName)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeCreateEnumType(out *strings.Builder, schema string, enum *storepb.EnumTypeMetadata) error {
+ _, _ = out.WriteString(`CREATE TYPE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(enum.Name)
+ _, _ = out.WriteString(`" AS ENUM (`)
+
+ for i, value := range enum.Values {
+ if i > 0 {
+ _, _ = out.WriteString(", ")
+ }
+ _, _ = out.WriteString("'")
+ _, _ = out.WriteString(value)
+ _, _ = out.WriteString("'")
+ }
+
+ _, _ = out.WriteString(");")
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeCreateSchema(out *strings.Builder, schema string) error {
+ _, _ = out.WriteString(`CREATE SCHEMA IF NOT EXISTS "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAddColumn(out *strings.Builder, schema, table string, column *storepb.ColumnMetadata) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD COLUMN "`)
+ _, _ = out.WriteString(column.Name)
+ _, _ = out.WriteString(`" `)
+ _, _ = out.WriteString(column.Type)
+
+ if column.DefaultValue != nil {
+ if defaultValue, ok := column.DefaultValue.(*storepb.ColumnMetadata_DefaultExpression); ok {
+ _, _ = out.WriteString(` DEFAULT `)
+ _, _ = out.WriteString(defaultValue.DefaultExpression)
+ }
+ }
+
+ if !column.Nullable {
+ _, _ = out.WriteString(` NOT NULL`)
+ }
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAlterColumnType(out *strings.Builder, schema, table, column, newType string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(column)
+ _, _ = out.WriteString(`" TYPE `)
+ _, _ = out.WriteString(newType)
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAlterColumnSetNotNull(out *strings.Builder, schema, table, column string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(column)
+ _, _ = out.WriteString(`" SET NOT NULL;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAlterColumnDropNotNull(out *strings.Builder, schema, table, column string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(column)
+ _, _ = out.WriteString(`" DROP NOT NULL;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAlterColumnSetDefault(out *strings.Builder, schema, table, column, defaultExpr string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(column)
+ _, _ = out.WriteString(`" SET DEFAULT `)
+ _, _ = out.WriteString(defaultExpr)
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAlterColumnDropDefault(out *strings.Builder, schema, table, column string) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ALTER COLUMN "`)
+ _, _ = out.WriteString(column)
+ _, _ = out.WriteString(`" DROP DEFAULT;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeAddCheckConstraint(out *strings.Builder, schema, table string, check *storepb.CheckConstraintMetadata) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(check.Name)
+ _, _ = out.WriteString(`" CHECK `)
+ _, _ = out.WriteString(check.Expression)
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+func writeFunctionDiff(out *strings.Builder, funcDiff *schema.FunctionDiff) error {
+ switch funcDiff.Action {
+ case schema.MetadataDiffActionCreate:
+ _, _ = out.WriteString(funcDiff.NewFunction.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(funcDiff.NewFunction.Definition), ";") {
+ _, _ = out.WriteString(";")
+ }
+ _, _ = out.WriteString("\n\n")
+ case schema.MetadataDiffActionAlter:
+ // PostgreSQL requires CREATE OR REPLACE for functions
+ _, _ = out.WriteString(funcDiff.NewFunction.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(funcDiff.NewFunction.Definition), ";") {
+ _, _ = out.WriteString(";")
+ }
+ _, _ = out.WriteString("\n\n")
+ }
+ return nil
+}
+
+// Helper functions to check if diff contains certain types of changes
+func hasCreateOrAlterObjects(diff *schema.MetadataDiff) bool {
+ return hasCreateOrAlterTables(diff) || hasCreateViewsOrFunctions(diff)
+}
+
+func hasCreateOrAlterTables(diff *schema.MetadataDiff) bool {
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionCreate || tableDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ for _, seqDiff := range diff.SequenceChanges {
+ if seqDiff.Action == schema.MetadataDiffActionCreate {
+ return true
+ }
+ }
+ return false
+}
+
+func hasCreateViewsOrFunctions(diff *schema.MetadataDiff) bool {
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionCreate || viewDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ for _, mvDiff := range diff.MaterializedViewChanges {
+ if mvDiff.Action == schema.MetadataDiffActionCreate || mvDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ for _, funcDiff := range diff.FunctionChanges {
+ if funcDiff.Action == schema.MetadataDiffActionCreate || funcDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ return false
+}
+
+// getObjectID generates a unique identifier for database objects
+func getMigrationObjectID(schema, name string) string {
+ return fmt.Sprintf("%s.%s", schema, name)
+}
+
+// writeCreateSequence writes a CREATE SEQUENCE statement
+func writeMigrationCreateSequence(out *strings.Builder, schema string, seq *storepb.SequenceMetadata) error {
+ _, _ = out.WriteString(`CREATE SEQUENCE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(seq.Name)
+ _, _ = out.WriteString(`"`)
+
+ if seq.DataType != "" {
+ _, _ = out.WriteString(` AS `)
+ _, _ = out.WriteString(seq.DataType)
+ }
+ if seq.Start != "" {
+ _, _ = out.WriteString(` START WITH `)
+ _, _ = out.WriteString(seq.Start)
+ }
+ if seq.Increment != "" {
+ _, _ = out.WriteString(` INCREMENT BY `)
+ _, _ = out.WriteString(seq.Increment)
+ }
+ if seq.MinValue != "" {
+ _, _ = out.WriteString(` MINVALUE `)
+ _, _ = out.WriteString(seq.MinValue)
+ }
+ if seq.MaxValue != "" {
+ _, _ = out.WriteString(` MAXVALUE `)
+ _, _ = out.WriteString(seq.MaxValue)
+ }
+ if seq.CacheSize != "" {
+ _, _ = out.WriteString(` CACHE `)
+ _, _ = out.WriteString(seq.CacheSize)
+ }
+ if seq.Cycle {
+ _, _ = out.WriteString(` CYCLE`)
+ }
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+// writeView writes a CREATE VIEW statement
+func writeMigrationView(out *strings.Builder, schema string, view *storepb.ViewMetadata) error {
+ _, _ = out.WriteString(`CREATE VIEW "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(view.Name)
+ _, _ = out.WriteString(`" AS `)
+ _, _ = out.WriteString(view.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(view.Definition), ";") {
+ _, _ = out.WriteString(`;`)
+ }
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+// writeMaterializedView writes a CREATE MATERIALIZED VIEW statement
+func writeMigrationMaterializedView(out *strings.Builder, schema string, view *storepb.MaterializedViewMetadata) error {
+ _, _ = out.WriteString(`CREATE MATERIALIZED VIEW "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(view.Name)
+ _, _ = out.WriteString(`" AS `)
+ _, _ = out.WriteString(view.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(view.Definition), ";") {
+ _, _ = out.WriteString(`;`)
+ }
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+// writeForeignKey writes an ALTER TABLE ADD CONSTRAINT statement for a foreign key
+func writeMigrationForeignKey(out *strings.Builder, schema, table string, fk *storepb.ForeignKeyMetadata) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(fk.Name)
+ _, _ = out.WriteString(`" FOREIGN KEY (`)
+
+ for i, col := range fk.Columns {
+ if i > 0 {
+ _, _ = out.WriteString(`, `)
+ }
+ _, _ = out.WriteString(`"`)
+ _, _ = out.WriteString(col)
+ _, _ = out.WriteString(`"`)
+ }
+
+ _, _ = out.WriteString(`) REFERENCES "`)
+ _, _ = out.WriteString(fk.ReferencedSchema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(fk.ReferencedTable)
+ _, _ = out.WriteString(`" (`)
+
+ for i, col := range fk.ReferencedColumns {
+ if i > 0 {
+ _, _ = out.WriteString(`, `)
+ }
+ _, _ = out.WriteString(`"`)
+ _, _ = out.WriteString(col)
+ _, _ = out.WriteString(`"`)
+ }
+
+ _, _ = out.WriteString(`)`)
+
+ if fk.OnUpdate != "" {
+ _, _ = out.WriteString(` ON UPDATE `)
+ _, _ = out.WriteString(fk.OnUpdate)
+ }
+ if fk.OnDelete != "" {
+ _, _ = out.WriteString(` ON DELETE `)
+ _, _ = out.WriteString(fk.OnDelete)
+ }
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+// writeCreateTable writes a CREATE TABLE statement
+func writeMigrationCreateTable(out *strings.Builder, schema, table string, columns []*storepb.ColumnMetadata, checks []*storepb.CheckConstraintMetadata) error {
+ _, _ = out.WriteString(`CREATE TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" (`)
+ _, _ = out.WriteString("\n")
+
+ // Write columns
+ for i, col := range columns {
+ if i > 0 {
+ _, _ = out.WriteString(",\n")
+ }
+ _, _ = out.WriteString(" \"")
+ _, _ = out.WriteString(col.Name)
+ _, _ = out.WriteString("\" ")
+ _, _ = out.WriteString(col.Type)
+
+ if !col.Nullable {
+ _, _ = out.WriteString(" NOT NULL")
+ }
+
+ if col.DefaultValue != nil {
+ _, _ = out.WriteString(" DEFAULT ")
+ _, _ = out.WriteString(getDefaultExpression(col))
+ }
+ }
+
+ // Write check constraints
+ for _, check := range checks {
+ _, _ = out.WriteString(",\n")
+ _, _ = out.WriteString(" CONSTRAINT \"")
+ _, _ = out.WriteString(check.Name)
+ _, _ = out.WriteString("\" CHECK (")
+ _, _ = out.WriteString(check.Expression)
+ _, _ = out.WriteString(")")
+ }
+
+ _, _ = out.WriteString("\n)")
+ return nil
+}
+
+// writePartitionClause writes the partition clause for a table
+func writeMigrationPartitionClause(out *strings.Builder, partition *storepb.TablePartitionMetadata) error {
+ _, _ = out.WriteString(" PARTITION BY ")
+ _, _ = out.WriteString(partition.Expression)
+ return nil
+}
+
+// writePrimaryKey writes an ALTER TABLE ADD PRIMARY KEY statement
+func writeMigrationPrimaryKey(out *strings.Builder, schema, table string, index *storepb.IndexMetadata) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(index.Name)
+ _, _ = out.WriteString(`" PRIMARY KEY (`)
+
+ for i, expr := range index.Expressions {
+ if i > 0 {
+ _, _ = out.WriteString(`, `)
+ }
+ _, _ = out.WriteString(expr)
+ }
+
+ _, _ = out.WriteString(`);`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+// writeUniqueKey writes an ALTER TABLE ADD UNIQUE statement
+func writeMigrationUniqueKey(out *strings.Builder, schema, table string, index *storepb.IndexMetadata) error {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(index.Name)
+ _, _ = out.WriteString(`" UNIQUE (`)
+
+ for i, expr := range index.Expressions {
+ if i > 0 {
+ _, _ = out.WriteString(`, `)
+ }
+ _, _ = out.WriteString(expr)
+ }
+
+ _, _ = out.WriteString(`);`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
+
+// writeIndex writes a CREATE INDEX statement
+func writeMigrationIndex(out *strings.Builder, schema, table string, index *storepb.IndexMetadata) error {
+ _, _ = out.WriteString(`CREATE `)
+ if index.Unique {
+ _, _ = out.WriteString(`UNIQUE `)
+ }
+ _, _ = out.WriteString(`INDEX "`)
+ _, _ = out.WriteString(index.Name)
+ _, _ = out.WriteString(`" ON "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" `)
+
+ if index.Type != "" && index.Type != "BTREE" {
+ _, _ = out.WriteString(`USING `)
+ _, _ = out.WriteString(index.Type)
+ _, _ = out.WriteString(` `)
+ }
+
+ _, _ = out.WriteString(`(`)
+ for i, expr := range index.Expressions {
+ if i > 0 {
+ _, _ = out.WriteString(`, `)
+ }
+ _, _ = out.WriteString(expr)
+
+ // Handle descending order if specified
+ if i < len(index.Descending) && index.Descending[i] {
+ _, _ = out.WriteString(` DESC`)
+ }
+ }
+ _, _ = out.WriteString(`)`)
+
+ // Note: IndexMetadata doesn't have a Where field in the current protobuf definition
+ // This would need to be added if partial indexes need to be supported
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+}
diff --git a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
new file mode 100644
index 0000000000..48ff79349b
--- /dev/null
+++ b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go
@@ -0,0 +1,780 @@
+package pg
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/stdlib"
+ "github.com/stretchr/testify/require"
+ "github.com/testcontainers/testcontainers-go"
+ "github.com/testcontainers/testcontainers-go/modules/postgres"
+ "github.com/testcontainers/testcontainers-go/wait"
+ "google.golang.org/protobuf/testing/protocmp"
+
+ "github.com/bytebase/bytebase/backend/plugin/db"
+ pgdb "github.com/bytebase/bytebase/backend/plugin/db/pg"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ "github.com/bytebase/bytebase/backend/store/model"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+// TestGenerateMigrationWithTestcontainer tests the generate migration function
+// by applying migrations and rollback to verify the schema can be restored.
+func TestGenerateMigrationWithTestcontainer(t *testing.T) {
+ ctx := context.Background()
+
+ // Start PostgreSQL container
+ pgContainer, err := postgres.Run(ctx,
+ "postgres:16-alpine",
+ postgres.WithDatabase("test_db"),
+ postgres.WithUsername("postgres"),
+ postgres.WithPassword("test"),
+ testcontainers.WithWaitStrategy(
+ wait.ForLog("database system is ready to accept connections").
+ WithOccurrence(2).
+ WithStartupTimeout(5*time.Minute),
+ ),
+ )
+ require.NoError(t, err)
+ defer func() {
+ if err := pgContainer.Terminate(ctx); err != nil {
+ t.Logf("failed to terminate container: %s", err)
+ }
+ }()
+
+ // Get connection string
+ connectionString, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
+ require.NoError(t, err)
+
+ // Connect to the database
+ connConfig, err := pgx.ParseConfig(connectionString)
+ require.NoError(t, err)
+ db := stdlib.OpenDB(*connConfig)
+ defer db.Close()
+
+ // Test cases with various schema changes
+ testCases := []struct {
+ name string
+ initialSchema string
+ migrationDDL string
+ description string
+ }{
+ {
+ name: "basic_table_operations",
+ initialSchema: `
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(50) NOT NULL,
+ email VARCHAR(100) NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE TABLE posts (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ title VARCHAR(200) NOT NULL,
+ content TEXT,
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id)
+);
+
+CREATE INDEX idx_posts_user_id ON posts(user_id);
+`,
+ migrationDDL: `
+-- Add new column
+ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;
+
+-- Create new table
+CREATE TABLE comments (
+ id SERIAL PRIMARY KEY,
+ post_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ content TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT fk_post FOREIGN KEY (post_id) REFERENCES posts(id),
+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id)
+);
+
+-- Add new index
+CREATE INDEX idx_users_email ON users(email);
+
+-- Add check constraint
+ALTER TABLE posts ADD CONSTRAINT check_title_length CHECK (length(title) > 0);
+`,
+ description: "Basic table operations with columns, constraints, and indexes",
+ },
+ {
+ name: "views_and_functions",
+ initialSchema: `
+CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ price DECIMAL(10, 2) NOT NULL,
+ stock INTEGER DEFAULT 0
+);
+
+CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ product_id INTEGER NOT NULL,
+ quantity INTEGER NOT NULL,
+ total DECIMAL(10, 2),
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)
+);
+`,
+ migrationDDL: `
+-- Create view
+CREATE VIEW product_inventory AS
+SELECT
+ p.id,
+ p.name,
+ p.price,
+ p.stock,
+ COALESCE(SUM(o.quantity), 0) as total_ordered
+FROM products p
+LEFT JOIN orders o ON p.id = o.product_id
+GROUP BY p.id, p.name, p.price, p.stock;
+
+-- Create function
+CREATE OR REPLACE FUNCTION calculate_order_total()
+RETURNS TRIGGER AS $$
+BEGIN
+ NEW.total := NEW.quantity * (SELECT price FROM products WHERE id = NEW.product_id);
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Create trigger
+CREATE TRIGGER update_order_total
+BEFORE INSERT OR UPDATE ON orders
+FOR EACH ROW
+EXECUTE FUNCTION calculate_order_total();
+
+-- Create materialized view
+CREATE MATERIALIZED VIEW product_stats AS
+SELECT
+ product_id,
+ COUNT(*) as order_count,
+ SUM(quantity) as total_quantity,
+ SUM(total) as total_revenue
+FROM orders
+GROUP BY product_id;
+
+-- Create index on materialized view
+CREATE INDEX idx_product_stats_revenue ON product_stats(total_revenue DESC);
+`,
+ description: "Views, functions, triggers, and materialized views",
+ },
+ {
+ name: "schema_and_sequences",
+ initialSchema: `
+CREATE SCHEMA inventory;
+
+CREATE TABLE inventory.items (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+);
+`,
+ migrationDDL: `
+-- Create new schema
+CREATE SCHEMA sales;
+
+-- Create sequence
+CREATE SEQUENCE sales.order_seq START WITH 1000 INCREMENT BY 10;
+
+-- Create table using sequence
+CREATE TABLE sales.orders (
+ id INTEGER DEFAULT nextval('sales.order_seq') PRIMARY KEY,
+ item_id INTEGER NOT NULL,
+ quantity INTEGER NOT NULL,
+ CONSTRAINT fk_item FOREIGN KEY (item_id) REFERENCES inventory.items(id)
+);
+
+-- Add enum type
+CREATE TYPE inventory.item_status AS ENUM ('available', 'out_of_stock', 'discontinued');
+
+-- Alter table to use enum
+ALTER TABLE inventory.items ADD COLUMN status inventory.item_status DEFAULT 'available';
+`,
+ description: "Schemas, sequences, and custom types",
+ },
+ {
+ name: "complex_dependencies",
+ initialSchema: `
+CREATE TABLE departments (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL
+);
+
+CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ department_id INTEGER,
+ CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(id)
+);
+`,
+ migrationDDL: `
+-- Create base view
+CREATE VIEW department_employees AS
+SELECT d.id as dept_id, d.name as dept_name, e.id as emp_id, e.name as emp_name
+FROM departments d
+LEFT JOIN employees e ON d.id = e.department_id;
+
+-- Create dependent view
+CREATE VIEW department_summary AS
+SELECT dept_id, dept_name, COUNT(emp_id) as employee_count
+FROM department_employees
+GROUP BY dept_id, dept_name;
+
+-- Create function that depends on table
+CREATE OR REPLACE FUNCTION get_department_employees(dept_id INTEGER)
+RETURNS TABLE(employee_id INTEGER, employee_name VARCHAR) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT id, name
+ FROM employees
+ WHERE department_id = dept_id;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Create another table with foreign key to existing table
+CREATE TABLE projects (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ department_id INTEGER NOT NULL,
+ lead_employee_id INTEGER,
+ CONSTRAINT fk_project_dept FOREIGN KEY (department_id) REFERENCES departments(id),
+ CONSTRAINT fk_project_lead FOREIGN KEY (lead_employee_id) REFERENCES employees(id)
+);
+`,
+ description: "Complex dependencies between views, functions, and tables",
+ },
+ {
+ name: "drop_indexes_and_constraints",
+ initialSchema: `
+CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ category VARCHAR(50),
+ price DECIMAL(10, 2),
+ supplier_id INTEGER
+);
+
+CREATE INDEX idx_products_category ON products(category);
+CREATE INDEX idx_products_price ON products(price);
+CREATE UNIQUE INDEX idx_products_name ON products(name);
+
+ALTER TABLE products ADD CONSTRAINT check_price_positive CHECK (price > 0);
+ALTER TABLE products ADD CONSTRAINT check_name_length CHECK (length(name) >= 3);
+`,
+ migrationDDL: `
+-- Drop indexes and constraints
+DROP INDEX idx_products_category;
+DROP INDEX idx_products_price;
+DROP INDEX idx_products_name;
+ALTER TABLE products DROP CONSTRAINT check_price_positive;
+ALTER TABLE products DROP CONSTRAINT check_name_length;
+`,
+ description: "Drop indexes and constraints from tables",
+ },
+ {
+ name: "drop_views_and_functions",
+ initialSchema: `
+CREATE TABLE sales (
+ id SERIAL PRIMARY KEY,
+ product_name VARCHAR(100) NOT NULL,
+ sale_amount DECIMAL(10, 2) NOT NULL,
+ sale_date DATE NOT NULL
+);
+
+CREATE VIEW monthly_sales AS
+SELECT
+ EXTRACT(YEAR FROM sale_date) as year,
+ EXTRACT(MONTH FROM sale_date) as month,
+ SUM(sale_amount) as total_sales
+FROM sales
+GROUP BY EXTRACT(YEAR FROM sale_date), EXTRACT(MONTH FROM sale_date);
+
+CREATE MATERIALIZED VIEW top_products AS
+SELECT
+ product_name,
+ COUNT(*) as sale_count,
+ SUM(sale_amount) as total_revenue
+FROM sales
+GROUP BY product_name
+ORDER BY total_revenue DESC;
+
+CREATE OR REPLACE FUNCTION get_monthly_total(year_param INTEGER, month_param INTEGER)
+RETURNS DECIMAL AS $$
+BEGIN
+ RETURN (
+ SELECT COALESCE(SUM(sale_amount), 0)
+ FROM sales
+ WHERE EXTRACT(YEAR FROM sale_date) = year_param
+ AND EXTRACT(MONTH FROM sale_date) = month_param
+ );
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE OR REPLACE FUNCTION calculate_discount(amount DECIMAL)
+RETURNS DECIMAL AS $$
+BEGIN
+ RETURN amount * 0.1;
+END;
+$$ LANGUAGE plpgsql;
+`,
+ migrationDDL: `
+-- Drop views and functions
+DROP MATERIALIZED VIEW top_products;
+DROP VIEW monthly_sales;
+DROP FUNCTION get_monthly_total(INTEGER, INTEGER);
+DROP FUNCTION calculate_discount(DECIMAL);
+`,
+ description: "Drop views and functions that depend on tables",
+ },
+ {
+ name: "alter_table_columns",
+ initialSchema: `
+CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(50) NOT NULL,
+ price DECIMAL(8, 2) NOT NULL,
+ description TEXT,
+ category VARCHAR(30),
+ is_active BOOLEAN DEFAULT true
+);
+
+CREATE INDEX idx_products_category ON products(category);
+CREATE INDEX idx_products_price ON products(price);
+`,
+ migrationDDL: `
+-- Alter table operations
+ALTER TABLE products
+ ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ ADD COLUMN stock_quantity INTEGER DEFAULT 0,
+ ADD COLUMN weight DECIMAL(5, 2);
+
+-- Change column types and constraints
+ALTER TABLE products ALTER COLUMN name TYPE VARCHAR(100);
+ALTER TABLE products ALTER COLUMN price TYPE DECIMAL(10, 2);
+ALTER TABLE products ALTER COLUMN description SET NOT NULL;
+ALTER TABLE products ALTER COLUMN category DROP NOT NULL;
+
+-- Add constraints
+ALTER TABLE products ADD CONSTRAINT check_price_positive CHECK (price > 0);
+ALTER TABLE products ADD CONSTRAINT check_stock_non_negative CHECK (stock_quantity >= 0);
+
+-- Add new index
+CREATE INDEX idx_products_created_at ON products(created_at);
+CREATE UNIQUE INDEX idx_products_name_category ON products(name, category);
+`,
+ description: "Alter table with column additions, type changes, and constraints",
+ },
+ {
+ name: "drop_and_recreate_constraints",
+ initialSchema: `
+CREATE TABLE authors (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ email VARCHAR(100) UNIQUE
+);
+
+CREATE TABLE books (
+ id SERIAL PRIMARY KEY,
+ title VARCHAR(200) NOT NULL,
+ author_id INTEGER NOT NULL,
+ isbn VARCHAR(20) UNIQUE,
+ published_year INTEGER,
+ price DECIMAL(8, 2),
+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),
+ CONSTRAINT check_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),
+ CONSTRAINT check_price_positive CHECK (price > 0)
+);
+
+CREATE INDEX idx_books_author ON books(author_id);
+CREATE INDEX idx_books_year ON books(published_year);
+`,
+ migrationDDL: `
+-- Drop and recreate foreign key with different options
+ALTER TABLE books DROP CONSTRAINT fk_author;
+ALTER TABLE books ADD CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE;
+
+-- Drop and modify check constraints
+ALTER TABLE books DROP CONSTRAINT check_year_valid;
+ALTER TABLE books ADD CONSTRAINT check_year_extended CHECK (published_year >= 1000 AND published_year <= 2030);
+
+-- Drop unique constraint and recreate as regular index
+ALTER TABLE books DROP CONSTRAINT books_isbn_key;
+CREATE INDEX idx_books_isbn ON books(isbn);
+
+-- Add new constraints
+ALTER TABLE books ADD CONSTRAINT check_title_length CHECK (length(title) >= 3);
+`,
+ description: "Drop and recreate constraints with different definitions",
+ },
+ {
+ name: "drop_sequence_and_type",
+ initialSchema: `
+CREATE SCHEMA accounting;
+
+CREATE TYPE accounting.transaction_status AS ENUM ('pending', 'completed', 'cancelled');
+
+CREATE SEQUENCE accounting.transaction_seq START 1000;
+
+CREATE TABLE accounting.simple_log (
+ message TEXT NOT NULL,
+ status accounting.transaction_status DEFAULT 'pending'
+);
+`,
+ migrationDDL: `
+-- Drop schema objects step by step
+DROP TABLE accounting.simple_log;
+DROP TYPE accounting.transaction_status;
+DROP SEQUENCE accounting.transaction_seq;
+DROP SCHEMA accounting;
+`,
+ description: "Drop schema with sequences and custom types",
+ },
+ {
+ name: "mixed_operations_complex",
+ initialSchema: `
+CREATE TABLE suppliers (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ contact_email VARCHAR(100)
+);
+
+CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(100) NOT NULL,
+ supplier_id INTEGER,
+ price DECIMAL(10, 2),
+ CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES suppliers(id)
+);
+`,
+ migrationDDL: `
+-- Mix of CREATE, ALTER, and DROP operations
+
+-- 1. Create new table
+CREATE TABLE categories (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(50) NOT NULL UNIQUE,
+ description TEXT
+);
+
+-- 2. Alter existing table (add column)
+ALTER TABLE products ADD COLUMN category_id INTEGER;
+
+-- 3. Create foreign key to new table
+ALTER TABLE products ADD CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id);
+
+-- 4. Create new view
+CREATE VIEW product_summary AS
+SELECT
+ p.id,
+ p.name as product_name,
+ s.name as supplier_name,
+ c.name as category_name,
+ p.price
+FROM products p
+LEFT JOIN suppliers s ON p.supplier_id = s.id
+LEFT JOIN categories c ON p.category_id = c.id;
+
+-- 5. Drop old constraint and recreate with different action
+ALTER TABLE products DROP CONSTRAINT fk_supplier;
+ALTER TABLE products ADD CONSTRAINT fk_supplier_cascade FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL;
+
+-- 6. Add new constraints
+ALTER TABLE products ADD CONSTRAINT check_price_range CHECK (price >= 0 AND price <= 10000);
+ALTER TABLE suppliers ADD CONSTRAINT check_email_format CHECK (contact_email LIKE '%@%');
+
+-- 7. Create indexes
+CREATE INDEX idx_products_category ON products(category_id);
+CREATE INDEX idx_products_price_range ON products(price) WHERE price > 100;
+
+-- 8. Create function
+CREATE OR REPLACE FUNCTION get_expensive_products(threshold DECIMAL DEFAULT 100)
+RETURNS TABLE(product_name VARCHAR, supplier_name VARCHAR, price DECIMAL) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT p.name, s.name, p.price
+ FROM products p
+ JOIN suppliers s ON p.supplier_id = s.id
+ WHERE p.price > threshold
+ ORDER BY p.price DESC;
+END;
+$$ LANGUAGE plpgsql;
+`,
+ description: "Mixed operations: CREATE, ALTER, DROP with complex dependencies",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Create a new database for each test case
+ dbName := fmt.Sprintf("test_%s", tc.name)
+ _, err := db.Exec(fmt.Sprintf("CREATE DATABASE %s", dbName))
+ require.NoError(t, err)
+ defer func() {
+ _, _ = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbName))
+ }()
+
+ // Connect to the test database
+ testConnConfig := *connConfig
+ testConnConfig.Database = dbName
+ testDB := stdlib.OpenDB(testConnConfig)
+ defer testDB.Close()
+
+ // Step 1: Initialize the database schema and get schema result A
+ _, err = testDB.Exec(tc.initialSchema)
+ require.NoError(t, err)
+
+ schemaA, err := getSyncMetadataForGenerateMigration(ctx, &testConnConfig, dbName)
+ require.NoError(t, err)
+
+ // Step 2: Do some migration and get schema result B
+ _, err = testDB.Exec(tc.migrationDDL)
+ require.NoError(t, err)
+
+ schemaB, err := getSyncMetadataForGenerateMigration(ctx, &testConnConfig, dbName)
+ require.NoError(t, err)
+
+ // Step 3: Call generate migration to get the rollback DDL
+ // Convert to model.DatabaseSchema
+ dbSchemaA := model.NewDatabaseSchema(schemaA, nil, nil, storepb.Engine_POSTGRES, false)
+ dbSchemaB := model.NewDatabaseSchema(schemaB, nil, nil, storepb.Engine_POSTGRES, false)
+
+ // Get diff from B to A (to generate rollback)
+ diff, err := schema.GetDatabaseSchemaDiff(dbSchemaB, dbSchemaA)
+ require.NoError(t, err)
+
+ // Log the diff for debugging
+ t.Logf("Test case: %s", tc.description)
+ t.Logf("Schema changes: %d", len(diff.SchemaChanges))
+ for _, sc := range diff.SchemaChanges {
+ t.Logf(" Schema: %s, Action: %v", sc.SchemaName, sc.Action)
+ }
+ t.Logf("Table changes: %d", len(diff.TableChanges))
+ for _, tc := range diff.TableChanges {
+ t.Logf(" Table: %s.%s, Action: %v", tc.SchemaName, tc.TableName, tc.Action)
+ }
+ t.Logf("Sequence changes: %d", len(diff.SequenceChanges))
+ for _, sc := range diff.SequenceChanges {
+ t.Logf(" Sequence: %s.%s, Action: %v", sc.SchemaName, sc.SequenceName, sc.Action)
+ }
+
+ // Log schema changes for debugging
+ if diff.SchemaChanges != nil {
+ for _, schemaDiff := range diff.SchemaChanges {
+ t.Logf("Schema diff: %s, Action: %v", schemaDiff.SchemaName, schemaDiff.Action)
+ if schemaDiff.OldSchema != nil {
+ t.Logf(" Old schema %s enum types: %d", schemaDiff.SchemaName, len(schemaDiff.OldSchema.EnumTypes))
+ for _, enum := range schemaDiff.OldSchema.EnumTypes {
+ t.Logf(" Old Enum: %s.%s", schemaDiff.SchemaName, enum.Name)
+ }
+ }
+ if schemaDiff.NewSchema != nil {
+ t.Logf(" New schema %s enum types: %d", schemaDiff.SchemaName, len(schemaDiff.NewSchema.EnumTypes))
+ for _, enum := range schemaDiff.NewSchema.EnumTypes {
+ t.Logf(" New Enum: %s.%s", schemaDiff.SchemaName, enum.Name)
+ }
+ }
+ }
+ }
+
+ // Generate rollback migration
+ rollbackDDL, err := schema.GenerateMigration(storepb.Engine_POSTGRES, diff)
+ require.NoError(t, err)
+
+ t.Logf("Rollback DDL:\n%s", rollbackDDL)
+
+ // Step 4: Run rollback DDL and get schema result C
+ _, err = testDB.Exec(rollbackDDL)
+ require.NoError(t, err)
+
+ schemaC, err := getSyncMetadataForGenerateMigration(ctx, &testConnConfig, dbName)
+ require.NoError(t, err)
+
+ // Step 5: Compare schema result A and C to ensure they are the same
+ normalizeMetadataForComparison(schemaA)
+ normalizeMetadataForComparison(schemaC)
+
+ // Use cmp with protocmp for proto message comparison
+ if diff := cmp.Diff(schemaA, schemaC, protocmp.Transform()); diff != "" {
+ t.Errorf("Schema mismatch after rollback (-want +got):\n%s", diff)
+ }
+ })
+ }
+}
+
+// getSyncMetadataForGenerateMigration retrieves metadata from the live database using Driver.SyncDBSchema
+func getSyncMetadataForGenerateMigration(ctx context.Context, connConfig *pgx.ConnConfig, dbName string) (*storepb.DatabaseSchemaMetadata, error) {
+ // Create a driver instance using the pg package
+ driver := &pgdb.Driver{}
+
+ // Create connection config
+ config := db.ConnectionConfig{
+ DataSource: &storepb.DataSource{
+ Type: storepb.DataSourceType_ADMIN,
+ Username: connConfig.User,
+ Host: connConfig.Host,
+ Port: fmt.Sprintf("%d", connConfig.Port),
+ Database: dbName,
+ },
+ Password: connConfig.Password,
+ ConnectionContext: db.ConnectionContext{
+ EngineVersion: "16.0", // PostgreSQL 16
+ DatabaseName: dbName,
+ },
+ }
+
+ // Open connection using the driver
+ openedDriver, err := driver.Open(ctx, storepb.Engine_POSTGRES, config)
+ if err != nil {
+ return nil, err
+ }
+ defer openedDriver.Close(ctx)
+
+ // Use SyncDBSchema to get the metadata
+ pgDriver, ok := openedDriver.(*pgdb.Driver)
+ if !ok {
+ return nil, errors.New("failed to cast to pg.Driver")
+ }
+
+ metadata, err := pgDriver.SyncDBSchema(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ return metadata, nil
+}
+
+// normalizeMetadataForComparison normalizes metadata to ignore differences that don't affect schema equality
+func normalizeMetadataForComparison(metadata *storepb.DatabaseSchemaMetadata) {
+ // Clear database name as it might differ
+ metadata.Name = ""
+
+ // Normalize schemas
+ for _, schema := range metadata.Schemas {
+ // Clear volatile fields (schemas don't have CreateTime/UpdateTime)
+
+ // Normalize tables
+ for _, table := range schema.Tables {
+ table.DataSize = 0
+ table.IndexSize = 0
+ table.RowCount = 0
+
+ // Sort columns by name for consistent comparison
+ sortColumnsByName(table.Columns)
+
+ // Sort indexes by name
+ sortIndexesByName(table.Indexes)
+
+ // Sort foreign keys by name
+ sortForeignKeysByName(table.ForeignKeys)
+
+ // Sort check constraints by name
+ sortCheckConstraintsByName(table.CheckConstraints)
+ }
+
+ // Normalize views (no volatile fields to clear)
+
+ // Normalize materialized views (no volatile fields to clear)
+
+ // Normalize functions (no volatile fields to clear)
+
+ // Normalize sequences (no volatile fields to clear)
+
+ // Sort all collections for consistent comparison
+ sortTablesByName(schema.Tables)
+ sortViewsByName(schema.Views)
+ sortMaterializedViewsByName(schema.MaterializedViews)
+ sortFunctionsByName(schema.Functions)
+ sortSequencesByName(schema.Sequences)
+ sortEnumsByName(schema.EnumTypes)
+ }
+
+ // Sort schemas by name
+ sortSchemasByName(metadata.Schemas)
+
+ // Sort extensions by name
+ sortExtensionsByName(metadata.Extensions)
+}
+
+// Sorting helper functions
+func sortSchemasByName(schemas []*storepb.SchemaMetadata) {
+ slices.SortFunc(schemas, func(a, b *storepb.SchemaMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortTablesByName(tables []*storepb.TableMetadata) {
+ slices.SortFunc(tables, func(a, b *storepb.TableMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortColumnsByName(columns []*storepb.ColumnMetadata) {
+ slices.SortFunc(columns, func(a, b *storepb.ColumnMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortIndexesByName(indexes []*storepb.IndexMetadata) {
+ slices.SortFunc(indexes, func(a, b *storepb.IndexMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortForeignKeysByName(fks []*storepb.ForeignKeyMetadata) {
+ slices.SortFunc(fks, func(a, b *storepb.ForeignKeyMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortCheckConstraintsByName(checks []*storepb.CheckConstraintMetadata) {
+ slices.SortFunc(checks, func(a, b *storepb.CheckConstraintMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortViewsByName(views []*storepb.ViewMetadata) {
+ slices.SortFunc(views, func(a, b *storepb.ViewMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortMaterializedViewsByName(mvs []*storepb.MaterializedViewMetadata) {
+ slices.SortFunc(mvs, func(a, b *storepb.MaterializedViewMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortFunctionsByName(functions []*storepb.FunctionMetadata) {
+ slices.SortFunc(functions, func(a, b *storepb.FunctionMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortSequencesByName(sequences []*storepb.SequenceMetadata) {
+ slices.SortFunc(sequences, func(a, b *storepb.SequenceMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortEnumsByName(enums []*storepb.EnumTypeMetadata) {
+ slices.SortFunc(enums, func(a, b *storepb.EnumTypeMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}
+
+func sortExtensionsByName(extensions []*storepb.ExtensionMetadata) {
+ slices.SortFunc(extensions, func(a, b *storepb.ExtensionMetadata) int {
+ return strings.Compare(a.Name, b.Name)
+ })
+}