-
Notifications
You must be signed in to change notification settings - Fork 2
/
service.go
94 lines (77 loc) · 2.59 KB
/
service.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
83
84
85
86
87
88
89
90
91
92
93
94
package service
import (
"context"
"fmt"
"github.com/go-pg/pg/v10"
"github.com/ottogroup/penelope/pkg/config"
"github.com/ottogroup/penelope/pkg/secret"
"github.com/ottogroup/penelope/pkg/service/sql"
"go.opencensus.io/trace"
)
// Service represent operation with PostgresSQL
type Service struct {
sqlClient sql.CloudSQLClient
}
// DefaultConnectionOptions returns default ConnectOptions
func DefaultConnectionOptions(ctxIn context.Context, credentialsProvider secret.SecretProvider) (sql.ConnectOptions, error) {
ctx, span := trace.StartSpan(ctxIn, "DefaultConnectionOptions")
defer span.End()
requiredEnvKeys := []config.EnvKey{config.PgUserEnv, config.PgDbEnv}
socket := ""
if config.PgSocket.Exist() {
socket = config.PgSocket.MustGet()
} else {
requiredEnvKeys = append(requiredEnvKeys, config.PgHostEnv)
}
var notSet []config.EnvKey
for _, envKey := range requiredEnvKeys {
if !envKey.Exist() {
notSet = append(notSet, envKey)
}
}
if len(notSet) > 0 {
return sql.ConnectOptions{}, fmt.Errorf("required env are not set: %s", notSet)
}
user := config.PgUserEnv.MustGet()
password, err := credentialsProvider.GetSecret(ctx, user)
if err != nil {
return sql.ConnectOptions{}, err
}
return sql.ConnectOptions{
Host: config.PgHostEnv.GetOrDefault(""),
Port: config.PgPortEnv.GetOrDefault("5432"),
Socket: socket,
User: user,
Password: password,
Database: config.PgDbEnv.MustGet(),
DebugQueries: config.PgDebugQueriesEnv.GetOrDefault(""),
}, nil
}
// NewStorageService create new instance of Service
func NewStorageService(ctxIn context.Context, credentialsProvider secret.SecretProvider) (*Service, error) {
ctx, span := trace.StartSpan(ctxIn, "NewStorageService")
defer span.End()
options, err := DefaultConnectionOptions(ctx, credentialsProvider)
if err != nil {
return nil, err
}
return NewStorageServiceWithConnectionOptions(ctx, options)
}
// NewStorageServiceWithConnectionOptions create new instance of Service with connection options
func NewStorageServiceWithConnectionOptions(ctxIn context.Context, options sql.ConnectOptions) (*Service, error) {
_, span := trace.StartSpan(ctxIn, "NewStorageServiceWithConnectionOptions")
defer span.End()
sqlClient := sql.NewCloudSQLClient(options)
if !sqlClient.IsInitialized() {
return &Service{}, fmt.Errorf("could not instantiate CloudSQLClient")
}
return &Service{sqlClient: sqlClient}, nil
}
// DB will create a new connection
func (c *Service) DB() *pg.DB {
return c.sqlClient.DB()
}
// Close closes db connection
func (c *Service) Close() error {
return c.sqlClient.Close()
}