dbresolver

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package dbresolver provides an explicit read/write split over Bun: writes go to the primary, reads are spread round-robin across replicas. Routing is explicit (Reader/Writer) because Bun query hooks are observational and cannot redirect a query's connection.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Resolver

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

Resolver routes database access to a primary and read replicas.

Example

Send writes to the primary and reads to replicas (round-robin).

package main

import (
	"database/sql"
	"fmt"

	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/sqlitedialect"
	"github.com/uptrace/bun/driver/sqliteshim"

	"github.com/rahmadafandi/fibr/dbresolver"
)

func open(name string) *bun.DB {
	sqldb, _ := sql.Open(sqliteshim.ShimName, "file:"+name+"?mode=memory&cache=shared")
	return bun.NewDB(sqldb, sqlitedialect.New())
}

// Send writes to the primary and reads to replicas (round-robin).
func main() {
	r := dbresolver.New(open("primary"), open("replica1"), open("replica2"))
	defer r.Close()

	// Writes: r.Writer().NewInsert()...  Reads: r.Reader().NewSelect()...
	fmt.Println(r.Writer() != nil, r.Reader() != nil)
}
Output:
true true

func New

func New(primary *bun.DB, replicas ...*bun.DB) *Resolver

New returns a Resolver. Writes use primary; reads round-robin across replicas (falling back to primary when none are given).

func (*Resolver) Close

func (r *Resolver) Close() error

Close closes the primary and every replica, returning the joined errors.

func (*Resolver) Ping

func (r *Resolver) Ping(ctx context.Context) error

Ping pings the primary and every replica, returning the joined errors.

func (*Resolver) Reader

func (r *Resolver) Reader() *bun.DB

Reader returns the next replica (round-robin), or the primary when no replicas are configured.

func (*Resolver) Writer

func (r *Resolver) Writer() *bun.DB

Writer returns the primary database, for writes and read-after-write reads.

Jump to

Keyboard shortcuts

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