Skip to content

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

chore: update get database definition for sql server (#16443)

rebelice80b8360dfab4
diff --git a/backend/plugin/schema/mssql/get_database_definition.go b/backend/plugin/schema/mssql/get_database_definition.go
index dff37f759e..9fbe4a6470 100644
--- a/backend/plugin/schema/mssql/get_database_definition.go
+++ b/backend/plugin/schema/mssql/get_database_definition.go
@@ -2,8 +2,10 @@ package mssql
import (
"fmt"
+ "sort"
"strings"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/plugin/schema"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
@@ -15,6 +17,9 @@ const (
func init() {
schema.RegisterGetDatabaseDefinition(storepb.Engine_MSSQL, GetDatabaseDefinition)
schema.RegisterGetTableDefinition(storepb.Engine_MSSQL, GetTableDefinition)
+ schema.RegisterGetViewDefinition(storepb.Engine_MSSQL, GetViewDefinition)
+ schema.RegisterGetFunctionDefinition(storepb.Engine_MSSQL, GetFunctionDefinition)
+ schema.RegisterGetProcedureDefinition(storepb.Engine_MSSQL, GetProcedureDefinition)
}
func GetDatabaseDefinition(_ schema.GetDefinitionContext, to *storepb.DatabaseSchemaMetadata) (string, error) {
@@ -23,8 +28,40 @@ func GetDatabaseDefinition(_ schema.GetDefinitionContext, to *storepb.DatabaseSc
}
var buf strings.Builder
+
+ // First, write all schemas
+ for _, schema := range to.Schemas {
+ if schema.Name != defaultSchema {
+ _, _ = fmt.Fprintf(&buf, "CREATE SCHEMA [%s];\nGO\n\n", schema.Name)
+ }
+ }
+
+ // Then, write all tables
+ for _, schema := range to.Schemas {
+ for _, table := range schema.Tables {
+ writeTable(&buf, schema.Name, table)
+ }
+ }
+
+ // Then, write all views in dependency order across all schemas
+ if hasViews(to.Schemas) {
+ // Add GO separator between tables and views if we have tables
+ hasTables := false
+ for _, schema := range to.Schemas {
+ if len(schema.Tables) > 0 {
+ hasTables = true
+ break
+ }
+ }
+ if hasTables {
+ _, _ = buf.WriteString("GO\n\n")
+ }
+ writeAllViewsInOrder(&buf, to.Schemas)
+ }
+
+ // Finally, write functions and procedures
for _, schema := range to.Schemas {
- writeSchema(&buf, schema)
+ writeFunctionsAndProcedures(&buf, schema)
}
return buf.String(), nil
@@ -36,16 +73,123 @@ func GetTableDefinition(schemaName string, table *storepb.TableMetadata, _ []*st
return buf.String(), nil
}
-func writeSchema(out *strings.Builder, schema *storepb.SchemaMetadata) {
- if schema.Name != defaultSchema {
- _, _ = fmt.Fprintf(out, "CREATE SCHEMA [%s];\nGO\n\n", schema.Name)
+func writeFunctionsAndProcedures(out *strings.Builder, schema *storepb.SchemaMetadata) {
+ for _, function := range schema.Functions {
+ writeFunction(out, schema.Name, function)
}
- for _, table := range schema.Tables {
- writeTable(out, schema.Name, table)
+ for _, procedure := range schema.Procedures {
+ writeProcedure(out, schema.Name, procedure)
}
}
+func hasViews(schemas []*storepb.SchemaMetadata) bool {
+ for _, schema := range schemas {
+ if len(schema.Views) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+func writeAllViewsInOrder(out *strings.Builder, schemas []*storepb.SchemaMetadata) {
+ // Collect all views from all schemas
+ var allViews []*viewWithSchema
+ for _, schema := range schemas {
+ for _, view := range schema.Views {
+ allViews = append(allViews, &viewWithSchema{
+ schema: schema.Name,
+ view: view,
+ })
+ }
+ }
+
+ if len(allViews) == 0 {
+ return
+ }
+
+ // Sort views by dependencies across all schemas
+ sortedViews := sortViewsByDependenciesAcrossSchemas(allViews)
+
+ // Write sorted views
+ for _, vws := range sortedViews {
+ writeView(out, vws.schema, vws.view)
+ }
+}
+
+type viewWithSchema struct {
+ schema string
+ view *storepb.ViewMetadata
+}
+
+// sortViewsByDependenciesAcrossSchemas sorts views using topological sort considering cross-schema dependencies
+func sortViewsByDependenciesAcrossSchemas(views []*viewWithSchema) []*viewWithSchema {
+ if len(views) <= 1 {
+ return views
+ }
+
+ // Create a map for quick lookup
+ viewMap := make(map[string]*viewWithSchema)
+ for _, vws := range views {
+ viewID := getObjectID(vws.schema, vws.view.Name)
+ viewMap[viewID] = vws
+ }
+
+ // Build dependency graph
+ graph := base.NewGraph()
+
+ // Add all view nodes
+ for _, vws := range views {
+ viewID := getObjectID(vws.schema, vws.view.Name)
+ graph.AddNode(viewID)
+ }
+
+ // Add edges based on dependencies
+ for _, vws := range views {
+ viewID := getObjectID(vws.schema, vws.view.Name)
+
+ // Get dependencies from the view definition
+ deps, err := getViewDependencies(vws.view.Definition, vws.schema)
+ if err != nil {
+ // If we can't parse dependencies, continue without adding edges
+ continue
+ }
+
+ // For each dependency, check if it's a view (in any schema)
+ for _, dep := range deps {
+ // dep is already in format schema.table
+ if _, isView := viewMap[dep]; isView {
+ // The dependency view must come before this view
+ graph.AddEdge(dep, viewID)
+ }
+ }
+ }
+
+ // Perform topological sort
+ sortedIDs, err := graph.TopologicalSort()
+ if err != nil {
+ // If there's a cycle or error, return views in original order
+ // Sort by schema then by name for deterministic output
+ sort.Slice(views, func(i, j int) bool {
+ if views[i].schema != views[j].schema {
+ return views[i].schema < views[j].schema
+ }
+ return views[i].view.Name < views[j].view.Name
+ })
+ return views
+ }
+
+ // Build the result in sorted order
+ var result []*viewWithSchema
+ for _, id := range sortedIDs {
+ if vws, ok := viewMap[id]; ok {
+ result = append(result, vws)
+ }
+ }
+
+ return result
+}
+
func writeTable(out *strings.Builder, schemaName string, table *storepb.TableMetadata) {
_, _ = fmt.Fprintf(out, "CREATE TABLE [%s].[%s] (\n", schemaName, table.Name)
for i, column := range table.Columns {
@@ -100,6 +244,9 @@ func writeNonClusteredColumnStoreIndex(out *strings.Builder, schemaName string,
func writeNormalIndex(out *strings.Builder, schemaName string, tableName string, index *storepb.IndexMetadata) {
_, _ = out.WriteString("CREATE")
+ if index.Unique {
+ _, _ = out.WriteString(" UNIQUE")
+ }
if index.Type != "" {
_, _ = fmt.Fprintf(out, " %s", index.Type)
}
@@ -109,7 +256,7 @@ func writeNormalIndex(out *strings.Builder, schemaName string, tableName string,
_, _ = out.WriteString(",\n")
}
_, _ = fmt.Fprintf(out, " [%s]", column)
- if index.Descending[i] {
+ if i < len(index.Descending) && index.Descending[i] {
_, _ = out.WriteString(" DESC")
} else {
_, _ = out.WriteString(" ASC")
@@ -174,7 +321,7 @@ func writeKey(out *strings.Builder, key *storepb.IndexMetadata) {
_, _ = out.WriteString(", ")
}
_, _ = fmt.Fprintf(out, "[%s]", column)
- if key.Descending[i] {
+ if i < len(key.Descending) && key.Descending[i] {
_, _ = out.WriteString(" DESC")
} else {
_, _ = out.WriteString(" ASC")
@@ -198,3 +345,34 @@ func writeColumn(out *strings.Builder, column *storepb.ColumnMetadata) {
_, _ = out.WriteString(" NOT NULL")
}
}
+
+func writeView(out *strings.Builder, _ string, view *storepb.ViewMetadata) {
+ // The view definition already contains CREATE VIEW statement
+ _, _ = fmt.Fprintf(out, "%s;\n\nGO\n\n", view.Definition)
+}
+
+func writeFunction(out *strings.Builder, _ string, function *storepb.FunctionMetadata) {
+ _, _ = fmt.Fprintf(out, "%s\n\nGO\n\n", function.Definition)
+}
+
+func writeProcedure(out *strings.Builder, _ string, procedure *storepb.ProcedureMetadata) {
+ _, _ = fmt.Fprintf(out, "%s\n\nGO\n\n", procedure.Definition)
+}
+
+func GetViewDefinition(schemaName string, view *storepb.ViewMetadata) (string, error) {
+ var buf strings.Builder
+ writeView(&buf, schemaName, view)
+ return buf.String(), nil
+}
+
+func GetFunctionDefinition(schemaName string, function *storepb.FunctionMetadata) (string, error) {
+ var buf strings.Builder
+ writeFunction(&buf, schemaName, function)
+ return buf.String(), nil
+}
+
+func GetProcedureDefinition(schemaName string, procedure *storepb.ProcedureMetadata) (string, error) {
+ var buf strings.Builder
+ writeProcedure(&buf, schemaName, procedure)
+ return buf.String(), nil
+}
diff --git a/backend/plugin/schema/mssql/get_database_definition_test.go b/backend/plugin/schema/mssql/get_database_definition_test.go
new file mode 100644
index 0000000000..8bfc759ad8
--- /dev/null
+++ b/backend/plugin/schema/mssql/get_database_definition_test.go
@@ -0,0 +1,67 @@
+package mssql
+
+import (
+ "io"
+ "os"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/parser/tsql"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+type getDatabaseDefinitionTestCase struct {
+ Input string `yaml:"input"`
+ Output string `yaml:"output"`
+}
+
+func TestGetDatabaseDefinition(t *testing.T) {
+ tests := []getDatabaseDefinitionTestCase{}
+ const (
+ record = false
+ )
+ var (
+ filepath = "test-data/test_get_database_definition.yaml"
+ )
+
+ a := require.New(t)
+ yamlFile, err := os.Open(filepath)
+ a.NoError(err)
+ defer yamlFile.Close()
+
+ byteValue, err := io.ReadAll(yamlFile)
+ a.NoError(err)
+ a.NoError(yaml.Unmarshal(byteValue, &tests))
+
+ for i, tc := range tests {
+ var metadata storepb.DatabaseSchemaMetadata
+ err := common.ProtojsonUnmarshaler.Unmarshal([]byte(tc.Input), &metadata)
+ a.NoError(err)
+
+ result, err := GetDatabaseDefinition(schema.GetDefinitionContext{}, &metadata)
+ a.NoError(err)
+
+ // Parse the output to ensure it's valid TSQL
+ _, err = tsql.ParseTSQL(result)
+ if err != nil {
+ t.Logf("Test case %d SQL:\n%s", i, result)
+ }
+ a.NoError(err, "Test case %d: Failed to parse generated SQL", i)
+
+ if record {
+ tests[i].Output = result
+ } else {
+ a.Equal(tc.Output, result, "Test case %d", i)
+ }
+ }
+ if record {
+ byteValue, err := yaml.Marshal(tests)
+ a.NoError(err)
+ err = os.WriteFile(filepath, byteValue, 0644)
+ a.NoError(err)
+ }
+}
diff --git a/backend/plugin/schema/mssql/test-data/test_get_database_definition.yaml b/backend/plugin/schema/mssql/test-data/test_get_database_definition.yaml
new file mode 100644
index 0000000000..1899522b38
--- /dev/null
+++ b/backend/plugin/schema/mssql/test-data/test_get_database_definition.yaml
@@ -0,0 +1,623 @@
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "users",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ },
+ {
+ "name": "email",
+ "position": 3,
+ "type": "NVARCHAR(255)",
+ "nullable": true,
+ "defaultExpression": "''"
+ },
+ {
+ "name": "created_at",
+ "position": 4,
+ "type": "DATETIME2",
+ "nullable": false,
+ "defaultExpression": "GETDATE()"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_users",
+ "expressions": ["id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true,
+ "type": "CLUSTERED"
+ },
+ {
+ "name": "IX_users_email",
+ "expressions": ["email"],
+ "descending": [false],
+ "unique": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE TABLE [dbo].[users] (
+ [id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ [email] NVARCHAR(255) DEFAULT '',
+ [created_at] DATETIME2 DEFAULT GETDATE() NOT NULL,
+ CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id] ASC)
+ );
+
+ CREATE UNIQUE INDEX [IX_users_email] ON
+ [dbo].[users] (
+ [email] ASC
+ );
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "order_id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "user_id",
+ "position": 2,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "amount",
+ "position": 3,
+ "type": "DECIMAL(10,2)",
+ "nullable": false
+ },
+ {
+ "name": "status",
+ "position": 4,
+ "type": "NVARCHAR(20)",
+ "nullable": false,
+ "defaultExpression": "'pending'"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_orders",
+ "expressions": ["order_id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true
+ }
+ ],
+ "foreignKeys": [
+ {
+ "name": "FK_orders_users",
+ "columns": ["user_id"],
+ "referencedSchema": "dbo",
+ "referencedTable": "users",
+ "referencedColumns": ["id"],
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION"
+ }
+ ],
+ "checkConstraints": [
+ {
+ "name": "CK_orders_amount",
+ "expression": "([amount] > 0)"
+ },
+ {
+ "name": "CK_orders_status",
+ "expression": "([status] IN ('pending', 'completed', 'cancelled'))"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE TABLE [dbo].[orders] (
+ [order_id] INT IDENTITY(1,1) NOT NULL,
+ [user_id] INT NOT NULL,
+ [amount] DECIMAL(10,2) NOT NULL,
+ [status] NVARCHAR(20) DEFAULT 'pending' NOT NULL,
+ CONSTRAINT [PK_orders] PRIMARY KEY ([order_id] ASC),
+ CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE CASCADE ON UPDATE NO ACTION,
+ CONSTRAINT [CK_orders_amount] CHECK ([amount] > 0),
+ CONSTRAINT [CK_orders_status] CHECK ([status] IN ('pending', 'completed', 'cancelled'))
+ );
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "views": [
+ {
+ "name": "v_active_users",
+ "definition": "CREATE VIEW [dbo].[v_active_users] AS SELECT u.id, u.name, u.email, COUNT(o.order_id) as order_count\nFROM dbo.users u\nLEFT JOIN dbo.orders o ON u.id = o.user_id\nWHERE u.created_at >= DATEADD(month, -6, GETDATE())\nGROUP BY u.id, u.name, u.email"
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE VIEW [dbo].[v_active_users] AS SELECT u.id, u.name, u.email, COUNT(o.order_id) as order_count
+ FROM dbo.users u
+ LEFT JOIN dbo.orders o ON u.id = o.user_id
+ WHERE u.created_at >= DATEADD(month, -6, GETDATE())
+ GROUP BY u.id, u.name, u.email;
+
+ GO
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "functions": [
+ {
+ "name": "fn_GetUserOrderTotal",
+ "definition": "CREATE FUNCTION [dbo].[fn_GetUserOrderTotal]\n(\n @UserId INT\n)\nRETURNS DECIMAL(10,2)\nAS\nBEGIN\n DECLARE @Total DECIMAL(10,2)\n\n SELECT @Total = SUM(amount)\n FROM dbo.orders\n WHERE user_id = @UserId\n AND status = 'completed'\n\n RETURN ISNULL(@Total, 0)\nEND"
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE FUNCTION [dbo].[fn_GetUserOrderTotal]
+ (
+ @UserId INT
+ )
+ RETURNS DECIMAL(10,2)
+ AS
+ BEGIN
+ DECLARE @Total DECIMAL(10,2)
+
+ SELECT @Total = SUM(amount)
+ FROM dbo.orders
+ WHERE user_id = @UserId
+ AND status = 'completed'
+
+ RETURN ISNULL(@Total, 0)
+ END
+
+ GO
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "procedures": [
+ {
+ "name": "sp_UpdateOrderStatus",
+ "definition": "CREATE PROCEDURE [dbo].[sp_UpdateOrderStatus]\n @OrderId INT,\n @NewStatus NVARCHAR(20)\nAS\nBEGIN\n SET NOCOUNT ON;\n\n UPDATE dbo.orders\n SET status = @NewStatus\n WHERE order_id = @OrderId;\n\n SELECT @@ROWCOUNT AS RowsAffected;\nEND"
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE PROCEDURE [dbo].[sp_UpdateOrderStatus]
+ @OrderId INT,
+ @NewStatus NVARCHAR(20)
+ AS
+ BEGIN
+ SET NOCOUNT ON;
+
+ UPDATE dbo.orders
+ SET status = @NewStatus
+ WHERE order_id = @OrderId;
+
+ SELECT @@ROWCOUNT AS RowsAffected;
+ END
+
+ GO
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "sales",
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "product_id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(200)",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_products",
+ "expressions": ["product_id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE TABLE [sales].[products] (
+ [product_id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(200) NOT NULL,
+ CONSTRAINT [PK_products] PRIMARY KEY ([product_id] ASC)
+ );
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "employees",
+ "columns": [
+ {
+ "name": "employee_id",
+ "position": 1,
+ "type": "INT",
+ "isIdentity": true,
+ "identitySeed": "1",
+ "identityIncrement": "1"
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PK_employees",
+ "expressions": ["employee_id"],
+ "descending": [false],
+ "primary": true,
+ "isConstraint": true
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_employee_list",
+ "definition": "CREATE VIEW [dbo].[v_employee_list] AS SELECT employee_id, name FROM dbo.employees WHERE employee_id > 0"
+ }
+ ],
+ "functions": [
+ {
+ "name": "fn_GetEmployeeName",
+ "definition": "CREATE FUNCTION [dbo].[fn_GetEmployeeName](@EmpId INT) RETURNS NVARCHAR(100) AS BEGIN DECLARE @Name NVARCHAR(100); SELECT @Name = name FROM dbo.employees WHERE employee_id = @EmpId; RETURN @Name; END"
+ }
+ ],
+ "procedures": [
+ {
+ "name": "sp_GetEmployee",
+ "definition": "CREATE PROCEDURE [dbo].[sp_GetEmployee] @EmpId INT AS BEGIN SELECT * FROM dbo.employees WHERE employee_id = @EmpId; END"
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE TABLE [dbo].[employees] (
+ [employee_id] INT IDENTITY(1,1) NOT NULL,
+ [name] NVARCHAR(100) NOT NULL,
+ CONSTRAINT [PK_employees] PRIMARY KEY ([employee_id] ASC)
+ );
+
+ GO
+
+ CREATE VIEW [dbo].[v_employee_list] AS SELECT employee_id, name FROM dbo.employees WHERE employee_id > 0;
+
+ GO
+
+ CREATE FUNCTION [dbo].[fn_GetEmployeeName](@EmpId INT) RETURNS NVARCHAR(100) AS BEGIN DECLARE @Name NVARCHAR(100); SELECT @Name = name FROM dbo.employees WHERE employee_id = @EmpId; RETURN @Name; END
+
+ GO
+
+ CREATE PROCEDURE [dbo].[sp_GetEmployee] @EmpId INT AS BEGIN SELECT * FROM dbo.employees WHERE employee_id = @EmpId; END
+
+ GO
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "international_data",
+ "columns": [
+ {
+ "name": "id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "text_data",
+ "position": 2,
+ "type": "NVARCHAR(MAX)",
+ "nullable": true,
+ "collation": "Latin1_General_CI_AS"
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE TABLE [dbo].[international_data] (
+ [id] INT NOT NULL,
+ [text_data] NVARCHAR(MAX) COLLATE Latin1_General_CI_AS
+ );
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "fact_sales",
+ "columns": [
+ {
+ "name": "sale_id",
+ "position": 1,
+ "type": "BIGINT",
+ "nullable": false
+ },
+ {
+ "name": "product_id",
+ "position": 2,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "quantity",
+ "position": 3,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "amount",
+ "position": 4,
+ "type": "DECIMAL(10,2)",
+ "nullable": false
+ }
+ ],
+ "indexes": [
+ {
+ "name": "CCI_fact_sales",
+ "type": "CLUSTERED COLUMNSTORE"
+ },
+ {
+ "name": "NCCI_fact_sales_product",
+ "type": "NONCLUSTERED COLUMNSTORE",
+ "expressions": ["product_id", "quantity"]
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE TABLE [dbo].[fact_sales] (
+ [sale_id] BIGINT NOT NULL,
+ [product_id] INT NOT NULL,
+ [quantity] INT NOT NULL,
+ [amount] DECIMAL(10,2) NOT NULL
+ );
+
+ CREATE CLUSTERED COLUMNSTORE INDEX [CCI_fact_sales] ON [dbo].[fact_sales];
+
+ CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_fact_sales_product] ON [dbo].[fact_sales] (
+ [product_id],
+ [quantity]
+ );
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "dbo",
+ "tables": [
+ {
+ "name": "customers",
+ "columns": [
+ {
+ "name": "customer_id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ }
+ ]
+ },
+ {
+ "name": "orders",
+ "columns": [
+ {
+ "name": "order_id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "customer_id",
+ "position": 2,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "total",
+ "position": 3,
+ "type": "DECIMAL(10,2)",
+ "nullable": false
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_customer_orders",
+ "definition": "CREATE VIEW [dbo].[v_customer_orders] AS SELECT c.customer_id, c.name, o.order_id, o.total FROM dbo.customers c JOIN dbo.orders o ON c.customer_id = o.customer_id"
+ },
+ {
+ "name": "v_customer_summary",
+ "definition": "CREATE VIEW [dbo].[v_customer_summary] AS SELECT customer_id, name, COUNT(order_id) as order_count, SUM(total) as total_amount FROM dbo.v_customer_orders GROUP BY customer_id, name"
+ },
+ {
+ "name": "v_top_customers",
+ "definition": "CREATE VIEW [dbo].[v_top_customers] AS SELECT TOP 10 * FROM dbo.v_customer_summary ORDER BY total_amount DESC"
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE TABLE [dbo].[customers] (
+ [customer_id] INT NOT NULL,
+ [name] NVARCHAR(100) NOT NULL
+ );
+
+ CREATE TABLE [dbo].[orders] (
+ [order_id] INT NOT NULL,
+ [customer_id] INT NOT NULL,
+ [total] DECIMAL(10,2) NOT NULL
+ );
+
+ GO
+
+ CREATE VIEW [dbo].[v_customer_orders] AS SELECT c.customer_id, c.name, o.order_id, o.total FROM dbo.customers c JOIN dbo.orders o ON c.customer_id = o.customer_id;
+
+ GO
+
+ CREATE VIEW [dbo].[v_customer_summary] AS SELECT customer_id, name, COUNT(order_id) as order_count, SUM(total) as total_amount FROM dbo.v_customer_orders GROUP BY customer_id, name;
+
+ GO
+
+ CREATE VIEW [dbo].[v_top_customers] AS SELECT TOP 10 * FROM dbo.v_customer_summary ORDER BY total_amount DESC;
+
+ GO
+
+- input: |
+ {
+ "schemas": [
+ {
+ "name": "sales",
+ "tables": [
+ {
+ "name": "products",
+ "columns": [
+ {
+ "name": "product_id",
+ "position": 1,
+ "type": "INT",
+ "nullable": false
+ },
+ {
+ "name": "name",
+ "position": 2,
+ "type": "NVARCHAR(100)",
+ "nullable": false
+ }
+ ]
+ }
+ ],
+ "views": [
+ {
+ "name": "v_product_list",
+ "definition": "CREATE VIEW [sales].[v_product_list] AS SELECT product_id, name FROM sales.products"
+ }
+ ]
+ },
+ {
+ "name": "reporting",
+ "views": [
+ {
+ "name": "v_all_products",
+ "definition": "CREATE VIEW [reporting].[v_all_products] AS SELECT * FROM sales.v_product_list"
+ }
+ ]
+ }
+ ]
+ }
+ output: |+
+ CREATE SCHEMA [sales];
+ GO
+
+ CREATE SCHEMA [reporting];
+ GO
+
+ CREATE TABLE [sales].[products] (
+ [product_id] INT NOT NULL,
+ [name] NVARCHAR(100) NOT NULL
+ );
+
+ GO
+
+ CREATE VIEW [sales].[v_product_list] AS SELECT product_id, name FROM sales.products;
+
+ GO
+
+ CREATE VIEW [reporting].[v_all_products] AS SELECT * FROM sales.v_product_list;
+
+ GO
+
diff --git a/backend/plugin/schema/mssql/test-data/test_migration_views.yaml b/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
index 226b03e95c..ec586afbd4 100644
--- a/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
+++ b/backend/plugin/schema/mssql/test-data/test_migration_views.yaml
@@ -19,7 +19,7 @@
CREATE VIEW [dbo].[v_users] AS
SELECT id, name FROM [dbo].[users];
GO
-- description: Create views with dependencies - correct order
+- description: Create views with dependencies - deterministic order
oldSchema: |
CREATE TABLE [dbo].[users] (
[id] int NOT NULL,
@@ -41,15 +41,15 @@
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
+ CREATE VIEW [dbo].[v_orders_with_users] AS
+ SELECT o.id, o.user_id, o.amount, v.name
FROM [dbo].[orders] o
- JOIN [dbo].[users] u ON o.user_id = u.id;
+ JOIN [dbo].[v_users] v ON o.user_id = v.id;
GO
- CREATE VIEW [dbo].[v_user_orders] AS
+ CREATE VIEW [dbo].[v_user_order_summary] 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
+ LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
GROUP BY u.id, u.name;
GO
expected: |
@@ -59,22 +59,22 @@
[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
+ CREATE VIEW [dbo].[v_orders_with_users] AS
+ SELECT o.id, o.user_id, o.amount, v.name
+ FROM [dbo].[orders] o
+ JOIN [dbo].[v_users] v ON o.user_id = v.id;
+ GO
+ CREATE VIEW [dbo].[v_user_order_summary] 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
+ LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
GROUP BY u.id, u.name;
GO
-- description: Drop views with dependencies - reverse order
+- description: Drop views with dependencies - deterministic order
oldSchema: |
CREATE TABLE [dbo].[users] (
[id] int NOT NULL,
@@ -90,15 +90,15 @@
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
+ CREATE VIEW [dbo].[v_orders_with_users] AS
+ SELECT o.id, o.user_id, o.amount, v.name
FROM [dbo].[orders] o
- JOIN [dbo].[users] u ON o.user_id = u.id;
+ JOIN [dbo].[v_users] v ON o.user_id = v.id;
GO
- CREATE VIEW [dbo].[v_user_orders] AS
+ CREATE VIEW [dbo].[v_user_order_summary] 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
+ LEFT JOIN [dbo].[v_orders_with_users] o ON u.id = o.user_id
GROUP BY u.id, u.name;
GO
newSchema: |
@@ -114,11 +114,11 @@
);
GO
expected: |
- DROP VIEW [dbo].[v_user_orders];
+ DROP VIEW [dbo].[v_user_order_summary];
GO
- DROP VIEW [dbo].[v_users];
+ DROP VIEW [dbo].[v_orders_with_users];
GO
- DROP VIEW [dbo].[v_orders];
+ DROP VIEW [dbo].[v_users];
GO
- description: Alter view - drop and recreate
oldSchema: |