支持lru缓存

This commit is contained in:
xiezhaodong 2025-04-14 20:27:45 +08:00
parent ecac72ad8b
commit bc26d3bda6

View File

@ -101,29 +101,33 @@ func (sdb *PreparedStmtDB) Reset() {
func (db *PreparedStmtDB) prepare(ctx context.Context, conn ConnPool, isTransaction bool, query string) (Stmt, error) { func (db *PreparedStmtDB) prepare(ctx context.Context, conn ConnPool, isTransaction bool, query string) (Stmt, error) {
db.Mux.RLock() db.Mux.RLock()
if stmt, ok := db.Stmts.Get(query); ok && (!stmt.Transaction || isTransaction) { if db.Stmts != nil {
db.Mux.RUnlock() if stmt, ok := db.Stmts.Get(query); ok && (!stmt.Transaction || isTransaction) {
// wait for other goroutines prepared db.Mux.RUnlock()
<-stmt.prepared // wait for other goroutines prepared
if stmt.prepareErr != nil { <-stmt.prepared
return Stmt{}, stmt.prepareErr if stmt.prepareErr != nil {
} return Stmt{}, stmt.prepareErr
}
return *stmt, nil return *stmt, nil
}
} }
db.Mux.RUnlock() db.Mux.RUnlock()
db.Mux.Lock() db.Mux.Lock()
// double check if db.Stmts != nil {
if stmt, ok := db.Stmts.Get(query); ok && (!stmt.Transaction || isTransaction) { // double check
db.Mux.Unlock() if stmt, ok := db.Stmts.Get(query); ok && (!stmt.Transaction || isTransaction) {
// wait for other goroutines prepared db.Mux.Unlock()
<-stmt.prepared // wait for other goroutines prepared
if stmt.prepareErr != nil { <-stmt.prepared
return Stmt{}, stmt.prepareErr if stmt.prepareErr != nil {
} return Stmt{}, stmt.prepareErr
}
return *stmt, nil return *stmt, nil
}
} }
// check db.Stmts first to avoid Segmentation Fault(setting value to nil map) // check db.Stmts first to avoid Segmentation Fault(setting value to nil map)
// which cause by calling Close and executing SQL concurrently // which cause by calling Close and executing SQL concurrently