forked from upper/db
/
connection.go
292 lines (246 loc) · 6.63 KB
/
connection.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (c) 2012-present The upper.io/db authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package postgresql
import (
"fmt"
"net"
"strings"
"unicode"
"github.com/lib/pq"
)
// scanner implements a tokenizer for libpq-style option strings.
type scanner struct {
s []rune
i int
}
// Next returns the next rune. It returns 0, false if the end of the text has
// been reached.
func (s *scanner) Next() (rune, bool) {
if s.i >= len(s.s) {
return 0, false
}
r := s.s[s.i]
s.i++
return r, true
}
// SkipSpaces returns the next non-whitespace rune. It returns 0, false if the
// end of the text has been reached.
func (s *scanner) SkipSpaces() (rune, bool) {
r, ok := s.Next()
for unicode.IsSpace(r) && ok {
r, ok = s.Next()
}
return r, ok
}
type values map[string]string
func (vs values) Set(k, v string) {
vs[k] = v
}
func (vs values) Get(k string) (v string) {
return vs[k]
}
func (vs values) Isset(k string) bool {
_, ok := vs[k]
return ok
}
// ConnectionURL represents a parsed PostgreSQL connection URL.
//
// You can use a ConnectionURL struct as an argument for Open:
//
// var settings = postgresql.ConnectionURL{
// Host: "localhost", // PostgreSQL server IP or name.
// Database: "peanuts", // Database name.
// User: "cbrown", // Optional user name.
// Password: "snoopy", // Optional user password.
// }
//
// sess, err = postgresql.Open(settings)
//
// If you already have a valid DSN, you can use ParseURL to convert it into
// a ConnectionURL before passing it to Open.
type ConnectionURL struct {
User string
Password string
Host string
Socket string
Database string
Options map[string]string
}
var escaper = strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
// String reassembles the parsed PostgreSQL connection URL into a valid DSN.
func (c ConnectionURL) String() (s string) {
u := make([]string, 0, 6)
// TODO: This surely needs some sort of escaping.
if c.User != "" {
u = append(u, "user="+escaper.Replace(c.User))
}
if c.Password != "" {
u = append(u, "password="+escaper.Replace(c.Password))
}
if c.Host != "" {
host, port, err := net.SplitHostPort(c.Host)
if err == nil {
if host == "" {
host = "127.0.0.1"
}
if port == "" {
port = "5432"
}
u = append(u, "host="+escaper.Replace(host))
u = append(u, "port="+escaper.Replace(port))
} else {
u = append(u, "host="+escaper.Replace(c.Host))
}
}
if c.Socket != "" {
u = append(u, "host="+escaper.Replace(c.Socket))
}
if c.Database != "" {
u = append(u, "dbname="+escaper.Replace(c.Database))
}
// Is there actually any connection data?
if len(u) == 0 {
return ""
}
if c.Options == nil {
c.Options = map[string]string{}
}
// If not present, SSL mode is assumed disabled.
if sslMode, ok := c.Options["sslmode"]; !ok || sslMode == "" {
c.Options["sslmode"] = "disable"
}
for k, v := range c.Options {
u = append(u, escaper.Replace(k)+"="+escaper.Replace(v))
}
return strings.Join(u, " ")
}
// ParseURL parses the given DSN into a ConnectionURL struct.
// A typical PostgreSQL connection URL looks like:
//
// postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full
func ParseURL(s string) (u ConnectionURL, err error) {
o := make(values)
if strings.HasPrefix(s, "postgres://") {
s, err = pq.ParseURL(s)
if err != nil {
return u, err
}
}
if err := parseOpts(s, o); err != nil {
return u, err
}
u.User = o.Get("user")
u.Password = o.Get("password")
h := o.Get("host")
p := o.Get("port")
if strings.HasPrefix(h, "/") {
u.Socket = h
} else {
if p == "" {
u.Host = h
} else {
u.Host = fmt.Sprintf("%s:%s", h, p)
}
}
u.Database = o.Get("dbname")
u.Options = make(map[string]string)
for k := range o {
switch k {
case "user", "password", "host", "port", "dbname":
// Skip
default:
u.Options[k] = o[k]
}
}
return u, err
}
// parseOpts parses the options from name and adds them to the values.
//
// The parsing code is based on conninfo_parse from libpq's fe-connect.c
func parseOpts(name string, o values) error {
s := newScanner(name)
for {
var (
keyRunes, valRunes []rune
r rune
ok bool
)
if r, ok = s.SkipSpaces(); !ok {
break
}
// Scan the key
for !unicode.IsSpace(r) && r != '=' {
keyRunes = append(keyRunes, r)
if r, ok = s.Next(); !ok {
break
}
}
// Skip any whitespace if we're not at the = yet
if r != '=' {
r, ok = s.SkipSpaces()
}
// The current character should be =
if r != '=' || !ok {
return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes))
}
// Skip any whitespace after the =
if r, ok = s.SkipSpaces(); !ok {
// If we reach the end here, the last value is just an empty string as per libpq.
o.Set(string(keyRunes), "")
break
}
if r != '\'' {
for !unicode.IsSpace(r) {
if r == '\\' {
if r, ok = s.Next(); !ok {
return fmt.Errorf(`missing character after backslash`)
}
}
valRunes = append(valRunes, r)
if r, ok = s.Next(); !ok {
break
}
}
} else {
quote:
for {
if r, ok = s.Next(); !ok {
return fmt.Errorf(`unterminated quoted string literal in connection string`)
}
switch r {
case '\'':
break quote
case '\\':
r, _ = s.Next()
fallthrough
default:
valRunes = append(valRunes, r)
}
}
}
o.Set(string(keyRunes), string(valRunes))
}
return nil
}
// newScanner returns a new scanner initialized with the option string s.
func newScanner(s string) *scanner {
return &scanner{[]rune(s), 0}
}