-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase_interface.go
84 lines (69 loc) · 1.84 KB
/
database_interface.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
package main
import (
"database/sql"
"log"
"os"
_ "github.com/mattn/go-sqlite3"
"time"
)
var err error
var st *sql.Stmt
// checkDatabase will check if the db already exists else it will create it
func checkDatabase() {
var info os.FileInfo
info, err = os.Stat(configuration.DBName)
if !os.IsNotExist(err) {
log.Print("Db already created")
}
// Directory doesn't exist so we will create it
log.Println("Creating db file")
os.Create(configuration.DBName)
time.Sleep(1000000000) // delay to give system time to create file just in case
if info.IsDir(){
log.Panic("A directory with db name.... not gonna work")
}
db, err := sql.Open("sqlite3", "db.sqlite3")
checkErr(err)
st, err = db.Prepare("CREATE TABLE IF NOT EXISTS people " +
"(dni VARCHAR PRIMARY KEY, " +
"name TEXT)" )
res, err := st.Exec()
st, err = db.Prepare("CREATE TABLE IF NOT EXISTS ticket " +
"(id INTEGER NOT NULL, " +
"hash binary(20), dni VARCHAR, PRIMARY KEY (id))" )
res, err = st.Exec()
checkErr(err)
log.Println(res)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func insertData( students []Student) {
log.Print("Inserting People data to db")
db, err := sql.Open("sqlite3", "db.sqlite3")
checkErr(err)
for _, student := range students {
st, err := db.Prepare("SELECT dni, name FROM people WHERE dni=$1 ")
checkErr(err)
rows, err := st.Query(student.Dni)
checkErr(err)
if !rows.Next() {
st, err = db.Prepare("INSERT INTO people (dni, name) VALUES (?, ?)" )
checkErr(err)
_ , err = st.Exec(student.Dni, student.Name)
checkErr(err)
}
_ = rows.Close()
for j := 0; j < len(student.Keys); j++ {
st, err = db.Prepare("INSERT INTO ticket (dni, hash) VALUES (?, ?)" )
checkErr(err)
_ , err = st.Exec(student.Dni, student.Keys[j])
checkErr(err)
}
}
db.Close()
log.Print("People data saved")
}