forked from revel/modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm.go
83 lines (68 loc) · 1.7 KB
/
gorm.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
package gormcontroller
import (
"database/sql"
"fmt"
"github.com/jinzhu/gorm"
gormdb "github.com/terhitormanen/modules/orm/gorm/app"
"github.com/terhitormanen/revel"
)
// Controller is a Revel controller with a pointer to the opened database.
type Controller struct {
*revel.Controller
DB *gorm.DB
}
func (c *Controller) setDB() revel.Result {
c.DB = gormdb.DB
return nil
}
// TxnController is a Revel controller with database transaction support (begin, commit and rollback).
type TxnController struct {
*revel.Controller
Txn *gorm.DB
}
// Begin begins a DB transaction.
func (c *TxnController) Begin() revel.Result {
txn := gormdb.DB.Begin()
if txn.Error != nil {
c.Log.Panic("Transaction begine error", "error", txn.Error)
}
c.Txn = txn
return nil
}
// Commit commits the database transition.
func (c *TxnController) Commit() revel.Result {
if c.Txn == nil {
return nil
}
c.Txn.Commit()
if c.Txn.Error != nil && c.Txn.Error != sql.ErrTxDone {
fmt.Println(c.Txn.Error)
panic(c.Txn.Error)
}
c.Txn = nil
return nil
}
// Rollback rolls back the transaction (eg. after a panic).
func (c *TxnController) Rollback() revel.Result {
if c.Txn == nil {
return nil
}
c.Txn.Rollback()
if c.Txn.Error != nil && c.Txn.Error != sql.ErrTxDone {
fmt.Println(c.Txn.Error)
panic(c.Txn.Error)
}
c.Txn = nil
return nil
}
func init() {
revel.OnAppStart(func() {
if revel.Config.BoolDefault("db.autoinit", true) {
gormdb.InitDB()
revel.InterceptMethod((*TxnController).Begin, revel.BEFORE)
revel.InterceptMethod((*TxnController).Commit, revel.AFTER)
revel.InterceptMethod((*TxnController).Rollback, revel.FINALLY)
revel.InterceptMethod((*Controller).setDB, revel.BEFORE)
}
})
}