databasecfg

package
v9.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProviderPostgres = "postgres"
	ProviderMySQL    = "mysql"
	ProviderSQLite   = "sqlite"
)

Variables

This section is empty.

Functions

func NewClientConfig

func NewClientConfig(cfg Config) database.ClientConfig

NewClientConfig converts Config to database.ClientConfig.

func NewDatabase

func NewDatabase(
	ctx context.Context,
	cfg *Config,
	migrator database.Migrator,
	opts ...Option,
) (client database.Client, err error)

NewDatabase creates a database client based on the configured provider and optionally runs migrations if RunMigrations is true and a migrator is provided. If metricsProvider is non-nil and cfg.EnableDatabaseMetrics is true, the client will emit db.sql.* metrics (e.g. db_sql_latency_milliseconds). DB metrics are off by default to avoid high cardinality.

func RegisterClientConfig

func RegisterClientConfig(i do.Injector)

RegisterClientConfig registers a database.ClientConfig with the injector.

func RegisterDatabase

func RegisterDatabase(i do.Injector)

RegisterDatabase registers a database.Client with the injector. Prerequisite: *Config must be registered in the injector. A database.Migrator is only required when the config's RunMigrations is true.

Types

type Config

type Config struct {
	Provider              string            `env:"PROVIDER"                envDefault:"postgres"        json:"provider"              yaml:"provider"`
	ReadConnection        ConnectionDetails `envPrefix:"READ_CONNECTION_"  json:"readConnection"        yaml:"readConnection"`
	WriteConnection       ConnectionDetails `envPrefix:"WRITE_CONNECTION_" json:"writeConnection"       yaml:"writeConnection"`
	PingWaitPeriod        time.Duration     `env:"PING_WAIT_PERIOD"        envDefault:"1s"              json:"pingWaitPeriod"        yaml:"pingWaitPeriod"`
	MaxPingAttempts       uint64            `env:"MAX_PING_ATTEMPTS"       json:"maxPingAttempts"       yaml:"maxPingAttempts"`
	ConnMaxLifetime       time.Duration     `env:"CONN_MAX_LIFETIME"       envDefault:"30m"             json:"connMaxLifetime"       yaml:"connMaxLifetime"`
	MaxIdleConns          uint16            `env:"MAX_IDLE_CONNS"          envDefault:"5"               json:"maxIdleConns"          yaml:"maxIdleConns"`
	MaxOpenConns          uint16            `env:"MAX_OPEN_CONNS"          envDefault:"7"               json:"maxOpenConns"          yaml:"maxOpenConns"`
	Debug                 bool              `env:"DEBUG"                   json:"debug"                 yaml:"debug"`
	LogQueries            bool              `env:"LOG_QUERIES"             json:"logQueries"            yaml:"logQueries"`
	RunMigrations         bool              `env:"RUN_MIGRATIONS"          json:"runMigrations"         yaml:"runMigrations"`
	EnableDatabaseMetrics bool              `env:"ENABLE_DATABASE_METRICS" json:"enableDatabaseMetrics" yaml:"enableDatabaseMetrics"`
	// contains filtered or unexported fields
}

Config represents our database configuration.

func (*Config) ConnectToReadDatabase

func (cfg *Config) ConnectToReadDatabase() (*sql.DB, error)

func (*Config) ConnectToWriteDatabase

func (cfg *Config) ConnectToWriteDatabase() (*sql.DB, error)

func (*Config) EnsureDefaults

func (cfg *Config) EnsureDefaults()

EnsureDefaults sets sensible defaults for zero-valued fields.

func (*Config) GetConnMaxLifetime

func (cfg *Config) GetConnMaxLifetime() time.Duration

GetConnMaxLifetime implements database.ClientConfig. Returns 30m when unset (zero).

func (*Config) GetLogQueries

func (cfg *Config) GetLogQueries() bool

GetLogQueries reports whether SQL query text should be recorded on database spans. The database client providers consume this via an optional interface assertion; when false (the default), otelsql is configured to suppress the db.statement attribute so raw SQL is not emitted into traces.

func (*Config) GetMaxIdleConns

func (cfg *Config) GetMaxIdleConns() int

GetMaxIdleConns implements database.ClientConfig. Returns 5 when unset (zero).

func (*Config) GetMaxOpenConns

func (cfg *Config) GetMaxOpenConns() int

