Debian Codegraph @

prepare_stmt.go

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