Adds new getter to DB for getting a transactions context

This commit is contained in:
Chris Townsend 2022-05-02 20:33:19 +01:00
parent b0104943ed
commit 044fd12f15
2 changed files with 23 additions and 0 deletions

View File

@ -298,6 +298,11 @@ func (db *DB) WithContext(ctx context.Context) *DB {
return db.Session(&Session{Context: ctx})
}
// Context returns the db.Statement.Context
func (db *DB) Context() context.Context {
return db.Statement.Context
}
// Debug start debug mode
func (db *DB) Debug() (tx *DB) {
return db.Session(&Session{

View File

@ -78,6 +78,24 @@ func TestCancelTransaction(t *testing.T) {
}
}
func TestGetContextTransaction(t *testing.T) {
type ctxValue string
passThrough := ctxValue("passThrough")
ctx := context.Background()
ctx = context.WithValue(ctx, passThrough, "passed")
user := *GetUser("get_context", Config{})
DB.Create(&user)
_ = DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
p := tx.Context().Value(passThrough).(string)
if p != "passed" {
t.Fatalf("Transaction did not contain the passThrough context value from context() function")
}
return nil
})
}
func TestTransactionWithBlock(t *testing.T) {
assertPanic := func(f func()) {
defer func() {