sqlpool

package module
v0.0.0-...-caa2fc3 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2021 License: MIT Imports: 8 Imported by: 0

README

SQL Connection Pool

This little package is supposed to be of help when needing multiple database connections of type *sql.DB. Available drivers are mysql, postgresql and sqlite.

Installation & Import

install with : go get -u github.com/KaiserWerk/SQL-Connection-Pool

import as e.g. sqlpool "github.com/KaiserWerk/SQL-Connection-Pool"

Usage

Create a new pool using default values, just supply the required driver and a DSN:

pool := sqlpool.New("mysql", "root:password@tcp(127.0.0.1:3306)/dbname", nil)
defer pool.Close()

You can supply a *PoolConfig as third parameter which allows you to alter the maximum connection limit and the connection check interval, e.g.

pool := sqlpool.New("mysql", "root:password@tcp(127.0.0.1:3306)/dbname", &sqlpool.PoolConfig{
    MaxConn: 10,
    MonitorInterval: 2 * time.Minute,
})
defer pool.Close()

pool.Close() closes all existing connections.

Get a connection (this either returns an unused existing one or creates a new connection if the maximum is not reached yet):

conn, err := pool.Get()

DB contains the actual *sql.DB connection. Use it to execute queries:

result, err := conn.DB.Query("SELECT * FROM user") // or Exec() or whatever

Return a connection when it is no longer needed. This makes the connection available again to be obtained via Get():

err := pool.Return(conn)

Niche methods

There are a few method which might prove to be helpful.

Return the current total connection count:

num := pool.GetConnectionCount()

Return the maximum connection count:

max := pool.GetMaxConnectionCount()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type PoolConfig

type PoolConfig struct {
	MaxConn         uint16
	MonitorInterval time.Duration
}

type SqlConn

type SqlConn struct {
	DB *sql.DB
	// contains filtered or unexported fields
}

type SqlPool

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

func New

func New(driver string, dsn string, config *PoolConfig) *SqlPool

func (*SqlPool) Close

func (pool *SqlPool) Close()

func (*SqlPool) Get

func (pool *SqlPool) Get() (*SqlConn, error)

func (*SqlPool) GetConnectionCount

func (pool *SqlPool) GetConnectionCount() int

func (*SqlPool) GetMaxConnectionCount

func (pool *SqlPool) GetMaxConnectionCount() uint16

func (*SqlPool) Return

func (pool *SqlPool) Return(conn *SqlConn) error

Jump to

Keyboard shortcuts

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