You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.0 KiB
77 lines
2.0 KiB
package database
|
|
|
|
import (
|
|
"strconv"
|
|
"strings"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/driver/sqlserver"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Credentials struct {
|
|
Host string
|
|
Port int
|
|
Dialect string
|
|
Database string
|
|
Table string
|
|
User string
|
|
Password string
|
|
Socket string
|
|
MaxOpenConn int
|
|
MaxIdleConn int
|
|
MaxLifeTime int
|
|
Debug bool
|
|
}
|
|
|
|
func (c *Credentials) getDSN() gorm.Dialector {
|
|
switch strings.ToLower(c.Dialect) {
|
|
case "mysql":
|
|
if c.Socket != "" {
|
|
dsn := c.User +
|
|
":" + c.Password +
|
|
"@unix(" + c.Socket +
|
|
")/" + c.Database +
|
|
"?charset=utf8mb4&collation=utf8mb4_unicode_ci&readTimeout=10s&writeTimeout=30s&timeout=5s&parseTime=True&loc=UTC&time_zone=%27%2B00%3A00%27"
|
|
return mysql.Open(dsn)
|
|
}
|
|
dsn := c.User +
|
|
":" + c.Password +
|
|
"@tcp(" + c.Host +
|
|
":" + strconv.Itoa(c.Port) +
|
|
")/" + c.Database +
|
|
"?charset=utf8mb4&collation=utf8mb4_unicode_ci&readTimeout=30s&writeTimeout=30s&timeout=5s&parseTime=True&loc=UTC&time_zone=%27%2B00%3A00%27"
|
|
return mysql.Open(dsn)
|
|
case "mssql":
|
|
dsn := "sqlserver://" + c.User +
|
|
":" + c.Password + "@" +
|
|
c.Host + ":" +
|
|
strconv.Itoa(c.Port) + "?database=" + c.Database + "&connection+timeout=5;SelectMethod=Cursor;integratedSecurity=true;"
|
|
return sqlserver.Open(dsn)
|
|
case "postgres":
|
|
dsn := "host=" + c.Host +
|
|
" port=" + strconv.Itoa(c.Port) +
|
|
" user=" + c.User +
|
|
" dbname=" + c.Database +
|
|
" password=" + c.Password +
|
|
" sslmode=disable connect_timeout=5"
|
|
return postgres.Open(dsn)
|
|
case "sqlite":
|
|
return sqlite.Open("gorm.db")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func Connect(c Credentials) (*gorm.DB, error) {
|
|
db, err := gorm.Open(c.getDSN(), &gorm.Config{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// sqlDB, err := db.DB()
|
|
// sqlDB.SetMaxOpenConns(config.Configuration.DBMaxOpenConn)
|
|
// sqlDB.SetMaxIdleConns(config.Configuration.DBMaxIdleConn)
|
|
// sqlDB.SetConnMaxLifetime(time.Duration(config.Configuration.DBMaxLifeTime) * time.Second)
|
|
return db, nil
|
|
}
|