-
Notifications
You must be signed in to change notification settings - Fork 124
/
driver_test.go
1776 lines (1636 loc) · 44.3 KB
/
driver_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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"context"
"crypto/rsa"
"database/sql"
"database/sql/driver"
"flag"
"fmt"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"testing"
"time"
)
var (
username string
pass string
account string
dbname string
schemaname string
warehouse string
rolename string
dsn string
host string
port string
protocol string
customPrivateKey bool // Whether user has specified the private key path
testPrivKey *rsa.PrivateKey // Valid private key used for all test cases
)
const (
selectNumberSQL = "SELECT %s::NUMBER(%v, %v) AS C"
selectVariousTypes = "SELECT 1.0::NUMBER(30,2) as C1, 2::NUMBER(38,0) AS C2, 't3' AS C3, 4.2::DOUBLE AS C4, 'abcd'::BINARY AS C5, true AS C6"
selectRandomGenerator = "SELECT SEQ8(), RANDSTR(1000, RANDOM()) FROM TABLE(GENERATOR(ROWCOUNT=>%v))"
PSTLocation = "America/Los_Angeles"
)
// The tests require the following parameters in the environment variables.
// SNOWFLAKE_TEST_USER, SNOWFLAKE_TEST_PASSWORD, SNOWFLAKE_TEST_ACCOUNT,
// SNOWFLAKE_TEST_DATABASE, SNOWFLAKE_TEST_SCHEMA, SNOWFLAKE_TEST_WAREHOUSE.
// Optionally you may specify SNOWFLAKE_TEST_PROTOCOL, SNOWFLAKE_TEST_HOST
// and SNOWFLAKE_TEST_PORT to specify the endpoint.
func init() {
// get environment variables
env := func(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
username = env("SNOWFLAKE_TEST_USER", "testuser")
pass = env("SNOWFLAKE_TEST_PASSWORD", "testpassword")
account = env("SNOWFLAKE_TEST_ACCOUNT", "testaccount")
dbname = env("SNOWFLAKE_TEST_DATABASE", "testdb")
schemaname = env("SNOWFLAKE_TEST_SCHEMA", "public")
rolename = env("SNOWFLAKE_TEST_ROLE", "sysadmin")
warehouse = env("SNOWFLAKE_TEST_WAREHOUSE", "testwarehouse")
protocol = env("SNOWFLAKE_TEST_PROTOCOL", "https")
host = os.Getenv("SNOWFLAKE_TEST_HOST")
port = env("SNOWFLAKE_TEST_PORT", "443")
if host == "" {
host = fmt.Sprintf("%s.snowflakecomputing.com", account)
} else {
host = fmt.Sprintf("%s:%s", host, port)
}
setupPrivateKey()
createDSN("UTC")
}
func createDSN(timezone string) {
dsn = fmt.Sprintf("%s:%s@%s/%s/%s", username, pass, host, dbname, schemaname)
parameters := url.Values{}
parameters.Add("timezone", timezone)
if protocol != "" {
parameters.Add("protocol", protocol)
}
if account != "" {
parameters.Add("account", account)
}
if warehouse != "" {
parameters.Add("warehouse", warehouse)
}
if rolename != "" {
parameters.Add("role", rolename)
}
if len(parameters) > 0 {
dsn += "?" + parameters.Encode()
}
}
// setup creates a test schema so that all tests can run in the same schema
func setup() (string, error) {
env := func(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
orgSchemaname := schemaname
if env("GITHUB_WORKFLOW", "") != "" {
githubRunnerID := env("RUNNER_TRACKING_ID", "GITHUB_RUNNER_ID")
githubRunnerID = strings.ReplaceAll(githubRunnerID, "-", "_")
githubSha := env("GITHUB_SHA", "GITHUB_SHA")
schemaname = fmt.Sprintf("%v_%v", githubRunnerID, githubSha)
} else {
schemaname = fmt.Sprintf("golang_%v", time.Now().UnixNano())
}
var db *sql.DB
var err error
if db, err = sql.Open("snowflake", dsn); err != nil {
return "", fmt.Errorf("failed to open db. err: %v", err)
}
defer db.Close()
if _, err = db.Exec(fmt.Sprintf("CREATE OR REPLACE SCHEMA %v", schemaname)); err != nil {
return "", fmt.Errorf("failed to create schema. %v", err)
}
createDSN("UTC")
return orgSchemaname, nil
}
// teardown drops the test schema
func teardown() error {
var db *sql.DB
var err error
if db, err = sql.Open("snowflake", dsn); err != nil {
return fmt.Errorf("failed to open db. %v, err: %v", dsn, err)
}
defer db.Close()
if _, err = db.Exec(fmt.Sprintf("DROP SCHEMA IF EXISTS %v", schemaname)); err != nil {
return fmt.Errorf("failed to create schema. %v", err)
}
return nil
}
func TestMain(m *testing.M) {
flag.Parse()
signal.Ignore(syscall.SIGQUIT)
if value := os.Getenv("SKIP_SETUP"); value != "" {
os.Exit(m.Run())
}
if _, err := setup(); err != nil {
panic(err)
}
ret := m.Run()
if err := teardown(); err != nil {
panic(err)
}
os.Exit(ret)
}
type DBTest struct {
*testing.T
conn *sql.Conn
}
func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *RowsExtended) {
// handler interrupt signal
ctx, cancel := context.WithCancel(context.Background())
c := make(chan os.Signal, 1)
c0 := make(chan bool, 1)
signal.Notify(c, os.Interrupt)
defer func() {
signal.Stop(c)
}()
go func() {
select {
case <-c:
fmt.Println("Caught signal, canceling...")
cancel()
case <-ctx.Done():
fmt.Println("Done")
case <-c0:
}
close(c)
}()
rs, err := dbt.conn.QueryContext(ctx, query, args...)
if err != nil {
dbt.fail("query", query, err)
}
return &RowsExtended{
rows: rs,
closeChan: &c0,
}
}
func (dbt *DBTest) mustQueryContext(ctx context.Context, query string, args ...interface{}) (rows *RowsExtended) {
// handler interrupt signal
ctx, cancel := context.WithCancel(ctx)
c := make(chan os.Signal, 1)
c0 := make(chan bool, 1)
signal.Notify(c, os.Interrupt)
defer func() {
signal.Stop(c)
}()
go func() {
select {
case <-c:
fmt.Println("Caught signal, canceling...")
cancel()
case <-ctx.Done():
fmt.Println("Done")
case <-c0:
}
close(c)
}()
rs, err := dbt.conn.QueryContext(ctx, query, args...)
if err != nil {
dbt.fail("query", query, err)
}
return &RowsExtended{
rows: rs,
closeChan: &c0,
}
}
func (dbt *DBTest) query(query string, args ...any) (*sql.Rows, error) {
return dbt.conn.QueryContext(context.Background(), query, args...)
}
func (dbt *DBTest) mustQueryAssertCount(query string, expected int, args ...interface{}) {
rows := dbt.mustQuery(query, args...)
defer rows.Close()
cnt := 0
for rows.Next() {
cnt++
}
if cnt != expected {
dbt.Fatalf("expected %v, got %v", expected, cnt)
}
}
func (dbt *DBTest) prepare(query string) (*sql.Stmt, error) {
return dbt.conn.PrepareContext(context.Background(), query)
}
func (dbt *DBTest) fail(method, query string, err error) {
if len(query) > 300 {
query = "[query too large to print]"
}
dbt.Fatalf("error on %s [%s]: %s", method, query, err.Error())
}
func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) {
return dbt.mustExecContext(context.Background(), query, args...)
}
func (dbt *DBTest) mustExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result) {
res, err := dbt.conn.ExecContext(ctx, query, args...)
if err != nil {
dbt.fail("exec context", query, err)
}
return res
}
func (dbt *DBTest) exec(query string, args ...any) (sql.Result, error) {
return dbt.conn.ExecContext(context.Background(), query, args...)
}
func (dbt *DBTest) mustDecimalSize(ct *sql.ColumnType) (pr int64, sc int64) {
var ok bool
pr, sc, ok = ct.DecimalSize()
if !ok {
dbt.Fatalf("failed to get decimal size. %v", ct)
}
return pr, sc
}
func (dbt *DBTest) mustFailDecimalSize(ct *sql.ColumnType) {
var ok bool
if _, _, ok = ct.DecimalSize(); ok {
dbt.Fatalf("should not return decimal size. %v", ct)
}
}
func (dbt *DBTest) mustLength(ct *sql.ColumnType) (cLen int64) {
var ok bool
cLen, ok = ct.Length()
if !ok {
dbt.Fatalf("failed to get length. %v", ct)
}
return cLen
}
func (dbt *DBTest) mustFailLength(ct *sql.ColumnType) {
var ok bool
if _, ok = ct.Length(); ok {
dbt.Fatalf("should not return length. %v", ct)
}
}
func (dbt *DBTest) mustNullable(ct *sql.ColumnType) (canNull bool) {
var ok bool
canNull, ok = ct.Nullable()
if !ok {
dbt.Fatalf("failed to get length. %v", ct)
}
return canNull
}
func (dbt *DBTest) mustPrepare(query string) (stmt *sql.Stmt) {
stmt, err := dbt.conn.PrepareContext(context.Background(), query)
if err != nil {
dbt.fail("prepare", query, err)
}
return stmt
}
type SCTest struct {
*testing.T
sc *snowflakeConn
}
func (sct *SCTest) fail(method, query string, err error) {
if len(query) > 300 {
query = "[query too large to print]"
}
sct.Fatalf("error on %s [%s]: %s", method, query, err.Error())
}
func (sct *SCTest) mustExec(query string, args []driver.Value) driver.Result {
result, err := sct.sc.Exec(query, args)
if err != nil {
sct.fail("exec", query, err)
}
return result
}
func (sct *SCTest) mustQuery(query string, args []driver.Value) driver.Rows {
rows, err := sct.sc.Query(query, args)
if err != nil {
sct.fail("query", query, err)
}
return rows
}
func (sct *SCTest) mustQueryContext(ctx context.Context, query string, args []driver.NamedValue) driver.Rows {
rows, err := sct.sc.QueryContext(ctx, query, args)
if err != nil {
sct.fail("QueryContext", query, err)
}
return rows
}
func (sct *SCTest) mustExecContext(ctx context.Context, query string, args []driver.NamedValue) driver.Result {
result, err := sct.sc.ExecContext(ctx, query, args)
if err != nil {
sct.fail("ExecContext", query, err)
}
return result
}
func runDBTest(t *testing.T, test func(dbt *DBTest)) {
conn := openConn(t)
defer conn.Close()
dbt := &DBTest{t, conn}
test(dbt)
}
func runSnowflakeConnTest(t *testing.T, test func(sct *SCTest)) {
config, err := ParseDSN(dsn)
if err != nil {
t.Error(err)
}
sc, err := buildSnowflakeConn(context.Background(), *config)
if err != nil {
t.Fatal(err)
}
defer sc.Close()
if err = authenticateWithConfig(sc); err != nil {
t.Fatal(err)
}
sct := &SCTest{t, sc}
test(sct)
}
func runningOnAWS() bool {
return os.Getenv("CLOUD_PROVIDER") == "AWS"
}
func runningOnGCP() bool {
return os.Getenv("CLOUD_PROVIDER") == "GCP"
}
func TestBogusUserPasswordParameters(t *testing.T) {
invalidDNS := fmt.Sprintf("%s:%s@%s", "bogus", pass, host)
invalidUserPassErrorTests(invalidDNS, t)
invalidDNS = fmt.Sprintf("%s:%s@%s", username, "INVALID_PASSWORD", host)
invalidUserPassErrorTests(invalidDNS, t)
}
func invalidUserPassErrorTests(invalidDNS string, t *testing.T) {
parameters := url.Values{}
if protocol != "" {
parameters.Add("protocol", protocol)
}
if account != "" {
parameters.Add("account", account)
}
invalidDNS += "?" + parameters.Encode()
db, err := sql.Open("snowflake", invalidDNS)
if err != nil {
t.Fatalf("error creating a connection object: %s", err.Error())
}
// actual connection won't happen until run a query
defer db.Close()
if _, err = db.Exec("SELECT 1"); err == nil {
t.Fatal("should cause an error.")
}
if driverErr, ok := err.(*SnowflakeError); ok {
if driverErr.Number != 390100 {
t.Fatalf("wrong error code: %v", driverErr)
}
if !strings.Contains(driverErr.Error(), "390100") {
t.Fatalf("error message should included the error code. got: %v", driverErr.Error())
}
} else {
t.Fatalf("wrong error code: %v", err)
}
}
func TestBogusHostNameParameters(t *testing.T) {
invalidDNS := fmt.Sprintf("%s:%s@%s", username, pass, "INVALID_HOST:1234")
invalidHostErrorTests(invalidDNS, []string{"no such host", "verify account name is correct", "HTTP Status: 403", "Temporary failure in name resolution", "server misbehaving"}, t)
invalidDNS = fmt.Sprintf("%s:%s@%s", username, pass, "INVALID_HOST")
invalidHostErrorTests(invalidDNS, []string{"read: connection reset by peer", "EOF", "verify account name is correct", "HTTP Status: 403", "Temporary failure in name resolution", "server misbehaving"}, t)
}
func invalidHostErrorTests(invalidDNS string, mstr []string, t *testing.T) {
parameters := url.Values{}
if protocol != "" {
parameters.Add("protocol", protocol)
}
if account != "" {
parameters.Add("account", account)
}
parameters.Add("loginTimeout", "10")
invalidDNS += "?" + parameters.Encode()
db, err := sql.Open("snowflake", invalidDNS)
if err != nil {
t.Fatalf("error creating a connection object: %s", err.Error())
}
// actual connection won't happen until run a query
defer db.Close()
if _, err = db.Exec("SELECT 1"); err == nil {
t.Fatal("should cause an error.")
}
found := false
for _, m := range mstr {
if strings.Contains(err.Error(), m) {
found = true
}
}
if !found {
t.Fatalf("wrong error: %v", err)
}
}
func TestCommentOnlyQuery(t *testing.T) {
runDBTest(t, func(dbt *DBTest) {
query := "--"
// just a comment, no query
rows, err := dbt.query(query)
if err == nil {
rows.Close()
dbt.fail("query", query, err)
}
if driverErr, ok := err.(*SnowflakeError); ok {
if driverErr.Number != 900 { // syntax error
dbt.fail("query", query, err)
}
}
})
}
func TestEmptyQuery(t *testing.T) {
runDBTest(t, func(dbt *DBTest) {
query := "select 1 from dual where 1=0"
// just a comment, no query
rows := dbt.conn.QueryRowContext(context.Background(), query)
var v1 any
if err := rows.Scan(&v1); err != sql.ErrNoRows {
dbt.Errorf("should fail. err: %v", err)
}
rows = dbt.conn.QueryRowContext(context.Background(), query)
if err := rows.Scan(&v1); err != sql.ErrNoRows {
dbt.Errorf("should fail. err: %v", err)
}
})
}
func TestEmptyQueryWithRequestID(t *testing.T) {
runDBTest(t, func(dbt *DBTest) {
query := "select 1"
ctx := WithRequestID(context.Background(), NewUUID())
rows := dbt.conn.QueryRowContext(ctx, query)
var v1 interface{}
if err := rows.Scan(&v1); err != nil {
dbt.Errorf("should not have failed with valid request id. err: %v", err)
}
})
}
func TestCRUD(t *testing.T) {
runDBTest(t, func(dbt *DBTest) {
// Create Table
dbt.mustExec("CREATE OR REPLACE TABLE test (value BOOLEAN)")
// Test for unexpected Data
var out bool
rows := dbt.mustQuery("SELECT * FROM test")
defer rows.Close()
if rows.Next() {
dbt.Error("unexpected Data in empty table")
}
// Create Data
res := dbt.mustExec("INSERT INTO test VALUES (true)")
count, err := res.RowsAffected()
if err != nil {
dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
}
if count != 1 {
dbt.Fatalf("expected 1 affected row, got %d", count)
}
id, err := res.LastInsertId()
if err != nil {
dbt.Fatalf("res.LastInsertId() returned error: %s", err.Error())
}
if id != -1 {
dbt.Fatalf(
"expected InsertId -1, got %d. Snowflake doesn't support last insert ID", id)
}
// Read
rows = dbt.mustQuery("SELECT value FROM test")
defer rows.Close()
if rows.Next() {
rows.Scan(&out)
if !out {
dbt.Errorf("%t should be true", out)
}
if rows.Next() {
dbt.Error("unexpected Data")
}
} else {
dbt.Error("no Data")
}
// Update
res = dbt.mustExec("UPDATE test SET value = ? WHERE value = ?", false, true)
count, err = res.RowsAffected()
if err != nil {
dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
}
if count != 1 {
dbt.Fatalf("expected 1 affected row, got %d", count)
}
// Check Update
rows = dbt.mustQuery("SELECT value FROM test")
defer rows.Close()
if rows.Next() {
rows.Scan(&out)
if out {
dbt.Errorf("%t should be true", out)
}
if rows.Next() {
dbt.Error("unexpected Data")
}
} else {
dbt.Error("no Data")
}
// Delete
res = dbt.mustExec("DELETE FROM test WHERE value = ?", false)
count, err = res.RowsAffected()
if err != nil {
dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
}
if count != 1 {
dbt.Fatalf("expected 1 affected row, got %d", count)
}
// Check for unexpected rows
res = dbt.mustExec("DELETE FROM test")
count, err = res.RowsAffected()
if err != nil {
dbt.Fatalf("res.RowsAffected() returned error: %s", err.Error())
}
if count != 0 {
dbt.Fatalf("expected 0 affected row, got %d", count)
}
})
}
func TestInt(t *testing.T) {
testInt(t, false)
}
func testInt(t *testing.T, json bool) {
runDBTest(t, func(dbt *DBTest) {
types := []string{"INT", "INTEGER"}
in := int64(42)
var out int64
var rows *RowsExtended
// SIGNED
for _, v := range types {
t.Run(v, func(t *testing.T) {
if json {
dbt.mustExec(forceJSON)
}
dbt.mustExec("CREATE OR REPLACE TABLE test (value " + v + ")")
dbt.mustExec("INSERT INTO test VALUES (?)", in)
rows = dbt.mustQuery("SELECT value FROM test")
defer rows.Close()
if rows.Next() {
rows.Scan(&out)
if in != out {
dbt.Errorf("%s: %d != %d", v, in, out)
}
} else {
dbt.Errorf("%s: no data", v)
}
})
}
dbt.mustExec("DROP TABLE IF EXISTS test")
})
}
func TestFloat32(t *testing.T) {
testFloat32(t, false)
}
func testFloat32(t *testing.T, json bool) {
runDBTest(t, func(dbt *DBTest) {
types := [2]string{"FLOAT", "DOUBLE"}
in := float32(42.23)
var out float32
var rows *RowsExtended
for _, v := range types {
t.Run(v, func(t *testing.T) {
if json {
dbt.mustExec(forceJSON)
}
dbt.mustExec("CREATE OR REPLACE TABLE test (value " + v + ")")
dbt.mustExec("INSERT INTO test VALUES (?)", in)
rows = dbt.mustQuery("SELECT value FROM test")
defer rows.Close()
if rows.Next() {
err := rows.Scan(&out)
if err != nil {
dbt.Errorf("failed to scan data: %v", err)
}
if in != out {
dbt.Errorf("%s: %g != %g", v, in, out)
}
} else {
dbt.Errorf("%s: no data", v)
}
})
}
dbt.mustExec("DROP TABLE IF EXISTS test")
})
}
func TestFloat64(t *testing.T) {
testFloat64(t, false)
}
func testFloat64(t *testing.T, json bool) {
runDBTest(t, func(dbt *DBTest) {
types := [2]string{"FLOAT", "DOUBLE"}
expected := 42.23
var out float64
var rows *RowsExtended
for _, v := range types {
t.Run(v, func(t *testing.T) {
if json {
dbt.mustExec(forceJSON)
}
dbt.mustExec("CREATE OR REPLACE TABLE test (value " + v + ")")
dbt.mustExec("INSERT INTO test VALUES (42.23)")
rows = dbt.mustQuery("SELECT value FROM test")
defer rows.Close()
if rows.Next() {
rows.Scan(&out)
if expected != out {
dbt.Errorf("%s: %g != %g", v, expected, out)
}
} else {
dbt.Errorf("%s: no data", v)
}
})
}
dbt.mustExec("DROP TABLE IF EXISTS test")
})
}
func TestString(t *testing.T) {
testString(t, false)
}
func testString(t *testing.T, json bool) {
runDBTest(t, func(dbt *DBTest) {
if json {
dbt.mustExec(forceJSON)
}
types := []string{"CHAR(255)", "VARCHAR(255)", "TEXT", "STRING"}
in := "κόσμε üöäßñóùéàâÿœ'îë Árvíztűrő いろはにほへとちりぬるを イロハニホヘト דג סקרן чащах น่าฟังเอย"
var out string
var rows *RowsExtended
for _, v := range types {
t.Run(v, func(t *testing.T) {
dbt.mustExec("CREATE OR REPLACE TABLE test (value " + v + ")")
dbt.mustExec("INSERT INTO test VALUES (?)", in)
rows = dbt.mustQuery("SELECT value FROM test")
defer rows.Close()
if rows.Next() {
rows.Scan(&out)
if in != out {
dbt.Errorf("%s: %s != %s", v, in, out)
}
} else {
dbt.Errorf("%s: no data", v)
}
})
}
dbt.mustExec("DROP TABLE IF EXISTS test")
// BLOB (Snowflake doesn't support BLOB type but STRING covers large text data)
dbt.mustExec("CREATE OR REPLACE TABLE test (id int, value STRING)")
id := 2
in = `Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
erat, sed diam voluptua. At vero eos et accusam et justo duo
dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet,
consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt
ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`
dbt.mustExec("INSERT INTO test VALUES (?, ?)", id, in)
if err := dbt.conn.QueryRowContext(context.Background(), "SELECT value FROM test WHERE id = ?", id).Scan(&out); err != nil {
dbt.Fatalf("Error on BLOB-Query: %s", err.Error())
} else if out != in {
dbt.Errorf("BLOB: %s != %s", in, out)
}
})
}
type tcDateTimeTimestamp struct {
dbtype string
tlayout string
tests []timeTest
}
type timeTest struct {
s string // source date time string
t time.Time // expected fetched data
}
func (tt timeTest) genQuery() string {
return "SELECT '%s'::%s"
}
func (tt timeTest) run(t *testing.T, dbt *DBTest, dbtype, tlayout string) {
var rows *RowsExtended
query := fmt.Sprintf(tt.genQuery(), tt.s, dbtype)
rows = dbt.mustQuery(query)
defer rows.Close()
var err error
if !rows.Next() {
err = rows.Err()
if err == nil {
err = fmt.Errorf("no data")
}
dbt.Errorf("%s: %s", dbtype, err)
return
}
var dst interface{}
if err = rows.Scan(&dst); err != nil {
dbt.Errorf("%s: %s", dbtype, err)
return
}
switch val := dst.(type) {
case []uint8:
str := string(val)
if str == tt.s {
return
}
dbt.Errorf("%s to string: expected %q, got %q",
dbtype,
tt.s,
str,
)
case time.Time:
if val.UnixNano() == tt.t.UnixNano() {
return
}
t.Logf("source:%v, expected: %v, got:%v", tt.s, tt.t, val)
dbt.Errorf("%s to string: expected %q, got %q",
dbtype,
tt.s,
val.Format(tlayout),
)
default:
dbt.Errorf("%s: unhandled type %T (is '%v')",
dbtype, val, val,
)
}
}
func TestSimpleDateTimeTimestampFetch(t *testing.T) {
testSimpleDateTimeTimestampFetch(t, false)
}
func testSimpleDateTimeTimestampFetch(t *testing.T, json bool) {
var scan = func(rows *RowsExtended, cd interface{}, ct interface{}, cts interface{}) {
if err := rows.Scan(cd, ct, cts); err != nil {
t.Fatal(err)
}
}
var fetchTypes = []func(*RowsExtended){
func(rows *RowsExtended) {
var cd, ct, cts time.Time
scan(rows, &cd, &ct, &cts)
},
func(rows *RowsExtended) {
var cd, ct, cts time.Time
scan(rows, &cd, &ct, &cts)
},
}
runDBTest(t, func(dbt *DBTest) {
if json {
dbt.mustExec(forceJSON)
}
for _, f := range fetchTypes {
rows := dbt.mustQuery("SELECT CURRENT_DATE(), CURRENT_TIME(), CURRENT_TIMESTAMP()")
defer rows.Close()
if rows.Next() {
f(rows)
} else {
t.Fatal("no results")
}
}
})
}
func TestDateTime(t *testing.T) {
testDateTime(t, false)
}
func testDateTime(t *testing.T, json bool) {
afterTime := func(t time.Time, d string) time.Time {
dur, err := time.ParseDuration(d)
if err != nil {
panic(err)
}
return t.Add(dur)
}
t0 := time.Time{}
tstr0 := "0000-00-00 00:00:00.000000000"
testcases := []tcDateTimeTimestamp{
{"DATE", format[:10], []timeTest{
{t: time.Date(2011, 11, 20, 0, 0, 0, 0, time.UTC)},
{t: time.Date(2, 8, 2, 0, 0, 0, 0, time.UTC), s: "0002-08-02"},
}},
{"TIME", format[11:19], []timeTest{
{t: afterTime(t0, "12345s")},
{t: t0, s: tstr0[11:19]},
}},
{"TIME(0)", format[11:19], []timeTest{
{t: afterTime(t0, "12345s")},
{t: t0, s: tstr0[11:19]},
}},
{"TIME(1)", format[11:21], []timeTest{
{t: afterTime(t0, "12345600ms")},
{t: t0, s: tstr0[11:21]},
}},
{"TIME(6)", format[11:], []timeTest{
{t: t0, s: tstr0[11:]},
}},
{"DATETIME", format[:19], []timeTest{
{t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},
}},
{"DATETIME(0)", format[:21], []timeTest{
{t: time.Date(2011, 11, 20, 21, 27, 37, 0, time.UTC)},
}},
{"DATETIME(1)", format[:21], []timeTest{
{t: time.Date(2011, 11, 20, 21, 27, 37, 100000000, time.UTC)},
}},
{"DATETIME(6)", format, []timeTest{
{t: time.Date(2011, 11, 20, 21, 27, 37, 123456000, time.UTC)},
}},
{"DATETIME(9)", format, []timeTest{
{t: time.Date(2011, 11, 20, 21, 27, 37, 123456789, time.UTC)},
}},
}
runDBTest(t, func(dbt *DBTest) {
if json {
dbt.mustExec(forceJSON)
}
for _, setups := range testcases {
t.Run(setups.dbtype, func(t *testing.T) {
for _, setup := range setups.tests {
if setup.s == "" {
// fill time string wherever Go can reliable produce it
setup.s = setup.t.Format(setups.tlayout)
}
setup.run(t, dbt, setups.dbtype, setups.tlayout)
}
})
}
})
}
func TestTimestampLTZ(t *testing.T) {
testTimestampLTZ(t, false)
}
func testTimestampLTZ(t *testing.T, json bool) {
// Set session time zone in Los Angeles, same as machine
createDSN(PSTLocation)
location, err := time.LoadLocation(PSTLocation)
if err != nil {
t.Error(err)
}
testcases := []tcDateTimeTimestamp{
{
dbtype: "TIMESTAMP_LTZ(9)",
tlayout: format,
tests: []timeTest{
{
s: "2016-12-30 05:02:03",
t: time.Date(2016, 12, 30, 5, 2, 3, 0, location),
},
{
s: "2016-12-30 05:02:03 -00:00",
t: time.Date(2016, 12, 30, 5, 2, 3, 0, time.UTC),
},
{
s: "2017-05-12 00:51:42",
t: time.Date(2017, 5, 12, 0, 51, 42, 0, location),
},
{
s: "2017-03-12 01:00:00",
t: time.Date(2017, 3, 12, 1, 0, 0, 0, location),
},
{
s: "2017-03-13 04:00:00",
t: time.Date(2017, 3, 13, 4, 0, 0, 0, location),
},
{
s: "2017-03-13 04:00:00.123456789",
t: time.Date(2017, 3, 13, 4, 0, 0, 123456789, location),
},
},
},
{
dbtype: "TIMESTAMP_LTZ(8)",
tlayout: format,
tests: []timeTest{
{
s: "2017-03-13 04:00:00.123456789",
t: time.Date(2017, 3, 13, 4, 0, 0, 123456780, location),
},
},
},
}
runDBTest(t, func(dbt *DBTest) {
if json {
dbt.mustExec(forceJSON)
}
for _, setups := range testcases {