forked from heavyai/heavydb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueryRunner.cpp
1332 lines (1219 loc) · 55.2 KB
/
QueryRunner.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.
*/
#include "QueryRunner.h"
#include "Calcite/Calcite.h"
#include "Catalog/Catalog.h"
#include "Catalog/DdlCommandExecutor.h"
#include "DistributedLoader.h"
#include "Geospatial/ColumnNames.h"
#include "ImportExport/CopyParams.h"
#include "Logger/Logger.h"
#include "Parser/ParserNode.h"
#include "Parser/ParserWrapper.h"
#include "QueryEngine/CalciteAdapter.h"
#include "QueryEngine/DataRecycler/HashtableRecycler.h"
#include "QueryEngine/ExtensionFunctionsWhitelist.h"
#include "QueryEngine/QueryDispatchQueue.h"
#include "QueryEngine/QueryPlanDagExtractor.h"
#include "QueryEngine/RelAlgExecutor.h"
#include "QueryEngine/TableFunctions/TableFunctionsFactory.h"
#include "QueryEngine/ThriftSerializers.h"
#ifdef HAVE_RUNTIME_LIBS
#include "RuntimeLibManager/RuntimeLibManager.h"
#endif
#include "Shared/StringTransform.h"
#include "Shared/SysDefinitions.h"
#include "Shared/SystemParameters.h"
#include "Shared/import_helpers.h"
#include "TestProcessSignalHandler.h"
#include "gen-cpp/CalciteServer.h"
#include "include/bcrypt.h"
#include <boost/filesystem/operations.hpp>
#include <csignal>
#include <random>
#define CALCITEPORT 3279
extern size_t g_leaf_count;
extern bool g_enable_filter_push_down;
double g_gpu_mem_limit_percent{0.9};
extern bool g_serialize_temp_tables;
bool g_enable_calcite_view_optimize{true};
std::mutex calcite_lock;
using namespace Catalog_Namespace;
namespace {
std::shared_ptr<Calcite> g_calcite = nullptr;
void calcite_shutdown_handler() noexcept {
if (g_calcite) {
g_calcite->close_calcite_server();
g_calcite.reset();
}
}
void setup_signal_handler() {
TestProcessSignalHandler::registerSignalHandler();
TestProcessSignalHandler::addShutdownCallback(calcite_shutdown_handler);
}
} // namespace
namespace QueryRunner {
std::unique_ptr<QueryRunner> QueryRunner::qr_instance_ = nullptr;
query_state::QueryStates QueryRunner::query_states_;
QueryRunner* QueryRunner::init(const char* db_path,
const std::string& udf_filename,
const size_t max_gpu_mem,
const int reserved_gpu_mem) {
return QueryRunner::init(db_path,
shared::kRootUsername,
"HyperInteractive",
shared::kDefaultDbName,
{},
{},
udf_filename,
true,
max_gpu_mem,
reserved_gpu_mem);
}
QueryRunner* QueryRunner::init(const File_Namespace::DiskCacheConfig* disk_cache_config,
const char* db_path,
const std::vector<LeafHostInfo>& string_servers,
const std::vector<LeafHostInfo>& leaf_servers) {
return QueryRunner::init(db_path,
shared::kRootUsername,
"HyperInteractive",
shared::kDefaultDbName,
string_servers,
leaf_servers,
"",
true,
0,
256 << 20,
false,
false,
disk_cache_config);
}
QueryRunner* QueryRunner::init(const char* db_path,
const std::string& user,
const std::string& pass,
const std::string& db_name,
const std::vector<LeafHostInfo>& string_servers,
const std::vector<LeafHostInfo>& leaf_servers,
const std::string& udf_filename,
bool uses_gpus,
const size_t max_gpu_mem,
const int reserved_gpu_mem,
const bool create_user,
const bool create_db,
const File_Namespace::DiskCacheConfig* disk_cache_config) {
// Whitelist root path for tests by default
ddl_utils::FilePathWhitelist::clear();
ddl_utils::FilePathWhitelist::initialize(db_path, "[\"/\"]", "[\"/\"]");
LOG_IF(FATAL, !leaf_servers.empty()) << "Distributed test runner not supported.";
CHECK(leaf_servers.empty());
qr_instance_.reset(new QueryRunner(db_path,
user,
pass,
db_name,
string_servers,
leaf_servers,
udf_filename,
uses_gpus,
max_gpu_mem,
reserved_gpu_mem,
create_user,
create_db,
disk_cache_config));
return qr_instance_.get();
}
QueryRunner::QueryRunner(const char* db_path,
const std::string& user_name,
const std::string& passwd,
const std::string& db_name,
const std::vector<LeafHostInfo>& string_servers,
const std::vector<LeafHostInfo>& leaf_servers,
const std::string& udf_filename,
bool uses_gpus,
const size_t max_gpu_mem,
const int reserved_gpu_mem,
const bool create_user,
const bool create_db,
const File_Namespace::DiskCacheConfig* cache_config)
: dispatch_queue_(std::make_unique<QueryDispatchQueue>(1)) {
g_serialize_temp_tables = true;
boost::filesystem::path base_path{db_path};
CHECK(boost::filesystem::exists(base_path));
auto system_db_file =
base_path / shared::kCatalogDirectoryName / shared::kDefaultDbName;
CHECK(boost::filesystem::exists(system_db_file));
auto data_dir = base_path / shared::kDataDirectoryName;
File_Namespace::DiskCacheConfig disk_cache_config{
(base_path / shared::kDefaultDiskCacheDirName).string(),
File_Namespace::DiskCacheLevel::fsi};
if (cache_config) {
disk_cache_config = *cache_config;
}
Catalog_Namespace::UserMetadata user;
setup_signal_handler();
logger::set_once_fatal_func(&calcite_shutdown_handler);
g_calcite =
std::make_shared<Calcite>(-1, CALCITEPORT, db_path, 1024, 5000, true, udf_filename);
ExtensionFunctionsWhitelist::add(g_calcite->getExtensionFunctionWhitelist());
if (!udf_filename.empty()) {
ExtensionFunctionsWhitelist::addUdfs(g_calcite->getUserDefinedFunctionWhitelist());
}
table_functions::init_table_functions();
#ifdef HAVE_RUNTIME_LIBS
RuntimeLibManager::loadTestRuntimeLibs();
RuntimeLibManager::loadRuntimeLibs();
#endif
auto udtfs = ThriftSerializers::to_thrift(
table_functions::TableFunctionsFactory::get_table_funcs(/*is_runtime=*/false));
std::vector<TUserDefinedFunction> udfs = {};
g_calcite->setRuntimeExtensionFunctions(udfs, udtfs, /*is_runtime=*/false);
std::unique_ptr<CudaMgr_Namespace::CudaMgr> cuda_mgr;
#ifdef HAVE_CUDA
if (uses_gpus) {
cuda_mgr = std::make_unique<CudaMgr_Namespace::CudaMgr>(-1, 0);
}
#else
uses_gpus = false;
#endif
const size_t num_gpus = static_cast<size_t>(cuda_mgr ? cuda_mgr->getDeviceCount() : 0);
SystemParameters mapd_params;
mapd_params.gpu_buffer_mem_bytes = max_gpu_mem;
mapd_params.aggregator = !leaf_servers.empty();
auto& sys_cat = Catalog_Namespace::SysCatalog::instance();
g_base_path = base_path.string();
if (!sys_cat.isInitialized()) {
auto data_mgr = std::make_shared<Data_Namespace::DataMgr>(data_dir.string(),
mapd_params,
std::move(cuda_mgr),
uses_gpus,
reserved_gpu_mem,
0,
disk_cache_config);
if (g_enable_executor_resource_mgr) {
// With the exception of cpu_result_mem, the below values essentially mirror
// how ExecutorResourceMgr is initialized by DBHandler for normal DB operation.
// The static 4GB allowcation of CPU result memory is sufficient for our tests,
// and prevents variability based on the DBHandler approach to sizing as a fraction
// of CPU buffer pool mem size.
Executor::init_resource_mgr(
cpu_threads() /* num_cpu_slots */,
num_gpus /* num_gpu_slots */,
static_cast<size_t>(1UL << 32) /* cpu_result_mem */,
data_mgr->getCpuBufferPoolSize() /* cpu_buffer_pool_mem */,
data_mgr->getGpuBufferPoolSize() /* gpu_buffer_pool_mem */,
0.9 /* per_query_max_cpu_slots_ratio */,
1.0 /* per_query_max_cpu_result_mem_ratio */,
true /* allow_cpu_kernel_concurrency */,
true /* allow_cpu_gpu_kernel_concurrency */,
false /* allow_cpu_slot_oversubscription_concurrency */,
false /* allow_cpu_result_mem_oversubscription_concurrency */,
0.9 /* max_available_resource_use_ratio */);
}
sys_cat.init(g_base_path,
data_mgr,
{},
g_calcite,
false,
mapd_params.aggregator,
string_servers);
}
query_engine_ =
QueryEngine::createInstance(sys_cat.getDataMgr().getCudaMgr(), !uses_gpus);
if (create_user) {
if (!sys_cat.getMetadataForUser(user_name, user)) {
sys_cat.createUser(
user_name,
UserAlterations{
passwd, /*is_super=*/false, /*default_db=*/"", /*can_login=*/true},
g_read_only);
}
}
CHECK(sys_cat.getMetadataForUser(user_name, user));
CHECK(bcrypt_checkpw(passwd.c_str(), user.passwd_hash.c_str()) == 0);
if (create_db) {
if (!sys_cat.getMetadataForDB(db_name, db_metadata_)) {
sys_cat.createDatabase(db_name, user.userId);
}
}
CHECK(sys_cat.getMetadataForDB(db_name, db_metadata_));
CHECK(user.isSuper || (user.userId == db_metadata_.dbOwner));
auto cat = sys_cat.getCatalog(db_metadata_, create_db);
CHECK(cat);
session_info_ = std::make_unique<Catalog_Namespace::SessionInfo>(
cat, user, ExecutorDeviceType::GPU, "");
}
void QueryRunner::resizeDispatchQueue(const size_t num_executors) {
dispatch_queue_ = std::make_unique<QueryDispatchQueue>(num_executors);
}
QueryRunner::QueryRunner(std::unique_ptr<Catalog_Namespace::SessionInfo> session)
: session_info_(std::move(session))
, dispatch_queue_(std::make_unique<QueryDispatchQueue>(1)) {}
std::shared_ptr<Catalog_Namespace::Catalog> QueryRunner::getCatalog() const {
CHECK(session_info_);
return session_info_->get_catalog_ptr();
}
std::shared_ptr<Calcite> QueryRunner::getCalcite() const {
// TODO: Embed Calcite shared_ptr ownership in QueryRunner
return g_calcite;
}
bool QueryRunner::gpusPresent() const {
CHECK(session_info_);
return session_info_->getCatalog().getDataMgr().gpusPresent();
}
void QueryRunner::clearGpuMemory() const {
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
Executor::clearMemory(Data_Namespace::MemoryLevel::GPU_LEVEL);
}
void QueryRunner::clearCpuMemory() const {
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
Executor::clearMemory(Data_Namespace::MemoryLevel::CPU_LEVEL);
}
std::vector<MemoryInfo> QueryRunner::getMemoryInfo(
const Data_Namespace::MemoryLevel memory_level) const {
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
return session_info_->getCatalog().getDataMgr().getMemoryInfo(memory_level);
}
BufferPoolStats QueryRunner::getBufferPoolStats(
const Data_Namespace::MemoryLevel memory_level,
const bool current_db_only) const {
// Only works single-node for now
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
const std::vector<MemoryInfo> memory_infos =
session_info_->getCatalog().getDataMgr().getMemoryInfo(memory_level);
if (memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
CHECK_EQ(memory_infos.size(), static_cast<size_t>(1));
}
std::set<std::vector<int32_t>> chunk_keys;
std::set<std::vector<int32_t>> table_keys;
std::set<std::vector<int32_t>> column_keys;
std::set<std::vector<int32_t>> fragment_keys;
size_t total_num_buffers{
0}; // can be greater than chunk keys set size due to table replication
size_t total_num_bytes{0};
for (auto& pool_memory_info : memory_infos) {
const std::vector<MemoryData>& memory_data = pool_memory_info.nodeMemoryData;
for (auto& memory_datum : memory_data) {
total_num_buffers++;
const auto& chunk_key = memory_datum.chunk_key;
if (memory_datum.memStatus == Buffer_Namespace::MemStatus::FREE ||
chunk_key.size() < 4) {
continue;
}
if (current_db_only) {
if (chunk_key[0] != db_metadata_.dbId) {
continue;
}
}
total_num_bytes += (memory_datum.numPages * pool_memory_info.pageSize);
table_keys.insert({chunk_key[0], chunk_key[1]});
column_keys.insert({chunk_key[0], chunk_key[1], chunk_key[2]});
fragment_keys.insert({chunk_key[0], chunk_key[1], chunk_key[3]});
chunk_keys.insert(chunk_key);
}
}
return {total_num_buffers,
total_num_bytes,
table_keys.size(),
column_keys.size(),
fragment_keys.size(),
chunk_keys.size()};
}
RegisteredQueryHint QueryRunner::getParsedQueryHint(const std::string& query_str) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
auto query_hints =
ra_executor.getParsedQueryHint(ra_executor.getRootRelAlgNodeShPtr().get());
return query_hints ? *query_hints : RegisteredQueryHint::defaults();
}
std::shared_ptr<const RelAlgNode> QueryRunner::getRootNodeFromParsedQuery(
const std::string& query_str) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
return ra_executor.getRootRelAlgNodeShPtr();
}
std::optional<
std::unordered_map<size_t, std::unordered_map<unsigned, RegisteredQueryHint>>>
QueryRunner::getParsedQueryHints(const std::string& query_str) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
return ra_executor.getParsedQueryHints();
}
std::optional<RegisteredQueryHint> QueryRunner::getParsedGlobalQueryHints(
const std::string& query_str) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
return ra_executor.getGlobalQueryHint();
}
RaExecutionSequence QueryRunner::getRaExecutionSequence(const std::string& query_str) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
return ra_executor.getRaExecutionSequence(ra_executor.getRootRelAlgNodeShPtr().get(),
executor.get());
}
// used to validate calcite ddl statements
void QueryRunner::validateDDLStatement(const std::string& stmt_str_in) {
CHECK(session_info_);
std::string stmt_str = stmt_str_in;
// First remove special chars
boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
// Then remove spaces
boost::algorithm::trim_left(stmt_str);
auto query_state = create_query_state(session_info_, stmt_str);
auto stdlog = STDLOG(query_state);
auto& cat = session_info_->getCatalog();
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
calcite_mgr->process(query_state->createQueryStateProxy(),
pg_shim(stmt_str),
calciteQueryParsingOption,
calciteOptimizationOption);
}
std::shared_ptr<RelAlgTranslator> QueryRunner::getRelAlgTranslator(
const std::string& query_str,
Executor* executor) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor, query_ra);
auto root_node_shared_ptr = ra_executor.getRootRelAlgNodeShPtr();
return ra_executor.getRelAlgTranslator(root_node_shared_ptr.get());
}
QueryPlanDagInfo QueryRunner::getQueryInfoForDataRecyclerTest(
const std::string& query_str) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto& cat = session_info_->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
// note that we assume the test for data recycler that needs to have join_info
// does not contain any ORDER BY clause; this is necessary to create work_unit
// without actually performing the query
auto root_node_shared_ptr = ra_executor.getRootRelAlgNodeShPtr();
auto join_info = ra_executor.getJoinInfo(root_node_shared_ptr.get());
auto relAlgTranslator = ra_executor.getRelAlgTranslator(root_node_shared_ptr.get());
return {root_node_shared_ptr, join_info.first, join_info.second, relAlgTranslator};
}
std::unique_ptr<Parser::Stmt> QueryRunner::createStatement(
const std::string& stmt_str_in) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
std::string stmt_str = stmt_str_in;
// First remove special chars
boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
// Then remove spaces
boost::algorithm::trim_left(stmt_str);
ParserWrapper pw{stmt_str};
auto query_state = create_query_state(session_info_, stmt_str);
auto stdlog = STDLOG(query_state);
if (pw.is_ddl) {
const auto& cat = session_info_->getCatalog();
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_json = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(stmt_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
return Parser::create_stmt_for_json(query_json);
}
// simply fail here as non-Calcite parsing is about to be removed
UNREACHABLE();
return nullptr;
}
void QueryRunner::runDDLStatement(const std::string& stmt_str_in) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
std::string stmt_str = stmt_str_in;
// First remove special chars
boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
// Then remove spaces
boost::algorithm::trim_left(stmt_str);
ParserWrapper pw{stmt_str};
auto query_state = create_query_state(session_info_, stmt_str);
auto stdlog = STDLOG(query_state);
if (pw.is_ddl || pw.getDMLType() == ParserWrapper::DMLType::Insert) {
auto& cat = session_info_->getCatalog();
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(stmt_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
if (pw.getDMLType() == ParserWrapper::DMLType::Insert) {
rapidjson::Document ddl_query;
ddl_query.Parse(query_ra);
CHECK(ddl_query.HasMember("payload"));
CHECK(ddl_query["payload"].IsObject());
auto stmt = Parser::InsertValuesStmt(cat, ddl_query["payload"].GetObject());
stmt.execute(*session_info_, false /* read only */);
return;
}
DdlCommandExecutor executor = DdlCommandExecutor(query_ra, session_info_);
executor.execute(false /* read only */);
return;
}
}
std::shared_ptr<ResultSet> QueryRunner::runSQL(const std::string& query_str,
CompilationOptions co,
ExecutionOptions eo) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
ParserWrapper pw{query_str};
if (pw.getDMLType() == ParserWrapper::DMLType::Insert) {
runDDLStatement(query_str);
return nullptr;
}
const auto execution_result = runSelectQuery(query_str, std::move(co), std::move(eo));
return execution_result->getRows();
}
std::shared_ptr<ResultSet> QueryRunner::runSQL(const std::string& query_str,
const ExecutorDeviceType device_type,
const bool hoist_literals,
const bool allow_loop_joins) {
auto co = CompilationOptions::defaults(device_type);
co.hoist_literals = hoist_literals;
return runSQL(
query_str, std::move(co), defaultExecutionOptionsForRunSQL(allow_loop_joins));
}
ExecutionOptions QueryRunner::defaultExecutionOptionsForRunSQL(bool allow_loop_joins,
bool just_explain) {
return {g_enable_columnar_output,
false,
true,
just_explain,
allow_loop_joins,
false,
false,
false,
false,
10000,
false,
false,
g_gpu_mem_limit_percent,
false,
0.5,
1000,
false};
}
std::shared_ptr<Executor> QueryRunner::getExecutor() const {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, "");
auto stdlog = STDLOG(query_state);
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
return executor;
}
std::shared_ptr<ResultSet> QueryRunner::runSQLWithAllowingInterrupt(
const std::string& query_str,
const std::string& session_id,
const ExecutorDeviceType device_type,
const double running_query_check_freq,
const unsigned pending_query_check_freq) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto current_user = session_info_->get_currentUser();
auto session_info = std::make_shared<Catalog_Namespace::SessionInfo>(
session_info_->get_catalog_ptr(), current_user, device_type, session_id);
auto query_state = create_query_state(session_info, query_str);
auto stdlog = STDLOG(query_state);
auto& cat = query_state->getConstSessionInfo()->getCatalog();
std::string query_ra{""};
std::shared_ptr<ExecutionResult> result;
auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
[&cat,
&query_ra,
&device_type,
&query_state,
&result,
&running_query_check_freq,
&pending_query_check_freq,
parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
auto executor = Executor::getExecutor(worker_id);
CompilationOptions co = CompilationOptions::defaults(device_type);
ExecutionOptions eo = {g_enable_columnar_output,
false,
true,
false,
true,
false,
false,
false,
false,
10000,
false,
false,
g_gpu_mem_limit_percent,
true,
running_query_check_freq,
pending_query_check_freq,
false};
{
// async query initiation for interrupt test
// incurs data race warning in TSAN since
// calcite_mgr is shared across multiple query threads
// so here we lock the manager during query parsing
std::lock_guard<std::mutex> calcite_lock_guard(calcite_lock);
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(
false, g_enable_watchdog, {}, false);
query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_state->getQueryStr()),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
}
auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
result = std::make_shared<ExecutionResult>(
ra_executor.executeRelAlgQuery(co, eo, false, false, nullptr));
});
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
executor->enrollQuerySession(session_id,
query_str,
query_state->getQuerySubmittedTime(),
Executor::UNITARY_EXECUTOR_ID,
QuerySessionStatus::QueryStatus::PENDING_QUEUE);
CHECK(dispatch_queue_);
dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
auto result_future = query_launch_task->get_future();
result_future.get();
CHECK(result);
return result->getRows();
}
std::vector<std::shared_ptr<ResultSet>> QueryRunner::runMultipleStatements(
const std::string& sql,
const ExecutorDeviceType dt) {
std::vector<std::shared_ptr<ResultSet>> results;
// TODO: Need to properly handle escaped semicolons instead of doing a naive split().
auto fields = split(sql, ";");
for (const auto& field : fields) {
auto text = strip(field) + ";";
if (text == ";") {
continue;
}
ParserWrapper pw{text};
if (pw.is_ddl || pw.getDMLType() == ParserWrapper::DMLType::Insert) {
runDDLStatement(text);
results.push_back(nullptr);
} else {
// is not DDL, then assume it's DML and try to execute
results.push_back(runSQL(text, dt, true, true));
}
}
return results;
}
void QueryRunner::runImport(Parser::CopyTableStmt* import_stmt) {
CHECK(import_stmt);
import_stmt->execute(*session_info_, false /* read only */);
}
std::unique_ptr<import_export::Loader> QueryRunner::getLoader(
const TableDescriptor* td) const {
auto cat = getCatalog();
return std::make_unique<import_export::Loader>(*cat, td);
}
namespace {
std::shared_ptr<ExecutionResult> run_select_query_with_filter_push_down(
QueryStateProxy query_state_proxy,
const ExecutorDeviceType device_type,
const bool hoist_literals,
const bool allow_loop_joins,
const bool just_explain,
const ExecutorExplainType explain_type,
const bool with_filter_push_down) {
auto& cat = query_state_proxy->getConstSessionInfo()->getCatalog();
auto executor = Executor::getExecutor(Executor::UNITARY_EXECUTOR_ID);
CompilationOptions co = CompilationOptions::defaults(device_type);
co.explain_type = explain_type;
ExecutionOptions eo = ExecutionOptions::defaults();
eo.output_columnar_hint = g_enable_columnar_output;
eo.just_explain = just_explain;
eo.allow_loop_joins = allow_loop_joins;
eo.find_push_down_candidates = with_filter_push_down;
eo.gpu_input_mem_limit_percent = g_gpu_mem_limit_percent;
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
auto calciteOptimizationOption =
calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state_proxy,
pg_shim(query_state_proxy->getQueryStr()),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
auto result = std::make_shared<ExecutionResult>(
ra_executor.executeRelAlgQuery(co, eo, false, false, nullptr));
const auto& filter_push_down_requests = result->getPushedDownFilterInfo();
if (!filter_push_down_requests.empty()) {
std::vector<TFilterPushDownInfo> filter_push_down_info;
for (const auto& req : filter_push_down_requests) {
TFilterPushDownInfo filter_push_down_info_for_request;
filter_push_down_info_for_request.input_prev = req.input_prev;
filter_push_down_info_for_request.input_start = req.input_start;
filter_push_down_info_for_request.input_next = req.input_next;
filter_push_down_info.push_back(filter_push_down_info_for_request);
}
calciteOptimizationOption.filter_push_down_info = filter_push_down_info;
const auto new_query_ra = calcite_mgr
->process(query_state_proxy,
pg_shim(query_state_proxy->getQueryStr()),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto eo_modified = eo;
eo_modified.find_push_down_candidates = false;
eo_modified.just_calcite_explain = false;
auto new_ra_executor = RelAlgExecutor(executor.get(), new_query_ra);
return std::make_shared<ExecutionResult>(
new_ra_executor.executeRelAlgQuery(co, eo_modified, false, false, nullptr));
} else {
return result;
}
}
} // namespace
std::shared_ptr<ResultSet> QueryRunner::getCalcitePlan(const std::string& query_str,
bool enable_watchdog,
bool is_explain_as_json_str,
bool is_explain_detailed) const {
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
CHECK(session_info_);
const auto& cat = session_info_->getCatalog();
auto query_state = create_query_state(session_info_, query_str);
auto stdlog = STDLOG(query_state);
std::shared_ptr<ResultSet> result;
auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
[&cat,
&query_str,
&enable_watchdog,
&is_explain_as_json_str,
&is_explain_detailed,
&query_state,
&result,
parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
auto executor = Executor::getExecutor(worker_id);
auto calcite_mgr = cat.getCalciteMgr();
// Calcite returns its plan as a form of `json_str` by default,
// so we set `is_explain` to TRUE if `!is_explain_as_json_str`
const auto calciteQueryParsingOption = calcite_mgr->getCalciteQueryParsingOption(
true, !is_explain_as_json_str, false, is_explain_detailed);
const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
g_enable_calcite_view_optimize, enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
result = std::make_shared<ResultSet>(query_ra);
return result;
});
CHECK(dispatch_queue_);
dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
auto result_future = query_launch_task->get_future();
result_future.get();
CHECK(result);
return result;
}
std::shared_ptr<ExecutionResult> QueryRunner::runSelectQuery(const std::string& query_str,
CompilationOptions co,
ExecutionOptions eo) {
CHECK(session_info_);
CHECK(!Catalog_Namespace::SysCatalog::instance().isAggregator());
auto query_state = create_query_state(session_info_, query_str);
auto stdlog = STDLOG(query_state);
if (g_enable_filter_push_down) {
return run_select_query_with_filter_push_down(query_state->createQueryStateProxy(),
co.device_type,
co.hoist_literals,
eo.allow_loop_joins,
eo.just_explain,
explain_type_,
g_enable_filter_push_down);
}
auto& cat = session_info_->getCatalog();
std::shared_ptr<ExecutionResult> result;
auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
[&cat,
&query_str,
&co,
explain_type = this->explain_type_,
&eo,
&query_state,
&result,
parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
auto executor = Executor::getExecutor(worker_id);
// TODO The next line should be deleted since it overwrites co, but then
// NycTaxiTest.RunSelectsEncodingDictWhereGreater fails due to co not getting
// reset to its default values.
co = CompilationOptions::defaults(co.device_type);
co.explain_type = explain_type;
auto calcite_mgr = cat.getCalciteMgr();
const auto calciteQueryParsingOption =
calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
g_enable_calcite_view_optimize, g_enable_watchdog, {}, false);
const auto query_ra = calcite_mgr
->process(query_state->createQueryStateProxy(),
pg_shim(query_str),
calciteQueryParsingOption,
calciteOptimizationOption)
.plan_result;
auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
result = std::make_shared<ExecutionResult>(
ra_executor.executeRelAlgQuery(co, eo, false, false, nullptr));
});
CHECK(dispatch_queue_);
dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
auto result_future = query_launch_task->get_future();
result_future.get();
CHECK(result);
return result;
}
std::shared_ptr<ExecutionResult> QueryRunner::runSelectQuery(
const std::string& query_str,
const ExecutorDeviceType device_type,
const bool hoist_literals,
const bool allow_loop_joins,
const bool just_explain) {
auto co = CompilationOptions::defaults(device_type);
co.hoist_literals = hoist_literals;
return runSelectQuery(query_str,
std::move(co),
defaultExecutionOptionsForRunSQL(allow_loop_joins, just_explain));
}