go-migrationGo Migration
Package Reference
Documentation

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.

go
func NewManager() *Manager

Returns: *Manager

go
import "github.com/gopackx/go-migration/pkg/database"

mgr := database.NewManager()
defer mgr.Close()

mgr.RegisterDriver()

Registers a database driver with the manager.

go
func (m *Manager) RegisterDriver(name string, driver Driver)
ParameterTypeDescription
namestringThe driver name connections reference via their Driver field
driverdatabase.DriverA driver implementation (Open(ConnectionConfig) (*sql.DB, error) + Name() string)
go
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.

go
func (m *Manager) AddConnection(name string, config ConnectionConfig) error
ParameterTypeDescription
namestringUnique name for this connection
configConnectionConfigConnection configuration (driver, host, credentials, pool settings, options)

Returns: error — returns an error if config.Driver is empty.

go
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().

go
func (m *Manager) SetDefault(name string) error
ParameterTypeDescription
namestringThe name of a registered connection

Returns: error — returns an error if the named connection is not registered.

go
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().

go
func (m *Manager) Default() (*sql.DB, error)

Returns: *sql.DB, error — returns an error if no default has been set.

go
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.

go
func (m *Manager) Connection(name string) (*sql.DB, error)
ParameterTypeDescription
namestringThe 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.

go
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.

go
func (m *Manager) Close() error

Returns: error — returns an error if any connection fails to close.

go
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).

go
func WithTransaction(db *sql.DB, fn TxFunc) error

type TxFunc func(tx *sql.Tx) error
ParameterTypeDescription
db*sql.DBThe database to open the transaction on
fnTxFuncFunction executed within the transaction; receives the *sql.Tx
go
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.

go
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.

FieldTypeDescriptionDefault
DriverstringName of the registered driver(required)
HoststringDatabase server hostname or IP
PortintDatabase server port
DatabasestringDatabase name (or file path for SQLite)
UsernamestringDatabase user
PasswordstringDatabase password
MaxOpenConnsintMaximum number of open connections0 → Go default (unlimited)
MaxIdleConnsintMaximum number of idle connections0 → Go default (2)
ConnMaxLifetimetime.DurationMaximum lifetime of a connection0 → Go default (no limit)
Optionsmap[string]stringDriver-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

main.go
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

ComponentMethodSignatureDescription
ManagerNewManagerNewManager() *ManagerCreate a manager
ManagerRegisterDriverRegisterDriver(name string, driver Driver)Register a database driver
ManagerAddConnectionAddConnection(name string, config ConnectionConfig) errorAdd a named connection
ManagerSetDefaultSetDefault(name string) errorSet the default connection
ManagerDefaultDefault() (*sql.DB, error)Get the default connection
ManagerConnectionConnection(name string) (*sql.DB, error)Get a connection by name
ManagerCloseClose() errorClose all connections
PackageWithTransactionWithTransaction(db *sql.DB, fn TxFunc) errorRun a function inside a transaction (commit/rollback automatically)
ConfigConnectionConfigstructDriver, host, credentials, pool settings, and options