Skip to content

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

feat: migrate three advisors (#17810)

h3n4l0ca46a4a2792
diff --git a/backend/plugin/advisor/pgantlr/advisor_collation_allowlist.go b/backend/plugin/advisor/pgantlr/advisor_collation_allowlist.go
new file mode 100644
index 0000000000..ac9e52efb7
--- /dev/null
+++ b/backend/plugin/advisor/pgantlr/advisor_collation_allowlist.go
@@ -0,0 +1,191 @@
+package pgantlr
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ "github.com/pkg/errors"
+
+ parser "github.com/bytebase/parser/postgresql"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/parser/pg"
+)
+
+var (
+ _ advisor.Advisor = (*CollationAllowlistAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_POSTGRES, advisor.SchemaRuleCollationAllowlist, &CollationAllowlistAdvisor{})
+}
+
+// CollationAllowlistAdvisor is the advisor checking for collation allowlist.
+type CollationAllowlistAdvisor struct {
+}
+
+// Check checks for collation allowlist.
+func (*CollationAllowlistAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
+ tree, err := pg.ParsePostgreSQL(checkCtx.Statements)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to parse statement")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(checkCtx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &collationAllowlistChecker{
+ BasePostgreSQLParserListener: &parser.BasePostgreSQLParserListener{},
+ level: level,
+ title: string(checkCtx.Rule.Type),
+ allowlist: make(map[string]bool),
+ tokens: tree.Tokens,
+ }
+ for _, collation := range payload.List {
+ checker.allowlist[collation] = true
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(checker, tree.Tree)
+
+ return checker.adviceList, nil
+}
+
+type collationAllowlistChecker struct {
+ *parser.BasePostgreSQLParserListener
+
+ adviceList []*storepb.Advice
+ level storepb.Advice_Status
+ title string
+ allowlist map[string]bool
+ tokens *antlr.CommonTokenStream
+}
+
+// EnterCreatestmt handles CREATE TABLE statements
+func (c *collationAllowlistChecker) EnterCreatestmt(ctx *parser.CreatestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ // Extract collations from column definitions
+ if ctx.Opttableelementlist() != nil {
+ c.checkTableElementList(ctx.Opttableelementlist(), ctx)
+ }
+}
+
+// EnterAltertablestmt handles ALTER TABLE statements
+func (c *collationAllowlistChecker) EnterAltertablestmt(ctx *parser.AltertablestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ // Check ALTER TABLE ADD COLUMN
+ if ctx.Alter_table_cmds() != nil {
+ c.checkAlterTableCmds(ctx.Alter_table_cmds(), ctx)
+ }
+}
+
+func (c *collationAllowlistChecker) checkTableElementList(listCtx parser.IOpttableelementlistContext, stmtCtx antlr.ParserRuleContext) {
+ if listCtx == nil || listCtx.Tableelementlist() == nil {
+ return
+ }
+
+ allElements := listCtx.Tableelementlist().AllTableelement()
+ for _, elem := range allElements {
+ if elem.ColumnDef() != nil {
+ c.checkColumnDef(elem.ColumnDef(), stmtCtx)
+ }
+ }
+}
+
+func (c *collationAllowlistChecker) checkColumnDef(colDef parser.IColumnDefContext, stmtCtx antlr.ParserRuleContext) {
+ if colDef == nil || colDef.Colquallist() == nil {
+ return
+ }
+
+ // Check column constraints for COLLATE clause
+ // colquallist -> colconstraint* -> COLLATE any_name
+ allConstraints := colDef.Colquallist().AllColconstraint()
+ for _, constraint := range allConstraints {
+ // Check if this constraint is a COLLATE constraint
+ if constraint.COLLATE() != nil && constraint.Any_name() != nil {
+ collName := c.extractCollationNameFromAnyName(constraint.Any_name())
+ if collName != "" && !c.allowlist[collName] {
+ c.addAdvice(collName, stmtCtx)
+ }
+ }
+ }
+}
+
+func (c *collationAllowlistChecker) checkAlterTableCmds(cmds parser.IAlter_table_cmdsContext, stmtCtx antlr.ParserRuleContext) {
+ if cmds == nil {
+ return
+ }
+
+ allCmds := cmds.AllAlter_table_cmd()
+ for _, cmd := range allCmds {
+ // ADD COLUMN
+ if cmd.ADD_P() != nil && cmd.ColumnDef() != nil {
+ c.checkColumnDef(cmd.ColumnDef(), stmtCtx)
+ }
+
+ // ALTER COLUMN TYPE with COLLATE
+ // Check if this is ALTER COLUMN ... TYPE ...
+ // Grammar: ALTER opt_column? colid opt_set_data? TYPE_P typename opt_collate_clause? alter_using?
+ if cmd.ALTER() != nil && cmd.TYPE_P() != nil && cmd.Opt_collate_clause() != nil && cmd.Opt_collate_clause().Any_name() != nil {
+ collName := c.extractCollationNameFromAnyName(cmd.Opt_collate_clause().Any_name())
+ if collName != "" && !c.allowlist[collName] {
+ c.addAdvice(collName, stmtCtx)
+ }
+ }
+ }
+}
+
+func (*collationAllowlistChecker) extractCollationNameFromAnyName(anyName parser.IAny_nameContext) string {
+ if anyName == nil {
+ return ""
+ }
+
+ // any_name can be: colid | colid attrs
+ // For collation names like "unknown" or "utf8mb4_0900_ai_ci", we need the text
+ // Handle quoted strings by getting the full text and removing quotes if present
+ text := anyName.GetText()
+
+ // Remove leading/trailing quotes if present
+ if len(text) >= 2 && text[0] == '"' && text[len(text)-1] == '"' {
+ return text[1 : len(text)-1]
+ }
+
+ return text
+}
+
+func (c *collationAllowlistChecker) addAdvice(collation string, ctx antlr.ParserRuleContext) {
+ text := c.tokens.GetTextFromRuleContext(ctx)
+
+ // Check if the next token after the context is a semicolon
+ stopIndex := ctx.GetStop().GetTokenIndex()
+ if stopIndex+1 < c.tokens.Size() {
+ nextToken := c.tokens.Get(stopIndex + 1)
+ if nextToken.GetText() == ";" {
+ text += ";"
+ }
+ }
+
+ c.adviceList = append(c.adviceList, &storepb.Advice{
+ Status: c.level,
+ Code: advisor.DisabledCollation.Int32(),
+ Title: c.title,
+ Content: fmt.Sprintf("Use disabled collation \"%s\", related statement \"%s\"", collation, text),
+ StartPosition: &storepb.Position{
+ Line: int32(ctx.GetStart().GetLine()),
+ Column: int32(ctx.GetStart().GetColumn()),
+ },
+ })
+}
diff --git a/backend/plugin/advisor/pgantlr/advisor_column_comment_convention.go b/backend/plugin/advisor/pgantlr/advisor_column_comment_convention.go
new file mode 100644
index 0000000000..491e0ed2a5
--- /dev/null
+++ b/backend/plugin/advisor/pgantlr/advisor_column_comment_convention.go
@@ -0,0 +1,306 @@
+package pgantlr
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/antlr4-go/antlr/v4"
+ "github.com/pkg/errors"
+
+ parser "github.com/bytebase/parser/postgresql"
+
+ "github.com/bytebase/bytebase/backend/common"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/parser/pg"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnCommentConventionAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_POSTGRES, advisor.SchemaRuleColumnCommentConvention, &ColumnCommentConventionAdvisor{})
+}
+
+// ColumnCommentConventionAdvisor is the advisor checking for column comment convention.
+type ColumnCommentConventionAdvisor struct {
+}
+
+func (*ColumnCommentConventionAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
+ tree, err := pg.ParsePostgreSQL(checkCtx.Statements)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to parse statement")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalCommentConventionRulePayload(checkCtx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &columnCommentConventionChecker{
+ BasePostgreSQLParserListener: &parser.BasePostgreSQLParserListener{},
+ level: level,
+ title: string(checkCtx.Rule.Type),
+ payload: payload,
+ classificationConfig: checkCtx.ClassificationConfig,
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(checker, tree.Tree)
+
+ // Now validate all collected columns against comments
+ return checker.generateAdvice(), nil
+}
+
+type columnInfo struct {
+ schema string
+ table string
+ column string
+ line int
+}
+
+type commentInfo struct {
+ schema string
+ table string
+ column string
+ comment string
+ line int
+}
+
+type columnCommentConventionChecker struct {
+ *parser.BasePostgreSQLParserListener
+
+ level storepb.Advice_Status
+ title string
+ payload *advisor.CommentConventionRulePayload
+ classificationConfig *storepb.DataClassificationSetting_DataClassificationConfig
+
+ columns []columnInfo
+ comments []commentInfo
+}
+
+func (c *columnCommentConventionChecker) EnterCreatestmt(ctx *parser.CreatestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ tableName := c.extractTableName(ctx.AllQualified_name())
+ if tableName == "" {
+ return
+ }
+
+ // Extract all columns
+ if ctx.Opttableelementlist() != nil && ctx.Opttableelementlist().Tableelementlist() != nil {
+ allElements := ctx.Opttableelementlist().Tableelementlist().AllTableelement()
+ for _, elem := range allElements {
+ if elem.ColumnDef() != nil && elem.ColumnDef().Colid() != nil {
+ columnName := elem.ColumnDef().Colid().GetText()
+ c.columns = append(c.columns, columnInfo{
+ schema: "public", // Default schema
+ table: tableName,
+ column: columnName,
+ line: ctx.GetStart().GetLine(),
+ })
+ }
+ }
+ }
+}
+
+func (c *columnCommentConventionChecker) EnterAltertablestmt(ctx *parser.AltertablestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ if ctx.Relation_expr() == nil || ctx.Relation_expr().Qualified_name() == nil {
+ return
+ }
+
+ tableName := ctx.Relation_expr().Qualified_name().GetText()
+ if tableName == "" {
+ return
+ }
+
+ // Check ALTER TABLE ADD COLUMN
+ if ctx.Alter_table_cmds() != nil {
+ allCmds := ctx.Alter_table_cmds().AllAlter_table_cmd()
+ for _, cmd := range allCmds {
+ // ADD COLUMN
+ if cmd.ADD_P() != nil && cmd.ColumnDef() != nil && cmd.ColumnDef().Colid() != nil {
+ columnName := cmd.ColumnDef().Colid().GetText()
+ c.columns = append(c.columns, columnInfo{
+ schema: "public", // Default schema
+ table: tableName,
+ column: columnName,
+ line: ctx.GetStart().GetLine(),
+ })
+ }
+ }
+ }
+}
+
+func (c *columnCommentConventionChecker) EnterCommentstmt(ctx *parser.CommentstmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ // Check if this is a COMMENT ON COLUMN statement
+ if ctx.COLUMN() == nil || ctx.Any_name() == nil {
+ return
+ }
+
+ // Extract table.column name from any_name
+ // any_name is like: table.column
+ anyName := ctx.Any_name()
+ text := anyName.GetText()
+
+ // Split by dot to get table and column
+ parts := splitIdentifier(text)
+ if len(parts) < 2 {
+ return
+ }
+
+ tableName := parts[len(parts)-2]
+ columnName := parts[len(parts)-1]
+
+ // Extract comment text
+ comment := ""
+ if ctx.Comment_text() != nil && ctx.Comment_text().Sconst() != nil {
+ comment = c.extractStringConstant(ctx.Comment_text().Sconst())
+ }
+
+ c.comments = append(c.comments, commentInfo{
+ schema: "public",
+ table: tableName,
+ column: columnName,
+ comment: comment,
+ line: ctx.GetStart().GetLine(),
+ })
+}
+
+func (*columnCommentConventionChecker) extractTableName(qualifiedNames []parser.IQualified_nameContext) string {
+ if len(qualifiedNames) == 0 {
+ return ""
+ }
+
+ // Take the first qualified name
+ text := qualifiedNames[0].GetText()
+
+ // Remove schema if present (e.g., "public.table" -> "table")
+ parts := splitIdentifier(text)
+ if len(parts) == 0 {
+ return ""
+ }
+
+ // Return the last part (table name)
+ return parts[len(parts)-1]
+}
+
+// splitIdentifier splits a qualified identifier by dots, handling quoted parts
+func splitIdentifier(s string) []string {
+ var parts []string
+ var current string
+ inQuote := false
+
+ for i := 0; i < len(s); i++ {
+ ch := s[i]
+ if ch == '"' {
+ inQuote = !inQuote
+ } else if ch == '.' && !inQuote {
+ if current != "" {
+ parts = append(parts, current)
+ current = ""
+ }
+ } else {
+ current += string(ch)
+ }
+ }
+
+ if current != "" {
+ parts = append(parts, current)
+ }
+
+ return parts
+}
+
+func (*columnCommentConventionChecker) extractStringConstant(sconst parser.ISconstContext) string {
+ if sconst == nil {
+ return ""
+ }
+
+ // Get the text and remove surrounding quotes
+ text := sconst.GetText()
+ if len(text) >= 2 && text[0] == '\'' && text[len(text)-1] == '\'' {
+ return text[1 : len(text)-1]
+ }
+ return text
+}
+
+func (c *columnCommentConventionChecker) generateAdvice() []*storepb.Advice {
+ var adviceList []*storepb.Advice
+
+ // For each column, find its comment and validate
+ for _, col := range c.columns {
+ // Find the last matching comment for this column
+ var matchedComment *commentInfo
+ for i := range c.comments {
+ comment := &c.comments[i]
+ if comment.schema == col.schema && comment.table == col.table && comment.column == col.column {
+ matchedComment = comment
+ // Continue to find the last one
+ }
+ }
+
+ if matchedComment == nil || matchedComment.comment == "" {
+ if c.payload.Required {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: c.level,
+ Code: advisor.CommentEmpty.Int32(),
+ Title: c.title,
+ Content: fmt.Sprintf("Comment is required for column `%s.%s`", col.table, col.column),
+ StartPosition: &storepb.Position{
+ Line: int32(col.line),
+ Column: 0,
+ },
+ })
+ }
+ } else {
+ comment := matchedComment.comment
+
+ // Check max length
+ if c.payload.MaxLength > 0 && len(comment) > c.payload.MaxLength {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: c.level,
+ Code: advisor.CommentTooLong.Int32(),
+ Title: c.title,
+ Content: fmt.Sprintf("Column `%s.%s` comment is too long. The length of comment should be within %d characters", col.table, col.column, c.payload.MaxLength),
+ StartPosition: &storepb.Position{
+ Line: int32(matchedComment.line),
+ Column: 0,
+ },
+ })
+ }
+
+ // Check classification
+ if c.payload.RequiredClassification {
+ if classification, _ := common.GetClassificationAndUserComment(comment, c.classificationConfig); classification == "" {
+ adviceList = append(adviceList, &storepb.Advice{
+ Status: c.level,
+ Code: advisor.CommentMissingClassification.Int32(),
+ Title: c.title,
+ Content: fmt.Sprintf("Column `%s.%s` comment requires classification", col.table, col.column),
+ StartPosition: &storepb.Position{
+ Line: int32(matchedComment.line),
+ Column: 0,
+ },
+ })
+ }
+ }
+ }
+ }
+
+ return adviceList
+}
diff --git a/backend/plugin/advisor/pgantlr/advisor_column_default_disallow_volatile.go b/backend/plugin/advisor/pgantlr/advisor_column_default_disallow_volatile.go
new file mode 100644
index 0000000000..ebb01bb81f
--- /dev/null
+++ b/backend/plugin/advisor/pgantlr/advisor_column_default_disallow_volatile.go
@@ -0,0 +1,206 @@
+package pgantlr
+
+import (
+ "context"
+ "fmt"
+ "slices"
+
+ "github.com/antlr4-go/antlr/v4"
+ "github.com/pkg/errors"
+
+ parser "github.com/bytebase/parser/postgresql"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/parser/pg"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDefaultDisallowVolatileAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_POSTGRES, advisor.SchemaRuleColumnDefaultDisallowVolatile, &ColumnDefaultDisallowVolatileAdvisor{})
+}
+
+// ColumnDefaultDisallowVolatileAdvisor is the advisor checking for column default volatile functions.
+type ColumnDefaultDisallowVolatileAdvisor struct {
+}
+
+// Check checks for column default volatile functions.
+func (*ColumnDefaultDisallowVolatileAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
+ tree, err := pg.ParsePostgreSQL(checkCtx.Statements)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to parse statement")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &columnDefaultDisallowVolatileChecker{
+ BasePostgreSQLParserListener: &parser.BasePostgreSQLParserListener{},
+ level: level,
+ title: string(checkCtx.Rule.Type),
+ columnSet: make(map[string]columnData),
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(checker, tree.Tree)
+
+ return checker.generateAdvice(), nil
+}
+
+type columnData struct {
+ schema string
+ table string
+ name string
+ line int
+}
+
+type columnDefaultDisallowVolatileChecker struct {
+ *parser.BasePostgreSQLParserListener
+
+ level storepb.Advice_Status
+ title string
+ columnSet map[string]columnData
+ adviceList []*storepb.Advice
+}
+
+func (c *columnDefaultDisallowVolatileChecker) EnterAltertablestmt(ctx *parser.AltertablestmtContext) {
+ if !isTopLevel(ctx.GetParent()) {
+ return
+ }
+
+ if ctx.Relation_expr() == nil || ctx.Relation_expr().Qualified_name() == nil {
+ return
+ }
+
+ tableName := ctx.Relation_expr().Qualified_name().GetText()
+ if tableName == "" {
+ return
+ }
+
+ // Check ALTER TABLE ADD COLUMN
+ if ctx.Alter_table_cmds() != nil {
+ allCmds := ctx.Alter_table_cmds().AllAlter_table_cmd()
+ for _, cmd := range allCmds {
+ // ADD COLUMN
+ if cmd.ADD_P() != nil && cmd.ColumnDef() != nil {
+ colDef := cmd.ColumnDef()
+ if colDef.Colid() != nil {
+ columnName := colDef.Colid().GetText()
+
+ // Check if this column has a volatile DEFAULT
+ if c.hasVolatileDefault(colDef) {
+ c.addColumn("public", tableName, columnName, ctx.GetStart().GetLine())
+ }
+ }
+ }
+ }
+ }
+}
+
+func (c *columnDefaultDisallowVolatileChecker) hasVolatileDefault(colDef parser.IColumnDefContext) bool {
+ if colDef == nil || colDef.Colquallist() == nil {
+ return false
+ }
+
+ // Check all column constraints
+ allConstraints := colDef.Colquallist().AllColconstraint()
+ for _, constraint := range allConstraints {
+ // Check if this is a DEFAULT constraint
+ if constraint.Colconstraintelem() != nil {
+ elem := constraint.Colconstraintelem()
+ if elem.DEFAULT() != nil && elem.B_expr() != nil {
+ // If the default expression contains a function call, it's potentially volatile
+ // We check if the expression contains a function call by looking for FuncExpr patterns
+ if c.containsFunctionCall(elem.B_expr()) {
+ return true
+ }
+ }
+ }
+ }
+
+ return false
+}
+
+func (c *columnDefaultDisallowVolatileChecker) containsFunctionCall(expr antlr.Tree) bool {
+ if expr == nil {
+ return false
+ }
+
+ // Check if this expression is or contains a function call
+ // In PostgreSQL, function calls are represented as func_expr
+ return c.hasFuncExpr(expr)
+}
+
+func (c *columnDefaultDisallowVolatileChecker) hasFuncExpr(node antlr.Tree) bool {
+ if node == nil {
+ return false
+ }
+
+ // Check if this node is a function expression
+ switch node.(type) {
+ case *parser.Func_exprContext,
+ *parser.Func_expr_windowlessContext,
+ *parser.Func_expr_common_subexprContext:
+ return true
+ }
+
+ // Recursively check children
+ if parserRule, ok := node.(antlr.ParserRuleContext); ok {
+ for i := 0; i < parserRule.GetChildCount(); i++ {
+ child := parserRule.GetChild(i)
+ if c.hasFuncExpr(child) {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+func (c *columnDefaultDisallowVolatileChecker) addColumn(schema string, table string, column string, line int) {
+ if schema == "" {
+ schema = "public"
+ }
+
+ c.columnSet[fmt.Sprintf("%s.%s.%s", schema, table, column)] = columnData{
+ schema: schema,
+ table: table,
+ name: column,
+ line: line,
+ }
+}
+
+func (c *columnDefaultDisallowVolatileChecker) generateAdvice() []*storepb.Advice {
+ var columnList []columnData
+ for _, column := range c.columnSet {
+ columnList = append(columnList, column)
+ }
+ slices.SortFunc(columnList, func(i, j columnData) int {
+ if i.line < j.line {
+ return -1
+ }
+ if i.line > j.line {
+ return 1
+ }
+ return 0
+ })
+
+ for _, column := range columnList {
+ c.adviceList = append(c.adviceList, &storepb.Advice{
+ Status: c.level,
+ Code: advisor.NoDefault.Int32(),
+ Title: c.title,
+ Content: fmt.Sprintf("Column %q.%q in schema %q has volatile DEFAULT", column.table, column.name, column.schema),
+ StartPosition: &storepb.Position{
+ Line: int32(column.line),
+ Column: 0,
+ },
+ })
+ }
+
+ return c.adviceList
+}
diff --git a/backend/plugin/advisor/pgantlr/pgantlr_test.go b/backend/plugin/advisor/pgantlr/pgantlr_test.go
index 36e9783f6a..65ec1d624c 100644
--- a/backend/plugin/advisor/pgantlr/pgantlr_test.go
+++ b/backend/plugin/advisor/pgantlr/pgantlr_test.go
@@ -9,8 +9,11 @@ import (
func TestPostgreSQLANTLRRules(t *testing.T) {
antlrRules := []advisor.SQLReviewRuleType{
- HelloWorldRule, // Test advisor to verify framework works
- advisor.BuiltinRulePriorBackupCheck, // Migrated from legacy
+ HelloWorldRule, // Test advisor to verify framework works
+ advisor.BuiltinRulePriorBackupCheck, // Migrated from legacy
+ advisor.SchemaRuleCollationAllowlist, // Migrated from legacy
+ advisor.SchemaRuleColumnCommentConvention, // Migrated from legacy
+ advisor.SchemaRuleColumnDefaultDisallowVolatile, // Migrated from legacy
// Add real rules here as you migrate them from legacy pg/ folder
// Example:
// advisor.SchemaRuleStatementDisallowCommit,
@@ -29,4 +32,5 @@ func TestPostgreSQLANTLRRules(t *testing.T) {
var advisorNeedMockData = map[advisor.SQLReviewRuleType]bool{
// advisor.SchemaRuleFullyQualifiedObjectName: true,
advisor.BuiltinRulePriorBackupCheck: true,
+ // New advisors don't need mock data
}
diff --git a/backend/plugin/advisor/pgantlr/test/column_comment.yaml b/backend/plugin/advisor/pgantlr/test/column_comment.yaml
new file mode 100644
index 0000000000..d62bd0e41a
--- /dev/null
+++ b/backend/plugin/advisor/pgantlr/test/column_comment.yaml
@@ -0,0 +1,55 @@
+- statement: |-
+ CREATE TABLE t(a int);
+ COMMENT ON COLUMN t.a IS 'comments';
+ changeType: 1
+- statement: CREATE TABLE t(a int);
+ changeType: 1
+ want:
+ - status: 2
+ code: 1032
+ title: column.comment
+ content: Comment is required for column `t.a`
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+- statement: |-
+ CREATE TABLE t(a int);
+ COMMENT ON COLUMN t.a IS 'loooooooong comments';
+ changeType: 1
+ want:
+ - status: 2
+ code: 1301
+ title: column.comment
+ content: Column `t.a` comment is too long. The length of comment should be within 10 characters
+ startposition:
+ line: 2
+ column: 0
+ endposition: null
+- statement: |-
+ CREATE TABLE t(a int, d text);
+ COMMENT ON COLUMN t.a IS 'comments';
+ changeType: 1
+ want:
+ - status: 2
+ code: 1032
+ title: column.comment
+ content: Comment is required for column `t.d`
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+- statement: |-
+ CREATE TABLE t(a int);
+ COMMENT ON COLUMN t.a IS 'loooooooong comments';
+ COMMENT ON COLUMN t.a IS NULL;
+ changeType: 1
+ want:
+ - status: 2
+ code: 1032
+ title: column.comment
+ content: Comment is required for column `t.a`
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
diff --git a/backend/plugin/advisor/pgantlr/test/column_default_disallow_volatile.yaml b/backend/plugin/advisor/pgantlr/test/column_default_disallow_volatile.yaml
new file mode 100644
index 0000000000..85d842a879
--- /dev/null
+++ b/backend/plugin/advisor/pgantlr/test/column_default_disallow_volatile.yaml
@@ -0,0 +1,13 @@
+- statement: CREATE TABLE t(a serial primary key, b int default 1, c boolean default true, d int default current_user)
+ changeType: 1
+- statement: ALTER TABLE tech_book ADD COLUMN b timestamp default now();
+ changeType: 1
+ want:
+ - status: 2
+ code: 420
+ title: column.default-disallow-volatile
+ content: Column "tech_book"."b" in schema "public" has volatile DEFAULT
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
diff --git a/backend/plugin/advisor/pgantlr/test/system_collation_allowlist.yaml b/backend/plugin/advisor/pgantlr/test/system_collation_allowlist.yaml
new file mode 100644
index 0000000000..7edae7f7c8
--- /dev/null
+++ b/backend/plugin/advisor/pgantlr/test/system_collation_allowlist.yaml
@@ -0,0 +1,35 @@
+- statement: CREATE TABLE t(a text COLLATE utf8mb4_0900_ai_ci)
+ changeType: 1
+- statement: CREATE TABLE t(a text COLLATE "unknown")
+ changeType: 1
+ want:
+ - status: 2
+ code: 1201
+ title: system.collation.allowlist
+ content: Use disabled collation "unknown", related statement "CREATE TABLE t(a text COLLATE "unknown")"
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+- statement: ALTER TABLE tech_book ADD COLUMN c1 text COLLATE "unknown"
+ changeType: 1
+ want:
+ - status: 2
+ code: 1201
+ title: system.collation.allowlist
+ content: Use disabled collation "unknown", related statement "ALTER TABLE tech_book ADD COLUMN c1 text COLLATE "unknown""
+ startposition:
+ line: 1
+ column: 0
+ endposition: null
+- statement: ALTER TABLE tech_book ALTER COLUMN id TYPE text COLLATE "unknown"
+ changeType: 1
+ want:
+ - status: 2
+ code: 1201
+ title: system.collation.allowlist
+ content: Use disabled collation "unknown", related statement "ALTER TABLE tech_book ALTER COLUMN id TYPE text COLLATE "unknown""
+ startposition:
+ line: 1
+ column: 0
+ endposition: null