Documentation
¶
Overview ¶
Package pgsql provides a Lynx plugin for PostgreSQL using the pgx driver via database/sql. Configure with config key "lynx.pgsql" (source required).
Index ¶
- func CheckHealth() error
- func GetConfig() *interfaces.Config
- func GetDB() (*sql.DB, error)
- func GetDBWithContext(ctx context.Context) (*sql.DB, error)
- func GetDialect() string
- func GetDriver() (*entsql.Driver, error)
- func GetDriverProvider() func(ctx context.Context) (*entsql.Driver, error)
- func GetMetricsGatherer() prometheus.Gatherer
- func GetProvider() interfaces.DBProvider
- func GetStats() *base.ConnectionPoolStats
- func GetValidatedConn(ctx context.Context) (*sql.Conn, error)
- func IsConnected() bool
- func WaitForDB(ctx context.Context) (*sql.DB, error)
- func WaitForDBConnected(ctx context.Context) (*sql.DB, error)
- func WaitForDriver(ctx context.Context) (*entsql.Driver, error)
- type DBPgsqlClient
- type PrometheusConfig
- type PrometheusMetrics
- func (pm *PrometheusMetrics) GetGatherer() prometheus.Gatherer
- func (pm *PrometheusMetrics) IncConnectAttempt(config *conf.Pgsql)
- func (pm *PrometheusMetrics) IncConnectFailure(config *conf.Pgsql)
- func (pm *PrometheusMetrics) IncConnectRetry(config *conf.Pgsql)
- func (pm *PrometheusMetrics) IncConnectSuccess(config *conf.Pgsql)
- func (pm *PrometheusMetrics) RecordHealthCheck(success bool, config *conf.Pgsql)
- func (pm *PrometheusMetrics) RecordQuery(op string, dur time.Duration, err error, threshold time.Duration, ...)
- func (pm *PrometheusMetrics) RecordTx(dur time.Duration, committed bool, config *conf.Pgsql)
- func (m *PrometheusMetrics) UpdateMetrics(stats *base.ConnectionPoolStats, config *conf.Pgsql)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetConfig ¶
func GetConfig() *interfaces.Config
GetConfig returns the current pgsql plugin config, or nil if the plugin is not loaded or not *DBPgsqlClient. Config is read-only; do not modify.
func GetDB ¶
GetDB gets the database connection from the PostgreSQL plugin. Lynx must be initialized and the pgsql plugin started before calling this. The pool is validated (ping) before return when ensure_alive_before_handout is enabled (default); on failure the plugin reconnects so the pool is not handed out when broken.
When auto-reconnect is enabled, do not cache the returned *sql.DB in long-lived structs (e.g. Data/Repo built at startup). After a reconnection the previous *sql.DB is closed; cached references will get "sql: database is closed". Call GetDB/GetDBWithContext at the start of each request and use the result only for that request, or inject a provider (e.g. GetDBWithContext) and call it when needed.
func GetDBWithContext ¶
GetDBWithContext gets the database connection with context support (timeout/cancellation).
func GetDriver ¶
GetDriver gets the ent SQL driver from the PostgreSQL plugin. Returns an error if the database connection cannot be obtained. When auto-reconnect is enabled, do not cache the returned driver (or an ent.Client built from it) in long-lived structs; after Reconnect() the underlying *sql.DB is closed. Obtain the driver at request scope (e.g. call GetDriver in each handler and create ent.Client per request) or use GetDriverProvider.
func GetDriverProvider ¶
GetDriverProvider returns a stable provider for ent SQL drivers. The returned closure resolves the current pool on each call and should be preferred over caching GetDriver().
func GetMetricsGatherer ¶
func GetMetricsGatherer() prometheus.Gatherer
GetMetricsGatherer returns the Prometheus Gatherer for the pgsql plugin, or nil if the plugin is not loaded or Prometheus is not enabled. Use this to merge pgsql metrics into your /metrics endpoint, e.g. with prometheus.Gatherers.
func GetProvider ¶
func GetProvider() interfaces.DBProvider
GetProvider returns a stable provider for the current pgsql pool. The provider does not hold a concrete *sql.DB; each call resolves the current pool so it remains valid after reconnect.
func GetStats ¶
func GetStats() *base.ConnectionPoolStats
GetStats returns connection pool statistics from the pgsql plugin, or nil if the plugin is not loaded.
func GetValidatedConn ¶
GetValidatedConn returns a single connection from the pool that has been verified alive (Ping). Use this when you need a connection guaranteed to be usable at handoff time. Caller must call conn.Close() when done.
func WaitForDB ¶ added in v1.5.4
WaitForDB blocks until the pgsql plugin has provided a valid *sql.DB (i.e. Lynx initialized, plugin registered and StartupTasks has run so that GetDB() succeeds). Use this when your code may run before or during plugin startup. The context controls timeout and cancellation.
Extreme cases handled:
- Plugin in manager but StartupTasks not yet run: keeps polling until GetDB() returns (db, nil) with db != nil.
- StartupTasks failed (e.g. DB down): returns once the pool exists (GetDB() succeeds); use db.PingContext(ctx) or CheckHealth() if you need to ensure the connection is actually up.
- Lynx shutdown during wait: cancel the context from your shutdown path so WaitForDB returns with context error.
func WaitForDBConnected ¶ added in v1.5.4
WaitForDBConnected blocks until WaitForDB succeeds and the plugin reports IsConnected() (i.e. health check has passed). Use this when you need to ensure the database is reachable before proceeding, not just that the pool exists. If the DB is down, this will block until ctx expires; set a reasonable timeout (e.g. 30s) on the context.
Types ¶
type DBPgsqlClient ¶
DBPgsqlClient represents PostgreSQL client plugin instance
func NewPgsqlClient ¶
func NewPgsqlClient() *DBPgsqlClient
NewPgsqlClient creates a new PostgreSQL client plugin instance
func (*DBPgsqlClient) CleanupTasks ¶
func (p *DBPgsqlClient) CleanupTasks() error
CleanupTasks gracefully closes database connection
func (*DBPgsqlClient) GetConfig ¶
func (p *DBPgsqlClient) GetConfig() *interfaces.Config
GetConfig returns the current database config (read-only). May be nil if plugin not initialized.
func (*DBPgsqlClient) GetMetricsGatherer ¶
func (p *DBPgsqlClient) GetMetricsGatherer() prometheus.Gatherer
GetMetricsGatherer returns the Prometheus Gatherer for this plugin's metrics, or nil if Prometheus is not enabled. The application can merge this with the default registry when exposing /metrics.
func (*DBPgsqlClient) InitializeResources ¶
func (p *DBPgsqlClient) InitializeResources(rt plugins.Runtime) error
InitializeResources loads protobuf configuration and initializes resources. We set p.config from proto first; base.InitializeResources(rt) is then called and will Scan(p.config) again—ensure your config source can fill interfaces.Config (e.g. same keys as Config) so base validation passes and proto values are not lost.
func (*DBPgsqlClient) StartupTasks ¶
func (p *DBPgsqlClient) StartupTasks() error
StartupTasks initializes database connection
type PrometheusConfig ¶
type PrometheusConfig struct {
// Prometheus metric namespace
Namespace string
// Prometheus metric subsystem
Subsystem string
// Additional labels for metrics (used to build static or extended labels)
Labels map[string]string
}
PrometheusConfig Prometheus metric semantic configuration (for plugin internal private registry)
type PrometheusMetrics ¶
type PrometheusMetrics struct {
// Connection pool metrics
MaxOpenConnections *prometheus.GaugeVec
OpenConnections *prometheus.GaugeVec
InUseConnections *prometheus.GaugeVec
IdleConnections *prometheus.GaugeVec
MaxIdleConnections *prometheus.GaugeVec
// Wait metrics (Gauge: DBStats returns cumulative totals, we Set current value each tick to avoid double-counting)
WaitCount *prometheus.GaugeVec
WaitDuration *prometheus.GaugeVec
// Connection close metrics (Gauge: cumulative totals from DBStats, Set each tick)
MaxIdleClosed *prometheus.GaugeVec
MaxLifetimeClosed *prometheus.GaugeVec
// Health check metrics
HealthCheckTotal *prometheus.CounterVec
HealthCheckSuccess *prometheus.CounterVec
HealthCheckFailure *prometheus.CounterVec
// Configuration metrics
ConfigMinConn *prometheus.GaugeVec
ConfigMaxConn *prometheus.GaugeVec
// Query/transaction metrics
QueryDuration *prometheus.HistogramVec
TxDuration *prometheus.HistogramVec
ErrorCounter *prometheus.CounterVec
SlowQueryCnt *prometheus.CounterVec
// Connection retry/attempt/success/failure metrics
ConnectAttempts *prometheus.CounterVec
ConnectRetries *prometheus.CounterVec
ConnectSuccess *prometheus.CounterVec
ConnectFailures *prometheus.CounterVec
// contains filtered or unexported fields
}
PrometheusMetrics Prometheus monitoring metrics
func NewPrometheusMetrics ¶
func NewPrometheusMetrics(config *PrometheusConfig) *PrometheusMetrics
NewPrometheusMetrics Creates new Prometheus monitoring metrics
func (*PrometheusMetrics) GetGatherer ¶
func (pm *PrometheusMetrics) GetGatherer() prometheus.Gatherer
GetGatherer Returns the plugin's private Prometheus Gatherer (used to aggregate to global /metrics during application assembly phase)
func (*PrometheusMetrics) IncConnectAttempt ¶
func (pm *PrometheusMetrics) IncConnectAttempt(config *conf.Pgsql)
IncConnectAttempt Increments connection attempt counter
func (*PrometheusMetrics) IncConnectFailure ¶
func (pm *PrometheusMetrics) IncConnectFailure(config *conf.Pgsql)
IncConnectFailure Increments connection failure counter
func (*PrometheusMetrics) IncConnectRetry ¶
func (pm *PrometheusMetrics) IncConnectRetry(config *conf.Pgsql)
IncConnectRetry Increments connection retry counter
func (*PrometheusMetrics) IncConnectSuccess ¶
func (pm *PrometheusMetrics) IncConnectSuccess(config *conf.Pgsql)
IncConnectSuccess Increments connection success counter
func (*PrometheusMetrics) RecordHealthCheck ¶
func (pm *PrometheusMetrics) RecordHealthCheck(success bool, config *conf.Pgsql)
RecordHealthCheck Records health check results
func (*PrometheusMetrics) RecordQuery ¶
func (pm *PrometheusMetrics) RecordQuery(op string, dur time.Duration, err error, threshold time.Duration, config *conf.Pgsql, sqlState string)
RecordQuery Records SQL query duration, errors and slow query count
func (*PrometheusMetrics) UpdateMetrics ¶
func (m *PrometheusMetrics) UpdateMetrics(stats *base.ConnectionPoolStats, config *conf.Pgsql)
UpdateMetrics Updates monitoring metrics