|
1 | 1 | package sqlite3 |
2 | 2 |
|
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + |
| 6 | + // Namespace Imports |
| 7 | + . "github.com/djthorpe/go-errors" |
| 8 | + sqlite3 "github.com/djthorpe/go-sqlite/sys/sqlite3" |
| 9 | + multierror "github.com/hashicorp/go-multierror" |
| 10 | +) |
| 11 | + |
3 | 12 | //////////////////////////////////////////////////////////////////////////////// |
4 | 13 | // TYPES |
5 | 14 |
|
6 | 15 | // PoolCache caches prepared statements and profiling information for |
7 | 16 | // statements so it's possible to see slow queries, etc. |
8 | | -type PoolCache struct { |
| 17 | +type PoolCache struct{} |
| 18 | + |
| 19 | +type ConnCache struct { |
| 20 | + sync.Mutex |
| 21 | + sync.Map |
9 | 22 | } |
10 | 23 |
|
| 24 | +//////////////////////////////////////////////////////////////////////////////// |
| 25 | +// GLOBALS |
| 26 | + |
| 27 | +const ( |
| 28 | + defaultCapacity = 100 |
| 29 | +) |
| 30 | + |
11 | 31 | //////////////////////////////////////////////////////////////////////////////// |
12 | 32 | // PUBLIC METHODS |
13 | 33 |
|
14 | | -// Return a prepared statement from the cache |
15 | | -func (cache *PoolCache) Prepare(q string) (*Results, error) { |
| 34 | +// Return a prepared statement from the cache, or prepare a new statement |
| 35 | +// and put it in the cache before returning |
| 36 | +func (cache *ConnCache) Prepare(conn *sqlite3.ConnEx, q string) (*Results, error) { |
| 37 | + if conn == nil { |
| 38 | + return nil, ErrInternalAppError |
| 39 | + } |
| 40 | + st, _ := cache.Map.Load(q) |
| 41 | + if st == nil { |
| 42 | + // Prepare a statement and store in cache |
| 43 | + var err error |
| 44 | + cache.Mutex.Lock() |
| 45 | + defer cache.Mutex.Unlock() |
| 46 | + if st, err = conn.Prepare(q); err != nil { |
| 47 | + return nil, err |
| 48 | + } else { |
| 49 | + cache.Map.Store(q, st) |
| 50 | + } |
| 51 | + } else { |
| 52 | + // Increment counter by one |
| 53 | + st.(*sqlite3.StatementEx).Inc(1) |
| 54 | + } |
| 55 | + return NewResults(st.(*sqlite3.StatementEx)), nil |
| 56 | +} |
| 57 | + |
| 58 | +// Close all conn cache prepared statements |
| 59 | +func (cache *ConnCache) Close() error { |
| 60 | + var result error |
| 61 | + cache.Map.Range(func(key, value interface{}) bool { |
| 62 | + if err := value.(*sqlite3.StatementEx).Close(); err != nil { |
| 63 | + result = multierror.Append(result, err) |
| 64 | + } |
| 65 | + return true |
| 66 | + }) |
16 | 67 |
|
| 68 | + // Return any errors |
| 69 | + return result |
17 | 70 | } |
0 commit comments