feat: Added DSN

This commit is contained in:
Flc゛ 2023-03-27 15:47:24 +08:00
parent b444011d09
commit 212cf19d05
2 changed files with 61 additions and 0 deletions

31
dsn.go Normal file
View File

@ -0,0 +1,31 @@
package gorm
import (
"net/url"
"strconv"
)
type DSN struct {
Host string
Port int
User string
Pass string
Db string
Options map[string]string
}
func (d DSN) String() string {
dsn := d.User + ":" + d.Pass + "@tcp(" + d.Host + ":" + strconv.Itoa(d.Port) + ")/" + d.Db
if d.Options != nil {
value := url.Values{}
for k, v := range d.Options {
value.Add(k, v)
}
dsn += "?" + value.Encode()
}
return dsn
}

30
dsn_test.go Normal file
View File

@ -0,0 +1,30 @@
package gorm
import "testing"
func TestDsn(t *testing.T) {
dsn := DSN{
Host: "127.0.0.1",
Port: 3306,
User: "root",
Pass: "password",
Db: "gorm",
}
t.Run("dsn string", func(t *testing.T) {
if dsn.String() != "root:password@tcp(127.0.0.1:3306)/gorm" {
t.Error("dsn string error")
}
})
t.Run("dsn string with options", func(t *testing.T) {
dsn.Options = map[string]string{
"charset": "utf8mb4",
"parseTime": "True",
}
if dsn.String() != "root:password@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True" {
t.Error("dsn string with options error")
}
})
}