Reuse opened session in the context (#44939)

This commit is contained in:
Yuriy Tseretyan
2022-02-08 09:02:23 -05:00
committed by GitHub
parent 67a3e1d6fd
commit 6a7a486c6f
3 changed files with 96 additions and 15 deletions
+19 -10
View File
@@ -5,11 +5,16 @@ import (
"reflect"
"xorm.io/xorm"
"github.com/grafana/grafana/pkg/infra/log"
)
var sessionLogger = log.New("sqlstore.session")
type DBSession struct {
*xorm.Session
events []interface{}
transactionOpen bool
events []interface{}
}
type DBTransactionFunc func(sess *DBSession) error
@@ -32,26 +37,27 @@ func newSession(ctx context.Context) *DBSession {
return sess
}
func startSession(ctx context.Context, engine *xorm.Engine, beginTran bool) (*DBSession, error) {
func startSessionOrUseExisting(ctx context.Context, engine *xorm.Engine, beginTran bool) (*DBSession, bool, error) {
value := ctx.Value(ContextSessionKey{})
var sess *DBSession
sess, ok := value.(*DBSession)
if ok {
sessionLogger.Debug("reusing existing session", "transaction", sess.transactionOpen)
sess.Session = sess.Session.Context(ctx)
return sess, nil
return sess, false, nil
}
newSess := &DBSession{Session: engine.NewSession()}
newSess := &DBSession{Session: engine.NewSession(), transactionOpen: beginTran}
if beginTran {
err := newSess.Begin()
if err != nil {
return nil, err
return nil, false, err
}
}
newSess.Session = newSess.Session.Context(ctx)
return newSess, nil
return newSess, true, nil
}
// WithDbSession calls the callback with a session.
@@ -60,10 +66,13 @@ func (ss *SQLStore) WithDbSession(ctx context.Context, callback DBTransactionFun
}
func withDbSession(ctx context.Context, engine *xorm.Engine, callback DBTransactionFunc) error {
sess := &DBSession{Session: engine.NewSession()}
sess.Session = sess.Session.Context(ctx)
defer sess.Close()
sess, isNew, err := startSessionOrUseExisting(ctx, engine, false)
if err != nil {
return err
}
if isNew {
defer sess.Close()
}
return callback(sess)
}