Skip to content

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

chore: mssql resource (#13281)

Danny Xu8ccfa5157026
diff --git a/backend/common/util.go b/backend/common/util.go
index 556e7665d5..f2a17cd627 100644
--- a/backend/common/util.go
+++ b/backend/common/util.go
@@ -57,6 +57,7 @@ var (
storepb.Engine_OCEANBASE: true,
storepb.Engine_ORACLE: true,
storepb.Engine_OCEANBASE_ORACLE: true,
+ storepb.Engine_MSSQL: true,
}
)
diff --git a/backend/plugin/parser/tsql/resource_change.go b/backend/plugin/parser/tsql/resource_change.go
new file mode 100644
index 0000000000..4bde2ac7e7
--- /dev/null
+++ b/backend/plugin/parser/tsql/resource_change.go
@@ -0,0 +1,286 @@
+package tsql
+
+import (
+ "strings"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/tsql-parser"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/store/model"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func init() {
+ base.RegisterExtractChangedResourcesFunc(storepb.Engine_MSSQL, extractChangedResources)
+}
+
+func extractChangedResources(currentDatabase string, currentSchema string, dbSchema *model.DBSchema, asts any, statement string) (*base.ChangeSummary, error) {
+ parseResult, ok := asts.(*ParseResult)
+ if !ok {
+ return nil, errors.Errorf("failed to convert ast to antlr.Tree")
+ }
+
+ changedResources := model.NewChangedResources(dbSchema)
+ l := &tsqlChangedResourceExtractListener{
+ currentDatabase: currentDatabase,
+ currentSchema: currentSchema,
+ dbSchema: dbSchema,
+ changedResources: changedResources,
+ statement: statement,
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(l, parseResult.Tree)
+
+ return &base.ChangeSummary{
+ ChangedResources: changedResources,
+ SampleDMLS: l.sampleDMLs,
+ DMLCount: l.dmlCount,
+ InsertCount: l.insertCount,
+ }, nil
+}
+
+type tsqlChangedResourceExtractListener struct {
+ *parser.BaseTSqlParserListener
+
+ currentDatabase string
+ currentSchema string
+ dbSchema *model.DBSchema
+ changedResources *model.ChangedResources
+ statement string
+ sampleDMLs []string
+ dmlCount int
+ insertCount int
+
+ // Internal data structure used temporarily.
+ text string
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterSql_clauses(ctx *parser.Sql_clausesContext) {
+ l.text = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterCreate_table(ctx *parser.Create_tableContext) {
+ tableName := ctx.Table_name()
+ if tableName == nil {
+ return
+ }
+ d, s, t := normalizeTableNameSeparated(tableName, l.currentDatabase, l.currentSchema, false /* caseSensitive */)
+
+ l.changedResources.AddTable(
+ d,
+ s,
+ &storepb.ChangedResourceTable{
+ Name: t,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ false)
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterDrop_table(ctx *parser.Drop_tableContext) {
+ if ctx.AllTable_name() == nil {
+ return
+ }
+
+ for _, tableName := range ctx.AllTable_name() {
+ d, s, t := normalizeTableNameSeparated(tableName, l.currentDatabase, l.currentSchema, false /* caseSensitive */)
+
+ l.changedResources.AddTable(
+ d,
+ s,
+ &storepb.ChangedResourceTable{
+ Name: t,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ true)
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterAlter_table(ctx *parser.Alter_tableContext) {
+ if ctx.AllTable_name() == nil {
+ return
+ }
+
+ for _, tableName := range ctx.AllTable_name() {
+ d, s, t := normalizeTableNameSeparated(tableName, l.currentDatabase, l.currentSchema, false /* caseSensitive */)
+
+ l.changedResources.AddTable(
+ d,
+ s,
+ &storepb.ChangedResourceTable{
+ Name: t,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ true)
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterCreate_index(ctx *parser.Create_indexContext) {
+ tableName := ctx.Table_name()
+ if tableName == nil {
+ return
+ }
+ d, s, t := normalizeTableNameSeparated(tableName, l.currentDatabase, l.currentSchema, false /* caseSensitive */)
+
+ l.changedResources.AddTable(
+ d,
+ s,
+ &storepb.ChangedResourceTable{
+ Name: t,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ false)
+}
+
+// EnterDrop_index is called when production drop_index is entered.
+func (l *tsqlChangedResourceExtractListener) EnterDrop_index(ctx *parser.Drop_indexContext) {
+ for _, index := range ctx.AllDrop_relational_or_xml_or_spatial_index() {
+ fullTable, err := NormalizeFullTableName(index.Full_table_name())
+ if err != nil {
+ continue
+ }
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ s, _ := NormalizeTSQLIdentifierText(l.currentSchema)
+ if fullTable.Database != "" {
+ d = fullTable.Database
+ }
+ if fullTable.Schema != "" {
+ s = fullTable.Schema
+ }
+
+ l.changedResources.AddTable(
+ d,
+ s,
+ &storepb.ChangedResourceTable{
+ Name: fullTable.Table,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ false)
+ }
+}
+
+// EnterCreate_view is called when production create_view is entered.
+func (l *tsqlChangedResourceExtractListener) EnterCreate_view(ctx *parser.Create_viewContext) {
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ schema, name := normalizeSimpleNameSeparated(ctx.Simple_name(), l.currentSchema, false)
+ l.changedResources.AddView(
+ d,
+ schema,
+ &storepb.ChangedResourceView{
+ Name: name,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ )
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterDrop_view(ctx *parser.Drop_viewContext) {
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ for _, simpleName := range ctx.AllSimple_name() {
+ schema, name := normalizeSimpleNameSeparated(simpleName, l.currentSchema, false)
+ l.changedResources.AddView(
+ d,
+ schema,
+ &storepb.ChangedResourceView{
+ Name: name,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ )
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterCreate_or_alter_procedure(ctx *parser.Create_or_alter_procedureContext) {
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ schema, procedure := normalizeProcedureSeparated(ctx.GetProcName(), l.currentSchema, false)
+
+ l.changedResources.AddProcedure(
+ d,
+ schema,
+ &storepb.ChangedResourceProcedure{
+ Name: procedure,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ )
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterDrop_procedure(ctx *parser.Drop_procedureContext) {
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ for _, functionName := range ctx.AllFunc_proc_name_schema() {
+ schema, function := normalizeProcedureSeparated(functionName, l.currentSchema, false)
+
+ l.changedResources.AddFunction(
+ d,
+ schema,
+ &storepb.ChangedResourceFunction{
+ Name: function,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ )
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterCreate_or_alter_function(ctx *parser.Create_or_alter_functionContext) {
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ schema, function := normalizeProcedureSeparated(ctx.GetFuncName(), l.currentSchema, false)
+
+ l.changedResources.AddFunction(
+ d,
+ schema,
+ &storepb.ChangedResourceFunction{
+ Name: function,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ )
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterDrop_function(ctx *parser.Drop_functionContext) {
+ d, _ := NormalizeTSQLIdentifierText(l.currentDatabase)
+ for _, functionName := range ctx.AllFunc_proc_name_schema() {
+ schema, function := normalizeProcedureSeparated(functionName, l.currentSchema, false)
+
+ l.changedResources.AddFunction(
+ d,
+ schema,
+ &storepb.ChangedResourceFunction{
+ Name: function,
+ Ranges: []*storepb.Range{base.NewRange(l.statement, trimStatement(l.text))},
+ },
+ )
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterInsert_statement(ctx *parser.Insert_statementContext) {
+ if ctx.Insert_statement_value() != nil && ctx.Insert_statement_value().Derived_table() != nil && ctx.Insert_statement_value().Derived_table().Table_value_constructor() != nil {
+ tvc := ctx.Insert_statement_value().Derived_table().Table_value_constructor()
+ l.insertCount += len(tvc.AllExpression_list_())
+ return
+ }
+
+ // Track DMLs.
+ l.dmlCount++
+ if len(l.sampleDMLs) < common.MaximumLintExplainSize {
+ l.sampleDMLs = append(l.sampleDMLs, trimStatement(l.text))
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterUpdate_statement(_ *parser.Update_statementContext) {
+ // Track DMLs.
+ l.dmlCount++
+ if len(l.sampleDMLs) < common.MaximumLintExplainSize {
+ l.sampleDMLs = append(l.sampleDMLs, trimStatement(l.text))
+ }
+}
+
+func (l *tsqlChangedResourceExtractListener) EnterDelete_statement(_ *parser.Delete_statementContext) {
+ // Track DMLs.
+ l.dmlCount++
+ if len(l.sampleDMLs) < common.MaximumLintExplainSize {
+ l.sampleDMLs = append(l.sampleDMLs, trimStatement(l.text))
+ }
+}
+
+func trimStatement(statement string) string {
+ // TODO(d): why test is "UPDATE t1 SET c1 = 5\n;".
+ return strings.TrimLeft(strings.TrimRight(statement, " ;\n\t"), " \n\t") + ";"
+}
diff --git a/backend/plugin/parser/tsql/resource_change_test.go b/backend/plugin/parser/tsql/resource_change_test.go
new file mode 100644
index 0000000000..ba86b8e1c2
--- /dev/null
+++ b/backend/plugin/parser/tsql/resource_change_test.go
@@ -0,0 +1,48 @@
+package tsql
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/store/model"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+func TestExtractChangedResources(t *testing.T) {
+ statement := `CREATE TABLE t1 (c1 INT);
+ DROP TABLE t1;
+ ALTER TABLE t1 ADD colb INT;
+ INSERT INTO t1 (c1) VALUES (1), (5);
+ UPDATE t1 SET c1 = 5;
+ `
+ changedResources := model.NewChangedResources(nil /* dbSchema */)
+ changedResources.AddTable(
+ "DB",
+ "OBO",
+ &storepb.ChangedResourceTable{
+ Name: "t1",
+ Ranges: []*storepb.Range{
+ {Start: 0, End: 25},
+ {Start: 27, End: 41},
+ {Start: 43, End: 71},
+ },
+ },
+ true,
+ )
+ want := &base.ChangeSummary{
+ ChangedResources: changedResources,
+ SampleDMLS: []string{
+ "UPDATE t1 SET c1 = 5;",
+ },
+ DMLCount: 1,
+ InsertCount: 2,
+ }
+
+ asts, err := ParseTSQL(statement)
+ require.NoError(t, err)
+ got, err := extractChangedResources("DB", "OBO", nil /* dbSchema */, asts, statement)
+ require.NoError(t, err)
+ require.Equal(t, want, got)
+}
diff --git a/backend/plugin/parser/tsql/tsql.go b/backend/plugin/parser/tsql/tsql.go
index 0a90f354fe..6de0b7541e 100644
--- a/backend/plugin/parser/tsql/tsql.go
+++ b/backend/plugin/parser/tsql/tsql.go
@@ -54,6 +54,22 @@ func ParseTSQL(statement string) (*ParseResult, error) {
return result, nil
}
+func normalizeSimpleNameSeparated(ctx parser.ISimple_nameContext, fallbackSchemaName string, _ bool) (string, string) {
+ schema := fallbackSchemaName
+ name := ""
+ if s := ctx.GetSchema(); s != nil {
+ if id, _ := NormalizeTSQLIdentifier(s); id != "" {
+ schema = id
+ }
+ }
+ if t := ctx.GetName(); t != nil {
+ if id, _ := NormalizeTSQLIdentifier(t); id != "" {
+ name = id
+ }
+ }
+ return schema, name
+}
+
func normalizeTableNameSeparated(ctx parser.ITable_nameContext, fallbackDatabaseName, fallbackSchemaName string, _ bool) (string, string, string) {
database := fallbackDatabaseName
schema := fallbackSchemaName
@@ -92,6 +108,22 @@ func NormalizeTSQLTableName(ctx parser.ITable_nameContext, fallbackDatabaseName,
return strings.Join(tableNameParts, ".")
}
+func normalizeProcedureSeparated(ctx parser.IFunc_proc_name_schemaContext, fallbackSchemaName string, _ bool) (string, string) {
+ schema := fallbackSchemaName
+ name := ""
+ if s := ctx.GetSchema(); s != nil {
+ if id, _ := NormalizeTSQLIdentifier(s); id != "" {
+ schema = id
+ }
+ }
+ if t := ctx.GetProcedure(); t != nil {
+ if id, _ := NormalizeTSQLIdentifier(t); id != "" {
+ name = id
+ }
+ }
+ return schema, name
+}
+
// NormalizeTSQLIdentifier returns the normalized identifier.
// https://learn.microsoft.com/zh-cn/sql/relational-databases/databases/database-identifiers?view=sql-server-ver15
// TODO(zp): currently, we returns the lowercase and original of the part, we may need to get the CI/CS from the server/database.
diff --git a/backend/runner/plancheck/statement_report_executor.go b/backend/runner/plancheck/statement_report_executor.go
index 934f0b2b04..9de35b538d 100644
--- a/backend/runner/plancheck/statement_report_executor.go
+++ b/backend/runner/plancheck/statement_report_executor.go
@@ -204,6 +204,8 @@ func (e *StatementReportExecutor) runReport(ctx context.Context, instance *store
explainCalculator = od.CountAffectedRows
defaultSchema = database.DatabaseName
+ case storepb.Engine_MSSQL:
+ defaultSchema = "OBO"
default:
// Already checked in the Run().
return nil, nil
@@ -237,14 +239,16 @@ func calculateAffectedRows(ctx context.Context, changeSummary *base.ChangeSummar
var totalAffectedRows int64
// Count DMLs.
sampleCount := 0
- for _, dml := range changeSummary.SampleDMLS {
- count, err := explainCalculator(ctx, dml)
- if err != nil {
- slog.Error("failed to calculate affected rows", log.BBError(err))
- continue
+ if explainCalculator != nil {
+ for _, dml := range changeSummary.SampleDMLS {
+ count, err := explainCalculator(ctx, dml)
+ if err != nil {
+ slog.Error("failed to calculate affected rows", log.BBError(err))
+ continue
+ }
+ sampleCount++
+ totalAffectedRows += count
}
- sampleCount++
- totalAffectedRows += count
}
if sampleCount > 0 {
totalAffectedRows = int64((float64(totalAffectedRows) / float64(sampleCount)) * float64(changeSummary.DMLCount))