From d52fe0b89b490d0d3703f4da9f84a971070f55a1 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Mon, 13 Feb 2023 17:24:15 -0600 Subject: [PATCH] Adding initial DBI class --- database/db.go | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 database/db.go diff --git a/database/db.go b/database/db.go new file mode 100644 index 0000000..6ba2efb --- /dev/null +++ b/database/db.go @@ -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} +} -- 2.45.2