-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbs.go
63 lines (53 loc) · 1.24 KB
/
dbs.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
package rabbit
import (
"io"
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func InitDatabase(driver, dsn string, logWrite io.Writer) *gorm.DB {
if driver == "" {
driver = GetEnv(ENV_DB_DRIVER)
}
if dsn == "" {
dsn = GetEnv(ENV_DSN)
}
var l logger.Interface
if logWrite == nil {
logWrite = os.Stdout
}
l = logger.New(
log.New(logWrite, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Warn, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: false, // Disable color
},
)
cfg := &gorm.Config{
Logger: l,
SkipDefaultTransaction: true,
}
db, err := CreateDatabaseInstance(driver, dsn, cfg)
if err != nil {
panic(err)
}
return db
}
func MakeMigrates(db *gorm.DB, insts ...any) error {
return db.AutoMigrate(insts...)
}
func CreateDatabaseInstance(driver, dsn string, cfg *gorm.Config) (*gorm.DB, error) {
if driver == "mysql" {
return gorm.Open(mysql.Open(dsn), cfg)
}
if dsn == "" {
dsn = "file::memory:"
}
return gorm.Open(sqlite.Open(dsn), cfg)
}