db

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 4, 2026 License: MPL-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultMaxConns limits concurrent connections to prevent resource exhaustion
	// during long-running deployments.
	DefaultMaxConns = 5

	// DefaultMinConns maintains at least one connection in the pool.
	DefaultMinConns = 1

	// DefaultMaxConnIdleTime keeps connections alive during long deployments
	// to avoid reconnection overhead.
	DefaultMaxConnIdleTime = 30 * time.Minute
)

Connection pool configuration constants

View Source
const AzurePostgreSQLScope = "https://ossrdbms-aad.database.windows.net/.default"

AzurePostgreSQLScope is the OAuth scope for Azure Database for PostgreSQL. This is the resource identifier that Azure AD uses to issue tokens for PostgreSQL access.

Variables

This section is empty.

Functions

func BuildConnectionString

func BuildConnectionString(config *pgmi.ConnectionConfig) string

BuildConnectionString converts a ConnectionConfig back to a PostgreSQL URI format. This is useful for creating connection strings for pgx.

func NewConnector

func NewConnector(config *pgmi.ConnectionConfig) (pgmi.Connector, error)

NewConnector is a factory function that creates the appropriate Connector based on the ConnectionConfig's AuthMethod.

func NewPoolAdapter

func NewPoolAdapter(pool *pgxpool.Pool) pgmi.DBConnection

NewPoolAdapter creates a new PoolAdapter wrapping the given pool.

func ParseConnectionString

func ParseConnectionString(connStr string) (*pgmi.ConnectionConfig, error)

ParseConnectionString parses a PostgreSQL connection string in either PostgreSQL URI format or ADO.NET format and returns a ConnectionConfig.

Supported formats:

  • PostgreSQL URI: postgresql://user:pass@localhost:5432/dbname?sslmode=disable
  • ADO.NET: Host=localhost;Port=5432;Database=dbname;Username=user;Password=pass

func ResolveConnectionParams

func ResolveConnectionParams(
	connStringFlag string,
	granularFlags *GranularConnFlags,
	azureFlags *AzureFlags,
	awsFlags *AWSFlags,
	googleFlags *GoogleFlags,
	certFlags *CertFlags,
	envVars *EnvVars,
	projectConfig *config.ProjectConfig,
) (*pgmi.ConnectionConfig, string, error)

ResolveConnectionParams resolves connection parameters using PostgreSQL-standard precedence:

1. Connection string flag (--connection) - if provided, parse and use directly 2. Granular flags (-h, -p, -U, -d) - if any provided, build config from flags 3. Environment variables (PGHOST, PGPORT, etc.) - fallback if no flags 4. DATABASE_URL environment variable - fallback if no granular params 5. Defaults (localhost:5432, prefer SSL)

Cloud Authentication: If azureFlags/awsFlags/googleFlags are provided OR corresponding environment variables are set, the AuthMethod is set accordingly and credentials are attached to the config. CLI flags take precedence over environment variables. Azure, AWS, and Google flags are mutually exclusive.

Returns:

  • ConnectionConfig with all parameters resolved
  • Maintenance database name (for CREATE DATABASE operations)
  • Error if configuration is invalid or conflicting

Conflict Detection: Returns error if BOTH --connection flag AND granular flags are provided. This prevents ambiguity and ensures clear user intent.

Types

type AWSFlags added in v0.9.0

type AWSFlags struct {
	Enabled bool
	Region  string // Overrides AWS_REGION or AWS_DEFAULT_REGION
}

AWSFlags represents AWS IAM authentication CLI flags. These override the corresponding AWS_* environment variables.

func (*AWSFlags) IsEmpty added in v0.9.0

func (a *AWSFlags) IsEmpty() bool

IsEmpty returns true if no AWS flags were provided.

type AWSIAMTokenProvider added in v0.9.0

type AWSIAMTokenProvider struct {
	// contains filtered or unexported fields
}

AWSIAMTokenProvider acquires IAM authentication tokens for RDS. Uses the default AWS credential chain (environment variables, config files, IAM roles, etc.)

func NewAWSIAMTokenProvider added in v0.9.0

func NewAWSIAMTokenProvider(endpoint, region, username string) (*AWSIAMTokenProvider, error)

NewAWSIAMTokenProvider creates a token provider for AWS RDS IAM authentication. endpoint is the RDS endpoint in host:port format (e.g., "mydb.cluster.region.rds.amazonaws.com:5432"). region is the AWS region (e.g., "us-west-2"). username is the database user configured for IAM authentication.

func (*AWSIAMTokenProvider) GetToken added in v0.9.0

func (p *AWSIAMTokenProvider) GetToken(ctx context.Context) (string, time.Time, error)

GetToken acquires an IAM authentication token from AWS. The token is valid for 15 minutes from acquisition time.

func (*AWSIAMTokenProvider) String added in v0.9.0

func (p *AWSIAMTokenProvider) String() string

String returns a human-readable representation of the provider.

