@@ -100,31 +100,36 @@ func TestContextSafety(t *testing.T) {
100100 assert .NoError (t , db .Insert (t .Context (), & TestModel2 {ID : int64 (- i )}))
101101 }
102102
103- actualCount := 0
104- // here: db.GetEngine(t.Context()) is a new *Session created from *Engine
105- _ = db .WithTx (t .Context (), func (ctx context.Context ) error {
106- _ = db .GetEngine (ctx ).Iterate (& TestModel1 {}, func (i int , bean any ) error {
107- // here: db.GetEngine(ctx) is always the unclosed "Iterate" *Session with autoResetStatement=false,
108- // and the internal states (including "cond" and others) are always there and not be reset in this callback.
109- m1 := bean .(* TestModel1 )
110- assert .EqualValues (t , i + 1 , m1 .ID )
111-
112- // here: XORM bug, it fails because the SQL becomes "WHERE id=-1", "WHERE id=-1 AND id=-2", "WHERE id=-1 AND id=-2 AND id=-3" ...
113- // and it conflicts with the "Iterate"'s internal states.
114- // has, err := db.GetEngine(ctx).Get(&TestModel2{ID: -m1.ID})
115-
116- actualCount ++
103+ t .Run ("Show-XORM-Bug" , func (t * testing.T ) {
104+ actualCount := 0
105+ // here: db.GetEngine(t.Context()) is a new *Session created from *Engine
106+ _ = db .WithTx (t .Context (), func (ctx context.Context ) error {
107+ _ = db .GetEngine (ctx ).Iterate (& TestModel1 {}, func (i int , bean any ) error {
108+ // here: db.GetEngine(ctx) is always the unclosed "Iterate" *Session with autoResetStatement=false,
109+ // and the internal states (including "cond" and others) are always there and not be reset in this callback.
110+ m1 := bean .(* TestModel1 )
111+ assert .EqualValues (t , i + 1 , m1 .ID )
112+
113+ // here: XORM bug, it fails because the SQL becomes "WHERE id=-1", "WHERE id=-1 AND id=-2", "WHERE id=-1 AND id=-2 AND id=-3" ...
114+ // and it conflicts with the "Iterate"'s internal states.
115+ // has, err := db.GetEngine(ctx).Get(&TestModel2{ID: -m1.ID})
116+
117+ actualCount ++
118+ return nil
119+ })
117120 return nil
118121 })
119- return nil
122+ assert . Equal ( t , testCount , actualCount )
120123 })
121- assert .Equal (t , testCount , actualCount )
122124
123- // deny the bad usages
124- assert .PanicsWithError (t , "using database context in an iterator would cause corrupted results" , func () {
125- _ = unittest .GetXORMEngine ().Iterate (& TestModel1 {}, func (i int , bean any ) error {
126- _ = db .GetEngine (t .Context ())
127- return nil
125+ t .Run ("DenyBadUsage" , func (t * testing.T ) {
126+ assert .PanicsWithError (t , "using session context in an iterator would cause corrupted results" , func () {
127+ _ = db .WithTx (t .Context (), func (ctx context.Context ) error {
128+ return db .GetEngine (ctx ).Iterate (& TestModel1 {}, func (i int , bean any ) error {
129+ _ = db .GetEngine (ctx )
130+ return nil
131+ })
132+ })
128133 })
129134 })
130135}
0 commit comments