database

package
v0.0.1-beta Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
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
)
View Source
var (
	ErrNoOptions      = errors.New("at least one database option must be provided")
	ErrWriterRequired = errors.New("writer configuration is required (use WithWriter)")
)
View Source
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

func WithWriterContext

func WithWriterContext(ctx context.Context) context.Context

WithWriterContext returns a new context that signals database operations to use the writer connection. This is useful for reading data immediately after a write to avoid replication lag.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client manages a pair of database connections for read/write splitting.

func NewClient

func NewClient(ctx context.Context, opts ...Option) (*Client, error)

NewClient creates a new Client using the provided options.

func (*Client) BeginTx

func (p *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

BeginTx starts a new transaction on the writer connection.

func (*Client) Close

func (p *Client) Close() error

Close closes both writer and reader connections.

func (*Client) ExecContext

func (p *Client) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

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

func (p *Client) InTransaction(ctx context.Context, opts *sql.TxOptions, fn TxFunc) (err error)

InTransaction executes the provided function within a transaction. Lifecycle Management:

  1. Starts a new transaction on the writer connection using BeginTx.

  2. 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) Ping

func (p *Client) Ping(ctx context.Context) error

Ping verifies the connectivity to both writer and reader databases.

func (*Client) QueryContext

func (p *Client) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

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

func (p *Client) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

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.

func (*Client) Reader

func (p *Client) Reader() *sql.DB

Reader returns the reader database connection.

func (*Client) Shutdown

func (p *Client) Shutdown(_ context.Context) error

Shutdown gracefully shuts down the database connections.

func (*Client) Stats

func (p *Client) Stats() Stats

Stats returns the aggregated statistics for both writer and reader connections.

func (*Client) Writer

func (p *Client) Writer() *sql.DB

Writer returns the writer database connection.

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.

func (Config) Validate

func (c Config) Validate() error

Validate ensures the database configuration is valid.

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

func WithReader(cfg Config) Option

WithReader configures the Client with a reader connection (optional).

func WithWriter

func WithWriter(cfg Config) Option

WithWriter configures the Client with a writer connection.

type Stats

type Stats struct {
	Writer sql.DBStats
	Reader sql.DBStats
}

Stats holds aggregated statistics for the database connections.

type TxFunc

type TxFunc func(ctx context.Context, tx *sql.Tx) error

TxFunc is a function that can be executed within a transaction.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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