rockbun

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

rockbun

A bun ORM wrapper for PostgreSQL that integrates with rockconfig and provides lifecycle management (Ping, Close, RunInTx) via the Service interface.

Unlike rockredis, this package does not wrap individual operations — bun's query builder is rich enough to use directly. Instead rockbun handles connection setup, pool configuration, and transactions.

Quick Start

svc := rockbun.NewService(rockbun.Configs{
    DSN: "postgres://user:pass@localhost:5432/mydb?sslmode=disable",
})

// With rockengine: initialised before apps, closed after them.
rockengine.RegisterResource("db", svc)

// Standalone:
if err := svc.Init(ctx); err != nil { // opens the pool and pings
    log.Fatal(err)
}
defer svc.Stop()

db := svc.DB() // *bun.DB — use for all queries

Loading Config from File

rockbun.Configs is compatible with rockconfig.InitFromFile. All fields are optional.

# config.yaml — option 1: DSN
dsn: "postgres://user:pass@localhost:5432/mydb?sslmode=disable"

# option 2: individual fields (used when dsn is empty)
host: "localhost"
port: 5432
user: "myuser"
password: "secret"
database: "mydb"
ssl_mode: "disable"

# pool settings
max_open_conns: 25
max_idle_conns: 5
conn_max_lifetime: "1h"
conn_max_idle_time: "30m"
cfg, err := rockconfig.InitFromFile[rockbun.Configs]("config.yaml")
if err != nil {
    log.Fatal(err)
}

// QueryHooks must be set in code
cfg.QueryHooks = []bun.QueryHook{bundebug.NewQueryHook()}

svc := rockbun.NewService(*cfg)

Config

type Configs struct {
    DSN string  // "postgres://user:pass@host:port/db?sslmode=disable"
                // takes priority over individual fields

    Host     string // default "localhost"
    Port     int    // default 5432
    User     string
    Password string
    Database string
    SSLMode  string // default "disable"; use "verify-full" in production

    MaxOpenConns    int           // default 25
    MaxIdleConns    int           // default 5
    ConnMaxLifetime time.Duration // default 1h
    ConnMaxIdleTime time.Duration // default 30m

    QueryHooks []bun.QueryHook `config:"-"` // set in code only
}

Queries

Access the full bun query builder via DB():

db := svc.DB()

// Select
var users []User
err := db.NewSelect().Model(&users).Where("active = ?", true).Scan(ctx)

// Insert
user := &User{Name: "Alice", Email: "alice@example.com"}
_, err = db.NewInsert().Model(user).Exec(ctx)

// Update
_, err = db.NewUpdate().Model(user).Column("name").Where("id = ?", user.ID).Exec(ctx)

// Delete
_, err = db.NewDelete().Model(user).Where("id = ?", user.ID).Exec(ctx)

// Raw SQL
var count int
err = db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users").Scan(&count)

Transactions

err := svc.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
    if _, err := tx.NewInsert().Model(&order).Exec(ctx); err != nil {
        return err
    }
    if _, err := tx.NewUpdate().Model(&stock).
        Set("qty = qty - ?", order.Qty).
        Where("id = ?", stock.ID).
        Exec(ctx); err != nil {
        return err
    }
    return nil
})

Pass nil opts for the default isolation level, or set it explicitly:

svc.RunInTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}, fn)

Query Logging

Use bun's built-in bundebug hook to log all queries:

import "github.com/uptrace/bun/extra/bundebug"

cfg.QueryHooks = []bun.QueryHook{
    bundebug.NewQueryHook(bundebug.WithVerbose(true)),
}

Or implement bun.QueryHook for a custom logger:

type myHook struct{}

func (h *myHook) BeforeQuery(ctx context.Context, e *bun.QueryEvent) context.Context {
    return ctx
}

func (h *myHook) AfterQuery(ctx context.Context, e *bun.QueryEvent) {
    log.Info("query",
        rocklog.Str("query", e.Query),
        rocklog.Dur("duration", time.Since(e.StartTime)),
        rocklog.Err(e.Err),
    )
}

cfg.QueryHooks = []bun.QueryHook{&myHook{}}

Schema Migrations

bun's migration system works directly on *bun.DB:

db := svc.DB()
migrator := migrate.NewMigrator(db, migrations.Migrations)
if err := migrator.Init(ctx); err != nil {
    log.Fatal(err)
}
if err := migrator.Migrate(ctx); err != nil {
    log.Fatal(err)
}

See the bun migrations guide for details.

