Skip to content

Commit 0d1e616

Browse files
heilerichwillnorris
authored andcommitted
db: add mutex to fix http errors during stats save
Signed-off-by: Felix Heilmeyer <[email protected]>
1 parent 7fd2d35 commit 0d1e616

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

db.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"io/fs"
1313
"net/url"
1414
"strings"
15+
"sync"
1516
"time"
1617

1718
_ "modernc.org/sqlite"
@@ -40,6 +41,7 @@ func linkID(short string) string {
4041
// SQLiteDB stores Links in a SQLite database.
4142
type SQLiteDB struct {
4243
db *sql.DB
44+
mu sync.RWMutex
4345
}
4446

4547
//go:embed schema.sql
@@ -66,6 +68,9 @@ func NewSQLiteDB(f string) (*SQLiteDB, error) {
6668
//
6769
// The caller owns the returned values.
6870
func (s *SQLiteDB) LoadAll() ([]*Link, error) {
71+
s.mu.RLock()
72+
defer s.mu.RUnlock()
73+
6974
var links []*Link
7075
rows, err := s.db.Query("SELECT Short, Long, Created, LastEdit, Owner FROM Links")
7176
if err != nil {
@@ -91,6 +96,9 @@ func (s *SQLiteDB) LoadAll() ([]*Link, error) {
9196
//
9297
// The caller owns the returned value.
9398
func (s *SQLiteDB) Load(short string) (*Link, error) {
99+
s.mu.RLock()
100+
defer s.mu.RUnlock()
101+
94102
link := new(Link)
95103
var created, lastEdit int64
96104
row := s.db.QueryRow("SELECT Short, Long, Created, LastEdit, Owner FROM Links WHERE ID = ?1 LIMIT 1", linkID(short))
@@ -108,6 +116,9 @@ func (s *SQLiteDB) Load(short string) (*Link, error) {
108116

109117
// Save saves a Link.
110118
func (s *SQLiteDB) Save(link *Link) error {
119+
s.mu.Lock()
120+
defer s.mu.Unlock()
121+
111122
result, err := s.db.Exec("INSERT OR REPLACE INTO Links (ID, Short, Long, Created, LastEdit, Owner) VALUES (?, ?, ?, ?, ?, ?)", linkID(link.Short), link.Short, link.Long, link.Created.Unix(), link.LastEdit.Unix(), link.Owner)
112123
if err != nil {
113124
return err
@@ -133,6 +144,9 @@ func (s *SQLiteDB) LoadStats() (ClickStats, error) {
133144
linkmap[linkID(link.Short)] = link.Short
134145
}
135146

147+
s.mu.RLock()
148+
defer s.mu.RUnlock()
149+
136150
rows, err := s.db.Query("SELECT ID, sum(Clicks) FROM Stats GROUP BY ID")
137151
if err != nil {
138152
return nil, err
@@ -155,6 +169,9 @@ func (s *SQLiteDB) LoadStats() (ClickStats, error) {
155169
// incremental clicks that have occurred since the last time SaveStats
156170
// was called.
157171
func (s *SQLiteDB) SaveStats(stats ClickStats) error {
172+
s.mu.Lock()
173+
defer s.mu.Unlock()
174+
158175
tx, err := s.db.BeginTx(context.TODO(), nil)
159176
if err != nil {
160177
return err

0 commit comments

Comments
 (0)