-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdatabase.go
71 lines (60 loc) · 1.77 KB
/
database.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func seedUserData(filename string) {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
byteValue, _ := ioutil.ReadAll(file)
var users []User
json.Unmarshal(byteValue, &users)
db, err := sql.Open("sqlite3", "data/users.db")
if err != nil {
panic(err)
}
defer db.Close()
dropTableQuery := "DROP TABLE IF EXISTS user;"
_, err = db.Exec(dropTableQuery)
if err != nil {
panic(err)
}
createTableQuery := "CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, company TEXT, title TEXT, email TEXT, phone TEXT, dob TEXT, ssn TEXT, salary NUMERIC, admin BOOLEAN);"
_, err = db.Exec(createTableQuery)
if err != nil {
panic(err)
}
for i := 0; i < len(users); i++ {
user := users[i]
insertUserQuery := fmt.Sprintf("INSERT INTO user VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s');", i+1, user.FirstName, user.LastName, user.Company, user.Title, user.Email, user.Phone, user.DOB, user.SSN, user.Salary, user.Admin)
_, err = db.Exec(insertUserQuery)
if err != nil {
panic(err)
}
}
}
func getUsers(search string) []User {
db, err := sql.Open("sqlite3", "data/users.db")
if err != nil {
panic(err)
}
selectUsersQuery := "SELECT * FROM user WHERE (first_name LIKE '%" + search + "%' OR last_name LIKE '%" + search + "%') AND admin == 'false';"
rows, err := db.Query(selectUsersQuery)
if err != nil {
panic(err)
}
var results []User
for rows.Next() {
var user User
_ = rows.Scan(&user.ID, &user.FirstName, &user.LastName, &user.Company, &user.Title, &user.Email, &user.Phone, &user.DOB, &user.SSN, &user.Salary, &user.Admin)
results = append(results, user)
}
rows.Close()
return results
}