-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.go
More file actions
130 lines (104 loc) · 2.26 KB
/
store.go
File metadata and controls
130 lines (104 loc) · 2.26 KB
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
package main
import (
"database/sql"
"fmt"
)
type Store struct {
db *sql.DB
}
type Storage interface {
CreateBook(Book) error
CreateHighlights([]Highlight) error
GetBookByISBN(string) (*Book, error)
GetRandomHighlights(limit, userId int) ([]*Highlight, error)
GetUsers() ([]*User, error)
}
func NewStore(db *sql.DB) *Store {
return &Store{db: db}
}
func (s *Store) CreateBook(b Book) error {
_, err := s.db.Exec(`
INSERT INTO books (isbn, title, authors)
VALUES (?, ?, ?)
`, b.ISBN, b.Title, b.Authors)
if err != nil {
return err
}
return nil
}
func (s *Store) CreateHighlights(hs []Highlight) error {
values := []interface{}{}
query := "INSERT INTO highlights (text, location, note, userId, bookId) VALUES "
for _, h := range hs {
query += "(?, ?, ?, ?, ?),"
values = append(values, h.Text, h.Location, h.Note, h.UserID, h.BookID)
}
query = query[:len(query)-1]
_, err := s.db.Exec(query, values...)
if err != nil {
return err
}
return nil
}
func (s *Store) GetBookByISBN(isbn string) (*Book, error) {
rows, err := s.db.Query(`
SELECT * FROM books WHERE isbn = ?
`, isbn)
if err != nil {
return nil, err
}
book := new(Book)
for rows.Next() {
if err := rows.Scan(&book.ISBN, &book.Title, &book.Authors, &book.CreatedAt); err != nil {
return nil, err
}
}
if book.ISBN == "" {
return nil, fmt.Errorf("book not found")
}
return book, nil
}
func (s *Store) GetRandomHighlights(n, userID int) ([]*Highlight, error) {
rows, err := s.db.Query("SELECT * FROM highlights WHERE userId = ? ORDER BY RAND() LIMIT ?", userID, n)
if err != nil {
return nil, err
}
var highlights []*Highlight
for rows.Next() {
h := new(Highlight)
if err := rows.Scan(
&h.ID,
&h.Text,
&h.Location,
&h.Note,
&h.UserID,
&h.BookID,
&h.CreatedAt,
); err != nil {
return nil, err
}
highlights = append(highlights, h)
}
return highlights, nil
}
func (s *Store) GetUsers() ([]*User, error) {
rows, err := s.db.Query("SELECT * FROM users")
if err != nil {
return nil, err
}
users := make([]*User, 0)
for rows.Next() {
u := new(User)
if err := rows.Scan(
&u.ID,
&u.Email,
&u.FirstName,
&u.LastName,
&u.CreatedAt,
); err != nil {
return nil, err
}
users = append(users, u)
}
return users, nil
}