Skip to content

Commit e741d86

Browse files
committed
feat(postgres): implement setting plan_cache_mode based on connection string
1 parent 5cdb87f commit e741d86

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

pkg/database/postgres/postgres.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"strings"
66
"time"
77

8+
"golang.org/x/exp/slog"
9+
810
"github.com/jackc/pgx/v5"
911

1012
"github.com/jackc/pgx/v5/pgxpool"
@@ -57,6 +59,8 @@ func New(uri string, opts ...Option) (*Postgres, error) {
5759

5860
setDefaultQueryExecMode(writeConfig.ConnConfig)
5961
setDefaultQueryExecMode(readConfig.ConnConfig)
62+
setPlanCacheMode(writeConfig.ConnConfig)
63+
setPlanCacheMode(readConfig.ConnConfig)
6064

6165
writeConfig.MinConns = int32(pg.maxIdleConnections)
6266
readConfig.MinConns = int32(pg.maxIdleConnections)
@@ -138,10 +142,35 @@ func setDefaultQueryExecMode(config *pgx.ConnConfig) {
138142
for key := range queryExecModes {
139143
if strings.Contains(config.ConnString(), "default_query_exec_mode="+key) {
140144
config.DefaultQueryExecMode = queryExecModes[key]
145+
slog.Info("setDefaultQueryExecMode", slog.String("mode", key))
141146
return
142147
}
143148
}
144149

145150
// Set to default mode if no matching mode is found
146151
config.DefaultQueryExecMode = queryExecModes[defaultMode]
152+
slog.Warn("setDefaultQueryExecMode", slog.String("mode", defaultMode))
153+
}
154+
155+
var planCacheModes = map[string]string{
156+
"auto": "auto",
157+
"force_custom_plan": "force_custom_plan",
158+
}
159+
160+
func setPlanCacheMode(config *pgx.ConnConfig) {
161+
// Default mode if no specific mode is found in the connection string
162+
defaultMode := "auto"
163+
164+
// Check if a plan cache mode is mentioned in the connection string and set it
165+
for key := range planCacheModes {
166+
if strings.Contains(config.ConnString(), "plan_cache_mode="+key) {
167+
config.Config.RuntimeParams["plan_cache_mode"] = planCacheModes[key]
168+
slog.Info("setPlanCacheMode", slog.String("mode", key))
169+
return
170+
}
171+
}
172+
173+
// Set to default mode if no matching mode is found
174+
config.Config.RuntimeParams["plan_cache_mode"] = planCacheModes[defaultMode]
175+
slog.Warn("setPlanCacheMode", slog.String("mode", defaultMode))
147176
}

0 commit comments

Comments
 (0)