Skip to content

Commit e9ef8f7

Browse files
committed
完成GORM的支持四个数据库的配置
1 parent be9c85a commit e9ef8f7

File tree

5 files changed

+182
-22
lines changed

5 files changed

+182
-22
lines changed

server/config.yaml

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,36 @@ mysql:
1919
max-open-conns: 10
2020
log-mode: false
2121

22-
#sqlite 配置
22+
# Postgresql connect configuration
23+
postgresql:
24+
username: 'gorm'
25+
password: 'gorm'
26+
db-name: 'gorm'
27+
port: '9920'
28+
config: 'sslmode=disable TimeZone=Asia/Shanghai'
29+
max-idle-conns: 10
30+
max-open-conns: 10
31+
logger: false
32+
prefer-simple-protocol: true
33+
34+
# sqlite connect configuration
35+
# sqlite需要gcc支持 windows用户需要自行安装gcc
2336
sqlite:
24-
path: db.db
25-
log-mode: true
26-
config: 'loc=Asia/Shanghai'
37+
# path: 'file::memory:?cache=shared' # 内存模式
38+
path: 'db.db'
39+
max-idle-conns: 10
40+
max-open-conns: 10
41+
logger: true
42+
43+
# Sqlserver connect configuration
44+
sqlserver:
45+
username: 'gorm'
46+
password: 'LoremIpsum86'
47+
db-name: 'gorm'
48+
path: 'localhost:9930'
49+
max-idle-conns: 10
50+
max-open-conns: 10
51+
logger: true
2752

2853
# oss configuration
2954

@@ -51,7 +76,7 @@ system:
5176
use-multipoint: false
5277
env: 'public' # Change to "develop" to skip authentication for development mode
5378
addr: 8888
54-
db-type: "mysql" # support mysql/sqlite
79+
db-type: "mysql" # support mysql/postgresql/sqlite/sqlserver
5580
need-init-data: false
5681

5782
# captcha configuration

server/config/config.go

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package config
22

