-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
68 lines (52 loc) · 1.52 KB
/
model.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
package main
import (
"database/sql"
)
type book struct {
ID string `json:"ID"`
Title string `json:"title"`
Author string `json:"author"`
Publisher string `json:"publisher"`
Date string `json:"date"`
Rating int `json:"rating"`
Status string `json:"status"`
}
func (b *book) getBook(db *sql.DB) error {
return db.QueryRow("SELECT * FROM books WHERE id=$1",
b.ID).Scan(&b.Title, &b.Author, &b.Publisher, &b.Date, &b.Rating, &b.Status)
}
func (b *book) updateBook(db *sql.DB) error {
_, err :=
db.Exec("UPDATE books SET title=$1, author=$2, publisher=$3, date=$4, rating=$5, status=$6 WHERE id=$7",
b.Title, b.Author, b.Publisher, b.Date, b.Rating, b.Status, b.ID)
return err
}
func (b *book) deleteBook(db *sql.DB) error {
_, err := db.Exec("DELETE FROM books WHERE id=$1", b.ID)
return err
}
func (b *book) createBook(db *sql.DB) error {
err := db.QueryRow(
"INSERT INTO books(title, author, publisher, date, rating, status) VALUES($1, $2, $3, $4, $5, $6) RETURNING id",
b.Title, b.Author, b.Publisher, b.Date, b.Rating, b.Status).Scan(&b.ID)
if err != nil {
return err
}
return nil
}
func getBooks(db *sql.DB, start, count int) ([]book, error) {
rows, err := db.Query("SELECT * FROM books")
if err != nil {
return nil, err
}
defer rows.Close()
books := []book{}
for rows.Next() {
var b book
if err := rows.Scan(&b.ID, &b.Title, &b.Author, &b.Publisher, &b.Date, &b.Rating, &b.Status); err != nil {
return nil, err
}
books = append(books, b)
}
return books, nil
}