-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
147 lines (128 loc) · 4.16 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// Content managed by Project Forge, see [projectforge.md] for details.
package database
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"admini.dev/admini/app/lib/telemetry"
"admini.dev/admini/app/lib/telemetry/dbmetrics"
"admini.dev/admini/app/util"
)
type DBType struct {
Key string `json:"key"`
Title string `json:"title"`
Quote string `json:"-"`
Placeholder string `json:"-"`
SupportsReturning bool `json:"-"`
}
type Service struct {
Key string `json:"key"`
DatabaseName string `json:"database,omitempty"`
SchemaName string `json:"schema,omitempty"`
Username string `json:"username,omitempty"`
Debug bool `json:"debug,omitempty"`
Type *DBType `json:"type"`
ReadOnly bool `json:"readonly,omitempty"`
db *sqlx.DB
metrics *dbmetrics.Metrics
}
func NewService(typ *DBType, key string, dbName string, schName string, username string, debug bool, db *sqlx.DB, logger util.Logger) (*Service, error) {
if logger == nil {
return nil, errors.New("logger must be provided to database service")
}
logger = logger.With("database", dbName, "user", username)
m, err := dbmetrics.NewMetrics(strings.ReplaceAll(key, "-", "_"), db, logger)
if err != nil {
logger.Debugf("unable to register database metrics for [%s]: %+v", key, err)
}
ret := &Service{Key: key, DatabaseName: dbName, SchemaName: schName, Username: username, Debug: debug, Type: typ, db: db, metrics: m}
err = ret.Healthcheck(dbName, db)
if err != nil {
return nil, errors.Wrap(err, "unable to run healthcheck")
}
register(ret, logger)
return ret, nil
}
func (s *Service) Healthcheck(dbName string, db *sqlx.DB) error {
q := "select 1"
res, err := db.Query(q)
if err != nil || res.Err() != nil {
if err == nil {
err = res.Err()
}
if strings.Contains(err.Error(), "does not exist") {
return errors.Wrapf(err, "database does not exist")
}
return errors.Wrapf(err, "unable to run healthcheck [%s]", q)
}
defer func() { _ = res.Close() }()
return nil
}
func (s *Service) StartTransaction(logger util.Logger) (*sqlx.Tx, error) {
if s.Debug {
logger.Debug("opening transaction")
}
return s.db.Beginx()
}
func (s *Service) Conn(ctx context.Context) (*sql.Conn, error) {
return s.db.Conn(ctx)
}
func (s *Service) Stats() sql.DBStats {
return s.db.Stats()
}
func (s *Service) Prepare(ctx context.Context, q string) (*sqlx.Stmt, error) {
return s.db.PreparexContext(ctx, q)
}
func (s *Service) Placeholder() string {
return s.Type.Placeholder
}
func errMessage(t string, q string, values []any) string {
return fmt.Sprintf("error running %s sql [%s] with values [%s]", t, strings.TrimSpace(q), valueStrings(values))
}
type logFunc func(count int, msg string, err error, output ...any)
func (s *Service) logQuery(ctx context.Context, msg string, q string, logger util.Logger, values []any) logFunc {
if s.Debug {
logger.Debugf("%s {\n SQL: %s\n Values: %s\n}", msg, strings.TrimSpace(q), valueStrings(values))
}
return func(count int, msg string, err error, output ...any) {}
}
func (s *Service) newSpan(
ctx context.Context, name string, q string, logger util.Logger,
) (time.Time, context.Context, *telemetry.Span, util.Logger) {
if ctx == nil {
return util.TimeCurrent(), context.Background(), nil, logger
}
if s.metrics != nil {
s.metrics.IncStmt(q, name)
}
nc, span, logger := telemetry.StartSpan(ctx, "database"+name, logger)
span.Attributes(
&telemetry.Attribute{Key: "db.statement", Value: q},
&telemetry.Attribute{Key: "db.system", Value: s.db.DriverName()},
&telemetry.Attribute{Key: "db.name", Value: s.DatabaseName},
&telemetry.Attribute{Key: "db.user", Value: s.Username},
)
return util.TimeCurrent(), nc, span, logger
}
func (s *Service) complete(q string, op string, span *telemetry.Span, started time.Time, _ util.Logger, err error) {
if err != nil && span != nil {
span.OnError(err)
}
if span != nil {
span.Complete()
}
if s.metrics != nil {
s.metrics.CompleteStmt(q, op, started)
}
}
func (s *Service) Close() error {
if s.metrics != nil {
_ = s.metrics.Close()
}
unregister(s)
return s.db.Close()
}