-
Notifications
You must be signed in to change notification settings - Fork 0
/
boardgame.go
158 lines (107 loc) · 2.42 KB
/
boardgame.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package models
import (
"database/sql"
"strconv"
_ "github.com/mattn/go-sqlite3"
)
var DB *sql.DB
type Boardgame struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
}
func ConnectDatabase() error {
db, err := sql.Open("sqlite3", "./boardgame-scores.db")
if err != nil {
return err
}
DB = db
return nil
}
func GetGames(count int) ([]Boardgame, error) {
rows, err := DB.Query("SELECT id, name, description from boardgames LIMIT " + strconv.Itoa(count))
if err != nil {
return nil, err
}
defer rows.Close()
games := make([]Boardgame, 0)
for rows.Next() {
singleGame := Boardgame{}
err = rows.Scan(&singleGame.ID, &singleGame.Name, &singleGame.Description)
if err != nil {
return nil, err
}
games = append(games, singleGame)
}
err = rows.Err()
if err != nil {
return nil, err
}
return games, err
}
func GetGameById(id string) (Boardgame, error) {
stmt, err := DB.Prepare("SELECT id, name, description from boardgames WHERE id = ?")
if err != nil {
return Boardgame{}, err
}
game := Boardgame{}
sqlErr := stmt.QueryRow(id).Scan(&game.ID, &game.Name, &game.Description)
if sqlErr != nil {
if sqlErr == sql.ErrNoRows {
return Boardgame{}, nil
}
return Boardgame{}, sqlErr
}
return game, nil
}
func AddGame(newGame Boardgame) (bool, error) {
tx, err := DB.Begin()
if err != nil {
return false, err
}
stmt, err := tx.Prepare("INSERT INTO boardgames (name, description) VALUES (?, ?)")
if err != nil {
return false, err
}
defer stmt.Close()
_, err = stmt.Exec(newGame.Name, newGame.Description)
if err != nil {
return false, err
}
tx.Commit()
return true, nil
}
func UpdateGame(ourGame Boardgame, id int) (bool, error) {
tx, err := DB.Begin()
if err != nil {
return false, err
}
stmt, err := tx.Prepare("UPDATE boardgames SET name = ?, description = ? WHERE id = ?")
if err != nil {
return false, err
}
defer stmt.Close()
_, err = stmt.Exec(ourGame.Name, ourGame.Description, id)
if err != nil {
return false, err
}
tx.Commit()
return true, nil
}
func DeleteGame(gameId int) (bool, error) {
tx, err := DB.Begin()
if err != nil {
return false, err
}
stmt, err := DB.Prepare("DELETE from boardgames where id = ?")
if err != nil {
return false, err
}
defer stmt.Close()
_, err = stmt.Exec(gameId)
if err != nil {
return false, err
}
tx.Commit()
return true, nil
}