postgres.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. // Copyright 2013 Beego Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package session
  16. import (
  17. "database/sql"
  18. "fmt"
  19. "log"
  20. "sync"
  21. "time"
  22. _ "github.com/lib/pq"
  23. "github.com/go-macaron/session"
  24. )
  25. // PostgresStore represents a postgres session store implementation.
  26. type PostgresStore struct {
  27. c *sql.DB
  28. sid string
  29. lock sync.RWMutex
  30. data map[interface{}]interface{}
  31. }
  32. // NewPostgresStore creates and returns a postgres session store.
  33. func NewPostgresStore(c *sql.DB, sid string, kv map[interface{}]interface{}) *PostgresStore {
  34. return &PostgresStore{
  35. c: c,
  36. sid: sid,
  37. data: kv,
  38. }
  39. }
  40. // Set sets value to given key in session.
  41. func (s *PostgresStore) Set(key, value interface{}) error {
  42. s.lock.Lock()
  43. defer s.lock.Unlock()
  44. s.data[key] = value
  45. return nil
  46. }
  47. // Get gets value by given key in session.
  48. func (s *PostgresStore) Get(key interface{}) interface{} {
  49. s.lock.RLock()
  50. defer s.lock.RUnlock()
  51. return s.data[key]
  52. }
  53. // Delete delete a key from session.
  54. func (s *PostgresStore) Delete(key interface{}) error {
  55. s.lock.Lock()
  56. defer s.lock.Unlock()
  57. delete(s.data, key)
  58. return nil
  59. }
  60. // ID returns current session ID.
  61. func (s *PostgresStore) ID() string {
  62. return s.sid
  63. }
  64. // save postgres session values to database.
  65. // must call this method to save values to database.
  66. func (s *PostgresStore) Release() error {
  67. data, err := session.EncodeGob(s.data)
  68. if err != nil {
  69. return err
  70. }
  71. _, err = s.c.Exec("UPDATE session SET data=$1, expiry=$2 WHERE key=$3",
  72. data, time.Now().Unix(), s.sid)
  73. return err
  74. }
  75. // Flush deletes all session data.
  76. func (s *PostgresStore) Flush() error {
  77. s.lock.Lock()
  78. defer s.lock.Unlock()
  79. s.data = make(map[interface{}]interface{})
  80. return nil
  81. }
  82. // PostgresProvider represents a postgres session provider implementation.
  83. type PostgresProvider struct {
  84. c *sql.DB
  85. maxlifetime int64
  86. }
  87. // Init initializes postgres session provider.
  88. // connStr: user=a password=b host=localhost port=5432 dbname=c sslmode=disable
  89. func (p *PostgresProvider) Init(maxlifetime int64, connStr string) (err error) {
  90. p.maxlifetime = maxlifetime
  91. p.c, err = sql.Open("postgres", connStr)
  92. if err != nil {
  93. return err
  94. }
  95. return p.c.Ping()
  96. }
  97. // Read returns raw session store by session ID.
  98. func (p *PostgresProvider) Read(sid string) (session.RawStore, error) {
  99. var data []byte
  100. err := p.c.QueryRow("SELECT data FROM session WHERE key=$1", sid).Scan(&data)
  101. if err == sql.ErrNoRows {
  102. _, err = p.c.Exec("INSERT INTO session(key,data,expiry) VALUES($1,$2,$3)",
  103. sid, "", time.Now().Unix())
  104. }
  105. if err != nil {
  106. return nil, err
  107. }
  108. var kv map[interface{}]interface{}
  109. if len(data) == 0 {
  110. kv = make(map[interface{}]interface{})
  111. } else {
  112. kv, err = session.DecodeGob(data)
  113. if err != nil {
  114. return nil, err
  115. }
  116. }
  117. return NewPostgresStore(p.c, sid, kv), nil
  118. }
  119. // Exist returns true if session with given ID exists.
  120. func (p *PostgresProvider) Exist(sid string) bool {
  121. var data []byte
  122. err := p.c.QueryRow("SELECT data FROM session WHERE key=$1", sid).Scan(&data)
  123. if err != nil && err != sql.ErrNoRows {
  124. panic("session/postgres: error checking existence: " + err.Error())
  125. }
  126. return err != sql.ErrNoRows
  127. }
  128. // Destory deletes a session by session ID.
  129. func (p *PostgresProvider) Destory(sid string) error {
  130. _, err := p.c.Exec("DELETE FROM session WHERE key=$1", sid)
  131. return err
  132. }
  133. // Regenerate regenerates a session store from old session ID to new one.
  134. func (p *PostgresProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
  135. if p.Exist(sid) {
  136. return nil, fmt.Errorf("new sid '%s' already exists", sid)
  137. }
  138. if !p.Exist(oldsid) {
  139. if _, err = p.c.Exec("INSERT INTO session(key,data,expiry) VALUES($1,$2,$3)",
  140. oldsid, "", time.Now().Unix()); err != nil {
  141. return nil, err
  142. }
  143. }
  144. if _, err = p.c.Exec("UPDATE session SET key=$1 WHERE key=$2", sid, oldsid); err != nil {
  145. return nil, err
  146. }
  147. return p.Read(sid)
  148. }
  149. // Count counts and returns number of sessions.
  150. func (p *PostgresProvider) Count() (total int) {
  151. if err := p.c.QueryRow("SELECT COUNT(*) AS NUM FROM session").Scan(&total); err != nil {
  152. panic("session/postgres: error counting records: " + err.Error())
  153. }
  154. return total
  155. }
  156. // GC calls GC to clean expired sessions.
  157. func (p *PostgresProvider) GC() {
  158. if _, err := p.c.Exec("DELETE FROM session WHERE EXTRACT(EPOCH FROM NOW()) - expiry > $1", p.maxlifetime); err != nil {
  159. log.Printf("session/postgres: error garbage collecting: %v", err)
  160. }
  161. }
  162. func init() {
  163. session.Register("postgres", &PostgresProvider{})
  164. }