Skip to content

Commit 1735906

Browse files
lunnyBetaCat0
authored andcommitted
Support local sql log (go-xorm#1338)
1 parent 0090e33 commit 1735906

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

engine.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ func (engine *Engine) Ping() error {
330330
return session.Ping()
331331
}
332332

333-
// logging sql
333+
// logSQL save sql
334334
func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) {
335335
if engine.showSQL && !engine.showExecTime {
336336
if len(sqlArgs) > 0 {

session.go

+23-1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ type Session struct {
5757
//beforeSQLExec func(string, ...interface{})
5858
lastSQL string
5959
lastSQLArgs []interface{}
60+
showSQL bool
6061

6162
ctx context.Context
6263
sessionType sessionType
@@ -72,6 +73,7 @@ func (session *Session) Clone() *Session {
7273
func (session *Session) Init() {
7374
session.statement.Init()
7475
session.statement.Engine = session.engine
76+
session.showSQL = session.engine.showSQL
7577
session.isAutoCommit = true
7678
session.isCommitedOrRollbacked = false
7779
session.isAutoClose = false
@@ -226,6 +228,16 @@ func (session *Session) Cascade(trueOrFalse ...bool) *Session {
226228
return session
227229
}
228230

231+
// MustLogSQL means record SQL or not and don't follow engine's setting
232+
func (session *Session) MustLogSQL(log ...bool) *Session {
233+
if len(log) > 0 {
234+
session.showSQL = log[0]
235+
} else {
236+
session.showSQL = true
237+
}
238+
return session
239+
}
240+
229241
// NoCache ask this session do not retrieve data from cache system and
230242
// get data from database directly.
231243
func (session *Session) NoCache() *Session {
@@ -842,7 +854,17 @@ func (session *Session) slice2Bean(scanResults []interface{}, fields []string, b
842854
func (session *Session) saveLastSQL(sql string, args ...interface{}) {
843855
session.lastSQL = sql
844856
session.lastSQLArgs = args
845-
session.engine.logSQL(sql, args...)
857+
session.logSQL(sql, args...)
858+
}
859+
860+
func (session *Session) logSQL(sqlStr string, sqlArgs ...interface{}) {
861+
if session.showSQL && !session.engine.showExecTime {
862+
if len(sqlArgs) > 0 {
863+
session.engine.logger.Infof("[SQL] %v %#v", sqlStr, sqlArgs)
864+
} else {
865+
session.engine.logger.Infof("[SQL] %v", sqlStr)
866+
}
867+
}
846868
}
847869

848870
// LastSQL returns last query information

session_raw.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ func (session *Session) queryRows(sqlStr string, args ...interface{}) (*core.Row
2727

2828
session.queryPreprocess(&sqlStr, args...)
2929

30-
if session.engine.showSQL {
30+
if session.showSQL {
31+
session.lastSQL = sqlStr
32+
session.lastSQLArgs = args
3133
if session.engine.showExecTime {
3234
b4ExecTime := time.Now()
3335
defer func() {

0 commit comments

Comments
 (0)