GetMaxOpenConns implements database.ClientConfig. Returns 7 when unset (zero).

func (*Config) GetMaxPingAttempts

func (cfg *Config) GetMaxPingAttempts() uint64

GetMaxPingAttempts implements database.ClientConfig. Returns 50 when unset (zero) so IsReady retries rather than making a single attempt.

func (*Config) GetPingWaitPeriod

func (cfg *Config) GetPingWaitPeriod() time.Duration

GetPingWaitPeriod implements database.ClientConfig.

func (*Config) GetReadConnectionString

func (cfg *Config) GetReadConnectionString() string

GetReadConnectionString implements database.ClientConfig.

func (*Config) GetWriteConnectionString

func (cfg *Config) GetWriteConnectionString() string

GetWriteConnectionString implements database.ClientConfig.

func (*Config) LoadConnectionDetailsFromURL

func (cfg *Config) LoadConnectionDetailsFromURL(u string) error

LoadConnectionDetailsFromURL wraps an inner function.

func (*Config) ValidateWithContext

func (cfg *Config) ValidateWithContext(ctx context.Context) error

ValidateWithContext validates a Config. Connection requirements are provider-aware: SQLite only needs a database file path (on either the read or write connection), while Postgres and MySQL require a fully specified read connection. A write connection, when supplied, is validated regardless of provider.

type ConnectionDetails

type ConnectionDetails struct {
	Username   string `env:"USERNAME"    json:"username"   yaml:"username"`
	Password   string `env:"PASSWORD"    json:"password"   yaml:"password"`
	Database   string `env:"DATABASE"    json:"database"   yaml:"database"`
	Host       string `env:"HOST"        json:"hostname"   yaml:"hostname"`
	Port       uint16 `env:"PORT"        json:"port"       yaml:"port"`
	DisableSSL bool   `env:"DISABLE_SSL" json:"disableSSL" yaml:"disableSSL"`
	// contains filtered or unexported fields
}

func (*ConnectionDetails) LoadFromURL

func (x *ConnectionDetails) LoadFromURL(u string) error

LoadFromURL accepts a Postgres connection string and parses it into the ConnectionDetails struct.

func (*ConnectionDetails) MySQLDSN

func (x *ConnectionDetails) MySQLDSN() string

MySQLDSN returns a MySQL DSN connection string. parseTime=true is required so the driver scans DATETIME/TIMESTAMP columns into time.Time rather than []byte, which the null-value helpers (e.g. TimeFromNullTime) depend on. The driver defaults loc to UTC, so times come back in UTC. The DSN is assembled via the driver's own Config so credentials/host values are escaped rather than concatenated.

func (*ConnectionDetails) SQLiteDSN

func (x *ConnectionDetails) SQLiteDSN() string

SQLiteDSN returns the database file path for SQLite.

func (*ConnectionDetails) String

func (x *ConnectionDetails) String() string

func (*ConnectionDetails) URI

func (x *ConnectionDetails) URI() string

func (*ConnectionDetails) ValidateWithContext

func (x *ConnectionDetails) ValidateWithContext(ctx context.Context) error

ValidateWithContext validates an DatabaseSettings struct.

type Option

type Option func(*options)

Option configures how NewDatabase assembles its client.

The observability dependencies are options rather than parameters because every one of them is genuinely optional: an absent logger logs nowhere, an absent tracer provider traces nowhere, and an absent metrics provider records nothing. Requiring them positionally made a caller that wanted none of the three name all three anyway, usually as noops.

func WithLogger

func WithLogger(logger logging.Logger) Option

WithLogger attaches a logger. An absent logger logs nowhere.

func WithMetricsProvider

func WithMetricsProvider(metricsProvider metrics.Provider) Option

WithMetricsProvider attaches a metrics provider. An absent provider records nothing.

func WithPillars

func WithPillars(p *observability.Pillars) Option

WithPillars attaches a logger, tracer provider, and metrics provider in one go, for the common case where a caller has already built them together. A nil Pillars attaches nothing.

It is applied in order with the individual options, so a caller can hand over its pillars and then override one of them.

func WithTracerProvider

func WithTracerProvider(tracerProvider tracing.TracerProvider) Option

WithTracerProvider attaches a tracer provider, enabling spans on the instrumented operations. An absent tracer provider traces nowhere.

Jump to

Keyboard shortcuts

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