From f87bfe8c31b7a44fc5fcfae7cc847ab4ed5b21e4 Mon Sep 17 00:00:00 2001 From: a631807682 <631807682@qq.com> Date: Sat, 13 Aug 2022 10:43:37 +0800 Subject: [PATCH] fix: double check prepare --- prepare_stmt.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/prepare_stmt.go b/prepare_stmt.go index 360b06a8..456204b8 100644 --- a/prepare_stmt.go +++ b/prepare_stmt.go @@ -58,8 +58,20 @@ func (db *PreparedStmtDB) prepare(ctx context.Context, conn ConnPool, isTransact } db.Mux.RUnlock() - // cache preparing stmt first db.Mux.Lock() + // double check + if stmt, ok := db.Stmts[query]; ok && (!stmt.Transaction || isTransaction) { + db.Mux.Unlock() + // wait for other goroutines prepared + <-stmt.prepared + if stmt.prepareErr != nil { + return Stmt{}, stmt.prepareErr + } + + return *stmt, nil + } + + // cache preparing stmt first cacheStmt := Stmt{Transaction: isTransaction, prepared: make(chan struct{})} db.Stmts[query] = &cacheStmt db.Mux.Unlock()