Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(advisor/pg): resolve unqualified tables through search_path in TABLE_REQUIRE_PK
rebelice68a25b09ca04
diff --git a/backend/plugin/advisor/pg/advisor_table_require_pk.go b/backend/plugin/advisor/pg/advisor_table_require_pk.goindex f095a139b0..598e215273 100644--- a/backend/plugin/advisor/pg/advisor_table_require_pk.go+++ b/backend/plugin/advisor/pg/advisor_table_require_pk.go@@ -44,8 +44,16 @@ func (*TableRequirePKAdvisor) Check(_ context.Context, checkCtx advisor.Context)},originalMetadata: checkCtx.OriginalMetadata,finalMetadata: checkCtx.FinalMetadata,+ searchPath: []string{"public"},tableMentions: make(map[string]*tableMention),}+ if checkCtx.OriginalMetadata != nil {+ // Resolve $user against SessionUser so unqualified names land in the+ // same schema the walkthrough uses when building FinalMetadata.+ if sp := checkCtx.OriginalMetadata.GetSearchPathForCurrentUser(checkCtx.SessionUser); len(sp) > 0 {+ rule.searchPath = sp+ }+ }// Manually iterate statements instead of using RunOmniRules because// validateFinalState must be called AFTER all statements have been processed.@@ -75,6 +83,8 @@ type tableRequirePKRule struct {OmniBaseRuleoriginalMetadata *model.DatabaseMetadatafinalMetadata *model.DatabaseMetadata+ // searchPath resolves unqualified table names; never empty.+ searchPath []string// Track last mention of each tabletableMentions map[string]*tableMention // key: "schema.table", value: last mention info@@ -104,7 +114,7 @@ func (r *tableRequirePKRule) handleCreateStmt(n *ast.CreateStmt) {if tableName == "" {return}- schema := omniSchemaName(n.Relation)+ schema := r.resolveSchema(n.Relation.Schemaname, tableName)key := fmt.Sprintf("%s.%s", schema, tableName)r.tableMentions[key] = &tableMention{@@ -121,11 +131,13 @@ func (r *tableRequirePKRule) handleAlterTableStmt(n *ast.AlterTableStmt) {if tableName == "" {return}- schema := omniSchemaName(n.Relation)+ schema := r.resolveSchema(n.Relation.Schemaname, tableName)key := fmt.Sprintf("%s.%s", schema, tableName)- if _, tracked := r.tableMentions[key]; !tracked && !r.originalTableHasPK(schema, tableName) {- return+ if _, tracked := r.tableMentions[key]; !tracked {+ if table := r.originalTable(schema, tableName); table == nil || table.GetPrimaryKey() == nil {+ return+ }}r.tableMentions[key] = &tableMention{startLine: int(r.ContentStartLine()) + r.BaseLine,@@ -139,19 +151,59 @@ func (r *tableRequirePKRule) handleDropStmt(n *ast.DropStmt) {return}- for _, obj := range omniDropObjects(n) {- key := fmt.Sprintf("%s.%s", obj[0], obj[1])- delete(r.tableMentions, key)+ if n.Objects == nil {+ return+ }+ for _, item := range n.Objects.Items {+ list, ok := item.(*ast.List)+ if !ok {+ continue+ }+ var parts []string+ for _, nameItem := range list.Items {+ if s, ok := nameItem.(*ast.String); ok {+ parts = append(parts, s.Str)+ }+ }+ var schema, tableName string+ switch len(parts) {+ case 1:+ tableName = parts[0]+ case 2:+ schema, tableName = parts[0], parts[1]+ default:+ continue+ }+ delete(r.tableMentions, fmt.Sprintf("%s.%s", r.resolveSchema(schema, tableName), tableName))+ }+}++// resolveSchema mirrors PostgreSQL name resolution. A qualified name is taken+// as-is. An unqualified name maps to the first search_path schema that already+// holds the table, either created earlier in this batch or present in the+// original metadata; otherwise to the first search_path schema, which is+// where CREATE TABLE places a new table.+func (r *tableRequirePKRule) resolveSchema(schema, tableName string) string {+ if schema != "" {+ return schema+ }+ for _, candidate := range r.searchPath {+ if _, ok := r.tableMentions[fmt.Sprintf("%s.%s", candidate, tableName)]; ok {+ return candidate+ }+ if r.originalTable(candidate, tableName) != nil {+ return candidate+ }}+ return r.searchPath[0]}-// originalTableHasPK reports whether the table had a PRIMARY KEY before this batch.-func (r *tableRequirePKRule) originalTableHasPK(schemaName, tableName string) bool {+// originalTable returns the table from the metadata before this batch, or nil.+func (r *tableRequirePKRule) originalTable(schemaName, tableName string) *model.TableMetadata {if r.originalMetadata == nil {- return false+ return nil}- table := r.originalMetadata.GetSchemaMetadata(schemaName).GetTable(tableName)- return table != nil && table.GetPrimaryKey() != nil+ return r.originalMetadata.GetSchemaMetadata(schemaName).GetTable(tableName)}// validateFinalState checks all mentioned tables against FinalMetadata for PRIMARY KEY.diff --git a/backend/plugin/advisor/pg/advisor_table_require_pk_test.go b/backend/plugin/advisor/pg/advisor_table_require_pk_test.gonew file mode 100644index 0000000000..90d1181612--- /dev/null+++ b/backend/plugin/advisor/pg/advisor_table_require_pk_test.go@@ -0,0 +1,121 @@+package pg++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"+ "google.golang.org/protobuf/proto"++ "github.com/bytebase/bytebase/backend/component/sheet"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/advisor"+ "github.com/bytebase/bytebase/backend/plugin/advisor/code"+ "github.com/bytebase/bytebase/backend/store/model"+)++// TestTableRequirePKSearchPath proves unqualified names resolve through the+// database search_path, matching the walkthrough that builds FinalMetadata.+// Both tables live only in app_schema; public is empty.+func TestTableRequirePKSearchPath(t *testing.T) {+ dbSchema := &storepb.DatabaseSchemaMetadata{+ Name: "test",+ SearchPath: "app_schema, public",+ Schemas: []*storepb.SchemaMetadata{+ {Name: "public"},+ {+ Name: "app_schema",+ Tables: []*storepb.TableMetadata{+ {+ Name: "with_pk",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer"},+ {Name: "name", Type: "text"},+ },+ Indexes: []*storepb.IndexMetadata{+ {Name: "with_pk_pkey", Expressions: []string{"id"}, Unique: true, Primary: true},+ },+ },+ {+ Name: "without_pk",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "integer"},+ },+ },+ },+ },+ },+ }++ tests := []struct {+ name string+ stmt string+ wantContent string // empty means no advice+ }{+ {+ name: "drop PK on unqualified table in non-public schema",+ stmt: "ALTER TABLE with_pk DROP CONSTRAINT with_pk_pkey;",+ wantContent: `Table "app_schema"."with_pk" requires PRIMARY KEY`,+ },+ {+ name: "drop PK column on unqualified table in non-public schema",+ stmt: "ALTER TABLE with_pk DROP COLUMN id;",+ wantContent: `Table "app_schema"."with_pk" requires PRIMARY KEY`,+ },+ {+ name: "unrelated ALTER on unqualified table with PK",+ stmt: "ALTER TABLE with_pk ADD COLUMN note TEXT;",+ },+ {+ name: "unrelated ALTER on unqualified table without PK",+ stmt: "ALTER TABLE without_pk ADD COLUMN note TEXT;",+ },+ {+ name: "create unqualified table lands in first search_path schema",+ stmt: "CREATE TABLE fresh(id INT);",+ wantContent: `Table "app_schema"."fresh" requires PRIMARY KEY`,+ },+ {+ name: "create then drop unqualified table in same batch",+ stmt: "CREATE TABLE fresh(id INT); DROP TABLE fresh;",+ },+ }++ rule := &storepb.SQLReviewRule{+ Type: storepb.SQLReviewRule_TABLE_REQUIRE_PK,+ Level: storepb.SQLReviewRule_WARNING,+ Engine: storepb.Engine_POSTGRES,+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ original, ok := proto.Clone(dbSchema).(*storepb.DatabaseSchemaMetadata)+ require.True(t, ok)+ final, ok := proto.Clone(dbSchema).(*storepb.DatabaseSchemaMetadata)+ require.True(t, ok)+ checkCtx := advisor.Context{+ DBType: storepb.Engine_POSTGRES,+ OriginalMetadata: model.NewDatabaseMetadata(original, nil, nil, storepb.Engine_POSTGRES, true),+ FinalMetadata: model.NewDatabaseMetadata(final, nil, nil, storepb.Engine_POSTGRES, true),+ CurrentDatabase: "test",+ DBSchema: dbSchema,+ NoAppendBuiltin: true,+ }++ advice, err := advisor.SQLReviewCheck(context.Background(), sheet.NewManager(), tc.stmt, []*storepb.SQLReviewRule{rule}, checkCtx)+ require.NoError(t, err)++ var got []*storepb.Advice+ for _, a := range advice {+ if a.Code == code.TableNoPK.Int32() {+ got = append(got, a)+ }+ }+ if tc.wantContent == "" {+ require.Empty(t, got)+ return+ }+ require.Len(t, got, 1)+ require.Contains(t, got[0].Content, tc.wantContent)+ })+ }+}