forked from sourcegraph/thesrc
/
posts.go
98 lines (82 loc) · 2.08 KB
/
posts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package datastore
import (
"fmt"
"math/rand"
"strings"
"time"
"github.com/jmoiron/modl"
"github.com/sourcegraph/thesrc"
)
func init() {
DB.AddTableWithName(thesrc.Post{}, "post").SetKeys(true, "ID")
createSQL = append(createSQL,
`CREATE INDEX post_submittedat ON post(submittedat DESC);`,
`CREATE UNIQUE INDEX post_linkurl ON post(linkurl);`,
)
}
type postsStore struct{ *Datastore }
func (s *postsStore) Get(id int) (*thesrc.Post, error) {
var posts []*thesrc.Post
if err := s.dbh.Select(&posts, `SELECT * FROM post WHERE id=$1;`, id); err != nil {
return nil, err
}
if len(posts) == 0 {
return nil, thesrc.ErrPostNotFound
}
return posts[0], nil
}
func (s *postsStore) List(opt *thesrc.PostListOptions) ([]*thesrc.Post, error) {
if opt == nil {
opt = &thesrc.PostListOptions{}
}
sql := `SELECT * FROM post`
var conds []string
if opt.CodeOnly {
conds = append(conds, "classification LIKE 'CODE%'")
}
if len(conds) > 0 {
sql += " WHERE (" + strings.Join(conds, ") AND (") + ")"
}
sql += " ORDER BY submittedat DESC LIMIT $1 OFFSET $2;"
var posts []*thesrc.Post
err := s.dbh.Select(&posts, sql, opt.PerPageOrDefault(), opt.Offset())
if err != nil {
return nil, err
}
return posts, nil
}
func (s *postsStore) Submit(post *thesrc.Post) (bool, error) {
retries := 3
var wantRetry bool
retry:
retries--
wantRetry = false
if retries == 0 {
return false, fmt.Errorf("failed to submit post with URL %q after retrying", post.LinkURL)
}
var created bool
err := transact(s.dbh, func(tx modl.SqlExecutor) error {
var existing []*thesrc.Post
if err := tx.Select(&existing, `SELECT * FROM post WHERE linkurl=$1 LIMIT 1;`, post.LinkURL); err != nil {
return err
}
if len(existing) > 0 {
*post = *existing[0]
return nil
}
if err := tx.Insert(post); err != nil {
if strings.Contains(err.Error(), `violates unique constraint "post_linkurl"`) {
time.Sleep(time.Duration(rand.Intn(75)) * time.Millisecond)
wantRetry = true
return err
}
return err
}
created = true
return nil
})
if wantRetry {
goto retry
}
return created, err
}