type AzureDefaultCredentialProvider

type AzureDefaultCredentialProvider struct {
	// contains filtered or unexported fields
}

AzureDefaultCredentialProvider uses Azure's DefaultAzureCredential chain. This automatically tries multiple authentication methods in order: 1. Environment variables (AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID) 2. Workload Identity (for Kubernetes) 3. Managed Identity (for Azure VMs, App Service, etc.) 4. Azure CLI (for local development) 5. Azure Developer CLI 6. Azure PowerShell

func NewAzureDefaultCredentialProvider

func NewAzureDefaultCredentialProvider() (*AzureDefaultCredentialProvider, error)

NewAzureDefaultCredentialProvider creates a provider using the default credential chain.

func (*AzureDefaultCredentialProvider) GetToken

func (*AzureDefaultCredentialProvider) String

type AzureFlags

type AzureFlags struct {
	Enabled  bool
	TenantID string // Overrides AZURE_TENANT_ID
	ClientID string // Overrides AZURE_CLIENT_ID
}

AzureFlags represents Azure Entra ID CLI flags. These override the corresponding AZURE_* environment variables. Note: Client secret is NOT included as a CLI flag for security reasons. Use AZURE_CLIENT_SECRET environment variable instead.

func (*AzureFlags) IsEmpty

func (a *AzureFlags) IsEmpty() bool

IsEmpty returns true if no Azure flags were provided.

type AzureServicePrincipalProvider

type AzureServicePrincipalProvider struct {
	// contains filtered or unexported fields
}

AzureServicePrincipalProvider acquires tokens using Service Principal credentials. This is the primary authentication method for CI/CD pipelines.

func NewAzureServicePrincipalProvider

func NewAzureServicePrincipalProvider(tenantID, clientID, clientSecret string) (*AzureServicePrincipalProvider, error)

NewAzureServicePrincipalProvider creates a token provider for Service Principal auth. All three parameters (tenantID, clientID, clientSecret) are required.

func (*AzureServicePrincipalProvider) GetToken

func (*AzureServicePrincipalProvider) String

type CertFlags added in v0.9.0

type CertFlags struct {
	SSLCert     string
	SSLKey      string
	SSLRootCert string
}

CertFlags represents TLS client certificate CLI flags. These are additive — they can be combined with --connection or granular flags.

func (*CertFlags) IsEmpty added in v0.9.0

func (c *CertFlags) IsEmpty() bool

IsEmpty returns true if no certificate flags were provided.

type EnvVars

type EnvVars struct {
	PGHOST            string // PostgreSQL server host
	PGPORT            string // PostgreSQL server port
	PGUSER            string // PostgreSQL username
	PGPASSWORD        string // PostgreSQL password (discouraged, use .pgpass instead)
	PGDATABASE        string // Default database name
	PGSSLMODE         string // SSL mode
	PGAPPNAME         string // application_name reported in pg_stat_activity
	PGCONNECT_TIMEOUT string // Connection timeout in seconds (libpq convention)
	DATABASE_URL      string // Full connection string (Heroku/Rails convention)

	// Azure Entra ID environment variables (Azure SDK standard names)
	AZURE_TENANT_ID     string // Azure AD tenant/directory ID
	AZURE_CLIENT_ID     string // Azure AD application/client ID
	AZURE_CLIENT_SECRET string // Azure AD client secret (for Service Principal auth)

	// AWS IAM environment variables (AWS SDK standard names)
	AWS_REGION         string // AWS region for RDS IAM auth
	AWS_DEFAULT_REGION string // Fallback region (AWS SDK convention)

	// TLS client certificate environment variables (PostgreSQL standard)
	PGSSLCERT     string // Client certificate path
	PGSSLKEY      string // Client key path
	PGSSLROOTCERT string // Root CA certificate path
	PGSSLPASSWORD string // Client key password
}

EnvVars represents PostgreSQL standard environment variables. See: https://www.postgresql.org/docs/current/libpq-envars.html

func LoadFromEnvironment

func LoadFromEnvironment() *EnvVars

LoadFromEnvironment loads PostgreSQL and cloud provider environment variables. This follows standard PostgreSQL client behavior and Azure/AWS SDK conventions.

func (*EnvVars) HasAzureCredentials

func (e *EnvVars) HasAzureCredentials() bool

HasAzureCredentials returns true if Azure Entra ID environment variables are set.

type GoogleCloudSQLConnector added in v0.9.0

type GoogleCloudSQLConnector struct {
	// contains filtered or unexported fields
}

GoogleCloudSQLConnector implements the Connector interface for Google Cloud SQL using IAM database authentication via the Cloud SQL Go Connector.

Implements io.Closer — caller must call Close() after the pool is closed to release the Cloud SQL dialer resources.

func NewGoogleCloudSQLConnector added in v0.9.0

func NewGoogleCloudSQLConnector(config *pgmi.ConnectionConfig, instance string) *GoogleCloudSQLConnector

