Skip to content

Commit

Permalink
refactor: remove unnecessary prepared statement allocation (#6374)
Browse files Browse the repository at this point in the history
  • Loading branch information
lzakharov authored Jun 5, 2023
1 parent c1ea730 commit 7a76c04
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
46 changes: 23 additions & 23 deletions gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,15 +187,9 @@ func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
}
}

preparedStmt := &PreparedStmtDB{
ConnPool: db.ConnPool,
Stmts: make(map[string]*Stmt),
Mux: &sync.RWMutex{},
PreparedSQL: make([]string, 0, 100),
}
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)

if config.PrepareStmt {
preparedStmt := NewPreparedStmtDB(db.ConnPool)
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
db.ConnPool = preparedStmt
}

Expand Down Expand Up @@ -256,24 +250,30 @@ func (db *DB) Session(config *Session) *DB {
}

if config.PrepareStmt {
var preparedStmt *PreparedStmtDB

if v, ok := db.cacheStore.Load(preparedStmtDBKey); ok {
preparedStmt := v.(*PreparedStmtDB)
switch t := tx.Statement.ConnPool.(type) {
case Tx:
tx.Statement.ConnPool = &PreparedStmtTX{
Tx: t,
PreparedStmtDB: preparedStmt,
}
default:
tx.Statement.ConnPool = &PreparedStmtDB{
ConnPool: db.Config.ConnPool,
Mux: preparedStmt.Mux,
Stmts: preparedStmt.Stmts,
}
preparedStmt = v.(*PreparedStmtDB)
} else {
preparedStmt = NewPreparedStmtDB(db.ConnPool)
db.cacheStore.Store(preparedStmtDBKey, preparedStmt)
}

switch t := tx.Statement.ConnPool.(type) {
case Tx:
tx.Statement.ConnPool = &PreparedStmtTX{
Tx: t,
PreparedStmtDB: preparedStmt,
}
default:
tx.Statement.ConnPool = &PreparedStmtDB{
ConnPool: db.Config.ConnPool,
Mux: preparedStmt.Mux,
Stmts: preparedStmt.Stmts,
}
txConfig.ConnPool = tx.Statement.ConnPool
txConfig.PrepareStmt = true
}
txConfig.ConnPool = tx.Statement.ConnPool
txConfig.PrepareStmt = true
}

if config.SkipHooks {
Expand Down
9 changes: 9 additions & 0 deletions prepare_stmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ type PreparedStmtDB struct {
ConnPool
}

func NewPreparedStmtDB(connPool ConnPool) *PreparedStmtDB {
return &PreparedStmtDB{
ConnPool: connPool,
Stmts: make(map[string]*Stmt),
Mux: &sync.RWMutex{},
PreparedSQL: make([]string, 0, 100),
}
}

func (db *PreparedStmtDB) GetDBConn() (*sql.DB, error) {
if dbConnector, ok := db.ConnPool.(GetDBConnector); ok && dbConnector != nil {
return dbConnector.GetDBConn()
Expand Down

0 comments on commit 7a76c04

Please sign in to comment.