Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(advisor): implement PG maximum-char-length rule (#4138)
rebelicee53444ec9580
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex 2d87930013..481f7520e8 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -271,6 +271,9 @@ const (// PostgreSQLColumnDisallowChangingType is an advisor type for PostgreSQL disallow changing column type.PostgreSQLColumnDisallowChangingType Type = "bb.plugin.advisor.postgresql.column.disallow-changing-type"++ // PostgreSQLColumnMaximumCharacterLength is an advisor type for PostgreSQL maximum character length.+ PostgreSQLColumnMaximumCharacterLength Type = "bb.plugin.advisor.postgresql.column.maximum-character-length")// Advice is the result of an advisor.diff --git a/plugin/advisor/pg/advisor_column_maximum_character_length.go b/plugin/advisor/pg/advisor_column_maximum_character_length.gonew file mode 100644index 0000000000..2287ad27e0--- /dev/null+++ b/plugin/advisor/pg/advisor_column_maximum_character_length.go@@ -0,0 +1,131 @@+package pg++// Framework code is generated by the generator.++import (+ "fmt"++ "github.com/bytebase/bytebase/plugin/advisor"+ "github.com/bytebase/bytebase/plugin/advisor/db"+ "github.com/bytebase/bytebase/plugin/parser/ast"+)++var (+ _ advisor.Advisor = (*ColumnMaximumCharacterLengthAdvisor)(nil)+ _ ast.Visitor = (*columnMaximumCharacterLengthChecker)(nil)+)++func init() {+ advisor.Register(db.Postgres, advisor.PostgreSQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})+}++// ColumnMaximumCharacterLengthAdvisor is the advisor checking for maximum character length.+type ColumnMaximumCharacterLengthAdvisor struct {+}++// Check checks for maximum character length.+func (*ColumnMaximumCharacterLengthAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {+ stmtList, errAdvice := parseStatement(statement)+ if errAdvice != nil {+ return errAdvice, nil+ }++ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)+ if err != nil {+ return nil, err+ }+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)+ if err != nil {+ return nil, err+ }+ checker := &columnMaximumCharacterLengthChecker{+ level: level,+ title: string(ctx.Rule.Type),+ maximum: payload.Number,+ }++ if payload.Number > 0 {+ for _, stmt := range stmtList {+ ast.Walk(checker, stmt)+ }+ }++ if len(checker.adviceList) == 0 {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: advisor.Success,+ Code: advisor.Ok,+ Title: "OK",+ Content: "",+ })+ }+ return checker.adviceList, nil+}++type columnMaximumCharacterLengthChecker struct {+ adviceList []advisor.Advice+ level advisor.Status+ title string+ maximum int+}++// Visit implements ast.Visitor interface.+func (checker *columnMaximumCharacterLengthChecker) Visit(in ast.Node) ast.Visitor {+ var tableName, columnName string+ var line int+ switch node := in.(type) {+ case *ast.CreateTableStmt:+ for _, column := range node.ColumnList {+ charLength := getCharLength(column)+ if charLength > checker.maximum {+ tableName = normalizeTableName(node.Name, "")+ columnName = column.ColumnName+ line = column.LastLine()+ break+ }+ }+ case *ast.AlterTableStmt:+ for _, item := range node.AlterItemList {+ switch itemNode := item.(type) {+ case *ast.AddColumnListStmt:+ for _, column := range itemNode.ColumnList {+ charLength := getCharLength(column)+ if charLength > checker.maximum {+ tableName = normalizeTableName(node.Table, "")+ columnName = column.ColumnName+ line = itemNode.LastLine()+ }+ }+ case *ast.AlterColumnTypeStmt:+ if char, ok := itemNode.Type.(*ast.Character); ok {+ if char.Size > checker.maximum {+ tableName = normalizeTableName(node.Table, "")+ columnName = itemNode.ColumnName+ line = itemNode.LastLine()+ }+ }+ }+ if tableName != "" {+ break+ }+ }+ }++ if tableName != "" {+ checker.adviceList = append(checker.adviceList, advisor.Advice{+ Status: checker.level,+ Code: advisor.CharLengthExceedsLimit,+ Title: checker.title,+ Content: fmt.Sprintf(`The length of the CHAR column %q in table %s is bigger than %d, please use VARCHAR instead`, columnName, tableName, checker.maximum),+ Line: line,+ })+ }++ return checker+}++func getCharLength(column *ast.ColumnDef) int {+ if char, ok := column.Type.(*ast.Character); ok {+ return char.Size+ }+ return 0+}diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.goindex a656fa9b60..1b78968a71 100644--- a/plugin/advisor/pg/pg_rules_test.go+++ b/plugin/advisor/pg/pg_rules_test.go@@ -32,6 +32,7 @@ func TestPostgreSQLRules(t *testing.T) {advisor.SchemaRuleColumnDisallowChangeType,advisor.SchemaRuleTableDisallowPartition,advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist,+ advisor.SchemaRuleColumnMaximumCharacterLength,}for _, rule := range pgRules {diff --git a/plugin/advisor/pg/test/column_maximum_character_length.yaml b/plugin/advisor/pg/test/column_maximum_character_length.yamlnew file mode 100644index 0000000000..2e2b2da4c2--- /dev/null+++ b/plugin/advisor/pg/test/column_maximum_character_length.yaml@@ -0,0 +1,35 @@+- statement: CREATE TABLE t(name char(20));+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+- statement: CREATE TABLE t(name varchar(225));+ want:+ - status: SUCCESS+ code: 0+ title: OK+ content: ""+ line: 0+- statement: CREATE TABLE t(name char(225));+ want:+ - status: WARN+ code: 415+ title: column.maximum-character-length+ content: The length of the CHAR column "name" in table "t" is bigger than 20, please use VARCHAR instead+ line: 1+- statement: ALTER TABLE public.tech_book ADD COLUMN name_2 char(225)+ want:+ - status: WARN+ code: 415+ title: column.maximum-character-length+ content: The length of the CHAR column "name_2" in table "public"."tech_book" is bigger than 20, please use VARCHAR instead+ line: 1+- statement: ALTER TABLE tech_book ALTER COLUMN name SET DATA TYPE char(225)+ want:+ - status: WARN+ code: 415+ title: column.maximum-character-length+ content: The length of the CHAR column "name" in table "tech_book" is bigger than 20, please use VARCHAR instead+ line: 1diff --git a/plugin/advisor/pg/utils.go b/plugin/advisor/pg/utils.goindex 1102dcf57c..7514c04d4b 100644--- a/plugin/advisor/pg/utils.go+++ b/plugin/advisor/pg/utils.go@@ -3,6 +3,8 @@ package pgimport ("fmt"++ "github.com/bytebase/bytebase/plugin/parser/ast")const (@@ -32,3 +34,15 @@ func normalizeSchemaName(name string) string {}return "public"}++func normalizeTableName(table *ast.TableDef, defaultSchema string) string {+ schema := table.Schema+ if schema == "" && defaultSchema != "" {+ schema = defaultSchema+ }++ if schema == "" {+ return fmt.Sprintf("%q", table.Name)+ }+ return fmt.Sprintf("%q.%q", schema, table.Name)+}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex 358dc6bd49..369e5f54e5 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -758,6 +758,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errswitch engine {case db.MySQL, db.TiDB:return MySQLColumnMaximumCharacterLength, nil+ case db.Postgres:+ return PostgreSQLColumnMaximumCharacterLength, nil}case SchemaRuleColumnAutoIncrementInitialValue:switch engine {