Skip to content

Commit 7c8b1ef

Browse files
committed
feat: add connector util
1 parent 4a963bd commit 7c8b1ef

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

internals/database/connector.go

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package database
2+
3+
import (
4+
"context"
5+
6+
"github.com/jackc/pgx/v5"
7+
)
8+
9+
type Connector interface {
10+
Connect(ctx context.Context) (*pgx.Conn, error)
11+
}
12+
13+
type ConnStringConnector struct {
14+
ConnString string
15+
}
16+
17+
func NewConnStringConnector(connString string) *ConnStringConnector {
18+
return &ConnStringConnector{
19+
ConnString: connString,
20+
}
21+
}
22+
23+
func (c *ConnStringConnector) Connect(ctx context.Context) (*pgx.Conn, error) {
24+
conn, err := pgx.Connect(ctx, c.ConnString)
25+
if err != nil {
26+
return nil, err
27+
}
28+
return conn, nil
29+
}
30+
31+
type ConfigConnector struct {
32+
Host string
33+
Database string
34+
User string
35+
Password string
36+
Port uint16
37+
}
38+
39+
func NewConfigConnector(host, database, user, password string, port uint16) *ConfigConnector {
40+
return &ConfigConnector{
41+
Host: host,
42+
Database: database,
43+
User: user,
44+
Password: password,
45+
Port: port,
46+
}
47+
}
48+
49+
func (c *ConfigConnector) Connect(ctx context.Context) (*pgx.Conn, error) {
50+
connConfig, err := pgx.ParseConfig("")
51+
if err != nil {
52+
return nil, err
53+
}
54+
55+
if c.Host != "" {
56+
connConfig.Host = c.Host
57+
}
58+
if c.Database != "" {
59+
connConfig.Database = c.Database
60+
}
61+
if c.User != "" {
62+
connConfig.User = c.User
63+
}
64+
if c.Password != "" {
65+
connConfig.Password = c.Password
66+
}
67+
if c.Port != 0 {
68+
connConfig.Port = uint16(c.Port)
69+
}
70+
71+
conn, err := pgx.ConnectConfig(ctx, connConfig)
72+
if err != nil {
73+
return nil, err
74+
}
75+
return conn, nil
76+
}

0 commit comments

Comments
 (0)