~netlandish/gobwebs

d52fe0b89b490d0d3703f4da9f84a971070f55a1 — Peter Sanchez 1 year, 9 months ago fd293b1
Adding initial DBI class
1 files changed, 82 insertions(+), 0 deletions(-)

A database/db.go
A database/db.go => database/db.go +82 -0
@@ 0,0 1,82 @@
package database

import (
	"context"
	"database/sql"
	"errors"
)

// DBI is an interface to provide database access
type DBI interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
	CommitTx() error
	RollbackTx() error
	WillCommit() bool
	EnableCommit() bool
	DisableCommit() bool
	GetDB() *sql.DB
}

// DB database wrapper that meets DBI interface signature
type DB struct {
	db     *sql.DB
	tx     *sql.Tx
	commit bool
}

// BeginTx begins a db transaction
func (d *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
	if d.db == nil {
		return nil, errors.New("You must first set the *sql.DB value")
	}
	if d.tx != nil {
		return d.tx, nil
	}
	return d.db.BeginTx(ctx, opts)
}

// CommitTx commits active transaction
func (d *DB) CommitTx() error {
	if d.tx == nil {
		return errors.New("You have no active db transaction")
	}
	if d.commit {
		return d.tx.Commit()
	}
	return nil
}

// RollbackTx rollsback active transaction
func (d *DB) RollbackTx() error {
	if d.tx == nil {
		return errors.New("You have no active db transaction")
	}
	return d.tx.Rollback()
}

// WillCommit will return the value of commit
func (d *DB) WillCommit() bool {
	return d.commit
}

// EnableCommit enables the commit flag
func (d *DB) EnableCommit() bool {
	d.commit = true
	return d.commit
}

// DisableCommit enables the commit flag
func (d *DB) DisableCommit() bool {
	d.commit = false
	return d.commit
}

// GetDB returns the *sql.DB instance
func (d *DB) GetDB() *sql.DB {
	return d.db
}

// NewDB returns a new DB struct
func NewDB(sdb *sql.DB) *DB {
	return &DB{db: sdb}
}