-
Notifications
You must be signed in to change notification settings - Fork 22
/
book.go
102 lines (80 loc) · 2.22 KB
/
book.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
package main
import (
"fmt"
"time"
"github.com/lib/pq"
)
func getBook(bookID int) (Book, error) {
//Retrieve
res := Book{}
var id int
var name string
var author string
var pages int
var publicationDate pq.NullTime
err := db.QueryRow(`SELECT id, name, author, pages, publication_date FROM books where id = $1`, bookID).Scan(&id, &name, &author, &pages, &publicationDate)
if err == nil {
res = Book{ID: id, Name: name, Author: author, Pages: pages, PublicationDate: publicationDate.Time}
}
return res, err
}
func allBooks() ([]Book, error) {
//Retrieve
books := []Book{}
rows, err := db.Query(`SELECT id, name, author, pages, publication_date FROM books order by id`)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id int
var name string
var author string
var pages int
var publicationDate pq.NullTime
err = rows.Scan(&id, &name, &author, &pages, &publicationDate)
if err != nil {
return books, err
}
currentBook := Book{ID: id, Name: name, Author: author, Pages: pages}
if publicationDate.Valid {
currentBook.PublicationDate = publicationDate.Time
}
books = append(books, currentBook)
}
return books, err
}
func insertBook(name, author string, pages int, publicationDate time.Time) (int, error) {
//Create
var bookID int
err := db.QueryRow(`INSERT INTO books(name, author, pages, publication_date) VALUES($1, $2, $3, $4) RETURNING id`, name, author, pages, publicationDate).Scan(&bookID)
if err != nil {
return 0, err
}
fmt.Printf("Last inserted ID: %v\n", bookID)
return bookID, err
}
func updateBook(id int, name, author string, pages int, publicationDate time.Time) (int, error) {
//Create
res, err := db.Exec(`UPDATE books set name=$1, author=$2, pages=$3, publication_date=$4 where id=$5 RETURNING id`, name, author, pages, publicationDate, id)
if err != nil {
return 0, err
}
rowsUpdated, err := res.RowsAffected()
if err != nil {
return 0, err
}
return int(rowsUpdated), err
}
func removeBook(bookID int) (int, error) {
//Delete
res, err := db.Exec(`delete from books where id = $1`, bookID)
if err != nil {
return 0, err
}
rowsDeleted, err := res.RowsAffected()
if err != nil {
return 0, err
}
return int(rowsDeleted), nil
}