-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql.go
348 lines (291 loc) · 8.21 KB
/
sql.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Package stdlib is the compatibility layer from pgx to database/sql.
//
// A database/sql connection can be established through sql.Open.
//
// db, err := sql.Open("pgx", "postgres://pgx_md5:secret@localhost:5432/pgx_test?sslmode=disable")
// if err != nil {
// return err
// }
//
// Or from a DSN string.
//
// db, err := sql.Open("pgx", "user=postgres password=secret host=localhost port=5432 database=pgx_test sslmode=disable")
// if err != nil {
// return err
// }
//
// Or a normal pgx connection pool can be established and the database/sql
// connection can be created through stdlib.OpenFromConnPool(). This allows
// more control over the connection process (such as TLS), more control
// over the connection pool, setting an AfterConnect hook, and using both
// database/sql and pgx interfaces as needed.
//
// connConfig := pgx.ConnConfig{
// Host: "localhost",
// User: "pgx_md5",
// Password: "secret",
// Database: "pgx_test",
// }
//
// config := pgx.ConnPoolConfig{ConnConfig: connConfig}
// pool, err := pgx.NewConnPool(config)
// if err != nil {
// return err
// }
//
// db, err := stdlib.OpenFromConnPool(pool)
// if err != nil {
// t.Fatalf("Unable to create connection pool: %v", err)
// }
//
// If the database/sql connection is established through
// stdlib.OpenFromConnPool then access to a pgx *ConnPool can be regained
// through db.Driver(). This allows writing a fast path for pgx while
// preserving compatibility with other drivers and database
//
// if driver, ok := db.Driver().(*stdlib.Driver); ok && driver.Pool != nil {
// // fast path with pgx
// } else {
// // normal path for other drivers and databases
// }
package stdlib
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"sync"
"github.com/jackc/pgx"
)
var (
openFromConnPoolCountMu sync.Mutex
openFromConnPoolCount int
)
// oids that map to intrinsic database/sql types. These will be allowed to be
// binary, anything else will be forced to text format
var databaseSqlOids map[pgx.Oid]bool
func init() {
d := &Driver{}
sql.Register("pgx", d)
databaseSqlOids = make(map[pgx.Oid]bool)
databaseSqlOids[pgx.BoolOid] = true
databaseSqlOids[pgx.ByteaOid] = true
databaseSqlOids[pgx.Int2Oid] = true
databaseSqlOids[pgx.Int4Oid] = true
databaseSqlOids[pgx.Int8Oid] = true
databaseSqlOids[pgx.Float4Oid] = true
databaseSqlOids[pgx.Float8Oid] = true
databaseSqlOids[pgx.DateOid] = true
databaseSqlOids[pgx.TimestampTzOid] = true
databaseSqlOids[pgx.TimestampOid] = true
}
type Driver struct {
Pool *pgx.ConnPool
}
func (d *Driver) Open(name string) (driver.Conn, error) {
if d.Pool != nil {
conn, err := d.Pool.Acquire()
if err != nil {
return nil, err
}
return &Conn{conn: conn, pool: d.Pool}, nil
}
connConfig, err := pgx.ParseConnectionString(name)
if err != nil {
return nil, err
}
conn, err := pgx.Connect(connConfig)
if err != nil {
return nil, err
}
c := &Conn{conn: conn}
return c, nil
}
// OpenFromConnPool takes the existing *pgx.ConnPool pool and returns a *sql.DB
// with pool as the backend. This enables full control over the connection
// process and configuration while maintaining compatibility with the
// database/sql interface. In addition, by calling Driver() on the returned
// *sql.DB and typecasting to *stdlib.Driver a reference to the pgx.ConnPool can
// be reaquired later. This allows fast paths targeting pgx to be used while
// still maintaining compatibility with other databases and drivers.
//
// pool connection size must be at least 2.
func OpenFromConnPool(pool *pgx.ConnPool) (*sql.DB, error) {
d := &Driver{Pool: pool}
openFromConnPoolCountMu.Lock()
name := fmt.Sprintf("pgx-%d", openFromConnPoolCount)
openFromConnPoolCount++
openFromConnPoolCountMu.Unlock()
sql.Register(name, d)
db, err := sql.Open(name, "")
if err != nil {
return nil, err
}
// Presumably OpenFromConnPool is being used because the user wants to use
// database/sql most of the time, but fast path with pgx some of the time.
// Allow database/sql to use all the connections, but release 2 idle ones.
// Don't have database/sql immediately release all idle connections because
// that would mean that prepared statements would be lost (which kills
// performance if the prepared statements constantly have to be reprepared)
stat := pool.Stat()
if stat.MaxConnections <= 2 {
return nil, errors.New("pool connection size must be at least 3")
}
db.SetMaxIdleConns(stat.MaxConnections - 2)
db.SetMaxOpenConns(stat.MaxConnections)
return db, nil
}
type Conn struct {
conn *pgx.Conn
pool *pgx.ConnPool
psCount int64 // Counter used for creating unique prepared statement names
}
func (c *Conn) Prepare(query string) (driver.Stmt, error) {
if !c.conn.IsAlive() {
return nil, driver.ErrBadConn
}
name := fmt.Sprintf("pgx_%d", c.psCount)
c.psCount++
ps, err := c.conn.Prepare(name, query)
if err != nil {
return nil, err
}
restrictBinaryToDatabaseSqlTypes(ps)
return &Stmt{ps: ps, conn: c}, nil
}
func (c *Conn) Close() error {
if c.pool != nil {
c.pool.Release(c.conn)
return nil
}
return c.conn.Close()
}
func (c *Conn) Begin() (driver.Tx, error) {
if !c.conn.IsAlive() {
return nil, driver.ErrBadConn
}
_, err := c.conn.Exec("begin")
if err != nil {
return nil, err
}
return &Tx{conn: c.conn}, nil
}
func (c *Conn) Exec(query string, argsV []driver.Value) (driver.Result, error) {
if !c.conn.IsAlive() {
return nil, driver.ErrBadConn
}
args := valueToInterface(argsV)
commandTag, err := c.conn.Exec(query, args...)
return driver.RowsAffected(commandTag.RowsAffected()), err
}
func (c *Conn) Query(query string, argsV []driver.Value) (driver.Rows, error) {
if !c.conn.IsAlive() {
return nil, driver.ErrBadConn
}
ps, err := c.conn.Prepare("", query)
if err != nil {
return nil, err
}
restrictBinaryToDatabaseSqlTypes(ps)
return c.queryPrepared("", argsV)
}
func (c *Conn) queryPrepared(name string, argsV []driver.Value) (driver.Rows, error) {
if !c.conn.IsAlive() {
return nil, driver.ErrBadConn
}
args := valueToInterface(argsV)
rows, err := c.conn.Query(name, args...)
if err != nil {
return nil, err
}
return &Rows{rows: rows}, nil
}
// Anything that isn't a database/sql compatible type needs to be forced to
// text format so that pgx.Rows.Values doesn't decode it into a native type
// (e.g. []int32)
func restrictBinaryToDatabaseSqlTypes(ps *pgx.PreparedStatement) {
for i := range ps.FieldDescriptions {
intrinsic, _ := databaseSqlOids[ps.FieldDescriptions[i].DataType]
if !intrinsic {
ps.FieldDescriptions[i].FormatCode = pgx.TextFormatCode
}
}
}
type Stmt struct {
ps *pgx.PreparedStatement
conn *Conn
}
func (s *Stmt) Close() error {
return s.conn.conn.Deallocate(s.ps.Name)
}
func (s *Stmt) NumInput() int {
return len(s.ps.ParameterOids)
}
func (s *Stmt) Exec(argsV []driver.Value) (driver.Result, error) {
return s.conn.Exec(s.ps.Name, argsV)
}
func (s *Stmt) Query(argsV []driver.Value) (driver.Rows, error) {
return s.conn.queryPrepared(s.ps.Name, argsV)
}
// TODO - rename to avoid alloc
type Rows struct {
rows *pgx.Rows
}
func (r *Rows) Columns() []string {
fieldDescriptions := r.rows.FieldDescriptions()
names := make([]string, 0, len(fieldDescriptions))
for _, fd := range fieldDescriptions {
names = append(names, fd.Name)
}
return names
}
func (r *Rows) Close() error {
r.rows.Close()
return nil
}
func (r *Rows) Next(dest []driver.Value) error {
more := r.rows.Next()
if !more {
if r.rows.Err() == nil {
return io.EOF
} else {
return r.rows.Err()
}
}
values, err := r.rows.Values()
if err != nil {
return err
}
if len(dest) < len(values) {
fmt.Printf("%d: %#v\n", len(dest), dest)
fmt.Printf("%d: %#v\n", len(values), values)
return errors.New("expected more values than were received")
}
for i, v := range values {
dest[i] = driver.Value(v)
}
return nil
}
func valueToInterface(argsV []driver.Value) []interface{} {
args := make([]interface{}, 0, len(argsV))
for _, v := range argsV {
if v != nil {
args = append(args, v.(interface{}))
} else {
args = append(args, nil)
}
}
return args
}
type Tx struct {
conn *pgx.Conn
}
func (t *Tx) Commit() error {
_, err := t.conn.Exec("commit")
return err
}
func (t *Tx) Rollback() error {
_, err := t.conn.Exec("rollback")
return err
}