-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
57 lines (47 loc) · 1.13 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
// SPDX-License-Identifier: MIT
package config
import (
"github.com/issue9/orm/v5"
"github.com/issue9/orm/v5/dialect"
"github.com/issue9/web/app"
"github.com/issue9/cmfx/locales"
)
// DB 数据库的配置文件格式
type DB struct {
// 表示数据库的类型
//
// 目前支持以下几种类型:
// - sqlite3
// - sqlite 纯 Go
// - mysql
// - mariadb
// - postgres
Type string `yaml:"type" json:"type" xml:"type,attr"`
// 连接数据库的参数
DSN string `yaml:"dsn" json:"dsn" xml:"dsn"`
db *orm.DB
}
func (conf *DB) SanitizeConfig() *app.ConfigError {
var d orm.Dialect
switch conf.Type {
case "sqlite3":
d = dialect.Sqlite3("sqlite3")
case "sqlite":
d = dialect.Sqlite3("sqlite")
case "mysql":
d = dialect.Mysql("mysql")
case "mariadb":
d = dialect.Mariadb("mysql")
case "postgres":
d = dialect.Postgres("postgres")
default:
return &app.ConfigError{Field: "type", Value: conf.Type, Message: locales.InvalidValue}
}
db, err := orm.NewDB(conf.DSN, d)
if err != nil {
return &app.ConfigError{Message: err}
}
conf.db = db
return nil
}
func (conf *DB) DB() *orm.DB { return conf.db }