@@ -3,22 +3,21 @@ package mysql
33import (
44 "context"
55 "database/sql"
6+ "encoding/json"
67 "fmt"
78 "io"
89 "os"
910 "sync"
1011 "time"
1112
1213 "github.com/go-session/session"
13- "github.com/json-iterator/go"
14- "gopkg.in/gorp.v2"
1514)
1615
1716var (
1817 _ session.ManagerStore = & managerStore {}
1918 _ session.Store = & store {}
20- jsonMarshal = jsoniter .Marshal
21- jsonUnmarshal = jsoniter .Unmarshal
19+ jsonMarshal = json .Marshal
20+ jsonUnmarshal = json .Unmarshal
2221)
2322
2423// NewConfig create mysql configuration instance
@@ -60,7 +59,7 @@ func NewStore(config *Config, tableName string, gcInterval int) session.ManagerS
6059// gcInterval Time interval for executing GC (in seconds, default 600)
6160func NewStoreWithDB (db * sql.DB , tableName string , gcInterval int ) session.ManagerStore {
6261 store := & managerStore {
63- db : & gorp. DbMap { Db : db , Dialect : gorp. MySQLDialect { Encoding : "UTF8" , Engine : "MyISAM" }} ,
62+ db : db ,
6463 tableName : "go_session" ,
6564 stdout : os .Stderr ,
6665 }
@@ -75,18 +74,7 @@ func NewStoreWithDB(db *sql.DB, tableName string, gcInterval int) session.Manage
7574 }
7675 store .ticker = time .NewTicker (time .Second * time .Duration (interval ))
7776
78- store .pool = sync.Pool {
79- New : func () interface {} {
80- return newStore (store .db , store .tableName )
81- },
82- }
83-
84- store .db .AddTableWithName (SessionItem {}, store .tableName )
85-
86- err := store .db .CreateTablesIfNotExists ()
87- if err != nil {
88- panic (err )
89- }
77+ store .db .Exec (fmt .Sprintf ("CREATE TABLE IF NOT EXISTS `%s` (`id` VARCHAR(255) NOT NULL PRIMARY KEY, `value` VARCHAR(2048), `expired_at` bigint) engine=InnoDB charset=UTF8;" , store .tableName ))
9078 store .db .Exec (fmt .Sprintf ("CREATE INDEX `idx_expired_at` ON %s (`expired_at`);" , store .tableName ))
9179
9280 go store .gc ()
@@ -95,8 +83,7 @@ func NewStoreWithDB(db *sql.DB, tableName string, gcInterval int) session.Manage
9583
9684type managerStore struct {
9785 ticker * time.Ticker
98- pool sync.Pool
99- db * gorp.DbMap
86+ db * sql.DB
10087 tableName string
10188 stdout io.Writer
10289}
@@ -111,13 +98,15 @@ func (s *managerStore) errorf(format string, args ...interface{}) {
11198func (s * managerStore ) gc () {
11299 for range s .ticker .C {
113100 now := time .Now ().Unix ()
114- query := fmt .Sprintf ("SELECT COUNT(*) FROM %s WHERE expired_at<=?" , s .tableName )
115- n , err := s .db .SelectInt (query , now )
101+
102+ var count int
103+ row := s .db .QueryRow (fmt .Sprintf ("SELECT COUNT(*) FROM `%s` WHERE `expired_at`<=?" , s .tableName ), now )
104+ err := row .Scan (& count )
116105 if err != nil {
117106 s .errorf ("[ERROR]:%s" , err .Error ())
118107 return
119- } else if n > 0 {
120- _ , err = s .db .Exec (fmt .Sprintf ("DELETE FROM %s WHERE expired_at<=?" , s .tableName ), now )
108+ } else if count > 0 {
109+ _ , err = s .db .Exec (fmt .Sprintf ("DELETE FROM `%s` WHERE ` expired_at` <=?" , s .tableName ), now )
121110 if err != nil {
122111 s .errorf ("[ERROR]:%s" , err .Error ())
123112 }
@@ -128,7 +117,8 @@ func (s *managerStore) gc() {
128117func (s * managerStore ) getValue (sid string ) (string , error ) {
129118 var item SessionItem
130119
131- err := s .db .SelectOne (& item , fmt .Sprintf ("SELECT * FROM %s WHERE id=?" , s .tableName ), sid )
120+ row := s .db .QueryRow (fmt .Sprintf ("SELECT `id`,`value`,`expired_at` FROM `%s` WHERE `id`=?" , s .tableName ), sid )
121+ err := row .Scan (& item .ID , & item .Value , & item .ExpiredAt )
132122 if err != nil {
133123 if err == sql .ErrNoRows {
134124 return "" , nil
@@ -162,23 +152,18 @@ func (s *managerStore) Check(_ context.Context, sid string) (bool, error) {
162152}
163153
164154func (s * managerStore ) Create (ctx context.Context , sid string , expired int64 ) (session.Store , error ) {
165- store := s .pool .Get ().(* store )
166- store .reset (ctx , sid , expired , nil )
167- return store , nil
155+ return newStore (ctx , s , sid , expired , nil ), nil
168156}
169157
170158func (s * managerStore ) Update (ctx context.Context , sid string , expired int64 ) (session.Store , error ) {
171- store := s .pool .Get ().(* store )
172-
173159 value , err := s .getValue (sid )
174160 if err != nil {
175161 return nil , err
176162 } else if value == "" {
177- store .reset (ctx , sid , expired , nil )
178- return store , nil
163+ return newStore (ctx , s , sid , expired , nil ), nil
179164 }
180165
181- _ , err = s .db .Exec (fmt .Sprintf ("UPDATE %s SET expired_at=? WHERE id =?" , s .tableName ),
166+ _ , err = s .db .Exec (fmt .Sprintf ("UPDATE `%s` SET ` expired_at` =? WHERE `id` =?" , s .tableName ),
182167 time .Now ().Add (time .Duration (expired )* time .Second ).Unix (),
183168 sid )
184169 if err != nil {
@@ -190,31 +175,24 @@ func (s *managerStore) Update(ctx context.Context, sid string, expired int64) (s
190175 return nil , err
191176 }
192177
193- store .reset (ctx , sid , expired , values )
194- return store , nil
178+ return newStore (ctx , s , sid , expired , values ), nil
195179}
196180
197181func (s * managerStore ) Delete (_ context.Context , sid string ) error {
198- _ , err := s .db .Exec (fmt .Sprintf ("DELETE FROM %s WHERE id =?" , s .tableName ), sid )
182+ _ , err := s .db .Exec (fmt .Sprintf ("DELETE FROM `%s` WHERE `id` =?" , s .tableName ), sid )
199183 return err
200184}
201185
202186func (s * managerStore ) Refresh (ctx context.Context , oldsid , sid string , expired int64 ) (session.Store , error ) {
203- store := s .pool .Get ().(* store )
204-
205187 value , err := s .getValue (oldsid )
206188 if err != nil {
207189 return nil , err
208190 } else if value == "" {
209- store .reset (ctx , sid , expired , nil )
210- return store , nil
191+ return newStore (ctx , s , sid , expired , nil ), nil
211192 }
212193
213- err = s .db .Insert (& SessionItem {
214- ID : sid ,
215- Value : value ,
216- ExpiredAt : time .Now ().Add (time .Duration (expired ) * time .Second ).Unix (),
217- })
194+ query := fmt .Sprintf ("INSERT INTO `%s` (`id`,`value`,`expired_at`) VALUES (?,?,?);" , s .tableName )
195+ _ , err = s .db .Exec (query , sid , value , time .Now ().Add (time .Duration (expired )* time .Second ).Unix ())
218196 if err != nil {
219197 return nil , err
220198 }
@@ -229,43 +207,40 @@ func (s *managerStore) Refresh(ctx context.Context, oldsid, sid string, expired
229207 return nil , err
230208 }
231209
232- store .reset (ctx , sid , expired , values )
233- return store , nil
210+ return newStore (ctx , s , sid , expired , values ), nil
234211}
235212
236213func (s * managerStore ) Close () error {
237214 s .ticker .Stop ()
238- s .db .Db . Close ()
215+ s .db .Close ()
239216 return nil
240217}
241218
242- func newStore (db * gorp.DbMap , tableName string ) * store {
219+ func newStore (ctx context.Context , s * managerStore , sid string , expired int64 , values map [string ]interface {}) * store {
220+ if values == nil {
221+ values = make (map [string ]interface {})
222+ }
223+
243224 return & store {
244- db : db ,
245- tableName : tableName ,
225+ db : s .db ,
226+ tableName : s .tableName ,
227+ ctx : ctx ,
228+ sid : sid ,
229+ expired : expired ,
230+ values : values ,
246231 }
247232}
248233
249234type store struct {
250235 sync.RWMutex
251236 ctx context.Context
252- db * gorp. DbMap
237+ db * sql. DB
253238 tableName string
254239 sid string
255240 expired int64
256241 values map [string ]interface {}
257242}
258243
259- func (s * store ) reset (ctx context.Context , sid string , expired int64 , values map [string ]interface {}) {
260- if values == nil {
261- values = make (map [string ]interface {})
262- }
263- s .ctx = ctx
264- s .sid = sid
265- s .expired = expired
266- s .values = values
267- }
268-
269244func (s * store ) Context () context.Context {
270245 return s .ctx
271246}
@@ -320,18 +295,18 @@ func (s *store) Save() error {
320295 }
321296 s .RUnlock ()
322297
323- n , err := s .db .SelectInt (fmt .Sprintf ("SELECT COUNT(*) FROM %s WHERE id=?" , s .tableName ), s .sid )
298+ var count int
299+ row := s .db .QueryRow (fmt .Sprintf ("SELECT COUNT(*) FROM %s WHERE id=?" , s .tableName ), s .sid )
300+ err := row .Scan (& count )
324301 if err != nil {
325302 return err
326- } else if n == 0 {
327- return s .db .Insert (& SessionItem {
328- ID : s .sid ,
329- Value : value ,
330- ExpiredAt : time .Now ().Add (time .Duration (s .expired ) * time .Second ).Unix (),
331- })
303+ } else if count == 0 {
304+ query := fmt .Sprintf ("INSERT INTO `%s` (`id`,`value`,`expired_at`) VALUES (?,?,?);" , s .tableName )
305+ _ , err = s .db .Exec (query , s .sid , value , time .Now ().Add (time .Duration (s .expired )* time .Second ).Unix ())
306+ return err
332307 }
333308
334- _ , err = s .db .Exec (fmt .Sprintf ("UPDATE %s SET value=?,expired_at=? WHERE id =?" , s .tableName ),
309+ _ , err = s .db .Exec (fmt .Sprintf ("UPDATE `%s` SET ` value` =?,` expired_at` =? WHERE `id` =?" , s .tableName ),
335310 value ,
336311 time .Now ().Add (time .Duration (s .expired )* time .Second ).Unix (),
337312 s .sid )
@@ -341,7 +316,7 @@ func (s *store) Save() error {
341316
342317// SessionItem Data items stored in mysql
343318type SessionItem struct {
344- ID string `db:"id,primarykey,size:255"`
345- Value string `db:"value,size:2048"`
346- ExpiredAt int64 `db:"expired_at"`
319+ ID string
320+ Value string
321+ ExpiredAt int64
347322}
0 commit comments