stmtcache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Package stmtcache is a cache for statement descriptions.
  2. package stmtcache
  3. import (
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "github.com/jackc/pgx/v5/pgconn"
  7. )
  8. // StatementName returns a statement name that will be stable for sql across multiple connections and program
  9. // executions.
  10. func StatementName(sql string) string {
  11. digest := sha256.Sum256([]byte(sql))
  12. return "stmtcache_" + hex.EncodeToString(digest[0:24])
  13. }
  14. // Cache caches statement descriptions.
  15. type Cache interface {
  16. // Get returns the statement description for sql. Returns nil if not found.
  17. Get(sql string) *pgconn.StatementDescription
  18. // Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache.
  19. Put(sd *pgconn.StatementDescription)
  20. // Invalidate invalidates statement description identified by sql. Does nothing if not found.
  21. Invalidate(sql string)
  22. // InvalidateAll invalidates all statement descriptions.
  23. InvalidateAll()
  24. // GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated.
  25. GetInvalidated() []*pgconn.StatementDescription
  26. // RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a
  27. // call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were
  28. // never seen by the call to GetInvalidated.
  29. RemoveInvalidated()
  30. // Len returns the number of cached prepared statement descriptions.
  31. Len() int
  32. // Cap returns the maximum number of cached prepared statement descriptions.
  33. Cap() int
  34. }