-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
55 lines (46 loc) · 1.03 KB
/
db.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
package models
import (
"database/sql"
"os"
"github.com/khoa-le/crontask/utils"
"github.com/jinzhu/gorm"
)
//Gdb connection
var Gdb *gorm.DB
//InitDB connection
func InitDB() {
//open db
utils.Log.Info("*** INIT DB ***")
connString := os.Getenv("MYSQL_DB")
db, err := gorm.Open("mysql", connString)
if err != nil {
utils.Log.Panic(err)
}
db.DB().Ping()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
//Migrations
db.AutoMigrate(&Task{})
db.AutoMigrate(&Execution{})
//Add FK
db.Model(&Execution{}).AddForeignKey("task_id", "tasks(id)", "CASCADE", "CASCADE")
Gdb = &db
}
//InTx executes function in a transaction
func InTx(f func(*gorm.DB) bool) {
utils.Log.Info("***INIT TRANSACTION***")
txn := Gdb.Begin()
if txn.Error != nil {
utils.Log.Panic(txn.Error)
}
if f(txn) == true {
utils.Log.Info("***TRANSACTION COMMITED***")
txn.Commit()
} else {
utils.Log.Info("***TRANSACTION ROLLBACK***")
txn.Rollback()
}
if err := txn.Error; err != nil && err != sql.ErrTxDone {
utils.Log.Panic(err)
}
}