Documentation
¶
Overview ¶
Package pool provides a pgxpool.Pool wrapper with schema isolation, database/sql compatibility, health check, and graceful shutdown.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Metrics ¶
type Metrics struct {
Active int32 `json:"active"`
Idle int32 `json:"idle"`
Total int32 `json:"total"`
Max int32 `json:"max"`
WaitTime time.Duration `json:"-"`
}
Metrics holds a snapshot of pool statistics.
func (Metrics) HealthJSON ¶
HealthJSON returns a JSON-encoded representation of the metrics suitable for use in health endpoints. WaitTime is expressed as milliseconds.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool wraps pgxpool.Pool with schema isolation and database/sql compatibility.
func NewPool ¶
NewPool opens a connection pool for the given DSN with schema isolation. It creates the schema if it doesn't exist and sets the search_path.
Example ¶
package main
import (
"context"
"log"
"github.com/benaskins/axon-base/pool"
)
func main() {
ctx := context.Background()
p, err := pool.NewPool(ctx, "postgres://postgres@localhost:5432/mydb", "public")
if err != nil {
log.Fatal(err)
}
defer p.Close()
if p.Healthy(ctx) {
log.Println("database is reachable")
}
}
Output:
func (*Pool) Close ¶
func (p *Pool) Close()
Close closes all connections in the pool and the database/sql handle if opened.
func (*Pool) Metrics ¶
Metrics returns a snapshot of the current pool statistics.
Example ¶
package main
import (
"context"
"log"
"github.com/benaskins/axon-base/pool"
)
func main() {
ctx := context.Background()
p, err := pool.NewPool(ctx, "postgres://postgres@localhost:5432/mydb", "public")
if err != nil {
log.Fatal(err)
}
defer p.Close()
m := p.Metrics()
data, err := m.HealthJSON()
if err != nil {
log.Fatal(err)
}
// data is JSON suitable for a health endpoint:
// {"active":0,"idle":0,"total":0,"max":4,"wait_time_ms":0}
_ = data
}
Output:
func (*Pool) StdDB ¶
StdDB returns a *sql.DB handle backed by the same DSN and search_path. The handle is created lazily and cached for the lifetime of the Pool. This provides compatibility with libraries that require database/sql (e.g., goose migrations, axon-fact event stores).
func (*Pool) WithTransaction ¶
WithTransaction begins a transaction, executes fn, and commits on success. If fn returns an error, the transaction is rolled back and the error is returned.
Example ¶
ctx := context.Background()
p, err := pool.NewPool(ctx, "postgres://postgres@localhost:5432/mydb", "public")
if err != nil {
log.Fatal(err)
}
defer p.Close()
err = p.WithTransaction(ctx, func(ctx context.Context, tx pgx.Tx) error {
_, err := tx.Exec(ctx, "INSERT INTO users (id, name) VALUES ($1, $2)", "abc", "alice")
return err
})
if err != nil {
log.Fatal(err)
}