Skip to content

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

feat: Support PostgreSQL walkthrough search_path resolution via current user (#19581)

p0ny566bef4be362
diff --git a/backend/plugin/advisor/advisor.go b/backend/plugin/advisor/advisor.go
index 4c72b6e1e0..8ca046a65d 100644
--- a/backend/plugin/advisor/advisor.go
+++ b/backend/plugin/advisor/advisor.go
@@ -60,7 +60,8 @@ type Context struct {
TenantMode bool
// SQL review level fields.
- DBType storepb.Engine
+ DBType storepb.Engine
+ SessionUser string
// Snowflake specific fields (duplicates CurrentDatabase, kept for compatibility).
// CurrentDatabase string
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index 1c4c80390a..0aa9b3f4c7 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -118,7 +118,10 @@ func SQLReviewCheck(
}
if checkContext.FinalMetadata != nil {
- if advice := schema.WalkThrough(checkContext.DBType, checkContext.FinalMetadata, asts); advice != nil {
+ walkThroughContext := schema.WalkThroughContext{
+ SessionUser: checkContext.SessionUser,
+ }
+ if advice := schema.WalkThroughWithContext(checkContext.DBType, walkThroughContext, checkContext.FinalMetadata, asts); advice != nil {
for _, rule := range ruleList {
if rule.Type == storepb.SQLReviewRule_BUILTIN_WALK_THROUGH_CHECK {
if status, err := NewStatusBySQLReviewRuleLevel(rule.Level); err == nil {
diff --git a/backend/plugin/schema/pg/walk_through.go b/backend/plugin/schema/pg/walk_through.go
index 85288ac48d..b9c47af333 100644
--- a/backend/plugin/schema/pg/walk_through.go
+++ b/backend/plugin/schema/pg/walk_through.go
@@ -21,11 +21,16 @@ const (
)
func init() {
- schema.RegisterWalkThrough(storepb.Engine_POSTGRES, WalkThrough)
+ schema.RegisterWalkThroughWithContext(storepb.Engine_POSTGRES, WalkThroughWithContext)
}
// WalkThrough walks through the PostgreSQL ANTLR parse tree and builds catalog metadata.
func WalkThrough(d *model.DatabaseMetadata, ast []base.AST) *storepb.Advice {
+ return WalkThroughWithContext(schema.WalkThroughContext{}, d, ast)
+}
+
+// WalkThroughWithContext walks through the PostgreSQL ANTLR parse tree and builds catalog metadata.
+func WalkThroughWithContext(ctx schema.WalkThroughContext, d *model.DatabaseMetadata, ast []base.AST) *storepb.Advice {
// Extract ANTLRAST from AST
var antlrASTList []*base.ANTLRAST
for _, unifiedAST := range ast {
@@ -48,6 +53,11 @@ func WalkThrough(d *model.DatabaseMetadata, ast []base.AST) *storepb.Advice {
listener := &pgCatalogListener{
BasePostgreSQLParserListener: &parser.BasePostgreSQLParserListener{},
databaseState: d,
+ session: pgSessionState{
+ sessionUser: ctx.SessionUser,
+ currentUser: ctx.SessionUser,
+ defaultSearchPath: d.GetConfiguredSearchPath(),
+ },
}
// Walk through all parse results
@@ -80,10 +90,242 @@ func WalkThrough(d *model.DatabaseMetadata, ast []base.AST) *storepb.Advice {
type pgCatalogListener struct {
*parser.BasePostgreSQLParserListener
databaseState *model.DatabaseMetadata
+ session pgSessionState
advice *storepb.Advice
currentLine int
}
+type pgSessionState struct {
+ sessionUser string
+ currentUser string
+ defaultSearchPath []model.PGSearchPathItem
+ searchPath []model.PGSearchPathItem
+}
+
+func (s *pgSessionState) configuredSearchPath() []model.PGSearchPathItem {
+ if s.searchPath != nil {
+ return s.searchPath
+ }
+ return s.defaultSearchPath
+}
+
+func (s *pgSessionState) resolvedSearchPath() []string {
+ return model.ResolvePGSearchPath(s.configuredSearchPath(), s.currentUser, nil)
+}
+
+func (s *pgSessionState) effectiveSearchPath(db *model.DatabaseMetadata) []string {
+ return model.ResolvePGSearchPath(s.configuredSearchPath(), s.currentUser, func(name string) bool {
+ return db.GetSchemaMetadata(name) != nil
+ })
+}
+
+func (l *pgCatalogListener) EnterVariablesetstmt(ctx *parser.VariablesetstmtContext) {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
+ return
+ }
+
+ setRest := ctx.Set_rest()
+ if setRest == nil {
+ return
+ }
+ setRestMore := setRest.Set_rest_more()
+ if setRestMore == nil {
+ return
+ }
+
+ if setRestMore.ROLE() != nil && setRestMore.Nonreservedword_or_sconst() != nil {
+ roleName, reset := normalizePGRoleName(setRestMore.Nonreservedword_or_sconst().GetText())
+ if reset {
+ l.session.currentUser = l.session.sessionUser
+ return
+ }
+ l.session.currentUser = roleName
+ return
+ }
+
+ genericSet := setRestMore.Generic_set()
+ if genericSet == nil {
+ return
+ }
+ varName := genericSet.Var_name()
+ if varName == nil || len(varName.AllColid()) != 1 {
+ return
+ }
+ name := pgparser.NormalizePostgreSQLColid(varName.Colid(0))
+ if !strings.EqualFold(name, "search_path") {
+ return
+ }
+
+ varList := genericSet.Var_list()
+ if varList == nil {
+ return
+ }
+ values := varList.AllVar_value()
+ if len(values) == 0 {
+ return
+ }
+ if len(values) == 1 && strings.EqualFold(strings.TrimSpace(values[0].GetText()), "default") {
+ l.session.searchPath = nil
+ return
+ }
+
+ parts := make([]string, 0, len(values))
+ for _, value := range values {
+ parts = append(parts, value.GetText())
+ }
+ l.session.searchPath = model.ParsePGConfiguredSearchPath(strings.Join(parts, ", "))
+}
+
+func (l *pgCatalogListener) EnterVariableresetstmt(ctx *parser.VariableresetstmtContext) {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
+ return
+ }
+
+ resetRest := ctx.Reset_rest()
+ if resetRest == nil {
+ return
+ }
+ if resetRest.SESSION() != nil && resetRest.AUTHORIZATION() != nil {
+ l.session.currentUser = l.session.sessionUser
+ return
+ }
+ genericReset := resetRest.Generic_reset()
+ if genericReset == nil {
+ return
+ }
+ if genericReset.ALL() != nil {
+ l.session.currentUser = l.session.sessionUser
+ l.session.searchPath = nil
+ return
+ }
+ varName := genericReset.Var_name()
+ if varName == nil || len(varName.AllColid()) != 1 {
+ return
+ }
+ name := pgparser.NormalizePostgreSQLColid(varName.Colid(0))
+ switch {
+ case strings.EqualFold(name, "search_path"):
+ l.session.searchPath = nil
+ case strings.EqualFold(name, "role"):
+ l.session.currentUser = l.session.sessionUser
+ default:
+ }
+}
+
+func normalizePGRoleName(roleName string) (string, bool) {
+ roleName = strings.TrimSpace(roleName)
+ if roleName == "" {
+ return "", true
+ }
+ trimmed := strings.Trim(roleName, `"'`)
+ if strings.EqualFold(trimmed, "none") || strings.EqualFold(trimmed, "default") {
+ return "", true
+ }
+ return trimmed, false
+}
+
+func (l *pgCatalogListener) lookupSearchPath() []string {
+ searchPath := l.session.effectiveSearchPath(l.databaseState)
+ if len(searchPath) == 0 {
+ return []string{PublicSchemaName}
+ }
+ return searchPath
+}
+
+func (l *pgCatalogListener) resolveSchemaForCreate(explicitSchemaName string, line int) (*model.SchemaMetadata, *storepb.Advice) {
+ if explicitSchemaName != "" {
+ return getOrCreatePublicSchema(l.databaseState, explicitSchemaName, line)
+ }
+ for _, schemaName := range l.session.resolvedSearchPath() {
+ schema := l.databaseState.GetSchemaMetadata(schemaName)
+ if schema != nil {
+ return schema, nil
+ }
+ if schemaName == PublicSchemaName {
+ return l.databaseState.CreateSchema(PublicSchemaName), nil
+ }
+ }
+ return getOrCreatePublicSchema(l.databaseState, PublicSchemaName, line)
+}
+
+func (l *pgCatalogListener) findTable(schemaName string, tableName string) (*model.SchemaMetadata, *model.TableMetadata) {
+ if schemaName != "" {
+ schema := l.databaseState.GetSchemaMetadata(schemaName)
+ if schema == nil {
+ return nil, nil
+ }
+ return schema, schema.GetTable(tableName)
+ }
+ resolvedSchemaName, table := l.databaseState.SearchTable(l.lookupSearchPath(), tableName)
+ if table == nil {
+ return nil, nil
+ }
+ return l.databaseState.GetSchemaMetadata(resolvedSchemaName), table
+}
+
+func (l *pgCatalogListener) findTableOrMaterializedView(schemaName string, relationName string) (*model.SchemaMetadata, *model.TableMetadata, *storepb.MaterializedViewMetadata) {
+ if schemaName != "" {
+ schema := l.databaseState.GetSchemaMetadata(schemaName)
+ if schema == nil {
+ return nil, nil, nil
+ }
+ return schema, schema.GetTable(relationName), schema.GetMaterializedView(relationName)
+ }
+ searchPath := l.lookupSearchPath()
+ if resolvedSchemaName, table := l.databaseState.SearchTable(searchPath, relationName); table != nil {
+ return l.databaseState.GetSchemaMetadata(resolvedSchemaName), table, nil
+ }
+ if resolvedSchemaName, matView := l.databaseState.SearchMaterializedView(searchPath, relationName); matView != nil {
+ return l.databaseState.GetSchemaMetadata(resolvedSchemaName), nil, matView
+ }
+ return nil, nil, nil
+}
+
+func (l *pgCatalogListener) findView(schemaName string, viewName string) (*model.SchemaMetadata, *storepb.ViewMetadata) {
+ if schemaName != "" {
+ schema := l.databaseState.GetSchemaMetadata(schemaName)
+ if schema == nil {
+ return nil, nil
+ }
+ return schema, schema.GetView(viewName)
+ }
+ resolvedSchemaName, view := l.databaseState.SearchView(l.lookupSearchPath(), viewName)
+ if view == nil {
+ return nil, nil
+ }
+ return l.databaseState.GetSchemaMetadata(resolvedSchemaName), view
+}
+
+func (l *pgCatalogListener) findMaterializedView(schemaName string, viewName string) (*model.SchemaMetadata, *storepb.MaterializedViewMetadata) {
+ if schemaName != "" {
+ schema := l.databaseState.GetSchemaMetadata(schemaName)
+ if schema == nil {
+ return nil, nil
+ }
+ return schema, schema.GetMaterializedView(viewName)
+ }
+ resolvedSchemaName, view := l.databaseState.SearchMaterializedView(l.lookupSearchPath(), viewName)
+ if view == nil {
+ return nil, nil
+ }
+ return l.databaseState.GetSchemaMetadata(resolvedSchemaName), view
+}
+
+func (l *pgCatalogListener) findIndex(schemaName string, indexName string) (*model.SchemaMetadata, *model.IndexMetadata) {
+ if schemaName != "" {
+ schema := l.databaseState.GetSchemaMetadata(schemaName)
+ if schema == nil {
+ return nil, nil
+ }
+ return schema, schema.GetIndex(indexName)
+ }
+ resolvedSchemaName, index := l.databaseState.SearchIndex(l.lookupSearchPath(), indexName)
+ if index == nil {
+ return nil, nil
+ }
+ return l.databaseState.GetSchemaMetadata(resolvedSchemaName), index
+}
+
// ========================================
// CREATE TABLE handling
// ========================================
@@ -118,7 +360,7 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
return
}
// Get or create schema
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
+ schema, err := l.resolveSchemaForCreate(schemaName, l.currentLine)
if err != nil {
l.advice = err
return
@@ -459,14 +701,8 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
}
relationName := extractTableName(relationExpr.Qualified_name())
schemaName := extractSchemaName(relationExpr.Qualified_name())
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- l.advice = err
- return
- }
// Try to find the relation as a table first, then as a materialized view
- table := schema.GetTable(relationName)
- matView := schema.GetMaterializedView(relationName)
+ schema, table, matView := l.findTableOrMaterializedView(schemaName, relationName)
if table == nil && matView == nil {
l.advice = &storepb.Advice{
Status: storepb.Advice_ERROR,
@@ -652,17 +888,12 @@ func (l *pgCatalogListener) EnterAltertablestmt(ctx *parser.AltertablestmtContex
return
}
// Get schema and table
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- l.advice = err
- return
- }
- table := schema.GetTable(tableName)
+ schema, table, matView := l.findTableOrMaterializedView(schemaName, tableName)
if table == nil {
// Check if it's a materialized view - PostgreSQL allows some ALTER TABLE
// commands on materialized views (e.g., OWNER TO). Skip processing for
// materialized views since we don't track these changes in metadata.
- if schema.GetMaterializedView(tableName) != nil {
+ if matView != nil {
return
}
l.advice = &storepb.Advice{
@@ -1318,14 +1549,7 @@ func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists
schemaName = parts[0]
tableName = parts[1]
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
- table := schema.GetTable(tableName)
+ schema, table := l.findTable(schemaName, tableName)
if table == nil {
if ifExists {
return nil
@@ -1381,12 +1605,21 @@ func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists b
default:
return nil
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- return err
+ schema, view := l.findView(schemaName, viewName)
+ if view == nil {
+ if !ifExists {
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ViewNotExists.Int32(),
+ Title: fmt.Sprintf("View %q does not exist", viewName),
+ Content: fmt.Sprintf("View %q does not exist", viewName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
+ }
+ return nil
}
// Try to drop the view
- if dropErr := schema.DropView(viewName); dropErr != nil {
+ if dropErr := schema.DropView(view.Name); dropErr != nil {
if !ifExists {
return &storepb.Advice{
Status: storepb.Advice_ERROR,
@@ -1414,15 +1647,21 @@ func (l *pgCatalogListener) dropMaterializedView(anyName parser.IAny_nameContext
default:
return nil
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
+ schema, view := l.findMaterializedView(schemaName, viewName)
+ if view == nil {
if ifExists {
return nil
}
- return err
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ViewNotExists.Int32(),
+ Title: fmt.Sprintf("Materialized view %q does not exist", viewName),
+ Content: fmt.Sprintf("Materialized view %q does not exist", viewName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
// Try to drop the materialized view
- if dropErr := schema.DropMaterializedView(viewName); dropErr != nil {
+ if dropErr := schema.DropMaterializedView(view.Name); dropErr != nil {
if !ifExists {
return &storepb.Advice{
Status: storepb.Advice_ERROR,
@@ -1448,24 +1687,20 @@ func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists
schemaName = parts[0]
indexName = parts[1]
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- if ifExists {
- return nil
- }
- return err
- }
- // Get the index - it could be on a table or materialized view
- index := schema.GetIndex(indexName)
+ schema, index := l.findIndex(schemaName, indexName)
if index == nil {
if ifExists {
return nil
}
+ indexTitle := fmt.Sprintf("Index %q does not exist", indexName)
+ if schema != nil {
+ indexTitle = fmt.Sprintf("Index %q does not exist in schema %q", indexName, schema.GetProto().Name)
+ }
return &storepb.Advice{
Status: storepb.Advice_ERROR,
Code: code.IndexNotExists.Int32(),
- Title: fmt.Sprintf("Index %q does not exist in schema %q", indexName, schema.GetProto().Name),
- Content: fmt.Sprintf("Index %q does not exist in schema %q", indexName, schema.GetProto().Name),
+ Title: indexTitle,
+ Content: indexTitle,
StartPosition: &storepb.Position{Line: int32(l.currentLine)},
}
}
@@ -1577,18 +1812,18 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
indexName := extractTableName(ctx.Qualified_name())
schemaName := extractSchemaName(ctx.Qualified_name())
newName := pgparser.NormalizePostgreSQLName(ctx.AllName()[0])
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- l.advice = err
+ schema, index := l.findIndex(schemaName, indexName)
+ if index == nil {
+ // Index not found, silently ignore (PostgreSQL behavior)
return
}
// Find the index across all tables
- foundTable, _, err := getIndexFromSchema(schema, indexName)
+ foundTable, _, err := getIndexFromSchema(schema, index.GetProto().Name)
if err != nil {
// Index not found, silently ignore (PostgreSQL behavior)
return
}
- if err := l.renameConstraint(schema, foundTable, indexName, newName, l.currentLine); err != nil {
+ if err := l.renameConstraint(schema, foundTable, index.GetProto().Name, newName, l.currentLine); err != nil {
l.advice = err
}
}
@@ -1601,14 +1836,9 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
viewName := extractTableName(ctx.Qualified_name())
schemaName := extractSchemaName(ctx.Qualified_name())
newName := pgparser.NormalizePostgreSQLName(ctx.AllName()[0])
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- l.advice = err
- return
- }
- // Check if it's a view
- if schema.GetView(viewName) != nil {
- if err := schema.RenameView(viewName, newName); err != nil {
+ schema, view := l.findView(schemaName, viewName)
+ if view != nil {
+ if err := schema.RenameView(view.Name, newName); err != nil {
l.advice = &storepb.Advice{
Status: storepb.Advice_ERROR,
Code: code.ViewNotExists.Int32(),
@@ -1626,11 +1856,7 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
tableName = extractTableName(ctx.Relation_expr().Qualified_name())
schemaName = extractSchemaName(ctx.Relation_expr().Qualified_name())
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
- if err != nil {
- l.advice = err
- return
- }
+ schema, table := l.findTable(schemaName, tableName)
// Check if this is column rename
if ctx.Opt_column() != nil {
// RENAME COLUMN: ALTER TABLE table RENAME COLUMN oldname TO newname
@@ -1639,7 +1865,6 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
if len(allNames) >= 2 && tableName != "" {
oldName := pgparser.NormalizePostgreSQLName(allNames[0])
newName := pgparser.NormalizePostgreSQLName(allNames[1])
- table := schema.GetTable(tableName)
if table == nil {
l.advice = &storepb.Advice{
Status: storepb.Advice_ERROR,
@@ -1663,7 +1888,6 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
if len(allNames) >= 2 {
oldName := pgparser.NormalizePostgreSQLName(allNames[0])
newName := pgparser.NormalizePostgreSQLName(allNames[1])
- table := schema.GetTable(tableName)
if table == nil {
l.advice = &storepb.Advice{
Status: storepb.Advice_ERROR,
@@ -1683,7 +1907,6 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
// Otherwise it's table rename: ALTER TABLE oldname RENAME TO newname
if tableName != "" && ctx.AllName() != nil && len(ctx.AllName()) > 0 {
newName := pgparser.NormalizePostgreSQLName(ctx.AllName()[0])
- table := schema.GetTable(tableName)
if table == nil {
l.advice = &storepb.Advice{
Status: storepb.Advice_ERROR,
@@ -1728,14 +1951,14 @@ func (l *pgCatalogListener) EnterViewstmt(ctx *parser.ViewstmtContext) {
}
return
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
+ schema, err := l.resolveSchemaForCreate(schemaName, l.currentLine)
if err != nil {
l.advice = err
return
}
// Check if view already exists - silently ignore duplicates
// This matches the legacy behavior in the old DatabaseState implementation
- if schema.GetView(viewName) != nil {
+ if existingView := schema.GetView(viewName); existingView != nil {
return
}
// Get the view definition (the SELECT statement)
@@ -1785,7 +2008,7 @@ func (l *pgCatalogListener) EnterCreatematviewstmt(ctx *parser.Creatematviewstmt
}
return
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
+ schema, err := l.resolveSchemaForCreate(schemaName, l.currentLine)
if err != nil {
l.advice = err
return
diff --git a/backend/plugin/schema/pg/walk_through_test.go b/backend/plugin/schema/pg/walk_through_test.go
index 7ae0c42aec..5a69d98d41 100644
--- a/backend/plugin/schema/pg/walk_through_test.go
+++ b/backend/plugin/schema/pg/walk_through_test.go
@@ -16,6 +16,7 @@ import (
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -220,3 +221,135 @@ func TestWalkThroughANTLR(t *testing.T) {
require.Empty(t, diff)
}
}
+
+func TestWalkThroughSearchPathState(t *testing.T) {
+ tests := []struct {
+ name string
+ searchPath string
+ session schema.WalkThroughContext
+ sql string
+ assert func(*testing.T, *model.DatabaseMetadata)
+ }{
+ {
+ name: "session user expands $user on initial resolution",
+ searchPath: `"$user", public`,
+ session: schema.WalkThroughContext{SessionUser: "alice"},
+ sql: `CREATE TABLE session_target (id int);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.NotNil(t, state.GetSchemaMetadata("alice").GetTable("session_target"))
+ require.Nil(t, state.GetSchemaMetadata("public").GetTable("session_target"))
+ },
+ },
+ {
+ name: "set role recomputes $user target schema",
+ searchPath: `"$user", public`,
+ session: schema.WalkThroughContext{SessionUser: "alice"},
+ sql: `SET ROLE bob; CREATE TABLE role_target (id int);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.NotNil(t, state.GetSchemaMetadata("bob").GetTable("role_target"))
+ require.Nil(t, state.GetSchemaMetadata("alice").GetTable("role_target"))
+ },
+ },
+ {
+ name: "set search_path changes unqualified create target",
+ searchPath: `public`,
+ sql: `SET search_path TO app, public; CREATE TABLE path_target (id int);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.NotNil(t, state.GetSchemaMetadata("app").GetTable("path_target"))
+ require.Nil(t, state.GetSchemaMetadata("public").GetTable("path_target"))
+ },
+ },
+ {
+ name: "ordered lookup picks first matching schema",
+ searchPath: `public`,
+ sql: `SET search_path TO app, public; CREATE INDEX idx_dup_id ON dup(id);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.NotNil(t, state.GetSchemaMetadata("app").GetTable("dup").GetIndex("idx_dup_id"))
+ require.Nil(t, state.GetSchemaMetadata("public").GetTable("dup").GetIndex("idx_dup_id"))
+ },
+ },
+ {
+ name: "set search_path to default restores configured path",
+ searchPath: `public, app`,
+ sql: `SET search_path TO app; SET search_path TO DEFAULT; CREATE TABLE default_target (id int);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.NotNil(t, state.GetSchemaMetadata("public").GetTable("default_target"))
+ require.Nil(t, state.GetSchemaMetadata("app").GetTable("default_target"))
+ },
+ },
+ {
+ name: "explicit schema still wins over current path",
+ searchPath: `public`,
+ sql: `SET search_path TO app; CREATE TABLE public.explicit_target (id int);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.NotNil(t, state.GetSchemaMetadata("public").GetTable("explicit_target"))
+ require.Nil(t, state.GetSchemaMetadata("app").GetTable("explicit_target"))
+ },
+ },
+ {
+ name: "missing first path entry is skipped rather than auto-created",
+ searchPath: `missing_schema, public`,
+ sql: `CREATE TABLE skipped_missing (id int);`,
+ assert: func(t *testing.T, state *model.DatabaseMetadata) {
+ t.Helper()
+ require.Nil(t, state.GetSchemaMetadata("missing_schema"))
+ require.NotNil(t, state.GetSchemaMetadata("public").GetTable("skipped_missing"))
+ },
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ state := newSearchPathTestState(test.searchPath)
+ stmts, err := base.ParseStatements(storepb.Engine_POSTGRES, test.sql)
+ require.NoError(t, err)
+ advice := WalkThroughWithContext(test.session, state, base.ExtractASTs(stmts))
+ require.Nil(t, advice)
+ test.assert(t, state)
+ })
+ }
+}
+
+func newSearchPathTestState(searchPath string) *model.DatabaseMetadata {
+ metadata := &storepb.DatabaseSchemaMetadata{
+ Name: "postgres",
+ SearchPath: searchPath,
+ Schemas: []*storepb.SchemaMetadata{
+ {Name: "alice"},
+ {Name: "bob"},
+ {
+ Name: "app",
+ Tables: []*storepb.TableMetadata{
+ newSearchPathTestTable("dup"),
+ },
+ },
+ {
+ Name: "public",
+ Tables: []*storepb.TableMetadata{
+ newSearchPathTestTable("dup"),
+ },
+ },
+ },
+ }
+ return model.NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_POSTGRES, true)
+}
+
+func newSearchPathTestTable(name string) *storepb.TableMetadata {
+ return &storepb.TableMetadata{
+ Name: name,
+ Columns: []*storepb.ColumnMetadata{
+ {
+ Name: "id",
+ Type: "int",
+ Nullable: false,
+ Position: 1,
+ },
+ },
+ }
+}
diff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.go
index 5bfee65f6a..53030b4364 100644
--- a/backend/plugin/schema/schema.go
+++ b/backend/plugin/schema/schema.go
@@ -26,6 +26,7 @@ var (
getSDLDiffs = make(map[storepb.Engine]getSDLDiff)
getMultiFileDatabaseDefinitions = make(map[storepb.Engine]getMultiFileDatabaseDefinition)
walkThroughs = make(map[storepb.Engine]walkThrough)
+ walkThroughsWithContext = make(map[storepb.Engine]walkThroughWithContext)
)
type getDatabaseDefinition func(GetDefinitionContext, *storepb.DatabaseSchemaMetadata) (string, error)
@@ -41,6 +42,12 @@ type getDatabaseMetadata func(string) (*storepb.DatabaseSchemaMetadata, error)
type generateMigration func(*MetadataDiff) (string, error)
type getSDLDiff func(currentSDLText, previousUserSDLText string, currentSchema *model.DatabaseMetadata) (*MetadataDiff, error)
type walkThrough func(*model.DatabaseMetadata, []base.AST) *storepb.Advice
+type walkThroughWithContext func(WalkThroughContext, *model.DatabaseMetadata, []base.AST) *storepb.Advice
+
+// WalkThroughContext carries optional session state into schema walk-through implementations.
+type WalkThroughContext struct {
+ SessionUser string
+}
type GetDefinitionContext struct {
SkipBackupSchema bool
@@ -278,7 +285,23 @@ func RegisterWalkThrough(engine storepb.Engine, f walkThrough) {
walkThroughs[engine] = f
}
+func RegisterWalkThroughWithContext(engine storepb.Engine, f walkThroughWithContext) {
+ mux.Lock()
+ defer mux.Unlock()
+ if _, dup := walkThroughsWithContext[engine]; dup {
+ panic(fmt.Sprintf("Register called twice %s", engine))
+ }
+ walkThroughsWithContext[engine] = f
+}
+
func WalkThrough(engine storepb.Engine, d *model.DatabaseMetadata, ast []base.AST) *storepb.Advice {
+ return WalkThroughWithContext(engine, WalkThroughContext{}, d, ast)
+}
+
+func WalkThroughWithContext(engine storepb.Engine, ctx WalkThroughContext, d *model.DatabaseMetadata, ast []base.AST) *storepb.Advice {
+ if f, ok := walkThroughsWithContext[engine]; ok {
+ return f(ctx, d, ast)
+ }
f, ok := walkThroughs[engine]
if !ok {
return nil
diff --git a/backend/store/model/database.go b/backend/store/model/database.go
index 65cf0e10e6..739a13a2d6 100644
--- a/backend/store/model/database.go
+++ b/backend/store/model/database.go
@@ -22,7 +22,7 @@ type DatabaseMetadata struct {
isDetailCaseSensitive bool
// Metadata fields (formerly in DatabaseMetadata)
- searchPath []string
+ searchPath []PGSearchPathItem
internal map[string]*SchemaMetadata
linkedDatabase map[string]*storepb.LinkedDatabaseMetadata
}
@@ -97,7 +97,7 @@ func NewDatabaseMetadata(
config: config,
isObjectCaseSensitive: isObjectCaseSensitive,
isDetailCaseSensitive: isDetailCaseSensitive,
- searchPath: normalizeSearchPath(metadata.SearchPath),
+ searchPath: ParsePGConfiguredSearchPath(metadata.SearchPath),
internal: make(map[string]*SchemaMetadata),
linkedDatabase: make(map[string]*storepb.LinkedDatabaseMetadata),
}
@@ -201,8 +201,20 @@ func (d *DatabaseMetadata) GetConfig() *storepb.DatabaseConfig {
return d.config
}
+func (d *DatabaseMetadata) GetConfiguredSearchPath() []PGSearchPathItem {
+ return slices.Clone(d.searchPath)
+}
+
func (d *DatabaseMetadata) GetSearchPath() []string {
- return d.searchPath
+ return ResolvePGSearchPath(d.searchPath, "", nil)
+}
+
+func (d *DatabaseMetadata) GetSearchPathForCurrentUser(currentUser string) []string {
+ return ResolvePGSearchPath(d.searchPath, currentUser, d.hasSchema)
+}
+
+func (d *DatabaseMetadata) hasSchema(name string) bool {
+ return d.GetSchemaMetadata(name) != nil
}
func (d *DatabaseMetadata) GetSchemaMetadata(name string) *SchemaMetadata {
diff --git a/backend/store/model/pg_search_path.go b/backend/store/model/pg_search_path.go
new file mode 100644
index 0000000000..da32d660ac
--- /dev/null
+++ b/backend/store/model/pg_search_path.go
@@ -0,0 +1,129 @@
+package model
+
+import "strings"
+
+// PGSearchPathItem is a parsed PostgreSQL search_path entry.
+type PGSearchPathItem struct {
+ Schema string
+ CurrentUser bool
+}
+
+// ParsePGConfiguredSearchPath parses a PostgreSQL search_path setting while preserving
+// non-system configured entries, including the special $user placeholder.
+func ParsePGConfiguredSearchPath(searchPath string) []PGSearchPathItem {
+ if searchPath == "" {
+ return []PGSearchPathItem{}
+ }
+
+ var result []PGSearchPathItem
+ for _, token := range splitPGSearchPath(searchPath) {
+ item, ok := parsePGSearchPathItem(token)
+ if !ok {
+ continue
+ }
+ result = append(result, item)
+ }
+ return result
+}
+
+// ResolvePGSearchPath resolves a parsed PostgreSQL search_path for a current user.
+// When schemaExists is provided, schemas missing from metadata are omitted.
+func ResolvePGSearchPath(configured []PGSearchPathItem, currentUser string, schemaExists func(string) bool) []string {
+ if len(configured) == 0 {
+ return []string{}
+ }
+
+ currentUser = strings.TrimSpace(currentUser)
+
+ var result []string
+ for _, item := range configured {
+ schema, ok := item.resolve(currentUser)
+ if !ok {
+ continue
+ }
+ if schemaExists != nil && !schemaExists(schema) {
+ continue
+ }
+ result = append(result, schema)
+ }
+ return result
+}
+
+func (i PGSearchPathItem) resolve(currentUser string) (string, bool) {
+ if i.CurrentUser {
+ if currentUser == "" {
+ return "", false
+ }
+ return currentUser, true
+ }
+ if i.Schema == "" {
+ return "", false
+ }
+ return i.Schema, true
+}
+
+func parsePGSearchPathItem(token string) (PGSearchPathItem, bool) {
+ token = strings.TrimSpace(token)
+ if token == "" {
+ return PGSearchPathItem{}, false
+ }
+
+ schema := strings.ToLower(token)
+ switch {
+ case len(token) >= 2 && token[0] == '"' && token[len(token)-1] == '"':
+ schema = strings.ReplaceAll(token[1:len(token)-1], `""`, `"`)
+ case len(token) >= 2 && token[0] == '\'' && token[len(token)-1] == '\'':
+ schema = strings.ReplaceAll(token[1:len(token)-1], `''`, `'`)
+ default:
+ }
+
+ if schema == "$user" {
+ return PGSearchPathItem{CurrentUser: true}, true
+ }
+ if isPGSystemPath(schema) {
+ return PGSearchPathItem{}, false
+ }
+ if schema == "" {
+ return PGSearchPathItem{}, false
+ }
+ return PGSearchPathItem{Schema: schema}, true
+}
+
+func splitPGSearchPath(searchPath string) []string {
+ var parts []string
+ start := 0
+ var quote byte
+
+ for i := 0; i < len(searchPath); i++ {
+ switch {
+ case quote != 0:
+ if searchPath[i] != quote {
+ continue
+ }
+ if i+1 < len(searchPath) && searchPath[i+1] == quote {
+ i++
+ continue
+ }
+ quote = 0
+ case searchPath[i] == '"' || searchPath[i] == '\'':
+ quote = searchPath[i]
+ case searchPath[i] == ',':
+ parts = append(parts, searchPath[start:i])
+ start = i + 1
+ default:
+ }
+ }
+ parts = append(parts, searchPath[start:])
+ return parts
+}
+
+// isPGSystemPath checks if a path is a PostgreSQL system schema.
+func isPGSystemPath(path string) bool {
+ systemSchemas := []string{"pg_catalog", "information_schema", "pg_toast", "pg_temp_1", "pg_temp_2", "pg_global"}
+ for _, schema := range systemSchemas {
+ if strings.EqualFold(path, schema) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/store/model/pg_search_path_test.go b/backend/store/model/pg_search_path_test.go
new file mode 100644
index 0000000000..62dc68b0d0
--- /dev/null
+++ b/backend/store/model/pg_search_path_test.go
@@ -0,0 +1,78 @@
+package model
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+func TestParsePGConfiguredSearchPath(t *testing.T) {
+ got := ParsePGConfiguredSearchPath(` "$user" , public, "CamelCase", "schema,with,comma", pg_catalog, 'SingleQuoted', information_schema `)
+
+ require.Equal(t, []PGSearchPathItem{
+ {CurrentUser: true},
+ {Schema: "public"},
+ {Schema: "CamelCase"},
+ {Schema: "schema,with,comma"},
+ {Schema: "SingleQuoted"},
+ }, got)
+}
+
+func TestResolvePGSearchPath(t *testing.T) {
+ configured := []PGSearchPathItem{
+ {CurrentUser: true},
+ {Schema: "public"},
+ {Schema: "MissingSchema"},
+ {Schema: "CamelCase"},
+ }
+
+ schemaSet := map[string]bool{
+ "alice": true,
+ "public": true,
+ "CamelCase": true,
+ }
+ got := ResolvePGSearchPath(configured, "alice", func(schema string) bool {
+ return schemaSet[schema]
+ })
+
+ require.Equal(t, []string{"alice", "public", "CamelCase"}, got)
+}
+
+func TestDatabaseMetadataSearchPathHelpers(t *testing.T) {
+ metadata := &storepb.DatabaseSchemaMetadata{
+ Name: "testdb",
+ SearchPath: `"$user", public, MissingSchema, "CamelCase"`,
+ Schemas: []*storepb.SchemaMetadata{
+ {Name: "alice"},
+ {Name: "public"},
+ {Name: "CamelCase"},
+ },
+ }
+
+ db := NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_POSTGRES, true)
+
+ require.Equal(t, []PGSearchPathItem{
+ {CurrentUser: true},
+ {Schema: "public"},
+ {Schema: "missingschema"},
+ {Schema: "CamelCase"},
+ }, db.GetConfiguredSearchPath())
+ require.Equal(t, []string{"public", "missingschema", "CamelCase"}, db.GetSearchPath())
+ require.Equal(t, []string{"alice", "public", "CamelCase"}, db.GetSearchPathForCurrentUser("alice"))
+}
+
+func TestDatabaseMetadataSearchPathHelpersSkipMissingCurrentUserSchema(t *testing.T) {
+ metadata := &storepb.DatabaseSchemaMetadata{
+ Name: "testdb",
+ SearchPath: `"$user", public, MissingSchema`,
+ Schemas: []*storepb.SchemaMetadata{
+ {Name: "public"},
+ },
+ }
+
+ db := NewDatabaseMetadata(metadata, nil, nil, storepb.Engine_POSTGRES, true)
+
+ require.Equal(t, []string{"public"}, db.GetSearchPathForCurrentUser("alice"))
+}
diff --git a/backend/store/model/pg_searcher.go b/backend/store/model/pg_searcher.go
index 3112fbef48..d64c833772 100644
--- a/backend/store/model/pg_searcher.go
+++ b/backend/store/model/pg_searcher.go
@@ -308,59 +308,3 @@ func (d *DatabaseMetadata) SearchObject(searchPath []string, name string) (strin
}
return "", ""
}
-
-// normalizeSearchPath normalizes the search path string into a slice of strings.
-// NOTE: This is primarily designed for PostgreSQL's search_path concept.
-func normalizeSearchPath(searchPath string) []string {
- if searchPath == "" {
- return []string{}
- }
-
- // Split the search path by comma and trim spaces.
- parts := strings.Split(searchPath, ",")
- for i, part := range parts {
- parts[i] = strings.TrimSpace(part)
- }
-
- // Remove empty parts.
- var result []string
- for _, part := range parts {
- schema := strings.TrimSpace(part)
- if part == "\"$user\"" {
- continue
- }
- if strings.HasPrefix(part, "\"") && strings.HasSuffix(part, "\"") {
- // Remove the quotes from the schema name.
- schema = strings.Trim(schema, "\"")
- } else if strings.HasPrefix(part, "'") && strings.HasSuffix(part, "'") {
- // Remove the single quotes from the schema name.
- schema = strings.Trim(schema, "'")
- } else {
- // For non-quoted schema names, we just return the lower string for PostgreSQL.
- schema = strings.ToLower(schema)
- }
- schema = strings.TrimSpace(schema)
- if isSystemPath(schema) {
- // Skip system schemas.
- continue
- }
- if schema != "" {
- result = append(result, schema)
- }
- }
-
- return result
-}
-
-// isSystemPath checks if a path is a PostgreSQL system schema.
-// NOTE: This is primarily designed for PostgreSQL.
-func isSystemPath(path string) bool {
- // PostgreSQL system schemas.
- systemSchemas := []string{"pg_catalog", "information_schema", "pg_toast", "pg_temp_1", "pg_temp_2", "pg_global", "$user"}
- for _, schema := range systemSchemas {
- if strings.EqualFold(path, schema) {
- return true
- }
- }
- return false
-}