-
Notifications
You must be signed in to change notification settings - Fork 2
/
mysql_test.go
1440 lines (1282 loc) · 42.8 KB
/
mysql_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
package mysql
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"reflect"
"strings"
"testing"
"github.com/nuveo/log"
"github.com/prest/adapter-mysql/internal/connection"
"github.com/prest/adapter-mysql/statements"
"github.com/prest/adapters"
"github.com/prest/config"
)
func init() {
config.Load()
Load()
}
func TestLoad(t *testing.T) {
// Only run the failing part when a specific env variable is set
if os.Getenv("BE_CRASHER") == "1" {
Load()
os.Setenv("PREST_PG_DATABASE", "prest")
return
}
os.Setenv("PREST_PG_DATABASE", "loadtest")
// Start the actual test in a different subprocess
cmd := exec.Command(os.Args[0], "-test.run=TestLoad")
cmd.Env = append(os.Environ(), "BE_CRASHER=1")
output, err := cmd.CombinedOutput()
e, ok := err.(*exec.ExitError)
if !ok || e.Success() {
t.Fatalf("Process ran with err %v, want exit status 255", err)
}
log.Printf("%s\n %v\n", string(output), e.Error())
if !cmd.ProcessState.Success() {
os.Exit(0)
}
}
func TestParseInsertRequest(t *testing.T) {
config.Load()
Load()
m := make(map[string]interface{})
m["name"] = "prest"
mc := make(map[string]interface{})
mc["test"] = "prest"
mc["dbname"] = "prest"
var testCases = []struct {
description string
body map[string]interface{}
expectedColNames []string
expectedValues []string
err error
}{
{"insert by request more than one field", mc, []string{"dbname", "test"}, []string{"prest", "prest"}, nil},
{"insert by request one field", m, []string{"name"}, []string{"prest"}, nil},
{"insert by request empty body", nil, nil, nil, ErrBodyEmpty},
}
for _, tc := range testCases {
t.Log(tc.description)
body, err := json.Marshal(tc.body)
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
req, err := http.NewRequest("POST", "/", bytes.NewReader(body))
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
colsNames, _, values, err := config.PrestConf.Adapter.ParseInsertRequest(req)
if err != tc.err {
t.Errorf("expected errors %v in where by request, got %v", tc.err, err)
}
for _, sql := range tc.expectedColNames {
if !strings.Contains(colsNames, sql) {
t.Errorf("expected %s in %s, but not was!", sql, colsNames)
}
}
expectedValuesSTR := strings.Join(tc.expectedValues, " ")
for _, value := range values {
if !strings.Contains(expectedValuesSTR, value.(string)) {
t.Errorf("expected %s in %s", value, expectedValuesSTR)
}
}
}
}
func TestSetByRequest(t *testing.T) {
m := make(map[string]interface{})
m["name"] = "prest"
mc := make(map[string]interface{})
mc["test"] = "prest"
mc["dbname"] = "prest"
ma := make(map[string]interface{})
ma["c.name"] = "prest"
var testCases = []struct {
description string
body map[string]interface{}
expectedSQL []string
expectedValues []string
err error
}{
{"set by request more than one field", mc, []string{`"dbname"=$`, `"test"=$`, ", "}, []string{"prest", "prest"}, nil},
{"set by request one field", m, []string{`"name"=$`}, []string{"prest"}, nil},
{"set by request alias", ma, []string{`"c".`, `"name"=$`}, []string{"prest"}, nil},
{"set by request empty body", nil, nil, nil, ErrBodyEmpty},
}
for _, tc := range testCases {
t.Log(tc.description)
body, err := json.Marshal(tc.body)
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
req, err := http.NewRequest("PUT", "/", bytes.NewReader(body))
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
setSyntax, values, err := config.PrestConf.Adapter.SetByRequest(req, 1)
if err != tc.err {
t.Errorf("expected errors %v in where by request, got %v", tc.err, err)
}
for _, sql := range tc.expectedSQL {
if !strings.Contains(setSyntax, sql) {
t.Errorf("expected %s in %s, but not was!", sql, setSyntax)
}
}
expectedValuesSTR := strings.Join(tc.expectedValues, " ")
for _, value := range values {
if !strings.Contains(expectedValuesSTR, value.(string)) {
t.Errorf("expected %s in %s", value, expectedValuesSTR)
}
}
}
}
func TestWhereByRequest(t *testing.T) {
var testCases = []struct {
description string
url string
expectedSQL []string
expectedValues []string
err error
}{
{"Where by request without paginate", "/databases?dbname=$eq.prest&test=$eq.cool", []string{`"dbname" = $`, `"test" = $`, " AND "}, []string{"prest", "cool"}, nil},
{"Where by request with alias", "/databases?dbname=$eq.prest&c.test=$eq.cool", []string{`"dbname" = $`, `"c".`, `"test" = $`, " AND "}, []string{"prest", "cool"}, nil},
{"Where by request with spaced values", "/prest/public/test5?name=$eq.prest tester", []string{`"name" = $`}, []string{"prest tester"}, nil},
{"Where by request with jsonb field", "/prest/public/test_jsonb_bug?name=$eq.goku&data->>description:jsonb=$eq.testing", []string{`"name" = $`, `"data"->>'description' = $`, " AND "}, []string{"goku", "testing"}, nil},
{"Where by request with dot values", "/prest/public/test5?name=$eq.prest.txt tester", []string{`"name" = $`}, []string{"prest.txt tester"}, nil},
{"Where by request with like", "/prest/public/test5?name=$like.%25val%25&phonenumber=123456", []string{`"name" LIKE $`, `"phonenumber" = $`, " AND "}, []string{"%val%", "123456"}, nil},
{"Where by request with ilike", "/prest/public/test5?name=$ilike.%25vAl%25&phonenumber=123456", []string{`"name" ILIKE $`, `"phonenumber" = $`, " AND "}, []string{"%vAl%", "123456"}, nil},
{"Where by request with multiple colunm values", "/prest/public/table?created_at='$gte.1997-11-03'&created_at='$lte.1997-12-05'", []string{`"created_at" >= $`, ` AND `, `"created_at" <= $`}, []string{`'1997-11-03'`, `'1997-12-05'`}, nil},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
where, values, err := config.PrestConf.Adapter.WhereByRequest(req, 1)
t.Log("where:", where)
t.Log("values:", values)
if err != nil {
t.Errorf("expected no errors in where by request, got %v", err)
}
for _, sql := range tc.expectedSQL {
if !strings.Contains(where, sql) {
t.Errorf("expected %s in %s, but not was!", sql, where)
}
}
expectedValuesSTR := strings.Join(tc.expectedValues, " ")
t.Log("expectedValuesSTR:", expectedValuesSTR)
for _, value := range values {
t.Log("in values:", values)
if !strings.Contains(expectedValuesSTR, value.(string)) {
t.Errorf("expected %s in %s", value, expectedValuesSTR)
}
}
}
}
func TestInvalidWhereByRequest(t *testing.T) {
var testCases = []struct {
description string
url string
}{
{"Where by request without jsonb key", "/prest/public/test_jsonb_bug?name=$eq.nuveo&data->>description:bla"},
{"Where by request with jsonb field invalid", "/prest/public/test_jsonb_bug?name=$eq.nuveo&data->>0description:jsonb=$eq.bla"},
{"Where by request with field invalid", "/prest/public/test?0name=$eq.prest"},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
where, values, err := config.PrestConf.Adapter.WhereByRequest(req, 1)
if err == nil {
t.Errorf("expected errors in where by request, got %v", err)
}
if where != "" {
t.Errorf("expected empty `where`, got %v", where)
}
if values != nil {
t.Errorf("expected empty `values`, got %v", values)
}
}
}
func TestReturningByRequest(t *testing.T) {
var testCases = []struct {
description string
url string
expectedSQL []string
err error
}{
{"Returning by request with nothing", "/prest/public/test_group_by_table", []string{""}, nil},
{"Returning by request with _returning=*", "/prest/public/test_group_by_table?_returning=*", []string{"RETURNING *"}, nil},
{"Returning by request with _returning=field", "/prest/public/test_group_by_table?_returning=age", []string{"RETURNING age"}, nil},
{"Returning by request with multiple _returning=field", "/prest/public/test_group_by_table?_returning=age&_returning=salary", []string{"RETURNING age,salary"}, nil},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
returning, err := config.PrestConf.Adapter.ReturningByRequest(req)
t.Log("returning:", returning)
if err != nil {
t.Errorf("expected no errors in returning by request, got %v", err)
}
for _, sql := range tc.expectedSQL {
if !strings.Contains(returning, sql) {
t.Errorf("expected %s in %s, but not was!", sql, returning)
}
}
}
}
func TestGroupByClause(t *testing.T) {
var testCases = []struct {
description string
url string
expectedSQL string
emptyCase bool
}{
{"Group by clause with one field", "/prest/public/test5?_groupby=celphone", `GROUP BY "celphone"`, false},
{"Group by clause with two fields", "/prest/public/test5?_groupby=celphone,name", `GROUP BY "celphone","name"`, false},
{"Group by clause with two fields", "/prest/public/test5?_groupby=c.celphone,c.name", `GROUP BY "c"."celphone","c"."name"`, false},
{"Group by clause without fields", "/prest/public/test5?_groupby=", "", true},
// having tests
{"Group by clause with having clause", "/prest/public/test5?_groupby=celphone->>having:sum:salary:$gt:500", `GROUP BY "celphone" HAVING SUM("salary") > 500`, false},
{"Group by clause with having clause", "/prest/public/test5?_groupby=c.celphone->>having:sum:salary:$gt:500", `GROUP BY "c"."celphone" HAVING SUM("salary") > 500`, false},
// having errors, but continue with group by
{"Group by clause with wrong having clause (insufficient params)", "/prest/public/test5?_groupby=celphone->>having:sum:salary", `GROUP BY "celphone"`, false},
{"Group by clause with wrong having clause (wrong query operator)", "/prest/public/test5?_groupby=celphone->>having:sum:salary:$at:500", `GROUP BY "celphone"`, false},
{"Group by clause with wrong having clause (wrong group func)", "/prest/public/test5?_groupby=celphone->>having:sun:salary:$gt:500", `GROUP BY "celphone"`, false},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, got %v", err)
}
groupBySQL := config.PrestConf.Adapter.GroupByClause(req)
if !tc.emptyCase && groupBySQL == "" {
t.Error("expected groupBySQL, got empty string")
}
if tc.emptyCase && groupBySQL != "" {
t.Errorf("expected empty, got %v", groupBySQL)
}
if groupBySQL != tc.expectedSQL {
t.Errorf("expected %s, got %s", tc.expectedSQL, groupBySQL)
}
}
}
func TestEmptyTable(t *testing.T) {
sc := config.PrestConf.Adapter.Query("SELECT * FROM test_empty_table")
if sc.Err() != nil {
t.Fatal(sc.Err())
}
if !bytes.Equal(sc.Bytes(), []byte("[]")) {
t.Fatalf("Query response returned '%v', expected '[]'", string(sc.Bytes()))
}
}
func TestQuery(t *testing.T) {
var sc adapters.Scanner
var testCases = []struct {
description string
sql string
param bool
jsonMinLen int
err error
}{
{"Query execution", "SELECT schema_name FROM information_schema.schemata ORDER BY schema_name ASC", false, 1, nil},
{"Query execution 2", "SELECT number FROM prest.public.test2 ORDER BY number ASC", false, 1, nil},
{"Query execution with quotes", `SELECT "number" FROM "prest"."public"."test2" ORDER BY "number" ASC`, false, 1, nil},
{"Query execution with params", "SELECT schema_name FROM information_schema.schemata WHERE schema_name = $1 ORDER BY schema_name ASC", true, 1, nil},
}
for _, tc := range testCases {
t.Log(tc.description)
if tc.param {
sc = config.PrestConf.Adapter.Query(tc.sql, "public")
} else {
sc = config.PrestConf.Adapter.Query(tc.sql)
}
if sc.Err() != tc.err {
t.Errorf("expected no errors, but got %s", sc.Err())
}
if len(sc.Bytes()) < tc.jsonMinLen {
t.Errorf("expected valid json response, but got %v", string(sc.Bytes()))
}
}
}
func TestInvalidQuery(t *testing.T) {
var testCases = []struct {
description string
sql string
}{
{"Query with invalid characters", "SELECT ~~, ``, ˜ schema_name FROM information_schema.schemata WHERE schema_name = $1 ORDER BY schema_name ASC"},
{"Query with invalid clause", "0SELECT schema_name FROM information_schema.schemata WHERE schema_name = $1 ORDER BY schema_name ASC"},
}
for _, tc := range testCases {
t.Log(tc.description)
sc := config.PrestConf.Adapter.Query(tc.sql, "public")
if sc.Err() == nil {
t.Error("expected errors, but got nil")
}
if sc.Bytes() != nil {
t.Errorf("expected no response, but got %s", string(sc.Bytes()))
}
}
}
func TestPaginateIfPossible(t *testing.T) {
var testCase = []struct {
description string
url string
expected string
err error
}{
{"Paginate if possible", "/databases?dbname=prest&test=cool&_page=1&_page_size=20", "LIMIT 20 OFFSET(1 - 1) * 20", nil},
{"Invalid Paginate if possible", "/databases?dbname=prest&test=cool", "", nil},
}
for _, tc := range testCase {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, but got %s", err)
}
sql, err := config.PrestConf.Adapter.PaginateIfPossible(req)
if err != nil {
t.Errorf("expected no errors, but got %s", err)
}
if !strings.Contains(tc.expected, sql) {
t.Errorf("expected %s in %s, but not was!", tc.expected, sql)
}
}
}
func TestInvalidPaginateIfPossible(t *testing.T) {
var testCases = []struct {
description string
url string
}{
{"Paginate with invalid page value", "/databases?dbname=prest&test=cool&_page=X&_page_size=20"},
{"Paginate with invalid page size value", "/databases?dbname=prest&test=cool&_page=1&_page_size=K"},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, but got %s", err)
}
sql, err := config.PrestConf.Adapter.PaginateIfPossible(req)
if err == nil {
t.Errorf("expected errors, but got %s", err)
}
if sql != "" {
t.Errorf("expected empty sql, but got: %s", sql)
}
}
}
func TestInsert(t *testing.T) {
var testCases = []struct {
description string
sql string
values []interface{}
}{
{"Insert data into a table with one field", `INSERT INTO prest.public.test4(name) VALUES($1)`, []interface{}{"prest-test-insert"}},
{"Insert data into a table with more than one field", `INSERT INTO prest.public.test5(name, celphone) VALUES($1, $2)`, []interface{}{"prest-test-insert", "88888888"}},
{"Insert data into a table with more than one field and with quotes case sensitive", `INSERT INTO "prest"."public"."Reply"("name") VALUES($1)`, []interface{}{"prest-test-insert"}},
}
for _, tc := range testCases {
t.Log(tc.description)
sc := config.PrestConf.Adapter.Insert(tc.sql, tc.values...)
if sc.Err() != nil {
t.Errorf("expected no errors, but got %s", sc.Err())
}
if len(sc.Bytes()) < 1 {
t.Errorf("expected valid response body, but got %s", string(sc.Bytes()))
}
}
}
func TestInsertInvalid(t *testing.T) {
var testCases = []struct {
description string
sql string
values []interface{}
}{
{"Insert data into a table invalid database", "INSERT INTO 0prest.public.test4(name) VALUES($1)", []interface{}{"prest-test-insert"}},
{"Insert data into a table invalid schema", "INSERT INTO prest.0public.test4(name) VALUES($1)", []interface{}{"prest-test-insert"}},
{"Insert data into a table invalid table", "INSERT INTO prest.public.0test4(name) VALUES($1)", []interface{}{"prest-test-insert"}},
{"Insert data into a table with empty name", "INSERT INTO (name) VALUES($1)", []interface{}{"prest-test-insert"}},
}
for _, tc := range testCases {
t.Log(tc.description)
sc := config.PrestConf.Adapter.Insert(tc.sql, tc.values...)
if sc.Err() == nil {
t.Errorf("expected errors, but no has")
}
if len(sc.Bytes()) > 0 {
t.Errorf("expected valid response body, but got %s", string(sc.Bytes()))
}
}
}
func TestDelete(t *testing.T) {
var testCases = []struct {
description string
sql string
values []interface{}
}{
{"Try Delete data from invalid database", "DELETE FROM 0prest.public.test WHERE name=$1", []interface{}{"nuveo"}},
{"Try Delete data from invalid schema", "DELETE FROM prest.0public.test WHERE name=$1", []interface{}{"nuveo"}},
{"Try Delete data from invalid table", "DELETE FROM prest.public.0test WHERE name=$1", []interface{}{"nuveo"}},
}
for _, tc := range testCases {
t.Log(tc.description)
sc := config.PrestConf.Adapter.Delete(tc.sql, tc.values)
if sc.Err() == nil {
t.Errorf("expected error, but got: %s", sc.Err())
}
if len(sc.Bytes()) > 0 {
t.Errorf("expected empty response body, but got %s", string(sc.Bytes()))
}
}
t.Log("Delete data from table")
sc := config.PrestConf.Adapter.Delete(`DELETE FROM "prest"."public"."test" WHERE "name"=$1`, "nuveo")
if sc.Err() != nil {
t.Errorf("expected no error, but got: %s", sc.Err())
}
if len(sc.Bytes()) < 1 {
t.Errorf("expected response body, but got %s", string(sc.Bytes()))
}
}
func TestUpdate(t *testing.T) {
var testCases = []struct {
description string
sql string
values []interface{}
}{
{"Update data into an invalid database", "UPDATE 0prest.publc.test3 SET name=$1", []interface{}{"prest tester"}},
{"Update data into an invalid schema", "UPDATE prest.0publc.test3 SET name=$1", []interface{}{"prest tester"}},
{"Update data into an invalid table", "UPDATE prest.publc.0test3 SET name=$1", []interface{}{"prest tester"}},
}
t.Log("Update data into a table")
sc := config.PrestConf.Adapter.Update(`UPDATE "prest"."public"."test" SET "name"=$2 WHERE "name"=$1`, "prest tester", "prest")
if sc.Err() != nil {
t.Errorf("expected no errors, but got: %s", sc.Err())
}
if len(sc.Bytes()) < 1 {
t.Errorf("expected a valid response body, but got %s", string(sc.Bytes()))
}
for _, tc := range testCases {
t.Log(tc.description)
sc := config.PrestConf.Adapter.Update(tc.sql, tc.values...)
if sc.Err() == nil {
t.Errorf("expected error, but got: %s", sc.Err())
}
if len(sc.Bytes()) > 0 {
t.Errorf("expected empty response body, but got %s", string(sc.Bytes()))
}
}
}
func TestChkInvaidIdentifier(t *testing.T) {
var testCases = []struct {
in string
out bool
}{
{"fildName", false},
{"_9fildName", false},
{"_fild.Name", false},
{"0fildName", true},
{"fild'Name", true},
{"fild\"Name", true},
{"fild;Name", true},
{"SUM(test)", false},
{`SUM("test")`, false},
{"_123456789_123456789_123456789_123456789_123456789_123456789_12345", true},
}
for _, tc := range testCases {
result := chkInvalidIdentifier(tc.in)
if result != tc.out {
t.Errorf("expected %v, got %v", tc.out, result)
}
}
}
func TestJoinByRequest(t *testing.T) {
var testCases = []struct {
description string
url string
expectedValues []string
testEmptyResult bool
}{
{"Join by request", "/prest/public/test?_join=inner:test2:test2.name:$eq:test.name", []string{"INNER JOIN", `"test2" ON `, `"test2"."name" = "test"."name"`}, false},
{"Join by request with schema", "/prest/public/test?_join=inner:public.test2:test2.name:$eq:test.name", []string{"INNER JOIN", `"public"."test2" ON `, `"test2"."name" = "test"."name"`}, false},
{"Join empty params", "/prest/public/test?_join", []string{}, true},
{"Join missing param", "/prest/public/test?_join=inner:test2:test2.name:$eq", []string{}, true},
{"Join invalid operator", "/prest/public/test?_join=inner:test2:test2.name:notexist:test.name", []string{}, true},
{"Join invalid fields", "/prest/public/test?_join=inner:0test2:test2.name:notexist:test.name", []string{}, true},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got %v", err)
}
join, err := config.PrestConf.Adapter.JoinByRequest(req)
if tc.testEmptyResult {
if join != nil {
t.Errorf("expected empty response, but got: %v", join)
}
} else {
if err != nil {
t.Errorf("expected no errors, but got: %v", err)
}
joinSQL := strings.Join(join, " ")
for _, sql := range tc.expectedValues {
if !strings.Contains(joinSQL, sql) {
t.Errorf("expected %s in %s, but no was!", sql, joinSQL)
}
}
}
}
t.Log("Join with where")
var expectedSQL = []string{`"name" = $`, `"data"->>'description' = $`, " AND "}
var expectedValues = []string{"nuveo", "bla"}
r, err := http.NewRequest("GET", "/prest/public/test?_join=inner:test2:test2.name:$eq:test.name&name=$eq.nuveo&data->>description:jsonb=$eq.bla", nil)
if err != nil {
t.Errorf("expected no errorn on New Request, got %v", err)
}
join, err := config.PrestConf.Adapter.JoinByRequest(r)
if err != nil {
t.Errorf("expected no errors, but got: %v", err)
}
joinStr := strings.Join(join, " ")
if !strings.Contains(joinStr, ` INNER JOIN "test2" ON "test2"."name" = "test"."name"`) {
t.Errorf(`expected %s in INNER JOIN "test2" ON "test2"."name" = "test"."name", but no was!`, joinStr)
}
where, values, err := config.PrestConf.Adapter.WhereByRequest(r, 1)
if err != nil {
t.Errorf("expected no errors, got: %v", err)
}
for _, sql := range expectedSQL {
if !strings.Contains(where, sql) {
t.Errorf("expected %s in %s, but not was!", sql, where)
}
}
expectedValuesSTR := strings.Join(expectedValues, " ")
for _, value := range values {
if !strings.Contains(expectedValuesSTR, value.(string)) {
t.Errorf("expected %s in %s", value, expectedValuesSTR)
}
}
}
func TestCountFields(t *testing.T) {
var testCases = []struct {
description string
url string
expectedSQL string
testError bool
}{
{"Count fields from table", "/prest/public/test5?_count=celphone", `SELECT COUNT("celphone") FROM`, false},
{"Count all from table", "/prest/public/test5?_count=*", "SELECT COUNT(*) FROM", false},
{"Count with empty params", "/prest/public/test5?_count=", "", false},
{"Count with invalid columns", "/prest/public/test5?_count=celphone,0name", "", true},
}
for _, tc := range testCases {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
sql, err := config.PrestConf.Adapter.CountByRequest(req)
if tc.testError {
if err == nil {
t.Error("expected errors, but no was!")
}
if sql != "" {
t.Errorf("expected empty sql, but got: %s", sql)
}
} else {
if err != nil {
t.Errorf("expected no errors, but got: %v", err)
}
if !strings.Contains(sql, tc.expectedSQL) {
t.Errorf("expected %s in %s", tc.expectedSQL, sql)
}
}
}
}
func TestDatabaseClause(t *testing.T) {
var testCases = []struct {
description string
url string
queryExpected string
}{
{"Return appropriate SELECT clause", "/databases", fmt.Sprintf(statements.DatabasesSelect, statements.FieldDatabaseName)},
{"Return appropriate COUNT clause", "/databases?_count=*", fmt.Sprintf(statements.DatabasesSelect, statements.FieldCountDatabaseName)},
}
for _, tc := range testCases {
t.Log(tc.description)
r, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
query, _ := config.PrestConf.Adapter.DatabaseClause(r)
if query != tc.queryExpected {
t.Errorf("query unexpected, got: %s", query)
}
}
}
func TestSchemaClause(t *testing.T) {
var testCases = []struct {
description string
url string
queryExpected string
}{
{"Return appropriate SELECT clause", "/schemas", fmt.Sprintf(statements.SchemasSelect, statements.FieldSchemaName)},
{"Return appropriate COUNT clause", "/schemas?_count=*", fmt.Sprintf(statements.SchemasSelect, statements.FieldCountSchemaName)},
}
for _, tc := range testCases {
t.Log(tc.description)
r, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
query, _ := config.PrestConf.Adapter.SchemaClause(r)
if query != tc.queryExpected {
t.Errorf("query unexpected, got: %s", query)
}
}
}
func TestGetQueryOperator(t *testing.T) {
var testCases = []struct {
in string
out string
}{
{"$eq", "="},
{"$ne", "!="},
{"$gt", ">"},
{"$gte", ">="},
{"$lt", "<"},
{"$lte", "<="},
{"$in", "IN"},
{"$nin", "NOT IN"},
{"$any", "ANY"},
{"$some", "SOME"},
{"$all", "ALL"},
{"$notnull", "IS NOT NULL"},
{"$null", "IS NULL"},
{"$true", "IS TRUE"},
{"$nottrue", "IS NOT TRUE"},
{"$false", "IS FALSE"},
{"$notfalse", "IS NOT FALSE"},
{"$like", "LIKE"},
{"$ilike", "ILIKE"},
}
for _, tc := range testCases {
t.Log(fmt.Sprintf("Query operator %s", tc.in))
op, err := GetQueryOperator(tc.in)
if err != nil {
t.Errorf("expected no errors, got: %v", err)
}
if op != tc.out {
t.Errorf("expected %s, got: %s", tc.out, op)
}
}
t.Log("Invalid query operator")
op, err := GetQueryOperator("!lol")
if err == nil {
t.Errorf("expected errors, got: %v", err)
}
if op != "" {
t.Errorf("expected empty op, got: %s", op)
}
}
func TestOrderByRequest(t *testing.T) {
t.Log("Query ORDER BY")
var expectedSQL = []string{"ORDER BY", `"name"`, `"number" DESC`}
r, err := http.NewRequest("GET", "/prest/public/test?_order=name,-number", nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
order, err := config.PrestConf.Adapter.OrderByRequest(r)
if err != nil {
t.Errorf("expected no errors on OrderByRequest, got: %v", err)
}
for _, sql := range expectedSQL {
if !strings.Contains(order, sql) {
t.Errorf("expected %s in %s, but no was!", sql, order)
}
}
t.Log("Query ORDER BY with alias")
expectedSQL = []string{"ORDER BY", `"c"."name"`, `"c"."number" DESC`}
r, err = http.NewRequest("GET", "/prest/public/test?_order=c.name,-c.number", nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
order, err = config.PrestConf.Adapter.OrderByRequest(r)
if err != nil {
t.Errorf("expected no errors on OrderByRequest, got: %v", err)
}
for _, sql := range expectedSQL {
if !strings.Contains(order, sql) {
t.Errorf("expected %s in %s, but no was!", sql, order)
}
}
t.Log("Query ORDER BY empty")
r, err = http.NewRequest("GET", "/prest/public/test?_order=", nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
order, err = config.PrestConf.Adapter.OrderByRequest(r)
if err != nil {
t.Errorf("expected no errors on OrderByRequest, got: %v", err)
}
if order != "" {
t.Errorf("expected order empty, got: %s", order)
}
t.Log("Query ORDER BY invalid column")
r, err = http.NewRequest("GET", "/prest/public/test?_order=0name", nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, got: %v", err)
}
order, err = config.PrestConf.Adapter.OrderByRequest(r)
if err == nil {
t.Errorf("expected errors on OrderByRequest, got: %v", err)
}
if order != "" {
t.Errorf("expected order empty, got: %s", order)
}
}
func TestTablePermissions(t *testing.T) {
var testCases = []struct {
description string
table string
permission string
out bool
}{
{"Read", "test_readonly_access", "read", true},
{"Try to read without permission", "test_write_and_delete_access", "read", false},
{"Write", "test_write_and_delete_access", "write", true},
{"Try to write without permission", "test_readonly_access", "write", false},
{"Delete", "test_write_and_delete_access", "delete", true},
{"Try to delete without permission", "test_readonly_access", "delete", false},
}
for _, tc := range testCases {
t.Log(tc.description)
p := config.PrestConf.Adapter.TablePermissions(tc.table, tc.permission)
if p != tc.out {
t.Errorf("expected %v, got %v", tc.out, p)
}
}
}
func TestRestrictFalse(t *testing.T) {
config.PrestConf.AccessConf.Restrict = false
t.Log("Read unrestrict", config.PrestConf.AccessConf.Restrict)
r, err := http.NewRequest("GET", "/prest/public/test_list_only_id?_select=*", nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, but got: %v", err)
}
fields, err := config.PrestConf.Adapter.FieldsPermissions(r, "test_list_only_id", "read")
if err != nil {
t.Errorf("expected no errors, but got %v", err)
}
if fields[0] != "*" {
t.Errorf("expected '*', got: %s", fields[0])
}
t.Log("Restrict disabled")
p := config.PrestConf.Adapter.TablePermissions("test_readonly_access", "delete")
if !p {
t.Errorf("expected %v, got: %v", p, !p)
}
}
func TestSelectFields(t *testing.T) {
var testCases = []struct {
description string
fields []string
expectedSQL string
}{
{"One field", []string{"test"}, `SELECT "test" FROM`},
{"One field with alias", []string{"c.test"}, `SELECT "c"."test" FROM`},
{"More field", []string{"test", "test02"}, `SELECT "test","test02" FROM`},
}
var testErrorCases = []struct {
description string
fields []string
expectedSQL string
}{
{"Invalid fields", []string{"0test", "test02"}, ""},
{"Empty fields", []string{}, ""},
}
for _, tc := range testCases {
t.Log(tc.description)
sql, err := config.PrestConf.Adapter.SelectFields(tc.fields)
if err != nil {
t.Errorf("expected no errors, but got: %v", err)
}
if sql != tc.expectedSQL {
t.Errorf("expected '%s', got: '%s'", tc.expectedSQL, sql)
}
}
for _, tc := range testErrorCases {
t.Log(tc.description)
sql, err := config.PrestConf.Adapter.SelectFields(tc.fields)
if err == nil {
t.Errorf("expected errors, but got: %v", err)
}
if sql != tc.expectedSQL {
t.Errorf("expected '%s', got: '%s'", tc.expectedSQL, sql)
}
}
}
func TestColumnsByRequest(t *testing.T) {
var testCases = []struct {
description string
url string
expectedSQL string
}{
{"Select array field from table", "/prest/public/testarray?_select=data", "data"},
{"Select fields from table", "/prest/public/test5?_select=celphone", "celphone"},
{"Select all from table", "/prest/public/test5?_select=*", "*"},
{"Select with empty '_select' field", "/prest/public/test5?_select=", ""},
{"Select with more columns", "/prest/public/test5?_select=celphone,battery", "celphone,battery"},
{"Select with more columns", "/prest/public/test5?_select=age,sum:salary&_groupby=age", `age,SUM("salary")`},
}
for _, tc := range testCases {
r, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors on NewRequest, but got: %v", err)
}
selectQuery, _ := columnsByRequest(r)
selectStr := strings.Join(selectQuery, ",")
if selectStr != tc.expectedSQL {
t.Errorf("expected %s, got: %s", tc.expectedSQL, selectStr)
}
}
}
func TestDistinctClause(t *testing.T) {
var testCase = []struct {
description string
url string
expected string
err error
}{
{"Valid distinct true", "/databases?dbname=prest&test=cool&_distinct=true", "SELECT DISTINCT", nil},
{"Valid distinct false", "/databases?dbname=prest&test=cool&_distinct=false", "", nil},
{"Invalid distinct", "/databases?dbname=prest&test=cool", "", nil},
}
for _, tc := range testCase {
t.Log(tc.description)
req, err := http.NewRequest("GET", tc.url, nil)
if err != nil {
t.Errorf("expected no errors in http request, but got %s", err)