feat: ? set the default timeout for every session #1993

Closed
asppj wants to merge 1 commits from master into master
2 changed files with 20 additions and 1 deletions

View File

@ -46,6 +46,7 @@ type Engine struct {
DatabaseTZ *time.Location // The timezone of the database
logSessionID bool // create session id
timeoutSecond uint // if > 0 set default timeout for session
}
// NewEngine new a db manager according to the parameter. Currently support four
@ -273,6 +274,16 @@ func (engine *Engine) SetDefaultCacher(cacher caches.Cacher) {
engine.cacherMgr.SetDefaultCacher(cacher)
}
// SetSessionTimeout set the default timeout for every session
func (engine *Engine) SetSessionTimeout(timeout uint) {
engine.timeoutSecond = timeout
}
// GetDefaultTimeout return the default timeout of new session
func (engine *Engine) GetDefaultTimeout() uint {
return engine.timeoutSecond
}
// GetDefaultCacher returns the default cacher
func (engine *Engine) GetDefaultCacher() caches.Cacher {
return engine.cacherMgr.GetDefaultCacher()

View File

@ -85,6 +85,7 @@ type Session struct {
lastSQLArgs []interface{}
ctx context.Context
cancel context.CancelFunc
sessionType sessionType
}
@ -106,9 +107,13 @@ func newSession(engine *Engine) *Session {
} else {
ctx = engine.defaultContext
}
var cancel context.CancelFunc
if engine.timeoutSecond > 0 {
ctx, cancel = context.WithTimeout(ctx, time.Second*time.Duration(engine.timeoutSecond))
}
session := &Session{
ctx: ctx,
cancel: cancel,
engine: engine,
tx: nil,
statement: statements.NewStatement(
@ -144,6 +149,9 @@ func newSession(engine *Engine) *Session {
// Close release the connection from pool
func (session *Session) Close() error {
if session.cancel != nil{
session.cancel()
}
for _, v := range session.stmtCache {
if err := v.Close(); err != nil {
return err