prepare_stmt.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package gorm
  2. import (
  3. "context"
  4. "database/sql"
  5. "database/sql/driver"
  6. "errors"
  7. "reflect"
  8. "sync"
  9. "time"
  10. "gorm.io/gorm/internal/stmt_store"
  11. )
  12. type PreparedStmtDB struct {
  13. Stmts stmt_store.Store
  14. Mux *sync.RWMutex
  15. ConnPool
  16. }
  17. // NewPreparedStmtDB creates and initializes a new instance of PreparedStmtDB.
  18. //
  19. // Parameters:
  20. // - connPool: A connection pool that implements the ConnPool interface, used for managing database connections.
  21. // - maxSize: The maximum number of prepared statements that can be stored in the statement store.
  22. // - ttl: The time-to-live duration for each prepared statement in the store. Statements older than this duration will be automatically removed.
  23. //
  24. // Returns:
  25. // - A pointer to a PreparedStmtDB instance, which manages prepared statements using the provided connection pool and configuration.
  26. func NewPreparedStmtDB(connPool ConnPool, maxSize int, ttl time.Duration) *PreparedStmtDB {
  27. return &PreparedStmtDB{
  28. ConnPool: connPool, // Assigns the provided connection pool to manage database connections.
  29. Stmts: stmt_store.New(maxSize, ttl), // Initializes a new statement store with the specified maximum size and TTL.
  30. Mux: &sync.RWMutex{}, // Sets up a read-write mutex for synchronizing access to the statement store.
  31. }
  32. }
  33. // GetDBConn returns the underlying *sql.DB connection
  34. func (db *PreparedStmtDB) GetDBConn() (*sql.DB, error) {
  35. if sqldb, ok := db.ConnPool.(*sql.DB); ok {
  36. return sqldb, nil
  37. }
  38. if dbConnector, ok := db.ConnPool.(GetDBConnector); ok && dbConnector != nil {
  39. return dbConnector.GetDBConn()
  40. }
  41. return nil, ErrInvalidDB
  42. }
  43. // Close closes all prepared statements in the store
  44. func (db *PreparedStmtDB) Close() {
  45. db.Mux.Lock()
  46. defer db.Mux.Unlock()
  47. for _, key := range db.Stmts.Keys() {
  48. db.Stmts.Delete(key)
  49. }
  50. }
  51. // Reset Deprecated use Close instead
  52. func (db *PreparedStmtDB) Reset() {
  53. db.Close()
  54. }
  55. func (db *PreparedStmtDB) prepare(ctx context.Context, conn ConnPool, isTransaction bool, query string) (_ *stmt_store.Stmt, err error) {
  56. db.Mux.RLock()
  57. if db.Stmts != nil {
  58. if stmt, ok := db.Stmts.Get(query); ok && (!stmt.Transaction || isTransaction) {
  59. db.Mux.RUnlock()
  60. return stmt, stmt.Error()
  61. }
  62. }
  63. db.Mux.RUnlock()
  64. // retry
  65. db.Mux.Lock()
  66. if db.Stmts != nil {
  67. if stmt, ok := db.Stmts.Get(query); ok && (!stmt.Transaction || isTransaction) {
  68. db.Mux.Unlock()
  69. return stmt, stmt.Error()
  70. }
  71. }
  72. return db.Stmts.New(ctx, query, isTransaction, conn, db.Mux)
  73. }
  74. func (db *PreparedStmtDB) BeginTx(ctx context.Context, opt *sql.TxOptions) (ConnPool, error) {
  75. if beginner, ok := db.ConnPool.(TxBeginner); ok {
  76. tx, err := beginner.BeginTx(ctx, opt)
  77. return &PreparedStmtTX{PreparedStmtDB: db, Tx: tx}, err
  78. }
  79. beginner, ok := db.ConnPool.(ConnPoolBeginner)
  80. if !ok {
  81. return nil, ErrInvalidTransaction
  82. }
  83. connPool, err := beginner.BeginTx(ctx, opt)
  84. if err != nil {
  85. return nil, err
  86. }
  87. if tx, ok := connPool.(Tx); ok {
  88. return &PreparedStmtTX{PreparedStmtDB: db, Tx: tx}, nil
  89. }
  90. return nil, ErrInvalidTransaction
  91. }
  92. func (db *PreparedStmtDB) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error) {
  93. stmt, err := db.prepare(ctx, db.ConnPool, false, query)
  94. if err == nil {
  95. result, err = stmt.ExecContext(ctx, args...)
  96. if errors.Is(err, driver.ErrBadConn) {
  97. db.Stmts.Delete(query)
  98. }
  99. }
  100. return result, err
  101. }
  102. func (db *PreparedStmtDB) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) {
  103. stmt, err := db.prepare(ctx, db.ConnPool, false, query)
  104. if err == nil {
  105. rows, err = stmt.QueryContext(ctx, args...)
  106. if errors.Is(err, driver.ErrBadConn) {
  107. db.Stmts.Delete(query)
  108. }
  109. }
  110. return rows, err
  111. }
  112. func (db *PreparedStmtDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
  113. stmt, err := db.prepare(ctx, db.ConnPool, false, query)
  114. if err == nil {
  115. return stmt.QueryRowContext(ctx, args...)
  116. }
  117. return &sql.Row{}
  118. }
  119. func (db *PreparedStmtDB) Ping() error {
  120. conn, err := db.GetDBConn()
  121. if err != nil {
  122. return err
  123. }
  124. return conn.Ping()
  125. }
  126. type PreparedStmtTX struct {
  127. Tx
  128. PreparedStmtDB *PreparedStmtDB
  129. }
  130. func (db *PreparedStmtTX) GetDBConn() (*sql.DB, error) {
  131. return db.PreparedStmtDB.GetDBConn()
  132. }
  133. func (tx *PreparedStmtTX) Commit() error {
  134. if tx.Tx != nil && !reflect.ValueOf(tx.Tx).IsNil() {
  135. return tx.Tx.Commit()
  136. }
  137. return ErrInvalidTransaction
  138. }
  139. func (tx *PreparedStmtTX) Rollback() error {
  140. if tx.Tx != nil && !reflect.ValueOf(tx.Tx).IsNil() {
  141. return tx.Tx.Rollback()
  142. }
  143. return ErrInvalidTransaction
  144. }
  145. func (tx *PreparedStmtTX) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error) {
  146. stmt, err := tx.PreparedStmtDB.prepare(ctx, tx.Tx, true, query)
  147. if err == nil {
  148. result, err = tx.Tx.StmtContext(ctx, stmt.Stmt).ExecContext(ctx, args...)
  149. if errors.Is(err, driver.ErrBadConn) {
  150. tx.PreparedStmtDB.Stmts.Delete(query)
  151. }
  152. }
  153. return result, err
  154. }
  155. func (tx *PreparedStmtTX) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) {
  156. stmt, err := tx.PreparedStmtDB.prepare(ctx, tx.Tx, true, query)
  157. if err == nil {
  158. rows, err = tx.Tx.StmtContext(ctx, stmt.Stmt).QueryContext(ctx, args...)
  159. if errors.Is(err, driver.ErrBadConn) {
  160. tx.PreparedStmtDB.Stmts.Delete(query)
  161. }
  162. }
  163. return rows, err
  164. }
  165. func (tx *PreparedStmtTX) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
  166. stmt, err := tx.PreparedStmtDB.prepare(ctx, tx.Tx, true, query)
  167. if err == nil {
  168. return tx.Tx.StmtContext(ctx, stmt.Stmt).QueryRowContext(ctx, args...)
  169. }
  170. return &sql.Row{}
  171. }
  172. func (tx *PreparedStmtTX) Ping() error {
  173. conn, err := tx.GetDBConn()
  174. if err != nil {
  175. return err
  176. }
  177. return conn.Ping()
  178. }