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
75 lines (60 loc) · 1.58 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
package main
import (
"errors"
"fmt"
"os"
// Using postgres sql driver
_ "github.com/lib/pq"
"github.com/fengjh/gorm-default-value/callbacks"
"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
Name string `sql:"not null"`
Price float64 `sql:"not null;default:'0.01'"`
Category string `sql:"not null;default:'clothing'"`
}
func (p *Product) BeforeCreate(scope *gorm.Scope) {
fmt.Printf("BeforeCreate --> %v\n", p.Price)
fmt.Printf("BeforeCreate --> %v\n", p.Category)
}
func (p *Product) AfterCreate(scope *gorm.Scope) {
fmt.Printf("AfterCreate --> %v\n", p.Price)
fmt.Printf("AfterCreate --> %v\n", p.Category)
}
func (p *Product) BeforeCreateTransactionCommit(scope *gorm.Scope) {
fmt.Printf("BeforeCreateTransactionCommit --> %v\n", p.Price)
fmt.Printf("BeforeCreateTransactionCommit --> %v\n", p.Category)
}
func (p *Product) AfterCreateTransactionCommit(scope *gorm.Scope) {
fmt.Printf("AfterCreateTransactionCommit --> %v\n", p.Price)
fmt.Printf("AfterCreateTransactionCommit --> %v\n", p.Category)
}
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)
}
// Register custom Gorm callbacks
callbacks.RegisterCallbacks(DB)
}
func migrate() {
DB.DropTableIfExists(&Product{})
DB.AutoMigrate(&Product{})
}