{"modulePath":"github.com/stacklok/toolhive-core","version":"v0.0.62","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package postgres\n\nPackage postgres provides a shared PostgreSQL connection layer for the ToolHive ecosystem. It wraps github.com/jackc/pgx/v5/pgxpool with a single Config type, a NewPool factory, and a dynamic-authentication dispatcher. Schema management — migrations, queries, and per-application type codecs — remains the caller's responsibility.\n\n### Quick Start {#hdr-Quick_Start}\n\n\tcfg := \u0026postgres.Config{\n\t    Host:     \"db.example.com\",\n\t    Port:     5432,\n\t    User:     \"appuser\",\n\t    Password: \"s3cret\",\n\t    Database: \"appdb\",\n\t}\n\n\tpool, err := postgres.NewPool(ctx, cfg)\n\tif err != nil {\n\t    return err\n\t}\n\tdefer pool.Close()\n\n### Dynamic Authentication {#hdr-Dynamic_Authentication}\n\nSetting Config.DynamicAuth causes NewPool to install a BeforeConnect hook that resolves a fresh credential before every connection attempt. Exactly one backend must be configured.\n\nCurrently supported backends:\n\n  - AWS RDS IAM — short-lived tokens signed with the workload's ambient AWS credentials (env vars, EC2 instance profile, EKS web identity, …). Region \"detect\" auto-discovers the region via IMDS.\n\n  - Azure Entra ID (formerly Azure AD) — OAuth2 tokens for Azure Database for PostgreSQL, acquired via DefaultAzureCredential's normal chain (environment variables, workload identity, managed identity, Azure CLI, …). AZURE\\_CLIENT\\_ID selects a user-assigned managed identity.\n\n  - GCP Cloud SQL IAM — OAuth2 tokens minted from ambient Application Default Credentials, connecting over a direct TCP+TLS connection. This is NOT the Cloud SQL Go connector (cloudsqlconn): it requires the instance to have a reachable IP (public, or private with direct network routing) and does not get Cloud SQL's automatic mTLS tunnel.\n\nExamples:\n\n\tcfg.DynamicAuth = \u0026postgres.DynamicAuthConfig{\n\t    AWSRDSIAM: \u0026postgres.DynamicAuthAWSRDSIAM{Region: \"us-east-1\"},\n\t}\n\n\tcfg.DynamicAuth = \u0026postgres.DynamicAuthConfig{\n\t    AzureAD: \u0026postgres.DynamicAuthAzureAD{},\n\t}\n\n\tcfg.DynamicAuth = \u0026postgres.DynamicAuthConfig{\n\t    GCPCloudSQLIAM: \u0026postgres.DynamicAuthGCPCloudSQLIAM{},\n\t}\n\nFor short-lived connections that cannot use a pool hook (for example golang-migrate's one-shot migration connection), call NewAuthToken to materialize a single token, then embed it via BuildConnectionStringWithAuth:\n\n\ttoken, _ := postgres.NewAuthToken(ctx, cfg, cfg.GetMigrationUser())\n\tconnStr := cfg.BuildConnectionStringWithAuth(cfg.GetMigrationUser(), token)\n\n### Hooks {#hdr-Hooks}\n\nWithAfterConnect installs an AfterConnect callback — the canonical place to register application-specific type codecs (for example, codecs for PostgreSQL enum array types defined in the caller's schema):\n\n\tpool, err := postgres.NewPool(ctx, cfg,\n\t    postgres.WithAfterConnect(func(ctx context.Context, conn *pgx.Conn) error {\n\t        return registerMyEnumCodecs(ctx, conn)\n\t    }),\n\t)\n\nWithBeforeConnect installs a BeforeConnect hook directly. It is mutually exclusive with Config.DynamicAuth — NewPool refuses both, because silently dropping one would leave production tokens to expire ~15 minutes after deploy. Callers that genuinely need both should call NewDynamicAuthFunc, compose with their hook, and pass the composition via WithBeforeConnect with Config.DynamicAuth left nil.\n\n### TLS and SSL Mode {#hdr-TLS_and_SSL_Mode}\n\nDefaultSSLMode is \"require\", which mandates an encrypted connection but does not verify the server certificate against a CA. This defends against passive eavesdropping; it does not defend against an active attacker that can present a forged certificate. For production deployments against cloud Postgres services that publish a CA bundle (for example AWS RDS, Google Cloud SQL, Azure Database for PostgreSQL), set SSLMode to \"verify-full\" and configure pgx with the appropriate CA roots — typically by placing the bundle on disk and setting PGSSLROOTCERT, or by attaching a \\*tls.Config via WithAfterConnect. \"require\" is kept as the package default because tighter modes break self-signed and dev environments out of the box; production callers should opt up explicitly.\n\n### Logging {#hdr-Logging}\n\nNewPool emits a single info-level message on success, redacting password fields via Config's slog.LogValuer implementation. StartPoolStatsLogger is an opt-in helper that periodically logs connection-pool statistics at debug level until its context is cancelled.\n\n### Secrets Handling {#hdr-Secrets_Handling}\n\nThis package treats Password and MigrationPassword as already-resolved strings. File-based secret loading, environment-variable overrides, and pgpass fallback all live in the caller's configuration layer. Config implements slog.LogValuer to redact credentials when logged.\n\n## Constants\n\n```go\nconst DefaultPoolStatsInterval = 60 * time.Second\n```\nDefaultPoolStatsInterval is the cadence at which StartPoolStatsLogger emits a connection-pool snapshot when no other interval is configured.\n\n```go\nconst DefaultSSLMode = \"require\"\n```\nDefaultSSLMode is applied when Config.SSLMode is empty. It mandates an encrypted connection but does not verify the server certificate against a CA — encryption-only, not authentication. Use \"verify-ca\" or \"verify-full\" when the deployment provides a CA bundle (for example, cloud Postgres services); see the package overview for production guidance.\n\n## Functions\n\n```go\nfunc NewAuthToken(ctx context.Context, cfg *Config, user string) (string, error)\n```\nNewAuthToken returns a short-lived password for user produced by the dynamic-authentication backend configured in cfg.DynamicAuth. When DynamicAuth is nil, the empty string is returned and no error is raised — this lets callers fall back to a static Password or PGPASSFILE.\n\nThis entry point is intended for short-lived connections (for example, running migrations) where pgxpool's BeforeConnect hook is not available. For pooled connections, prefer NewDynamicAuthFunc.\n\n```go\nfunc NewPool(ctx context.Context, cfg *Config, opts ...Option) (*pgxpool.Pool, error)\n```\nNewPool creates a \\*pgxpool.Pool from cfg. When cfg.DynamicAuth is set, NewPool installs the appropriate dynamic-auth hook on BeforeConnect.\n\nPassing both cfg.DynamicAuth and WithBeforeConnect is an error — the failure mode of a silently-replaced auth hook (tokens expiring 15 min after deploy) is severe enough to refuse the ambiguity. Callers that genuinely want to layer logic on top of dynamic auth should call NewDynamicAuthFunc, compose the hooks themselves, and pass the composition via WithBeforeConnect with cfg.DynamicAuth left nil.\n\ncfg is validated; cfg is not mutated.\n\n```go\nfunc StartPoolStatsLogger(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, interval time.Duration)\n```\nStartPoolStatsLogger emits a connection-pool snapshot at DEBUG every interval until ctx is cancelled. When interval is zero, the default cadence is used. When logger is nil, slog.Default() is used.\n\nThis is an opt-in helper; consumers that want pool metrics through a different sink (OpenTelemetry, Prometheus) should read pool.Stat() themselves.\n\n## Types\n\n```go\ntype BeforeConnectFn func(ctx context.Context, conn *pgx.ConnConfig) error\n```\nBeforeConnectFn rewrites a connection config (typically by replacing the password) immediately before pgx dials. It is the contract used by pgxpool.Config.BeforeConnect and by this package's dynamic-auth backends.\n\n```go\nfunc NewDynamicAuthFunc(ctx context.Context, cfg *Config, user string) (BeforeConnectFn, error)\n```\nNewDynamicAuthFunc returns a BeforeConnect hook that resolves a fresh dynamic-auth credential on every connection attempt. The returned hook writes the resolved token into connConfig.Password.\n\nReturns an error when cfg.DynamicAuth is nil — callers that may or may not be configured for dynamic auth should branch on cfg.DynamicAuth before calling this constructor, or use NewPool which handles both shapes transparently.\n\n```go\ntype Config struct {\n\t// Host is the database server hostname or IP address.\n\tHost string\n\n\t// Port is the database server port. Required.\n\tPort int\n\n\t// User is the database username for normal operations\n\t// (SELECT/INSERT/UPDATE/DELETE).\n\tUser string\n\n\t// Password is the application-user password. When empty, pgx falls back\n\t// to PGPASSFILE / ~/.pgpass. Mutually exclusive with DynamicAuth at the\n\t// caller's option — this package does not enforce mutual exclusion\n\t// because some callers legitimately want a static fallback during local\n\t// development.\n\tPassword string //nolint:gosec // G101: field name, not a hardcoded credential\n\n\t// MigrationUser is the database username for schema migrations. When\n\t// empty, defaults to User.\n\tMigrationUser string\n\n\t// MigrationPassword is the password for MigrationUser. When empty and\n\t// MigrationUser equals User, falls back to Password. Otherwise pgx falls\n\t// back to PGPASSFILE / ~/.pgpass.\n\tMigrationPassword string //nolint:gosec // G101: field name, not a hardcoded credential\n\n\t// Database is the database name.\n\tDatabase string\n\n\t// SSLMode is the SSL mode for the connection (disable, require, verify-ca,\n\t// verify-full). When empty, DefaultSSLMode is applied by the connection\n\t// string builder.\n\tSSLMode string\n\n\t// DynamicAuth, when non-nil, generates short-lived credentials at connect\n\t// time via NewPool's automatically-installed BeforeConnect hook.\n\tDynamicAuth *DynamicAuthConfig\n\n\t// MaxOpenConns sets the upper bound on open connections in the pool. When\n\t// zero, pgxpool's default is used.\n\tMaxOpenConns int32\n\n\t// MinConns is the minimum number of connections pgxpool actively\n\t// maintains in the pool — the pool keeps this many connections open\n\t// even when the application is idle. When zero, pgxpool's default is\n\t// used.\n\t//\n\t// Note for readers used to database/sql: this is the opposite of\n\t// database/sql's MaxIdleConns (which is a ceiling on idle\n\t// connections). pgxpool has no idle-ceiling concept; the floor is the\n\t// only knob.\n\tMinConns int32\n\n\t// ConnMaxLifetime is the maximum lifetime of a connection. When zero,\n\t// pgxpool's default is used.\n\tConnMaxLifetime time.Duration\n}\n```\nConfig configures a PostgreSQL connection pool. Password fields are resolved by the caller — file-based secrets, environment variables, and pgpass fallback all live outside this package.\n\n```go\nfunc (c *Config) BuildConnectionStringWithAuth(user, password string) string\n```\nBuildConnectionStringWithAuth builds a libpq-style connection URL using the supplied user and password. When password is empty, the resulting URL omits credentials and pgx will fall back to PGPASSFILE / ~/.pgpass.\n\nThe caller is responsible for resolving credentials — dynamic-auth token generation, secret-file reads, and env-var overrides all happen outside this package.\n\n```go\nfunc (c *Config) ConnectionString() string\n```\nConnectionString builds a libpq-style connection URL for the application user. When Password is empty, pgx falls back to PGPASSFILE / ~/.pgpass.\n\n```go\nfunc (c *Config) GetMigrationPassword() string\n```\nGetMigrationPassword returns the password for the migration user. When MigrationPassword is unset and the migration user matches User, the application Password is returned. Otherwise an empty string is returned so pgx can fall back to PGPASSFILE / ~/.pgpass.\n\n```go\nfunc (c *Config) GetMigrationUser() string\n```\nGetMigrationUser returns the user that owns schema migrations. Falls back to User when MigrationUser is unset.\n\n```go\nfunc (c *Config) LogValue() slog.Value\n```\nLogValue implements slog.LogValuer. It redacts password fields and reports only presence-indicators for credentials, preventing accidental secret disclosure in logs.\n\n```go\nfunc (c *Config) MigrationConnectionString() string\n```\nMigrationConnectionString builds a libpq-style connection URL for the migration user. Useful for short-lived migration tooling where a BeforeConnect hook is not available.\n\n```go\nfunc (c *Config) Validate() error\n```\nValidate checks Config for required-field and consistency errors and returns the first violation encountered.\n\n```go\ntype DynamicAuthAWSRDSIAM struct {\n\t// Region is the AWS region used to sign IAM tokens. Use \"detect\" to\n\t// auto-discover the region from the EC2 instance metadata service (IMDS).\n\tRegion string\n}\n```\nDynamicAuthAWSRDSIAM configures AWS RDS IAM dynamic authentication.\n\n```go\ntype DynamicAuthAzureAD struct{}\n```\nDynamicAuthAzureAD configures Azure Entra ID (formerly Azure AD) authentication for Azure Database for PostgreSQL. It has no fields: the token is minted from DefaultAzureCredential's normal resolution order (environment variables — including AZURE\\_CLIENT\\_ID to select a user-assigned managed identity — workload identity, system-assigned managed identity, Azure CLI, ...).\n\n```go\ntype DynamicAuthConfig struct {\n\t// AWSRDSIAM enables AWS RDS IAM authentication tokens.\n\tAWSRDSIAM *DynamicAuthAWSRDSIAM\n\n\t// AzureAD enables Azure Entra ID (formerly Azure AD) authentication\n\t// tokens for Azure Database for PostgreSQL.\n\tAzureAD *DynamicAuthAzureAD\n\n\t// GCPCloudSQLIAM enables GCP Cloud SQL IAM database authentication\n\t// tokens over a direct TCP+TLS connection. This is NOT the Cloud SQL Go\n\t// connector (cloudsqlconn): it requires the instance to have a reachable\n\t// IP (public, or private with direct network routing) and does not get\n\t// Cloud SQL's automatic mTLS tunnel. Instances reachable only through\n\t// the connector need a different integration this package does not\n\t// provide.\n\tGCPCloudSQLIAM *DynamicAuthGCPCloudSQLIAM\n}\n```\nDynamicAuthConfig selects a dynamic-authentication backend. Exactly one backend field must be non-nil when DynamicAuthConfig itself is non-nil.\n\n```go\ntype DynamicAuthGCPCloudSQLIAM struct{}\n```\nDynamicAuthGCPCloudSQLIAM configures GCP Cloud SQL IAM database authentication. It has no fields: the token is minted from ambient Application Default Credentials, scoped for Cloud SQL login.\n\n```go\ntype Option func(*options)\n```\nOption customizes NewPool. See WithBeforeConnect, WithAfterConnect, and WithLogger.\n\n```go\nfunc WithAfterConnect(fn func(ctx context.Context, conn *pgx.Conn) error) Option\n```\nWithAfterConnect installs a hook that runs immediately after a new connection has been established. The typical use case is registering custom type codecs (for example, application-defined enum array codecs).\n\n```go\nfunc WithBeforeConnect(fn BeforeConnectFn) Option\n```\nWithBeforeConnect installs a hook that runs immediately before pgx dials.\n\nNewPool rejects a combination of WithBeforeConnect and cfg.DynamicAuth — a silently-replaced auth hook would leave production tokens to expire 15 minutes after deploy. Callers that need both must call NewDynamicAuthFunc explicitly, compose the two hooks themselves in the order they want, and pass the composed result via WithBeforeConnect (with cfg.DynamicAuth left nil so this package does not also try to install an auth hook).\n\n```go\nfunc WithLogger(logger *slog.Logger) Option\n```\nWithLogger sets the slog.Logger used for pool-creation messages and (when invoked) StartPoolStatsLogger output. When unset, slog.Default() is used.\n\n","path":"github.com/stacklok/toolhive-core/postgres","name":"postgres","synopsis":"Package postgres provides a shared PostgreSQL connection layer for the ToolHive ecosystem.","isRedistributable":true}
