Skip to content

Commit d29fdda

Browse files
author
Cairry
committed
✨ Support both MySQL and SQLite database
1 parent 8b1b5f0 commit d29fdda

File tree

6 files changed

+96
-37
lines changed

6 files changed

+96
-37
lines changed

config/config.go

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ import (
77
)
88

99
type App struct {
10-
Server Server `json:"Server"`
11-
MySQL MySQL `json:"MySQL"`
12-
Redis Redis `json:"Redis"`
13-
Jwt Jwt `json:"Jwt"`
14-
Jaeger Jaeger `json:"Jaeger"`
10+
Server Server `json:"Server"`
11+
Database Database `json:"Database"`
12+
Redis Redis `json:"Redis"`
13+
Jwt Jwt `json:"Jwt"`
14+
Jaeger Jaeger `json:"Jaeger"`
1515
}
1616

1717
type Server struct {
@@ -20,13 +20,15 @@ type Server struct {
2020
EnableElection bool `json:"enableElection"`
2121
}
2222

23-
type MySQL struct {
24-
Host string `json:"host"`
25-
Port string `json:"port"`
26-
User string `json:"user"`
27-
Pass string `json:"pass"`
28-
DBName string `json:"dbName"`
29-
Timeout string `json:"timeout"`
23+
type Database struct {
24+
Type string `json:"type"` // mysql 或 sqlite
25+
Host string `json:"host"` // MySQL 主机地址
26+
Port string `json:"port"` // MySQL 端口
27+
User string `json:"user"` // MySQL 用户名
28+
Pass string `json:"pass"` // MySQL 密码
29+
DBName string `json:"dbName"` // MySQL 数据库名
30+
Timeout string `json:"timeout"` // MySQL 连接超时
31+
Path string `json:"path"` // SQLite 数据库文件路径
3032
}
3133

3234
type Redis struct {

config/config.yaml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@ Server:
33
# release / debug / test
44
mode: "release"
55

6-
MySQL:
6+
Database:
7+
# 数据库类型: mysql 或 sqlite (默认: mysql)
8+
type: mysql
9+
# MySQL 配置 (当 type 为 mysql 时使用)
710
host: w8t-mysql
811
port: 3306
912
user: root
1013
pass: w8t.123
1114
dbName: watchalert
1215
timeout: 10s
16+
# SQLite 配置 (当 type 为 sqlite 时使用)
17+
path: data/w8t.db
1318

1419
Redis:
1520
host: w8t-redis

go.mod

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ require (
4040
gopkg.in/ldap.v2 v2.5.1
4141
gopkg.in/yaml.v3 v3.0.1
4242
gorm.io/driver/mysql v1.5.4
43-
gorm.io/gorm v1.25.7
43+
gorm.io/gorm v1.30.0
4444
k8s.io/api v0.34.1
4545
k8s.io/apimachinery v0.34.1
4646
k8s.io/client-go v0.34.1
@@ -112,6 +112,7 @@ require (
112112
github.com/mailru/easyjson v0.7.7 // indirect
113113
github.com/mattn/go-colorable v0.1.13 // indirect
114114
github.com/mattn/go-isatty v0.0.20 // indirect
115+
github.com/mattn/go-sqlite3 v1.14.22 // indirect
115116
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
116117
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
117118
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
@@ -150,6 +151,7 @@ require (
150151
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
151152
gopkg.in/inf.v0 v0.9.1 // indirect
152153
gopkg.in/ini.v1 v1.67.0 // indirect
154+
gorm.io/driver/sqlite v1.6.0 // indirect
153155
k8s.io/klog/v2 v2.130.1 // indirect
154156
k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b // indirect
155157
k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 // indirect

go.sum

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,8 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
267267
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
268268
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
269269
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
270+
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
271+
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
270272
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
271273
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
272274
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -601,9 +603,13 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
601603
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
602604
gorm.io/driver/mysql v1.5.4 h1:igQmHfKcbaTVyAIHNhhB888vvxh8EdQ2uSUT0LPcBso=
603605
gorm.io/driver/mysql v1.5.4/go.mod h1:9rYxJph/u9SWkWc9yY4XJ1F/+xO0S/ChOmbk3+Z5Tvs=
606+
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
607+
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
604608
gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
605609
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
606610
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
611+
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
612+
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
607613
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
608614
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
609615
k8s.io/api v0.34.1 h1:jC+153630BMdlFukegoEL8E/yT7aLyQkIVuwhmwDgJM=

internal/repo/entry.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,16 @@ type (
4343
)
4444

4545
func NewRepoEntry() InterEntryRepo {
46-
sql := global.Config.MySQL
46+
dbConfig := global.Config.Database
4747
db := client.NewDBClient(client.DBConfig{
48-
Host: sql.Host,
49-
Port: sql.Port,
50-
User: sql.User,
51-
Pass: sql.Pass,
52-
DBName: sql.DBName,
53-
Timeout: sql.Timeout,
48+
Type: dbConfig.Type,
49+
Host: dbConfig.Host,
50+
Port: dbConfig.Port,
51+
User: dbConfig.User,
52+
Pass: dbConfig.Pass,
53+
DBName: dbConfig.DBName,
54+
Timeout: dbConfig.Timeout,
55+
Path: dbConfig.Path,
5456
})
5557
g := NewInterGormDBCli(db)
5658
return &entryRepo{

pkg/client/db.go

Lines changed: 58 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,47 @@ package client
33
import (
44
"context"
55
"fmt"
6+
"os"
7+
"path/filepath"
68
"watchAlert/internal/global"
79
"watchAlert/internal/models"
810

911
"github.com/zeromicro/go-zero/core/logc"
1012
"gorm.io/driver/mysql"
13+
"gorm.io/driver/sqlite"
1114
"gorm.io/gorm"
1215
"gorm.io/gorm/logger"
1316
)
1417

1518
type DBConfig struct {
16-
Host string
17-
Port string
18-
User string
19-
Pass string
20-
DBName string
21-
Timeout string
19+
Type string // 数据库类型: mysql 或 sqlite
20+
Host string // MySQL 主机地址
21+
Port string // MySQL 端口
22+
User string // MySQL 用户名
23+
Pass string // MySQL 密码
24+
DBName string // MySQL 数据库名
25+
Timeout string // MySQL 连接超时
26+
Path string // SQLite 数据库文件路径
2227
}
2328

2429
func NewDBClient(config DBConfig) *gorm.DB {
25-
// 初始化本地 test.db 数据库文件
26-
//db, err := gorm.Open(sqlite.Open("data/sql.db"), &gorm.Config{})
30+
var db *gorm.DB
31+
var err error
2732

28-
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4,utf8&parseTime=True&loc=Local&timeout=%s",
29-
config.User,
30-
config.Pass,
31-
config.Host,
32-
config.Port,
33-
config.DBName,
34-
config.Timeout)
35-
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
33+
// 设置默认数据库类型为 mysql
34+
if config.Type == "" {
35+
config.Type = "mysql"
36+
}
37+
38+
switch config.Type {
39+
case "sqlite":
40+
db, err = initSQLiteDB(config)
41+
case "mysql":
42+
db, err = initMySQLDB(config)
43+
default:
44+
logc.Errorf(context.Background(), "unsupported database type: %s", config.Type)
45+
return nil
46+
}
3647

3748
if err != nil {
3849
logc.Errorf(context.Background(), "failed to connect database: %s", err.Error())
@@ -83,3 +94,34 @@ func NewDBClient(config DBConfig) *gorm.DB {
8394

8495
return db
8596
}
97+
98+
// initMySQLDB 初始化 MySQL 数据库连接
99+
func initMySQLDB(config DBConfig) (*gorm.DB, error) {
100+
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4,utf8&parseTime=True&loc=Local&timeout=%s",
101+
config.User,
102+
config.Pass,
103+
config.Host,
104+
config.Port,
105+
config.DBName,
106+
config.Timeout)
107+
108+
logc.Infof(context.Background(), "connecting to MySQL database: %s:%s/%s", config.Host, config.Port, config.DBName)
109+
return gorm.Open(mysql.Open(dsn), &gorm.Config{})
110+
}
111+
112+
// initSQLiteDB 初始化 SQLite 数据库连接
113+
func initSQLiteDB(config DBConfig) (*gorm.DB, error) {
114+
// 设置默认 SQLite 文件路径
115+
if config.Path == "" {
116+
config.Path = "data/watchalert.db"
117+
}
118+
119+
// 确保目录存在
120+
dir := filepath.Dir(config.Path)
121+
if err := os.MkdirAll(dir, 0755); err != nil {
122+
return nil, fmt.Errorf("failed to create directory %s: %w", dir, err)
123+
}
124+
125+
logc.Infof(context.Background(), "connecting to SQLite database: %s", config.Path)
126+
return gorm.Open(sqlite.Open(config.Path), &gorm.Config{})
127+
}

0 commit comments

Comments
 (0)