Skip to content

Commit 6c22346

Browse files
committed
refactor: remove unnecessary prepared statement allocation
1 parent 740f2be commit 6c22346

File tree

2 files changed

+32
-23
lines changed

2 files changed

+32
-23
lines changed

gorm.go

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -187,15 +187,9 @@ func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
187187
}
188188
}
189189

190-
preparedStmt := &PreparedStmtDB{
191-
ConnPool: db.ConnPool,
192-
Stmts: make(map[string]*Stmt),
193-
Mux: &sync.RWMutex{},
194-
PreparedSQL: make([]string, 0, 100),
195-
}
196-
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
197-
198190
if config.PrepareStmt {
191+
preparedStmt := NewPreparedStmtDB(db.ConnPool)
192+
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
199193
db.ConnPool = preparedStmt
200194
}
201195

@@ -256,24 +250,30 @@ func (db *DB) Session(config *Session) *DB {
256250
}
257251

258252
if config.PrepareStmt {
253+
var preparedStmt *PreparedStmtDB
254+
259255
if v, ok := db.cacheStore.Load(preparedStmtDBKey); ok {
260-
preparedStmt := v.(*PreparedStmtDB)
261-
switch t := tx.Statement.ConnPool.(type) {
262-
case Tx:
263-
tx.Statement.ConnPool = &PreparedStmtTX{
264-
Tx: t,
265-
PreparedStmtDB: preparedStmt,
266-
}
267-
default:
268-
tx.Statement.ConnPool = &PreparedStmtDB{
269-
ConnPool: db.Config.ConnPool,
270-
Mux: preparedStmt.Mux,
271-
Stmts: preparedStmt.Stmts,
272-
}
256+
preparedStmt = v.(*PreparedStmtDB)
257+
} else {
258+
preparedStmt = NewPreparedStmtDB(db.ConnPool)
259+
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
260+
}
261+
262+
switch t := tx.Statement.ConnPool.(type) {
263+
case Tx:
264+
tx.Statement.ConnPool = &PreparedStmtTX{
265+
Tx: t,
266+
PreparedStmtDB: preparedStmt,
267+
}
268+
default:
269+
tx.Statement.ConnPool = &PreparedStmtDB{
270+
ConnPool: db.Config.ConnPool,
271+
Mux: preparedStmt.Mux,
272+
Stmts: preparedStmt.Stmts,
273273
}
274-
txConfig.ConnPool = tx.Statement.ConnPool
275-
txConfig.PrepareStmt = true
276274
}
275+
txConfig.ConnPool = tx.Statement.ConnPool
276+
txConfig.PrepareStmt = true
277277
}
278278

279279
if config.SkipHooks {

prepare_stmt.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ type PreparedStmtDB struct {
2121
ConnPool
2222
}
2323

24+
func NewPreparedStmtDB(connPool ConnPool) *PreparedStmtDB {
25+
return &PreparedStmtDB{
26+
ConnPool: connPool,
27+
Stmts: make(map[string]*Stmt),
28+
Mux: &sync.RWMutex{},
29+
PreparedSQL: make([]string, 0, 100),
30+
}
31+
}
32+
2433
func (db *PreparedStmtDB) GetDBConn() (*sql.DB, error) {
2534
if dbConnector, ok := db.ConnPool.(GetDBConnector); ok && dbConnector != nil {
2635
return dbConnector.GetDBConn()

0 commit comments

Comments
 (0)