-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathgorm.go
72 lines (62 loc) · 1.15 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package oauth2gorm
import (
"fmt"
"log"
"os"
"time"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type DBType int8
// Config gorm configuration
type Config struct {
TableName string
MaxLifetime time.Duration
Dialector gorm.Dialector
}
const (
MySQL = iota
PostgreSQL
SQLite
SQLServer
)
var defaultConfig = &gorm.Config{
Logger: logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // slow SQL
LogLevel: logger.Info, // log level
Colorful: true, // color
},
),
}
func NewConfig(dsn string, dbType DBType, tableName string) *Config {
var d gorm.Dialector
switch dbType {
case MySQL:
d = mysql.New(mysql.Config{
DSN: dsn,
})
case PostgreSQL:
d = postgres.New(postgres.Config{
DSN: dsn,
})
case SQLite:
d = sqlite.Open(dsn)
case SQLServer:
d = sqlserver.Open(dsn)
default:
fmt.Println("unsupported databases")
d = nil
}
config := &Config{
TableName: tableName,
MaxLifetime: time.Hour * 2,
Dialector: d,
}
return config
}