Skip to content

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

chore: add a SQL review rule framework code generator (#2399)

rebelice874f35a21e9a
diff --git a/go.mod b/go.mod
index ad14269936..20b4453a9f 100644
--- a/go.mod
+++ b/go.mod
@@ -39,6 +39,7 @@ require (
github.com/xo/dburl v0.11.0
go.uber.org/zap v1.21.0
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
+ golang.org/x/text v0.3.7
gopkg.in/yaml.v3 v3.0.1
)
@@ -145,7 +146,6 @@ require (
golang.org/x/net v0.0.0-20220805013720-a33c5aa5df48 // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect
- golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect
golang.org/x/tools v0.1.12 // indirect
golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index c1380fa13f..5cb4c0babf 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -84,6 +84,9 @@ const (
// MySQLColumnNoNull is an advisor type for MySQL column no NULL value.
MySQLColumnNoNull Type = "bb.plugin.advisor.mysql.column.no-null"
+ // MySQLColumnDisallowChangingType is an advisor type for MySQL disallow changing column type.
+ MySQLColumnDisallowChangingType Type = "bb.plugin.advisor.mysql.column.disallow-changing-type"
+
// MySQLNoSelectAll is an advisor type for MySQL no select all.
MySQLNoSelectAll Type = "bb.plugin.advisor.mysql.select.no-select-all"
diff --git a/plugin/advisor/generator/README.md b/plugin/advisor/generator/README.md
new file mode 100644
index 0000000000..b435e97eed
--- /dev/null
+++ b/plugin/advisor/generator/README.md
@@ -0,0 +1,29 @@
+This is a SQL review rule generator. It's used for implementing a specific SQL review rule.
+
+## How To Use
+
+1. Add the `Advisor Type` in `/plugin/advisor/advisor.go`:
+ ```go
+ const (
+ // ...
+
+ // MySQLColumnDisallowChangingType is an advisor type for MySQL disallow changing column type.
+ MySQLColumnDisallowChangingType Type = "bb.plugin.advisor.mysql.column.disallow-changing-type"
+ )
+ ```
+ You need write both code and the comment.
+2. build the generator.
+ ```shell
+ go build
+ ```
+ in `/plugin/advisor/generator`
+3. run generator to generate the framework code.
+ ```shell
+ ./generator --flag {AdvisorType}
+ ```
+ in `/plugin/advisor/generator`
+ e.g.
+ ```shell
+ ./generator --flag MySQLColumnDisallowChangingType
+ ```
+4. Implement the rule-specific logic in the generated files.
diff --git a/plugin/advisor/generator/main.go b/plugin/advisor/generator/main.go
new file mode 100644
index 0000000000..fecba64054
--- /dev/null
+++ b/plugin/advisor/generator/main.go
@@ -0,0 +1,148 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "path"
+ "strings"
+
+ "github.com/pkg/errors"
+ "github.com/spf13/cobra"
+ "golang.org/x/text/cases"
+ "golang.org/x/text/language"
+)
+
+const (
+ typeFile = "../advisor.go"
+ mysqlTemplate = "./mysql.template"
+ mysqlTestTemplate = "./mysql_test.template"
+ lowerMySQL = "mysql"
+ lowerPostgreSQL = "postgresql"
+)
+
+var (
+ flags struct {
+ rule string
+ }
+
+ cmd = &cobra.Command{
+ Use: "generator",
+ Short: "This is a SQL review rule generator",
+ Run: func(cmd *cobra.Command, args []string) {
+ // Get AdvisorComment, AdvisorName, CheckerName, FileName and TestName
+ var advisorComment, advisorName, checkerName, fileName, testName string
+ var fileNameTokenList, advisorNameTokenList []string
+ file, err := os.Open(typeFile)
+ if err != nil {
+ fmt.Printf("can not open %q: %s\n", typeFile, err.Error())
+ return
+ }
+ defer file.Close()
+ scanner := bufio.NewScanner(file)
+ for scanner.Scan() {
+ line := scanner.Text()
+ if !strings.Contains(line, flags.rule) {
+ continue
+ }
+ wordList := strings.Fields(line)
+ if strings.HasPrefix(wordList[0], "//") {
+ for i, word := range wordList {
+ switch strings.ToLower(word) {
+ case lowerMySQL:
+ advisorComment = strings.Join(wordList[i+1:], " ")
+ case lowerPostgreSQL:
+ fmt.Printf("not support PostgreSQL")
+ return
+ }
+ if advisorComment != "" {
+ break
+ }
+ }
+ } else {
+ needed := false
+ typeToken := strings.Split(strings.Trim(wordList[3], "\""), ".")
+ for _, token := range typeToken {
+ if needed {
+ nameWord := strings.Split(token, "-")
+ fileNameTokenList = append(fileNameTokenList, nameWord...)
+ continue
+ }
+ switch token {
+ case lowerMySQL:
+ needed = true
+ case lowerPostgreSQL:
+ fmt.Printf("not support PostgreSQL")
+ return
+ }
+ }
+ break
+ }
+ }
+
+ fileName = fmt.Sprintf("advisor_%s", strings.Join(fileNameTokenList, "_"))
+ for _, token := range fileNameTokenList {
+ advisorNameTokenList = append(advisorNameTokenList, cases.Title(language.AmericanEnglish).String(token))
+ }
+ testName = strings.Join(advisorNameTokenList, "")
+ advisorName = fmt.Sprintf("%sAdvisor", testName)
+ checkerName = fmt.Sprintf("%s%sChecker", strings.ToLower(advisorNameTokenList[0]), strings.Join(advisorNameTokenList[1:], ""))
+
+ fmt.Printf("Try to generate %s...\n", fileName)
+ fmt.Printf("SQL rule type is %s\n", flags.rule)
+ fmt.Printf("Advisor name is %s\n", advisorName)
+ fmt.Printf("This rule checks for %s\n", advisorComment)
+ fmt.Printf("Checker name is %s\n", checkerName)
+ fmt.Printf("Test name is %s\n", testName)
+
+ // generator code
+ if err := generateFile(fmt.Sprintf("%s.go", fileName), mysqlTemplate, flags.rule, advisorName, advisorComment, checkerName, testName); err != nil {
+ fmt.Printf("%s\n", err.Error())
+ }
+ if err := generateFile(fmt.Sprintf("%s_test.go", fileName), mysqlTestTemplate, flags.rule, advisorName, advisorComment, checkerName, testName); err != nil {
+ fmt.Printf("%s\n", err.Error())
+ }
+ },
+ }
+)
+
+func generateFile(filePath, tempelatePath, advisorType, advisorName, advisorComment, checkerName, testName string) error {
+ templateFile, err := os.Open(tempelatePath)
+ if err != nil {
+ return errors.Wrapf(err, "failed to open template file %s", tempelatePath)
+ }
+ defer templateFile.Close()
+ goFile, err := os.Create(path.Join("..", "mysql", filePath))
+ if err != nil {
+ return errors.Wrapf(err, "failed to create %s", filePath)
+ }
+ defer goFile.Close()
+ scanner := bufio.NewScanner(templateFile)
+ writer := bufio.NewWriter(goFile)
+ for scanner.Scan() {
+ text := scanner.Text()
+ text = strings.ReplaceAll(text, `%AdvisorType`, advisorType)
+ text = strings.ReplaceAll(text, `%AdvisorName`, advisorName)
+ text = strings.ReplaceAll(text, `%AdvisorComment`, advisorComment)
+ text = strings.ReplaceAll(text, `%CheckerName`, checkerName)
+ text = strings.ReplaceAll(text, `%TestName`, testName)
+ _, err := writer.WriteString(text + "\n")
+ if err != nil {
+ return errors.Wrapf(err, "failed to write string to file %s", filePath)
+ }
+ }
+ if err := writer.Flush(); err != nil {
+ return errors.Wrap(err, "failed to flush")
+ }
+ fmt.Printf("Generate %s successfully!\n", filePath)
+ return nil
+}
+
+func init() {
+ cmd.PersistentFlags().StringVar(&flags.rule, "rule", "", "rule type you want to generate. This rule type and comment must exist in /plugin/advisor/advisor.go")
+}
+
+func main() {
+ //nolint
+ cmd.Execute()
+}
diff --git a/plugin/advisor/generator/mysql.template b/plugin/advisor/generator/mysql.template
new file mode 100644
index 0000000000..d966849209
--- /dev/null
+++ b/plugin/advisor/generator/mysql.template
@@ -0,0 +1,76 @@
+package mysql
+
+import (
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/pingcap/tidb/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*%AdvisorName)(nil)
+ _ ast.Visitor = (*%CheckerName)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.%AdvisorType, &%AdvisorName{})
+ advisor.Register(db.TiDB, advisor.%AdvisorType, &%AdvisorName{})
+}
+
+// %AdvisorName is the advisor checking for %AdvisorComment.
+type %AdvisorName struct {
+}
+
+// Check checks for %AdvisorComment.
+func (*%AdvisorName) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmtList, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &%CheckerName{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ 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 %CheckerName struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (*%CheckerName) Enter(in ast.Node) (ast.Node, bool) {
+ // TODO: implement it
+ // switch node := in.(type) {
+ // }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*%CheckerName) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/plugin/advisor/generator/mysql_test.template b/plugin/advisor/generator/mysql_test.template
new file mode 100644
index 0000000000..65bef3925a
--- /dev/null
+++ b/plugin/advisor/generator/mysql_test.template
@@ -0,0 +1,28 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func Test%TestName(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: ``,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ }
+
+ advisor.RunSQLReviewRuleTests(t, tests, &%AdvisorName{}, &advisor.SQLReviewRule{
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: "",
+ }, advisor.MockMySQLDatabase)
+}
diff --git a/plugin/advisor/mysql/advisor_column_disallow_changing_type.go b/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
new file mode 100644
index 0000000000..6da0c5af0b
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
@@ -0,0 +1,76 @@
+package mysql
+
+import (
+ "github.com/bytebase/bytebase/plugin/advisor"
+ "github.com/bytebase/bytebase/plugin/advisor/db"
+ "github.com/pingcap/tidb/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDisallowChangingTypeAdvisor)(nil)
+ _ ast.Visitor = (*columnDisallowChangingTypeChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.MySQL, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
+ advisor.Register(db.TiDB, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
+}
+
+// ColumnDisallowChangingTypeAdvisor is the advisor checking for disallow changing column type..
+type ColumnDisallowChangingTypeAdvisor struct {
+}
+
+// Check checks for disallow changing column type..
+func (*ColumnDisallowChangingTypeAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ stmtList, errAdvice := parseStatement(statement, ctx.Charset, ctx.Collation)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnDisallowChangingTypeChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ 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 columnDisallowChangingTypeChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (*columnDisallowChangingTypeChecker) Enter(in ast.Node) (ast.Node, bool) {
+ // TODO: implement it
+ // switch node := in.(type) {
+ // }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnDisallowChangingTypeChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go b/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go
new file mode 100644
index 0000000000..dcf097b3bc
--- /dev/null
+++ b/plugin/advisor/mysql/advisor_column_disallow_changing_type_test.go
@@ -0,0 +1,28 @@
+package mysql
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/plugin/advisor"
+)
+
+func TestColumnDisallowChangingType(t *testing.T) {
+ tests := []advisor.TestCase{
+ {
+ Statement: ``,
+ Want: []advisor.Advice{
+ {
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ },
+ },
+ },
+ }
+
+ advisor.RunSQLReviewRuleTests(t, tests, &ColumnDisallowChangingTypeAdvisor{}, &advisor.SQLReviewRule{
+ Level: advisor.SchemaRuleLevelWarning,
+ Payload: "",
+ }, advisor.MockMySQLDatabase)
+}