-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_type.go
97 lines (82 loc) · 1.8 KB
/
test_type.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
package gopsql
import (
"errors"
"fmt"
)
type Book struct {
ID int `column_type:"SERIAL primary key" column_skip_insert:"yes"`
Title string `column_type:"varchar(255)"`
Author string `column_type:"varchar(255)"`
Pages []Page `column_skip:"yes"`
}
// Implement Saveable interface
func (b Book) GetID() int {
return b.ID
}
// Implement Saveable interface
func (b Book) SetID(id int) {
b.ID = id
}
func (b *Book) Save() error {
if b.ID > 0 { //Exists, update
return UpdateExisting(*b)
}
// New
return InsertNew(*b).Scan(&b.ID)
}
func (b *Book) Find() error {
rows, err := GetFiltered(*b, "ID", fmt.Sprintf("%v", b.ID))
if err != nil {
return err
}
defer rows.Close()
if rows.Next() {
err := rows.Scan(&b.ID, &b.Title, &b.Author)
if err != nil {
return err
}
b.Pages, err = GetAllPagesForBook(b.ID)
return err
}
return errors.New("No matching book found")
}
func (b *Book) Delete() error {
return Delete(*b)
}
type Page struct {
ID int `column_type:"SERIAL primary key" column_skip_insert:"yes" column_order_by:"yes"`
BookID int `column_type:"SERIAL references Book(ID)"`
Content string `column_type:"TEXT"`
}
// Implement Saveable
func (p Page) GetID() int {
return p.ID
}
// Implement Saveable interface
func (p Page) SetID(id int) {
p.ID = id
}
func (p *Page) Save() error {
if p.ID > 0 { // Exists, update
return UpdateExisting(*p)
}
// New
return InsertNew(*p).Scan(&p.ID)
}
func GetAllPagesForBook(bookID int) ([]Page, error) {
var res []Page
rows, err := GetFiltered(Page{}, "BookID", fmt.Sprintf("%d", bookID))
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
page := Page{}
err := rows.Scan(&page.ID, &page.BookID, &page.Content)
if err != nil {
return nil, err
}
res = append(res, page)
}
return res, nil
}