Skip to content

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

feat: implement Oracle require PK rule (#5948)

rebelice28bce18fe8ae
diff --git a/.golangci.yaml b/.golangci.yaml
index b4e78b13a8..a49f3bc4f7 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -30,6 +30,8 @@ issues:
- pgInstance.Stop
- fmt.Printf
- fmt.Print
+ - Enter(.*)_(.*)
+ - Exit(.*)_(.*)
run:
timeout: 5m
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 8211ef6e61..d26e139a0d 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -332,6 +332,11 @@ const (
// PostgreSQLCollationAllowlist is an advisor type for PostgreSQL collation allowlist.
PostgreSQLCollationAllowlist Type = "bb.plugin.advisor.postgresql.collation.allowlist"
+
+ // Oracle Advisor.
+
+ // OracleTableRequirePK is an advisor type for Oracle table require primary key.
+ OracleTableRequirePK Type = "bb.plugin.advisor.oracle.table.require-pk"
)
// Advice is the result of an advisor.
@@ -391,6 +396,9 @@ type Context struct {
Catalog *catalog.Finder
Driver *sql.DB
Context context.Context
+
+ // CurrentSchema is the current schema. Special for Oracle.
+ CurrentSchema string
}
// Advisor is the interface for advisor.
diff --git a/backend/plugin/advisor/db/db.go b/backend/plugin/advisor/db/db.go
index 4e5de88595..567b5c3e41 100644
--- a/backend/plugin/advisor/db/db.go
+++ b/backend/plugin/advisor/db/db.go
@@ -21,6 +21,8 @@ const (
TiDB Type = "TIDB"
// MariaDB is the database type for MariaDB.
MariaDB Type = "MARIADB"
+ // Oracle is the database type for Oracle.
+ Oracle Type = "ORACLE"
)
// ConvertToAdvisorDBType will convert db type into advisor db type.
@@ -32,6 +34,8 @@ func ConvertToAdvisorDBType(dbType string) (Type, error) {
return Postgres, nil
case string(TiDB):
return TiDB, nil
+ case string(Oracle):
+ return Oracle, nil
}
return "", errors.Errorf("unsupported db type %s for advisor", dbType)
diff --git a/backend/plugin/advisor/oracle/advisor_table_require_pk.go b/backend/plugin/advisor/oracle/advisor_table_require_pk.go
new file mode 100644
index 0000000000..c278167b95
--- /dev/null
+++ b/backend/plugin/advisor/oracle/advisor_table_require_pk.go
@@ -0,0 +1,157 @@
+// Package oracle is the advisor for oracle database.
+package oracle
+
+import (
+ "fmt"
+
+ "github.com/antlr/antlr4/runtime/Go/antlr/v4"
+ parser "github.com/bytebase/plsql-parser"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"
+)
+
+var (
+ _ advisor.Advisor = (*TableRequirePKAdvisor)(nil)
+)
+
+func init() {
+ advisor.Register(db.Oracle, advisor.OracleTableRequirePK, &TableRequirePKAdvisor{})
+}
+
+// TableRequirePKAdvisor is the advisor checking table requires PK.
+type TableRequirePKAdvisor struct {
+}
+
+// Check checks table requires PK.
+func (*TableRequirePKAdvisor) Check(ctx advisor.Context, statement string) ([]advisor.Advice, error) {
+ tree, errAdvice := parseStatement(statement)
+ if errAdvice != nil {
+ return errAdvice, nil
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ listener := &TableRequirePKListener{
+ level: level,
+ title: string(ctx.Rule.Type),
+ currentSchema: ctx.CurrentSchema,
+ tableWitPK: make(map[string]bool),
+ tableLine: make(map[string]int),
+ }
+
+ antlr.ParseTreeWalkerDefault.Walk(listener, tree)
+
+ return listener.generateAdvice()
+}
+
+// TableRequirePKListener is the listener used to collect table requires PK.
+type TableRequirePKListener struct {
+ *parser.BasePlSqlParserListener
+
+ level advisor.Status
+ title string
+ currentSchema string
+ tableName string
+ tableWitPK map[string]bool
+ tableLine map[string]int
+}
+
+func (l *TableRequirePKListener) generateAdvice() ([]advisor.Advice, error) {
+ advice := []advisor.Advice{}
+ for tableName, hasPK := range l.tableWitPK {
+ if !hasPK {
+ advice = append(advice, advisor.Advice{
+ Status: l.level,
+ Code: advisor.TableNoPK,
+ Title: l.title,
+ Content: fmt.Sprintf("Table %s requires PRIMARY KEY.", normalizeTableName(tableName)),
+ Line: l.tableLine[tableName],
+ })
+ }
+ }
+
+ if len(advice) == 0 {
+ advice = append(advice, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return advice, nil
+}
+
+// EnterCreate_table is called when production create_table is entered.
+func (l *TableRequirePKListener) EnterCreate_table(ctx *parser.Create_tableContext) {
+ schemaName := l.currentSchema
+ if ctx.Schema_name() != nil {
+ schemaName = normalizeIdentifier(ctx.Schema_name(), l.currentSchema)
+ }
+
+ l.tableName = fmt.Sprintf("%s.%s", schemaName, normalizeIdentifier(ctx.Table_name(), l.currentSchema))
+ l.tableWitPK[l.tableName] = false
+ l.tableLine[l.tableName] = ctx.GetStop().GetLine()
+}
+
+// ExitCreate_table is called when production create_table is exited.
+func (l *TableRequirePKListener) ExitCreate_table(_ *parser.Create_tableContext) {
+ l.tableName = ""
+}
+
+// EnterInline_constraint is called when production inline_constraint is entered.
+func (l *TableRequirePKListener) EnterInline_constraint(ctx *parser.Inline_constraintContext) {
+ if ctx.PRIMARY() != nil {
+ if _, exists := l.tableWitPK[l.tableName]; exists {
+ l.tableWitPK[l.tableName] = true
+ }
+ }
+}
+
+// EnterConstraint_clauses is called when production constraint_clauses is entered.
+func (l *TableRequirePKListener) EnterConstraint_clauses(ctx *parser.Constraint_clausesContext) {
+ if ctx.PRIMARY() != nil {
+ if _, exists := l.tableWitPK[l.tableName]; exists {
+ l.tableWitPK[l.tableName] = true
+ }
+ }
+}
+
+// EnterOut_of_line_constraint is called when production out_of_line_constraint is entered.
+func (l *TableRequirePKListener) EnterOut_of_line_constraint(ctx *parser.Out_of_line_constraintContext) {
+ if ctx.PRIMARY() != nil {
+ if _, exists := l.tableWitPK[l.tableName]; exists {
+ l.tableWitPK[l.tableName] = true
+ }
+ }
+}
+
+// EnterAlter_table is called when production alter_table is entered.
+func (l *TableRequirePKListener) EnterAlter_table(ctx *parser.Alter_tableContext) {
+ l.tableName = normalizeIdentifier(ctx.Tableview_name(), l.currentSchema)
+}
+
+// ExitAlter_table is called when production alter_table is exited.
+func (l *TableRequirePKListener) ExitAlter_table(_ *parser.Alter_tableContext) {
+ l.tableName = ""
+}
+
+// EnterDrop_table is called when production drop_table is entered.
+func (l *TableRequirePKListener) EnterDrop_table(ctx *parser.Drop_tableContext) {
+ tableName := normalizeIdentifier(ctx.Tableview_name(), l.currentSchema)
+ if _, exists := l.tableWitPK[tableName]; !exists {
+ return
+ }
+ delete(l.tableWitPK, tableName)
+}
+
+// EnterDrop_primary_key_or_unique_or_generic_clause is called when production drop_primary_key_or_unique_or_generic_clause is entered.
+func (l *TableRequirePKListener) EnterDrop_primary_key_or_unique_or_generic_clause(ctx *parser.Drop_primary_key_or_unique_or_generic_clauseContext) {
+ if _, exists := l.tableWitPK[l.tableName]; exists && ctx.PRIMARY() != nil {
+ l.tableWitPK[l.tableName] = false
+ l.tableLine[l.tableName] = ctx.GetStop().GetLine()
+ }
+}
diff --git a/backend/plugin/advisor/oracle/oracle_rules_test.go b/backend/plugin/advisor/oracle/oracle_rules_test.go
new file mode 100644
index 0000000000..6ea4585b6f
--- /dev/null
+++ b/backend/plugin/advisor/oracle/oracle_rules_test.go
@@ -0,0 +1,19 @@
+// Package oracle is the advisor for oracle database.
+package oracle
+
+import (
+ "testing"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/db"
+)
+
+func TestOracleRules(t *testing.T) {
+ oracleRules := []advisor.SQLReviewRuleType{
+ advisor.SchemaRuleTableRequirePK,
+ }
+
+ for _, rule := range oracleRules {
+ advisor.RunSQLReviewRuleTest(t, rule, db.Oracle, false /* record */)
+ }
+}
diff --git a/backend/plugin/advisor/oracle/parser.go b/backend/plugin/advisor/oracle/parser.go
new file mode 100644
index 0000000000..3179ad691d
--- /dev/null
+++ b/backend/plugin/advisor/oracle/parser.go
@@ -0,0 +1,101 @@
+// Package oracle is the advisor for oracle database.
+package oracle
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/antlr/antlr4/runtime/Go/antlr/v4"
+
+ plsql "github.com/bytebase/plsql-parser"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ parser "github.com/bytebase/bytebase/backend/plugin/parser/sql"
+)
+
+func parseStatement(statement string) (antlr.Tree, []advisor.Advice) {
+ tree, err := parser.ParsePLSQL(statement + ";")
+ if err != nil {
+ if syntaxErr, ok := err.(*parser.SyntaxError); ok {
+ return nil, []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.StatementSyntaxError,
+ Title: advisor.SyntaxErrorTitle,
+ Content: syntaxErr.Message,
+ Line: syntaxErr.Line,
+ },
+ }
+ }
+ return nil, []advisor.Advice{
+ {
+ Status: advisor.Error,
+ Code: advisor.Internal,
+ Title: "Parse error",
+ Content: err.Error(),
+ Line: 1,
+ },
+ }
+ }
+
+ return tree, nil
+}
+
+func normalizeIdentifier(ctx antlr.ParserRuleContext, currentSchema string) string {
+ switch ctx := ctx.(type) {
+ case *plsql.IdentifierContext:
+ return normalizeIdentifierContext(ctx)
+ case *plsql.Schema_nameContext:
+ return normalizeIdentifierContext(ctx.Identifier())
+ case *plsql.Table_nameContext:
+ return normalizeIdentifierContext(ctx.Identifier())
+ case *plsql.Tableview_nameContext:
+ if ctx.Identifier() != nil {
+ result := []string{normalizeIdentifierContext(ctx.Identifier())}
+ if ctx.Id_expression() != nil {
+ result = append(result, normalizeIDExpression(ctx.Id_expression()))
+ }
+ if len(result) == 1 {
+ result = []string{currentSchema, result[0]}
+ }
+ return strings.Join(result, ".")
+ }
+ return ""
+ }
+ return ""
+}
+
+func normalizeIdentifierContext(identifier plsql.IIdentifierContext) string {
+ if identifier == nil {
+ return ""
+ }
+
+ return normalizeIDExpression(identifier.Id_expression())
+}
+
+func normalizeIDExpression(idExpression plsql.IId_expressionContext) string {
+ if idExpression == nil {
+ return ""
+ }
+
+ regularID := idExpression.Regular_id()
+ if regularID != nil {
+ return strings.ToUpper(regularID.GetText())
+ }
+
+ delimitedID := idExpression.DELIMITED_ID()
+ if delimitedID != nil {
+ return strings.Trim(delimitedID.GetText(), "\"")
+ }
+
+ return ""
+}
+
+func normalizeTableName(name string) string {
+ list := strings.Split(name, ".")
+ var result []string
+ for _, item := range list {
+ result = append(result, fmt.Sprintf("\"%s\"", item))
+ }
+ return strings.Join(result, ".")
+}
diff --git a/backend/plugin/advisor/oracle/test/table_require_pk.yaml b/backend/plugin/advisor/oracle/test/table_require_pk.yaml
new file mode 100644
index 0000000000..6e4560e81f
--- /dev/null
+++ b/backend/plugin/advisor/oracle/test/table_require_pk.yaml
@@ -0,0 +1,54 @@
+- statement: CREATE TABLE abc.t(id INT PRIMARY KEY);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id INT, PRIMARY KEY (id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE "SYS".t(id INT)
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table "SYS"."T" requires PRIMARY KEY.
+ line: 1
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ DROP TABLE t
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ ALTER TABLE t ADD CONSTRAINT tpk PRIMARY KEY (id)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT PRIMARY KEY);
+ ALTER TABLE t DROP PRIMARY KEY
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table "SYS"."T" requires PRIMARY KEY.
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 2458b9d668..f5b5f32461 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -438,6 +438,9 @@ type SQLReviewCheckContext struct {
Catalog catalog.Catalog
Driver *sql.DB
Context context.Context
+
+ // Oracle specific fields
+ CurrentSchema string
}
// SQLReviewCheck checks the statements with sql review rules.
@@ -472,12 +475,13 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext S
checkContext.DbType,
advisorType,
Context{
- Charset: checkContext.Charset,
- Collation: checkContext.Collation,
- Rule: rule,
- Catalog: finder,
- Driver: checkContext.Driver,
- Context: checkContext.Context,
+ Charset: checkContext.Charset,
+ Collation: checkContext.Collation,
+ Rule: rule,
+ Catalog: finder,
+ Driver: checkContext.Driver,
+ Context: checkContext.Context,
+ CurrentSchema: checkContext.CurrentSchema,
},
statements,
)
@@ -923,6 +927,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
return MySQLTableRequirePK, nil
case db.Postgres:
return PostgreSQLTableRequirePK, nil
+ case db.Oracle:
+ return OracleTableRequirePK, nil
}
case SchemaRuleTableNoFK:
switch engine {
diff --git a/backend/plugin/advisor/utils_for_tests.go b/backend/plugin/advisor/utils_for_tests.go
index f8df596b4a..f3a4f261e0 100644
--- a/backend/plugin/advisor/utils_for_tests.go
+++ b/backend/plugin/advisor/utils_for_tests.go
@@ -174,12 +174,13 @@ func RunSQLReviewRuleTest(t *testing.T, rule SQLReviewRuleType, dbType db.Type,
}
ctx := SQLReviewCheckContext{
- Charset: "",
- Collation: "",
- DbType: dbType,
- Catalog: &testCatalog{finder: finder},
- Driver: nil,
- Context: context.Background(),
+ Charset: "",
+ Collation: "",
+ DbType: dbType,
+ Catalog: &testCatalog{finder: finder},
+ Driver: nil,
+ Context: context.Background(),
+ CurrentSchema: "SYS",
}
adviceList, err := SQLReviewCheck(tc.Statement, ruleList, ctx)
diff --git a/backend/plugin/parser/sql/plsql.go b/backend/plugin/parser/sql/plsql.go
index c532f6d044..a5e586bd6c 100644
--- a/backend/plugin/parser/sql/plsql.go
+++ b/backend/plugin/parser/sql/plsql.go
@@ -1,18 +1,28 @@
package parser
import (
- "errors"
- "strconv"
- "strings"
+ "fmt"
"github.com/antlr/antlr4/runtime/Go/antlr/v4"
parser "github.com/bytebase/plsql-parser"
)
+// SyntaxError is a syntax error.
+type SyntaxError struct {
+ Line int
+ Column int
+ Message string
+}
+
+// Error returns the error message.
+func (e *SyntaxError) Error() string {
+ return e.Message
+}
+
// PLSQLErrorListener is a custom error listener for PLSQL parser.
type PLSQLErrorListener struct {
- errors []string
+ err *SyntaxError
}
// NewPLSQLErrorListener creates a new PLSQLErrorListener.
@@ -25,7 +35,15 @@ func (l *PLSQLErrorListener) SyntaxError(_ antlr.Recognizer, _ any, line, column
if len(msg) > 1024 {
msg = msg[:1024]
}
- l.errors = append(l.errors, "line "+strconv.Itoa(line)+":"+strconv.Itoa(column)+" "+msg)
+ if l.err == nil {
+ l.err = &SyntaxError{
+ Line: line,
+ Column: column,
+ Message: fmt.Sprintf("line %d:%d %s", line, column, msg),
+ }
+ } else {
+ l.err.Message = fmt.Sprintf("%s \nline %d:%d %s", l.err.Message, line, column, msg)
+ }
}
// ReportAmbiguity reports an ambiguity.
@@ -61,12 +79,12 @@ func ParsePLSQL(sql string) (antlr.Tree, error) {
p.BuildParseTrees = true
tree := p.Sql_script()
- if len(lexerErrorListener.errors) > 0 {
- return nil, errors.New(strings.Join(lexerErrorListener.errors, " \n"))
+ if lexerErrorListener.err != nil {
+ return nil, lexerErrorListener.err
}
- if len(parserErrorListener.errors) > 0 {
- return nil, errors.New(strings.Join(parserErrorListener.errors, " \n"))
+ if parserErrorListener.err != nil {
+ return nil, parserErrorListener.err
}
return tree, nil
diff --git a/backend/plugin/parser/sql/plsql_test.go b/backend/plugin/parser/sql/plsql_test.go
index 35baa09fe4..f73c6b3064 100644
--- a/backend/plugin/parser/sql/plsql_test.go
+++ b/backend/plugin/parser/sql/plsql_test.go
@@ -11,6 +11,9 @@ func TestPLSQLParser(t *testing.T) {
statement string
errorMessage string
}{
+ {
+ statement: "SELECT * FROM t1 WHERE c1 = 1; SELECT * FROM t2;",
+ },
{
statement: "CREATE TABLE t1 (c1 NUMBER(10,2), c2 VARCHAR2(10));",
},