-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
374 lines (282 loc) · 7.33 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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package db
import (
"database/sql"
"errors"
"fmt"
"github.com/mattn/go-sqlite3"
"log"
)
/*
SQLiteRepository struct abstracts SQLite database
db: reference to a database, enabling db operations
currentTable: the table that certain statements will be ran against
*/
type SQLiteRepository struct {
db *sql.DB
currentTable string
}
/*
SQLiteRepository struct constructor
Given a proper SQL database reference. A reference to a new SQLiteRepository
will be returned.
*/
func NewSQLiteRepository(db *sql.DB) (*SQLiteRepository, error) {
err := validateTableName(DEFAULT_TABLE)
if err != nil {
return nil, err
}
return &SQLiteRepository{
db: db,
currentTable: DEFAULT_TABLE,
}, nil
}
func (r *SQLiteRepository) CurrentTable() string {
return r.currentTable
}
/*
Createas the default table.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) Initialize() error {
query := fmt.Sprintf(createTable, DEFAULT_TABLE)
_, err := r.db.Exec(query)
if err != nil {
log.Fatalf("cannot create table: %q", err)
}
return err
}
/*
Inserts en Entry into currentTable and returns the reference of the Entry
with an ID given to it from the database.
Logs to console and terminates execution if there is an issue with SQLer
*/
func (r *SQLiteRepository) Insert(e Entry) (*Entry, error) {
err := validateEntry(&e)
if err != nil {
return nil, err
}
query := fmt.Sprintf(insert, r.currentTable)
res, err := r.db.Exec(query, e.Name, e.Username, e.Email)
if err != nil {
var sqliteErr sqlite3.Error
if errors.As(err, &sqliteErr) {
if errors.Is(sqliteErr.ExtendedCode, sqlite3.ErrConstraintUnique) {
return nil, ErrDuplicate
}
}
log.Fatalf("cannot insert record into table: %q", err)
}
id, err := res.LastInsertId()
if err != nil {
return nil, err
}
e.ID = id
return &e, nil
}
/*
Queries currentTable return all the Entries
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) All() (all []*Entry, err error) {
query := fmt.Sprintf(selectAll, r.currentTable)
rows, err := r.db.Query(query)
if err != nil {
log.Fatalf("cannot query table: %q", err)
}
defer rows.Close()
for rows.Next() {
e := new(Entry)
err := rows.Scan(&e.ID, &e.Name, &e.Username, &e.Email)
if err != nil {
log.Fatalf("cannot scan row: %q", err)
}
all = append(all, e)
}
return all, nil
}
/*
Queries currentTable to return a reference to an Entry when given a valid
username.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) GetByUsername(username string) (*Entry, error) {
err := validateField(username, usernamePattern, ErrInvalidUsername)
if err != nil {
return nil, err
}
query := fmt.Sprintf(selectByUername, r.currentTable)
row := r.db.QueryRow(query, username)
e := new(Entry)
err = row.Scan(&e.ID, &e.Name, &e.Username, &e.Email)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
}
return e, nil
}
/*
Updates an Entry in the currentTable given it's username with the newly
updated Entry. Returns the updated entry if there are no issues.
If there are no updates no Entry is returned and corresponding
error is returned also.
Logs error to console and terminates execution if there is an issue with the
SQL.
*/
func (r *SQLiteRepository) Update(username string, u *Entry) (*Entry, error) {
err := validateField(username, usernamePattern, ErrInvalidUsername)
if err != nil {
return nil, err
}
err = validateEntry(u)
if err != nil {
return nil, err
}
query := fmt.Sprintf(update, r.currentTable)
res, err := r.db.Exec(query, u.Name, u.Username, u.Email,
username)
if err != nil {
log.Fatalf("cannot execute statement: %q", err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
log.Fatalf("cannot update record: %q", err)
}
if rowsAffected == 0 {
return nil, ErrUpdateFailed
}
return u, nil
}
/*
Deletes an Entry in the currentTable given a valid id.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) Delete(username string) error {
err := validateField(username, usernamePattern, ErrInvalidUsername)
if err != nil {
return err
}
query := fmt.Sprintf(delete, r.currentTable)
res, err := r.db.Exec(query, username)
if err != nil {
return err
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return ErrDeleteFailed
}
return nil
}
/*
Creates a new table within the database. currentTable is updated if the
table is valid and does not already exist.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) NewTable(tableName string) error {
exists, err := r.TableExists(tableName)
if err != nil && !errors.Is(err, ErrTableDoesNotExist) {
return err
}
if exists {
return ErrTableExists
}
query := fmt.Sprintf(createTable, tableName)
_, err = r.db.Exec(query, tableName)
if err != nil {
log.Fatalf("cannot create table: %q", err)
}
r.currentTable = tableName
return nil
}
/*
Updates the currentTable variable to to the tableName parameter given the
table exists and has a valid name.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) SwitchTable(tableName string) error {
exists, err := r.TableExists(tableName)
if err != nil {
return err
}
if !exists {
return ErrTableDoesNotExist
}
r.currentTable = tableName
return nil
}
/*
Wipes the current table.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) ClearTable() error {
query := fmt.Sprintf(clearTable, r.currentTable)
_, err := r.db.Exec(query)
if err != nil {
log.Fatalf("could not drop table: %q", err)
}
return nil
}
/*
Checks for the existence of a the given tableName and will return a bool
for the table's existence. If the table does not exist an error will be
returned to the caller as to why not.
Logs to console and terminates execution if there is an issue with SQL
*/
func (r *SQLiteRepository) TableExists(tableName string) (bool, error) {
err := validateTableName(tableName)
if err != nil {
return false, ErrInvalidTableName
}
rows, err := r.db.Query(selectTable, tableName)
if err != nil {
log.Fatalf("cannot query database: %q", err)
}
defer rows.Close()
if rows.Next() {
return true, nil
}
return false, ErrTableDoesNotExist
}
/*
Delete the table from the database that is passed. This function cannot and
will not delete the DEFAULT_TABLE.
*/
func (r *SQLiteRepository) DeleteTable(tableName string) error {
_, err := r.TableExists(tableName)
if err != nil {
return err
}
if tableName == DEFAULT_TABLE {
return ErrTableCannotBeDeleted
}
if r.currentTable == tableName {
r.currentTable = DEFAULT_TABLE
}
query := fmt.Sprintf(deleteTable, tableName)
_, err = r.db.Exec(query)
if err != nil {
return ErrTableCannotBeDeleted
}
return nil
}
/*
List all tables that the user created.
*/
func (r *SQLiteRepository) ListTables() (tables []string) {
rows, err := r.db.Query(listTables)
if err != nil {
log.Fatalf("cannot query db: %q", err)
}
for rows.Next() {
var s string
err = rows.Scan(&s)
if err != nil {
log.Fatalf("cannot get row: %q", err)
}
tables = append(tables, s)
}
return
}