-
Notifications
You must be signed in to change notification settings - Fork 1
/
sqlf.go
123 lines (107 loc) · 2.05 KB
/
sqlf.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
type datausage struct {
ip string
tx, rx uint
}
func initDB(filepath string) *sql.DB {
// initial database
db, err := sql.Open("sqlite3", filepath)
if err != nil {
log.Fatal(err)
}
return db
}
func createTable(db *sql.DB) {
// create table if not exists
sqlTable := `
CREATE TABLE IF NOT EXISTS items(
IP TEXT NOT NULL PRIMARY KEY,
RX TEXT,
TX TEXT,
TIME DATETIME
);
`
if _, err := db.Exec(sqlTable); err != nil {
log.Fatal(err)
}
}
func storeItem(db *sql.DB, items map[string]datausage) {
// store items in database
sqlAdditem := `
INSERT OR REPLACE INTO items(
IP,
RX,
TX,
TIME
) values(?, ?, ?, CURRENT_TIMESTAMP)
`
sqlSumitem := `
INSERT OR REPLACE INTO items(
IP,
RX,
TX,
TIME
) values(
?,
(SELECT RX FROM items WHERE IP=?)+?,
(SELECT TX FROM items WHERE IP=?)+?,
CURRENT_TIMESTAMP)
`
stmt, err := db.Prepare(sqlAdditem)
nstmt, err := db.Prepare(sqlSumitem)
defer stmt.Close()
defer nstmt.Close()
if err != nil {
log.Fatal(err)
}
for _, item := range items {
if ipExists(db, item.ip) {
_, err := nstmt.Exec(item.ip, item.ip, item.rx, item.ip, item.tx)
if err != nil {
log.Fatal(err)
}
} else {
_, err := stmt.Exec(item.ip, item.rx, item.tx)
if err != nil {
log.Fatal(err)
}
}
}
}
func readItem(db *sql.DB) map[string]datausage {
// read and return data from database
sqlReadall := `
SELECT IP, RX, TX FROM items
ORDER BY datetime(TIME) DESC
`
rows, err := db.Query(sqlReadall)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
result := make(map[string]datausage)
for rows.Next() {
item := datausage{}
if err := rows.Scan(&item.ip, &item.rx, &item.tx); err != nil {
log.Fatal(err)
}
result[item.ip] = item
}
return result
}
func ipExists(db *sql.DB, qur string) bool {
sqlStmt := `SELECT IP FROM items WHERE IP = ?`
err := db.QueryRow(sqlStmt, qur).Scan(&qur)
if err != nil {
if err != sql.ErrNoRows {
log.Fatal(err)
}
return false
}
return true
}