Skip to content

fix: Fix nested transactions should function correctly #2470

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion coderd/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,17 @@ type sqlQuerier struct {

// InTx performs database operations inside a transaction.
func (q *sqlQuerier) InTx(function func(Store) error) error {
if q.sdb == nil {
if _, ok := q.db.(*sql.Tx); ok {
// If the current inner "db" is already a transaction, we just reuse it.
// We do not need to handle commit/rollback as the outer tx will handle
// that.
err := function(q)
if err != nil {
return xerrors.Errorf("execute transaction: %w", err)
}
return nil
}

transaction, err := q.sdb.Begin()
if err != nil {
return xerrors.Errorf("begin transaction: %w", err)
Expand Down
46 changes: 46 additions & 0 deletions coderd/database/db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//go:build linux

package database_test

import (
"context"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/require"

"github.com/coder/coder/coderd/database"
)

func TestNestedInTx(t *testing.T) {
t.Parallel()

uid := uuid.New()
sqlDB := testSQLDB(t)
err := database.MigrateUp(sqlDB)
require.NoError(t, err, "migrations")

db := database.New(sqlDB)
err = db.InTx(func(outer database.Store) error {
return outer.InTx(func(inner database.Store) error {
//nolint:gocritic
require.Equal(t, outer, inner, "should be same transaction")

_, err := inner.InsertUser(context.Background(), database.InsertUserParams{
ID: uid,
Email: "coder@coder.com",
Username: "coder",
HashedPassword: []byte{},
CreatedAt: database.Now(),
UpdatedAt: database.Now(),
RBACRoles: []string{},
})
return err
})
})
require.NoError(t, err, "outer tx: %w", err)

user, err := db.GetUserByID(context.Background(), uid)
require.NoError(t, err, "user exists")
require.Equal(t, uid, user.ID, "user id expected")
}