Skip to content

Commit

Permalink
fix: call query hook when tx is started, committed, or rolled back
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Nov 7, 2021
1 parent ce9957d commit 30e85b5
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 7 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ Projects using Bun:

</details>

## But why?
## Why another database client?

So you can write queries like this:
So you can elegantly write complex queries:

```go
regionalSales := db.NewSelect().
Expand Down
24 changes: 21 additions & 3 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ func (db *DB) PrepareContext(ctx context.Context, query string) (Stmt, error) {
//------------------------------------------------------------------------------

type Tx struct {
db *DB
ctx context.Context
db *DB
*sql.Tx
}

Expand All @@ -382,16 +383,33 @@ func (db *DB) Begin() (Tx, error) {
}

func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (Tx, error) {
ctx, event := db.beforeQuery(ctx, nil, "BEGIN", nil, nil)
tx, err := db.DB.BeginTx(ctx, opts)
db.afterQuery(ctx, event, nil, err)
if err != nil {
return Tx{}, err
}
return Tx{
db: db,
Tx: tx,
ctx: ctx,
db: db,
Tx: tx,
}, nil
}

func (tx Tx) Commit() error {
ctx, event := tx.db.beforeQuery(tx.ctx, nil, "COMMIT", nil, nil)
err := tx.Tx.Commit()
tx.db.afterQuery(ctx, event, nil, err)
return err
}

func (tx Tx) Rollback() error {
ctx, event := tx.db.beforeQuery(tx.ctx, nil, "ROLLBACK", nil, nil)
err := tx.Tx.Rollback()
tx.db.afterQuery(ctx, event, nil, err)
return err
}

func (tx Tx) Exec(query string, args ...interface{}) (sql.Result, error) {
return tx.ExecContext(context.TODO(), query, args...)
}
Expand Down
2 changes: 1 addition & 1 deletion extra/bundebug/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {

if !h.verbose {
switch event.Err {
case nil, sql.ErrNoRows:
case nil, sql.ErrNoRows, sql.ErrTxDone:
return
}
}
Expand Down
2 changes: 1 addition & 1 deletion extra/bunotel/otel.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {
}

switch event.Err {
case nil, sql.ErrNoRows:
case nil, sql.ErrNoRows, sql.ErrTxDone:
// ignore
default:
span.RecordError(event.Err)
Expand Down

0 comments on commit 30e85b5

Please sign in to comment.