implement
This commit is contained in:
73
internal/postgres/client.go
Normal file
73
internal/postgres/client.go
Normal file
@ -0,0 +1,73 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/exp/slog"
|
||||
)
|
||||
|
||||
type DatabaseStats struct {
|
||||
MaxConnections int32
|
||||
TotalConnections int32
|
||||
AcquiredConnections int32
|
||||
IdleConnections int32
|
||||
}
|
||||
|
||||
type Client interface {
|
||||
io.Closer
|
||||
|
||||
Queue() QueueClient
|
||||
|
||||
GetStats() DatabaseStats
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
MaxConns int64
|
||||
MaxIdleConns int64
|
||||
MasterDSN string
|
||||
}
|
||||
|
||||
type client struct {
|
||||
pool *pgxpool.Pool
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func New(ctx context.Context, config Config, logger *slog.Logger) (*client, error) {
|
||||
pgconfig, err := pgxpool.ParseConfig(config.MasterDSN)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing config: %w", err)
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pgconfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("making new connection: %w", err)
|
||||
}
|
||||
|
||||
return &client{
|
||||
pool: pool,
|
||||
log: logger.With(slog.String("name", "db")),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *client) Close() error {
|
||||
if c.pool == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
c.pool.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) GetStats() DatabaseStats {
|
||||
stat := c.pool.Stat()
|
||||
|
||||
return DatabaseStats{
|
||||
MaxConnections: stat.MaxConns(),
|
||||
TotalConnections: stat.TotalConns(),
|
||||
AcquiredConnections: stat.AcquiredConns(),
|
||||
IdleConnections: stat.IdleConns(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user