Chore: Deduplicate sqlstore transaction code (#17069)

* Deduplicate transaction code

* More deduplication
This commit is contained in:
Andrej Ocenas
2019-05-16 12:39:59 +02:00
committed by GitHub
parent 2904e2d9fe
commit 3dbc3251d1
3 changed files with 29 additions and 102 deletions

View File

@@ -4,63 +4,34 @@ import (
"context"
"time"
"github.com/go-xorm/xorm"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
sqlite3 "github.com/mattn/go-sqlite3"
)
// WithTransactionalDbSession calls the callback with an session within a transaction
func (ss *SqlStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error {
return inTransactionWithRetryCtx(ss.engine, ctx, callback, 0)
}
func (ss *SqlStore) InTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
return ss.inTransactionWithRetry(ctx, fn, 0)
}
func (ss *SqlStore) inTransactionWithRetry(ctx context.Context, fn func(ctx context.Context) error, retry int) error {
sess, err := startSession(ctx, ss.engine, true)
if err != nil {
return err
}
defer sess.Close()
withValue := context.WithValue(ctx, ContextSessionName, sess)
err = fn(withValue)
// special handling of database locked errors for sqlite, then we can retry 3 times
if sqlError, ok := err.(sqlite3.Error); ok && retry < 5 {
if sqlError.Code == sqlite3.ErrLocked {
sess.Rollback()
time.Sleep(time.Millisecond * time.Duration(10))
ss.log.Info("Database table locked, sleeping then retrying", "retry", retry)
return ss.inTransactionWithRetry(ctx, fn, retry+1)
}
}
if err != nil {
sess.Rollback()
return err
}
if err = sess.Commit(); err != nil {
return err
}
if len(sess.events) > 0 {
for _, e := range sess.events {
if err = bus.Publish(e); err != nil {
ss.log.Error("Failed to publish event after commit", err)
}
}
}
return nil
return inTransactionWithRetryCtx(ss.engine, ctx, func(sess *DBSession) error {
withValue := context.WithValue(ctx, ContextSessionName, sess)
return fn(withValue)
}, retry)
}
func inTransactionWithRetry(callback dbTransactionFunc, retry int) error {
return inTransactionWithRetryCtx(context.Background(), callback, retry)
return inTransactionWithRetryCtx(x, context.Background(), callback, retry)
}
func inTransactionWithRetryCtx(ctx context.Context, callback dbTransactionFunc, retry int) error {
sess, err := startSession(ctx, x, true)
func inTransactionWithRetryCtx(engine *xorm.Engine, ctx context.Context, callback dbTransactionFunc, retry int) error {
sess, err := startSession(ctx, engine, true)
if err != nil {
return err
}
@@ -102,5 +73,5 @@ func inTransaction(callback dbTransactionFunc) error {
}
func inTransactionCtx(ctx context.Context, callback dbTransactionFunc) error {
return inTransactionWithRetryCtx(ctx, callback, 0)
return inTransactionWithRetryCtx(x, ctx, callback, 0)
}