generated from fun-stack/example
-
Notifications
You must be signed in to change notification settings - Fork 4
/
domain_penalties.go
69 lines (56 loc) · 1.59 KB
/
domain_penalties.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
package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"strconv"
"github.com/pkg/errors"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type DomainPenalty struct {
Domain string `gorm:"primaryKey"`
AvgPenalty float64
}
func (ndb newsDatabase) importPenaltiesData(sqliteDataDir string) error {
frontpageDatabaseFilename := fmt.Sprintf("%s/%s", sqliteDataDir, sqliteDataFilename)
db, err := gorm.Open(sqlite.Open(frontpageDatabaseFilename), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
err = db.AutoMigrate(&DomainPenalty{})
if err != nil {
return errors.Wrap(err, "db.AutoMigrate Domain Penalties table")
}
// Open domain penalty seed data file as CSV
b, _ := resources.ReadFile("seed/domain-penalties.csv")
buf := bytes.NewBuffer(b)
r := csv.NewReader(buf)
// Read the header row.
_, err = r.Read()
if err != nil {
return errors.Wrap(err, "missing header row in domain penalties data")
}
for {
record, err := r.Read()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return errors.Wrapf(err, "Parsing penalty CSV")
}
avgPenalty, err := strconv.ParseFloat(record[1], 64)
if err != nil {
return errors.Wrapf(err, "Parsing penalty record %s, %s", record[0], record[1])
}
err = db.Clauses(clause.OnConflict{ // adding this onConflict clause makes the create into an upsert
UpdateAll: true,
}).Create(&DomainPenalty{Domain: record[0], AvgPenalty: avgPenalty}).Error
if err != nil {
return errors.Wrapf(err, "Parsing inserting domain penalty %s, %f", record[0], avgPenalty)
}
}
return nil
}