db

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2024 License: ISC Imports: 10 Imported by: 0

README

Golang Database Wrapper

Go Reference

go get github.com/nicolasparada/go-db

Simple Golang database wrapper over github.com/jackc/pgx/v5 with better transactions API. Specifically designed to work with CockroachDB.

Instead of starting a transaction, commiting (or rolling back) each time, you simply pass a callback function. This allows for defining methods over a single database object and you can either run them standalone or inside a transaction.

type Repo struct {
    db *db.DB
}

func (repo *Repo) Insert(ctx context.Context) error {
    repo.db.Exec(ctx, "INSERT INTO ...")
}

func (repo *Repo) Update(ctx context.Context) error {
    repo.db.Exec(ctx, "UPDATE ... SET ...")
}

func (repo *Repo) InsertAndUpdate(ctx context.Context) error {
    return repo.db.RunTx(ctx, func(ctx context.Context) error {
        repo.Insert(ctx)
        repo.Update(ctx)
    })
}

How it works?

When you call RunTx it starts a new transaction and saves that object inside context. Calls to Query, QueryRow and Exec will check on the context and will either use the new transaction object or take a connection directly from the pool.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsError

func IsError(err error, code string, cols ...string) bool

func IsForeignKeyViolationError

func IsForeignKeyViolationError(err error, cols ...string) bool

func IsNotFoundError added in v0.3.0

func IsNotFoundError(err error) bool

func IsNotNullViolationError

func IsNotNullViolationError(err error, cols ...string) bool

func IsUniqueViolationError

func IsUniqueViolationError(err error, cols ...string) bool

Types

type DB

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

func New

func New(pool *pgxpool.Pool) *DB

func (*DB) Exec

func (db *DB) Exec(ctx context.Context, query string, args ...any) (pgconn.CommandTag, error)

func (*DB) Query

func (db *DB) Query(ctx context.Context, query string, args ...any) (pgx.Rows, error)

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, query string, args ...any) pgx.Row

func (*DB) RunTx

func (db *DB) RunTx(ctx context.Context, fn func(ctx context.Context) error) (err error)

Jump to

Keyboard shortcuts

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