NewGoogleCloudSQLConnector creates a connector for Google Cloud SQL IAM authentication. instance is the instance connection name in format: project:region:instance

func (*GoogleCloudSQLConnector) Close added in v0.9.1

func (c *GoogleCloudSQLConnector) Close() error

Close releases the Cloud SQL dialer resources. Must be called after the connection pool returned by Connect() is closed.

func (*GoogleCloudSQLConnector) Connect added in v0.9.0

Connect establishes a connection pool using Google Cloud SQL IAM authentication. The Cloud SQL Go Connector handles authentication, TLS, and connection management.

After the pool is closed, the caller must call Close() on this connector to release the Cloud SQL dialer.

type GoogleFlags added in v0.9.0

type GoogleFlags struct {
	Enabled  bool
	Instance string // Instance connection name: project:region:instance
}

GoogleFlags represents Google Cloud SQL IAM authentication CLI flags.

func (*GoogleFlags) IsEmpty added in v0.9.0

func (g *GoogleFlags) IsEmpty() bool

IsEmpty returns true if no Google flags were provided.

type GranularConnFlags

type GranularConnFlags struct {
	Host     string
	Port     int
	Username string
	Database string
	SSLMode  string
}

GranularConnFlags represents connection parameters from CLI flags. These follow PostgreSQL standard flag conventions (-h, -p, -U, -d).

Note: Password is NOT included as a CLI flag for security reasons. Use one of these methods instead:

  1. $PGPASSWORD environment variable
  2. .pgpass file (PostgreSQL standard)
  3. Connection string with embedded password

func (*GranularConnFlags) IsEmpty

func (g *GranularConnFlags) IsEmpty() bool

IsEmpty returns true if no connection-related granular flags were provided by the user. Note: Database flag is excluded from this check because it can be used to override the database specified in a connection string.

type PoolAdapter

type PoolAdapter struct {
	// contains filtered or unexported fields
}

PoolAdapter adapts *pgxpool.Pool to implement the pgmi.DBConnection interface. This decouples the internal implementation from the public API, preventing direct exposure of pgx-specific types.

Thread-Safety: Safe for concurrent use (pgxpool.Pool is thread-safe).

func (*PoolAdapter) Acquire

Acquire obtains a dedicated connection from the pool.

func (*PoolAdapter) Exec

func (p *PoolAdapter) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)

Exec executes a query without returning any rows.

func (*PoolAdapter) QueryRow

func (p *PoolAdapter) QueryRow(ctx context.Context, sql string, args ...any) pgmi.Row

QueryRow executes a query that is expected to return at most one row.

type StandardConnector

type StandardConnector struct {
	// contains filtered or unexported fields
}

StandardConnector implements the Connector interface for standard username/password authentication with automatic retry on transient failures.

func NewStandardConnector

func NewStandardConnector(config *pgmi.ConnectionConfig) *StandardConnector

NewStandardConnector creates a new StandardConnector with the given configuration. Retry behavior uses pgmi defaults: DefaultRetryMaxAttempts attempts, exponential backoff starting at DefaultRetryInitialDelay, max DefaultRetryMaxDelay.

func (*StandardConnector) Connect

func (c *StandardConnector) Connect(ctx context.Context) (*pgxpool.Pool, error)

Connect establishes a connection pool using standard authentication with automatic retry.

type TokenBasedConnector added in v0.9.1

type TokenBasedConnector struct {
	// contains filtered or unexported fields
}

TokenBasedConnector implements the Connector interface for cloud providers that authenticate via short-lived tokens (AWS IAM, Azure Entra ID). The token is acquired from a TokenProvider and used as the PostgreSQL password.

func NewTokenBasedConnector added in v0.9.1

func NewTokenBasedConnector(config *pgmi.ConnectionConfig, tokenProvider TokenProvider, providerName string) *TokenBasedConnector

NewTokenBasedConnector creates a connector that uses a TokenProvider for authentication. providerName is used in error/warning messages (e.g., "AWS IAM", "Azure").

func (*TokenBasedConnector) Connect added in v0.9.1

func (c *TokenBasedConnector) Connect(ctx context.Context) (*pgxpool.Pool, error)

type TokenProvider

type TokenProvider interface {
	// GetToken acquires an OAuth token for database authentication.
	// The token is used as the password when connecting to cloud-hosted PostgreSQL.
	// Returns the token string and its expiry time.
	GetToken(ctx context.Context) (token string, expiresOn time.Time, err error)

	// String returns a human-readable description for logging.
	// Should NOT include secrets. Example: "AzureServicePrincipal(tenant=xxx, client=yyy)"
	String() string
}

TokenProvider abstracts cloud token acquisition for database authentication. This interface enables testability (mock providers) and future extensibility (AWS IAM, GCP, etc. can implement the same interface).

Directories

Path Synopsis
Package manager provides database management operations for PostgreSQL.
Package manager provides database management operations for PostgreSQL.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL