Skip to content

Commit 217cc2b

Browse files
committed
refactor: added Connect and Close functions for 'database/sql' standard library
1 parent 2f9b8e5 commit 217cc2b

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

sql/connection.go

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package sql
2+
3+
import (
4+
"database/sql"
5+
"time"
6+
)
7+
8+
type (
9+
// Config struct
10+
Config struct {
11+
DB *sql.DB
12+
MaxOpenConnections *int
13+
MaxIdleConnections *int
14+
ConnectionMaxLifetime *time.Duration
15+
}
16+
)
17+
18+
// NewConfig creates a new configuration
19+
func NewConfig(
20+
maxOpenConnections *int,
21+
maxIdleConnections *int,
22+
connectionMaxLifetime *time.Duration,
23+
) *Config {
24+
return &Config{
25+
MaxOpenConnections: maxOpenConnections,
26+
MaxIdleConnections: maxIdleConnections,
27+
ConnectionMaxLifetime: connectionMaxLifetime,
28+
}
29+
}
30+
31+
// Connect returns a new SQL connection
32+
func Connect(
33+
driverName, dataSourceName string,
34+
config *Config,
35+
) (*sql.DB, error) {
36+
// Open a new connection
37+
db, err := sql.Open(driverName, dataSourceName)
38+
if err != nil {
39+
return nil, err
40+
}
41+
42+
// Check if the configuration is nil
43+
if config == nil {
44+
return db, nil
45+
}
46+
47+
// Set the maximum open connections
48+
if config.MaxOpenConnections != nil {
49+
db.SetMaxOpenConns(*config.MaxOpenConnections)
50+
}
51+
52+
// Set the maximum idle connections
53+
if config.MaxIdleConnections != nil {
54+
db.SetMaxIdleConns(*config.MaxIdleConnections)
55+
}
56+
57+
// Set the connection max lifetime
58+
if config.ConnectionMaxLifetime != nil {
59+
db.SetConnMaxLifetime(*config.ConnectionMaxLifetime)
60+
}
61+
return db, nil
62+
}
63+
64+
// Close closes the SQL connection
65+
func Close(db *sql.DB) error {
66+
return db.Close()
67+
}
68+
69+
// Connect returns a new SQL connection
70+
func (c *Config) Connect(
71+
driverName, dataSourceName string,
72+
) (*sql.DB, error) {
73+
return Connect(driverName, dataSourceName, c)
74+
}
75+
76+
// Close closes the SQL connection
77+
func (c *Config) Close(db *sql.DB) error {
78+
return Close(db)
79+
}

0 commit comments

Comments
 (0)