-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql_config.go
82 lines (69 loc) · 1.59 KB
/
sql_config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package ginboot
import (
"database/sql"
"fmt"
"time"
)
type SQLConfig struct {
Driver string
Host string
Port int
Username string
Password string
Database string
Options map[string]string
}
func NewSQLConfig() *SQLConfig {
return &SQLConfig{
Host: "localhost",
Port: 5432,
Options: make(map[string]string),
}
}
func (c *SQLConfig) WithDriver(driver string) *SQLConfig {
c.Driver = driver
return c
}
func (c *SQLConfig) WithCredentials(username, password string) *SQLConfig {
c.Username = username
c.Password = password
return c
}
func (c *SQLConfig) WithHost(host string, port int) *SQLConfig {
c.Host = host
c.Port = port
return c
}
func (c *SQLConfig) WithDatabase(database string) *SQLConfig {
c.Database = database
return c
}
func (c *SQLConfig) WithOption(key, value string) *SQLConfig {
c.Options[key] = value
return c
}
func (c *SQLConfig) BuildDSN() string {
switch c.Driver {
case "postgres":
return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
c.Host, c.Port, c.Username, c.Password, c.Database)
case "mysql":
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s",
c.Username, c.Password, c.Host, c.Port, c.Database)
default:
return ""
}
}
func (c *SQLConfig) Connect() (*sql.DB, error) {
db, err := sql.Open(c.Driver, c.BuildDSN())
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %v", err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(5 * time.Minute)
if err = db.Ping(); err != nil {
return nil, fmt.Errorf("failed to ping database: %v", err)
}
return db, nil
}