mysql.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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/go-sql-driver/mysql"
  23. "github.com/go-macaron/session"
  24. )
  25. // MysqlStore represents a mysql session store implementation.
  26. type MysqlStore struct {
  27. c *sql.DB
  28. sid string
  29. lock sync.RWMutex
  30. data map[interface{}]interface{}
  31. expiry int64
  32. dirty bool
  33. }
  34. // NewMysqlStore creates and returns a mysql session store.
  35. func NewMysqlStore(c *sql.DB, sid string, kv map[interface{}]interface{}, expiry int64) *MysqlStore {
  36. return &MysqlStore{
  37. c: c,
  38. sid: sid,
  39. data: kv,
  40. expiry: expiry,
  41. dirty: false,
  42. }
  43. }
  44. // Set sets value to given key in session.
  45. func (s *MysqlStore) Set(key, val interface{}) error {
  46. s.lock.Lock()
  47. defer s.lock.Unlock()
  48. s.data[key] = val
  49. s.dirty = true
  50. return nil
  51. }
  52. // Get gets value by given key in session.
  53. func (s *MysqlStore) Get(key interface{}) interface{} {
  54. s.lock.RLock()
  55. defer s.lock.RUnlock()
  56. return s.data[key]
  57. }
  58. // Delete delete a key from session.
  59. func (s *MysqlStore) Delete(key interface{}) error {
  60. s.lock.Lock()
  61. defer s.lock.Unlock()
  62. delete(s.data, key)
  63. s.dirty = true
  64. return nil
  65. }
  66. // ID returns current session ID.
  67. func (s *MysqlStore) ID() string {
  68. return s.sid
  69. }
  70. // Release releases resource and save data to provider.
  71. func (s *MysqlStore) Release() error {
  72. newExpiry := time.Now().Unix()
  73. if !s.dirty && (s.expiry+60) >= newExpiry {
  74. return nil
  75. }
  76. data, err := session.EncodeGob(s.data)
  77. if err != nil {
  78. return err
  79. }
  80. _, err = s.c.Exec("UPDATE session SET data=?, expiry=? WHERE `key`=?",
  81. data, newExpiry, s.sid)
  82. s.dirty = false
  83. s.expiry = newExpiry
  84. return err
  85. }
  86. // Flush deletes all session data.
  87. func (s *MysqlStore) Flush() error {
  88. s.lock.Lock()
  89. defer s.lock.Unlock()
  90. s.data = make(map[interface{}]interface{})
  91. s.dirty = true
  92. return nil
  93. }
  94. // MysqlProvider represents a mysql session provider implementation.
  95. type MysqlProvider struct {
  96. c *sql.DB
  97. expire int64
  98. }
  99. // Init initializes mysql session provider.
  100. // connStr: username:password@protocol(address)/dbname?param=value
  101. func (p *MysqlProvider) Init(expire int64, connStr string) (err error) {
  102. p.expire = expire
  103. p.c, err = sql.Open("mysql", connStr)
  104. p.c.SetConnMaxLifetime(time.Second * time.Duration(sessionConnMaxLifetime))
  105. if err != nil {
  106. return err
  107. }
  108. return p.c.Ping()
  109. }
  110. // Read returns raw session store by session ID.
  111. func (p *MysqlProvider) Read(sid string) (session.RawStore, error) {
  112. expiry := time.Now().Unix()
  113. var data []byte
  114. err := p.c.QueryRow("SELECT data,expiry FROM session WHERE `key`=?", sid).Scan(&data, &expiry)
  115. if err == sql.ErrNoRows {
  116. _, err = p.c.Exec("INSERT INTO session(`key`,data,expiry) VALUES(?,?,?)",
  117. sid, "", expiry)
  118. }
  119. if err != nil {
  120. return nil, err
  121. }
  122. var kv map[interface{}]interface{}
  123. if len(data) == 0 {
  124. kv = make(map[interface{}]interface{})
  125. } else {
  126. kv, err = session.DecodeGob(data)
  127. if err != nil {
  128. return nil, err
  129. }
  130. }
  131. return NewMysqlStore(p.c, sid, kv, expiry), nil
  132. }
  133. // Exist returns true if session with given ID exists.
  134. func (p *MysqlProvider) Exist(sid string) bool {
  135. exists, err := p.queryExists(sid)
  136. if err != nil {
  137. exists, err = p.queryExists(sid)
  138. }
  139. if err != nil {
  140. log.Printf("session/mysql: error checking if session exists: %v", err)
  141. return false
  142. }
  143. return exists
  144. }
  145. func (p *MysqlProvider) queryExists(sid string) (bool, error) {
  146. var data []byte
  147. err := p.c.QueryRow("SELECT data FROM session WHERE `key`=?", sid).Scan(&data)
  148. if err != nil && err != sql.ErrNoRows {
  149. return false, err
  150. }
  151. return err != sql.ErrNoRows, nil
  152. }
  153. // Destory deletes a session by session ID.
  154. func (p *MysqlProvider) Destory(sid string) error {
  155. _, err := p.c.Exec("DELETE FROM session WHERE `key`=?", sid)
  156. return err
  157. }
  158. // Regenerate regenerates a session store from old session ID to new one.
  159. func (p *MysqlProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
  160. if p.Exist(sid) {
  161. return nil, fmt.Errorf("new sid '%s' already exists", sid)
  162. }
  163. if !p.Exist(oldsid) {
  164. if _, err = p.c.Exec("INSERT INTO session(`key`,data,expiry) VALUES(?,?,?)",
  165. oldsid, "", time.Now().Unix()); err != nil {
  166. return nil, err
  167. }
  168. }
  169. if _, err = p.c.Exec("UPDATE session SET `key`=? WHERE `key`=?", sid, oldsid); err != nil {
  170. return nil, err
  171. }
  172. return p.Read(sid)
  173. }
  174. // Count counts and returns number of sessions.
  175. func (p *MysqlProvider) Count() (total int) {
  176. if err := p.c.QueryRow("SELECT COUNT(*) AS NUM FROM session").Scan(&total); err != nil {
  177. panic("session/mysql: error counting records: " + err.Error())
  178. }
  179. return total
  180. }
  181. // GC calls GC to clean expired sessions.
  182. func (p *MysqlProvider) GC() {
  183. var err error
  184. if _, err = p.c.Exec("DELETE FROM session WHERE expiry + ? <= UNIX_TIMESTAMP(NOW())", p.expire); err != nil {
  185. _, err = p.c.Exec("DELETE FROM session WHERE expiry + ? <= UNIX_TIMESTAMP(NOW())", p.expire)
  186. }
  187. if err != nil {
  188. log.Printf("session/mysql: error garbage collecting: %v", err)
  189. }
  190. }
  191. func init() {
  192. session.Register("mysql", &MysqlProvider{})
  193. }