-
Notifications
You must be signed in to change notification settings - Fork 10
/
relation_db.go
62 lines (53 loc) · 2.42 KB
/
relation_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
56
57
58
59
60
61
62
package artifact
import (
"errors"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"os"
"time"
)
var DB *Database
type Database struct {
*gorm.DB
}
func NewDatabase() (*Database, error) {
dsn := Config.GetString(Config.RelationDBConfig+".Username") + ":" + Config.GetString(Config.RelationDBConfig+".Password") + "@tcp(" + Config.GetString(Config.RelationDBConfig+".Host") + ":" + Config.GetString(Config.RelationDBConfig+".Port") + ")/" + Config.GetString(Config.RelationDBConfig+".Database") + "?charset=utf8mb4&parseTime=True&loc=Local"
connection := Config.GetString(Config.RelationDBConfig + ".Connection")
config := &gorm.Config{}
if Config.GetString(Config.RelationDBConfig+".DbLogEnabled") == "true" {
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Info, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
ParameterizedQueries: false, // Don't include params in the SQL log
Colorful: true, // Disable color
},
)
config.Logger = newLogger
}
err := error(nil)
var db *gorm.DB
switch connection {
case "mysql":
dsn = Config.GetString(Config.RelationDBConfig+".Username") + ":" + Config.GetString(Config.RelationDBConfig+".Password") + "@tcp(" + Config.GetString(Config.RelationDBConfig+".Host") + ":" + Config.GetString(Config.RelationDBConfig+".Port") + ")/" + Config.GetString(Config.RelationDBConfig+".Database") + "?charset=utf8mb4&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), config)
case "postgres":
dsn = "host=" + Config.GetString(Config.RelationDBConfig+".Host") + " user=" + Config.GetString(Config.RelationDBConfig+".Username") + " password=" + Config.GetString(Config.RelationDBConfig+".Password") + " dbname=" + Config.GetString(Config.RelationDBConfig+".Database") + " port=" + Config.GetString(Config.RelationDBConfig+".Port") + " sslmode=disable TimeZone=Asia/Shanghai"
db, err = gorm.Open(postgres.Open(dsn), config)
case "sqlite":
dsn = Config.GetString(Config.RelationDBConfig + ".Database")
db, err = gorm.Open(sqlite.Open(dsn), config)
default:
err = errors.New("db connection not supported")
}
if err != nil {
return nil, err
}
return &Database{db}, nil
}