forked from Sina-Ghaderi/go-ipfm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlf.go
130 lines (115 loc) · 2.35 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
123
124
125
126
127
128
129
130
package main
import (
"database/sql"
"log"
"time"
_ "github.com/mattn/go-sqlite3"
)
type datausage struct {
ip string
tx, rx uint
tstamp string
}
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,
RX TEXT,
TX TEXT,
TIME TEXT,
PRIMARY KEY (IP, TIME)
);
`
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(?, ?, ?, ?)
`
sqlSumitem := `
INSERT OR REPLACE INTO items(
IP,
RX,
TX,
TIME
) values(
?,
(SELECT RX FROM items WHERE IP=? AND TIME=?)+?,
(SELECT TX FROM items WHERE IP=? AND TIME=?)+?,
?)
`
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, time.Now().Format(captureMask), item.rx, item.ip, time.Now().Format(captureMask), item.tx, time.Now().Format(captureMask))
if err != nil {
log.Fatal(err)
}
} else {
_, err := stmt.Exec(item.ip, item.rx, item.tx, time.Now().Format(captureMask))
if err != nil {
log.Fatal(err)
}
}
}
}
func readItem(db *sql.DB, date string) map[string]datausage {
// read and return data from database
sqlReadall := `
SELECT IP, RX, TX, TIME FROM items
WHERE TIME = ?
ORDER BY TIME DESC
`
stmt, err := db.Prepare(sqlReadall)
if err != nil {
log.Fatal(err)
}
rows, err := stmt.Query(date)
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, &item.tstamp); 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 = ? and TIME = ?`
err := db.QueryRow(sqlStmt, qur, time.Now().Format(captureMask)).Scan(&qur)
if err != nil {
if err != sql.ErrNoRows {
log.Fatal(err)
}
return false
}
return true
}