Skip to content

Commit

Permalink
Add stmt cache for transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Petrunin committed Jan 28, 2015
1 parent 599acb0 commit be2e4da
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions stmtcacher.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,61 @@ func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner {
func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) {
return sp.db.Begin()
}

// DBTransactionProxy wraps transaction and includes DBProxy interface
type DBTransactionProxy interface {
DBProxy
Begin() error
Commit() error
Rollback() error
}

type stmtCacheTransactionProxy struct {
DBProxy
db *sql.DB
transaction *sql.Tx
}

// NewStmtCacheTransactionProxy returns a DBTransactionProxy
// wrapping an open transaction in stmtCacher.
// You should use Begin() each time you want a new transaction and
// cache will be valid only for that transaction.
//
// Usage example:
// proxy := sq.NewStmtCacheTransactionProxy(db)
// mydb := sq.StatementBuilder.RunWith(proxy)
// insertUsers := mydb.Insert("users").Columns("name")
// insertUsers.Values("username1").Exec()
// insertUsers.Values("username2").Exec()
// proxy.Commit()
//
// proxy.Begin()
// insertPets := mydb.Insert("pets").Columns("name", "username")
// insertPets.Values("petname1", "username1").Exec()
// insertPets.Values("petname2", "username1").Exec()
// proxy.Commit()
func NewStmtCacheTransactionProxy(db *sql.DB) (proxy DBTransactionProxy, err error) {
proxy = &stmtCacheTransactionProxy{db: db}
return proxy, proxy.Begin()
}

func (sp *stmtCacheTransactionProxy) Begin() (err error) {
tr, err := sp.db.Begin()

if err != nil {
return
}

sp.DBProxy = NewStmtCacher(tr)
sp.transaction = tr

return
}

func (sp *stmtCacheTransactionProxy) Commit() error {
return sp.transaction.Commit()
}

func (sp *stmtCacheTransactionProxy) Rollback() error {
return sp.transaction.Rollback()
}

0 comments on commit be2e4da

Please sign in to comment.