http urls monitor.

statement.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package sqladapter
  2. import (
  3. "database/sql"
  4. "errors"
  5. "sync"
  6. "sync/atomic"
  7. )
  8. var (
  9. activeStatements int64
  10. )
  11. // Stmt represents a *sql.Stmt that is cached and provides the
  12. // OnPurge method to allow it to clean after itself.
  13. type Stmt struct {
  14. *sql.Stmt
  15. query string
  16. mu sync.Mutex
  17. count int64
  18. dead bool
  19. }
  20. // NewStatement creates an returns an opened statement
  21. func NewStatement(stmt *sql.Stmt, query string) *Stmt {
  22. s := &Stmt{
  23. Stmt: stmt,
  24. query: query,
  25. }
  26. atomic.AddInt64(&activeStatements, 1)
  27. return s
  28. }
  29. // Open marks the statement as in-use
  30. func (c *Stmt) Open() (*Stmt, error) {
  31. c.mu.Lock()
  32. defer c.mu.Unlock()
  33. if c.dead {
  34. return nil, errors.New("statement is dead")
  35. }
  36. c.count++
  37. return c, nil
  38. }
  39. // Close closes the underlying statement if no other go-routine is using it.
  40. func (c *Stmt) Close() error {
  41. c.mu.Lock()
  42. defer c.mu.Unlock()
  43. c.count--
  44. return c.checkClose()
  45. }
  46. func (c *Stmt) checkClose() error {
  47. if c.dead && c.count == 0 {
  48. // Statement is dead and we can close it for real.
  49. err := c.Stmt.Close()
  50. if err != nil {
  51. return err
  52. }
  53. // Reduce active statements counter.
  54. atomic.AddInt64(&activeStatements, -1)
  55. }
  56. return nil
  57. }
  58. // OnPurge marks the statement as ready to be cleaned up.
  59. func (c *Stmt) OnPurge() {
  60. c.mu.Lock()
  61. defer c.mu.Unlock()
  62. c.dead = true
  63. c.checkClose()
  64. }
  65. // NumActiveStatements returns the global number of prepared statements in use
  66. // at any point.
  67. func NumActiveStatements() int64 {
  68. return atomic.LoadInt64(&activeStatements)
  69. }