-
Notifications
You must be signed in to change notification settings - Fork 493
/
database.go
50 lines (43 loc) · 1.01 KB
/
database.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
package common
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"os"
)
type Database struct {
*gorm.DB
}
var DB *gorm.DB
// Opening a database and save the reference to `Database` struct.
func Init() *gorm.DB {
db, err := gorm.Open("sqlite3", "./../gorm.db")
if err != nil {
fmt.Println("db err: (Init) ", err)
}
db.DB().SetMaxIdleConns(10)
//db.LogMode(true)
DB = db
return DB
}
// This function will create a temporarily database for running testing cases
func TestDBInit() *gorm.DB {
test_db, err := gorm.Open("sqlite3", "./../gorm_test.db")
if err != nil {
fmt.Println("db err: (TestDBInit) ", err)
}
test_db.DB().SetMaxIdleConns(3)
test_db.LogMode(true)
DB = test_db
return DB
}
// Delete the database after running testing cases.
func TestDBFree(test_db *gorm.DB) error {
test_db.Close()
err := os.Remove("./../gorm_test.db")
return err
}
// Using this function to get a connection, you can create your connection pool here.
func GetDB() *gorm.DB {
return DB
}