Documentation
¶
Index ¶
- Variables
- func WithWriterContext(ctx context.Context) context.Context
- type Client
- func (p *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (p *Client) Close() error
- func (p *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (p *Client) HealthCheck(ctx context.Context) HealthStatus
- func (p *Client) InTransaction(ctx context.Context, opts *sql.TxOptions, fn TxFunc) (err error)
- func (p *Client) Ping(ctx context.Context) error
- func (p *Client) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
- func (p *Client) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (p *Client) Reader() *sql.DB
- func (p *Client) Shutdown(_ context.Context) error
- func (p *Client) Stats() Stats
- func (p *Client) Writer() *sql.DB
- type Config
- type HealthStatus
- type Option
- type Stats
- type TxFunc
Constants ¶
This section is empty.
Variables ¶
var ( // DefaultConnectTimeout is the default duration to wait for a database connection to be established. DefaultConnectTimeout = 5 * time.Second // DefaultQueryTimeout is the default duration to wait for a database query to complete. DefaultQueryTimeout = 30 * time.Second // WarmupMaxRetries is the maximum number of times to retry the database ping during warmup. WarmupMaxRetries = 5 // WarmupBaseDelay is the initial delay between retries. WarmupBaseDelay = 500 * time.Millisecond // WarmupMaxDelay is the maximum delay between retries. WarmupMaxDelay = 5 * time.Second )
var ( ErrNoOptions = errors.New("at least one database option must be provided") ErrWriterRequired = errors.New("writer configuration is required (use WithWriter)") )
var ( ErrInvalidDriver = errors.New("database driver is required") ErrInvalidDSN = errors.New("database DSN is required") ErrInvalidMaxOpenConns = errors.New("max open connections cannot be negative") ErrInvalidMaxIdleConns = errors.New("max idle connections cannot be negative") ErrInvalidConnMaxLifetime = errors.New("conn max lifetime cannot be negative") ErrInvalidConnMaxIdleTime = errors.New("conn max idle time cannot be negative") ErrInvalidConnectTimeout = errors.New("connect timeout cannot be negative") ErrInvalidQueryTimeout = errors.New("query timeout cannot be negative") )
Functions ¶
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client manages a pair of database connections for read/write splitting.
func (*Client) ExecContext ¶
ExecContext executes a query without returning any rows. It always uses the writer connection pool.
func (*Client) HealthCheck ¶
func (p *Client) HealthCheck(ctx context.Context) HealthStatus
HealthCheck performs a ping on both databases and aggregates the results and stats.
func (*Client) InTransaction ¶
InTransaction executes the provided function within a transaction. Lifecycle Management:
Starts a new transaction on the writer connection using BeginTx.
Executes the callback function 'fn'. Example usage: err := db.InTransaction(ctx, nil, func(ctx context.Context, tx *sql.Tx) error { // 'tx' is the active transaction. Use it for all operations. res, err := tx.ExecContext(ctx, "UPDATE users SET active = ? WHERE id = ?", true, 1) if err != nil { return fmt.Errorf("failed to update user: %w", err) // triggers Rollback }
if _, err := tx.ExecContext(ctx, "INSERT INTO logs..."); err != nil { return fmt.Errorf("failed to log action: %w", err) // triggers Rollback }
return nil // triggers Commit })
3. Atomicity:
- If 'fn' returns an error, the transaction is automatically rolled back.
- If 'fn' panics, the panic is captured, the transaction is rolled back, and the panic is returned as an error.
- If 'fn' succeeds (returns nil), the transaction is committed.
- If the commit itself fails, that error is returned.
func (*Client) QueryContext ¶
QueryContext executes a query that returns rows, typically a SELECT. It uses the reader connection pool if available, otherwise it falls back to the writer. If the context has the writer forced signal, it uses the writer pool.
func (*Client) QueryRowContext ¶
QueryRowContext executes a query that is expected to return at most one row. It uses the reader connection pool if available, otherwise it falls back to the writer. If the context has the writer forced signal, it uses the writer pool.
type Config ¶
type Config struct {
Driver string
DSN string
MaxOpenConnections int
MaxIdleConnections int
ConnectionsMaxLifetime time.Duration
ConnectionsMaxIdleTime time.Duration
Warmup bool
ConnectTimeout time.Duration
QueryTimeout time.Duration
}
Config holds the database connection settings.
func NewConfig ¶
func NewConfig( driver string, dsn string, maxOpenConns int, maxIdleConns int, connMaxLifetime time.Duration, connMaxIdleTime time.Duration, warmup bool, connectTimeout time.Duration, queryTimeout time.Duration, ) (Config, error)
NewConfig creates a new database configuration and validates it.
type HealthStatus ¶
type HealthStatus struct {
WriterAlive bool
ReaderAlive bool
OpenConns int
IdleConns int
Message string
}
HealthStatus represents the aggregated health of the Client.
type Option ¶
type Option func(*options)
Option defines a functional configuration for the database client.
func WithReader ¶
WithReader configures the Client with a reader connection (optional).
func WithWriter ¶
WithWriter configures the Client with a writer connection.