-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
106 lines (87 loc) · 2.49 KB
/
store.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
package main
import (
"database/sql"
"github.com/eyan422/Blog/CommonStruct"
"log"
)
type Store interface {
CreateArticle(article *CommonStruct.Article) (int64, error)
GetArticles() (articles []*CommonStruct.Article, err error)
GetArticle(id uint64) (articles *CommonStruct.Article, err error)
}
type dbStore struct {
db *sql.DB
}
func (store *dbStore) CreateArticle(article *CommonStruct.Article) (int64, error) {
res, err := store.db.Query("SELECT id, title, content, author from article where title = ? and content = ? and author = ?",
article.Title,
article.Content,
article.Author,
)
defer res.Close()
if err != nil {
return 0, err
}
var articleRetrieved *CommonStruct.Article
if res.Next() {
articleRetrieved = &CommonStruct.Article{}
if err := res.Scan(&articleRetrieved.Id, &articleRetrieved.Title, &articleRetrieved.Content, &articleRetrieved.Author); err != nil {
return 0, err
}
}
if articleRetrieved != nil && articleRetrieved.Id > 0 {
return -1, nil
}
query := "INSERT INTO article(title, content, author) VALUES (?, ?, ?)"
stmt, err := store.db.Prepare(query)
if err != nil {
log.Printf("Error %s when preparing SQL statement", err)
return 0, err
}
defer stmt.Close()
res1, err := stmt.Exec(article.Title, article.Content, article.Author)
rows, err := res1.RowsAffected()
if err != nil {
log.Printf("Error %s when finding rows affected", err)
return 0, err
}
log.Printf("%d record created ", rows)
lastId, err := res1.LastInsertId()
if err != nil {
return 0, err
}
return lastId, err
}
func (store *dbStore) GetArticles() (articles []*CommonStruct.Article, err error) {
rows, err := store.db.Query("SELECT id, title, content, author from article order by id")
defer rows.Close()
if err != nil {
return nil, err
}
for rows.Next() {
article := &CommonStruct.Article{}
if err := rows.Scan(&article.Id, &article.Title, &article.Content, &article.Author); err != nil {
return nil, err
}
articles = append(articles, article)
}
return articles, nil
}
func (store *dbStore) GetArticle(id uint64) (article *CommonStruct.Article, err error) {
res, err := store.db.Query("SELECT id, title, content, author from article where id = ?", id)
defer res.Close()
if err != nil {
return nil, err
}
if res.Next() {
article = &CommonStruct.Article{}
if err := res.Scan(&article.Id, &article.Title, &article.Content, &article.Author); err != nil {
return nil, err
}
}
return article, nil
}
var store Store
func InitStore(s Store) {
store = s
}