-
Notifications
You must be signed in to change notification settings - Fork 448
/
ForeignTableDmlTest.cpp
7722 lines (6844 loc) · 314 KB
/
ForeignTableDmlTest.cpp
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 2022 HEAVY.AI, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file ForeignTableDmlTest.cpp
* @brief Test suite for DML SQL queries on foreign tables
*/
#include <fstream>
#include <regex>
#include <string>
#include <gtest/gtest.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "Catalog/OptionsContainer.h"
#include "Catalog/RefreshTimeCalculator.h"
#include "DBHandlerTestHelpers.h"
#include "DataMgr/ForeignStorage/DataPreview.h"
#include "DataMgr/ForeignStorage/ForeignStorageCache.h"
#include "DataMgr/ForeignStorage/ForeignStorageException.h"
#include "DataMgr/ForeignStorage/RegexFileBufferParser.h"
#include "Geospatial/Types.h"
#include "ImportExport/DelimitedParserUtils.h"
#include "Shared/StringTransform.h"
#include "Shared/SysDefinitions.h"
#include "Shared/scope.h"
#include "TestHelpers.h"
#ifndef BASE_PATH
#define BASE_PATH "./tmp"
#endif
extern bool g_enable_fsi;
extern bool g_enable_s3_fsi;
extern bool g_enable_seconds_refresh;
extern bool g_allow_s3_server_privileges;
extern std::optional<size_t> g_detect_test_sample_size;
std::string test_binary_file_path;
std::string test_temp_dir;
bool g_run_odbc{false};
namespace bp = boost::process;
namespace bf = boost::filesystem;
namespace po = boost::program_options;
// Typedefs for clarity.
using path = bf::path;
using WrapperType = std::string;
using FragmentSizeType = int32_t;
using ChunkSizeType = int64_t;
using FileNameType = std::string;
using RecoverCacheFlag = bool;
using EvictCacheFlag = bool;
using RowGroupSizeType = int32_t;
using ScheduledRefreshFlag = bool;
using AnnotationType = std::string;
using UseDsnFlag = bool;
using DsnType = std::string;
using FileExtType = std::string;
using EvictCacheString = std::string;
using ImportFlag = bool;
using NameTypePair = std::pair<std::string, std::string>;
// sets of wrappers for parametarized testing
static const std::vector<WrapperType> local_wrappers{"csv",
"parquet",
"sqlite",
"postgres",
"regex_parser"};
static const std::vector<WrapperType> file_wrappers{"csv", "parquet", "regex_parser"};
static const std::vector<WrapperType> s3_wrappers{"csv",
"parquet",
"csv_s3_select",
"regex_parser"};
static const std::vector<WrapperType> csv_s3_wrappers{"csv", "csv_s3_select"};
static const std::vector<WrapperType> odbc_wrappers{"snowflake",
"sqlite",
"postgres",
"redshift",
"bigquery",
"hive"};
static const std::string default_table_name = "test_foreign_table";
static const std::string default_table_name_2 = "test_foreign_table_2";
static const std::string default_file_name = "temp_file";
static const std::string default_select = "SELECT * FROM " + default_table_name + ";";
namespace {
// Needs to be a macro since GTEST_SKIP() breaks by invoking "return".
#define SKIP_SETUP_IF_DISTRIBUTED(msg) \
if (isDistributedMode()) { \
skip_teardown_ = true; \
GTEST_SKIP() << msg; \
}
#define SKIP_IF_DISTRIBUTED(msg) \
if (isDistributedMode()) { \
GTEST_SKIP() << msg; \
}
// These need to be done as macros because GTEST_SKIP() invokes "return" in the function
// it is called in as well as setting IsSkipped().
#define SKIP_SETUP_IF_ODBC_DISABLED() \
GTEST_SKIP() << "ODBC tests not supported with this build configuration."
bool is_regex(const std::string& wrapper_type) {
return (wrapper_type == "regex_parser");
}
std::string wrapper_file_type(const std::string& wrapper_type) {
return (is_odbc(wrapper_type) || wrapper_type == "regex_parser") ? "csv" : wrapper_type;
}
FileExtType wrapper_ext(const std::string& wrapper_type) {
return "." + wrapper_file_type(wrapper_type);
}
void recursive_copy(const std::string& origin, const std::string& dest) {
bf::create_directory(dest);
for (bf::directory_iterator file(origin); file != bf::directory_iterator(); ++file) {
const auto& path = file->path();
if (bf::is_directory(path)) {
recursive_copy(path.string(), dest + "/" + path.filename().string());
} else {
bf::copy_file(path.string(), dest + "/" + path.filename().string());
}
}
}
bool does_cache_contain_chunks(Catalog_Namespace::Catalog* cat,
const std::string& table_name,
const std::vector<std::vector<int>>& subkeys) {
// subkey is chunkey without db, table ids
auto td = cat->getMetadataForTable(table_name, false);
ChunkKey table_key{cat->getCurrentDB().dbId, td->tableId};
auto cache = cat->getDataMgr().getPersistentStorageMgr()->getDiskCache();
for (const auto& subkey : subkeys) {
auto chunk_key = table_key;
chunk_key.insert(chunk_key.end(), subkey.begin(), subkey.end());
if (cache->getCachedChunkIfExists(chunk_key) == nullptr) {
return false;
}
}
return true;
}
// compare files, adjusting for basepath
bool compare_json_files(const std::string& generated,
const std::string& reference,
const std::string& basepath) {
std::ifstream gen_file(generated);
std::ifstream ref_file(reference);
// Compare each file line by line
while (gen_file && ref_file) {
std::string gen_line;
std::getline(gen_file, gen_line);
std::string ref_line;
std::getline(ref_file, ref_line);
boost::replace_all(gen_line, basepath, "BASEPATH/");
boost::algorithm::trim(gen_line);
boost::algorithm::trim(ref_line);
if (gen_line.compare(ref_line) != 0) {
std::cout << "Mismatched json lines \n";
std::cout << gen_line << "\n";
std::cout << ref_line << "\n";
return false;
}
}
if (ref_file || gen_file) {
std::cerr << "# of lines mismatch\n";
std::cerr << generated << " vs " << reference << "\n";
// # of lines mismatch
return false;
}
return true;
}
std::string repeat_regex(size_t repeat_count, const std::string& regex) {
std::string repeated_regex;
for (size_t i = 0; i < repeat_count; i++) {
if (!repeated_regex.empty()) {
repeated_regex += "\\s*,\\s*";
}
repeated_regex += regex;
}
return repeated_regex;
}
std::string get_line_regex(size_t column_count) {
return repeat_regex(column_count, "\"?([^,\"]*)\"?");
}
std::string get_line_array_regex(size_t column_count) {
return repeat_regex(column_count, "(\\{[^\\}]+\\}|NULL|)");
}
std::string get_line_geo_regex(size_t column_count) {
return repeat_regex(column_count,
"\"?((?:MULTI)?(?:POINT|LINESTRING|POLYGON)[^\"]+|\\\\N)\"?");
}
std::string get_default_server(const std::string& data_wrapper_type) {
std::string suffix;
if (data_wrapper_type == "parquet") {
suffix = "parquet";
} else if (data_wrapper_type == "csv") {
suffix = "delimited";
} else if (data_wrapper_type == "regex_parser") {
suffix = "regex_parsed";
} else {
UNREACHABLE() << "Unexpected default server data wrapper type: " << data_wrapper_type;
}
return "default_local_" + suffix;
}
std::string get_data_wrapper_name(const std::string& data_wrapper_type) {
std::string data_wrapper;
if (is_regex(data_wrapper_type)) {
data_wrapper = "regex_parsed_file";
} else if (data_wrapper_type == "csv" || data_wrapper_type == "csv_s3_select") {
data_wrapper = "delimited_file";
} else if (data_wrapper_type == "parquet") {
data_wrapper = "parquet_file";
} else if (is_odbc(data_wrapper_type)) {
data_wrapper = "odbc";
} else {
UNREACHABLE() << "Unexpected data wrapper type: " << data_wrapper_type;
}
return data_wrapper;
}
} // namespace
/**
* Helper base class that creates and maintains a temporary directory
*/
class TempDirManager {
public:
TempDirManager() {
bf::remove_all(test_temp_dir);
bf::create_directory(test_temp_dir);
}
~TempDirManager() { bf::remove_all(test_temp_dir); }
static void overwriteTempDir(const std::string& source_path) {
bf::remove_all(test_temp_dir);
recursive_copy(source_path, test_temp_dir);
}
};
/**
* Helper class for creating foreign tables
*/
class ForeignTableTest : public DBHandlerTestFixture {
protected:
inline static const std::string DEFAULT_ODBC_SERVER_NAME_ = "temp_odbc";
std::string wrapper_type_ = "csv";
bool skip_teardown_ = false;
void SetUp() override {
if (is_odbc(wrapper_type_)) {
SKIP_SETUP_IF_ODBC_DISABLED();
}
g_enable_fsi = true;
DBHandlerTestFixture::SetUp();
}
void TearDown() override {
if (skip_teardown_) {
return;
}
g_enable_fsi = true;
DBHandlerTestFixture::TearDown();
}
static std::string getCreateForeignTableQuery(const std::string& columns,
const std::string& file_name_base,
const std::string& data_wrapper_type,
const int table_number = 0) {
return getCreateForeignTableQuery(
columns, {}, file_name_base, data_wrapper_type, table_number);
}
static std::string getCreateForeignTableQuery(
const std::string& columns,
const foreign_storage::OptionsMap& options,
const std::string& file_name_base,
const std::string& data_wrapper_type,
const int table_number = 0,
const std::string& table_name = default_table_name,
const std::string extension = "",
const std::string& source_dir = getDataFilesPath()) {
std::string query{"CREATE FOREIGN TABLE " + table_name};
if (table_number) {
query += "_" + std::to_string(table_number);
}
std::string filename = file_name_base;
if (extension == "dir") {
filename += "_" + data_wrapper_type + "_dir";
} else if (extension.empty()) {
filename += "." + data_wrapper_type;
} else {
filename += "." + extension;
}
query += " " + columns + " SERVER " + get_default_server(data_wrapper_type) +
" WITH (file_path = '" + source_dir + filename + "'";
for (auto& [key, value] : options) {
query += ", " + key + " = '" + value + "'";
}
// If this is a regex wrapper then we should skip the header.
if (is_regex(data_wrapper_type)) {
if (options.find("HEADER") == options.end()) {
query += ", HEADER = 'TRUE'";
}
}
query += ");";
return query;
}
static void createUserMappingForDsn(const std::string& server_name,
const std::string& username,
const std::string& password) {
sql("CREATE USER MAPPING FOR PUBLIC SERVER " + server_name + " WITH (username='" +
username + "', password='" + password + "');");
}
static void createUserMappingForCs(const std::string& server_name,
const std::map<std::string, std::string>& pairs,
const std::string& connection_string_suffix = "") {
CHECK(!pairs.empty());
auto statement = "CREATE USER MAPPING FOR PUBLIC SERVER " + server_name +
" WITH (credential_string='";
for (auto const& [key, value] : pairs) {
statement += key + "=" + value + ";";
}
statement.pop_back();
statement += connection_string_suffix + "');";
sql(statement);
}
static void createUserMappingForOdbc(const std::string& server_name,
const std::map<std::string, std::string>& pairs,
const bool use_dsn,
const std::string& connection_string_suffix = "") {
if (use_dsn) {
auto username_it = pairs.find("USERNAME");
auto password_it = pairs.find("PASSWORD");
CHECK(username_it != pairs.end());
CHECK(password_it != pairs.end());
createUserMappingForDsn(server_name, username_it->second, password_it->second);
} else {
createUserMappingForCs(server_name, pairs, connection_string_suffix);
}
}
static void createUserMappingForS3(const std::string& server_name,
const std::string& access_key,
const std::string& secret_key,
const std::string session_token = "") {
sql("CREATE USER MAPPING FOR PUBLIC SERVER " + server_name +
" WITH (s3_access_key='" + access_key + "', s3_secret_key='" + secret_key +
(session_token.empty() ? "" : "', s3_session_token='" + session_token) + "');");
}
/**
* Returns a query to create a foreign table. Creates a source odbc table for odbc
* datawrappers.
*/
static std::string createForeignTableQuery(
const std::vector<NameTypePair>& column_pairs,
const std::string& src_path,
const std::string& data_wrapper_type,
const foreign_storage::OptionsMap options = {},
const std::string& table_name = default_table_name,
const std::vector<NameTypePair>& db_specific_column_pairs = {},
const int order_by_column_index = -1) {
std::stringstream ss;
ss << "CREATE FOREIGN TABLE " << table_name << " (";
ss << column_pairs_to_schema_string(column_pairs) << ") ";
const auto& stored_column_pairs =
(db_specific_column_pairs.empty()) ? column_pairs : db_specific_column_pairs;
if (is_odbc(data_wrapper_type)) {
createODBCSourceTable(table_name, stored_column_pairs, src_path, data_wrapper_type);
} else {
ss << "SERVER " + get_default_server(data_wrapper_type);
ss << " WITH (file_path = '";
ss << src_path << "'";
}
if (data_wrapper_type == "regex_parser") {
if (options.find("LINE_REGEX") == options.end()) {
ss << ", LINE_REGEX = '" + get_line_regex(column_pairs.size()) + "'";
}
if (options.find("HEADER") == options.end()) {
ss << ", HEADER = 'TRUE'";
}
}
for (auto& [key, value] : options) {
ss << ", " << key << " = '" << value << "'";
}
ss << ");";
return ss.str();
}
static std::string getDataFilesPath() {
return bf::canonical(test_binary_file_path + "/../../Tests/FsiDataFiles").string() +
"/";
}
static void sqlCreateForeignTable(const std::string& columns,
const std::string& file_name,
const std::string& data_wrapper_type,
const foreign_storage::OptionsMap options = {},
const int table_number = 0,
const std::string& table_name = default_table_name) {
sqlDropForeignTable(table_number, table_name);
auto query = getCreateForeignTableQuery(
columns, options, file_name, data_wrapper_type, table_number, table_name);
sql(query);
}
static void sqlDropForeignTable(const int table_number = 0,
const std::string& table_name = default_table_name) {
std::string query{"DROP FOREIGN TABLE IF EXISTS " + table_name};
if (table_number != 0) {
query += "_" + std::to_string(table_number);
}
sql(query);
}
static ChunkKey getChunkKeyFromTable(const Catalog_Namespace::Catalog& cat,
const std::string& table_name,
const ChunkKey& key_suffix) {
const TableDescriptor* fd = cat.getMetadataForTable(table_name, false);
ChunkKey key{cat.getCurrentDB().dbId, fd->tableId};
for (auto i : key_suffix) {
key.push_back(i);
}
return key;
}
void queryAndAssertFileNotFoundException(const std::string& file_path,
const std::string& query = "SELECT * FROM " +
default_table_name +
";") {
queryAndAssertException(query,
"File or directory \"" + file_path + "\" does not exist.");
}
void queryAndAssertExample2Result() {
std::string query = "SELECT * FROM " + default_table_name + " ORDER BY t, i;";
TQueryResult result;
sql(result, query);
assertResultSetEqual({{"a", i(1), 1.1},
{"aa", i(1), 1.1},
{"aa", i(2), 2.2},
{"aaa", i(1), 1.1},
{"aaa", i(2), 2.2},
{"aaa", i(3), 3.3}},
result);
}
void queryAndAssertExample2Count() {
TQueryResult result;
sql(result, "SELECT COUNT(*) FROM " + default_table_name + ";");
assertResultSetEqual({{i(6)}}, result);
}
std::vector<std::vector<NullableTargetValue>> getExpectedScalarTypesResult(
bool allow_coercion) {
// clang-format off
std::vector<std::vector<NullableTargetValue>> expected{
{
True, i(100), i(30000), i(2000000000), i(9000000000000000000), 10.1f,
100.1234, "00:00:10", "1/1/2000 00:00:59", "1/1/2000", "text_1", "quoted text"
},
{
False, i(110), i(30500), i(2000500000), i(9000000050000000000), 100.12f,
2.1234, "00:10:00", "6/15/2020 00:59:59", "6/15/2020", "text_2", "quoted text 2"
},
{
True, i(120), i(31000), i(2100000000), i(9100000000000000000),
(wrapper_type_ == "redshift" ? 1000.12f : 1000.123f),
100.1, "10:00:00", "12/31/2500 23:59:59", "12/31/2500", "text_3", "quoted text 3"
},
{
i(NULL_BOOLEAN),
((!allow_coercion && wrapper_type_ == "postgres") ? i(NULL_SMALLINT) : i(NULL_TINYINT)), // TINYINT
i(NULL_SMALLINT), i(NULL_INT), i(NULL_BIGINT),
((!allow_coercion && wrapper_type_ == "sqlite") ? NULL_DOUBLE : NULL_FLOAT), // FLOAT
NULL_DOUBLE, Null, Null, Null, Null, Null
}
};
// clang-format on
return expected;
}
void queryAndAssertScalarTypesResult(bool allow_coercion = false) {
sqlAndCompareResult("SELECT * FROM " + default_table_name + " ORDER BY s;",
getExpectedScalarTypesResult(allow_coercion));
}
void queryAndAssertGeoTypesResult() {
sqlAndCompareResult("SELECT * FROM " + default_table_name + " ORDER BY id;",
getExpectedGeoTypesResult());
}
std::vector<std::vector<NullableTargetValue>> getExpectedGeoTypesResult() {
// clang-format off
return {
{
i(1), "POINT (0 0)", "MULTIPOINT (0 0,1 1)", "LINESTRING (0 0,1 1)", "MULTILINESTRING ((0 0,1 1),(5 5,2 2))", "POLYGON ((0 0,1 0,1 1,0 1,0 0))",
"MULTIPOLYGON (((0 0,1 0,0 1,0 0)),((2 2,3 2,2 3,2 2)))"
},
{
i(2), Null, Null, Null, Null, Null, Null
},
{
i(3), "POINT (1 1)", "MULTIPOINT (0 0,1 2,3 2,0 4)", "LINESTRING (1 1,2 2,3 3)", "MULTILINESTRING ((1 1,2 2),(3 3,4 4))", "POLYGON ((5 4,7 4,6 5,5 4))",
"MULTIPOLYGON (((0 0,1 0,0 1,0 0)),((2 2,3 2,2 3,2 2),(2.1 2.1,2.1 2.9,2.9 2.1,2.1 2.1)))"
},
{
i(4), "POINT (2 2)", "MULTIPOINT (5 5,2 2,1 0)", "LINESTRING (2 2,3 3)", "MULTILINESTRING ((2 2,3 3),(4 4,5 5))", "POLYGON ((1 1,3 1,2 3,1 1))",
"MULTIPOLYGON (((5 5,8 8,5 8,5 5)),((0 0,3 0,0 3,0 0)),((11 11,10 12,10 10,11 11)))"
},
{
i(5), Null, Null, Null, Null, Null, Null
}
};
// clang-format on
}
void createForeignTableForGeoTypes(const std::string& data_wrapper_type,
const std::string& extension,
size_t fragment_size = DEFAULT_FRAGMENT_ROWS) {
// geotypes in odbc data wrappers are currently only supported by text data types
std::vector<NameTypePair> odbc_columns{};
if (is_odbc(data_wrapper_type)) {
odbc_columns = {{"id", "INT"},
{"p", "TEXT"},
{"mp", "TEXT"},
{"l", "TEXT"},
{"ml", "TEXT"},
{"poly", "TEXT"},
{"multipoly", "TEXT"}};
}
foreign_storage::OptionsMap options{{"FRAGMENT_SIZE", std::to_string(fragment_size)}};
if (data_wrapper_type == "regex_parser") {
options["LINE_REGEX"] = "(\\d+),\\s*" + get_line_geo_regex(6);
}
sql(createForeignTableQuery({{"id", "INT"},
{"p", "POINT"},
{"mp", "MULTIPOINT"},
{"l", "LINESTRING"},
{"ml", "MULTILINESTRING"},
{"poly", "POLYGON"},
{"multipoly", "MULTIPOLYGON"}},
getDataFilesPath() + "geo_types_valid" + extension,
data_wrapper_type,
options,
default_table_name,
odbc_columns,
is_odbc(data_wrapper_type) ? true : false));
}
void queryAndAssertQuotedIdentifierPairs() {
TQueryResult result;
// clang-format off
sqlAndCompareResult("SELECT * FROM " + default_table_name + " ORDER BY id;",{
{1L}
});
// clang-format on
}
};
class SelectQueryTest : public ForeignTableTest {
protected:
void SetUp() override {
ForeignTableTest::SetUp();
import_export::delimited_parser::set_max_buffer_resize(max_buffer_resize_);
sqlDropForeignTable();
sqlDropForeignTable(0, default_table_name_2);
sql("DROP SERVER IF EXISTS test_server;");
}
void TearDown() override {
if (skip_teardown_) {
return;
}
g_enable_fsi = true;
sqlDropForeignTable();
sqlDropForeignTable(0, default_table_name_2);
sql("DROP SERVER IF EXISTS test_server;");
ForeignTableTest::TearDown();
}
template <typename T>
inline static std::unique_ptr<ChunkMetadata> createChunkMetadata(
const int column_id,
const size_t num_bytes,
const size_t num_elements,
const T& min,
const T& max,
bool has_nulls,
const std::string& table_name) {
auto chunk_metadata =
createChunkMetadata(column_id, num_bytes, num_elements, has_nulls, table_name);
if (chunk_metadata->sqlType.is_array()) {
auto saved_sql_type = chunk_metadata->sqlType;
chunk_metadata->sqlType = saved_sql_type.get_elem_type();
chunk_metadata->fillChunkStats(min, max, has_nulls);
chunk_metadata->sqlType = saved_sql_type;
} else {
chunk_metadata->fillChunkStats(min, max, has_nulls);
}
return chunk_metadata;
}
template <typename T>
inline static std::unique_ptr<ChunkMetadata> createChunkMetadata(
const int column_id,
const size_t num_bytes,
const size_t num_elements,
const T& min,
const T& max,
bool has_nulls) {
return createChunkMetadata(
column_id, num_bytes, num_elements, min, max, has_nulls, default_table_name);
}
inline static std::unique_ptr<ChunkMetadata> createChunkMetadata(
const int column_id,
const size_t num_bytes,
const size_t num_elements,
bool has_nulls,
const std::string& table_name) {
auto& cat = getCatalog();
auto foreign_table = cat.getMetadataForTable(table_name, false);
auto column_descriptor = cat.getMetadataForColumn(foreign_table->tableId, column_id);
auto chunk_metadata = std::make_unique<ChunkMetadata>();
chunk_metadata->sqlType = column_descriptor->columnType;
chunk_metadata->numElements = num_elements;
chunk_metadata->numBytes = num_bytes;
chunk_metadata->chunkStats.has_nulls = has_nulls;
chunk_metadata->chunkStats.min.stringval = nullptr;
chunk_metadata->chunkStats.max.stringval = nullptr;
return chunk_metadata;
}
inline static std::unique_ptr<ChunkMetadata> createChunkMetadata(
const int column_id,
const size_t num_bytes,
const size_t num_elements,
bool has_nulls) {
return createChunkMetadata(
column_id, num_bytes, num_elements, has_nulls, default_table_name);
}
void assertExpectedChunkMetadata(
const std::map<std::pair<int, int>, std::unique_ptr<ChunkMetadata>>&
expected_metadata) const {
assertExpectedChunkMetadata(expected_metadata, default_table_name);
}
void assertExpectedChunkMetadata(
const std::map<std::pair<int, int>, std::unique_ptr<ChunkMetadata>>&
expected_metadata,
const std::string& table_name) const {
auto& cat = getCatalog();
auto foreign_table = cat.getMetadataForTable(table_name, false);
if (!foreign_table) {
throw std::runtime_error("Could not find foreign table: " + table_name);
}
auto fragmenter = foreign_table->fragmenter;
if (!fragmenter) {
throw std::runtime_error("Fragmenter does not exist for foreign table: " +
table_name);
}
std::map<std::pair<int, int>, bool> expected_metadata_found;
for (auto& [k, v] : expected_metadata) {
expected_metadata_found[k] = false;
}
auto query_info = fragmenter->getFragmentsForQuery();
for (const auto& fragment : query_info.fragments) {
auto& chunk_metadata_map = fragment.getChunkMetadataMapPhysical();
for (auto& [col_id, chunk_metadata] : chunk_metadata_map) {
auto fragment_id = fragment.fragmentId;
auto column_id = col_id;
auto fragment_column_ids = std::make_pair(fragment_id, column_id);
auto expected_metadata_iter = expected_metadata.find(fragment_column_ids);
EXPECT_NE(expected_metadata_iter, expected_metadata.end())
<< boost::format(
"Foreign table chunk metadata not found in expected metadata: "
"fragment_id: %d, column_id: %d") %
fragment_id % column_id;
expected_metadata_found[fragment_column_ids] = true;
EXPECT_EQ(*chunk_metadata, *expected_metadata_iter->second)
<< (boost::format("At fragment_id: %d, column_id: %d") % fragment_id %
column_id)
<< " Expected: " << *expected_metadata_iter->second
<< ", Found: " << *chunk_metadata;
}
}
for (auto& [k, v] : expected_metadata_found) {
auto fragment_id = k.first;
auto column_id = k.second;
if (!v) {
ASSERT_TRUE(false) << boost::format(
"Expected chunk metadata not found in foreign table "
"metadata: fragment_id: %d, column_id: %d") %
fragment_id % column_id;
}
}
}
inline static size_t max_buffer_resize_ =
import_export::delimited_parser::get_max_buffer_resize();
};
class CacheControllingSelectQueryBaseTest : public SelectQueryTest {
public:
inline static std::string cache_path_ =
to_string(BASE_PATH) + "/" + shared::kDefaultDiskCacheDirName;
std::optional<File_Namespace::DiskCacheLevel> starting_cache_level_;
File_Namespace::DiskCacheLevel cache_level_;
CacheControllingSelectQueryBaseTest(const File_Namespace::DiskCacheLevel& cache_level)
: cache_level_(cache_level) {}
protected:
void resetPersistentStorageMgr(File_Namespace::DiskCacheLevel cache_level) {
for (auto table_it : getCatalog().getAllTableMetadata()) {
getCatalog().removeFragmenterForTable(table_it->tableId);
}
getCatalog().getDataMgr().resetBufferMgrs(
{cache_path_, cache_level}, 0, getSystemParameters());
}
void SetUp() override {
// Distributed mode doens't handle the resetPersistentStorageMgr appropriately as the
// leaves don't have a way of being updated, so we skip these tests.
SKIP_SETUP_IF_DISTRIBUTED("Test relies on disk cache");
// Disable/enable the cache as test param requires
starting_cache_level_ = getCatalog()
.getDataMgr()
.getPersistentStorageMgr()
->getDiskCacheConfig()
.enabled_level;
if (starting_cache_level_ && (*starting_cache_level_ != cache_level_)) {
resetPersistentStorageMgr(cache_level_);
}
SelectQueryTest::SetUp();
}
void TearDown() override {
if (skip_teardown_) {
return;
}
SelectQueryTest::TearDown();
// Reset cache to pre-test conditions
if (starting_cache_level_ && (*starting_cache_level_ != cache_level_)) {
resetPersistentStorageMgr(*starting_cache_level_);
}
}
};
class CacheControllingSelectQueryTest
: public CacheControllingSelectQueryBaseTest,
public ::testing::WithParamInterface<File_Namespace::DiskCacheLevel> {
public:
CacheControllingSelectQueryTest() : CacheControllingSelectQueryBaseTest(GetParam()) {}
};
class RecoverCacheQueryTest : public ForeignTableTest {
public:
inline static std::string cache_path_ =
to_string(BASE_PATH) + "/" + shared::kDefaultDiskCacheDirName;
Catalog_Namespace::Catalog* cat_;
PersistentStorageMgr* psm_;
foreign_storage::ForeignStorageCache* cache_ = nullptr;
protected:
void resetPersistentStorageMgr(File_Namespace::DiskCacheConfig cache_config) {
for (auto table_it : cat_->getAllTableMetadata()) {
cat_->removeFragmenterForTable(table_it->tableId);
}
cat_->getDataMgr().resetBufferMgrs(cache_config, 0, getSystemParameters());
psm_ = cat_->getDataMgr().getPersistentStorageMgr();
cache_ = psm_->getDiskCache();
}
bool isTableDatawrapperRestored(const std::string& name) {
auto td = getCatalog().getMetadataForTable(name, false);
ChunkKey table_key{getCatalog().getCurrentDB().dbId, td->tableId};
return getCatalog()
.getDataMgr()
.getPersistentStorageMgr()
->getForeignStorageMgr()
->isDatawrapperRestored(table_key);
}
bool isTableDatawrapperDataOnDisk(const std::string& name) {
auto td = getCatalog().getMetadataForTable(name, false);
auto db_id = getCatalog().getCurrentDB().dbId;
ChunkKey table_key{db_id, td->tableId};
return bf::exists(getCatalog()
.getDataMgr()
.getPersistentStorageMgr()
->getDiskCache()
->getSerializedWrapperPath(db_id, td->tableId));
}
bool compareTableDatawrapperMetadataToFile(const std::string& name,
const std::string& filepath) {
auto td = getCatalog().getMetadataForTable(name, false);
auto db_id = getCatalog().getCurrentDB().dbId;
ChunkKey table_key{db_id, td->tableId};
return compare_json_files(getCatalog()
.getDataMgr()
.getPersistentStorageMgr()
->getDiskCache()
->getSerializedWrapperPath(db_id, td->tableId),
filepath,
getDataFilesPath());
}
void resetStorageManagerAndClearTableMemory(const ChunkKey& table_key) {
// Reset cache and clear memory representations.
resetPersistentStorageMgr({cache_path_, File_Namespace::DiskCacheLevel::fsi});
cat_->getDataMgr().deleteChunksWithPrefix(table_key, MemoryLevel::CPU_LEVEL);
cat_->getDataMgr().deleteChunksWithPrefix(table_key, MemoryLevel::GPU_LEVEL);
}
std::string getWrapperMetadataPath(const std::string& prefix,
const std::string& data_wrapper_type = {}) {
std::string path = getDataFilesPath() + "/wrapper_metadata/" + prefix;
if (!data_wrapper_type.empty()) {
path += "_" + data_wrapper_type;
}
return path + ".json";
}
ChunkKey getTestTableKey() {
auto& catalog = getCatalog();
auto td = catalog.getMetadataForTable(default_table_name, false);
CHECK(td);
return ChunkKey{catalog.getDatabaseId(), td->tableId};
}
void setOldDataWrapperMetadata(const std::string& table_name,
const std::string& file_name_prefix) {
auto& catalog = getCatalog();
auto disk_cache = catalog.getDataMgr().getPersistentStorageMgr()->getDiskCache();
ASSERT_NE(disk_cache, nullptr);
auto db_id = catalog.getDatabaseId();
auto td = getCatalog().getMetadataForTable(table_name, false);
ASSERT_NE(td, nullptr);
auto wrapper_metadata_path = disk_cache->getSerializedWrapperPath(db_id, td->tableId);
ASSERT_TRUE(boost::filesystem::exists(wrapper_metadata_path));
auto file_name_suffix = is_regex(wrapper_type_) ? "csv" : wrapper_type_;
auto prefix = (boost::filesystem::path("old") / file_name_prefix).string();
auto old_wrapper_metadata_path = getWrapperMetadataPath(prefix, file_name_suffix);
ASSERT_TRUE(boost::filesystem::exists(old_wrapper_metadata_path));
// Write content from the old wrapper metadata test file, replacing "BASEPATH" with
// the actual base path value.
boost::filesystem::remove(wrapper_metadata_path);
std::ofstream new_file{wrapper_metadata_path};
std::ifstream old_file{old_wrapper_metadata_path};
std::string line;
while (std::getline(old_file, line)) {
static std::regex base_path_regex{"BASEPATH"};
new_file << std::regex_replace(line, base_path_regex, getDataFilesPath());
}
}
void SetUp() override {
ForeignTableTest::SetUp();
cat_ = &getCatalog();
psm_ = cat_->getDataMgr().getPersistentStorageMgr();
cache_ = psm_->getDiskCache();
sqlDropForeignTable();
cache_->clear();
}
void TearDown() override {
if (skip_teardown_) {
return;
}
sqlDropForeignTable();
if (cache_) {
// Cache may not exist if SetUp() was skipped.
cache_->clear();
}
ForeignTableTest::TearDown();
}
inline static boost::filesystem::path test_dir_{test_temp_dir + "recover_test_dir"};
};
TEST_F(RecoverCacheQueryTest, RecoverWithoutWrappers) {
SKIP_IF_DISTRIBUTED("Test relies on local metadata or cache access");
std::string query = "CREATE FOREIGN TABLE " + default_table_name +
" (t TEXT, i BIGINT[]) "s +
"SERVER default_local_delimited WITH (file_path = '" +
getDataFilesPath() + "/" + "example_1_dir_archives/');";
sql(query);
auto td = cat_->getMetadataForTable(default_table_name, false);
ChunkKey key{cat_->getCurrentDB().dbId, td->tableId, 1, 0};
ChunkKey table_key{cat_->getCurrentDB().dbId, td->tableId};
sqlAndCompareResult("SELECT * FROM " + default_table_name + " ORDER BY t;",
{{"a", array({i(1), i(1), i(1)})},
{"aa", array({NULL_BIGINT, i(2), i(2)})},
{"aaa", array({i(3), NULL_BIGINT, i(3)})}});
// Reset cache and clear memory representations.
resetStorageManagerAndClearTableMemory(table_key);
ASSERT_FALSE(isTableDatawrapperRestored(default_table_name));
sqlAndCompareResult("SELECT * FROM " + default_table_name + " ORDER BY t;",
{{"a", array({i(1), i(1), i(1)})},
{"aa", array({NULL_BIGINT, i(2), i(2)})},
{"aaa", array({i(3), NULL_BIGINT, i(3)})}});
ASSERT_EQ(cache_->getNumCachedChunks(), 3U); // 2 data + 1 index chunk
ASSERT_EQ(cache_->getNumCachedMetadata(), 2U); // Only 2 metadata
ASSERT_TRUE(isTableDatawrapperRestored(default_table_name));
}
TEST_F(RecoverCacheQueryTest, ErrorDuringRecovery) {
SKIP_IF_DISTRIBUTED("Test relies on local metadata or cache access");
boost::filesystem::create_directory(test_dir_);
boost::filesystem::copy_file(getDataFilesPath() + "0.csv", test_dir_ / "0.csv");
boost::filesystem::copy_file(getDataFilesPath() + "1.csv", test_dir_ / "1.csv");
std::string query = "CREATE FOREIGN TABLE " + default_table_name +
" (i INTEGER) SERVER default_local_delimited "
"WITH (file_path = '" +
test_dir_.string() + "');";
sql(query);
auto td = cat_->getMetadataForTable(default_table_name, false);
ChunkKey table_key{cat_->getCurrentDB().dbId, td->tableId};
sqlAndCompareResult("SELECT * FROM " + default_table_name + " ORDER BY i;",
{{i(0)}, {i(1)}});
// Clear cached table chunks and reset cache.
ChunkMetadataVector metadata_vector;
cache_->getCachedMetadataVecForKeyPrefix(metadata_vector, table_key);
for (const auto& [chunk_key, metadata] : metadata_vector) {
cache_->eraseChunk(chunk_key);
}
resetStorageManagerAndClearTableMemory(table_key);
ASSERT_FALSE(isTableDatawrapperRestored(default_table_name));
// Removing one of the referenced files should cause an error during cache recovery.
// Error should be gracefully handled without interrupting the query.
auto deleted_file_path = test_dir_ / "0.csv";
boost::filesystem::remove_all(deleted_file_path);
sqlAndCompareResult("SELECT * FROM " + default_table_name + ";", {{i(1)}});
ASSERT_EQ(cache_->getNumCachedChunks(), size_t(1));
ASSERT_EQ(cache_->getNumCachedMetadata(), size_t(1));
ASSERT_FALSE(isTableDatawrapperRestored(default_table_name));
// Subsequent query after cache recovery error would previously cause a crash.
sqlAndCompareResult("SELECT * FROM " + default_table_name + ";", {{i(1)}});