-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert.go
76 lines (72 loc) · 1.36 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
package database
import (
"database/sql"
)
// Add inserts a Node entry into the database if it doesn't exist already.
func (db *DB) Add(input Node) (err error) {
// Attempt to grab lock.
db.lock.Lock()
defer db.lock.Unlock()
// Ping to check that database connection still exists.
err = db.conn.Ping()
if err != nil {
return err
}
_, err = db.get(input.ID)
if err != nil {
if err == sql.ErrNoRows {
err = db.insert(input)
} else {
return err
}
} else {
err = db.update(input)
}
return err
}
// Insert adds a Node entry to the database.
func (db *DB) insert(entry Node) (err error) {
stmt, err := db.conn.Prepare(
`INSERT INTO nodes(
id,
username,
email,
total_space,
used_space,
last_seen,
first_seen
) VALUES(?,?,?,?,?,datetime('now'),datetime('now'));`)
if err != nil {
return err
}
_, err = stmt.Exec(
entry.ID,
entry.Username,
entry.Email,
entry.TotalSpace,
entry.UsedSpace,
)
return err
}
// update changes a file's status in the database.
func (db *DB) update(entry Node) (err error) {
stmt, err := db.conn.Prepare(
`UPDATE nodes SET
username = ?,
email = ?,
total_space = ?,
used_space = ?,
last_seen = datetime('now')
WHERE id = ?;`)
if err != nil {
return err
}
_, err = stmt.Exec(
entry.Username,
entry.Email,
entry.TotalSpace,
entry.UsedSpace,
entry.ID,
)
return err
}