Skip to content

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

feat(advisor): implement PG specify-column-for-insert rule (#4169)

rebelicef01f9d8020fa
diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.go
index b47e205438..b8f3a358c7 100644
--- a/plugin/advisor/advisor.go
+++ b/plugin/advisor/advisor.go
@@ -254,6 +254,9 @@ const (
// PostgreSQLInsertRowLimit is an advisor type for PostgreSQL to limit INSERT rows.
PostgreSQLInsertRowLimit Type = "bb.plugin.advisor.postgresql.insert.row-limit"
+ // PostgreSQLInsertMustSpecifyColumn is an advisor type for PostgreSQL to enforce column specified.
+ PostgreSQLInsertMustSpecifyColumn Type = "bb.plugin.advisor.postgresql.insert.must-specify-column"
+
// PostgreSQLIndexKeyNumberLimit is an advisor type for postgresql index key number limit.
PostgreSQLIndexKeyNumberLimit Type = "bb.plugin.advisor.postgresql.index.key-number-limit"
diff --git a/plugin/advisor/pg/advisor_insert_must_specify_column.go b/plugin/advisor/pg/advisor_insert_must_specify_column.go
new file mode 100644
index 0000000000..0fb47cdd4a
--- /dev/null
+++ b/plugin/advisor/pg/advisor_insert_must_specify_column.go
@@ -0,0 +1,78 @@
+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 = (*InsertMustSpecifyColumnAdvisor)(nil)
+ _ ast.Visitor = (*insertMustSpecifyColumnChecker)(nil)
+)
+
+func init() {
+ advisor.Register(db.Postgres, advisor.PostgreSQLInsertMustSpecifyColumn, &InsertMustSpecifyColumnAdvisor{})
+}
+
+// InsertMustSpecifyColumnAdvisor is the advisor checking for to enforce column specified.
+type InsertMustSpecifyColumnAdvisor struct {
+}
+
+// Check checks for to enforce column specified.
+func (*InsertMustSpecifyColumnAdvisor) 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
+ }
+ checker := &insertMustSpecifyColumnChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ 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 insertMustSpecifyColumnChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+}
+
+// Visit implements ast.Visitor interface.
+func (checker *insertMustSpecifyColumnChecker) Visit(in ast.Node) ast.Visitor {
+ if node, ok := in.(*ast.InsertStmt); ok && len(node.ColumnList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.InsertNotSpecifyColumn,
+ Title: checker.title,
+ Content: fmt.Sprintf("The INSERT statement must specify columns but \"%s\" does not", checker.text),
+ Line: node.LastLine(),
+ })
+ }
+
+ return checker
+}
diff --git a/plugin/advisor/pg/pg_rules_test.go b/plugin/advisor/pg/pg_rules_test.go
index cd3036bf1c..80a276471d 100644
--- a/plugin/advisor/pg/pg_rules_test.go
+++ b/plugin/advisor/pg/pg_rules_test.go
@@ -35,6 +35,7 @@ func TestPostgreSQLRules(t *testing.T) {
advisor.SchemaRuleColumnMaximumCharacterLength,
advisor.SchemaRuleStatementDisallowCommit,
advisor.SchemaRuleStatementDMLDryRun,
+ advisor.SchemaRuleStatementInsertMustSpecifyColumn,
}
for _, rule := range pgRules {
diff --git a/plugin/advisor/pg/test/statement_insert_must_specify_column.yaml b/plugin/advisor/pg/test/statement_insert_must_specify_column.yaml
new file mode 100644
index 0000000000..bcf13aec8f
--- /dev/null
+++ b/plugin/advisor/pg/test/statement_insert_must_specify_column.yaml
@@ -0,0 +1,14 @@
+- statement: INSERT INTO tech_book(id, name) VALUES (1, '1')
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+- statement: INSERT INTO tech_book VALUES (1, '1')
+ want:
+ - status: WARN
+ code: 1107
+ title: statement.insert.must-specify-column
+ content: The INSERT statement must specify columns but "INSERT INTO tech_book VALUES (1, '1')" does not
+ line: 1
diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.go
index 0678c8ae36..89a0e7c595 100644
--- a/plugin/advisor/sql_review.go
+++ b/plugin/advisor/sql_review.go
@@ -884,6 +884,8 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, err
switch engine {
case db.MySQL, db.TiDB:
return MySQLInsertMustSpecifyColumn, nil
+ case db.Postgres:
+ return PostgreSQLInsertMustSpecifyColumn, nil
}
case SchemaRuleStatementInsertDisallowOrderByRand:
switch engine {
diff --git a/plugin/advisor/utils.go b/plugin/advisor/utils.go
index 31757202af..67c3520940 100644
--- a/plugin/advisor/utils.go
+++ b/plugin/advisor/utils.go
@@ -6,6 +6,15 @@ import (
"strings"
)
+// NormalizeStatement limit the max length of the statements.
+func NormalizeStatement(statement string) string {
+ maxLength := 1000
+ if len(statement) > maxLength {
+ return statement[:maxLength] + "..."
+ }
+ return statement
+}
+
// Query runs the EXPLAIN or SELECT statements for advisors.
func Query(ctx context.Context, connection *sql.DB, statement string) ([]interface{}, error) {
tx, err := connection.BeginTx(ctx, &sql.TxOptions{})
diff --git a/plugin/parser/ast/insert_stmt.go b/plugin/parser/ast/insert_stmt.go
index e326706794..cecec77779 100644
--- a/plugin/parser/ast/insert_stmt.go
+++ b/plugin/parser/ast/insert_stmt.go
@@ -4,7 +4,8 @@ package ast
type InsertStmt struct {
dml
- Table *TableDef
- ValueList [][]ExpressionNode
- Select *SelectStmt
+ Table *TableDef
+ ColumnList []string
+ ValueList [][]ExpressionNode
+ Select *SelectStmt
}
diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.go
index b0f287df6b..93e290f29c 100644
--- a/plugin/parser/engine/pg/convert.go
+++ b/plugin/parser/engine/pg/convert.go
@@ -583,6 +583,14 @@ func convert(node *pgquery.Node, statement parser.SingleSQL) (res ast.Node, err
Table: convertRangeVarToTableName(in.InsertStmt.Relation, ast.TableTypeBaseTable),
}
+ for _, columnNode := range in.InsertStmt.Cols {
+ if column, ok := columnNode.Node.(*pgquery.Node_ResTarget); ok {
+ insertStmt.ColumnList = append(insertStmt.ColumnList, column.ResTarget.Name)
+ } else {
+ return nil, parser.NewConvertErrorf("expected ResTarget but found %t", columnNode.Node)
+ }
+ }
+
if in.InsertStmt.SelectStmt != nil {
if selectNode, ok := in.InsertStmt.SelectStmt.Node.(*pgquery.Node_SelectStmt); ok {
// PG parser will parse the value list as a SELECT statement.
diff --git a/plugin/parser/engine/pg/convert_test.go b/plugin/parser/engine/pg/convert_test.go
index 97922e5578..a204f3eaea 100644
--- a/plugin/parser/engine/pg/convert_test.go
+++ b/plugin/parser/engine/pg/convert_test.go
@@ -2044,13 +2044,17 @@ func TestAlterColumnType(t *testing.T) {
func TestInsertStmt(t *testing.T) {
tests := []testData{
{
- stmt: "INSERT INTO tech_book VALUES (1, 'a'), (2, 'b')",
+ stmt: "INSERT INTO tech_book(a, b) VALUES (1, 'a'), (2, 'b')",
want: []ast.Node{
&ast.InsertStmt{
Table: &ast.TableDef{
Type: ast.TableTypeBaseTable,
Name: "tech_book",
},
+ ColumnList: []string{
+ "a",
+ "b",
+ },
ValueList: [][]ast.ExpressionNode{
{
&ast.UnconvertedExpressionDef{},
@@ -2069,7 +2073,7 @@ func TestInsertStmt(t *testing.T) {
},
statementList: []parser.SingleSQL{
{
- Text: "INSERT INTO tech_book VALUES (1, 'a'), (2, 'b')",
+ Text: "INSERT INTO tech_book(a, b) VALUES (1, 'a'), (2, 'b')",
LastLine: 1,
},
},