Debian Codegraph @

postgres/postgres.go

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