MCPcopy Create free account
hub / github.com/bytebase/bytebase / dropViewsInOrder

Function dropViewsInOrder

backend/plugin/schema/mssql/generate_migration.go:1174–1269  ·  view source on GitHub ↗

dropViewsInOrder drops views in reverse topological order (dependent views first)

(diff *schema.MetadataDiff, buf *strings.Builder)

Source from the content-addressed store, hash-verified

1172
1173// dropViewsInOrder drops views in reverse topological order (dependent views first)
1174func dropViewsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
1175 // Build dependency graph for views being dropped or altered
1176 graph := base.NewGraph()
1177 viewMap := make(map[string]*schema.ViewDiff)
1178
1179 // First pass: Add all views to be dropped or altered to the graph and viewMap
1180 // Sort for deterministic processing order
1181 var viewsToProcess []*schema.ViewDiff
1182 for _, viewDiff := range diff.ViewChanges {
1183 if viewDiff.Action == schema.MetadataDiffActionDrop || viewDiff.Action == schema.MetadataDiffActionAlter {
1184 viewsToProcess = append(viewsToProcess, viewDiff)
1185 }
1186 }
1187 slices.SortFunc(viewsToProcess, func(i, j *schema.ViewDiff) int {
1188 iFullName := getObjectID(i.SchemaName, i.ViewName)
1189 jFullName := getObjectID(j.SchemaName, j.ViewName)
1190 if iFullName < jFullName {
1191 return -1
1192 }
1193 if iFullName > jFullName {
1194 return 1
1195 }
1196 return 0
1197 })
1198
1199 for _, viewDiff := range viewsToProcess {
1200 viewID := getObjectID(viewDiff.SchemaName, viewDiff.ViewName)
1201 graph.AddNode(viewID)
1202 viewMap[viewID] = viewDiff
1203 }
1204
1205 // Second pass: Add dependency edges now that all views are in viewMap
1206 for _, viewDiff := range viewsToProcess {
1207 viewID := getObjectID(viewDiff.SchemaName, viewDiff.ViewName)
1208
1209 // Get dependencies from the old view definition
1210 if viewDiff.OldView != nil && viewDiff.OldView.Definition != "" {
1211 deps, err := getViewDependencies(viewDiff.OldView.Definition, viewDiff.SchemaName)
1212 if err != nil {
1213 // If we can't parse dependencies, we'll just drop in original order
1214 continue
1215 }
1216
1217 // Add edges from this view to its dependencies
1218 for _, dep := range deps {
1219 // Only add edge if the dependency is also being dropped/altered
1220 if _, exists := viewMap[dep]; exists {
1221 graph.AddEdge(viewID, dep)
1222 }
1223 }
1224 }
1225 }
1226
1227 // Get topological order
1228 orderedList, err := graph.TopologicalSort()
1229 if err != nil {
1230 // If there's a cycle or error, fall back to original order
1231 var fallbackViews []*schema.ViewDiff

Callers 1

generateMigrationFunction · 0.85

Calls 6

AddNodeMethod · 0.95
AddEdgeMethod · 0.95
TopologicalSortMethod · 0.95
NewGraphFunction · 0.92
getObjectIDFunction · 0.70
getViewDependenciesFunction · 0.70

Tested by

no test coverage detected