Skip to content
This repository has been archived by the owner on Jul 24, 2024. It is now read-only.

Commit

Permalink
perf: 移除冗余代码和细节优化
Browse files Browse the repository at this point in the history
  • Loading branch information
kyour-cn committed Jul 23, 2024
1 parent df9c584 commit 41df143
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 47 deletions.
47 changes: 5 additions & 42 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package database

import (
"fmt"
"github.com/go-gourd/gourd/config"
"net/url"
)

// Config 适用于单个连接的配置
Expand All @@ -17,11 +17,6 @@ type Config struct {
SlowLogTime int `toml:"slow_log_time" json:"slow_log_time"` //慢日志阈值(毫秒)0为不开启
}

// ConfigMap 适用于多个连接的配置
type ConfigMap map[string]Config

var maps *ConfigMap

// GenerateDsn 根据配置生成sdn连接信息
func (conf Config) GenerateDsn() string {
dsn := ""
Expand All @@ -32,55 +27,23 @@ func (conf Config) GenerateDsn() string {
dsnParam = "?" + conf.Param
}
dsnF := "%s:%s@(%s:%d)/%s%s"
dsn = fmt.Sprintf(dsnF, conf.User, conf.Pass, conf.Host, conf.Port, conf.Database, dsnParam)
dsn = fmt.Sprintf(dsnF, conf.User, url.QueryEscape(conf.Pass), conf.Host, conf.Port, conf.Database, dsnParam)
} else if conf.Type == "sqlserver" {
if conf.Param != "" {
dsnParam = "&" + conf.Param
}
dsnF := "sqlserver://%s:%s@%s:%d?database=%s%s"
dsn = fmt.Sprintf(dsnF, conf.User, conf.Pass, conf.Host, conf.Port, conf.Database, dsnParam)
dsn = fmt.Sprintf(dsnF, conf.User, url.QueryEscape(conf.Pass), conf.Host, conf.Port, conf.Database, dsnParam)
} else if conf.Type == "postgres" {
if conf.Param != "" {
dsnParam = "?" + conf.Param
}
dsnF := "host=%s user=%s password=%s dbname=%s port=%d %s"
dsn = fmt.Sprintf(dsnF, conf.Host, conf.User, conf.Pass, conf.Database, conf.Port, dsnParam)
dsn = fmt.Sprintf(dsnF, conf.Host, conf.User, url.QueryEscape(conf.Pass), conf.Database, conf.Port, dsnParam)
} else if conf.Type == "oracle" {
dsnF := "%s/%s@%s:%d/%s"
dsn = fmt.Sprintf(dsnF, conf.User, conf.Pass, conf.Host, conf.Port, conf.Database)
dsn = fmt.Sprintf(dsnF, conf.User, url.QueryEscape(conf.Pass), conf.Host, conf.Port, conf.Database)
}

return dsn
}

// GetConfig 获取指定数据库配置
func GetConfig(name string) *Config {

all := *GetConfigAll()

// 判断all中是否存在
if _, ok := all[name]; ok {
db := all[name]
return &db
}
return nil
}

// GetConfigAll 获取所有数据库配置
func GetConfigAll() *ConfigMap {

//已存在 -返回
if maps != nil {
return maps
}

// 初始化配置默认值
maps = &ConfigMap{}

err := config.Unmarshal("database", maps)
if err != nil {
panic(err)
}

return maps
}
6 changes: 1 addition & 5 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
module github.com/go-gourd/database

go 1.20

require github.com/go-gourd/gourd v1.0.3

require github.com/pelletier/go-toml/v2 v2.1.0 // indirect
go 1.22

0 comments on commit 41df143

Please sign in to comment.