From 3833253578970a8000a9775214b4e1d163129d0c Mon Sep 17 00:00:00 2001 From: Martijn Pieters Date: Wed, 19 Jun 2024 11:33:04 +0100 Subject: [PATCH] Postgres: Support "$user" search path This simply replaces the string `"$user"` in the Postgres search path with the current username. --- drivers/postgres/postgres.go | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/drivers/postgres/postgres.go b/drivers/postgres/postgres.go index d5606bc3c..d602e8e27 100644 --- a/drivers/postgres/postgres.go +++ b/drivers/postgres/postgres.go @@ -70,7 +70,27 @@ func (p *Postgres) Analyze(s *schema.Schema) error { return errors.WithStack(err) } } - s.Driver.Meta.SearchPaths = strings.Split(searchPaths, ", ") + splitPaths := strings.Split(searchPaths, ", ") + // Replace "$user" with the current username + for idx, path := range splitPaths { + if path == `"$user"` { + var userName string + userNameRows, err := p.db.Query(`SELECT current_user`) + if err != nil { + return errors.WithStack(err) + } + defer userNameRows.Close() + for userNameRows.Next() { + err := userNameRows.Scan(&userName) + if err != nil { + return errors.WithStack(err) + } + } + splitPaths[idx] = userName + } + } + + s.Driver.Meta.SearchPaths = splitPaths fullTableNames := []string{} @@ -649,7 +669,6 @@ func detectFullTableName(name string, searchPaths, fullTableNames []string) (str for _, n := range fullTableNames { if strings.HasSuffix(n, name) { for _, p := range searchPaths { - // TODO: Support $user if n == fmt.Sprintf("%s.%s", p, name) { fns = append(fns, n) }