Skip to content

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

feat: view safe order with topo sort for sql server (#16436)

rebelice696df740d20a
diff --git a/backend/plugin/schema/mssql/generate_migration.go b/backend/plugin/schema/mssql/generate_migration.go
index 058e1c339a..e7b56b1dea 100644
--- a/backend/plugin/schema/mssql/generate_migration.go
+++ b/backend/plugin/schema/mssql/generate_migration.go
@@ -1,10 +1,19 @@
package mssql
import (
+ "context"
"fmt"
+ "sort"
"strings"
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/tsql-parser"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
"github.com/bytebase/bytebase/backend/plugin/schema"
+ "github.com/bytebase/bytebase/backend/store/model"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -15,11 +24,23 @@ func init() {
func generateMigration(diff *schema.MetadataDiff) (string, error) {
var buf strings.Builder
+ // Collect schemas to create first (needed for checking if create phase will have content)
+ var schemasToCreate []string
+ for _, schemaDiff := range diff.SchemaChanges {
+ if schemaDiff.Action == schema.MetadataDiffActionCreate {
+ // Skip creating dbo schema as it already exists by default
+ if strings.ToLower(schemaDiff.SchemaName) != "dbo" {
+ schemasToCreate = append(schemasToCreate, schemaDiff.SchemaName)
+ }
+ }
+ }
+ sort.Strings(schemasToCreate)
+
// Safe order for migrations:
// 1. Drop dependent objects first (in reverse dependency order)
// - Drop foreign keys
// - Drop indexes
- // - Drop views (might depend on tables/columns)
+ // - Drop views (in reverse topological order)
// - Drop functions/procedures (might depend on tables)
// - Drop tables
// - Drop schemas
@@ -28,7 +49,7 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {
// - Create/Alter tables and columns
// - Create indexes
// - Create foreign keys
- // - Create views
+ // - Create views (in topological order)
// - Create functions/procedures
// Phase 1: Drop dependent objects
@@ -83,15 +104,9 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {
}
}
- // 1.4 Drop views (might depend on tables/columns)
- for _, viewDiff := range diff.ViewChanges {
- if viewDiff.Action == schema.MetadataDiffActionDrop {
- _, _ = buf.WriteString("DROP VIEW [")
- _, _ = buf.WriteString(viewDiff.SchemaName)
- _, _ = buf.WriteString("].[")
- _, _ = buf.WriteString(viewDiff.ViewName)
- _, _ = buf.WriteString("];\nGO\n")
- }
+ // 1.4 Drop views in reverse topological order (dependent views first)
+ if err := dropViewsInOrder(diff, &buf); err != nil {
+ return "", err
}
// 1.5 Drop indexes and constraints from tables being altered
@@ -172,47 +187,51 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {
}
}
- // Add blank line between drop and create phases if we had any drops
- if buf.Len() > 0 {
+ // Only add blank line if we have drops AND we're about to create something
+ dropPhaseHasContent := buf.Len() > 0
+ createPhaseWillHaveContent := len(schemasToCreate) > 0 ||
+ hasCreateOrAlterTables(diff) ||
+ hasCreateViews(diff) ||
+ hasCreateFunctions(diff) ||
+ hasCreateProcedures(diff)
+
+ if dropPhaseHasContent && createPhaseWillHaveContent {
_, _ = buf.WriteString("\n")
}
// Phase 2: Create/Alter objects
- // 2.1 Create schemas first
- for _, schemaDiff := range diff.SchemaChanges {
- if schemaDiff.Action == schema.MetadataDiffActionCreate {
- // Skip creating dbo schema as it already exists by default
- if strings.ToLower(schemaDiff.SchemaName) == "dbo" {
- continue
- }
- _, _ = buf.WriteString("CREATE SCHEMA [")
- _, _ = buf.WriteString(schemaDiff.SchemaName)
- _, _ = buf.WriteString("];\nGO\n")
- }
+ // 2.1 Create schemas first (already sorted)
+ for _, schemaName := range schemasToCreate {
+ _, _ = buf.WriteString("CREATE SCHEMA [")
+ _, _ = buf.WriteString(schemaName)
+ _, _ = buf.WriteString("];\nGO\n")
}
- // Add blank line after schema creation if any
- schemasCreated := false
- for _, schemaDiff := range diff.SchemaChanges {
- if schemaDiff.Action == schema.MetadataDiffActionCreate && strings.ToLower(schemaDiff.SchemaName) != "dbo" {
- schemasCreated = true
- break
- }
- }
- if schemasCreated {
+ // Add blank line after schema creation only if we have schemas and more content follows
+ if len(schemasToCreate) > 0 && (hasCreateOrAlterTables(diff) || hasCreateViews(diff) || hasCreateFunctions(diff) || hasCreateProcedures(diff)) {
_, _ = buf.WriteString("\n")
}
- // 2.2 Create new tables
+ // 2.2 Create new tables WITHOUT foreign keys (sorted for consistent output)
+ var tablesToCreate []*schema.TableDiff
for _, tableDiff := range diff.TableChanges {
if tableDiff.Action == schema.MetadataDiffActionCreate {
- createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable)
- if err != nil {
- return "", err
- }
- _, _ = buf.WriteString(createTableSQL)
- _, _ = buf.WriteString("\n")
+ tablesToCreate = append(tablesToCreate, tableDiff)
+ }
+ }
+ // Sort by schema.table name for consistent output
+ sort.Slice(tablesToCreate, func(i, j int) bool {
+ iFullName := getObjectID(tablesToCreate[i].SchemaName, tablesToCreate[i].TableName)
+ jFullName := getObjectID(tablesToCreate[j].SchemaName, tablesToCreate[j].TableName)
+ return iFullName < jFullName
+ })
+ for _, tableDiff := range tablesToCreate {
+ createTableSQL, err := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable)
+ if err != nil {
+ return "", err
}
+ _, _ = buf.WriteString(createTableSQL)
+ _, _ = buf.WriteString("\n")
}
// 2.3 Alter existing tables (add columns, alter columns)
@@ -223,33 +242,35 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {
return "", err
}
_, _ = buf.WriteString(alterTableSQL)
+ if alterTableSQL != "" {
+ _, _ = buf.WriteString("\n")
+ }
}
}
- // 2.4 Create views (after tables are ready)
- for _, viewDiff := range diff.ViewChanges {
- switch viewDiff.Action {
- case schema.MetadataDiffActionCreate:
- _, _ = buf.WriteString(viewDiff.NewView.Definition)
- if !strings.HasSuffix(strings.TrimSpace(viewDiff.NewView.Definition), ";") {
- _, _ = buf.WriteString(";")
- }
- _, _ = buf.WriteString("\nGO\n")
- case schema.MetadataDiffActionAlter:
- // MSSQL requires dropping and recreating views
- _, _ = buf.WriteString("DROP VIEW [")
- _, _ = buf.WriteString(viewDiff.SchemaName)
- _, _ = buf.WriteString("].[")
- _, _ = buf.WriteString(viewDiff.ViewName)
- _, _ = buf.WriteString("];\nGO\n")
- _, _ = buf.WriteString(viewDiff.NewView.Definition)
- if !strings.HasSuffix(strings.TrimSpace(viewDiff.NewView.Definition), ";") {
- _, _ = buf.WriteString(";")
+ // 2.4 Add foreign keys for newly created tables (after all tables exist)
+ for _, tableDiff := range tablesToCreate {
+ for _, fk := range tableDiff.NewTable.ForeignKeys {
+ fkSQL, err := generateAddForeignKey(tableDiff.SchemaName, tableDiff.TableName, fk)
+ if err != nil {
+ return "", err
}
- _, _ = buf.WriteString("\nGO\n")
+ _, _ = buf.WriteString(fkSQL)
+ _, _ = buf.WriteString(";\n")
}
}
+ // Add a GO statement to separate table creation/alteration from the next phase
+ // Only add if we have tables/alters and we have views/functions/procedures to follow
+ if hasCreateOrAlterTables(diff) && (hasCreateViews(diff) || hasCreateFunctions(diff) || hasCreateProcedures(diff)) {
+ _, _ = buf.WriteString("\nGO\n")
+ }
+
+ // 2.4 Create views in topological order (dependencies first)
+ if err := createViewsInOrder(diff, &buf); err != nil {
+ return "", err
+ }
+
// 2.5 Create functions
for _, funcDiff := range diff.FunctionChanges {
if funcDiff.Action == schema.MetadataDiffActionCreate {
@@ -383,16 +404,7 @@ func generateCreateTable(schemaName, tableName string, table *storepb.TableMetad
}
}
- // Add foreign keys (after table and referenced tables exist)
- for _, fk := range table.ForeignKeys {
- fkSQL, err := generateAddForeignKey(schemaName, tableName, fk)
- if err != nil {
- return "", err
- }
- _, _ = buf.WriteString("\n")
- _, _ = buf.WriteString(fkSQL)
- _, _ = buf.WriteString(";")
- }
+ // Note: Foreign keys are now added in a separate phase after all tables are created
return buf.String(), nil
}
@@ -813,3 +825,304 @@ func getDefaultExpression(column *storepb.ColumnMetadata) string {
return ""
}
+
+type queryClauseListener struct {
+ *parser.BaseTSqlParserListener
+
+ result string
+}
+
+func (l *queryClauseListener) EnterCreate_view(ctx *parser.Create_viewContext) {
+ if l.result != "" {
+ return
+ }
+
+ l.result = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.Select_statement_standalone())
+}
+
+// getViewDependencies extracts the tables that a view depends on
+func getViewDependencies(viewDef string, schemaName string) ([]string, error) {
+ // Parse the CREATE VIEW statement to extract the query properly
+ // We need to find the AS keyword that's part of CREATE VIEW, not column aliases
+
+ parseResult, err := tsql.ParseTSQL(viewDef)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to parse view definition")
+ }
+
+ // Extract the query part after the CREATE VIEW statement
+ // This assumes the viewDef is a valid CREATE VIEW statement
+ // and that it contains a valid T-SQL query.
+ l := &queryClauseListener{}
+ antlr.ParseTreeWalkerDefault.Walk(l, parseResult.Tree)
+ if l.result == "" {
+ return []string{}, nil
+ }
+
+ // Use GetQuerySpan with mock functions to avoid nil pointer dereference
+ span, err := tsql.GetQuerySpan(
+ context.Background(),
+ base.GetQuerySpanContext{
+ GetDatabaseMetadataFunc: func(_ context.Context, _, databaseName string) (string, *model.DatabaseMetadata, error) {
+ // Return minimal metadata - we only need table references, not column info
+ metadata := &storepb.DatabaseSchemaMetadata{
+ Name: databaseName,
+ Schemas: []*storepb.SchemaMetadata{
+ {
+ Name: schemaName,
+ Tables: []*storepb.TableMetadata{},
+ },
+ },
+ }
+ dbMetadata := model.NewDatabaseMetadata(metadata, false, false)
+ return databaseName, dbMetadata, nil
+ },
+ ListDatabaseNamesFunc: func(_ context.Context, _ string) ([]string, error) {
+ // Return empty list - we don't need actual database names for dependency extraction
+ return []string{}, nil
+ },
+ },
+ l.result,
+ "", // database
+ schemaName,
+ false, // case sensitive
+ )
+
+ // If error parsing query span, return empty dependencies to allow migration to proceed
+ // This is intentional - we prefer to proceed with no dependencies rather than block the migration
+ if err != nil {
+ return []string{}, nil // nolint:nilerr
+ }
+
+ // Collect unique dependencies
+ dependencyMap := make(map[string]bool)
+ for sourceColumn := range span.SourceColumns {
+ // Create dependency ID in format: schema.table
+ depID := getObjectID(sourceColumn.Schema, sourceColumn.Table)
+ dependencyMap[depID] = true
+ }
+
+ // Convert map to slice
+ var dependencies []string
+ for dep := range dependencyMap {
+ dependencies = append(dependencies, dep)
+ }
+
+ return dependencies, nil
+}
+
+// getObjectID creates a unique identifier for a database object
+func getObjectID(schema, name string) string {
+ if schema == "" {
+ return name
+ }
+ return fmt.Sprintf("%s.%s", schema, name)
+}
+
+// dropViewsInOrder drops views in reverse topological order (dependent views first)
+func dropViewsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {
+ // Build dependency graph for views being dropped or altered
+ graph := base.NewGraph()
+ viewMap := make(map[string]*schema.ViewDiff)
+
+ // First pass: Add all views to be dropped or altered to the graph and viewMap
+ // Sort for deterministic processing order
+ var viewsToProcess []*schema.ViewDiff
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionDrop || viewDiff.Action == schema.MetadataDiffActionAlter {
+ viewsToProcess = append(viewsToProcess, viewDiff)
+ }
+ }
+ sort.Slice(viewsToProcess, func(i, j int) bool {
+ return getObjectID(viewsToProcess[i].SchemaName, viewsToProcess[i].ViewName) < getObjectID(viewsToProcess[j].SchemaName, viewsToProcess[j].ViewName)
+ })
+
+ for _, viewDiff := range viewsToProcess {
+ viewID := getObjectID(viewDiff.SchemaName, viewDiff.ViewName)
+ graph.AddNode(viewID)
+ viewMap[viewID] = viewDiff
+ }
+
+ // Second pass: Add dependency edges now that all views are in viewMap
+ for _, viewDiff := range viewsToProcess {
+ viewID := getObjectID(viewDiff.SchemaName, viewDiff.ViewName)
+
+ // Get dependencies from the old view definition
+ if viewDiff.OldView != nil && viewDiff.OldView.Definition != "" {
+ deps, err := getViewDependencies(viewDiff.OldView.Definition, viewDiff.SchemaName)
+ if err != nil {
+ // If we can't parse dependencies, we'll just drop in original order
+ continue
+ }
+
+ // Add edges from this view to its dependencies
+ for _, dep := range deps {
+ // Only add edge if the dependency is also being dropped/altered
+ if _, exists := viewMap[dep]; exists {
+ graph.AddEdge(viewID, dep)
+ }
+ }
+ }
+ }
+
+ // Get topological order
+ orderedList, err := graph.TopologicalSort()
+ if err != nil {
+ // If there's a cycle or error, fall back to original order
+ var fallbackViews []*schema.ViewDiff
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionDrop || viewDiff.Action == schema.MetadataDiffActionAlter {
+ fallbackViews = append(fallbackViews, viewDiff)
+ }
+ }
+ // Sort alphabetically for deterministic output
+ sort.Slice(fallbackViews, func(i, j int) bool {
+ return getObjectID(fallbackViews[i].SchemaName, fallbackViews[i].ViewName) < getObjectID(fallbackViews[j].SchemaName, fallbackViews[j].ViewName)
+ })
+ for _, viewDiff := range fallbackViews {
+ _, _ = buf.WriteString("DROP VIEW [")
+ _, _ = buf.WriteString(viewDiff.SchemaName)
+ _, _ = buf.WriteString("].[")
+ _, _ = buf.WriteString(viewDiff.ViewName)
+ _, _ = buf.WriteString("];\nGO\n")
+ }
+ return nil
+ }
+
+ // Drop views in order (most dependent first due to edge direction)
+ for _, viewID := range orderedList {
+ if viewDiff, ok := viewMap[viewID]; ok {
+ _, _ = buf.WriteString("DROP VIEW [")
+ _, _ = buf.WriteString(viewDiff.SchemaName)
+ _, _ = buf.WriteString("].[")
+ _, _ = buf.WriteString(viewDiff.ViewName)
+ _, _ = buf.WriteString("];\nGO\n")
+ }
+ }
+
+ return nil
+}
+
+// createViewsInOrder creates views in topological order (dependencies first)
+func createViewsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {
+ // Build dependency graph for views being created or altered
+ graph := base.NewGraph()
+ viewMap := make(map[string]*schema.ViewDiff)
+
+ // First pass: Add all views to be created or altered to the graph and viewMap
+ // Sort for deterministic processing order
+ var viewsToProcess []*schema.ViewDiff
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionCreate || viewDiff.Action == schema.MetadataDiffActionAlter {
+ viewsToProcess = append(viewsToProcess, viewDiff)
+ }
+ }
+ sort.Slice(viewsToProcess, func(i, j int) bool {
+ return getObjectID(viewsToProcess[i].SchemaName, viewsToProcess[i].ViewName) < getObjectID(viewsToProcess[j].SchemaName, viewsToProcess[j].ViewName)
+ })
+
+ for _, viewDiff := range viewsToProcess {
+ viewID := getObjectID(viewDiff.SchemaName, viewDiff.ViewName)
+ graph.AddNode(viewID)
+ viewMap[viewID] = viewDiff
+ }
+
+ // Second pass: Add dependency edges now that all views are in viewMap
+ for _, viewDiff := range viewsToProcess {
+ viewID := getObjectID(viewDiff.SchemaName, viewDiff.ViewName)
+
+ // Get dependencies from the new view definition
+ if viewDiff.NewView != nil && viewDiff.NewView.Definition != "" {
+ deps, err := getViewDependencies(viewDiff.NewView.Definition, viewDiff.SchemaName)
+ if err != nil {
+ // If we can't parse dependencies, we'll just create in original order
+ continue
+ }
+
+ // Add edges from dependencies to this view
+ for _, dep := range deps {
+ // Only add edge if the dependency is also being created/altered
+ if _, exists := viewMap[dep]; exists {
+ graph.AddEdge(dep, viewID)
+ }
+ }
+ }
+ }
+
+ // Get topological order
+ orderedList, err := graph.TopologicalSort()
+ if err != nil {
+ // If there's a cycle or error, fall back to original order
+ var fallbackViews []*schema.ViewDiff
+ for _, viewDiff := range diff.ViewChanges {
+ // Only handle CREATE and ALTER (as create) in this phase
+ if viewDiff.Action == schema.MetadataDiffActionCreate || viewDiff.Action == schema.MetadataDiffActionAlter {
+ fallbackViews = append(fallbackViews, viewDiff)
+ }
+ }
+ // Sort alphabetically for deterministic output
+ sort.Slice(fallbackViews, func(i, j int) bool {
+ return getObjectID(fallbackViews[i].SchemaName, fallbackViews[i].ViewName) < getObjectID(fallbackViews[j].SchemaName, fallbackViews[j].ViewName)
+ })
+ for _, viewDiff := range fallbackViews {
+ _, _ = buf.WriteString(viewDiff.NewView.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(viewDiff.NewView.Definition), ";") {
+ _, _ = buf.WriteString(";")
+ }
+ _, _ = buf.WriteString("\nGO\n")
+ }
+ return nil
+ }
+
+ // Create views in order
+ for _, viewID := range orderedList {
+ if viewDiff, ok := viewMap[viewID]; ok {
+ // Both CREATE and ALTER actions create the view in this phase
+ // (ALTER views were already dropped in the drop phase)
+ _, _ = buf.WriteString(viewDiff.NewView.Definition)
+ if !strings.HasSuffix(strings.TrimSpace(viewDiff.NewView.Definition), ";") {
+ _, _ = buf.WriteString(";")
+ }
+ _, _ = buf.WriteString("\nGO\n")
+ }
+ }
+
+ return nil
+}
+
+// Helper functions to check if diff contains certain types of changes
+func hasCreateOrAlterTables(diff *schema.MetadataDiff) bool {
+ for _, tableDiff := range diff.TableChanges {
+ if tableDiff.Action == schema.MetadataDiffActionCreate || tableDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ return false
+}
+
+func hasCreateViews(diff *schema.MetadataDiff) bool {
+ for _, viewDiff := range diff.ViewChanges {
+ if viewDiff.Action == schema.MetadataDiffActionCreate || viewDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ return false
+}
+
+func hasCreateFunctions(diff *schema.MetadataDiff) bool {
+ for _, funcDiff := range diff.FunctionChanges {
+ if funcDiff.Action == schema.MetadataDiffActionCreate {
+ return true
+ }
+ }
+ return false
+}
+
+func hasCreateProcedures(diff *schema.MetadataDiff) bool {
+ for _, procDiff := range diff.ProcedureChanges {
+ if procDiff.Action == schema.MetadataDiffActionCreate || procDiff.Action == schema.MetadataDiffActionAlter {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/schema/mssql/generate_migration_test.go b/backend/plugin/schema/mssql/generate_migration_test.go
index 918cf82724..6d5fc8f147 100644
--- a/backend/plugin/schema/mssql/generate_migration_test.go
+++ b/backend/plugin/schema/mssql/generate_migration_test.go
@@ -134,13 +134,9 @@ func TestGenerateMigration_Procedures(t *testing.T) {
}
func TestGenerateMigration_Views(t *testing.T) {
- // Skip views test for now due to parser limitations with multiple statements
- t.Skip("Skipping views test due to parser limitations")
runMigrationTest(t, "test_migration_views.yaml", false /* record */)
}
func TestGenerateMigration_SafeOrder(t *testing.T) {
- // Skip safe order test for now due to parser limitations with multiple statements
- t.Skip("Skipping safe order test due to parser limitations")
runMigrationTest(t, "test_migration_safe_order.yaml", false /* record */)
}
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml b/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml
index 61eb21dda4..1ad9ac71f2 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_constraints.yaml
@@ -24,8 +24,9 @@
CONSTRAINT [PK_employees] PRIMARY KEY CLUSTERED ([id]),
CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[employees] ADD CONSTRAINT [FK_employees_departments] FOREIGN KEY ([department_id]) REFERENCES [dbo].[departments] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+
- description: Drop foreign key constraint
oldSchema: |
CREATE TABLE [dbo].[departments] (
@@ -70,8 +71,9 @@
CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id]),
CONSTRAINT [CK_products_price] CHECK ([price] > 0)
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[products] ADD CONSTRAINT [CK_products_price] CHECK ([price] > 0);
+
- description: Drop check constraint
oldSchema: |
CREATE TABLE [dbo].[products] (
@@ -101,8 +103,9 @@
[name] nvarchar(100) NOT NULL,
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[users] ADD CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id]);
+
- description: Drop primary key constraint
oldSchema: |
CREATE TABLE [dbo].[users] (
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml b/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml
index 43cfd1b263..3906bd0ef5 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_functions.yaml
@@ -36,10 +36,9 @@
RETURN @FirstName + ' ' + @LastName
END
newSchema: ""
- expected: |+
+ expected: |
DROP FUNCTION [dbo].[GetFullName];
GO
-
- description: Create table-valued function
oldSchema: ""
newSchema: |
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml b/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml
index 01921e7358..8dffc2bb1e 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_indexes.yaml
@@ -12,8 +12,9 @@
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
- expected: |
+ expected: |+
CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email]);
+
- description: Drop index
oldSchema: |
CREATE TABLE [dbo].[users] (
@@ -45,8 +46,9 @@
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
CREATE UNIQUE NONCLUSTERED INDEX [UX_users_email] ON [dbo].[users] ([email]);
- expected: |
+ expected: |+
CREATE UNIQUE NONCLUSTERED INDEX [UX_users_email] ON [dbo].[users] ([email]);
+
- description: Create unique constraint
oldSchema: |
CREATE TABLE [dbo].[users] (
@@ -61,8 +63,9 @@
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id]),
CONSTRAINT [UQ_users_email] UNIQUE NONCLUSTERED ([email])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[users] ADD CONSTRAINT [UQ_users_email] UNIQUE NONCLUSTERED ([email]);
+
- description: Create clustered columnstore index
oldSchema: |
CREATE TABLE [dbo].[sales_data] (
@@ -79,8 +82,9 @@
[amount] decimal(10,2) NOT NULL
);
CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
- expected: |
+ expected: |+
CREATE CLUSTERED COLUMNSTORE INDEX [CCI_sales_data] ON [dbo].[sales_data];
+
- description: Create nonclustered columnstore index with columns
oldSchema: |
CREATE TABLE [dbo].[analytics_data] (
@@ -101,8 +105,9 @@
CONSTRAINT [PK_analytics_data] PRIMARY KEY CLUSTERED ([id])
);
CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_analytics_data] ON [dbo].[analytics_data] ([product_id], [sale_date], [amount]);
- expected: |
+ expected: |+
CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_analytics_data] ON [dbo].[analytics_data] ([product_id], [sale_date], [amount]);
+
- description: Drop columnstore index
oldSchema: |
CREATE TABLE [dbo].[sales_data] (
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml b/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml
index 5446f64d7d..6d7b3d3ad6 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_procedures.yaml
@@ -24,10 +24,9 @@
SELECT * FROM Users WHERE Id = @UserId
END
newSchema: ""
- expected: |+
+ expected: |
DROP PROCEDURE [dbo].[GetUserById];
GO
-
- description: Create procedure with output parameters
oldSchema: ""
newSchema: |
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
new file mode 100644
index 0000000000..8de3917acb
--- /dev/null
+++ b/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml
@@ -0,0 +1,227 @@
+- description: Safe order - drop dependent objects before tables
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL PRIMARY KEY,
+ [user_id] int NOT NULL,
+ CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
+ );
+ GO
+ CREATE INDEX [IX_orders_user_id] ON [dbo].[orders]([user_id]);
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[users] u
+ LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ CREATE PROCEDURE [dbo].[sp_get_user_orders]
+ @user_id int
+ AS
+ BEGIN
+ SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
+ END;
+ GO
+ newSchema: ""
+ expected: |
+ ALTER TABLE [dbo].[orders] DROP CONSTRAINT [FK_orders_users];
+ DROP PROCEDURE [dbo].[sp_get_user_orders];
+ GO
+ DROP VIEW [dbo].[v_user_orders];
+ GO
+ DROP TABLE [dbo].[orders];
+ DROP TABLE [dbo].[users];
+- description: Safe order - create tables before dependent objects
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL PRIMARY KEY,
+ [user_id] int NOT NULL,
+ CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
+ );
+ GO
+ CREATE INDEX [IX_orders_user_id] ON [dbo].[orders]([user_id]);
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[users] u
+ LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ CREATE PROCEDURE [dbo].[sp_get_user_orders]
+ @user_id int
+ AS
+ BEGIN
+ SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
+ END;
+ GO
+ expected: |
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ CONSTRAINT [PK_orders_2] PRIMARY KEY ([id])
+ );
+ CREATE INDEX [IX_orders_user_id] ON [dbo].[orders] ([user_id]);
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ CONSTRAINT [PK_users_1] PRIMARY KEY ([id])
+ );
+ ALTER TABLE [dbo].[orders] ADD CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
+
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[users] u
+ LEFT JOIN [dbo].[orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ CREATE PROCEDURE [dbo].[sp_get_user_orders]
+ @user_id int
+ AS
+ BEGIN
+ SELECT * FROM [dbo].[v_user_orders] WHERE id = @user_id;
+ END;
+ GO
+- description: Safe order - complex view dependencies with drops and creates
+ oldSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL,
+ [dept_id] int NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_departments] AS
+ SELECT id, name FROM [dbo].[departments];
+ GO
+ CREATE VIEW [dbo].[v_employees] AS
+ SELECT id, name, dept_id FROM [dbo].[employees];
+ 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;
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[departments] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL,
+ [location] nvarchar(200) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[employees] (
+ [id] int NOT NULL PRIMARY KEY,
+ [name] nvarchar(100) NULL,
+ [dept_id] int NULL,
+ [salary] decimal(10,2) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_departments] AS
+ SELECT id, name, location FROM [dbo].[departments];
+ GO
+ CREATE VIEW [dbo].[v_employees] AS
+ SELECT id, name, dept_id, salary FROM [dbo].[employees];
+ 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;
+ GO
+ CREATE VIEW [dbo].[v_dept_summary] AS
+ SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
+ FROM [dbo].[v_employee_dept]
+ GROUP BY dept_name, location;
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_employee_dept];
+ GO
+ DROP VIEW [dbo].[v_employees];
+ GO
+ DROP VIEW [dbo].[v_departments];
+ GO
+
+ ALTER TABLE [dbo].[departments] ADD [location] nvarchar(200) NULL;
+
+ ALTER TABLE [dbo].[employees] ADD [salary] decimal(10,2) NULL;
+
+
+ GO
+ CREATE VIEW [dbo].[v_departments] AS
+ SELECT id, name, location FROM [dbo].[departments];
+ GO
+ CREATE VIEW [dbo].[v_employees] AS
+ SELECT id, name, dept_id, salary FROM [dbo].[employees];
+ 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;
+ GO
+ CREATE VIEW [dbo].[v_dept_summary] AS
+ SELECT dept_name, location, COUNT(*) as emp_count, AVG(salary) as avg_salary
+ FROM [dbo].[v_employee_dept]
+ GROUP BY dept_name, location;
+ GO
+- description: Safe order - circular view dependency fallback
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[table1] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[table2] (
+ [id] int NOT NULL,
+ [value] nvarchar(100) NULL
+ );
+ GO
+ -- Note: These views create a circular dependency which should fall back to original order
+ CREATE VIEW [dbo].[v_circular1] AS
+ SELECT t1.id, t1.name, t2.value
+ FROM [dbo].[table1] t1
+ JOIN [dbo].[table2] t2 ON t1.id = t2.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular2] v WHERE v.id = t1.id);
+ GO
+ CREATE VIEW [dbo].[v_circular2] AS
+ SELECT t2.id, t2.value, t1.name
+ FROM [dbo].[table2] t2
+ JOIN [dbo].[table1] t1 ON t2.id = t1.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular1] v WHERE v.id = t2.id);
+ GO
+ expected: |
+ CREATE TABLE [dbo].[table1] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ CREATE TABLE [dbo].[table2] (
+ [id] int NOT NULL,
+ [value] nvarchar(100) NULL
+ );
+
+ GO
+ CREATE VIEW [dbo].[v_circular1] AS
+ SELECT t1.id, t1.name, t2.value
+ FROM [dbo].[table1] t1
+ JOIN [dbo].[table2] t2 ON t1.id = t2.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular2] v WHERE v.id = t1.id);
+ GO
+ CREATE VIEW [dbo].[v_circular2] AS
+ SELECT t2.id, t2.value, t1.name
+ FROM [dbo].[table2] t2
+ JOIN [dbo].[table1] t1 ON t2.id = t1.id
+ WHERE EXISTS (SELECT 1 FROM [dbo].[v_circular1] v WHERE v.id = t2.id);
+ GO
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml b/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml
index 7e0bf4cdb9..b4a3090b51 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_tables.yaml
@@ -24,9 +24,8 @@
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
newSchema: ""
- expected: |+
+ expected: |
DROP TABLE [dbo].[users];
-
- description: Add column to existing table
oldSchema: |
CREATE TABLE [dbo].[users] (
@@ -41,8 +40,9 @@
[email] nvarchar(255) NULL,
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[users] ADD [email] nvarchar(255) NULL;
+
- description: Drop column from table
oldSchema: |
CREATE TABLE [dbo].[users] (
@@ -73,8 +73,9 @@
[name] nvarchar(100) NOT NULL,
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[users] ALTER COLUMN [name] nvarchar(100) NOT NULL;
+
- description: Change column nullability
oldSchema: |
CREATE TABLE [dbo].[users] (
@@ -90,8 +91,9 @@
[email] nvarchar(255) NULL,
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[users] ALTER COLUMN [email] nvarchar(255) NULL;
+
- description: Add default constraint
oldSchema: |
CREATE TABLE [dbo].[users] (
@@ -105,8 +107,9 @@
[status] int NOT NULL DEFAULT 1,
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
);
- expected: |
+ expected: |+
ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_status] DEFAULT 1 FOR [status];
+
- description: Create table with check constraint
oldSchema: ""
newSchema: |
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_views.yaml b/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
new file mode 100644
index 0000000000..226b03e95c
--- /dev/null
+++ b/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
@@ -0,0 +1,283 @@
+- description: Create single view
+ oldSchema: ""
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ expected: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+- description: Create views with dependencies - correct order
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_orders] AS
+ SELECT o.id, o.user_id, o.amount, u.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[users] u ON o.user_id = u.id;
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[v_users] u
+ LEFT JOIN [dbo].[v_orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ expected: |
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+
+ GO
+ CREATE VIEW [dbo].[v_orders] AS
+ SELECT o.id, o.user_id, o.amount, u.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[users] u ON o.user_id = u.id;
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[v_users] u
+ LEFT JOIN [dbo].[v_orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+- description: Drop views with dependencies - reverse order
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_orders] AS
+ SELECT o.id, o.user_id, o.amount, u.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[users] u ON o.user_id = u.id;
+ GO
+ CREATE VIEW [dbo].[v_user_orders] AS
+ SELECT u.id, u.name, COUNT(o.id) as order_count
+ FROM [dbo].[v_users] u
+ LEFT JOIN [dbo].[v_orders] o ON u.id = o.user_id
+ GROUP BY u.id, u.name;
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE TABLE [dbo].[orders] (
+ [id] int NOT NULL,
+ [user_id] int NOT NULL,
+ [amount] decimal(10,2) NULL
+ );
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_user_orders];
+ GO
+ DROP VIEW [dbo].[v_users];
+ GO
+ DROP VIEW [dbo].[v_orders];
+ GO
+- description: Alter view - drop and recreate
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [email] nvarchar(200) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, email FROM [dbo].[users];
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_users];
+ GO
+
+ ALTER TABLE [dbo].[users] ADD [email] nvarchar(200) NULL;
+
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, email FROM [dbo].[users];
+ GO
+- description: Alter multiple views with dependencies
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_active_users] AS
+ SELECT * FROM [dbo].[v_users] WHERE id > 0;
+ GO
+ newSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [status] nvarchar(50) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, status FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_active_users] AS
+ SELECT * FROM [dbo].[v_users] WHERE status = 'active';
+ GO
+ expected: |
+ DROP VIEW [dbo].[v_active_users];
+ GO
+ DROP VIEW [dbo].[v_users];
+ GO
+
+ ALTER TABLE [dbo].[users] ADD [status] nvarchar(50) NULL;
+
+
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name, status FROM [dbo].[users];
+ GO
+ CREATE VIEW [dbo].[v_active_users] AS
+ SELECT * FROM [dbo].[v_users] WHERE status = 'active';
+ GO
+- description: Create views in different schemas
+ oldSchema: |
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ newSchema: |
+ CREATE SCHEMA [reporting];
+ GO
+ CREATE TABLE [dbo].[users] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL
+ );
+ GO
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [reporting].[v_user_report] AS
+ SELECT * FROM [dbo].[v_users];
+ GO
+ expected: |
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE VIEW [dbo].[v_users] AS
+ SELECT id, name FROM [dbo].[users];
+ GO
+ CREATE VIEW [reporting].[v_user_report] AS
+ SELECT * FROM [dbo].[v_users];
+ GO
+- description: Complex view dependencies across schemas
+ oldSchema: ""
+ newSchema: |
+ CREATE SCHEMA [sales];
+ GO
+ CREATE SCHEMA [reporting];
+ GO
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [price] decimal(10,2) NULL
+ );
+ GO
+ CREATE TABLE [sales].[orders] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [quantity] int NOT NULL
+ );
+ GO
+ CREATE VIEW [sales].[v_order_details] AS
+ SELECT o.id, o.product_id, o.quantity, p.name, p.price
+ FROM [sales].[orders] o
+ JOIN [dbo].[products] p ON o.product_id = p.id;
+ GO
+ CREATE VIEW [reporting].[v_sales_summary] AS
+ SELECT product_id, SUM(quantity) as total_quantity, SUM(quantity * price) as total_revenue
+ FROM [sales].[v_order_details]
+ GROUP BY product_id;
+ GO
+ expected: |
+ CREATE SCHEMA [reporting];
+ GO
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE TABLE [dbo].[products] (
+ [id] int NOT NULL,
+ [name] nvarchar(100) NULL,
+ [price] decimal(10,2) NULL
+ );
+ CREATE TABLE [sales].[orders] (
+ [id] int NOT NULL,
+ [product_id] int NOT NULL,
+ [quantity] int NOT NULL
+ );
+
+ GO
+ CREATE VIEW [sales].[v_order_details] AS
+ SELECT o.id, o.product_id, o.quantity, p.name, p.price
+ FROM [sales].[orders] o
+ JOIN [dbo].[products] p ON o.product_id = p.id;
+ GO
+ CREATE VIEW [reporting].[v_sales_summary] AS
+ SELECT product_id, SUM(quantity) as total_quantity, SUM(quantity * price) as total_revenue
+ FROM [sales].[v_order_details]
+ GROUP BY product_id;
+ GO