forked from sampork/go-sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opendb.go
150 lines (121 loc) · 4.28 KB
/
opendb.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
148
149
150
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pool
import (
"context"
"slices"
"strings"
"time"
zapadapter "github.com/jackc/pgx-zap"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/tracelog"
"go.uber.org/zap"
"github.com/40t/go-sniffer/plugSrc/mongodb/build/FerretDB-internal/util/lazyerrors"
"github.com/40t/go-sniffer/plugSrc/mongodb/build/FerretDB-internal/util/state"
)
var (
// The only supported encoding in canonical form.
encoding = "UTF8"
// Supported locales in canonical forms.
locales = []string{"POSIX", "C", "C.UTF8", "en_US.UTF8"}
)
// openDB creates a pool of connections to PostgreSQL database
// and check that it works (authentication passes, settings are okay).
func openDB(uri string, l *zap.Logger, sp *state.Provider) (*pgxpool.Pool, error) {
config, err := pgxpool.ParseConfig(uri)
if err != nil {
return nil, lazyerrors.Error(err)
}
// version could change without FerretDB restart
config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
var v string
var err error //nolint:vet // to avoid capturing the outer variable
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if err = conn.QueryRow(ctx, `SELECT version()`).Scan(&v); err != nil {
return lazyerrors.Error(err)
}
n, v, _ := strings.Cut(v, " ")
if sp.Get().BackendVersion != v {
if err = sp.Update(func(s *state.State) { s.BackendName = n; s.BackendVersion = v }); err != nil {
l.Error("openDB: failed to update state", zap.Error(err))
}
}
return nil
}
// port tracing, tweak logging
// TODO https://github.com/FerretDB/FerretDB/issues/3554
// try to log everything; logger's configuration will skip extra levels if needed
config.ConnConfig.Tracer = &tracelog.TraceLog{
Logger: zapadapter.NewLogger(l),
LogLevel: tracelog.LogLevelTrace,
}
config.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeCacheStatement
// see https://github.com/jackc/pgx/issues/1726#issuecomment-1711612138
ctx := context.TODO()
p, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, lazyerrors.Error(err)
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err = checkConnection(ctx, p); err != nil {
p.Close()
return nil, lazyerrors.Error(err)
}
return p, nil
}
// simplify simplifies PostgreSQL setting value for comparison.
func simplify(v string) string {
return strings.ToLower(strings.ReplaceAll(v, "-", ""))
}
// checkConnection checks that connection works and PostgreSQL settings are what we expect.
func checkConnection(ctx context.Context, p *pgxpool.Pool) error {
rows, err := p.Query(ctx, "SHOW ALL")
if err != nil {
return lazyerrors.Error(err)
}
defer rows.Close()
for rows.Next() {
// handle variable number of columns as a workaround for https://github.com/cockroachdb/cockroach/issues/101715
values, err := rows.Values()
if err != nil {
return lazyerrors.Error(err)
}
if len(values) < 2 {
return lazyerrors.Errorf("invalid row: %#v", values)
}
n, v := values[0].(string), values[1].(string)
switch n {
case "server_encoding", "client_encoding":
if simplify(v) != simplify(encoding) {
return lazyerrors.Errorf("%q is %q; supported value is %q", n, v, encoding)
}
case "lc_collate", "lc_ctype":
if !slices.ContainsFunc(locales, func(l string) bool { return simplify(v) == simplify(l) }) {
return lazyerrors.Errorf("%q is %q; supported values are %v", n, v, locales)
}
case "standard_conforming_strings":
// To sanitize safely: https://github.com/jackc/pgx/issues/868#issuecomment-725544647
if v != "on" {
return lazyerrors.Errorf("%q is %q, want %q", n, v, "on")
}
}
}
if err := rows.Err(); err != nil {
return lazyerrors.Error(err)
}
return nil
}