This repository has been archived by the owner on Aug 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
76 lines (62 loc) · 1.34 KB
/
main.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
package main
import (
"errors"
"fmt"
"os"
// Using postgres sql driver
_ "github.com/lib/pq"
"github.com/jinzhu/gorm"
)
var (
// DB returns a gorm.DB interface, it is used to access to database
DB *gorm.DB
)
type Product struct {
gorm.Model
Title string `sql:"not null"`
Description string `sql:"not null;size:2000"`
}
func init() {
initDB()
migrate()
}
func initDB() {
var err error
var db gorm.DB
dbParams := os.Getenv("DB_PARAMS")
if dbParams == "" {
panic(errors.New("DB_PARAMS environment variable not set"))
}
db, err = gorm.Open("postgres", fmt.Sprintf(dbParams))
if err == nil {
DB = &db
} else {
panic(err)
}
}
func migrate() {
DB.DropTableIfExists(&Product{})
DB.AutoMigrate(&Product{})
}
func loadProductsWithRows() (products []Product, err error) {
products = []Product{}
rows, err := DB.Model(&Product{}).Select("id, title, description, created_at, updated_at, deleted_at").Rows()
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
product := Product{}
rows.Scan(&product.ID, &product.Title, &product.Description, &product.CreatedAt, &product.UpdatedAt, &product.DeletedAt)
products = append(products, product)
}
return
}
func loadProductsWithFind() (products []Product, err error) {
products = []Product{}
err = DB.Find(&products).Error
if err != nil {
return
}
return
}