1 // Package stmtcache is a cache that can be used to implement lazy prepared statements. 2 package stmtcache 3 4 import ( 5 "context" 6 7 "github.com/jackc/pgconn" 8 ) 9 10 const ( 11 ModePrepare = iota // Cache should prepare named statements. 12 ModeDescribe // Cache should prepare the anonymous prepared statement to only fetch the description of the statement. 13 ) 14 15 // Cache prepares and caches prepared statement descriptions. 16 type Cache interface { 17 // Get returns the prepared statement description for sql preparing or describing the sql on the server as needed. 18 Get(ctx context.Context, sql string) (*pgconn.StatementDescription, error) 19 20 // Clear removes all entries in the cache. Any prepared statements will be deallocated from the PostgreSQL session. 21 Clear(ctx context.Context) error 22 23 // StatementErrored informs the cache that the given statement resulted in an error when it 24 // was last used against the database. In some cases, this will cause the cache to maer that 25 // statement as bad. The bad statement will instead be flushed during the next call to Get 26 // that occurs outside of a failed transaction. 27 StatementErrored(sql string, err error) 28 29 // Len returns the number of cached prepared statement descriptions. 30 Len() int 31 32 // Cap returns the maximum number of cached prepared statement descriptions. 33 Cap() int 34 35 // Mode returns the mode of the cache (ModePrepare or ModeDescribe) 36 Mode() int 37 } 38 39 // New returns the preferred cache implementation for mode and cap. mode is either ModePrepare or ModeDescribe. cap is 40 // the maximum size of the cache. 41 func New(conn *pgconn.PgConn, mode int, cap int) Cache { 42 mustBeValidMode(mode) 43 mustBeValidCap(cap) 44 45 return NewLRU(conn, mode, cap) 46 } 47 48 func mustBeValidMode(mode int) { 49 if mode != ModePrepare && mode != ModeDescribe { 50 panic("mode must be ModePrepare or ModeDescribe") 51 } 52 } 53 54 func mustBeValidCap(cap int) { 55 if cap < 1 { 56 panic("cache must have cap of >= 1") 57 } 58 } 59