Skip to content
This repository was archived by the owner on Aug 29, 2021. It is now read-only.

Commit b722a81

Browse files
committed
Initial commit
0 parents  commit b722a81

File tree

4 files changed

+240
-0
lines changed

4 files changed

+240
-0
lines changed

README.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Gorm Default Value
2+
3+
Gorm takes the default value back from database after you create a new record with no value specified.
4+
5+
## Quick Started
6+
7+
# Get code
8+
$ go get -u github.com/fengjh/gorm-default-value
9+
10+
# Set environment variables
11+
$ source .env
12+
13+
# Setup postgres database
14+
$ postgres=# CREATE USER gorm_default_value;
15+
$ postgres=# CREATE DATABASE gorm_default_value OWNER gorm_default_value;
16+
17+
# Run Application
18+
$ go test -v
19+
20+
## Test Result
21+
22+
=== RUN TestCreateProductPriceWithDefaultValue
23+
BeforeCreate --> 0
24+
AfterCreate --> 0.01
25+
BeforeCreateTransactionCommit --> 0.01
26+
AfterCreateTransactionCommit --> 0.01
27+
--- PASS: TestCreateProductPriceWithDefaultValue (0.00s)
28+
=== RUN TestSaveProductPriceWithDefaultValue
29+
BeforeCreate --> 0
30+
AfterCreate --> 0.01
31+
BeforeCreateTransactionCommit --> 0.01
32+
AfterCreateTransactionCommit --> 0.01
33+
--- PASS: TestSaveProductPriceWithDefaultValue (0.00s)
34+
PASS
35+
ok github.com/fengjh/gorm-default-value 0.072s

callbacks/callbacks.go

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Package callbacks extends default Gorm callbacks such as
2+
// executing callback after create transaction commit.
3+
package callbacks
4+
5+
import "github.com/jinzhu/gorm"
6+
7+
// CreateTransactionCommitCallback defines an interface
8+
// for executing callback before/after commit the create
9+
// transaction.
10+
type CreateTransactionCommitCallback interface {
11+
BeforeCreateTransactionCommit(scope *gorm.Scope)
12+
AfterCreateTransactionCommit(scope *gorm.Scope)
13+
}
14+
15+
func beforeCreateTransaction(scope *gorm.Scope) {
16+
if !scope.HasError() {
17+
if createTransactionCommitCallback, ok := scope.Value.(CreateTransactionCommitCallback); ok {
18+
createTransactionCommitCallback.BeforeCreateTransactionCommit(scope)
19+
}
20+
}
21+
}
22+
23+
func afterCreateTransaction(scope *gorm.Scope) {
24+
if !scope.HasError() {
25+
if createTransactionCommitCallback, ok := scope.Value.(CreateTransactionCommitCallback); ok {
26+
createTransactionCommitCallback.AfterCreateTransactionCommit(scope)
27+
}
28+
}
29+
}
30+
31+
// RegisterCallbacks registers custom Gorm callbacks.
32+
func RegisterCallbacks(db *gorm.DB) {
33+
callback := db.Callback()
34+
35+
callback.Create().Before("gorm:commit_or_rollback_transaction").Register("callbacks:before_create_transaction", beforeCreateTransaction)
36+
callback.Create().After("gorm:commit_or_rollback_transaction").Register("callbacks:after_create_transaction", afterCreateTransaction)
37+
}

