dbx

package module
v0.0.0-...-3baa8e4 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 16 Imported by: 0

README

dbx

dbx is a Go package that provides robust database management functionality, including connection pooling, caching, migration support, and optimized SQLite configuration. It is built on top of the Bun ORM and provides high-level abstractions for common database operations.

Features

  • Optimized SQLite Support: Automatic configuration with WAL mode, synchronous=NORMAL, and connection pooling settings tailored for SQLite.
  • Connection Caching: Built-in cache for database connections with automatic cleanup of inactive connections.
  • Migration Support: Seamless integration with goose for running migrations from embedded filesystems.
  • Robust Transactions: Simple API for managing transactions, including support for nested transactions via savepoints.
  • Bun ORM Integration: Returns *bun.DB instances, allowing you to use all the power of the Bun ORM.
  • Multi-Driver Support: Compatible with SQLite (modern sqlite and mattn/go-sqlite3), PostgreSQL, MySQL, and MSSQL.

Installation

go get github.com/akinmayowa/dbx

Quick Start

Opening a Database Connection

dbx.OpenDB handles driver-specific configurations and sets up connection pooling.

import "github.com/akinmayowa/dbx"

// Open a SQLite database
db, err := dbx.OpenDB("myapp", 
    dbx.WithDriverName(dbx.DriverSQLite),
    dbx.WithDbFolder("./data"),
)
if err != nil {
    log.Fatal(err)
}
defer db.Close()
Database Migrations

You can easily run migrations using an embedded filesystem.

//go:embed migrations/*.sql
var migrations embed.FS

err := dbx.MigrateDB("myapp",
    dbx.CreateWithSource(migrations),
    dbx.CreateWithSrcFolder("migrations"),
)
Using the Connection Cache

The Cache allows you to manage multiple database connections efficiently, which is useful in multi-tenant applications.

cache := dbx.NewCache(30 * time.Minute) // Cleanup connections inactive for 30m
defer cache.Close()

// GetOrOpen will return an existing connection or open a new one
db, err := cache.GetOrOpen("tenant_1", 
    dbx.WithDbFolder("./tenants"),
)
Transaction Management

The Transact helper simplifies transaction handling and supports nesting.

t, err := dbx.NewTransact(db)
if err != nil {
    log.Fatal(err)
}

err = t.Transaction(ctx, nil, func(ctx context.Context) error {
    // Perform operations using t.Db()
    _, err := t.Db().NewInsert().Model(&item).Exec(ctx)
    if err != nil {
        return err // Will trigger rollback
    }

    // Nested transaction (uses savepoints)
    return t.Transaction(ctx, nil, func(ctx context.Context) error {
        // ... nested operations
        return nil
    })
})

Configuration Options

Open Options (OpenOptFn)
  • WithDriverName(name): Specify the database driver (default: DriverSQLite).
  • WithDbFolder(path): Folder for SQLite database files (default: ./data).
  • WithMaxOpenConns(n): Set maximum open connections.
  • WithMaxIdleConns(n): Set maximum idle connections.
  • WithConnMaxLifetime(d): Set maximum connection lifetime.
Create Options (CreateOptFn)
  • CreateWithDriverName(name): Specify the driver for migrations.
  • CreateWithDbFolder(path): Folder for SQLite database files.
  • CreateWithSource(fs): embed.FS containing migration files.
  • CreateWithSrcFolder(path): Path within the embed.FS where migrations are located.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCacheClosed        = errors.New("cache is closed")
	ErrDatabaseNotFound   = errors.New("database not found in cache")
	ErrDatabaseOpenFailed = errors.New("database failed to open in another goroutine")
)
View Source
var ErrDBFileNotFound = errors.New("db file not found")

Functions

func CreateDB

func CreateDB(dsn string, opts ...CreateOptFn) error

CreateDB creates a new database specified by the dsn and runs migrations. Provides the following options:

  • CreateWithDriverName(driverName DriverName) - specify the database driver (default: DriverSQLite)
  • CreateWithDbFolder(folder string) - specify the folder to create the SQLite database file in (default: "./data")
  • CreateWithSource(fs embed.FS) - specify the embedded filesystem containing migration files
  • CreateWithSrcFolder(folder string) - specify the folder within the embedded filesystem containing migration files

