/
insert.go
88 lines (80 loc) · 1.68 KB
/
insert.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
package database
import (
"database/sql"
"log"
"strings"
"github.com/alecbcs/lookout/results"
)
// Add checks if an entry is already in the database and
// if found updates the entry, else it adds the entry.
func Add(db *sql.DB, entry *results.Entry) {
result, found := Get(db, entry.ID)
if found == nil {
results.Patch(result, entry)
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
Update(tx, result)
err = tx.Commit()
if err != nil {
log.Fatal(err)
}
} else {
Insert(db, entry)
}
}
// Insert adds a new entry into the database.
func Insert(db *sql.DB, entry *results.Entry) {
// Ping to check that database connection still exists.
err := db.Ping()
if err != nil {
log.Fatal(err)
}
stmt, err := db.Prepare(
"INSERT INTO appdata(" +
"id," +
"latestURL," +
"latestVERSION," +
"currentURL," +
"currentVERSION," +
"upToDate" +
") VALUES(?,?,?,?,?,?);")
if err != nil {
log.Fatal(err)
}
_, err = stmt.Exec(
entry.ID,
entry.LatestURL,
strings.Join(entry.LatestVersion, "."),
entry.CurrentURL,
strings.Join(entry.CurrentVersion, "."),
entry.UpToDate)
if err != nil {
log.Fatal(err)
}
}
// Update patches an existing db entry with new data.
func Update(tx *sql.Tx, entry *results.Entry) {
stmt, err := tx.Prepare(
"UPDATE appdata SET " +
"latestURL = ?," +
"latestVERSION = ?," +
"currentURL = ?," +
"currentVERSION = ?," +
"upToDate = ?" +
"WHERE id = ?;")
if err != nil {
log.Fatal(err)
}
_, err = stmt.Exec(
entry.LatestURL,
strings.Join(entry.LatestVersion, "."),
entry.CurrentURL,
strings.Join(entry.CurrentVersion, "."),
entry.UpToDate,
entry.ID)
if err != nil {
log.Fatal(err)
}
}