Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: fix topo order for pg and oracle and use stable order for differ (#17297)
rebelice3bd59ab2e2cf
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex efdc3b90a8..b28202ab39 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -1,6 +1,7 @@package schemaimport (+ "slices""strings""github.com/bytebase/bytebase/backend/common"@@ -247,6 +248,9 @@ func GetDatabaseSchemaDiff(engine storepb.Engine, oldSchema, newSchema *model.Da}}+ // Sort all diff lists to ensure stable output order+ sortDiffLists(diff)+return diff, nil}@@ -1986,3 +1990,254 @@ func procedureDefinitionsEqual(def1, def2, _ string) bool {// For other engines, fall back to simple comparisonreturn false}++// sortDiffLists sorts all diff lists to ensure stable output order+func sortDiffLists(diff *MetadataDiff) {+ // Sort schema changes by schema name+ slices.SortFunc(diff.SchemaChanges, func(a, b *SchemaDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort table changes by schema name, then table name, then action+ slices.SortFunc(diff.TableChanges, func(a, b *TableDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.TableName != b.TableName {+ return strings.Compare(a.TableName, b.TableName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort view changes by schema name, then view name, then action+ slices.SortFunc(diff.ViewChanges, func(a, b *ViewDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.ViewName != b.ViewName {+ return strings.Compare(a.ViewName, b.ViewName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort materialized view changes by schema name, then view name, then action+ slices.SortFunc(diff.MaterializedViewChanges, func(a, b *MaterializedViewDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.MaterializedViewName != b.MaterializedViewName {+ return strings.Compare(a.MaterializedViewName, b.MaterializedViewName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort function changes by schema name, then function name, then action+ slices.SortFunc(diff.FunctionChanges, func(a, b *FunctionDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.FunctionName != b.FunctionName {+ return strings.Compare(a.FunctionName, b.FunctionName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort procedure changes by schema name, then procedure name, then action+ slices.SortFunc(diff.ProcedureChanges, func(a, b *ProcedureDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.ProcedureName != b.ProcedureName {+ return strings.Compare(a.ProcedureName, b.ProcedureName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort sequence changes by schema name, then sequence name, then action+ slices.SortFunc(diff.SequenceChanges, func(a, b *SequenceDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.SequenceName != b.SequenceName {+ return strings.Compare(a.SequenceName, b.SequenceName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort enum type changes by schema name, then enum name, then action+ slices.SortFunc(diff.EnumTypeChanges, func(a, b *EnumTypeDiff) int {+ if a.SchemaName != b.SchemaName {+ return strings.Compare(a.SchemaName, b.SchemaName)+ }+ if a.EnumTypeName != b.EnumTypeName {+ return strings.Compare(a.EnumTypeName, b.EnumTypeName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort event changes by event name, then action+ slices.SortFunc(diff.EventChanges, func(a, b *EventDiff) int {+ if a.EventName != b.EventName {+ return strings.Compare(a.EventName, b.EventName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort sub-object changes within table diffs+ for _, tableDiff := range diff.TableChanges {+ sortTableSubObjectChanges(tableDiff)+ }+}++// sortTableSubObjectChanges sorts the changes within a table diff+func sortTableSubObjectChanges(tableDiff *TableDiff) {+ // Sort column changes by column position (for MySQL/Oracle), then by name (for PostgreSQL/MSSQL), then action+ // This provides stable sorting across different database engines+ slices.SortFunc(tableDiff.ColumnChanges, func(a, b *ColumnDiff) int {+ aPos := int32(0)+ aName := ""+ if a.NewColumn != nil {+ aPos = a.NewColumn.Position+ aName = a.NewColumn.Name+ } else if a.OldColumn != nil {+ aPos = a.OldColumn.Position+ aName = a.OldColumn.Name+ }++ bPos := int32(0)+ bName := ""+ if b.NewColumn != nil {+ bPos = b.NewColumn.Position+ bName = b.NewColumn.Name+ } else if b.OldColumn != nil {+ bPos = b.OldColumn.Position+ bName = b.OldColumn.Name+ }++ // First, sort by position if both positions are valid (> 0)+ if aPos > 0 && bPos > 0 && aPos != bPos {+ return int(aPos - bPos)+ }++ // If positions are not available or equal, sort by column name+ if aName != bName {+ return strings.Compare(aName, bName)+ }++ // Finally, sort by action for stable sorting+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort index changes by index name, then action+ slices.SortFunc(tableDiff.IndexChanges, func(a, b *IndexDiff) int {+ aName := ""+ if a.NewIndex != nil {+ aName = a.NewIndex.Name+ } else if a.OldIndex != nil {+ aName = a.OldIndex.Name+ }++ bName := ""+ if b.NewIndex != nil {+ bName = b.NewIndex.Name+ } else if b.OldIndex != nil {+ bName = b.OldIndex.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort foreign key changes by foreign key name, then action+ slices.SortFunc(tableDiff.ForeignKeyChanges, func(a, b *ForeignKeyDiff) int {+ aName := ""+ if a.NewForeignKey != nil {+ aName = a.NewForeignKey.Name+ } else if a.OldForeignKey != nil {+ aName = a.OldForeignKey.Name+ }++ bName := ""+ if b.NewForeignKey != nil {+ bName = b.NewForeignKey.Name+ } else if b.OldForeignKey != nil {+ bName = b.OldForeignKey.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort check constraint changes by constraint name, then action+ slices.SortFunc(tableDiff.CheckConstraintChanges, func(a, b *CheckConstraintDiff) int {+ aName := ""+ if a.NewCheckConstraint != nil {+ aName = a.NewCheckConstraint.Name+ } else if a.OldCheckConstraint != nil {+ aName = a.OldCheckConstraint.Name+ }++ bName := ""+ if b.NewCheckConstraint != nil {+ bName = b.NewCheckConstraint.Name+ } else if b.OldCheckConstraint != nil {+ bName = b.OldCheckConstraint.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort partition changes by partition name, then action+ slices.SortFunc(tableDiff.PartitionChanges, func(a, b *PartitionDiff) int {+ aName := ""+ if a.NewPartition != nil {+ aName = a.NewPartition.Name+ } else if a.OldPartition != nil {+ aName = a.OldPartition.Name+ }++ bName := ""+ if b.NewPartition != nil {+ bName = b.NewPartition.Name+ } else if b.OldPartition != nil {+ bName = b.OldPartition.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort trigger changes by trigger name, then action+ slices.SortFunc(tableDiff.TriggerChanges, func(a, b *TriggerDiff) int {+ aName := ""+ if a.NewTrigger != nil {+ aName = a.NewTrigger.Name+ } else if a.OldTrigger != nil {+ aName = a.OldTrigger.Name+ }++ bName := ""+ if b.NewTrigger != nil {+ bName = b.NewTrigger.Name+ } else if b.OldTrigger != nil {+ bName = b.OldTrigger.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })+}diff --git a/backend/plugin/schema/oracle/generate_migration.go b/backend/plugin/schema/oracle/generate_migration.goindex bbdfe2ed01..2912cfc999 100644--- a/backend/plugin/schema/oracle/generate_migration.go+++ b/backend/plugin/schema/oracle/generate_migration.go@@ -434,9 +434,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {// Track all object IDs for dependency resolutionallObjects := make(map[string]bool)- // Add tables to graph+ // Add tables to graph (both CREATE and ALTER for column additions)for _, tableDiff := range diff.TableChanges {- if tableDiff.Action == schema.MetadataDiffActionCreate {+ if tableDiff.Action == schema.MetadataDiffActionCreate || tableDiff.Action == schema.MetadataDiffActionAlter {tableID := getMigrationObjectID(tableDiff.SchemaName, tableDiff.TableName)graph.AddNode(tableID)tableMap[tableID] = tableDiff@@ -485,9 +485,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {}// Add dependency edges- // For tables with foreign keys depending on other tables+ // For tables with foreign keys depending on other tables (only for CREATE operations)for tableID, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, fk := range tableDiff.NewTable.ForeignKeys {depID := getMigrationObjectID(fk.ReferencedSchema, fk.ReferencedTable)if depID != tableID {@@ -553,24 +553,47 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {// 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+ if tableDiff.Action == schema.MetadataDiffActionCreate {+ createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable, false)+ if err != nil {+ return+ }+ _, _ = buf.WriteString(createTableSQL)+ if createTableSQL != "" {+ _, _ = buf.WriteString("\n")+ }}- _, _ = buf.WriteString(createTableSQL)- if createTableSQL != "" {- _, _ = buf.WriteString("\n")+ }++ // Handle column additions for ALTER operations (only columns in topological order)+ for _, tableDiff := range tableMap {+ if tableDiff.Action == schema.MetadataDiffActionAlter {+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionCreate {+ writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ }+ }}}// Create viewsfor _, viewDiff := range viewMap {- writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView)+ switch viewDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView)+ default:+ // No action needed+ }}// Create materialized viewsfor _, mvDiff := range materializedViewMap {- writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView)+ switch mvDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView)+ default:+ // No action needed+ }}// Create functions@@ -583,9 +606,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {writeProcedureDiff(buf, procDiff)}- // Add foreign keys+ // Add foreign keys (only for CREATE operations)for _, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, fk := range tableDiff.NewTable.ForeignKeys {writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk)}@@ -595,19 +618,41 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {// 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- }- _, _ = buf.WriteString(createTableSQL)- if createTableSQL != "" {- _, _ = buf.WriteString("\n")+ switch tableDiff.Action {+ case schema.MetadataDiffActionCreate:+ // Create table without foreign keys+ createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable, false)+ if err != nil {+ return+ }+ _, _ = buf.WriteString(createTableSQL)+ if createTableSQL != "" {+ _, _ = buf.WriteString("\n")+ }+ case schema.MetadataDiffActionAlter:+ // Handle column additions for ALTER operations (only columns in topological order)+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionCreate {+ writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ }+ }+ default:+ // No action needed}} else if viewDiff, ok := viewMap[objID]; ok {- writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView)+ switch viewDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView)+ default:+ // No action needed+ }} else if mvDiff, ok := materializedViewMap[objID]; ok {- writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView)+ switch mvDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView)+ default:+ // No action needed+ }} else if funcDiff, ok := functionMap[objID]; ok {writeFunctionDiff(buf, funcDiff)} else if procDiff, ok := procedureMap[objID]; ok {@@ -615,9 +660,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {}}- // Add foreign keys after all tables are created+ // Add foreign keys after all tables are created (only for CREATE operations)for _, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, fk := range tableDiff.NewTable.ForeignKeys {writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk)}@@ -625,13 +670,55 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {}}- // Handle ALTER table operations+ // Handle remaining ALTER table operations (not columns, which are handled in topological order)for _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionAlter {- alterTableSQL := generateAlterTable(tableDiff)- _, _ = buf.WriteString(alterTableSQL)- if alterTableSQL != "" {- _, _ = buf.WriteString("\n")+ // Skip column additions (already handled in topological order)+ // Handle other ALTER operations++ // Alter columns (type changes, nullability, etc.)+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionAlter {+ alterColSQL := generateAlterColumn(tableDiff.SchemaName, tableDiff.TableName, colDiff)+ _, _ = 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 {+ writeMigrationPrimaryKey(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)+ } else if indexDiff.NewIndex.Unique {+ writeMigrationUniqueKey(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)+ }+ } else {+ writeMigrationIndex(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)+ }+ }+ }++ // Add check constraints+ for _, checkDiff := range tableDiff.CheckConstraintChanges {+ if checkDiff.Action == schema.MetadataDiffActionCreate {+ writeAddCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.NewCheckConstraint)+ }+ }++ // Add foreign keys+ for _, fkDiff := range tableDiff.ForeignKeyChanges {+ if fkDiff.Action == schema.MetadataDiffActionCreate {+ writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.NewForeignKey)+ }+ }++ // Add triggers+ for _, triggerDiff := range tableDiff.TriggerChanges {+ if triggerDiff.Action == schema.MetadataDiffActionCreate {+ writeMigrationTrigger(buf, triggerDiff.NewTrigger)+ }}// Handle table comment changes@@ -704,64 +791,6 @@ func generateCreateTable(schemaName, tableName string, table *storepb.TableMetadreturn buf.String(), nil}-func generateAlterTable(tableDiff *schema.TableDiff) string {- var buf strings.Builder-- // Add columns first (other operations might depend on them)- for _, colDiff := range tableDiff.ColumnChanges {- if colDiff.Action == schema.MetadataDiffActionCreate {- writeAddColumn(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)- }- }-- // Alter columns- for _, colDiff := range tableDiff.ColumnChanges {- if colDiff.Action == schema.MetadataDiffActionAlter {- alterColSQL := generateAlterColumn(tableDiff.SchemaName, tableDiff.TableName, colDiff)- _, _ = 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 {- writeMigrationPrimaryKey(&buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)- } else if indexDiff.NewIndex.Unique {- writeMigrationUniqueKey(&buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)- }- } else {- writeMigrationIndex(&buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)- }- }- }-- // Add check constraints- for _, checkDiff := range tableDiff.CheckConstraintChanges {- if checkDiff.Action == schema.MetadataDiffActionCreate {- writeAddCheckConstraint(&buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.NewCheckConstraint)- }- }-- // Add foreign keys last (they depend on other tables/columns)- for _, fkDiff := range tableDiff.ForeignKeyChanges {- if fkDiff.Action == schema.MetadataDiffActionCreate {- writeMigrationForeignKey(&buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.NewForeignKey)- }- }-- // Add triggers- for _, triggerDiff := range tableDiff.TriggerChanges {- if triggerDiff.Action == schema.MetadataDiffActionCreate {- writeMigrationTrigger(&buf, triggerDiff.NewTrigger)- }- }-- return buf.String()-}-func generateAlterColumn(schemaName, tableName string, colDiff *schema.ColumnDiff) string {var buf strings.Builderdiff --git a/backend/plugin/schema/oracle/topological_order_test.go b/backend/plugin/schema/oracle/topological_order_test.gonew file mode 100644index 0000000000..1b25908de9--- /dev/null+++ b/backend/plugin/schema/oracle/topological_order_test.go@@ -0,0 +1,400 @@+package oracle++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+)++// TestTopologicalOrderCreateObjects tests that objects are created in the correct dependency order+func TestTopologicalOrderCreateObjects(t *testing.T) {+ tests := []struct {+ name string+ diff *schema.MetadataDiff+ description string+ }{+ {+ name: "table_depends_on_table_via_foreign_key",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ // Create orders table that depends on customers table via FK+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "ORDERS",+ NewTable: &storepb.TableMetadata{+ Name: "ORDERS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "CUSTOMER_ID", Type: "NUMBER", Nullable: false},+ },+ ForeignKeys: []*storepb.ForeignKeyMetadata{+ {+ Name: "FK_ORDERS_CUSTOMER",+ Columns: []string{"CUSTOMER_ID"},+ ReferencedSchema: "TESTUSER",+ ReferencedTable: "CUSTOMERS",+ ReferencedColumns: []string{"ID"},+ },+ },+ },+ },+ // Create customers table (should be created first)+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "CUSTOMERS",+ NewTable: &storepb.TableMetadata{+ Name: "CUSTOMERS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "NAME", Type: "VARCHAR2(100)", Nullable: false},+ },+ },+ },+ },+ },+ description: "Customers table should be created before orders table due to FK dependency",+ },+ {+ name: "view_depends_on_tables",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "USERS",+ NewTable: &storepb.TableMetadata{+ Name: "USERS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "NAME", Type: "VARCHAR2(100)", Nullable: false},+ },+ },+ },+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "ORDERS",+ NewTable: &storepb.TableMetadata{+ Name: "ORDERS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "USER_ID", Type: "NUMBER", Nullable: false},+ },+ },+ },+ },+ ViewChanges: []*schema.ViewDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ ViewName: "USER_ORDERS",+ NewView: &storepb.ViewMetadata{+ Name: "USER_ORDERS",+ Definition: "SELECT u.NAME, o.ID FROM USERS u JOIN ORDERS o ON u.ID = o.USER_ID",+ DependencyColumns: []*storepb.DependencyColumn{+ {Schema: "TESTUSER", Table: "USERS", Column: "ID"},+ {Schema: "TESTUSER", Table: "USERS", Column: "NAME"},+ {Schema: "TESTUSER", Table: "ORDERS", Column: "ID"},+ {Schema: "TESTUSER", Table: "ORDERS", Column: "USER_ID"},+ },+ },+ },+ },+ },+ description: "View should be created after tables it depends on",+ },+ {+ name: "column_addition_follows_table_dependency",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ // Add column to orders table+ {+ Action: schema.MetadataDiffActionAlter,+ SchemaName: "TESTUSER",+ TableName: "ORDERS",+ ColumnChanges: []*schema.ColumnDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ NewColumn: &storepb.ColumnMetadata{+ Name: "CUSTOMER_REF",+ Type: "NUMBER",+ Nullable: true,+ },+ },+ },+ },+ // Add column to customers table (should be added first in dependency order)+ {+ Action: schema.MetadataDiffActionAlter,+ SchemaName: "TESTUSER",+ TableName: "CUSTOMERS",+ ColumnChanges: []*schema.ColumnDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ NewColumn: &storepb.ColumnMetadata{+ Name: "STATUS",+ Type: "VARCHAR2(20)",+ Nullable: true,+ },+ },+ },+ },+ },+ },+ description: "Column additions should follow table topological order",+ },+ {+ name: "materialized_view_depends_on_view",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "PRODUCTS",+ NewTable: &storepb.TableMetadata{+ Name: "PRODUCTS",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "NAME", Type: "VARCHAR2(100)", Nullable: false},+ {Name: "PRICE", Type: "NUMBER(10,2)", Nullable: false},+ },+ },+ },+ },+ ViewChanges: []*schema.ViewDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ ViewName: "EXPENSIVE_PRODUCTS",+ NewView: &storepb.ViewMetadata{+ Name: "EXPENSIVE_PRODUCTS",+ Definition: "SELECT * FROM PRODUCTS WHERE PRICE > 100",+ DependencyColumns: []*storepb.DependencyColumn{+ {Schema: "TESTUSER", Table: "PRODUCTS", Column: "ID"},+ {Schema: "TESTUSER", Table: "PRODUCTS", Column: "NAME"},+ {Schema: "TESTUSER", Table: "PRODUCTS", Column: "PRICE"},+ },+ },+ },+ },+ MaterializedViewChanges: []*schema.MaterializedViewDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ MaterializedViewName: "EXPENSIVE_PRODUCTS_MV",+ NewMaterializedView: &storepb.MaterializedViewMetadata{+ Name: "EXPENSIVE_PRODUCTS_MV",+ Definition: "SELECT NAME FROM EXPENSIVE_PRODUCTS",+ DependencyColumns: []*storepb.DependencyColumn{+ {Schema: "TESTUSER", Table: "EXPENSIVE_PRODUCTS", Column: "NAME"},+ },+ },+ },+ },+ },+ description: "Materialized view should be created after view it depends on",+ },+ {+ name: "function_depends_on_table",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "EMPLOYEES",+ NewTable: &storepb.TableMetadata{+ Name: "EMPLOYEES",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "SALARY", Type: "NUMBER(10,2)", Nullable: false},+ },+ },+ },+ },+ FunctionChanges: []*schema.FunctionDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ FunctionName: "GET_AVG_SALARY",+ NewFunction: &storepb.FunctionMetadata{+ Name: "GET_AVG_SALARY",+ Definition: "CREATE OR REPLACE FUNCTION GET_AVG_SALARY RETURN NUMBER IS avg_sal NUMBER; BEGIN SELECT AVG(SALARY) INTO avg_sal FROM EMPLOYEES; RETURN avg_sal; END;",+ DependencyTables: []*storepb.DependencyTable{+ {Schema: "TESTUSER", Table: "EMPLOYEES"},+ },+ },+ },+ },+ },+ description: "Function should be created after table it depends on",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result, err := generateMigration(tt.diff)+ require.NoError(t, err, "Generate migration should not error")++ // Verify the SQL is not empty+ assert.NotEmpty(t, result, "Generated migration should not be empty")++ // Parse the generated SQL to check order+ statements := parseStatements(result)++ // Verify topological order based on test case+ switch tt.name {+ case "table_depends_on_table_via_foreign_key":+ // customers table should be created before orders table+ customersIndex := findStatementIndex(statements, "CREATE TABLE", "CUSTOMERS")+ ordersIndex := findStatementIndex(statements, "CREATE TABLE", "ORDERS")+ assert.True(t, customersIndex < ordersIndex,+ "Customers table should be created before orders table. Got statements: %v", statements)++ case "view_depends_on_tables":+ // Both tables should be created before the view+ usersIndex := findStatementIndex(statements, "CREATE TABLE", "USERS")+ ordersIndex := findStatementIndex(statements, "CREATE TABLE", "ORDERS")+ viewIndex := findStatementIndex(statements, "CREATE VIEW", "USER_ORDERS")+ assert.True(t, usersIndex < viewIndex && ordersIndex < viewIndex,+ "Tables should be created before view. Got statements: %v", statements)++ case "column_addition_follows_table_dependency":+ // Verify column additions are in the topological order+ customersAlterIndex := findStatementIndex(statements, "ALTER TABLE", "CUSTOMERS")+ ordersAlterIndex := findStatementIndex(statements, "ALTER TABLE", "ORDERS")+ // Both should exist+ assert.True(t, customersAlterIndex >= 0, "Customers ALTER should exist")+ assert.True(t, ordersAlterIndex >= 0, "Orders ALTER should exist")++ case "materialized_view_depends_on_view":+ // Table, then view, then materialized view+ tableIndex := findStatementIndex(statements, "CREATE TABLE", "PRODUCTS")+ viewIndex := findStatementIndex(statements, "CREATE VIEW", "EXPENSIVE_PRODUCTS")+ mvIndex := findStatementIndex(statements, "CREATE MATERIALIZED VIEW", "EXPENSIVE_PRODUCTS_MV")+ assert.True(t, tableIndex < viewIndex && viewIndex < mvIndex,+ "Objects should be created in dependency order: table -> view -> materialized view. Got statements: %v", statements)++ case "function_depends_on_table":+ // Table should be created before function+ tableIndex := findStatementIndex(statements, "CREATE TABLE", "EMPLOYEES")+ funcIndex := findStatementIndex(statements, "CREATE OR REPLACE FUNCTION", "GET_AVG_SALARY")+ if funcIndex == -1 {+ // Try alternative function creation pattern+ funcIndex = findStatementIndex(statements, "CREATE FUNCTION", "GET_AVG_SALARY")+ }+ assert.True(t, tableIndex < funcIndex,+ "Table should be created before function. Got statements: %v", statements)+ default:+ // No specific verification for this test case+ }+ })+ }+}++// TestTopologicalOrderWithCycles tests behavior when there are circular dependencies+func TestTopologicalOrderWithCycles(t *testing.T) {+ // Create a diff with circular dependency (should fall back to safe order)+ diff := &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "TABLE_A",+ NewTable: &storepb.TableMetadata{+ Name: "TABLE_A",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "B_ID", Type: "NUMBER", Nullable: true},+ },+ ForeignKeys: []*storepb.ForeignKeyMetadata{+ {+ Name: "FK_A_TO_B",+ Columns: []string{"B_ID"},+ ReferencedSchema: "TESTUSER",+ ReferencedTable: "TABLE_B",+ ReferencedColumns: []string{"ID"},+ },+ },+ },+ },+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "TESTUSER",+ TableName: "TABLE_B",+ NewTable: &storepb.TableMetadata{+ Name: "TABLE_B",+ Columns: []*storepb.ColumnMetadata{+ {Name: "ID", Type: "NUMBER", Nullable: false},+ {Name: "A_ID", Type: "NUMBER", Nullable: true},+ },+ ForeignKeys: []*storepb.ForeignKeyMetadata{+ {+ Name: "FK_B_TO_A",+ Columns: []string{"A_ID"},+ ReferencedSchema: "TESTUSER",+ ReferencedTable: "TABLE_A",+ ReferencedColumns: []string{"ID"},+ },+ },+ },+ },+ },+ }++ result, err := generateMigration(diff)+ require.NoError(t, err, "Generate migration should handle cycles gracefully")+ assert.NotEmpty(t, result, "Generated migration should not be empty even with cycles")++ // With cycles, it should fall back to creating tables without foreign keys first+ statements := parseStatements(result)++ // Both CREATE TABLE statements should exist+ tableAIndex := findStatementIndex(statements, "CREATE TABLE", "TABLE_A")+ tableBIndex := findStatementIndex(statements, "CREATE TABLE", "TABLE_B")+ assert.True(t, tableAIndex >= 0, "Table A should be created")+ assert.True(t, tableBIndex >= 0, "Table B should be created")++ // Foreign key constraints should be added later as separate ALTER TABLE statements+ fkCount := 0+ for _, stmt := range statements {+ if strings.Contains(strings.ToUpper(stmt), "ADD CONSTRAINT") && strings.Contains(strings.ToUpper(stmt), "FOREIGN KEY") {+ fkCount+++ }+ }+ assert.True(t, fkCount >= 2, "Both foreign keys should be added separately, found %d FK statements", fkCount)+}++// Helper function to parse SQL statements+func parseStatements(sql string) []string {+ var statements []string+ lines := strings.Split(sql, "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if line != "" && !strings.HasPrefix(line, "--") {+ statements = append(statements, line)+ }+ }+ return statements+}++// Helper function to find the index of a statement containing specific keywords+func findStatementIndex(statements []string, stmtType, objectName string) int {+ for i, stmt := range statements {+ upperStmt := strings.ToUpper(stmt)+ upperType := strings.ToUpper(stmtType)+ upperName := strings.ToUpper(objectName)++ if strings.Contains(upperStmt, upperType) && strings.Contains(upperStmt, upperName) {+ return i+ }+ }+ return -1+}diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.goindex cc154ee6a8..588407d7ce 100644--- a/backend/plugin/schema/pg/generate_migration.go+++ b/backend/plugin/schema/pg/generate_migration.go@@ -497,9 +497,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error// Track all object IDs for dependency resolutionallObjects := make(map[string]bool)- // Add tables to graph+ // Add tables to graph (both CREATE and ALTER for column additions)for _, tableDiff := range diff.TableChanges {- if tableDiff.Action == schema.MetadataDiffActionCreate {+ if tableDiff.Action == schema.MetadataDiffActionCreate || tableDiff.Action == schema.MetadataDiffActionAlter {tableID := getMigrationObjectID(tableDiff.SchemaName, tableDiff.TableName)graph.AddNode(tableID)tableMap[tableID] = tableDiff@@ -538,9 +538,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}// Add dependency edges- // For tables with foreign keys depending on other tables+ // For tables with foreign keys depending on other tables (only for CREATE operations)for tableID, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, fk := range tableDiff.NewTable.ForeignKeys {depID := getMigrationObjectID(fk.ReferencedSchema, fk.ReferencedTable)if depID != tableID {@@ -590,23 +590,36 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error// 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")- }+ if tableDiff.Action == schema.MetadataDiffActionCreate {+ createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable, false)+ if err != nil {+ return err+ }+ _, _ = buf.WriteString(createTableSQL)+ if createTableSQL != "" {+ _, _ = buf.WriteString("\n")+ }- // Add table and column comments for newly created tables- if tableDiff.NewTable != nil && tableDiff.NewTable.Comment != "" {- writeCommentOnTable(buf, tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable.Comment)+ // Add table and column comments for newly created tables+ if tableDiff.NewTable != nil && tableDiff.NewTable.Comment != "" {+ writeCommentOnTable(buf, tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable.Comment)+ }+ if tableDiff.NewTable != nil {+ for _, col := range tableDiff.NewTable.Columns {+ if col.Comment != "" {+ writeCommentOnColumn(buf, tableDiff.SchemaName, tableDiff.TableName, col.Name, col.Comment)+ }+ }+ }}- if tableDiff.NewTable != nil {- for _, col := range tableDiff.NewTable.Columns {- if col.Comment != "" {- writeCommentOnColumn(buf, tableDiff.SchemaName, tableDiff.TableName, col.Name, col.Comment)+ }++ // Handle column additions for ALTER operations (only columns in topological order)+ for _, tableDiff := range tableMap {+ if tableDiff.Action == schema.MetadataDiffActionAlter {+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionCreate {+ writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)}}}@@ -614,8 +627,13 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error// Create viewsfor _, viewDiff := range viewMap {- if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {- return err+ switch viewDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {+ return err+ }+ default:+ // No action needed}// Add view comment for newly created viewsif viewDiff.NewView != nil && viewDiff.NewView.Comment != "" {@@ -625,8 +643,13 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error// Create materialized viewsfor _, mvDiff := range materializedViewMap {- if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {- return err+ switch mvDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {+ return err+ }+ default:+ // No action needed}// Add materialized view comment for newly created materialized viewsif mvDiff.NewMaterializedView != nil && mvDiff.NewMaterializedView.Comment != "" {@@ -654,9 +677,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}- // Add foreign keys+ // Add foreign keys (only for CREATE table operations)for _, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, fk := range tableDiff.NewTable.ForeignKeys {if err := writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk); err != nil {return err@@ -665,71 +688,83 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}} else {- // First pass: Create tables and functions only+ // Follow topological order completely - create objects in dependency orderfor _, 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")- }+ switch tableDiff.Action {+ case schema.MetadataDiffActionCreate:+ // 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")+ }- // Add table and column comments for newly created tables- if tableDiff.NewTable != nil && tableDiff.NewTable.Comment != "" {- writeCommentOnTable(buf, tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable.Comment)- }- if tableDiff.NewTable != nil {- for _, col := range tableDiff.NewTable.Columns {- if col.Comment != "" {- writeCommentOnColumn(buf, tableDiff.SchemaName, tableDiff.TableName, col.Name, col.Comment)+ // Add table and column comments for newly created tables+ if tableDiff.NewTable != nil && tableDiff.NewTable.Comment != "" {+ writeCommentOnTable(buf, tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable.Comment)+ }+ if tableDiff.NewTable != nil {+ for _, col := range tableDiff.NewTable.Columns {+ if col.Comment != "" {+ writeCommentOnColumn(buf, tableDiff.SchemaName, tableDiff.TableName, col.Name, col.Comment)+ }}}- }- } else if funcDiff, ok := functionMap[objID]; ok {- if err := writeFunctionDiff(buf, funcDiff); err != nil {- return err- }- // Add function comment for newly created functions- if funcDiff.Action == schema.MetadataDiffActionCreate && funcDiff.NewFunction != nil && funcDiff.NewFunction.Comment != "" {- writeCommentOnFunction(buf, funcDiff.SchemaName, funcDiff.NewFunction.Signature, funcDiff.NewFunction.Comment)- }- }- }-- // Handle ALTER table operations that add columns (views might depend on these)- for _, tableDiff := range diff.TableChanges {- if tableDiff.Action == schema.MetadataDiffActionAlter {- // Only process column additions here- for _, colDiff := range tableDiff.ColumnChanges {- if colDiff.Action == schema.MetadataDiffActionCreate {- writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ case schema.MetadataDiffActionAlter:+ // Handle column additions for ALTER operations+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionCreate {+ writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ }}+ default:+ // No action needed for other operations}- }- }-- // Second pass: Create views and materialized views (after columns are added)- for _, objID := range orderedList {- if viewDiff, ok := viewMap[objID]; ok {- if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {- return err+ } else if viewDiff, ok := viewMap[objID]; ok {+ switch viewDiff.Action {+ case schema.MetadataDiffActionCreate, schema.MetadataDiffActionAlter:+ if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {+ return err+ }+ default:+ // No action needed for other operations}- // Add view comment for newly created views+ // Add view comment for newly created or altered viewsif viewDiff.NewView != nil && viewDiff.NewView.Comment != "" {writeCommentOnView(buf, viewDiff.SchemaName, viewDiff.ViewName, viewDiff.NewView.Comment)}} else if mvDiff, ok := materializedViewMap[objID]; ok {- if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {- return err+ switch mvDiff.Action {+ case schema.MetadataDiffActionCreate:+ if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {+ return err+ }+ case schema.MetadataDiffActionAlter:+ // For PostgreSQL materialized views, we need to drop and recreate+ // since ALTER MATERIALIZED VIEW doesn't support changing the definition+ writeDropMaterializedView(buf, mvDiff.SchemaName, mvDiff.MaterializedViewName)+ if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {+ return err+ }+ default:+ // No action needed for other operations}- // Add materialized view comment for newly created materialized views+ // Add materialized view comment for newly created or altered materialized viewsif mvDiff.NewMaterializedView != nil && mvDiff.NewMaterializedView.Comment != "" {writeCommentOnMaterializedView(buf, mvDiff.SchemaName, mvDiff.MaterializedViewName, mvDiff.NewMaterializedView.Comment)}+ } else if funcDiff, ok := functionMap[objID]; ok {+ if err := writeFunctionDiff(buf, funcDiff); err != nil {+ return err+ }+ // Add function comment for newly created or altered functions+ if (funcDiff.Action == schema.MetadataDiffActionCreate || funcDiff.Action == schema.MetadataDiffActionAlter) && funcDiff.NewFunction != nil && funcDiff.NewFunction.Comment != "" {+ writeCommentOnFunction(buf, funcDiff.SchemaName, funcDiff.NewFunction.Signature, funcDiff.NewFunction.Comment)+ }}}@@ -742,9 +777,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}- // Add foreign keys after all tables are created+ // Add foreign keys after all tables are created (only for CREATE table operations)for _, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, fk := range tableDiff.NewTable.ForeignKeys {if err := writeMigrationForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fk); err != nil {return err@@ -753,9 +788,9 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}- // Create triggers after foreign keys+ // Create triggers after foreign keys (only for CREATE table operations)for _, tableDiff := range tableMap {- if tableDiff.NewTable != nil {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {for _, trigger := range tableDiff.NewTable.Triggers {writeMigrationTrigger(buf, trigger)}diff --git a/backend/plugin/schema/pg/topological_order_test.go b/backend/plugin/schema/pg/topological_order_test.gonew file mode 100644index 0000000000..dbd0935102--- /dev/null+++ b/backend/plugin/schema/pg/topological_order_test.go@@ -0,0 +1,357 @@+package pg++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+)++// TestTopologicalOrderCreateObjects tests that objects are created in the correct dependency order+func TestTopologicalOrderCreateObjects(t *testing.T) {+ tests := []struct {+ name string+ diff *schema.MetadataDiff+ expectedSQL string+ description string+ }{+ {+ name: "table_depends_on_table_via_foreign_key",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ // Create orders table that depends on customers table via FK+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "orders",+ NewTable: &storepb.TableMetadata{+ Name: "orders",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "customer_id", Type: "INT", Nullable: false},+ },+ ForeignKeys: []*storepb.ForeignKeyMetadata{+ {+ Name: "fk_orders_customer",+ Columns: []string{"customer_id"},+ ReferencedSchema: "public",+ ReferencedTable: "customers",+ ReferencedColumns: []string{"id"},+ },+ },+ },+ },+ // Create customers table (should be created first)+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "customers",+ NewTable: &storepb.TableMetadata{+ Name: "customers",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "name", Type: "VARCHAR(100)", Nullable: false},+ },+ },+ },+ },+ },+ description: "Customers table should be created before orders table due to FK dependency",+ },+ {+ name: "view_depends_on_tables",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "users",+ NewTable: &storepb.TableMetadata{+ Name: "users",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "name", Type: "VARCHAR(100)", Nullable: false},+ },+ },+ },+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "orders",+ NewTable: &storepb.TableMetadata{+ Name: "orders",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "user_id", Type: "INT", Nullable: false},+ },+ },+ },+ },+ ViewChanges: []*schema.ViewDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ ViewName: "user_orders",+ NewView: &storepb.ViewMetadata{+ Name: "user_orders",+ Definition: "SELECT u.name, o.id FROM users u JOIN orders o ON u.id = o.user_id",+ DependencyColumns: []*storepb.DependencyColumn{+ {Schema: "public", Table: "users", Column: "id"},+ {Schema: "public", Table: "users", Column: "name"},+ {Schema: "public", Table: "orders", Column: "id"},+ {Schema: "public", Table: "orders", Column: "user_id"},+ },+ },+ },+ },+ },+ description: "View should be created after tables it depends on",+ },+ {+ name: "column_addition_follows_table_dependency",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ // Add column to orders table that references customers+ {+ Action: schema.MetadataDiffActionAlter,+ SchemaName: "public",+ TableName: "orders",+ ColumnChanges: []*schema.ColumnDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ NewColumn: &storepb.ColumnMetadata{+ Name: "customer_ref",+ Type: "INT",+ Nullable: true,+ },+ },+ },+ },+ // Add column to customers table (should be added first)+ {+ Action: schema.MetadataDiffActionAlter,+ SchemaName: "public",+ TableName: "customers",+ ColumnChanges: []*schema.ColumnDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ NewColumn: &storepb.ColumnMetadata{+ Name: "status",+ Type: "VARCHAR(20)",+ Nullable: true,+ },+ },+ },+ },+ },+ },+ description: "Column additions should follow table topological order",+ },+ {+ name: "materialized_view_depends_on_view",+ diff: &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "products",+ NewTable: &storepb.TableMetadata{+ Name: "products",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "name", Type: "VARCHAR(100)", Nullable: false},+ {Name: "price", Type: "DECIMAL(10,2)", Nullable: false},+ },+ },+ },+ },+ ViewChanges: []*schema.ViewDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ ViewName: "expensive_products",+ NewView: &storepb.ViewMetadata{+ Name: "expensive_products",+ Definition: "SELECT * FROM products WHERE price > 100",+ DependencyColumns: []*storepb.DependencyColumn{+ {Schema: "public", Table: "products", Column: "id"},+ {Schema: "public", Table: "products", Column: "name"},+ {Schema: "public", Table: "products", Column: "price"},+ },+ },+ },+ },+ MaterializedViewChanges: []*schema.MaterializedViewDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ MaterializedViewName: "expensive_products_mv",+ NewMaterializedView: &storepb.MaterializedViewMetadata{+ Name: "expensive_products_mv",+ Definition: "SELECT name FROM expensive_products",+ DependencyColumns: []*storepb.DependencyColumn{+ {Schema: "public", Table: "expensive_products", Column: "name"},+ },+ },+ },+ },+ },+ description: "Materialized view should be created after view it depends on",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result, err := generateMigration(tt.diff)+ require.NoError(t, err, "Generate migration should not error")++ // Verify the SQL is not empty+ assert.NotEmpty(t, result, "Generated migration should not be empty")++ // Parse the generated SQL to check order+ statements := parseStatements(result)++ // Verify topological order based on test case+ switch tt.name {+ case "table_depends_on_table_via_foreign_key":+ // customers table should be created before orders table+ customersIndex := findStatementIndex(statements, "CREATE TABLE", "customers")+ ordersIndex := findStatementIndex(statements, "CREATE TABLE", "orders")+ assert.True(t, customersIndex < ordersIndex,+ "Customers table should be created before orders table. Got statements: %v", statements)++ case "view_depends_on_tables":+ // Both tables should be created before the view+ usersIndex := findStatementIndex(statements, "CREATE TABLE", "users")+ ordersIndex := findStatementIndex(statements, "CREATE TABLE", "orders")+ viewIndex := findStatementIndex(statements, "CREATE VIEW", "user_orders")+ assert.True(t, usersIndex < viewIndex && ordersIndex < viewIndex,+ "Tables should be created before view. Got statements: %v", statements)++ case "column_addition_follows_table_dependency":+ // Verify column additions are in the right order+ // This is more complex as we need to check ALTER TABLE statements+ customersAlterIndex := findStatementIndex(statements, "ALTER TABLE", "customers")+ ordersAlterIndex := findStatementIndex(statements, "ALTER TABLE", "orders")+ // Both should exist, actual order depends on topological sorting+ assert.True(t, customersAlterIndex >= 0, "Customers ALTER should exist")+ assert.True(t, ordersAlterIndex >= 0, "Orders ALTER should exist")++ case "materialized_view_depends_on_view":+ // Table, then view, then materialized view+ tableIndex := findStatementIndex(statements, "CREATE TABLE", "products")+ viewIndex := findStatementIndex(statements, "CREATE VIEW", "expensive_products")+ mvIndex := findStatementIndex(statements, "CREATE MATERIALIZED VIEW", "expensive_products_mv")+ assert.True(t, tableIndex < viewIndex && viewIndex < mvIndex,+ "Objects should be created in dependency order: table -> view -> materialized view. Got statements: %v", statements)+ default:+ // No specific verification for this test case+ }+ })+ }+}++// TestTopologicalOrderWithCycles tests behavior when there are circular dependencies+func TestTopologicalOrderWithCycles(t *testing.T) {+ // Create a diff with circular dependency (should fall back to safe order)+ diff := &schema.MetadataDiff{+ TableChanges: []*schema.TableDiff{+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "table_a",+ NewTable: &storepb.TableMetadata{+ Name: "table_a",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "b_id", Type: "INT", Nullable: true},+ },+ ForeignKeys: []*storepb.ForeignKeyMetadata{+ {+ Name: "fk_a_to_b",+ Columns: []string{"b_id"},+ ReferencedSchema: "public",+ ReferencedTable: "table_b",+ ReferencedColumns: []string{"id"},+ },+ },+ },+ },+ {+ Action: schema.MetadataDiffActionCreate,+ SchemaName: "public",+ TableName: "table_b",+ NewTable: &storepb.TableMetadata{+ Name: "table_b",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "SERIAL", Nullable: false},+ {Name: "a_id", Type: "INT", Nullable: true},+ },+ ForeignKeys: []*storepb.ForeignKeyMetadata{+ {+ Name: "fk_b_to_a",+ Columns: []string{"a_id"},+ ReferencedSchema: "public",+ ReferencedTable: "table_a",+ ReferencedColumns: []string{"id"},+ },+ },+ },+ },+ },+ }++ result, err := generateMigration(diff)+ require.NoError(t, err, "Generate migration should handle cycles gracefully")+ assert.NotEmpty(t, result, "Generated migration should not be empty even with cycles")++ // With cycles, it should fall back to creating tables without foreign keys first+ statements := parseStatements(result)++ // Both CREATE TABLE statements should exist+ tableAIndex := findStatementIndex(statements, "CREATE TABLE", "table_a")+ tableBIndex := findStatementIndex(statements, "CREATE TABLE", "table_b")+ assert.True(t, tableAIndex >= 0, "Table A should be created")+ assert.True(t, tableBIndex >= 0, "Table B should be created")++ // Foreign key constraints should be added later+ fkCount := 0+ for _, stmt := range statements {+ if strings.Contains(stmt, "ADD CONSTRAINT") && strings.Contains(stmt, "FOREIGN KEY") {+ fkCount+++ }+ }+ assert.Equal(t, 2, fkCount, "Both foreign keys should be added separately")+}++// Helper function to parse SQL statements+func parseStatements(sql string) []string {+ var statements []string+ lines := strings.Split(sql, "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if line != "" && !strings.HasPrefix(line, "--") {+ statements = append(statements, line)+ }+ }+ return statements+}++// Helper function to find the index of a statement containing specific keywords+func findStatementIndex(statements []string, stmtType, objectName string) int {+ for i, stmt := range statements {+ upperStmt := strings.ToUpper(stmt)+ upperType := strings.ToUpper(stmtType)+ upperName := strings.ToUpper(objectName)++ if strings.Contains(upperStmt, upperType) && strings.Contains(upperStmt, upperName) {+ return i+ }+ }+ return -1+}