-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudsql.go
39 lines (32 loc) · 987 Bytes
/
cloudsql.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
package cloudsql
import (
"context"
"database/sql"
"fmt"
"net"
"cloud.google.com/go/cloudsqlconn"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"github.com/mpsdantas/bottle/pkg/database/connection"
"github.com/mpsdantas/bottle/pkg/log"
)
func DB(ctx context.Context, cfg *connection.Config) *sql.DB {
dsn := fmt.Sprintf("user=%s password=%s database=%s", cfg.User, cfg.Password, cfg.Database)
config, err := pgx.ParseConfig(dsn)
if err != nil {
log.Fatal(ctx, "could not parse config", log.Err(err))
}
d, err := cloudsqlconn.NewDialer(context.Background())
if err != nil {
log.Fatal(ctx, "could not create dialler", log.Err(err))
}
config.DialFunc = func(ctx context.Context, network, instance string) (net.Conn, error) {
return d.Dial(ctx, cfg.ConnectionName)
}
dbURI := stdlib.RegisterConnConfig(config)
dbPool, err := sql.Open("pgx", dbURI)
if err != nil {
log.Fatal(ctx, "could open sql connection", log.Err(err))
}
return dbPool
}