transactions.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package sqlstore
  2. import (
  3. "context"
  4. "time"
  5. "github.com/go-xorm/xorm"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/infra/log"
  8. sqlite3 "github.com/mattn/go-sqlite3"
  9. )
  10. // WithTransactionalDbSession calls the callback with an session within a transaction
  11. func (ss *SqlStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error {
  12. return inTransactionWithRetryCtx(ctx, ss.engine, callback, 0)
  13. }
  14. func (ss *SqlStore) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
  15. return ss.inTransactionWithRetry(ctx, fn, 0)
  16. }
  17. func (ss *SqlStore) inTransactionWithRetry(ctx context.Context, fn func(ctx context.Context) error, retry int) error {
  18. return inTransactionWithRetryCtx(ctx, ss.engine, func(sess *DBSession) error {
  19. withValue := context.WithValue(ctx, ContextSessionName, sess)
  20. return fn(withValue)
  21. }, retry)
  22. }
  23. func inTransactionWithRetry(callback dbTransactionFunc, retry int) error {
  24. return inTransactionWithRetryCtx(context.Background(), x, callback, retry)
  25. }
  26. func inTransactionWithRetryCtx(ctx context.Context, engine *xorm.Engine, callback dbTransactionFunc, retry int) error {
  27. sess, err := startSession(ctx, engine, true)
  28. if err != nil {
  29. return err
  30. }
  31. defer sess.Close()
  32. err = callback(sess)
  33. // special handling of database locked errors for sqlite, then we can retry 3 times
  34. if sqlError, ok := err.(sqlite3.Error); ok && retry < 5 {
  35. if sqlError.Code == sqlite3.ErrLocked {
  36. sess.Rollback()
  37. time.Sleep(time.Millisecond * time.Duration(10))
  38. sqlog.Info("Database table locked, sleeping then retrying", "retry", retry)
  39. return inTransactionWithRetry(callback, retry+1)
  40. }
  41. }
  42. if err != nil {
  43. sess.Rollback()
  44. return err
  45. } else if err = sess.Commit(); err != nil {
  46. return err
  47. }
  48. if len(sess.events) > 0 {
  49. for _, e := range sess.events {
  50. if err = bus.Publish(e); err != nil {
  51. log.Error(3, "Failed to publish event after commit. error: %v", err)
  52. }
  53. }
  54. }
  55. return nil
  56. }
  57. func inTransaction(callback dbTransactionFunc) error {
  58. return inTransactionWithRetry(callback, 0)
  59. }
  60. func inTransactionCtx(ctx context.Context, callback dbTransactionFunc) error {
  61. return inTransactionWithRetryCtx(ctx, x, callback, 0)
  62. }