Files
zitadel/backend/v3/storage/database/dialect/postgres/config.go

90 lines
2.0 KiB
Go
Raw Normal View History

2025-04-29 06:03:47 +02:00
package postgres
import (
"context"
"errors"
"slices"
"strings"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/mitchellh/mapstructure"
"github.com/zitadel/zitadel/backend/v3/storage/database"
)
var (
_ database.Connector = (*Config)(nil)
Name = "postgres"
isMigrated bool
2025-04-29 06:03:47 +02:00
)
type Config struct {
*pgxpool.Config
*pgxpool.Pool
2025-04-29 06:03:47 +02:00
// Host string
// Port int32
// Database string
// MaxOpenConns uint32
// MaxIdleConns uint32
// MaxConnLifetime time.Duration
// MaxConnIdleTime time.Duration
// User User
// // Additional options to be appended as options=<Options>
// // The value will be taken as is. Multiple options are space separated.
// Options string
// configuredFields []string
2025-04-29 06:03:47 +02:00
}
// Connect implements [database.Connector].
func (c *Config) Connect(ctx context.Context) (database.Pool, error) {
pool, err := c.getPool(ctx)
2025-04-29 06:03:47 +02:00
if err != nil {
return nil, wrapError(err)
2025-04-29 06:03:47 +02:00
}
if err = pool.Ping(ctx); err != nil {
return nil, wrapError(err)
2025-04-29 06:03:47 +02:00
}
return &pgxPool{Pool: pool}, nil
2025-04-29 06:03:47 +02:00
}
func (c *Config) getPool(ctx context.Context) (*pgxpool.Pool, error) {
if c.Pool != nil {
return c.Pool, nil
}
return pgxpool.NewWithConfig(ctx, c.Config)
}
2025-04-29 06:03:47 +02:00
func NameMatcher(name string) bool {
return slices.Contains([]string{"postgres", "pg"}, strings.ToLower(name))
}
func DecodeConfig(input any) (database.Connector, error) {
switch c := input.(type) {
case string:
config, err := pgxpool.ParseConfig(c)
if err != nil {
return nil, err
}
return &Config{Config: config}, nil
case map[string]any:
connector := new(Config)
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
WeaklyTypedInput: true,
Result: connector,
})
if err != nil {
return nil, err
}
if err = decoder.Decode(c); err != nil {
return nil, err
}
return &Config{
Config: &pgxpool.Config{},
}, nil
}
return nil, errors.New("invalid configuration")
}