Skip to content

Commit 1b2db62

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

File tree

1 file changed

+33
-23
lines changed

1 file changed

+33
-23
lines changed

gorm.go

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -187,15 +187,14 @@ 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 := &PreparedStmtDB{
192+
ConnPool: db.ConnPool,
193+
Stmts: make(map[string]*Stmt),
194+
Mux: &sync.RWMutex{},
195+
PreparedSQL: make([]string, 0, 100),
196+
}
197+
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
199198
db.ConnPool = preparedStmt
200199
}
201200

@@ -256,24 +255,35 @@ func (db *DB) Session(config *Session) *DB {
256255
}
257256

258257
if config.PrepareStmt {
258+
var preparedStmt *PreparedStmtDB
259+
259260
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-
}
261+
preparedStmt = v.(*PreparedStmtDB)
262+
} else {
263+
preparedStmt = &PreparedStmtDB{
264+
ConnPool: db.ConnPool,
265+
Stmts: make(map[string]*Stmt),
266+
Mux: &sync.RWMutex{},
267+
PreparedSQL: make([]string, 0, 100),
268+
}
269+
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
270+
}
271+
272+
switch t := tx.Statement.ConnPool.(type) {
273+
case Tx:
274+
tx.Statement.ConnPool = &PreparedStmtTX{
275+
Tx: t,
276+
PreparedStmtDB: preparedStmt,
277+
}
278+
default:
279+
tx.Statement.ConnPool = &PreparedStmtDB{
280+
ConnPool: db.Config.ConnPool,
281+
Mux: preparedStmt.Mux,
282+
Stmts: preparedStmt.Stmts,
273283
}
274-
txConfig.ConnPool = tx.Statement.ConnPool
275-
txConfig.PrepareStmt = true
276284
}
285+
txConfig.ConnPool = tx.Statement.ConnPool
286+
txConfig.PrepareStmt = true
277287
}
278288

279289
if config.SkipHooks {

0 commit comments

Comments
 (0)