Skip to content

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

feat(advisor): implement PG collation allowlist rule (#4214)

rebelice252e4ae958c5
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index 8ec316dae7..fa9d8b46f0 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -289,6 +289,9 @@ const (
// PostgreSQLTableDropNamingConvention is an advisor type for PostgreSQL table drop with naming convention.
PostgreSQLTableDropNamingConvention Type = "bb.plugin.advisor.postgresql.table.drop-naming-convention"
+
+ // PostgreSQLCollationAllowlist is an advisor type for PostgreSQL collation allowlist.
+ PostgreSQLCollationAllowlist Type = "bb.plugin.advisor.postgresql.collation.allowlist"
)
// Advice is the result of an advisor.
diff --git a/plugin/advisor/pg/advisor_collation_allowlist.go b/plugin/advisor/pg/advisor_collation_allowlist.go
new file mode 100644
index 0000000000..95c2e47c25
--- /dev/null
+++ b/plugin/advisor/pg/advisor_collation_allowlist.go
@@ -0,0 +1,133 @@
+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 = (*CollationAllowlistAdvisor)(nil)
+ _ ast.Visitor = (*collationAllowlistChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLCollationAllowlist, &CollationAllowlistAdvisor{})
+}
+
+// CollationAllowlistAdvisor is the advisor checking for collation allowlist.
+type CollationAllowlistAdvisor struct {
+}
+
+// Check checks for collation allowlist.
+func (*CollationAllowlistAdvisor) 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.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &collationAllowlistChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ allowlist: make(map[string]bool),
+ }
+ for _, collation := range payload.List {
+ checker.allowlist[collation] = true
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = advisor.NormalizeStatement(stmt.Text())
+ 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 collationAllowlistChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ allowlist map[string]bool
+}
+
+// Visit implements ast.Visitor interface.
+func (checker *collationAllowlistChecker) Visit(in ast.Node) ast.Visitor {
+ code := advisor.Ok
+ line := 0
+ disabledCollation := ""
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.ColumnList {
+ if column.Collation != nil {
+ if _, exists := checker.allowlist[column.Collation.Name]; !exists {
+ code = advisor.DisabledCollation
+ line = column.LastLine()
+ disabledCollation = column.Collation.Name
+ break
+ }
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, item := range node.AlterItemList {
+ switch itemNode := item.(type) {
+ case *ast.AddColumnListStmt:
+ for _, column := range itemNode.ColumnList {
+ if column.Collation != nil {
+ if _, exists := checker.allowlist[column.Collation.Name]; !exists {
+ code = advisor.DisabledCollation
+ line = node.LastLine()
+ disabledCollation = column.Collation.Name
+ break
+ }
+ }
+ }
+ case *ast.AlterColumnTypeStmt:
+ if itemNode.Collation != nil {
+ if _, exists := checker.allowlist[itemNode.Collation.Name]; !exists {
+ code = advisor.DisabledCollation
+ line = node.LastLine()
+ disabledCollation = itemNode.Collation.Name
+ break
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ break
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("Use disabled collation \"%s\", related statement \"%s\"", disabledCollation, checker.text),
+ Line: line,
+ })
+ }
+
+ return checker
+}
diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.go
index 5deda25a48..f80866b0de 100644
--- a/plugin/advisor/pg/pg_rules_test.go
+++ b/plugin/advisor/pg/pg_rules_test.go
@@ -38,6 +38,7 @@ func TestPostgreSQLRules(t *testing.T) {
advisor.SchemaRuleStatementInsertMustSpecifyColumn,
advisor.SchemaRuleStatementInsertDisallowOrderByRand,
advisor.SchemaRuleTableDropNamingConvention,
+ advisor.SchemaRuleCollationAllowlist,
}
for _, rule := range pgRules {
diff --git a/plugin/advisor/pg/test/system_collation_allowlist.yaml b/plugin/advisor/pg/test/system_collation_allowlist.yaml
new file mode 100644
index 0000000000..9dd31f1066
--- /dev/null
+++ b/plugin/advisor/pg/test/system_collation_allowlist.yaml
@@ -0,0 +1,28 @@
+- statement: CREATE TABLE t(a text COLLATE utf8mb4_0900_ai_ci)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: CREATE TABLE t(a text COLLATE "unknown")
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: Use disabled collation "unknown", related statement "CREATE TABLE t(a text COLLATE "unknown")"
+ line: 1
+- statement: ALTER TABLE t ADD COLUMN c1 text COLLATE "unknown"
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: Use disabled collation "unknown", related statement "ALTER TABLE t ADD COLUMN c1 text COLLATE "unknown""
+ line: 1
+- statement: ALTER TABLE tech_book ALTER COLUMN id TYPE text COLLATE "unknown"
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: Use disabled collation "unknown", related statement "ALTER TABLE tech_book ALTER COLUMN id TYPE text COLLATE "unknown""
+ line: 1
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 67a8ebf4c4..4ba6fb7344 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -860,6 +860,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
switch engine {
case db.MySQL, db.TiDB:
return MySQLCollationAllowlist, nil
+ case db.Postgres:
+ return PostgreSQLCollationAllowlist, nil
}
case SchemaRuleIndexPKTypeLimit:
switch engine {
diff --git a/plugin/parser/ast/alter_column_type_stmt.go b/plugin/parser/ast/alter_column_type_stmt.go
index 97b207d43c..3cd5223b0a 100644
--- a/plugin/parser/ast/alter_column_type_stmt.go
+++ b/plugin/parser/ast/alter_column_type_stmt.go
@@ -7,4 +7,5 @@ type AlterColumnTypeStmt struct {
Table *TableDef
ColumnName string
Type DataType
+ Collation *CollationNameDef
}
diff --git a/plugin/parser/ast/column_def.go b/plugin/parser/ast/column_def.go
index eb60f32d7a..f0896216f0 100644
--- a/plugin/parser/ast/column_def.go
+++ b/plugin/parser/ast/column_def.go
@@ -6,5 +6,14 @@ type ColumnDef struct {
ColumnName string
Type DataType
+ Collation *CollationNameDef
ConstraintList []*ConstraintDef
}
+
+// CollationNameDef is the struct for collation name.
+type CollationNameDef struct {
+ node
+
+ Schema string
+ Name string
+}
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index b2040ab859..b1ad25c7c1 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -109,10 +109,18 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, err
if err != nil {
return nil, err
}
+ collation := (*ast.CollationNameDef)(nil)
+ if column.ColumnDef.CollClause != nil {
+ collation, err = convertCollationName(column.ColumnDef.CollClause)
+ if err != nil {
+ return nil, err
+ }
+ }
alterColumType := &ast.AlterColumnTypeStmt{
Table: alterTable.Table,
ColumnName: alterCmd.Name,
Type: dataType,
+ Collation: collation,
}
alterTable.AlterItemList = append(alterTable.AlterItemList, alterColumType)
@@ -1529,9 +1537,41 @@ func convertColumnDef(in *pgquery.Node_ColumnDef) (*ast.ColumnDef, error) {
column.ConstraintList = append(column.ConstraintList, columnCons)
}
+ if in.ColumnDef.CollClause != nil {
+ collation, err := convertCollationName(in.ColumnDef.CollClause)
+ if err != nil {
+ return nil, err
+ }
+ column.Collation = collation
+ }
+
return column, nil
}
+func convertCollationName(collation *pgquery.CollateClause) (*ast.CollationNameDef, error) {
+ result := &ast.CollationNameDef{}
+ var err error
+ switch len(collation.Collname) {
+ case 1:
+ result.Name, err = convertToString(collation.Collname[0])
+ if err != nil {
+ return nil, err
+ }
+ case 2:
+ result.Schema, err = convertToString(collation.Collname[0])
+ if err != nil {
+ return nil, err
+ }
+ result.Name, err = convertToString(collation.Collname[1])
+ if err != nil {
+ return nil, err
+ }
+ default:
+ return nil, parser.NewConvertErrorf("expected one or two length but found %d", len(collation.Collname))
+ }
+ return result, nil
+}
+
func convertToTableType(relationType pgquery.ObjectType) (ast.TableType, error) {
switch relationType {
case pgquery.ObjectType_OBJECT_TABLE:
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index 88efcd5186..cfe797f6de 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -65,7 +65,8 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
stmt: `
CREATE TABLE tech_book(
a int,
- b int
+ b int,
+ c text COLLATE public."de_DE"
)
PARTITION BY RANGE (a)
`,
@@ -85,6 +86,14 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
ColumnName: "b",
Type: &ast.Integer{Size: 4},
},
+ {
+ ColumnName: "c",
+ Type: &ast.Text{},
+ Collation: &ast.CollationNameDef{
+ Schema: "public",
+ Name: "de_DE",
+ },
+ },
},
PartitionDef: &ast.UnconvertedStmt{},
},
@@ -93,14 +102,15 @@ func TestPGConvertCreateTableStmt(t *testing.T) {
{
Text: `CREATE TABLE tech_book(
a int,
- b int
+ b int,
+ c text COLLATE public."de_DE"
)
PARTITION BY RANGE (a)`,
- LastLine: 6,
+ LastLine: 7,
},
},
columnLine: [][]int{
- {3, 4},
+ {3, 4, 5},
},
},
{
@@ -2024,7 +2034,7 @@ func TestExplainStmt(t *testing.T) {
func TestAlterColumnType(t *testing.T) {
tests := []testData{
{
- stmt: "ALTER TABLE tech_book ALTER COLUMN a TYPE int",
+ stmt: `ALTER TABLE tech_book ALTER COLUMN a TYPE TEXT COLLATE "en_EN"`,
want: []ast.Node{
&ast.AlterTableStmt{
Table: &ast.TableDef{
@@ -2038,8 +2048,9 @@ func TestAlterColumnType(t *testing.T) {
Name: "tech_book",
},
ColumnName: "a",
- Type: &ast.Integer{
- Size: 4,
+ Type: &ast.Text{},
+ Collation: &ast.CollationNameDef{
+ Name: "en_EN",
},
},
},
@@ -2047,7 +2058,7 @@ func TestAlterColumnType(t *testing.T) {
},
statementList: []parser.SingleSQL{
{
- Text: "ALTER TABLE tech_book ALTER COLUMN a TYPE int",
+ Text: `ALTER TABLE tech_book ALTER COLUMN a TYPE TEXT COLLATE "en_EN"`,
LastLine: 1,
},
},