1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2025-08-02 16:35:19 +02:00

fix: use parent context for new transactions (#8464)

- Older code (154 places to be exact) that want to do transactions uses `TxContext`. If the context is not already in a transaction then it uses `DefaultContext` for the new transaction.
- Not reusing the context it was given leads to two problems: for tracing (forgejo/forgejo#6470) any SQL code that is executed inside this transaction is not shown in the trace. If the context is cancelled then the transaction is not cancelled and will always complete (given there's no SQL error).
- When this function was introduced it didn't take a parent context, hence the usage of `DefaultContext`. When `parentCtx` was introduced it was only used to avoid nested transactions and use the parent's transaction. I do not see any reasons why the parent context cannot be reused, it is reused in the newer transaction function `WithTx` without any known problems.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/8464
Reviewed-by: Otto <otto@codeberg.org>
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Gusted <postmaster@gusted.xyz>
Co-committed-by: Gusted <postmaster@gusted.xyz>
This commit is contained in:
Gusted 2025-07-10 14:07:18 +02:00 committed by Gusted
parent 3f1ed6dde4
commit 7cd313951a
2 changed files with 13 additions and 1 deletions

View file

@ -84,4 +84,16 @@ func TestTxContext(t *testing.T) {
return nil
}))
}
t.Run("Reuses parent context", func(t *testing.T) {
type unique struct{}
ctx := context.WithValue(db.DefaultContext, unique{}, "yes!")
assert.False(t, db.InTransaction(ctx))
require.NoError(t, db.WithTx(ctx, func(ctx context.Context) error {
assert.Equal(t, "yes!", ctx.Value(unique{}))
return nil
}))
})
}