This repository has been archived by the owner on Aug 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
183 lines (159 loc) · 4.63 KB
/
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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package db
import (
"context"
"fmt"
"net/url"
"strings"
"time"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"github.com/laojianzi/mdclubgo/conf"
"github.com/laojianzi/mdclubgo/log"
)
var instance *gorm.DB
// parsePostgreSQLHostPort fork https://github.com/gogs/gogs/blob/main/internal/db/db.go#L31
func parsePostgreSQLHostPort(info string) (host, port string) {
host, port = "127.0.0.1", "5432"
if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
idx := strings.LastIndex(info, ":")
host = info[:idx]
port = info[idx+1:]
} else if len(info) > 0 {
host = info
}
return host, port
}
// parseMSSQLHostPort fork https://github.com/gogs/gogs/blob/main/internal/db/db.go#L43
func parseMSSQLHostPort(info string) (host, port string) {
host, port = "127.0.0.1", "1433"
switch {
case strings.Contains(info, ":"):
host = strings.Split(info, ":")[0]
port = strings.Split(info, ":")[1]
case strings.Contains(info, ","):
host = strings.Split(info, ",")[0]
port = strings.TrimSpace(strings.Split(info, ",")[1])
case len(info) > 0:
host = info
}
return host, port
}
// DSN return parsed DSN
func DSN() (dsn string, err error) {
concate := "?"
if strings.Contains(conf.Database.Name, concate) {
concate = "&"
}
switch conf.Database.Type {
case Mysql, Tidb:
var format string
if conf.Database.Host[0] == '/' { // Looks like a unix socket
format = "%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true"
} else {
format = "%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true"
}
dsn = fmt.Sprintf(format, conf.Database.User, conf.Database.Password, conf.Database.Host, conf.Database.Name, concate)
case Postgres:
host, port := parsePostgreSQLHostPort(conf.Database.Host)
if host[0] == '/' { // looks like a unix socket
dsn = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), port, conf.Database.Name, concate, conf.Database.SSLMode, host)
} else {
dsn = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
url.QueryEscape(conf.Database.User), url.QueryEscape(conf.Database.Password), host, port, conf.Database.Name, concate, conf.Database.SSLMode)
}
case Mssql:
host, port := parseMSSQLHostPort(conf.Database.Host)
dsn = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
host, port, conf.Database.Name, conf.Database.User, conf.Database.Password)
case Sqlite3:
dsn = "file:" + conf.Database.Path + "?cache=shared&mode=rwc"
default:
return "", fmt.Errorf("unrecognized dialect: %s", conf.Database.Type)
}
return dsn, nil
}
func open(cfg *gorm.Config) (*gorm.DB, error) {
dsn, err := DSN()
if err != nil {
return nil, fmt.Errorf("parse DSN: %w", err)
}
var dialector gorm.Dialector
switch conf.Database.Type {
case Mysql, Tidb:
dialector = mysql.Open(dsn)
case Postgres:
dialector = postgres.Open(dsn)
case Mssql:
dialector = sqlserver.Open(dsn)
case Sqlite3:
dialector = sqlite.Open(dsn)
default:
log.Fatal("unreachable")
}
return gorm.Open(dialector, cfg)
}
// Init for db
func Init() {
logger.Default = logger.New(
new(Logger),
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // Log level
Colorful: conf.App.Debug, // 禁用彩色打印
},
)
db, err := open(&gorm.Config{
PrepareStmt: true, // 开启预编译 SQL
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
NowFunc: func() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
},
})
if err != nil {
log.Fatal(fmt.Errorf("open database: %w", err).Error())
}
sqlDB, err := db.DB()
if err != nil {
log.Fatal(fmt.Errorf("get underlying *sql.DB: %w", err).Error())
}
sqlDB.SetMaxOpenConns(conf.Database.MaxOpenConns)
sqlDB.SetMaxIdleConns(conf.Database.MaxIdleConns)
sqlDB.SetConnMaxLifetime(time.Minute)
typ := strings.ToLower(strings.TrimSpace(conf.Database.Type))
switch typ {
case "postgres":
conf.UsePostgreSQL = true
case "mysql":
conf.UseMySQL = true
db = db.Set("gorm:table_options", "ENGINE=InnoDB").Session(&gorm.Session{})
case "sqlite3":
conf.UseSQLite3 = true
case "mssql":
conf.UseMSSQL = true
default:
log.Fatal("email type unrecognized dialect: %s", typ)
}
instance = db
}
// Instance return a opened *gorm.DB
func Instance() *gorm.DB {
return instance.WithContext(context.Background())
}
// Close sql db connect
func Close() {
sqlDB, err := instance.DB()
if err != nil {
log.Error("get *sql.DB error: %s", err)
} else {
_ = sqlDB.Close()
}
instance = nil
}