Skip to content
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

fix: prepare deadlock #5568

Merged
merged 8 commits into from Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 9 additions & 14 deletions prepare_stmt.go
Expand Up @@ -50,23 +50,18 @@ func (db *PreparedStmtDB) prepare(ctx context.Context, conn ConnPool, isTransact
}
db.Mux.RUnlock()

db.Mux.Lock()
defer db.Mux.Unlock()

// double check
if stmt, ok := db.Stmts[query]; ok && (!stmt.Transaction || isTransaction) {
return stmt, nil
} else if ok {
go stmt.Close()
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
}

stmt, err := conn.PrepareContext(ctx, query)
a631807682 marked this conversation as resolved.
Show resolved Hide resolved
if err == nil {
db.Stmts[query] = Stmt{Stmt: stmt, Transaction: isTransaction}
db.PreparedSQL = append(db.PreparedSQL, query)
if err != nil {
return Stmt{}, err
}

return db.Stmts[query], err
cacheStmt := Stmt{Stmt: stmt, Transaction: isTransaction}
db.Mux.Lock()
db.Stmts[query] = cacheStmt
db.PreparedSQL = append(db.PreparedSQL, query)
db.Mux.Unlock()

return cacheStmt, nil
}

func (db *PreparedStmtDB) BeginTx(ctx context.Context, opt *sql.TxOptions) (ConnPool, error) {
Expand Down
25 changes: 25 additions & 0 deletions tests/prepared_stmt_test.go
Expand Up @@ -2,6 +2,7 @@ package tests_test

import (
"context"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -88,3 +89,27 @@ func TestPreparedStmtFromTransaction(t *testing.T) {
}
tx2.Commit()
}

func TestPreparedStmtDeadlock(t *testing.T) {
tx, err := OpenTestConnection()
AssertEqual(t, err, nil)

sqlDB, _ := tx.DB()
sqlDB.SetMaxOpenConns(1)

tx = tx.Session(&gorm.Session{PrepareStmt: true})

wg := sync.WaitGroup{}
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
user := User{Name: "jinzhu"}
tx.Create(&user)

var result User
tx.First(&result)
wg.Done()
}()
}
wg.Wait()
}