Limitations

  • Init closes the pool again if Ping fails (DB() stays nil); calling Init again replaces and closes the previous pool. After Stop, queries return sql: database is closed.
  • User, password and database from individual fields are URL-escaped, so passwords with @, :, / or # work. A hand-written DSN must be escaped by you.
  • SSLMode defaults to disable. In pgdriver prefer / require encrypt but do not verify the server certificate (and prefer does not fall back to plaintext). Use verify-full for real protection.
  • PostgreSQL only (via pgdriver). For MySQL or SQLite, use bun.NewDB directly with the appropriate driver and pass the *bun.DB through a custom wrapper.
  • QueryHooks are applied at construction time; they cannot be added or removed after NewService.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Configs

type Configs struct {
	// DSN takes priority over individual fields when non-empty.
	// Format: "postgres://user:pass@host:port/db?sslmode=disable"
	DSN string `config:",omitempty"`

	// Individual connection fields — used when DSN is empty.
	Host     string `config:",omitempty"` // default "localhost"
	Port     int    `config:",omitempty"` // default 5432
	User     string `config:",omitempty"`
	Password string `config:",omitempty"`
	Database string `config:",omitempty"`
	SSLMode  string `config:",omitempty"` // default "disable"

	// Connection pool settings.
	MaxOpenConns    int           `config:",omitempty"` // default 25
	MaxIdleConns    int           `config:",omitempty"` // default 5
	ConnMaxLifetime time.Duration `config:",omitempty"` // default 1h
	ConnMaxIdleTime time.Duration `config:",omitempty"` // default 30m

	// QueryHooks are registered on the bun.DB instance.
	// Use them to add query logging, tracing, or metrics.
	// Must be set in code — function types are not loadable from file.
	QueryHooks []bun.QueryHook `config:"-"`
}

Configs holds configuration for a bun DB connection (PostgreSQL via pgdriver).

Compatible with rockconfig.InitFromFile. If DSN is set it takes priority; otherwise the connection string is built from the individual Host/Port/User/Password/Database/SSLMode fields.

Example config.yaml:

dsn: "postgres://user:pass@localhost:5432/mydb?sslmode=disable"

— or individual fields —

host: "localhost"
port: 5432
user: "myuser"
password: "secret"
database: "mydb"
ssl_mode: "disable"
max_open_conns: 25
max_idle_conns: 5
conn_max_lifetime: "1h"
conn_max_idle_time: "30m"

type Service

type Service interface {
	// Init opens the connection pool and verifies connectivity via Ping.
	Init(ctx context.Context) error

	// Stop closes the connection pool.
	Stop() error

	// DB returns the underlying *bun.DB for building queries.
	// Must not be called before Init.
	DB() *bun.DB

	// Ping verifies the database connection is alive.
	Ping(ctx context.Context) error

	// RunInTx runs fn inside a database transaction.
	// The transaction is committed if fn returns nil, rolled back otherwise.
	// Pass nil opts to use the database default isolation level.
	RunInTx(ctx context.Context, opts *sql.TxOptions, fn func(ctx context.Context, tx bun.Tx) error) error
}

Service wraps a bun.DB and provides lifecycle management.

Call order: Init → use → Stop.

Use DB() to access the full bun query builder for selects, inserts, updates, deletes, and schema migrations. Use RunInTx for transactional work.

func NewService

func NewService(cfg Configs) Service

NewService creates a Service that is ready to be initialised. No connection is opened — call Init to establish the connection pool.

Example
package main

import (
	"context"
	"database/sql"
	"log"

	"github.com/arzab/gorock-kit/rockbun"
	"github.com/uptrace/bun"
)

func main() {
	svc := rockbun.NewService(rockbun.Configs{
		Host: "localhost", User: "app", Password: "p@ss:w/rd", Database: "app", SSLMode: "verify-full",
	})

	ctx := context.Background()
	if err := svc.Init(ctx); err != nil { // opens the pool and pings
		log.Fatal(err)
	}
	defer func() { _ = svc.Stop() }()

	var n int
	if err := svc.DB().NewSelect().ColumnExpr("1").Scan(ctx, &n); err != nil {
		log.Fatal(err)
	}
	err := svc.RunInTx(ctx, &sql.TxOptions{}, func(ctx context.Context, tx bun.Tx) error {
		_, err := tx.NewRaw("SELECT 1").Exec(ctx)
		return err
	})
	if err != nil {
		log.Fatal(err)
	}
}

Jump to

Keyboard shortcuts

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