main.go

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"os"
7+
8+
// Using postgres sql driver
9+
_ "github.com/lib/pq"
10+
11+
"github.com/fengjh/gorm-default-value/callbacks"
12+
"github.com/jinzhu/gorm"
13+
)
14+
15+
var (
16+
// DB returns a gorm.DB interface, it is used to access to database
17+
DB *gorm.DB
18+
)
19+
20+
type Product struct {
21+
gorm.Model
22+
Name string `sql:"not null"`
23+
Price float64 `sql:"not null;default:'0.01'"`
24+
Category string `sql:"not null;default:'clothing'"`
25+
}
26+
27+
func (p *Product) BeforeCreate(scope *gorm.Scope) {
28+
fmt.Printf("BeforeCreate --> %v\n", p.Price)
29+
fmt.Printf("BeforeCreate --> %v\n", p.Category)
30+
}
31+
32+
func (p *Product) AfterCreate(scope *gorm.Scope) {
33+
fmt.Printf("AfterCreate --> %v\n", p.Price)
34+
fmt.Printf("AfterCreate --> %v\n", p.Category)
35+
}
36+
37+
func (p *Product) BeforeCreateTransactionCommit(scope *gorm.Scope) {
38+
fmt.Printf("BeforeCreateTransactionCommit --> %v\n", p.Price)
39+
fmt.Printf("BeforeCreateTransactionCommit --> %v\n", p.Category)
40+
}
41+
42+
func (p *Product) AfterCreateTransactionCommit(scope *gorm.Scope) {
43+
fmt.Printf("AfterCreateTransactionCommit --> %v\n", p.Price)
44+
fmt.Printf("AfterCreateTransactionCommit --> %v\n", p.Category)
45+
}
46+
47+
func init() {
48+
initDB()
49+
migrate()
50+
}
51+
52+
func initDB() {
53+
var err error
54+
var db *gorm.DB
55+
56+
dbParams := os.Getenv("DB_PARAMS")
57+
if dbParams == "" {
58+
panic(errors.New("DB_PARAMS environment variable not set"))
59+
}
60+
61+
db, err = gorm.Open("postgres", fmt.Sprintf(dbParams))
62+
if err == nil {
63+
DB = db
64+
} else {
65+
panic(err)
66+
}
67+
68+
// Register custom Gorm callbacks
69+
callbacks.RegisterCallbacks(DB)
70+
}
71+
72+
func migrate() {
73+
DB.DropTableIfExists(&Product{})
74+
DB.AutoMigrate(&Product{})
75+
}

main_test.go

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package main
2+
3+
import (
4+
"os"
5+
"testing"
6+
)
7+
8+
func TestMain(m *testing.M) {
9+
initDB()
10+
migrate()
11+
12+
retCode := m.Run()
13+
14+
os.Exit(retCode)
15+
}
16+
17+
func TestCreateProductWithNoValueSpecified(t *testing.T) {
18+
product := Product{Name: "Create product with no value specified"}
19+
20+
if product.Price != 0 {
21+
t.Fatalf("expected new product's price is zero, but got %v", product.Price)
22+
}
23+
24+
if product.Category != "" {
25+
t.Fatalf("expected new product's category is zero, but got %v", product.Category)
26+
}
27+
28+
err := DB.Create(&product).Error
29+
30+
if err != nil {
31+
t.Fatalf("Unexpected error: %v", err)
32+
}
33+
34+
if product.Price != 0.01 {
35+
t.Fatalf("expected product.Price with default value 0.01, but got %v", product.Price)
36+
}
37+
38+
if product.Category != "clothing" {
39+
t.Fatalf("expected product.Price with default value clothing, but got %v", product.Category)
40+
}
41+
}
42+
43+
func TestSaveProductPriceWithNoValueSpecified(t *testing.T) {
44+
product := Product{Name: "Save product with no value specified"}
45+
46+
if product.Price != 0 {
47+
t.Fatalf("expected new product's price is zero, but got %v", product.Price)
48+
}
49+
50+
if product.Category != "" {
51+
t.Fatalf("expected new product's category is zero, but got %v", product.Category)
52+
}
53+
54+
err := DB.Save(&product).Error
55+
56+
if err != nil {
57+
t.Fatalf("Unexpected error: %v", err)
58+
}
59+
60+
if product.Price != 0.01 {
61+
t.Fatalf("expected product.Price with default value 0.01, but got %v", product.Price)
62+
}
63+
64+
if product.Category != "clothing" {
65+
t.Fatalf("expected product.Price with default value clothing, but got %v", product.Category)
66+
}
67+
}
68+
69+
func TestCreateProductPriceWithZeroValueSpecified(t *testing.T) {
70+
product := Product{Name: "Product with zero value specified", Price: 0.0}
71+
72+
if product.Price != 0 {
73+
t.Fatalf("expected new product's price is zero, but got %v", product.Price)
74+
}
75+
76+
if product.Category != "" {
77+
t.Fatalf("expected new product's category is zero, but got %v", product.Category)
78+
}
79+
80+
err := DB.Create(&product).Error
81+
82+
if err != nil {
83+
t.Fatalf("Unexpected error: %v", err)
84+
}
85+
86+
if product.Price != 0.01 {
87+
t.Fatalf("expected product.Price with default value 0.01, but got %v", product.Price)
88+
}
89+
90+
if product.Category != "clothing" {
91+
t.Fatalf("expected product.Price with default value clothing, but got %v", product.Category)
92+
}
93+
}

0 commit comments

Comments
 (0)