Connection Manager
Complete package reference for the go-migration Connection Manager, Driver registration, and ConnectionConfig — all public methods with signatures, parameters, return types, and usage examples.
Connection Manager API
The Connection Manager handles multiple named database connections with configurable connection pooling. It works with any database/sql-compatible driver.
Import path: github.com/gopackx/go-migration/pkg/database
Driver implementations live in github.com/gopackx/go-migration/pkg/database/drivers.
For conceptual documentation, see Connection Manager.
database.NewManager()
Creates a new connection manager.
func NewManager() *ManagerReturns: *Manager
import "github.com/gopackx/go-migration/pkg/database"
mgr := database.NewManager()
defer mgr.Close()mgr.RegisterDriver()
Registers a database driver with the manager.
func (m *Manager) RegisterDriver(name string, driver Driver)| Parameter | Type | Description |
|---|---|---|
name | string | The driver name connections reference via their Driver field |
driver | database.Driver | A driver implementation (Open(ConnectionConfig) (*sql.DB, error) + Name() string) |
import (
"github.com/gopackx/go-migration/pkg/database/drivers"
_ "github.com/lib/pq"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
)
mgr.RegisterDriver("postgres", drivers.NewPostgresDriver())
mgr.RegisterDriver("mysql", drivers.NewMySQLDriver())
mgr.RegisterDriver("sqlite3", drivers.NewSQLiteDriver())The second argument is a Driver value, not a string. Use the constructors in the drivers package: NewPostgresDriver(), NewMySQLDriver(), NewSQLiteDriver(). You must also import the underlying database/sql driver package with a blank identifier (_) so it registers itself via its init() function.
See Drivers for setup details for each database.
mgr.AddConnection()
Registers a named connection with its discrete connection fields and pool settings. The actual connection is opened lazily on the first Connection() call. The first connection added becomes the default.
func (m *Manager) AddConnection(name string, config ConnectionConfig) error| Parameter | Type | Description |
|---|---|---|
name | string | Unique name for this connection |
config | ConnectionConfig | Connection configuration (driver, host, credentials, pool settings, options) |
Returns: error — returns an error if config.Driver is empty.
import "time"
err := mgr.AddConnection("primary", database.ConnectionConfig{
Driver: "postgres",
Host: "localhost",
Port: 5432,
Database: "myapp",
Username: "user",
Password: "pass",
MaxOpenConns: 25,
MaxIdleConns: 5,
ConnMaxLifetime: 5 * time.Minute,
Options: map[string]string{"sslmode": "disable"},
})
if err != nil {
log.Fatalf("add connection: %v", err)
}See Pool Configuration for recommended pool values.
mgr.SetDefault()
Sets which named connection is the default. The connection must already be registered with AddConnection().
func (m *Manager) SetDefault(name string) error| Parameter | Type | Description |
|---|---|---|
name | string | The name of a registered connection |
Returns: error — returns an error if the named connection is not registered.
if err := mgr.SetDefault("primary"); err != nil {
log.Fatalf("set default: %v", err)
}mgr.Default()
Returns the default *sql.DB. The first connection added becomes the default automatically unless changed with SetDefault().
func (m *Manager) Default() (*sql.DB, error)Returns: *sql.DB, error — returns an error if no default has been set.
db, err := mgr.Default()
if err != nil {
log.Fatalf("get default connection: %v", err)
}mgr.Connection()
Retrieves a *sql.DB instance by its registered name.
func (m *Manager) Connection(name string) (*sql.DB, error)| Parameter | Type | Description |
|---|---|---|
name | string | The name used in AddConnection() |
Returns: *sql.DB, error
The returned *sql.DB is a standard Go database connection — use it with any library or ORM.
db, err := mgr.Connection("primary")
if err != nil {
log.Fatalf("failed to get connection: %v", err)
}
rows, err := db.Query("SELECT id, name FROM users")mgr.Close()
Closes all managed database connections.
func (m *Manager) Close() errorReturns: error — returns an error if any connection fails to close.
if err := mgr.Close(); err != nil {
log.Printf("error closing connections: %v", err)
}Always call mgr.Close() (or use defer mgr.Close()) when your application exits to release database connections.
database.WithTransaction()
A package-level helper for running arbitrary work inside a single database transaction. It begins a transaction, calls your function, commits if it returns nil, and rolls back if it returns an error (if the commit itself fails, it attempts a rollback and returns a descriptive error).
func WithTransaction(db *sql.DB, fn TxFunc) error
type TxFunc func(tx *sql.Tx) error| Parameter | Type | Description |
|---|---|---|
db | *sql.DB | The database to open the transaction on |
fn | TxFunc | Function executed within the transaction; receives the *sql.Tx |
import "github.com/gopackx/go-migration/pkg/database"
err := database.WithTransaction(db, func(tx *sql.Tx) error {
if _, err := tx.Exec("INSERT INTO users (name) VALUES ($1)", "Alice"); err != nil {
return err // rolls back
}
if _, err := tx.Exec("INSERT INTO profiles (user_id) VALUES (lastval())"); err != nil {
return err // rolls back
}
return nil // commits
})This is useful in seeders or any code that needs all-or-nothing behavior across multiple statements. See Manual Transactions for more.
ConnectionConfig Struct
Configuration for a single database connection.
type ConnectionConfig struct {
Driver string
Host string
Port int
Database string
Username string
Password string
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
Options map[string]string
}There is no DSN field. Each driver builds its own DSN from these discrete fields; driver-specific parameters (like PostgreSQL's sslmode) go in Options.
| Field | Type | Description | Default |
|---|---|---|---|
Driver | string | Name of the registered driver | (required) |
Host | string | Database server hostname or IP | |
Port | int | Database server port | |
Database | string | Database name (or file path for SQLite) | |
Username | string | Database user | |
Password | string | Database password | |
MaxOpenConns | int | Maximum number of open connections | 0 → Go default (unlimited) |
MaxIdleConns | int | Maximum number of idle connections | 0 → Go default (2) |
ConnMaxLifetime | time.Duration | Maximum lifetime of a connection | 0 → Go default (no limit) |
Options | map[string]string | Driver-specific options, e.g. {"sslmode": "disable"} | nil |
Pool settings map directly to Go's *sql.DB methods: SetMaxOpenConns(), SetMaxIdleConns(), and SetConnMaxLifetime(). go-migration only calls these when the value is greater than zero, otherwise the database/sql defaults apply.
See Pool Configuration for tuning guidance.
Complete Example
package main
import (
"fmt"
"log"
"time"
"github.com/gopackx/go-migration/pkg/database"
"github.com/gopackx/go-migration/pkg/database/drivers"
_ "github.com/lib/pq"
_ "github.com/go-sql-driver/mysql"
)
func main() {
mgr := database.NewManager()
defer mgr.Close()
// Register drivers
mgr.RegisterDriver("postgres", drivers.NewPostgresDriver())
mgr.RegisterDriver("mysql", drivers.NewMySQLDriver())
// Add connections
mgr.AddConnection("primary", database.ConnectionConfig{
Driver: "postgres",
Host: "localhost",
Port: 5432,
Database: "myapp",
Username: "user",
Password: "pass",
MaxOpenConns: 25,
MaxIdleConns: 5,
ConnMaxLifetime: 5 * time.Minute,
Options: map[string]string{"sslmode": "disable"},
})
mgr.AddConnection("analytics", database.ConnectionConfig{
Driver: "mysql",
Host: "localhost",
Port: 3306,
Database: "analytics",
Username: "user",
Password: "pass",
MaxOpenConns: 10,
MaxIdleConns: 3,
ConnMaxLifetime: 5 * time.Minute,
Options: map[string]string{"parseTime": "true"},
})
// Use connections
primaryDB, err := mgr.Connection("primary")
if err != nil {
log.Fatalf("primary connection failed: %v", err)
}
analyticsDB, err := mgr.Connection("analytics")
if err != nil {
log.Fatalf("analytics connection failed: %v", err)
}
fmt.Println("Primary:", primaryDB.Stats().OpenConnections, "open")
fmt.Println("Analytics:", analyticsDB.Stats().OpenConnections, "open")
}Quick Reference
| Component | Method | Signature | Description |
|---|---|---|---|
| Manager | NewManager | NewManager() *Manager | Create a manager |
| Manager | RegisterDriver | RegisterDriver(name string, driver Driver) | Register a database driver |
| Manager | AddConnection | AddConnection(name string, config ConnectionConfig) error | Add a named connection |
| Manager | SetDefault | SetDefault(name string) error | Set the default connection |
| Manager | Default | Default() (*sql.DB, error) | Get the default connection |
| Manager | Connection | Connection(name string) (*sql.DB, error) | Get a connection by name |
| Manager | Close | Close() error | Close all connections |
| Package | WithTransaction | WithTransaction(db *sql.DB, fn TxFunc) error | Run a function inside a transaction (commit/rollback automatically) |
| Config | ConnectionConfig | struct | Driver, host, credentials, pool settings, and options |