forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind_uploader.go
281 lines (262 loc) · 7.37 KB
/
bind_uploader.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
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"bytes"
"context"
"database/sql/driver"
"fmt"
"reflect"
"strconv"
"strings"
)
const (
bindStageName = "SYSTEM$BIND"
createTemporaryStageStmt = "CREATE OR REPLACE TEMPORARY STAGE " + bindStageName +
" file_format=" + "(type=csv field_optionally_enclosed_by='\"')"
// size (in bytes) of max input stream (10MB default) as per JDBC specs
inputStreamBufferSize = 1024 * 1024 * 10
)
type bindUploader struct {
ctx context.Context
sc *snowflakeConn
stagePath string
fileCount int
arrayBindStage string
}
func (bu *bindUploader) upload(bindings []driver.NamedValue) (*execResponse, error) {
bindingRows, err := bu.buildRowsAsBytes(bindings)
if err != nil {
return nil, err
}
startIdx, numBytes, rowNum := 0, 0, 0
bu.fileCount = 0
var data *execResponse
for rowNum < len(bindingRows) {
for numBytes < inputStreamBufferSize && rowNum < len(bindingRows) {
numBytes += len(bindingRows[rowNum])
rowNum++
}
// concatenate all byte arrays into 1 and put into input stream
var b bytes.Buffer
b.Grow(numBytes)
for i := startIdx; i < rowNum; i++ {
b.Write(bindingRows[i])
}
bu.fileCount++
data, err = bu.uploadStreamInternal(&b, bu.fileCount, true)
if err != nil {
return nil, err
}
startIdx = rowNum
numBytes = 0
}
return data, nil
}
func (bu *bindUploader) uploadStreamInternal(
inputStream *bytes.Buffer,
dstFileName int,
compressData bool) (
*execResponse, error) {
if err := bu.createStageIfNeeded(); err != nil {
return nil, err
}
stageName := bu.stagePath
if stageName == "" {
return nil, (&SnowflakeError{
Number: ErrBindUpload,
Message: "stage name is null",
}).exceptionTelemetry(bu.sc)
}
// use a placeholder for source file
putCommand := fmt.Sprintf("put 'file:///tmp/placeholder/%v' '%v' overwrite=true", dstFileName, stageName)
// for Windows queries
putCommand = strings.ReplaceAll(putCommand, "\\", "\\\\")
// prepare context for PUT command
ctx := WithFileStream(bu.ctx, inputStream)
ctx = WithFileTransferOptions(ctx, &SnowflakeFileTransferOptions{
compressSourceFromStream: compressData})
return bu.sc.exec(ctx, putCommand, false, true, false, []driver.NamedValue{})
}
func (bu *bindUploader) createStageIfNeeded() error {
if bu.arrayBindStage != "" {
return nil
}
data, err := bu.sc.exec(bu.ctx, createTemporaryStageStmt, false, false, false, []driver.NamedValue{})
if err != nil {
newThreshold := "0"
bu.sc.cfg.Params[sessionArrayBindStageThreshold] = &newThreshold
return err
}
if !data.Success {
code, err := strconv.Atoi(data.Code)
if err != nil {
return err
}
return (&SnowflakeError{
Number: code,
SQLState: data.Data.SQLState,
Message: err.Error(),
QueryID: data.Data.QueryID,
}).exceptionTelemetry(bu.sc)
}
bu.arrayBindStage = bindStageName
return nil
}
// transpose the columns to rows and write them to a list of bytes
func (bu *bindUploader) buildRowsAsBytes(columns []driver.NamedValue) ([][]byte, error) {
numColumns := len(columns)
if columns[0].Value == nil {
return nil, (&SnowflakeError{
Number: ErrBindSerialization,
Message: "no binds found in the first column",
}).exceptionTelemetry(bu.sc)
}
_, column := snowflakeArrayToString(&columns[0], true)
numRows := len(column)
csvRows := make([][]byte, 0)
rows := make([][]string, 0)
for rowIdx := 0; rowIdx < numRows; rowIdx++ {
rows = append(rows, make([]string, numColumns))
}
for rowIdx := 0; rowIdx < numRows; rowIdx++ {
rows[rowIdx][0] = *column[rowIdx]
}
for colIdx := 1; colIdx < numColumns; colIdx++ {
_, column = snowflakeArrayToString(&columns[colIdx], true)
iNumRows := len(column)
if iNumRows != numRows {
return nil, (&SnowflakeError{
Number: ErrBindSerialization,
Message: errMsgBindColumnMismatch,
MessageArgs: []interface{}{colIdx, iNumRows, numRows},
}).exceptionTelemetry(bu.sc)
}
for rowIdx := 0; rowIdx < numRows; rowIdx++ {
rows[rowIdx][colIdx] = *column[rowIdx] // length of column = number of rows
}
}
for _, row := range rows {
csvRows = append(csvRows, bu.createCSVRecord(row))
}
return csvRows, nil
}
func (bu *bindUploader) createCSVRecord(data []string) []byte {
var b strings.Builder
b.Grow(1024)
for i := 0; i < len(data); i++ {
if i > 0 {
b.WriteString(",")
}
b.WriteString(escapeForCSV(data[i]))
}
b.WriteString("\n")
return []byte(b.String())
}
func (sc *snowflakeConn) processBindings(
ctx context.Context,
bindings []driver.NamedValue,
describeOnly bool,
requestID UUID,
req *execRequest) error {
arrayBindThreshold := sc.getArrayBindStageThreshold()
numBinds := arrayBindValueCount(bindings)
if 0 < arrayBindThreshold && arrayBindThreshold <= numBinds && !describeOnly && isArrayBind(bindings) {
uploader := bindUploader{
sc: sc,
ctx: ctx,
stagePath: "@" + bindStageName + "/" + requestID.String(),
}
uploader.upload(bindings)
req.Bindings = nil
req.BindStage = uploader.stagePath
} else {
var err error
req.Bindings, err = getBindValues(bindings)
if err != nil {
return err
}
req.BindStage = ""
}
return nil
}
func getBindValues(bindings []driver.NamedValue) (map[string]execBindParameter, error) {
tsmode := timestampNtzType
idx := 1
var err error
bindValues := make(map[string]execBindParameter, len(bindings))
for _, binding := range bindings {
t := goTypeToSnowflake(binding.Value, tsmode)
if t == changeType {
tsmode, err = dataTypeMode(binding.Value)
if err != nil {
return nil, err
}
} else {
var val interface{}
if t == sliceType {
// retrieve array binding data
t, val = snowflakeArrayToString(&binding, false)
} else {
val, err = valueToString(binding.Value, tsmode)
if err != nil {
return nil, err
}
}
if t == nullType || t == unSupportedType {
t = textType // if null or not supported, pass to GS as text
}
bindValues[strconv.Itoa(idx)] = execBindParameter{
Type: t.String(),
Value: val,
}
idx++
}
}
return bindValues, nil
}
func arrayBindValueCount(bindValues []driver.NamedValue) int {
if !isArrayBind(bindValues) {
return 0
}
_, arr := snowflakeArrayToString(&bindValues[0], false)
return len(bindValues) * len(arr)
}
func isArrayBind(bindings []driver.NamedValue) bool {
if len(bindings) == 0 {
return false
}
for _, binding := range bindings {
if supported := supportedArrayBind(&binding); !supported {
return false
}
}
return true
}
func supportedArrayBind(nv *driver.NamedValue) bool {
switch reflect.TypeOf(nv.Value) {
case reflect.TypeOf(&intArray{}), reflect.TypeOf(&int32Array{}),
reflect.TypeOf(&int64Array{}), reflect.TypeOf(&float64Array{}),
reflect.TypeOf(&float32Array{}), reflect.TypeOf(&boolArray{}),
reflect.TypeOf(&stringArray{}), reflect.TypeOf(&byteArray{}),
reflect.TypeOf(×tampNtzArray{}), reflect.TypeOf(×tampLtzArray{}),
reflect.TypeOf(×tampTzArray{}), reflect.TypeOf(&dateArray{}),
reflect.TypeOf(&timeArray{}):
return true
case reflect.TypeOf([]uint8{}):
// internal binding ts mode
val, ok := nv.Value.([]uint8)
if !ok {
return ok
}
if len(val) == 0 {
return true // for null binds
}
if fixedType <= snowflakeType(val[0]) && snowflakeType(val[0]) <= unSupportedType {
return true
}
return false
default:
// TODO SNOW-176486 variant, object, array
return false
}
}