Debian Codegraph @

internal/stmt_store/stmt_store.go

raw
1 package stmt_store
2
3 import (
4 "context"
5 "database/sql"
6 "math"
7 "sync"
8 "time"
9
10 "gorm.io/gorm/internal/lru"
11 )
12
13 type Stmt struct {
14 *sql.Stmt
15 Transaction bool
16 prepared chan struct{}
17 prepareErr error
18 }
19
20 func (stmt *Stmt) Error() error {
21 return stmt.prepareErr
22 }
23
24 func (stmt *Stmt) Close() error {
25 <-stmt.prepared
26
27 if stmt.Stmt != nil {
28 return stmt.Stmt.Close()
29 }
30 return nil
31 }
32
33 // Store defines an interface for managing the caching operations of SQL statements (Stmt).
34 // This interface provides methods for creating new statements, retrieving all cache keys,
35 // getting cached statements, setting cached statements, and deleting cached statements.
36 type Store interface {
37 // New creates a new Stmt object and caches it.
38 // Parameters:
39 // ctx: The context for the request, which can carry deadlines, cancellation signals, etc.
40 // key: The key representing the SQL query, used for caching and preparing the statement.
41 // isTransaction: Indicates whether this operation is part of a transaction, which may affect the caching strategy.
42 // connPool: A connection pool that provides database connections.
43 // locker: A synchronization lock that is unlocked after initialization to avoid deadlocks.
44 // Returns:
45 // *Stmt: A newly created statement object for executing SQL operations.
46 // error: An error if the statement preparation fails.
47 New(ctx context.Context, key string, isTransaction bool, connPool ConnPool, locker sync.Locker) (*Stmt, error)
48
49 // Keys returns a slice of all cache keys in the store.
50 Keys() []string
51
52 // Get retrieves a Stmt object from the store based on the given key.
53 // Parameters:
54 // key: The key used to look up the Stmt object.
55 // Returns:
56 // *Stmt: The found Stmt object, or nil if not found.
57 // bool: Indicates whether the corresponding Stmt object was successfully found.
58 Get(key string) (*Stmt, bool)
59
60 // Set stores the given Stmt object in the store and associates it with the specified key.
61 // Parameters:
62 // key: The key used to associate the Stmt object.
63 // value: The Stmt object to be stored.
64 Set(key string, value *Stmt)
65
66 // Delete removes the Stmt object corresponding to the specified key from the store.
67 // Parameters:
68 // key: The key associated with the Stmt object to be deleted.
69 Delete(key string)
70 }
71
72 // defaultMaxSize defines the default maximum capacity of the cache.
73 // Its value is the maximum value of the int64 type, which means that when the cache size is not specified,
74 // the cache can theoretically store as many elements as possible.
75 // (1 << 63) - 1 is the maximum value that an int64 type can represent.
76 const (
77 defaultMaxSize = math.MaxInt
78 // defaultTTL defines the default time-to-live (TTL) for each cache entry.
79 // When the TTL for cache entries is not specified, each cache entry will expire after 24 hours.
80 defaultTTL = time.Hour * 24
81 )
82
83 // New creates and returns a new Store instance.
84 //
85 // Parameters:
86 // - size: The maximum capacity of the cache. If the provided size is less than or equal to 0,
87 // it defaults to defaultMaxSize.
88 // - ttl: The time-to-live duration for each cache entry. If the provided ttl is less than or equal to 0,
89 // it defaults to defaultTTL.
90 //
91 // This function defines an onEvicted callback that is invoked when a cache entry is evicted.
92 // The callback ensures that if the evicted value (v) is not nil, its Close method is called asynchronously
93 // to release associated resources.
94 //
95 // Returns:
96 // - A Store instance implemented by lruStore, which internally uses an LRU cache with the specified size,
97 // eviction callback, and TTL.
98 func New(size int, ttl time.Duration) Store {
99 if size <= 0 {
100 size = defaultMaxSize
101 }
102
103 if ttl <= 0 {
104 ttl = defaultTTL
105 }
106
107 onEvicted := func(k string, v *Stmt) {
108 if v != nil {
109 go v.Close()
110 }
111 }
112 return &lruStore{lru: lru.NewLRU[string, *Stmt](size, onEvicted, ttl)}
113 }
114
115 type lruStore struct {
116 lru *lru.LRU[string, *Stmt]
117 }
118
119 func (s *lruStore) Keys() []string {
120 return s.lru.Keys()
121 }
122
123 func (s *lruStore) Get(key string) (*Stmt, bool) {
124 stmt, ok := s.lru.Get(key)
125 if ok && stmt != nil {
126 <-stmt.prepared
127 }
128 return stmt, ok
129 }
130
131 func (s *lruStore) Set(key string, value *Stmt) {
132 s.lru.Add(key, value)
133 }
134
135 func (s *lruStore) Delete(key string) {
136 s.lru.Remove(key)
137 }
138
139 type ConnPool interface {
140 PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
141 }
142
143 // New creates a new Stmt object for executing SQL queries.
144 // It caches the Stmt object for future use and handles preparation and error states.
145 // Parameters:
146 //
147 // ctx: Context for the request, used to carry deadlines, cancellation signals, etc.
148 // key: The key representing the SQL query, used for caching and preparing the statement.
149 // isTransaction: Indicates whether this operation is part of a transaction, affecting cache strategy.
150 // conn: A connection pool that provides database connections.
151 // locker: A synchronization lock that is unlocked after initialization to avoid deadlocks.
152 //
153 // Returns:
154 //
155 // *Stmt: A newly created statement object for executing SQL operations.
156 // error: An error if the statement preparation fails.
157 func (s *lruStore) New(ctx context.Context, key string, isTransaction bool, conn ConnPool, locker sync.Locker) (_ *Stmt, err error) {
158 // Create a Stmt object and set its Transaction property.
159 // The prepared channel is used to synchronize the statement preparation state.
160 cacheStmt := &Stmt{
161 Transaction: isTransaction,
162 prepared: make(chan struct{}),
163 }
164 // Cache the Stmt object with the associated key.
165 s.Set(key, cacheStmt)
166 // Unlock after completing initialization to prevent deadlocks.
167 locker.Unlock()
168
169 // Ensure the prepared channel is closed after the function execution completes.
170 defer close(cacheStmt.prepared)
171
172 // Prepare the SQL statement using the provided connection.
173 cacheStmt.Stmt, err = conn.PrepareContext(ctx, key)
174 if err != nil {
175 // If statement preparation fails, record the error and remove the invalid Stmt object from the cache.
176 cacheStmt.prepareErr = err
177 s.Delete(key)
178 return &Stmt{}, err
179 }
180
181 // Return the successfully prepared Stmt object.
182 return cacheStmt, nil
183 }