-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm.go
50 lines (38 loc) · 1.16 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
package database
import (
"strconv"
"time"
"github.com/DATA-DOG/go-txdb"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
const testEnv = "test"
// NewConnection returns a new Gorm database connection.
func NewConnection(config *Config, environment string) (*gorm.DB, error) {
connectionDetails := NewConnectionDetails(config)
connectionString := connectionDetails.String()
driverName := connectionDetails.Dialect
// Register the test driver and mock driver name and connection string in test environment.
if environment == testEnv {
// Using time.Now() as a unique identifier for the test database so that we can call NewConnection()
// multiple times without getting an error.
testDriverName := strconv.Itoa(int(time.Now().UnixNano()))
txdb.Register(testDriverName, connectionDetails.Dialect, connectionString)
driverName = testDriverName
connectionString = testDriverName
}
dialector := mysql.New(mysql.Config{
DSN: connectionString,
DriverName: driverName,
})
db, err := gorm.Open(dialector)
if err != nil {
return nil, err
}
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
sqlDB.SetMaxIdleConns(config.Pool)
return db, nil
}