remove global context cache

This commit is contained in:
Lunny Xiao 2018-09-18 15:15:09 +08:00
parent b0fd84832d
commit dc08f27b23
No known key found for this signature in database
GPG Key ID: C3B7C91B632F738A
6 changed files with 87 additions and 60 deletions

View File

@ -34,6 +34,8 @@ Xorm is a simple and powerful ORM for Go.
* Postgres schema support * Postgres schema support
* Context Get Cache
## Drivers Support ## Drivers Support
Drivers for Go's sql package which currently support database/sql includes: Drivers for Go's sql package which currently support database/sql includes:
@ -358,6 +360,33 @@ if _, err := session.Exec("delete from userinfo where username = ?", user2.Usern
return session.Commit() return session.Commit()
``` ```
* Context Cache, if enabled, current query result will be cached on session and be used by next same statement on the same session.
```Go
sess := engine.NewSession()
defer sess.Close()
var c2 ContextGetStruct
has, err := sess.ID(1).ContextCache().Get(&c2)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 1, c2.Id)
assert.EqualValues(t, "1", c2.Name)
sql, args := sess.LastSQL()
assert.True(t, len(sql) > 0)
assert.True(t, len(args) > 0)
var c3 ContextGetStruct
has, err = sess.ID(1).Get(&c3)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 1, c3.Id)
assert.EqualValues(t, "1", c3.Name)
sql, args = sess.LastSQL()
assert.True(t, len(sql) == 0)
assert.True(t, len(args) == 0)
```
## Contributing ## Contributing
If you want to pull request, please see [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md). And we also provide [Xorm on Google Groups](https://groups.google.com/forum/#!forum/xorm) to discuss. If you want to pull request, please see [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md). And we also provide [Xorm on Google Groups](https://groups.google.com/forum/#!forum/xorm) to discuss.

View File

@ -24,14 +24,3 @@ func (session *Session) PingContext(ctx context.Context) error {
session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName()) session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName())
return session.DB().PingContext(ctx) return session.DB().PingContext(ctx)
} }
// WithContext cooperate with ctx
func (session *Session) WithContext(ctx context.Context) *Session {
session.context = ctx
return session
}
// WithContext cooperate session with ctx
func WithContext(sess *Session, ctx context.Context) *Session {
return sess.WithContext(ctx)
}

View File

@ -84,11 +84,7 @@ func (session *Session) Init() {
session.lastSQL = "" session.lastSQL = ""
session.lastSQLArgs = []interface{}{} session.lastSQLArgs = []interface{}{}
if session.engine.enableContextCache { session.context = nil
session.context = context.Background()
} else {
session.context = nil
}
} }
// Close release the connection from pool // Close release the connection from pool
@ -109,6 +105,16 @@ func (session *Session) Close() {
} }
} }
// ContextCache enable context cache or not
func (session *Session) ContextCache(enabled ...bool) *Session {
if len(enabled) > 0 {
session.statement.enableContextCache = enabled[0]
} else {
session.statement.enableContextCache = true
}
return session
}
// IsClosed returns if session is closed // IsClosed returns if session is closed
func (session *Session) IsClosed() bool { func (session *Session) IsClosed() bool {
return session.db == nil return session.db == nil

View File

@ -83,7 +83,10 @@ func (session *Session) get(bean interface{}) (bool, error) {
if err != nil || !has { if err != nil || !has {
return has, err return has, err
} }
if session.context != nil { if session.statement.enableContextCache {
if session.context == nil {
session.context = context.Background()
}
session.context = context.WithValue(session.context, fmt.Sprintf("%v-%v", sqlStr, args), bean) session.context = context.WithValue(session.context, fmt.Sprintf("%v-%v", sqlStr, args), bean)
} }

View File

@ -5,7 +5,6 @@
package xorm package xorm
import ( import (
"context"
"database/sql" "database/sql"
"fmt" "fmt"
"testing" "testing"
@ -333,11 +332,11 @@ func TestContextGet(t *testing.T) {
_, err := testEngine.Insert(&ContextGetStruct{Name: "1"}) _, err := testEngine.Insert(&ContextGetStruct{Name: "1"})
assert.NoError(t, err) assert.NoError(t, err)
sess := WithContext(testEngine.NewSession(), context.Background()) sess := testEngine.NewSession()
defer sess.Close() defer sess.Close()
var c2 ContextGetStruct var c2 ContextGetStruct
has, err := sess.ID(1).Get(&c2) has, err := sess.ID(1).ContextCache().Get(&c2)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.EqualValues(t, 1, c2.Id) assert.EqualValues(t, 1, c2.Id)

View File

@ -19,46 +19,47 @@ import (
// Statement save all the sql info for executing SQL // Statement save all the sql info for executing SQL
type Statement struct { type Statement struct {
RefTable *core.Table RefTable *core.Table
Engine *Engine Engine *Engine
Start int Start int
LimitN int LimitN int
idParam *core.PK idParam *core.PK
OrderStr string OrderStr string
JoinStr string JoinStr string
joinArgs []interface{} joinArgs []interface{}
GroupByStr string GroupByStr string
HavingStr string HavingStr string
ColumnStr string ColumnStr string
selectStr string selectStr string
useAllCols bool useAllCols bool
OmitStr string OmitStr string
AltTableName string AltTableName string
tableName string tableName string
RawSQL string RawSQL string
RawParams []interface{} RawParams []interface{}
UseCascade bool UseCascade bool
UseAutoJoin bool UseAutoJoin bool
StoreEngine string StoreEngine string
Charset string Charset string
UseCache bool UseCache bool
UseAutoTime bool UseAutoTime bool
noAutoCondition bool noAutoCondition bool
IsDistinct bool IsDistinct bool
IsForUpdate bool IsForUpdate bool
TableAlias string TableAlias string
allUseBool bool allUseBool bool
checkVersion bool checkVersion bool
unscoped bool unscoped bool
columnMap columnMap columnMap columnMap
omitColumnMap columnMap omitColumnMap columnMap
mustColumnMap map[string]bool mustColumnMap map[string]bool
nullableMap map[string]bool nullableMap map[string]bool
incrColumns map[string]incrParam incrColumns map[string]incrParam
decrColumns map[string]decrParam decrColumns map[string]decrParam
exprColumns map[string]exprParam exprColumns map[string]exprParam
cond builder.Cond cond builder.Cond
bufferSize int bufferSize int
enableContextCache bool
} }
// Init reset all the statement's fields // Init reset all the statement's fields