@@ 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}
+}