Skip to content

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

feat: implement PG column no null value rule (#1953)

rebelice1bdc82a3d4c4
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 82c7258984..2634cd6c41 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -111,6 +111,9 @@ const (
// PostgreSQLNamingFKConvention is an advisor type for PostgreSQL foreign key naming convention.
PostgreSQLNamingFKConvention Type = "bb.plugin.advisor.postgresql.naming.fk"
+ // PostgreSQLColumnNoNull is an advisor type for PostgreSQL column no NULL value.
+ PostgreSQLColumnNoNull Type = "bb.plugin.advisor.postgresql.column.no-null"
+
// PostgreSQLTableRequirePK is an advisor type for PostgreSQL table require primary key.
PostgreSQLTableRequirePK Type = "bb.plugin.advisor.postgresql.table.require-pk"
)
diff --git a/plugin/advisor/pg/advisor_column_no_null.go b/plugin/advisor/pg/advisor_column_no_null.go
new file mode 100644
index 0000000000..c6848b9ae8
--- /dev/null
+++ b/plugin/advisor/pg/advisor_column_no_null.go
@@ -0,0 +1,182 @@
+package pg
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "sort"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/catalog"
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnNoNullAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(advisor.Postgres, advisor.PostgreSQLColumnNoNull, &ColumnNoNullAdvisor{})
+}
+
+// ColumnNoNullAdvisor is the advisor checking for column no NULL value.
+type ColumnNoNullAdvisor struct {
+}
+
+// Check checks for column no NULL value.
+func (adv *ColumnNoNullAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmts, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &columnNoNullChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ catalog: ctx.Catalog,
+ nullableColumns: make(columnMap),
+ }
+
+ for _, stmt := range stmts {
+ ast.Walk(checker, stmt)
+ }
+
+ return checker.generateAdviceList(), nil
+}
+
+type columnNoNullChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ catalog catalog.Catalog
+ nullableColumns columnMap
+}
+
+func (checker *columnNoNullChecker) generateAdviceList() []advisor.Advice {
+ var columnList []columnName
+ for column := range checker.nullableColumns {
+ columnList = append(columnList, column)
+ }
+ if len(columnList) > 0 {
+ // Order it cause the random iteration order in Go, see https://go.dev/blog/maps
+ sort.Slice(columnList, func(i, j int) bool {
+ if columnList[i].schema != columnList[j].schema {
+ return columnList[i].schema < columnList[j].schema
+ }
+ if columnList[i].table != columnList[j].table {
+ return columnList[i].table < columnList[j].table
+ }
+ return columnList[i].column < columnList[j].column
+ })
+ }
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.ColumnCanNotNull,
+ Title: checker.title,
+ Content: fmt.Sprintf(`Column "%s" in %s can not have NULL value`, column.column, column.normalizeTableName()),
+ })
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList
+}
+
+// Visit implements the ast.Visitor interface.
+func (checker *columnNoNullChecker) Visit(node ast.Node) ast.Visitor {
+ switch n := node.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ for _, column := range n.ColumnList {
+ checker.addColumn(n.Name, column.ColumnName)
+ checker.removeColumnByConstraintList(n.Name, column.ConstraintList)
+ }
+ checker.removeColumnByConstraintList(n.Name, n.ConstraintList)
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ for _, item := range n.AlterItemList {
+ switch cmd := item.(type) {
+ // ALTER TABLE ADD COLUMN
+ case *ast.AddColumnListStmt:
+ for _, column := range cmd.ColumnList {
+ checker.addColumn(n.Table, column.ColumnName)
+ checker.removeColumnByConstraintList(n.Table, column.ConstraintList)
+ }
+ // ALTER TABLE ALTER COLUMN SET NOT NULL
+ case *ast.SetNotNullStmt:
+ checker.removeColumn(n.Table, cmd.ColumnName)
+ // ALTER TABLE ALTER COLUMN DROP NOT NULL
+ case *ast.DropNotNullStmt:
+ checker.addColumn(n.Table, cmd.ColumnName)
+ // ALTER TABLE ADD CONSTRAINT
+ case *ast.AddConstraintStmt:
+ checker.removeColumnByConstraintList(n.Table, []*ast.ConstraintDef{cmd.Constraint})
+ }
+ }
+ }
+
+ return checker
+}
+
+func (checker *columnNoNullChecker) addColumn(table *ast.TableDef, column string) {
+ checker.nullableColumns[convertToColumnName(table, column)] = true
+}
+
+func (checker *columnNoNullChecker) removeColumn(table *ast.TableDef, column string) {
+ delete(checker.nullableColumns, convertToColumnName(table, column))
+}
+
+func (checker *columnNoNullChecker) removeColumnByConstraintList(table *ast.TableDef, constraintList []*ast.ConstraintDef) {
+ for _, constraint := range constraintList {
+ switch constraint.Type {
+ case ast.ConstraintTypeNotNull, ast.ConstraintTypePrimary:
+ for _, column := range constraint.KeyList {
+ checker.removeColumn(table, column)
+ }
+ case ast.ConstraintTypePrimaryUsingIndex:
+ index, err := checker.catalog.FindIndex(context.Background(), &catalog.IndexFind{
+ TableName: getTableNameWithSchema(table),
+ IndexName: constraint.IndexName,
+ })
+ if err != nil {
+ log.Printf(
+ "Cannot find index %s in table %s with error %v\n",
+ constraint.IndexName,
+ getTableNameWithSchema(table),
+ err,
+ )
+ continue
+ }
+ if index == nil {
+ continue
+ }
+ for _, column := range index.ColumnExpressions {
+ checker.removeColumn(table, column)
+ }
+ }
+ }
+}
+
+func convertToColumnName(table *ast.TableDef, column string) columnName {
+ colName := columnName{
+ schema: table.Schema,
+ table: table.Name,
+ column: column,
+ }
+ if colName.schema == "" {
+ colName.schema = PostgreSQLPublicSchema
+ }
+ return colName
+}
diff --git a/plugin/advisor/pg/advisor_column_no_null_test.go b/plugin/advisor/pg/advisor_column_no_null_test.go
new file mode 100644
index 0000000000..d4821b5f6d
--- /dev/null
+++ b/plugin/advisor/pg/advisor_column_no_null_test.go
@@ -0,0 +1,123 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestColumnNoNULL(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: "CREATE TABLE book(id int, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "id" in "public"."book" can not have NULL value`,
+ },
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "name" in "public"."book" can not have NULL value`,
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id int, name varchar(255), PRIMARY KEY (id))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "name" in "public"."book" can not have NULL value`,
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id int PRIMARY KEY, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "name" in "public"."book" can not have NULL value`,
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id int NOT NULL, name varchar(255))",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "name" in "public"."book" can not have NULL value`,
+ },
+ },
+ },
+ {
+ Statement: "CREATE TABLE book(id int PRIMARY KEY, name varchar(255) NOT NULL)",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE book ADD COLUMN id int",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "id" in "public"."book" can not have NULL value`,
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE book ADD COLUMN id int PRIMARY KEY, ADD COLUMN name varchar(255) NOT NULL",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE book ALTER COLUMN id SET NOT NULL",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ {
+ Statement: "ALTER TABLE book ALTER COLUMN id DROP NOT NULL",
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Warn,
+ Code: advisor.ColumnCanNotNull,
+ Title: "column.no-null",
+ Content: `Column "id" in "public"."book" can not have NULL value`,
+ },
+ },
+ },
+ }
+
+ advisor.RunSchemaReviewRuleTests(t, tests, &ColumnNoNullAdvisor{}, &advisor.SQLReviewRule{
+ Type: advisor.SchemaRuleColumnNotNull,
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: "",
+ }, &advisor.MockCatalogService{})
+}
diff --git a/plugin/advisor/pg/utils.go b/plugin/advisor/pg/utils.go
new file mode 100644
index 0000000000..834787c588
--- /dev/null
+++ b/plugin/advisor/pg/utils.go
@@ -0,0 +1,36 @@
+package pg
+
+import (
+ "fmt"
+
+ "github.com/bytebase/bytebase/plugin/parser/ast"
+)
+
+const (
+ // PostgreSQLPublicSchema is the string for PostgreSQL public schema
+ PostgreSQLPublicSchema = "public"
+)
+
+type columnName struct {
+ schema string
+ table string
+ column string
+}
+
+func (c columnName) normalizeTableName() string {
+ schema := c.schema
+ if schema == "" {
+ schema = "public"
+ }
+ return fmt.Sprintf(`"%s"."%s"`, schema, c.table)
+}
+
+type columnMap map[columnName]bool
+
+func getTableNameWithSchema(table *ast.TableDef) string {
+ schema := table.Schema
+ if schema == "" {
+ schema = "public"
+ }
+ return fmt.Sprintf("%s.%s", schema, table.Name)
+}
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index d821d78216..a786f619ba 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -363,6 +363,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine DBType) (Type, erro
switch engine {
case MySQL, TiDB:
return MySQLColumnNoNull, nil
+ case Postgres:
+ return PostgreSQLColumnNoNull, nil
}
case SchemaRuleTableRequirePK:
switch engine {
diff --git a/plugin/parser/ast/utils.go b/plugin/parser/ast/utils.go
index 8a002e872b..c31e7962c1 100644
--- a/plugin/parser/ast/utils.go
+++ b/plugin/parser/ast/utils.go
@@ -67,6 +67,10 @@ func Walk(v Visitor, node Node) {
for _, indexDef := range n.IndexList {
Walk(v, indexDef)
}
+ case *DropNotNullStmt:
+ if n.Table != nil {
+ Walk(v, n.Table)
+ }
case *DropTableStmt:
for _, tableDef := range n.TableList {
Walk(v, tableDef)
@@ -99,6 +103,10 @@ func Walk(v Visitor, node Node) {
if n.Table != nil {
Walk(v, n.Table)
}
+ case *SetNotNullStmt:
+ if n.Table != nil {
+ Walk(v, n.Table)
+ }
case *TableDef:
}
}