Skip to content

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

feat(sql-review, mssql): support column not null sql review rule for mssql (#7162)

h3n4lc7a3d963c538
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index acf5f12ac2..39edf9b267 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -464,6 +464,9 @@ const (
// MSSQLTableRequirePK is an advisor type for MSSQL table require primary key.
MSSQLTableRequirePK Type = "bb.plugin.advisor.mssql.table.require-pk"
+
+ // MSSQLColumnNoNull is an advisor type for MSSQL column no NULL value.
+ MSSQLColumnNoNull Type = "bb.plugin.advisor.mssql.column.no-null"
)
// Advice is the result of an advisor.
diff --git a/backend/plugin/advisor/mssql/advisor_column_no_null.go b/backend/plugin/advisor/mssql/advisor_column_no_null.go
new file mode 100644
index 0000000000..9afe70d591
--- /dev/null
+++ b/backend/plugin/advisor/mssql/advisor_column_no_null.go
@@ -0,0 +1,188 @@
+// Package mssql is the advisor for MSSQL database.
+package mssql
+
+import (
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/tsql-parser"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"
+ bbparser "github.com/bytebase/bytebase/backend/plugin/parser/sql"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnNoNullAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(db.MSSQL, advisor.MSSQLColumnNoNull, &ColumnNoNullAdvisor{})
+}
+
+// ColumnNoNullAdvisor is the advisor checking for column no NULL value..
+type ColumnNoNullAdvisor struct {
+}
+
+// Check checks for column no NULL value..
+func (*ColumnNoNullAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ tree, ok := ctx.AST.(antlr.Tree)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to Tree")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ listener := &columnNoNullChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ currentNormalizedTableName: "",
+ isCurrentTableColumnNullable: make(map[string]bool),
+ currentTableColumnIsNullableLine: make(map[string]int),
+ adviceList: make([]advisor.Advice, 0),
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+
+ return listener.generateAdvice()
+}
+
+// columnNoNullChecker is the listener for column no NULL value.
+type columnNoNullChecker struct {
+ *parser.BaseTSqlParserListener
+
+ level advisor.Status
+ title string
+ // currentNormalizedTableName is the normalized table name of the current table.
+ currentNormalizedTableName string
+ // isCurrentTableColumnNullable is the map of column name to whether the column is nullable.
+ isCurrentTableColumnNullable map[string]bool
+ // currentTableColumnIsNullableLine is the map of column name to the line number of the column definition.
+ currentTableColumnIsNullableLine map[string]int
+
+ adviceList []advisor.Advice
+}
+
+// generateAdvice returns the advices generated by the listener, the advices must not be empty.
+func (l *columnNoNullChecker) generateAdvice() ([]advisor.Advice, error) {
+ if len(l.adviceList) == 0 {
+ l.adviceList = append(l.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return l.adviceList, nil
+}
+
+// EnterCreate_table is called when production create_table is entered.
+func (l *columnNoNullChecker) EnterCreate_table(ctx *parser.Create_tableContext) {
+ tableName := ctx.Table_name()
+ if tableName == nil {
+ return
+ }
+ normalizedTableName := bbparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
+
+ l.currentNormalizedTableName = normalizedTableName
+}
+
+// ExitCreate_table is called when production create_table is exited.
+func (l *columnNoNullChecker) ExitCreate_table(_ *parser.Create_tableContext) {
+ l.currentNormalizedTableName = ""
+ for columnName, isNullable := range l.isCurrentTableColumnNullable {
+ if !isNullable {
+ continue
+ }
+ l.adviceList = append(l.adviceList, advisor.Advice{
+ Status: l.level,
+ Code: advisor.ColumnCannotNull,
+ Title: l.title,
+ Content: fmt.Sprintf("Column [%s] is nullable, which is not allowed.", columnName),
+ Line: l.currentTableColumnIsNullableLine[columnName],
+ })
+ }
+
+ l.isCurrentTableColumnNullable = make(map[string]bool)
+ l.currentTableColumnIsNullableLine = make(map[string]int)
+}
+
+// EnterTable_constraint is called when production table_constraint is entered.
+func (l *columnNoNullChecker) EnterTable_constraint(ctx *parser.Table_constraintContext) {
+ parent := ctx.GetParent()
+ switch parent.(type) {
+ case *parser.Column_def_table_constraintContext:
+ default:
+ return
+ }
+ if ctx.PRIMARY() != nil {
+ allColumns := ctx.Column_name_list_with_order().AllId_()
+ for _, column := range allColumns {
+ columnName := bbparser.NormalizeTSQLIdentifier(column)
+ l.isCurrentTableColumnNullable[columnName] = false
+ }
+ }
+}
+
+// EnterColumn_definition is called when production column_definition is entered.
+func (l *columnNoNullChecker) EnterColumn_definition(ctx *parser.Column_definitionContext) {
+ parent := ctx.GetParent()
+ switch parent.(type) {
+ case *parser.Alter_tableContext:
+ case *parser.Column_def_table_constraintContext:
+ default:
+ return
+ }
+ columnName := bbparser.NormalizeTSQLIdentifier(ctx.Id_())
+ l.isCurrentTableColumnNullable[columnName] = true
+ l.currentTableColumnIsNullableLine[columnName] = ctx.Id_().GetStart().GetLine()
+ allColumnDefinitionElements := ctx.AllColumn_definition_element()
+ for _, columnDefinitionElement := range allColumnDefinitionElements {
+ if v := columnDefinitionElement.Column_constraint(); v != nil {
+ if v.PRIMARY() != nil {
+ l.isCurrentTableColumnNullable[columnName] = false
+ break
+ }
+ if (v.Null_notnull() != nil && v.Null_notnull().NOT() != nil) || v.Null_notnull() == nil {
+ l.isCurrentTableColumnNullable[columnName] = false
+ break
+ }
+ }
+ }
+}
+
+// EnterAlter_table is called when production alter_table is entered.
+func (l *columnNoNullChecker) EnterAlter_table(ctx *parser.Alter_tableContext) {
+ tableName := ctx.Table_name(0)
+ if tableName == nil {
+ return
+ }
+ if (len(ctx.AllALTER()) == 2 && ctx.COLUMN() != nil) /* ALTER COLUMN */ || (len(ctx.AllALTER()) == 1 && ctx.ADD() != nil && ctx.WITH() == nil) /* ALTER */ {
+ normalizedTableName := bbparser.NormalizeTSQLTableName(tableName, "" /* fallbackDatabase */, "dbo" /* fallbackSchema */, false /* caseSensitive */)
+ l.currentNormalizedTableName = normalizedTableName
+ }
+}
+
+// ExitAlter_table is called when production alter_table is exited.
+func (l *columnNoNullChecker) ExitAlter_table(_ *parser.Alter_tableContext) {
+ l.currentNormalizedTableName = ""
+ for columnName, isNullable := range l.isCurrentTableColumnNullable {
+ if !isNullable {
+ continue
+ }
+ l.adviceList = append(l.adviceList, advisor.Advice{
+ Status: l.level,
+ Code: advisor.ColumnCannotNull,
+ Title: l.title,
+ Content: fmt.Sprintf("Column [%s] is nullable, which is not allowed.", columnName),
+ Line: l.currentTableColumnIsNullableLine[columnName],
+ })
+ }
+
+ l.isCurrentTableColumnNullable = make(map[string]bool)
+ l.currentTableColumnIsNullableLine = make(map[string]int)
+}
diff --git a/backend/plugin/advisor/mssql/mssql_rules_test.go b/backend/plugin/advisor/mssql/mssql_rules_test.go
index aede69d88f..20e8c37aee 100644
--- a/backend/plugin/advisor/mssql/mssql_rules_test.go
+++ b/backend/plugin/advisor/mssql/mssql_rules_test.go
@@ -18,6 +18,7 @@ func TestMSSQLRules(t *testing.T) {
advisor.SchemaRuleColumnMaximumVarcharLength,
advisor.SchemaRuleTableDropNamingConvention,
advisor.SchemaRuleTableRequirePK,
+ advisor.SchemaRuleColumnNotNull,
}
for _, rule := range snowflakeRules {
diff --git a/backend/plugin/advisor/mssql/test/column_no_null.yaml b/backend/plugin/advisor/mssql/test/column_no_null.yaml
new file mode 100644
index 0000000000..57370d5404
--- /dev/null
+++ b/backend/plugin/advisor/mssql/test/column_no_null.yaml
@@ -0,0 +1,75 @@
+- statement: |-
+ CREATE TABLE MyTable (
+ Id INT PRIMARY KEY,
+ Name VARCHAR(100) NOT NULL,
+ Age INT,
+ Address VARCHAR(200)
+ );
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: Column [age] is nullable, which is not allowed.
+ line: 4
+ details: ""
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: Column [address] is nullable, which is not allowed.
+ line: 5
+ details: ""
+- statement: |-
+ CREATE TABLE MyTable (
+ Id INT,
+ Name VARCHAR(100) NOT NULL,
+ Age INT,
+ Address VARCHAR(200),
+ PRIMARY KEY (Id, Age)
+ );
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: Column [address] is nullable, which is not allowed.
+ line: 5
+ details: ""
+- statement: ALTER TABLE MyTable ALTER COLUMN Name VARCHAR(100) NULL;
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: Column [name] is nullable, which is not allowed.
+ line: 1
+ details: ""
+- statement: ALTER TABLE MyTable ALTER COLUMN Name VARCHAR(100) NOT NULL;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE MyTable ADD Age INT;
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: Column [age] is nullable, which is not allowed.
+ line: 1
+ details: ""
+- statement: ALTER TABLE MyTable ADD Age INT NULL;
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: Column [age] is nullable, which is not allowed.
+ line: 1
+ details: ""
+- statement: ALTER TABLE MyTable ADD Age INT NOT NULL;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index a803f7b9d7..f6be5135b6 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -1193,6 +1193,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
return OracleColumnNoNull, nil
case db.Snowflake:
return SnowflakeColumnNoNull, nil
+ case db.MSSQL:
+ return MSSQLColumnNoNull, nil
}
case SchemaRuleColumnDisallowChangeType:
switch engine {
diff --git a/frontend/src/types/sql-review-schema.yaml b/frontend/src/types/sql-review-schema.yaml
index 47ec73a9cf..571c198c6a 100644
--- a/frontend/src/types/sql-review-schema.yaml
+++ b/frontend/src/types/sql-review-schema.yaml
@@ -371,6 +371,7 @@ ruleList:
- ORACLE
- OCEANBASE
- SNOWFLAKE
+ - MSSQL
componentList: []
- type: column.disallow-change-type
category: COLUMN