-
-
Notifications
You must be signed in to change notification settings - Fork 955
Expand file tree
/
Copy pathcopy.go
More file actions
337 lines (299 loc) · 7.32 KB
/
copy.go
File metadata and controls
337 lines (299 loc) · 7.32 KB
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
package pq
import (
"context"
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"os"
"sync"
"github.com/lib/pq/internal/proto"
)
var (
errCopyInClosed = errors.New("pq: copyin statement has already been closed")
errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY")
errCopyToNotSupported = errors.New("pq: COPY TO is not supported")
errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction")
)
type copyin struct {
cn *conn
buffer []byte
rowData chan []byte
done chan bool
closed bool
mu struct {
sync.Mutex
err error
driver.Result
}
}
const (
ciBufferSize = 64 * 1024
// flush buffer before the buffer is filled up and needs reallocation
ciBufferFlushSize = 63 * 1024
)
func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, resErr error) {
if !cn.isInTransaction() {
return nil, errCopyNotSupportedOutsideTxn
}
ci := ©in{
cn: cn,
buffer: make([]byte, 0, ciBufferSize),
rowData: make(chan []byte),
done: make(chan bool, 1),
}
// add CopyData identifier + 4 bytes for message length
ci.buffer = append(ci.buffer, byte(proto.CopyDataRequest), 0, 0, 0, 0)
b := cn.writeBuf(proto.Query)
b.string(q)
err := cn.send(b)
if err != nil {
return nil, err
}
awaitCopyInResponse:
for {
t, r, err := cn.recv1()
if err != nil {
return nil, err
}
switch t {
case proto.CopyInResponse:
if r.byte() != 0 {
resErr = errBinaryCopyNotSupported
break awaitCopyInResponse
}
go ci.resploop()
return ci, nil
case proto.CopyOutResponse:
resErr = errCopyToNotSupported
break awaitCopyInResponse
case proto.ErrorResponse:
resErr = parseError(r, q)
case proto.ReadyForQuery:
if resErr == nil {
ci.setBad(driver.ErrBadConn)
return nil, fmt.Errorf("pq: unexpected ReadyForQuery in response to COPY")
}
cn.processReadyForQuery(r)
return nil, resErr
default:
ci.setBad(driver.ErrBadConn)
return nil, fmt.Errorf("pq: unknown response for copy query: %q", t)
}
}
// something went wrong, abort COPY before we return
b = cn.writeBuf(proto.CopyFail)
b.string(resErr.Error())
err = cn.send(b)
if err != nil {
return nil, err
}
for {
t, r, err := cn.recv1()
if err != nil {
return nil, err
}
switch t {
case proto.CopyDoneResponse, proto.CommandComplete, proto.ErrorResponse:
case proto.ReadyForQuery:
// correctly aborted, we're done
cn.processReadyForQuery(r)
return nil, resErr
default:
ci.setBad(driver.ErrBadConn)
return nil, fmt.Errorf("pq: unknown response for CopyFail: %q", t)
}
}
}
func (ci *copyin) flush(buf []byte) error {
if len(buf)-1 > proto.MaxUint32 {
return errors.New("pq: too many columns")
}
if debugProto {
fmt.Fprintf(os.Stderr, "CLIENT → %-20s %5d %q\n", proto.RequestCode(buf[0]), len(buf)-5, buf[5:])
}
binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) // Set message length (without message identifier).
_, err := ci.cn.c.Write(buf)
return err
}
func (ci *copyin) resploop() {
for {
var r readBuf
t, err := ci.cn.recvMessage(&r)
if err != nil {
ci.setBad(driver.ErrBadConn)
ci.setError(err)
ci.done <- true
return
}
switch t {
case proto.CommandComplete:
// complete
res, _, err := ci.cn.parseComplete(r.string())
if err != nil {
panic(err)
}
ci.setResult(res)
case proto.NoticeResponse:
if n := ci.cn.noticeHandler; n != nil {
n(parseError(&r, ""))
}
case proto.ReadyForQuery:
ci.cn.processReadyForQuery(&r)
ci.done <- true
return
case proto.ErrorResponse:
err := parseError(&r, "")
ci.setError(err)
default:
ci.setBad(driver.ErrBadConn)
ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t))
ci.done <- true
return
}
}
}
func (ci *copyin) setBad(err error) {
ci.cn.err.set(err)
}
func (ci *copyin) getBad() error {
return ci.cn.err.get()
}
func (ci *copyin) err() error {
ci.mu.Lock()
err := ci.mu.err
ci.mu.Unlock()
return err
}
// setError() sets ci.err if one has not been set already. Caller must not be
// holding ci.Mutex.
func (ci *copyin) setError(err error) {
ci.mu.Lock()
if ci.mu.err == nil {
ci.mu.err = err
}
ci.mu.Unlock()
}
func (ci *copyin) setResult(result driver.Result) {
ci.mu.Lock()
ci.mu.Result = result
ci.mu.Unlock()
}
func (ci *copyin) getResult() driver.Result {
ci.mu.Lock()
result := ci.mu.Result
ci.mu.Unlock()
if result == nil {
return driver.RowsAffected(0)
}
return result
}
func (ci *copyin) NumInput() int {
return -1
}
func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) {
return nil, ErrNotSupported
}
// Exec inserts values into the COPY stream. The insert is asynchronous
// and Exec can return errors from previous Exec calls to the same
// COPY stmt.
//
// You need to call Exec(nil) to sync the COPY stream and to get any
// errors from pending data, since Stmt.Close() doesn't return errors
// to the user.
func (ci *copyin) Exec(v []driver.Value) (driver.Result, error) {
if ci.closed {
return nil, errCopyInClosed
}
if err := ci.getBad(); err != nil {
return nil, err
}
if err := ci.err(); err != nil {
return nil, err
}
if len(v) == 0 {
if err := ci.Close(); err != nil {
return driver.RowsAffected(0), err
}
return ci.getResult(), nil
}
var (
numValues = len(v)
err error
)
for i, value := range v {
ci.buffer, err = appendEncodedText(ci.buffer, value)
if err != nil {
return nil, ci.cn.handleError(err)
}
if i < numValues-1 {
ci.buffer = append(ci.buffer, '\t')
}
}
ci.buffer = append(ci.buffer, '\n')
if len(ci.buffer) > ciBufferFlushSize {
err := ci.flush(ci.buffer)
if err != nil {
return nil, ci.cn.handleError(err)
}
// reset buffer, keep bytes for message identifier and length
ci.buffer = ci.buffer[:5]
}
return driver.RowsAffected(0), nil
}
// CopyData inserts a raw string into the COPY stream. The insert is
// asynchronous and CopyData can return errors from previous CopyData calls to
// the same COPY stmt.
//
// You need to call Exec(nil) to sync the COPY stream and to get any
// errors from pending data, since Stmt.Close() doesn't return errors
// to the user.
func (ci *copyin) CopyData(ctx context.Context, line string) (driver.Result, error) {
if ci.closed {
return nil, errCopyInClosed
}
defer ci.cn.watchCancel(ctx, false)()
if err := ci.getBad(); err != nil {
return nil, err
}
if err := ci.err(); err != nil {
return nil, err
}
ci.buffer = append(ci.buffer, []byte(line)...)
ci.buffer = append(ci.buffer, '\n')
if len(ci.buffer) > ciBufferFlushSize {
err := ci.flush(ci.buffer)
if err != nil {
return nil, ci.cn.handleError(err)
}
// reset buffer, keep bytes for message identifier and length
ci.buffer = ci.buffer[:5]
}
return driver.RowsAffected(0), nil
}
func (ci *copyin) Close() error {
if ci.closed { // Don't do anything, we're already closed
return nil
}
ci.closed = true
if err := ci.getBad(); err != nil {
return err
}
if len(ci.buffer) > 0 {
err := ci.flush(ci.buffer)
if err != nil {
return ci.cn.handleError(err)
}
}
// Avoid touching the scratch buffer as resploop could be using it.
err := ci.cn.sendSimpleMessage(proto.CopyDoneRequest)
if err != nil {
return ci.cn.handleError(err)
}
<-ci.done
ci.cn.inProgress.Store(false)
if err := ci.err(); err != nil {
return err
}
return nil
}