Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): policy db should use pool connection hook to set search_path #1443

Merged
merged 4 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions service/pkg/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,6 @@ func New(ctx context.Context, config Config, logCfg logger.Config, o ...OptsFunc
}
}

// Set the Client search_path to the schema
q := fmt.Sprintf("SET search_path TO %s", config.Schema)
if _, err := c.Pgx.Exec(ctx, q); err != nil {
return nil, fmt.Errorf("failed to SET search_path for db Client schema to [%s]: %w", config.Schema, err)
}

slog.Info("successfully set database client search_path", slog.String("schema", config.Schema))
return &c, nil
}

Expand All @@ -185,7 +178,21 @@ func (c Config) buildConfig() (*pgxpool.Config, error) {
c.Database,
c.SSLMode,
)
return pgxpool.ParseConfig(u)
parsed, err := pgxpool.ParseConfig(u)
if err != nil {
return nil, fmt.Errorf("failed to parse pgx config: %w", err)
}
// Configure the search_path schema immediately on connection opening
parsed.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, fmt.Sprintf("SET search_path TO %s", c.Schema))
if err != nil {
slog.Error("failed to set database client search_path", slog.String("schema", c.Schema), slog.String("error", err.Error()))
return err
}
slog.Debug("successfully set database client search_path", slog.String("schema", c.Schema))
return nil
}
return parsed, nil
}

// Common function for all queryRow calls
Expand Down
2 changes: 2 additions & 0 deletions service/pkg/db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,7 @@ func Test_BuildConfig(t *testing.T) {
cfg, err := test.config.buildConfig()
require.NoError(t, err)
assert.Equal(t, test.want, cfg.ConnString())
// AfterConnect hook was defined when building
assert.NotNil(t, cfg.AfterConnect)
}
}
Loading