forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.go
207 lines (189 loc) · 5.37 KB
/
async.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
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
)
func isAsyncModeNoFetch(ctx context.Context) bool {
if flag, ok := ctx.Value(asyncModeNoFetch).(bool); ok && flag {
return true
}
return false
}
func (sr *snowflakeRestful) processAsync(
ctx context.Context,
respd *execResponse,
headers map[string]string,
timeout time.Duration,
cfg *Config,
requestID UUID) (*execResponse, error) {
// placeholder object to return to user while retrieving results
rows := new(snowflakeRows)
res := new(snowflakeResult)
switch resType := getResultType(ctx); resType {
case execResultType:
res.queryID = respd.Data.QueryID
res.status = QueryStatusInProgress
res.errChannel = make(chan error)
respd.Data.AsyncResult = res
case queryResultType:
rows.queryID = respd.Data.QueryID
rows.status = QueryStatusInProgress
rows.errChannel = make(chan error)
respd.Data.AsyncRows = rows
default:
return respd, nil
}
// spawn goroutine to retrieve asynchronous results
go func() {
_ = sr.getAsync(ctx, headers, sr.getFullURL(respd.Data.GetResultURL, nil), timeout, res, rows, requestID, cfg)
}()
return respd, nil
}
func (sr *snowflakeRestful) getAsync(
ctx context.Context,
headers map[string]string,
URL *url.URL,
timeout time.Duration,
res *snowflakeResult,
rows *snowflakeRows,
requestID UUID,
cfg *Config) error {
resType := getResultType(ctx)
var errChannel chan error
sfError := &SnowflakeError{
Number: ErrAsync,
}
if resType == execResultType {
errChannel = res.errChannel
sfError.QueryID = res.queryID
} else {
errChannel = rows.errChannel
sfError.QueryID = rows.queryID
}
defer close(errChannel)
token, _, _ := sr.TokenAccessor.GetTokens()
headers[headerAuthorizationKey] = fmt.Sprintf(headerSnowflakeToken, token)
// the get call pulling for result status is
var response *execResponse
var err error
for response == nil || isQueryInProgress(response) {
response, err = sr.getAsyncOrStatus(ctx, URL, headers, timeout)
if err != nil {
logger.WithContext(ctx).Errorf("failed to get response. err: %v", err)
if err == context.Canceled || err == context.DeadlineExceeded {
// use the default top level 1 sec timeout for cancellation as throughout the driver
if err := cancelQuery(context.TODO(), sr, requestID, time.Second); err != nil {
logger.WithContext(ctx).Errorf("failed to cancel async query, err: %v", err)
}
}
sfError.Message = err.Error()
errChannel <- sfError
return err
}
}
sc := &snowflakeConn{rest: sr, cfg: cfg, queryContextCache: (&queryContextCache{}).init(), currentTimeProvider: defaultTimeProvider}
// the result response sometimes contains only Data and not anything else.
// if code is not set we treat as success
if response.Success || response.Code == "" {
if resType == execResultType {
res.insertID = -1
if isDml(response.Data.StatementTypeID) {
res.affectedRows, err = updateRows(response.Data)
if err != nil {
return err
}
} else if isMultiStmt(&response.Data) {
r, err := sc.handleMultiExec(ctx, response.Data)
if err != nil {
res.errChannel <- err
return err
}
res.affectedRows, err = r.RowsAffected()
if err != nil {
res.errChannel <- err
return err
}
}
res.queryID = response.Data.QueryID
res.errChannel <- nil // mark exec status complete
} else {
rows.sc = sc
rows.queryID = response.Data.QueryID
if !isAsyncModeNoFetch(ctx) {
if isMultiStmt(&response.Data) {
if err = sc.handleMultiQuery(ctx, response.Data, rows); err != nil {
rows.errChannel <- err
close(errChannel)
return err
}
} else {
rows.addDownloader(populateChunkDownloader(ctx, sc, response.Data))
}
if err = rows.ChunkDownloader.start(); err != nil {
rows.errChannel <- err
close(errChannel)
return err
}
}
rows.errChannel <- nil // mark query status complete
}
} else {
errChannel <- &SnowflakeError{
Number: parseCode(response.Code),
SQLState: response.Data.SQLState,
Message: response.Message,
QueryID: response.Data.QueryID,
}
}
return nil
}
func isQueryInProgress(execResponse *execResponse) bool {
if !execResponse.Success {
return false
}
switch parseCode(execResponse.Code) {
case ErrQueryExecutionInProgress, ErrAsyncExecutionInProgress:
return true
default:
return false
}
}
func parseCode(codeStr string) int {
if code, err := strconv.Atoi(codeStr); err == nil {
return code
}
return -1
}
func (sr *snowflakeRestful) getAsyncOrStatus(
ctx context.Context,
url *url.URL,
headers map[string]string,
timeout time.Duration) (*execResponse, error) {
startTime := time.Now()
resp, err := sr.FuncGet(ctx, sr, url, headers, timeout)
if err != nil {
return nil, err
}
if reportAsyncErrorFromContext(ctx) {
// if we dont get a response, or we get a bad response, this is not expected, so derive the information to know
// why this happened and panic with that message
if resp == nil || resp.StatusCode != http.StatusOK {
panicMessage := newPanicMessage(ctx, resp, startTime, timeout)
panic(panicMessage)
}
}
if resp.Body != nil {
defer func() { _ = resp.Body.Close() }()
}
response := &execResponse{}
if err = json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, err
}
return response, nil
}