/
sources.go
65 lines (51 loc) · 1.1 KB
/
sources.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
package repo
import (
"fmt"
"strings"
)
type Sources struct {
Sources map[string]*Source `json:"sources,omitempty"` // the key is the sha of the database
}
func NewSources() *Sources {
return &Sources{
Sources: make(map[string]*Source),
}
}
func (d *Sources) Add(name, url string) *Source {
if _, ok := d.Sources[name]; !ok {
d.Sources[name] = NewSource(name, url)
}
return d.Sources[name]
}
func (d *Sources) CountInDB() int {
db := Conn()
defer db.Close()
var count int
row := db.QueryRow("SELECT COUNT(1) FROM sources")
row.Scan(&count)
return count
}
func (d *Sources) Upsert() {
if len(d.Sources) == 0 {
return
}
rows := d.insValues()
query := fmt.Sprintf(d.ins(), strings.Join(rows, ",\n"))
db := Conn()
defer db.Close()
ExecuteQuery(db, query)
}
func (d *Sources) ins() string {
return `INSERT INTO sources (uid, name, url)
VALUES %s
ON CONFLICT (uid) DO NOTHING;`
}
func (d *Sources) insValues() []string {
var rows []string
for name, source := range d.Sources {
rows = append(rows,
fmt.Sprintf("('%s', '%s', '%s')",
source.UID, name, source.URL))
}
return rows
}