Skip to content

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

chore: get view definition when view dependence error appears (#5278)

rebelice67e404efece1
diff --git a/backend/plugin/advisor/catalog/test/pg_walk_through.yaml b/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
index beb3ec4bfe..a0a1dea6fa 100644
--- a/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
+++ b/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
@@ -707,18 +707,24 @@
type: 408
content: 'Cannot drop column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
line: 1
+ payload:
+ - '"public"."v1"'
- statement: ALTER TABLE test ALTER COLUMN id TYPE varchar(20);
want: null
err:
type: 408
content: 'Cannot alter type of column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
line: 1
+ payload:
+ - '"public"."v1"'
- statement: DROP TABLE test;
want: null
err:
type: 304
content: 'Cannot drop table "public"."test", it''s referenced by view: "public"."v1"'
line: 1
+ payload:
+ - '"public"."v1"'
- statement: |-
DROP VIEW v1;
ALTER TABLE test DROP COLUMN id;
diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.go
index ea7cf1a201..5de40256cf 100644
--- a/backend/plugin/advisor/catalog/walk_through.go
+++ b/backend/plugin/advisor/catalog/walk_through.go
@@ -129,6 +129,8 @@ type WalkThroughError struct {
Type WalkThroughErrorType
Content string
Line int
+
+ Payload interface{}
}
// NewParseError returns a new ErrorTypeParseError.
diff --git a/backend/plugin/advisor/catalog/walk_through_for_pg.go b/backend/plugin/advisor/catalog/walk_through_for_pg.go
index b418426884..a9f2f71a22 100644
--- a/backend/plugin/advisor/catalog/walk_through_for_pg.go
+++ b/backend/plugin/advisor/catalog/walk_through_for_pg.go
@@ -198,6 +198,7 @@ func (d *DatabaseState) pgDropTable(tableDef *ast.TableDef, ifExists bool, _ ast
return &WalkThroughError{
Type: ErrorTypeTableIsReferencedByView,
Content: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", schema.name, table.name, strings.Join(viewList, ", ")),
+ Payload: viewList,
}
}
@@ -415,6 +416,7 @@ func (d *DatabaseState) pgAlterColumnType(schema *SchemaState, t *TableState, no
return &WalkThroughError{
Type: ErrorTypeColumnIsReferencedByView,
Content: fmt.Sprintf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, t.name, strings.Join(viewList, ", ")),
+ Payload: viewList,
}
}
@@ -448,6 +450,7 @@ func (d *DatabaseState) pgDropColumn(schema *SchemaState, t *TableState, node *a
return &WalkThroughError{
Type: ErrorTypeColumnIsReferencedByView,
Content: fmt.Sprintf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, t.name, strings.Join(viewList, ", ")),
+ Payload: viewList,
}
}
diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.go
index 345120203e..6eebd2aab8 100644
--- a/backend/plugin/advisor/catalog/walk_through_test.go
+++ b/backend/plugin/advisor/catalog/walk_through_test.go
@@ -105,6 +105,14 @@ func TestPostgreSQLWalkThrough(t *testing.T) {
}
}
+func convertInterfaceSliceToStringSlice(slice []interface{}) []string {
+ var res []string
+ for _, item := range slice {
+ res = append(res, item.(string))
+ }
+ return res
+}
+
func runWalkThroughTest(t *testing.T, file string, engineType db.Type, originDatabase *storepb.DatabaseMetadata, record bool) {
tests := []testData{}
filepath := filepath.Join("test", file+".yaml")
@@ -133,7 +141,19 @@ func runWalkThroughTest(t *testing.T, file string, engineType db.Type, originDat
require.True(t, ok)
tests[i].Err = walkThroughError
} else {
- require.Equal(t, err, test.Err)
+ err, yes := err.(*WalkThroughError)
+ require.True(t, yes)
+ if err.Payload != nil {
+ actualPayloadText, yes := err.Payload.([]string)
+ require.True(t, yes)
+ expectedPayloadText := convertInterfaceSliceToStringSlice(test.Err.Payload.([]interface{}))
+ err.Payload = nil
+ test.Err.Payload = nil
+ require.Equal(t, test.Err, err)
+ require.Equal(t, expectedPayloadText, actualPayloadText)
+ } else {
+ require.Equal(t, test.Err, err)
+ }
}
continue
}
diff --git a/backend/plugin/advisor/code.go b/backend/plugin/advisor/code.go
index 0194831839..3947a259e9 100644
--- a/backend/plugin/advisor/code.go
+++ b/backend/plugin/advisor/code.go
@@ -74,6 +74,7 @@ const (
DefaultCurrentTimeColumnCountExceedsLimit Code = 418
OnUpdateCurrentTimeColumnCountExceedsLimit Code = 419
NoDefault Code = 420
+ ColumnIsReferencedByView Code = 421
// 501 engine error code.
NotInnoDBEngine Code = 501
@@ -87,6 +88,7 @@ const (
TableCommentTooLong Code = 606
TableExists Code = 607
CreateTablePartition Code = 608
+ TableIsReferencedByView Code = 609
// 701 ~ 799 database advisor error code.
DatabaseNotEmpty Code = 701
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index e447da6bb9..e673da51b1 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -1,14 +1,18 @@
package advisor
import (
+ "bytes"
"context"
"database/sql"
"encoding/json"
- "log"
+ "fmt"
"regexp"
+ "strings"
"github.com/pkg/errors"
+ "go.uber.org/zap"
+ "github.com/bytebase/bytebase/backend/common/log"
"github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
"github.com/bytebase/bytebase/backend/plugin/advisor/db"
)
@@ -443,7 +447,7 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext S
switch checkContext.DbType {
case db.TiDB, db.MySQL, db.MariaDB, db.Postgres:
if err := finder.WalkThrough(statements); err != nil {
- return convertWalkThroughErrorToAdvice(err)
+ return convertWalkThroughErrorToAdvice(checkContext, err)
}
}
@@ -458,7 +462,7 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext S
advisorType, err := getAdvisorTypeByRule(rule.Type, checkContext.DbType)
if err != nil {
if rule.Engine != "" {
- log.Printf("not supported rule: %v. error: %v\n", rule.Type, err)
+ log.Warn("not supported rule", zap.String("rule type", string(rule.Type)), zap.String("engine", string(rule.Engine)), zap.Error(err))
}
continue
}
@@ -498,7 +502,7 @@ func SQLReviewCheck(statements string, ruleList []*SQLReviewRule, checkContext S
return result, nil
}
-func convertWalkThroughErrorToAdvice(err error) ([]Advice, error) {
+func convertWalkThroughErrorToAdvice(checkContext SQLReviewCheckContext, err error) ([]Advice, error) {
walkThroughError, ok := err.(*catalog.WalkThroughError)
if !ok {
return nil, err
@@ -641,6 +645,48 @@ func convertWalkThroughErrorToAdvice(err error) ([]Advice, error) {
Content: walkThroughError.Content,
Line: walkThroughError.Line,
})
+ case catalog.ErrorTypeColumnIsReferencedByView:
+ content := walkThroughError.Content
+ if checkContext.DbType == db.Postgres {
+ list, yes := walkThroughError.Payload.([]string)
+ if !yes {
+ return nil, errors.Errorf("invalid payload for ColumnIsReferencedByView, expect []string but found %T", walkThroughError.Payload)
+ }
+ if definition, err := getViewDefinition(checkContext, list); err != nil {
+ log.Warn("failed to get view definition", zap.Error(err))
+ } else {
+ content = fmt.Sprintf("%s\n\n%s", content, definition)
+ }
+ }
+
+ res = append(res, Advice{
+ Status: Error,
+ Code: ColumnIsReferencedByView,
+ Title: "Column is referenced by view",
+ Content: content,
+ Line: walkThroughError.Line,
+ })
+ case catalog.ErrorTypeTableIsReferencedByView:
+ content := walkThroughError.Content
+ if checkContext.DbType == db.Postgres {
+ list, yes := walkThroughError.Payload.([]string)
+ if !yes {
+ return nil, errors.Errorf("invalid payload for TableIsReferencedByView, expect []string but found %T", walkThroughError.Payload)
+ }
+ if definition, err := getViewDefinition(checkContext, list); err != nil {
+ log.Warn("failed to get view definition", zap.Error(err))
+ } else {
+ content = fmt.Sprintf("%s\n\n%s", content, definition)
+ }
+ }
+
+ res = append(res, Advice{
+ Status: Error,
+ Code: TableIsReferencedByView,
+ Title: "Table is referenced by view",
+ Content: content,
+ Line: walkThroughError.Line,
+ })
default:
res = append(res, Advice{
Status: Error,
@@ -654,6 +700,49 @@ func convertWalkThroughErrorToAdvice(err error) ([]Advice, error) {
return res, nil
}
+func getViewDefinition(checkContext SQLReviewCheckContext, viewList []string) (string, error) {
+ var buf bytes.Buffer
+ sql := fmt.Sprintf(`
+ WITH view_list(view_name) AS (
+ VALUES ('%s')
+ )
+ SELECT view_name, pg_get_viewdef(view_name) AS view_definition
+ FROM view_list;
+ `, strings.Join(viewList, "'),('"))
+
+ rows, err := checkContext.Driver.QueryContext(checkContext.Context, sql)
+ if err != nil {
+ return "", err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var viewName, viewDefinition string
+ if err := rows.Scan(&viewName, &viewDefinition); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString("The definition of view "); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString(viewName); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString(" is \n"); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString(viewDefinition); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString("\n\n"); err != nil {
+ return "", err
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return "", err
+ }
+
+ return buf.String(), nil
+}
+
// RuleExists returns true if rule exists.
func RuleExists(ruleType SQLReviewRuleType, engine db.Type) bool {
_, err := getAdvisorTypeByRule(ruleType, engine)