33
type Server struct {
44
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
5+
Postgresql Postgresql `mapstructure:"postgresql" json:"postgresql" yaml:"postgresql"`
56
Sqlite Sqlite `mapstructure:"sqlite" json:"sqlite" yaml:"sqlite"`
7+
Sqlserver Sqlserver `mapstructure:"sqlserver" json:"sqlserver" yaml:"sqlserver"`
68
Qiniu Qiniu `mapstructure:"qiniu" json:"qiniu" yaml:"qiniu"`
79
Casbin Casbin `mapstructure:"casbin" json:"casbin" yaml:"casbin"`
810
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
@@ -40,6 +42,35 @@ type Mysql struct {
4042
LogMode bool `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"`
4143
}
4244

45+
type Postgresql struct {
46+
Username string `mapstructure:"username" json:"username" yaml:"username"`
47+
Password string `mapstructure:"password" json:"password" yaml:"password"`
48+
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"`
49+
Port string `mapstructure:"port" json:"port" yaml:"port"`
50+
Config string `mapstructure:"config" json:"config" yaml:"config"`
51+
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"`
52+
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"`
53+
Logger bool `mapstructure:"logger" json:"logger" yaml:"logger"`
54+
PreferSimpleProtocol bool `mapstructure:"prefer-simple-protocol" json:"preferSimpleProtocol" yaml:"prefer-simple-protocol"`
55+
}
56+
57+
type Sqlite struct {
58+
Path string `mapstructure:"path" json:"path" yaml:"path"`
59+
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"`
60+
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"`
61+
Logger bool `mapstructure:"logger" json:"logger" yaml:"logger"`
62+
}
63+
64+
type Sqlserver struct {
65+
Username string `mapstructure:"username" json:"username" yaml:"username"`
66+
Password string `mapstructure:"password" json:"password" yaml:"password"`
67+
Path string `mapstructure:"path" json:"path" yaml:"path"`
68+
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"`
69+
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"`
70+
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"`
71+
Logger bool `mapstructure:"logger" json:"logger" yaml:"logger"`
72+
}
73+
4374
type Redis struct {
4475
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"`
4576
Password string `mapstructure:"password" json:"password" yaml:"password"`
@@ -65,14 +96,6 @@ type Captcha struct {
6596
ImgHeight int `mapstructure:"img-height" json:"imgHeight" yaml:"img-height"`
6697
}
6798

68-
type Sqlite struct {
69-
Username string `mapstructure:"username" json:"username" yaml:"username"`
70-
Password string `mapstructure:"password" json:"password" yaml:"password"`
71-
Path string `mapstructure:"path" json:"path" yaml:"path"`
72-
Config string `mapstructure:"config" json:"config" yaml:"config"`
73-
LogMode bool `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"`
74-
}
75-
7699
type Zap struct {
77100
Level string `mapstructure:"level" json:"level" yaml:"level"`
78101
Format string `mapstructure:"format" json:"format" yaml:"format"`

server/go.mod

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,14 @@ require (
4141
github.com/tebeka/strftime v0.1.3 // indirect
4242
github.com/unrolled/secure v1.0.7
4343
go.uber.org/zap v1.10.0
44-
golang.org/x/net v0.0.0-20200320220750-118fecf932d8 // indirect
4544
golang.org/x/sys v0.0.0-20200610111108-226ff32320da // indirect
4645
golang.org/x/tools v0.0.0-20200324003944-a576cf524670 // indirect
4746
google.golang.org/protobuf v1.24.0 // indirect
4847
gopkg.in/ini.v1 v1.55.0 // indirect
4948
gopkg.in/yaml.v2 v2.3.0 // indirect
5049
gorm.io/driver/mysql v0.3.1
50+
gorm.io/driver/postgres v0.2.6
51+
gorm.io/driver/sqlite v1.1.1
52+
gorm.io/driver/sqlserver v0.2.4
5153
gorm.io/gorm v0.2.35
5254
)

server/initialize/gorm.go

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
package initialize
2+
3+
import (
4+
"gin-vue-admin/global"
5+
"go.uber.org/zap"
6+
"gorm.io/driver/mysql"
7+
"gorm.io/driver/postgres"
8+
"gorm.io/driver/sqlite"
9+
"gorm.io/driver/sqlserver"
10+
"gorm.io/gorm"
11+
"gorm.io/gorm/logger"
12+
"os"
13+
)
14+
15+
// Gorm 初始化数据库并产生数据库全局变量
16+
func Gorm() {
17+
switch global.GVA_CONFIG.System.DbType {
18+
case "mysql":
19+
GormMysql()
20+
case "postgresql":
21+
GormPostgreSql()
22+
case "sqlite":
23+
GormSqlite()
24+
case "sqlserver":
25+
GormSqlServer()
26+
}
27+
}
28+
29+
// GormMysql 初始化Mysql数据库
30+
func GormMysql() {
31+
m := global.GVA_CONFIG.Mysql
32+
dsn := m.Username + ":" + m.Password + "@(" + m.Path + ")/" + m.Dbname + "?" + m.Config
33+
mysqlConfig := mysql.Config{
34+
DSN: dsn, // DSN data source name
35+
DefaultStringSize: 191, // string 类型字段的默认长度
36+
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
37+
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
38+
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
39+
SkipInitializeWithVersion: false, // 根据版本自动配置
40+
}
41+
gormConfig := config(m.LogMode)
42+
if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig); err != nil {
43+
global.GVA_LOG.Error("MySQL启动异常", zap.Any("err", err))
44+
os.Exit(0)
45+
} else {
46+
global.GVA_DB = db
47+
sqlDB, _ := db.DB()
48+
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
49+
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
50+
}
51+
}
52+
53+
// GormPostgreSql 初始化PostgreSql数据库
54+
func GormPostgreSql() {
55+
p := global.GVA_CONFIG.Postgresql
56+
dsn := "user=" + p.Username + " password=" + p.Password + " dbname=" + p.Dbname + " port=" + p.Port + " " + p.Config
57+
postgresConfig := postgres.Config{
58+
DSN: dsn, // DSN data source name
59+
PreferSimpleProtocol: p.PreferSimpleProtocol, // 禁用隐式 prepared statement
60+
}
61+
gormConfig := config(p.Logger)
62+
if db, err := gorm.Open(postgres.New(postgresConfig), gormConfig); err != nil {
63+
global.GVA_LOG.Error("PostgreSql启动异常", zap.Any("err", err))
64+
os.Exit(0)
65+
} else {
66+
global.GVA_DB = db
67+
sqlDB, _ := db.DB()
68+
sqlDB.SetMaxIdleConns(p.MaxIdleConns)
69+
sqlDB.SetMaxOpenConns(p.MaxOpenConns)
70+
}
71+
}
72+
73+
// GormSqlite 初始化Sqlite数据库
74+
func GormSqlite() {
75+
s := global.GVA_CONFIG.Sqlite
76+
gormConfig := config(s.Logger)
77+
if db, err := gorm.Open(sqlite.Open(s.Path), gormConfig); err != nil {
78+
global.GVA_LOG.Error("Sqlite启动异常", zap.Any("err", err))
79+
os.Exit(0)
80+
} else {
81+
global.GVA_DB = db
82+
sqlDB, _ := db.DB()
83+
sqlDB.SetMaxIdleConns(s.MaxIdleConns)
84+
sqlDB.SetMaxOpenConns(s.MaxOpenConns)
85+
}
86+
}
87+
88+
// GormSqlite 初始化Sqlite数据库
89+
func GormSqlServer() {
90+
ss := global.GVA_CONFIG.Sqlserver
91+
dsn := "sqlserver://" + ss.Username + ":" + ss.Password + "@" + ss.Path + "?database=gorm"
92+
if db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{}); err != nil {
93+
global.GVA_LOG.Error("SqlServer启动异常", zap.Any("err", err))
94+
os.Exit(0)
95+
} else {
96+
global.GVA_DB = db
97+
sqlDB, _ := db.DB()
98+
sqlDB.SetMaxIdleConns(ss.MaxIdleConns)
99+
sqlDB.SetMaxOpenConns(ss.MaxOpenConns)
100+
}
101+
}
102+
103+
// config 根据配置决定是否开启日志
104+
func config(mod bool) (c *gorm.Config) {
105+
if mod {
106+
c = &gorm.Config{
107+
Logger: logger.Default.LogMode(logger.Info),
108+
DisableForeignKeyConstraintWhenMigrating: true,
109+
}
110+
} else {
111+
c = &gorm.Config{
112+
Logger: logger.Default.LogMode(logger.Silent),
113+
DisableForeignKeyConstraintWhenMigrating: true,
114+
}
115+
}
116+
return
117+
}

server/main.go

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,7 @@ import (
1515
// @name x-token
1616
// @BasePath /
1717
func main() {
18-
switch global.GVA_CONFIG.System.DbType {
19-
case "mysql":
20-
initialize.Mysql()
21-
// case "sqlite":
22-
// initialize.Sqlite() // sqlite需要gcc支持 windows用户需要自行安装gcc 如需使用打开注释即可
23-
default:
24-
initialize.Mysql()
25-
}
18+
initialize.Gorm()
2619
initialize.DBTables()
2720
if global.GVA_CONFIG.System.NeedInitData {
2821
init_data.InitData() // 通过配置文件初始化数据 默认为 false 首次运行需要将 ./config.yaml中 system下的 need-init-data 修改为true

0 commit comments

Comments
 (0)