Transaction runs the given function in a postgres transaction. If fn returns an error the txn will be rolled back.
(f func(DB) error)
| 335 | // Transaction runs the given function in a postgres transaction. If fn returns |
| 336 | // an error the txn will be rolled back. |
| 337 | func (d DB) Transaction(f func(DB) error) error { |
| 338 | if _, ok := d.dbProxy.(*sql.Tx); ok { |
| 339 | // Already in a nested transaction |
| 340 | return f(d) |
| 341 | } |
| 342 | |
| 343 | tx, err := d.dbProxy.(*sql.DB).Begin() |
| 344 | if err != nil { |
| 345 | return err |
| 346 | } |
| 347 | err = f(DB{ |
| 348 | dbProxy: tx, |
| 349 | StatementBuilderType: statementBuilder(tx), |
| 350 | }) |
| 351 | if err != nil { |
| 352 | // Rollback error is ignored as we already have one in progress |
| 353 | if err2 := tx.Rollback(); err2 != nil { |
| 354 | level.Warn(util_log.Logger).Log("msg", "transaction rollback error (ignored)", "err", err2) |
| 355 | } |
| 356 | return err |
| 357 | } |
| 358 | return tx.Commit() |
| 359 | } |
| 360 | |
| 361 | // Close finishes using the db |
| 362 | func (d DB) Close() error { |