transactions: start sessions and transactions at the same place

this make it possible for handler to use `withSession` when
transactions is not nedded and `inTransactionCtx` if its needed
without knowing who owns the session/transaction
This commit is contained in:
bergquist
2018-06-15 20:52:57 +02:00
parent 09e71e00a3
commit da91b91b4b
3 changed files with 24 additions and 22 deletions
+14 -5
View File
@@ -22,21 +22,30 @@ func newSession() *DBSession {
return &DBSession{Session: x.NewSession()}
}
func startSession(ctx context.Context) *DBSession {
func startSession(ctx context.Context, engine *xorm.Engine, beginTran bool) (*DBSession, error) {
value := ctx.Value(ContextSessionName)
var sess *DBSession
sess, ok := value.(*DBSession)
if !ok {
newSess := newSession()
return newSess
newSess := &DBSession{Session: engine.NewSession()}
if beginTran {
err := newSess.Begin()
if err != nil {
return nil, err
}
}
return newSess, nil
}
return sess
return sess, nil
}
func withDbSession(ctx context.Context, callback dbTransactionFunc) error {
sess := startSession(ctx)
sess, err := startSession(ctx, x, false)
if err != nil {
return err
}
return callback(sess)
}