Fix bug when invoking session in the after load (#2569)

Fix #2511

Reviewed-on: https://gitea.com/xorm/xorm/pulls/2569
This commit is contained in:
Lunny Xiao
2026-02-09 01:39:56 +00:00
parent a5e639c934
commit ab3ffa8fa5
2 changed files with 60 additions and 0 deletions
+1
View File
@@ -69,6 +69,7 @@ func (executor *executedProcessor) execute() error {
func (session *Session) executeProcessors() error {
processors := session.afterProcessors
session.afterProcessors = make([]executedProcessor, 0)
session.resetStatement()
for _, processor := range processors {
if err := processor.execute(); err != nil {
return err
+59
View File
@@ -7,6 +7,7 @@ package tests
import (
"errors"
"fmt"
"strings"
"testing"
"xorm.io/xorm"
@@ -121,6 +122,35 @@ type ProcessorsStruct struct {
AfterSetFlag int `xorm:"-"`
}
type AfterLoadSessionTable struct {
Id int64
Name string
LastSQL string `xorm:"-"`
}
func (AfterLoadSessionTable) TableName() string {
return "after_load_session_table"
}
func (t *AfterLoadSessionTable) AfterLoad(sess *xorm.Session) {
var target AfterLoadSessionTarget
if _, err := sess.Where("name = ?", "second").Get(&target); err != nil {
t.LastSQL = err.Error()
return
}
lastSQL, _ := sess.LastSQL()
t.LastSQL = lastSQL
}
type AfterLoadSessionTarget struct {
Id int64
Name string
}
func (AfterLoadSessionTarget) TableName() string {
return "after_load_session_table"
}
func (p *ProcessorsStruct) BeforeInsert() {
p.B4InsertFlag = 1
}
@@ -914,6 +944,35 @@ func TestAfterLoadProcessor(t *testing.T) {
}
}
func TestAfterLoadSessionProcessorResetsStatement(t *testing.T) {
assert.NoError(t, PrepareEngine())
assertSync(t, new(AfterLoadSessionTable))
first := AfterLoadSessionTable{Name: "first"}
_, err := testEngine.Insert(&first)
assert.NoError(t, err)
_, err = testEngine.Insert(&AfterLoadSessionTable{Name: "second"})
assert.NoError(t, err)
var loaded AfterLoadSessionTable
has, err := testEngine.ID(first.Id).Get(&loaded)
assert.NoError(t, err)
assert.True(t, has)
whereIndex := strings.Index(strings.ToLower(loaded.LastSQL), "where")
if whereIndex == -1 {
t.Fatalf("expected WHERE clause in SQL: %s", loaded.LastSQL)
}
whereClause := strings.ToLower(loaded.LastSQL[whereIndex:])
if orderIndex := strings.Index(whereClause, "order by"); orderIndex != -1 {
whereClause = whereClause[:orderIndex]
}
assert.Contains(t, whereClause, "name")
assert.NotContains(t, whereClause, "id")
}
type AfterInsertStruct struct {
Id int64
}