dbconnpool

package
v0.1.149 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package dbconnpool provides a connection pool for SQLite databases using database/sql. It manages connection lifecycle including acquisition, validation, release and cleanup. The pool maintains both maximum total connections and minimum idle connections, automatically scaling between these bounds based on demand.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrPoolClosed is returned when attempting to get a connection from a closed pool.
	ErrPoolClosed = errors.New("connection pool is closed")
	// ErrConnectionUnavailable is returned when no connections are available and max connections reached.
	ErrConnectionUnavailable = errors.New("no connections available and max connections reached")
)

Common errors that can be returned by the connection pool.

Functions

This section is empty.

Types

type Config

type Config struct {
	// DriverName specifies the name of the database driver to use (e.g., "sqlite").
	DriverName string

	// ReadOnly opens connections in read-only mode. When true, connection
	// creation is not serialized, allowing parallel preparation of statements.
	ReadOnly bool

	// Maximum number of connections the pool will create.
	MaxConnections int64

	// Minimum number of idle connections to maintain.
	MinIdleConnections int64

	// QueriesFunc is a function to instantiate a Queries object for a new connection.
	QueriesFunc func(db gallerydb.DBTX) *gallerydb.CustomQueries

	// MonitorInterval specifies how often the connection maintenance monitor should run.
	MonitorInterval time.Duration

	// HealthCheckThreshold is the minimum idle duration before a connection is
	// pinged on Get(). Connections idle for less than this are assumed healthy
	// and returned without a round-trip ping.
	// Default: 30s. Set to 0 to ping on every Get().
	HealthCheckThreshold time.Duration
}

Config holds the configuration parameters for DbSQLConnPool.

type ConnectionError

type ConnectionError struct {
	Op  string // the operation that failed (e.g., "ping", "connect")
	Err error  // the underlying error
}

ConnectionError represents an error that occurred with a specific connection.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type ConnectionPool

type ConnectionPool interface {
	// Get acquires a connection from the pool. Blocks if pool is at capacity.
	// Returns ErrPoolClosed if the pool has been closed.
	Get() (*CpConn, error)

	// Put returns a connection to the pool for reuse.
	// Safe to call with nil (no-op).
	Put(cpc *CpConn)

	// Close gracefully shuts down the pool, closing all connections.
	// Returns ErrPoolClosed if already closed.
	Close() error

	// DB returns the underlying *sql.DB for operations that need direct access
	// (e.g., migrations). Use sparingly.
	DB() *sql.DB

	// NumIdleConnections returns the current number of idle connections.
	NumIdleConnections() int

	// NumConnections returns the total number of connections (idle + in-use).
	NumConnections() int64
}

ConnectionPool abstracts database connection pool operations. Implementations manage connection lifecycle, pooling, and health checks.

type CpConn

type CpConn struct {
	// Conn is the underlying database connection.
	Conn *sql.Conn

	// Queries holds the sqlc-generated query methods for this connection.
	Queries *gallerydb.CustomQueries
	// contains filtered or unexported fields
}

CpConn wraps an underlying *sql.Conn and holds a set of prepared queries associated with that connection.

func (*CpConn) Close

func (cpc *CpConn) Close() error

func (*CpConn) PragmaOptimize

func (cpc *CpConn) PragmaOptimize(ctx context.Context)

type DbSQLConnPool

type DbSQLConnPool struct {
	// Config holds the pool's configuration.
	Config Config
	// contains filtered or unexported fields
}

DbSQLConnPool manages a pool of SQL database connections. It provides thread-safe access to connections through a buffered channel, maintains connection health, and automatically scales the pool size.

All mutable state is managed via atomic operations and channels; no mutex is required on the Get/Put hot path.

func NewDbSQLConnPool

func NewDbSQLConnPool(
	ctx context.Context,
	dataSourceName string,
	config Config,
) (*DbSQLConnPool, error)

NewDbSQLConnPool creates a new connection pool with the specified parameters. driverName and dataSourceName are passed to sql.Open to create the base pool. config specifies the pool's connection limits and behavior. Returns error if the database connection cannot be established.

func (*DbSQLConnPool) Close

func (p *DbSQLConnPool) Close() error

Close gracefully shuts down the pool and releases all resources. Uses atomic CompareAndSwap to guarantee exactly-once shutdown. Returns ErrPoolClosed if already closed.

func (*DbSQLConnPool) DB

func (p *DbSQLConnPool) DB() *sql.DB

DB returns the underlying *sql.DB instance. This method should be used with caution, primarily for tools like database migrators that require direct access to the *sql.DB object. The connection pool should not be in active use when the returned *sql.DB is being manipulated.

func (*DbSQLConnPool) DbStats

func (p *DbSQLConnPool) DbStats() sql.DBStats

DbStats returns database/sql DBStats for the underlying sql.DB pool.

func (*DbSQLConnPool) Get

func (p *DbSQLConnPool) Get() (*CpConn, error)

Get acquires a connection from the pool. It will:

  • Return an existing idle connection if available (skipping ping if recently used)
  • Create a new connection if below maxConnections (slot reserved via CAS)
  • Block waiting for a connection if at maxConnections

Returns ErrPoolClosed if pool has been closed.

func (*DbSQLConnPool) Monitor

func (p *DbSQLConnPool) Monitor()

Monitor maintains the pool's connection count within configured bounds. Running as a goroutine, it periodically:

  • Creates connections up to the full deficit if idle < minIdleConnections
  • Closes one excess idle connection per tick if idle > minIdleConnections

Exits when context is cancelled or done channel is closed.

func (*DbSQLConnPool) NumConnections

func (p *DbSQLConnPool) NumConnections() int64

NumConnections returns the current total number of connections in the pool.

func (*DbSQLConnPool) NumIdleConnections

func (p *DbSQLConnPool) NumIdleConnections() int

NumIdleConnections returns the current number of idle connections in the pool.

func (*DbSQLConnPool) Put

func (p *DbSQLConnPool) Put(cpc *CpConn)

Put returns a connection to the pool for reuse. The connection's idleSince is stamped so that Get() can skip health-check pings for recently-returned connections. If the pool is closed, the connection is closed immediately. Safe to call with nil (no-op).

Jump to

Keyboard shortcuts

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