forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
put_get_with_aws_test.go
373 lines (340 loc) · 10.4 KB
/
put_get_with_aws_test.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func TestLoadS3(t *testing.T) {
if runningOnGithubAction() && !runningOnAWS() {
t.Skip("skipping non aws environment")
}
runTests(t, dsn, func(dbt *DBTest) {
data, err := createTestData(dbt)
if err != nil {
t.Skip("snowflake admin account not accessible")
}
defer cleanupPut(dbt, data)
dbt.mustExec("use warehouse " + data.warehouse)
dbt.mustExec("use schema " + data.database + ".gotesting_schema")
execQuery := `create or replace table tweets(created_at timestamp,
id number, id_str string, text string, source string,
in_reply_to_status_id number, in_reply_to_status_id_str string,
in_reply_to_user_id number, in_reply_to_user_id_str string,
in_reply_to_screen_name string, user__id number, user__id_str string,
user__name string, user__screen_name string, user__location string,
user__description string, user__url string,
user__entities__description__urls string, user__protected string,
user__followers_count number, user__friends_count number,
user__listed_count number, user__created_at timestamp,
user__favourites_count number, user__utc_offset number,
user__time_zone string, user__geo_enabled string,
user__verified string, user__statuses_count number, user__lang string,
user__contributors_enabled string, user__is_translator string,
user__profile_background_color string,
user__profile_background_image_url string,
user__profile_background_image_url_https string,
user__profile_background_tile string, user__profile_image_url string,
user__profile_image_url_https string, user__profile_link_color string,
user__profile_sidebar_border_color string,
user__profile_sidebar_fill_color string, user__profile_text_color string,
user__profile_use_background_image string, user__default_profile string,
user__default_profile_image string, user__following string,
user__follow_request_sent string, user__notifications string,
geo string, coordinates string, place string, contributors string,
retweet_count number, favorite_count number, entities__hashtags string,
entities__symbols string, entities__urls string,
entities__user_mentions string, favorited string, retweeted string,
lang string)`
dbt.mustExec(execQuery)
defer dbt.mustExec("drop table if exists tweets")
dbt.mustQueryAssertCount("ls @%tweets", 0)
rows := dbt.mustQuery(fmt.Sprintf(`copy into tweets from
s3://sfc-dev1-data/twitter/O1k/tweets/ credentials=(AWS_KEY_ID='%v'
AWS_SECRET_KEY='%v') file_format=(skip_header=1 null_if=('')
field_optionally_enclosed_by='\"')`,
data.awsAccessKeyID, data.awsSecretAccessKey))
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9 string
cnt := 0
for rows.Next() {
rows.Scan(&s0, &s1, &s2, &s3, &s4, &s5, &s6, &s7, &s8, &s9)
cnt++
}
if cnt != 1 {
t.Fatal("copy into tweets did not set row count to 1")
}
if s0 != "s3://sfc-dev1-data/twitter/O1k/tweets/1.csv.gz" {
t.Fatalf("got %v as file", s0)
}
})
}
func TestPutWithInvalidToken(t *testing.T) {
if !runningOnAWS() {
t.Skip("skipping non aws environment")
}
tmpDir, err := ioutil.TempDir("", "aws_put")
if err != nil {
t.Error(err)
}
defer os.RemoveAll(tmpDir)
fname := filepath.Join(tmpDir, "test_put_get_with_aws.txt.gz")
originalContents := "123,test1\n456,test2\n"
var b bytes.Buffer
gzw := gzip.NewWriter(&b)
gzw.Write([]byte(originalContents))
gzw.Close()
if err := ioutil.WriteFile(fname, b.Bytes(), os.ModePerm); err != nil {
t.Fatal("could not write to gzip file")
}
config, err := ParseDSN(dsn)
if err != nil {
t.Error(err)
}
sc, err := buildSnowflakeConn(context.Background(), *config)
if err != nil {
t.Fatal(err)
}
if err = authenticateWithConfig(sc); err != nil {
t.Fatal(err)
}
tableName := randomString(5)
if _, err = sc.Exec("create or replace table "+tableName+
" (a int, b string)", nil); err != nil {
t.Fatal(err)
}
defer sc.Exec("drop table "+tableName, nil)
jsonBody, err := json.Marshal(execRequest{
SQLText: fmt.Sprintf("put 'file://%v' @%%%v", fname, tableName),
})
if err != nil {
t.Error(err)
}
headers := getHeaders()
headers[httpHeaderAccept] = headerContentTypeApplicationJSON
data, err := sc.rest.FuncPostQuery(
sc.ctx, sc.rest, &url.Values{}, headers, jsonBody,
sc.rest.RequestTimeout, getOrGenerateRequestIDFromContext(sc.ctx), sc.cfg)
if err != nil {
t.Fatal(err)
}
s3Util := new(snowflakeS3Client)
s3Cli, err := s3Util.createClient(&data.Data.StageInfo, false)
if err != nil {
t.Error(err)
}
client := s3Cli.(*s3.Client)
s3Loc, err := s3Util.extractBucketNameAndPath(data.Data.StageInfo.Location)
if err != nil {
t.Error(err)
}
s3Path := s3Loc.s3Path + baseName(fname) + ".gz"
f, err := os.Open(fname)
if err != nil {
t.Error(err)
}
defer f.Close()
uploader := manager.NewUploader(client)
if _, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
Bucket: &s3Loc.bucketName,
Key: &s3Path,
Body: f,
}); err != nil {
t.Fatal(err)
}
parentPath := filepath.Dir(filepath.Dir(s3Path)) + "/"
if _, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
Bucket: &s3Loc.bucketName,
Key: &parentPath,
Body: f,
}); err == nil {
t.Fatal("should have failed attempting to put file in parent path")
}
info := execResponseStageInfo{
Creds: execResponseCredentials{
AwsID: data.Data.StageInfo.Creds.AwsID,
AwsSecretKey: data.Data.StageInfo.Creds.AwsSecretKey,
},
}
s3Cli, err = s3Util.createClient(&info, false)
if err != nil {
t.Error(err)
}
client = s3Cli.(*s3.Client)
uploader = manager.NewUploader(client)
if _, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
Bucket: &s3Loc.bucketName,
Key: &s3Path,
Body: f,
}); err == nil {
t.Fatal("should have failed attempting to put with missing aws token")
}
}
func TestPretendToPutButList(t *testing.T) {
if runningOnGithubAction() && !runningOnAWS() {
t.Skip("skipping non aws environment")
}
tmpDir, err := ioutil.TempDir("", "aws_put")
if err != nil {
t.Error(err)
}
defer os.RemoveAll(tmpDir)
fname := filepath.Join(tmpDir, "test_put_get_with_aws.txt.gz")
originalContents := "123,test1\n456,test2\n"
var b bytes.Buffer
gzw := gzip.NewWriter(&b)
gzw.Write([]byte(originalContents))
gzw.Close()
if err := ioutil.WriteFile(fname, b.Bytes(), os.ModePerm); err != nil {
t.Fatal("could not write to gzip file")
}
config, err := ParseDSN(dsn)
if err != nil {
t.Error(err)
}
sc, err := buildSnowflakeConn(context.Background(), *config)
if err != nil {
t.Fatal(err)
}
if err = authenticateWithConfig(sc); err != nil {
t.Fatal(err)
}
tableName := randomString(5)
if _, err = sc.Exec("create or replace table "+tableName+
" (a int, b string)", nil); err != nil {
t.Fatal(err)
}
defer sc.Exec("drop table "+tableName, nil)
jsonBody, err := json.Marshal(execRequest{
SQLText: fmt.Sprintf("put 'file://%v' @%%%v", fname, tableName),
})
if err != nil {
t.Error(err)
}
headers := getHeaders()
headers[httpHeaderAccept] = headerContentTypeApplicationJSON
data, err := sc.rest.FuncPostQuery(
sc.ctx, sc.rest, &url.Values{}, headers, jsonBody,
sc.rest.RequestTimeout, getOrGenerateRequestIDFromContext(sc.ctx), sc.cfg)
if err != nil {
t.Fatal(err)
}
s3Util := new(snowflakeS3Client)
s3Cli, err := s3Util.createClient(&data.Data.StageInfo, false)
if err != nil {
t.Error(err)
}
client := s3Cli.(*s3.Client)
if _, err = client.ListBuckets(context.Background(),
&s3.ListBucketsInput{}); err == nil {
t.Fatal("list buckets should fail")
}
}
func TestPutGetAWSStage(t *testing.T) {
if runningOnGithubAction() && !runningOnAWS() {
t.Skip("skipping non aws environment")
}
tmpDir, err := ioutil.TempDir("", "put_get")
if err != nil {
t.Error(err)
}
defer os.RemoveAll(tmpDir)
name := "test_put_get.txt.gz"
fname := filepath.Join(tmpDir, name)
originalContents := "123,test1\n456,test2\n"
stageName := "test_put_get_stage_" + randomString(5)
var b bytes.Buffer
gzw := gzip.NewWriter(&b)
gzw.Write([]byte(originalContents))
gzw.Close()
if err = ioutil.WriteFile(fname, b.Bytes(), os.ModePerm); err != nil {
t.Fatal("could not write to gzip file")
}
runTests(t, dsn, func(dbt *DBTest) {
var createStageQuery string
keyID, secretKey, _, err := getAWSCredentials()
if err != nil {
t.Skip("snowflake admin account not accessible")
}
createStageQuery = fmt.Sprintf(createStageStmt,
stageName,
"s3://"+stageName,
fmt.Sprintf("AWS_KEY_ID='%v' AWS_SECRET_KEY='%v'", keyID, secretKey))
dbt.mustExec(createStageQuery)
defer dbt.mustExec("DROP STAGE IF EXISTS " + stageName)
sql := "put 'file://%v' @~/%v auto_compress=false"
sqlText := fmt.Sprintf(sql, strings.ReplaceAll(fname, "\\", "\\\\"), stageName)
rows := dbt.mustQuery(sqlText)
var s0, s1, s2, s3, s4, s5, s6, s7 string
if rows.Next() {
if err = rows.Scan(&s0, &s1, &s2, &s3, &s4, &s5, &s6, &s7); err != nil {
t.Fatal(err)
}
}
if s6 != uploaded.String() {
t.Fatalf("expected %v, got: %v", uploaded, s6)
}
sql = fmt.Sprintf("get @~/%v 'file://%v'", stageName, tmpDir)
sqlText = strings.ReplaceAll(sql, "\\", "\\\\")
rows = dbt.mustQuery(sqlText)
defer rows.Close()
for rows.Next() {
if err = rows.Scan(&s0, &s1, &s2, &s3); err != nil {
t.Error(err)
}
if strings.Compare(s0, name) != 0 {
t.Error("a file was not downloaded by GET")
}
if v, err := strconv.Atoi(s1); err != nil || v != 41 {
t.Error("did not return the right file size")
}
if s2 != "DOWNLOADED" {
t.Error("did not return DOWNLOADED status")
}
if s3 != "" {
t.Errorf("returned %v", s3)
}
}
files, err := filepath.Glob(filepath.Join(tmpDir, "*"))
if err != nil {
t.Fatal(err)
}
fileName := files[0]
f, err := os.Open(fileName)
if err != nil {
t.Error(err)
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
t.Error(err)
}
var contents string
for {
c := make([]byte, defaultChunkBufferSize)
if n, err := gz.Read(c); err != nil {
if err == io.EOF {
contents = contents + string(c[:n])
break
}
t.Error(err)
} else {
contents = contents + string(c[:n])
}
}
if contents != originalContents {
t.Error("output is different from the original file")
}
})
}