/
sql_db.go
64 lines (55 loc) · 1.46 KB
/
sql_db.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
package base
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
type SQLGarinDB struct {
AbstractGarinDB
Handle *sqlx.DB
}
func (self *SQLGarinDB) Open() {
db, err := sqlx.Open(self.dbType, self.dbArgs)
if err != nil {
Die(err)
}
self.Handle = db
self.createIfNotExists()
}
func (self *SQLGarinDB) Close() {
self.Handle.Close()
}
func (self *SQLGarinDB) checkIfExists() bool {
if dbExists {
return true
}
_, err := self.Handle.Exec("select * from destinations limit 1")
if err != nil {
return false
} else {
dbExists = true
return true
}
}
func (self *SQLGarinDB) createIfNotExists() {
creationMutex.Lock()
self._createIfNotExists()
creationMutex.Unlock()
}
func (self *SQLGarinDB) _createIfNotExists() {
if self.checkIfExists() {
return
}
schema := `
create table destinations (source_ip VARCHAR(15), destination_ip VARCHAR(15), server_name VARCHAR(100), protocol VARCHAR(10),timestamp DATE);
`
// exec the schema or fail; multi-statement Exec behavior varies between
// database drivers; pq will exec them all, sqlite3 won't, ymmv
self.Handle.MustExec(schema)
}
func (self *SQLGarinDB) RecordDestination(destination *Destination) {
_, err := self.Handle.NamedExec("INSERT INTO "+DESTINATIONS_TABLE_NAME+" (source_ip, destination_ip, server_name, protocol, timestamp) VALUES(:source_ip, :destination_ip, :server_name, :protocol, :timestamp)", destination)
if err != nil {
panic(err)
}
}