Skip to content

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

feat: check dependence when drop column/table or alter column type (#5173)

rebelice1c5dac6136a1
diff --git a/backend/plugin/advisor/catalog/state.go b/backend/plugin/advisor/catalog/state.go
index e7620059dd..127cc33e64 100644
--- a/backend/plugin/advisor/catalog/state.go
+++ b/backend/plugin/advisor/catalog/state.go
@@ -5,6 +5,7 @@ package catalog
// 2. the underlying implementation of Finder
import (
+ "fmt"
"strings"
"github.com/bytebase/bytebase/backend/plugin/advisor/db"
@@ -26,6 +27,21 @@ func newDatabaseState(d *storepb.DatabaseMetadata, context *FinderContext) *Data
database.schemaSet[schema.Name] = newSchemaState(schema, database.ctx)
}
+ for _, schema := range d.Schemas {
+ for _, view := range schema.Views {
+ for _, dependentColumn := range view.DependentColumns {
+ if schemaState, exist := database.schemaSet[dependentColumn.Schema]; exist {
+ if tableState, exist := schemaState.tableSet[dependentColumn.Table]; exist {
+ tableState.dependentView[fmt.Sprintf("%q.%q", schema.Name, view.Name)] = true
+ if columnState, exist := tableState.columnSet[dependentColumn.Column]; exist {
+ columnState.dependentView[fmt.Sprintf("%q.%q", schema.Name, view.Name)] = true
+ }
+ }
+ }
+ }
+ }
+ }
+
return database
}
@@ -67,12 +83,13 @@ func newViewState(v *storepb.ViewMetadata) *ViewState {
func newTableState(t *storepb.TableMetadata) *TableState {
table := &TableState{
- name: t.Name,
- engine: newStringPointer(t.Engine),
- collation: newStringPointer(t.Collation),
- comment: newStringPointer(t.Comment),
- columnSet: make(columnStateMap),
- indexSet: make(indexStateMap),
+ name: t.Name,
+ engine: newStringPointer(t.Engine),
+ collation: newStringPointer(t.Collation),
+ comment: newStringPointer(t.Comment),
+ columnSet: make(columnStateMap),
+ indexSet: make(indexStateMap),
+ dependentView: make(map[string]bool),
}
for i, column := range t.Columns {
@@ -92,14 +109,15 @@ func newColumnState(c *storepb.ColumnMetadata, position int) *ColumnState {
defaultValue = copyStringPointer(&c.Default.Value)
}
return &ColumnState{
- name: c.Name,
- position: newIntPointer(position),
- defaultValue: defaultValue,
- nullable: newBoolPointer(c.Nullable),
- columnType: newStringPointer(c.Type),
- characterSet: newStringPointer(c.CharacterSet),
- collation: newStringPointer(c.Collation),
- comment: newStringPointer(c.Comment),
+ name: c.Name,
+ position: newIntPointer(position),
+ defaultValue: defaultValue,
+ nullable: newBoolPointer(c.Nullable),
+ columnType: newStringPointer(c.Type),
+ characterSet: newStringPointer(c.CharacterSet),
+ collation: newStringPointer(c.Collation),
+ comment: newStringPointer(c.Comment),
+ dependentView: make(map[string]bool),
}
}
@@ -321,6 +339,10 @@ type TableState struct {
columnSet columnStateMap
// indexSet isn't supported for ClickHouse, Snowflake.
indexSet indexStateMap
+
+ // dependentView is used to record the dependent view for the table.
+ // Used to check if the table is used by any view.
+ dependentView map[string]bool
}
// CountIndex return the index total number.
@@ -419,6 +441,10 @@ type ColumnState struct {
collation *string
// comment isn't supported for SQLite.
comment *string
+
+ // dependentView is used to record the dependent view for the column.
+ // Used to check if the column is used by any view.
+ dependentView map[string]bool
}
func (col *ColumnState) copy() *ColumnState {
diff --git a/backend/plugin/advisor/catalog/test/pg_walk_through.yaml b/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
index 35fa3f8a2f..beb3ec4bfe 100644
--- a/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
+++ b/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
@@ -32,6 +32,34 @@
createoptions: ""
comment: ""
foreignkeys: []
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -92,6 +120,34 @@
createoptions: ""
comment: ""
foreignkeys: []
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -182,6 +238,34 @@
createoptions: ""
comment: ""
foreignkeys: []
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -292,6 +376,34 @@
createoptions: ""
comment: ""
foreignkeys: []
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -383,6 +495,34 @@
createoptions: ""
comment: ""
foreignkeys: []
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -465,6 +605,34 @@
createoptions: ""
comment: ""
foreignkeys: []
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -483,7 +651,35 @@
name: postgres
schemas:
- name: public
- tables: []
+ tables:
+ - name: test
+ columns:
+ - name: id
+ position: 1
+ default: null
+ nullable: false
+ type: int
+ characterset: ""
+ collation: ""
+ comment: ""
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
views: []
characterset: ""
collation: ""
@@ -505,3 +701,54 @@
collation: ""
extensions: []
err: null
+- statement: ALTER TABLE test DROP COLUMN id;
+ want: null
+ err:
+ type: 408
+ content: 'Cannot drop column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
+ line: 1
+- 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
+- statement: DROP TABLE test;
+ want: null
+ err:
+ type: 304
+ content: 'Cannot drop table "public"."test", it''s referenced by view: "public"."v1"'
+ line: 1
+- statement: |-
+ DROP VIEW v1;
+ ALTER TABLE test DROP COLUMN id;
+ want:
+ name: postgres
+ schemas:
+ - name: public
+ tables:
+ - name: test
+ columns:
+ - name: name
+ position: 2
+ default: null
+ nullable: true
+ type: varchar(20)
+ characterset: ""
+ collation: ""
+ comment: ""
+ indexes: []
+ engine: ""
+ collation: ""
+ rowcount: 0
+ datasize: 0
+ indexsize: 0
+ datafree: 0
+ createoptions: ""
+ comment: ""
+ foreignkeys: []
+ views: []
+ characterset: ""
+ collation: ""
+ extensions: []
+ err: null
diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.go
index 202ed7f908..e12bb7bb26 100644
--- a/backend/plugin/advisor/catalog/walk_through.go
+++ b/backend/plugin/advisor/catalog/walk_through.go
@@ -56,6 +56,10 @@ const (
ErrorTypeTableNotExists = 302
// ErrorTypeUseCreateTableAs is the error that using CREATE TABLE AS statements.
ErrorTypeUseCreateTableAs = 303
+ // ErrorTypeTableIsReferencedByView is the error that table is referenced by view.
+ ErrorTypeTableIsReferencedByView = 304
+ // ErrorTypeViewNotExists is the error that view not exists.
+ ErrorTypeViewNotExists = 305
// 401 ~ 499 column error type.
@@ -73,6 +77,8 @@ const (
ErrorTypeSetNullDefaultForNotNullColumn = 406
// ErrorTypeInvalidColumnTypeForDefaultValue is the error that invalid column type for default value.
ErrorTypeInvalidColumnTypeForDefaultValue = 407
+ // ErrorTypeColumnIsReferencedByView is the error that column is referenced by view.
+ ErrorTypeColumnIsReferencedByView = 408
// 501 ~ 599 index error type.
diff --git a/backend/plugin/advisor/catalog/walk_through_for_pg.go b/backend/plugin/advisor/catalog/walk_through_for_pg.go
index c9fe851a22..b418426884 100644
--- a/backend/plugin/advisor/catalog/walk_through_for_pg.go
+++ b/backend/plugin/advisor/catalog/walk_through_for_pg.go
@@ -2,8 +2,11 @@ package catalog
import (
"fmt"
+ "regexp"
"strings"
+ "github.com/pkg/errors"
+
"github.com/bytebase/bytebase/backend/plugin/parser"
"github.com/bytebase/bytebase/backend/plugin/parser/ast"
)
@@ -100,14 +103,76 @@ func (d *DatabaseState) pgDropIndex(indexDef *ast.IndexDef, ifExists bool, _ ast
func (d *DatabaseState) pgDropTableList(node *ast.DropTableStmt) *WalkThroughError {
for _, tableName := range node.TableList {
- if err := d.pgDropTable(tableName, node.IfExists, node.Behavior); err != nil {
- return err
+ if tableName.Type == ast.TableTypeView {
+ if err := d.pgDropView(tableName, node.IfExists, node.Behavior); err != nil {
+ return err
+ }
+ } else {
+ if err := d.pgDropTable(tableName, node.IfExists, node.Behavior); err != nil {
+ return err
+ }
}
}
return nil
}
+func (d *DatabaseState) pgDropView(tableDef *ast.TableDef, ifExists bool, _ ast.DropBehavior) *WalkThroughError {
+ schema, err := d.getSchema(tableDef.Schema)
+ if err != nil {
+ if ifExists {
+ return nil
+ }
+ return err
+ }
+
+ view, err := schema.getView(tableDef.Name)
+ if err != nil {
+ return err
+ }
+
+ delete(schema.identifierMap, view.name)
+ delete(schema.viewSet, view.name)
+ return nil
+}
+
+func parseViewName(viewName string) (string, string, error) {
+ pattern := `^"(.+?)"\."(.+?)"$`
+
+ re := regexp.MustCompile(pattern)
+
+ match := re.FindStringSubmatch(viewName)
+
+ if len(match) != 3 {
+ return "", "", errors.Errorf("invalid view name: %s", viewName)
+ }
+
+ return match[1], match[2], nil
+}
+
+func (d *DatabaseState) existedViewList(viewMap map[string]bool) ([]string, *WalkThroughError) {
+ var result []string
+ for viewName := range viewMap {
+ schemaName, viewName, err := parseViewName(viewName)
+ if err != nil {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeInternal,
+ Content: fmt.Sprintf("failed to check view dependency: %s", err.Error()),
+ }
+ }
+ schemaMeta, exists := d.schemaSet[schemaName]
+ if !exists {
+ continue
+ }
+ if _, exists := schemaMeta.viewSet[viewName]; !exists {
+ continue
+ }
+
+ result = append(result, fmt.Sprintf("%q.%q", schemaName, viewName))
+ }
+ return result, nil
+}
+
func (d *DatabaseState) pgDropTable(tableDef *ast.TableDef, ifExists bool, _ ast.DropBehavior) *WalkThroughError {
schema, err := d.getSchema(tableDef.Schema)
if err != nil {
@@ -125,6 +190,17 @@ func (d *DatabaseState) pgDropTable(tableDef *ast.TableDef, ifExists bool, _ ast
return err
}
+ viewList, err := d.existedViewList(table.dependentView)
+ if err != nil {
+ return err
+ }
+ if len(viewList) > 0 {
+ 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, ", ")),
+ }
+ }
+
for indexName := range table.indexSet {
delete(schema.identifierMap, indexName)
}
@@ -235,11 +311,11 @@ func (d *DatabaseState) pgAlterTable(node *ast.AlterTableStmt) *WalkThroughError
return err
}
case *ast.DropColumnStmt:
- if err := schema.pgDropColumn(table, itemNode); err != nil {
+ if err := d.pgDropColumn(schema, table, itemNode); err != nil {
return err
}
case *ast.AlterColumnTypeStmt:
- if err := schema.pgAlterColumnType(table, itemNode); err != nil {
+ if err := d.pgAlterColumnType(schema, table, itemNode); err != nil {
return err
}
case *ast.SetDefaultStmt:
@@ -325,12 +401,23 @@ func (t *TableState) pgSetDefault(node *ast.SetDefaultStmt) *WalkThroughError {
return nil
}
-func (*SchemaState) pgAlterColumnType(t *TableState, node *ast.AlterColumnTypeStmt) *WalkThroughError {
+func (d *DatabaseState) pgAlterColumnType(schema *SchemaState, t *TableState, node *ast.AlterColumnTypeStmt) *WalkThroughError {
column, err := t.getColumn(node.ColumnName)
if err != nil {
return err
}
+ viewList, err := d.existedViewList(column.dependentView)
+ if err != nil {
+ return err
+ }
+ if len(viewList) > 0 {
+ 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, ", ")),
+ }
+ }
+
typeString, deparseErr := parser.Deparse(parser.Postgres, parser.DeparseContext{}, node.Type)
if deparseErr != nil {
return &WalkThroughError{
@@ -344,14 +431,26 @@ func (*SchemaState) pgAlterColumnType(t *TableState, node *ast.AlterColumnTypeSt
return nil
}
-func (*SchemaState) pgDropColumn(t *TableState, node *ast.DropColumnStmt) *WalkThroughError {
- if _, exists := t.columnSet[node.ColumnName]; !exists {
+func (d *DatabaseState) pgDropColumn(schema *SchemaState, t *TableState, node *ast.DropColumnStmt) *WalkThroughError {
+ column, exists := t.columnSet[node.ColumnName]
+ if !exists {
if node.IfExists {
return nil
}
return NewColumnNotExistsError(t.name, node.ColumnName)
}
+ viewList, err := d.existedViewList(column.dependentView)
+ if err != nil {
+ return err
+ }
+ if len(viewList) > 0 {
+ 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, ", ")),
+ }
+ }
+
// Drop the constraints and indexes involving the column.
var dropIndexList []string
@@ -924,6 +1023,17 @@ func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThrough
return schema, nil
}
+func (s *SchemaState) getView(viewName string) (*ViewState, *WalkThroughError) {
+ view, exists := s.viewSet[viewName]
+ if !exists {
+ return nil, &WalkThroughError{
+ Type: ErrorTypeViewNotExists,
+ Content: fmt.Sprintf("The view %q doesn't exists in schema %q", viewName, s.name),
+ }
+ }
+ return view, nil
+}
+
func (s *SchemaState) getTable(tableName string) (*TableState, *WalkThroughError) {
table, exists := s.tableSet[tableName]
if !exists {
diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.go
index 246986a388..345120203e 100644
--- a/backend/plugin/advisor/catalog/walk_through_test.go
+++ b/backend/plugin/advisor/catalog/walk_through_test.go
@@ -57,6 +57,41 @@ func TestPostgreSQLWalkThrough(t *testing.T) {
Schemas: []*storepb.SchemaMetadata{
{
Name: "public",
+ Tables: []*storepb.TableMetadata{
+ {
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "id",
+ Type: "int",
+ Nullable: false,
+ },
+ {
+ Name: "name",
+ Type: "varchar(20)",
+ Nullable: true,
+ },
+ },
+ },
+ },
+ Views: []*storepb.ViewMetadata{
+ {
+ Name: "v1",
+ Definition: "SELECT id, name FROM test",
+ DependentColumns: []*storepb.DependentColumn{
+ {
+ Schema: "public",
+ Table: "test",
+ Column: "id",
+ },
+ {
+ Schema: "public",
+ Table: "test",
+ Column: "name",
+ },
+ },
+ },
+ },
},
},
}
@@ -92,7 +127,7 @@ func runWalkThroughTest(t *testing.T, file string, engineType db.Type, originDat
}
err := state.WalkThrough(test.Statement)
- if test.Err != nil {
+ if err != nil {
if record {
walkThroughError, ok := err.(*WalkThroughError)
require.True(t, ok)