-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.go
More file actions
135 lines (112 loc) · 2.32 KB
/
options.go
File metadata and controls
135 lines (112 loc) · 2.32 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package dbo
import (
"errors"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
type ENGINE string
type DRIVER string
const (
DRIVER_MYSQL DRIVER = "mysql"
DRIVER_PGSQL DRIVER = "pgsql"
DRIVER_SQLITE DRIVER = "sqlite"
)
const (
ENGINE_INNODB ENGINE = "InnoDB"
)
type Options struct {
Driver DRIVER
Host string
Port string
Username string
Password string
DBName string
Charset string
Collation string
DSN string
Engine ENGINE
Config *gorm.Config
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime int // Maximum lifetime for a connection (in milliseconds)
ConnMaxIdleTime int // Maximum idle time for a connection (in milliseconds)
}
func (x *Options) getConfig() *gorm.Config {
if x.Config != nil {
return x.Config
}
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
}
}
func (x *Options) getDialector() (conn gorm.Dialector, err error) {
switch x.getDriver() {
case DRIVER_MYSQL:
conn = func() gorm.Dialector {
if x.DSN != "" {
return mysql.Open(x.DSN)
}
return mysql.Open(fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=%s&collation=%s&parseTime=True&loc=Local",
x.Username,
x.Password,
x.Host,
x.Port,
x.DBName,
x.getCharset(),
x.getCollation(),
))
}()
case DRIVER_PGSQL:
conn = func() gorm.Dialector {
if x.DSN != "" {
return postgres.Open(x.DSN)
}
return postgres.Open(fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s",
x.Username,
x.Password,
x.Host,
x.Port,
x.DBName,
))
}()
case DRIVER_SQLITE:
conn = sqlite.Open(x.DSN)
default:
err = errors.New("DB Driver not available")
}
return
}
func (x *Options) getDriver() DRIVER {
if x.Driver == "" {
x.Driver = DRIVER_PGSQL
}
return x.Driver
}
func (x *Options) getEngine() ENGINE {
if x.Engine == "" {
x.Engine = ENGINE_INNODB
}
return x.Engine
}
func (x *Options) getCharset() string {
if x.Charset == "" {
x.Charset = "utf8mb4"
}
return x.Charset
}
func (x *Options) getCollation() string {
if x.Collation == "" {
x.Collation = "utf8mb4_general_ci"
}
return x.Collation
}