Support get dataSourceName on ContextHook for monitor which DB executed SQL (#1740)

Merge branch 'log_context_add_db_info'

add session to context

Revert "accept lunny's suggestion"

This reverts commit 57fd669942.

Merge branch 'master' of https://gitea.com/Thomas_An/thomasan_xorm

accept lunny's suggestion

Merge branch 'master' into master

add test code

session add Engine func

Used to monitor which DB executed this SQL

Co-authored-by: yong.an <yong.an@shopee.com>
Reviewed-on: https://gitea.com/xorm/xorm/pulls/1740
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
Thomas_An 2020-07-13 13:29:38 +00:00 committed by Lunny Xiao
parent 946fb57e1c
commit 0fae64bb3b
4 changed files with 20 additions and 2 deletions

View File

@ -54,3 +54,11 @@ func TestMustLogSQL(t *testing.T) {
_, err := testEngine.Table("userinfo").MustLogSQL(true).Get(new(Userinfo)) _, err := testEngine.Table("userinfo").MustLogSQL(true).Get(new(Userinfo))
assert.NoError(t, err) assert.NoError(t, err)
} }
func TestEnableSessionId(t *testing.T) {
assert.NoError(t, PrepareEngine())
testEngine.EnableSessionID(true)
assertSync(t, new(Userinfo))
_, err := testEngine.Table("userinfo").MustLogSQL(true).Get(new(Userinfo))
assert.NoError(t, err)
}

View File

@ -120,6 +120,7 @@ type EngineInterface interface {
TableInfo(bean interface{}) (*schemas.Table, error) TableInfo(bean interface{}) (*schemas.Table, error)
TableName(interface{}, ...bool) string TableName(interface{}, ...bool) string
UnMapType(reflect.Type) UnMapType(reflect.Type)
EnableSessionID(bool)
} }
var ( var (

View File

@ -42,6 +42,7 @@ var (
// enumerate all the context keys // enumerate all the context keys
var ( var (
SessionIDKey = "__xorm_session_id" SessionIDKey = "__xorm_session_id"
SessionKey = "__xorm_session_key"
SessionShowSQLKey = "__xorm_show_sql" SessionShowSQLKey = "__xorm_show_sql"
) )

View File

@ -107,7 +107,7 @@ func newSession(engine *Engine) *Session {
ctx = engine.defaultContext ctx = engine.defaultContext
} }
return &Session{ session := &Session{
ctx: ctx, ctx: ctx,
engine: engine, engine: engine,
tx: nil, tx: nil,
@ -136,6 +136,10 @@ func newSession(engine *Engine) *Session {
sessionType: engineSession, sessionType: engineSession,
} }
if engine.logSessionID {
session.ctx = context.WithValue(session.ctx, log.SessionKey, session)
}
return session
} }
// Close release the connection from pool // Close release the connection from pool
@ -165,6 +169,10 @@ func (session *Session) db() *core.DB {
return session.engine.db return session.engine.db
} }
func (session *Session) Engine() *Engine {
return session.engine
}
func (session *Session) getQueryer() core.Queryer { func (session *Session) getQueryer() core.Queryer {
if session.tx != nil { if session.tx != nil {
return session.tx return session.tx