For SQLite, if the database file already exists, it will not be overwritten. For other databases, ensure that the user has the necessary permissions to create a new database.

func DbFilePath

func DbFilePath(name, dbFolder string) (string, error)

DbFilePath converts a name into a full path to the db including the file extension

func IsSQLite

func IsSQLite(dn DriverName) bool

func MigrateDB

func MigrateDB(dsn string, opts ...CreateOptFn) (err error)

MigrateDB runs migrations on the db

func OpenDB

func OpenDB(dsn string, opts ...OpenOptFn) (*bun.DB, error)

OpenDB opens a new database connection. for sqlite, dsn should be a file name (without extension)

func TableExists

func TableExists(ctx context.Context, db *bun.DB, tableName string) (bool, error)

TableExists checks if a table exists in the database

Types

type Cache

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

func NewCache

func NewCache(inactiveDuration time.Duration) *Cache

func (*Cache) Cleanup

func (c *Cache) Cleanup()

func (*Cache) Close

func (c *Cache) Close() error

func (*Cache) Get

func (c *Cache) Get(name string) (db *bun.DB, err error)

func (*Cache) GetOrOpen

func (c *Cache) GetOrOpen(name string, openOptions ...OpenOptFn) (db *bun.DB, err error)

func (*Cache) Has

func (c *Cache) Has(name string) *bun.DB

func (*Cache) Set

func (c *Cache) Set(name string, db *bun.DB) bool

type CreateOptFn

type CreateOptFn func(options *CreateOptions)

func CreateWithDbFolder

func CreateWithDbFolder(nme string) CreateOptFn

func CreateWithDriverName

func CreateWithDriverName(dn DriverName) CreateOptFn

func CreateWithSource

func CreateWithSource(fs embed.FS) CreateOptFn

func CreateWithSrcFolder

func CreateWithSrcFolder(n string) CreateOptFn

type CreateOptions

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

type DriverName

type DriverName string
const (
	DriverSQLiteMc DriverName = "sqlite"
	DriverSQLite   DriverName = "sqlite3"
	DriverPostgres DriverName = "postgres"
	DriverPgx      DriverName = "pgx"
	DriverMySQL    DriverName = "mysql"
	DriverMSSQL    DriverName = "mssql"
)

type IDB

type IDB interface {
	Db() (db bun.IDB)
	Start(opt *sql.TxOptions) error
	Commit() error
	Rollback() error
	Transaction(opt *sql.TxOptions, fn TransactFunc) (err error)
	Ctx() context.Context
}

type ListOptions

type ListOptions struct {
	Where string
	Args  []any
	Limit int
}

type OpenOptFn

type OpenOptFn func(options *Options)

func WithConnMaxIdleTime

func WithConnMaxIdleTime(n time.Duration) OpenOptFn

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) OpenOptFn

func WithDbFolder

func WithDbFolder(nme string) OpenOptFn

func WithDriverName

func WithDriverName(dn DriverName) OpenOptFn

func WithLog

func WithLog(log bool) OpenOptFn

func WithMaxIdleConns

func WithMaxIdleConns(n int) OpenOptFn

func WithMaxOpenConns

func WithMaxOpenConns(n int) OpenOptFn

type Options

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

type Transact

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

func NewTransact

func NewTransact(ctx context.Context, db *bun.DB) (tsx *Transact, err error)

func (*Transact) Commit

func (t *Transact) Commit() error

func (*Transact) Ctx

func (t *Transact) Ctx() context.Context

func (*Transact) Db

func (t *Transact) Db() (db bun.IDB)

func (*Transact) Rollback

func (t *Transact) Rollback() error

func (*Transact) Start

func (t *Transact) Start(opt *sql.TxOptions) error

func (*Transact) Transaction

func (t *Transact) Transaction(opt *sql.TxOptions, fn TransactFunc) (err error)

type TransactFunc

type TransactFunc func(ctx context.Context) error

Jump to

Keyboard shortcuts

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