OmniSciDB  c1a53651b2
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
QueryRunner.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "QueryRunner.h"
18 
19 #include "Calcite/Calcite.h"
20 #include "Catalog/Catalog.h"
22 #include "DistributedLoader.h"
23 #include "Geospatial/ColumnNames.h"
25 #include "Logger/Logger.h"
26 #include "Parser/ParserNode.h"
27 #include "Parser/ParserWrapper.h"
36 #include "Shared/StringTransform.h"
37 #include "Shared/SysDefinitions.h"
39 #include "Shared/import_helpers.h"
41 #include "gen-cpp/CalciteServer.h"
42 #include "include/bcrypt.h"
43 
44 #include <boost/filesystem/operations.hpp>
45 #include <csignal>
46 #include <random>
47 
48 #define CALCITEPORT 3279
49 
50 extern size_t g_leaf_count;
51 extern bool g_enable_filter_push_down;
52 
54 
55 extern bool g_serialize_temp_tables;
57 std::mutex calcite_lock;
58 
59 using namespace Catalog_Namespace;
60 namespace {
61 
62 std::shared_ptr<Calcite> g_calcite = nullptr;
63 
64 void calcite_shutdown_handler() noexcept {
65  if (g_calcite) {
66  g_calcite->close_calcite_server();
67  g_calcite.reset();
68  }
69 }
70 
74 }
75 
76 } // namespace
77 
78 namespace QueryRunner {
79 
80 std::unique_ptr<QueryRunner> QueryRunner::qr_instance_ = nullptr;
81 
82 query_state::QueryStates QueryRunner::query_states_;
83 
84 QueryRunner* QueryRunner::init(const char* db_path,
85  const std::string& udf_filename,
86  const size_t max_gpu_mem,
87  const int reserved_gpu_mem) {
88  return QueryRunner::init(db_path,
90  "HyperInteractive",
92  {},
93  {},
94  udf_filename,
95  true,
96  max_gpu_mem,
97  reserved_gpu_mem);
98 }
99 
101  const char* db_path,
102  const std::vector<LeafHostInfo>& string_servers,
103  const std::vector<LeafHostInfo>& leaf_servers) {
104  return QueryRunner::init(db_path,
106  "HyperInteractive",
108  string_servers,
109  leaf_servers,
110  "",
111  true,
112  0,
113  256 << 20,
114  false,
115  false,
116  disk_cache_config);
117 }
118 
119 QueryRunner* QueryRunner::init(const char* db_path,
120  const std::string& user,
121  const std::string& pass,
122  const std::string& db_name,
123  const std::vector<LeafHostInfo>& string_servers,
124  const std::vector<LeafHostInfo>& leaf_servers,
125  const std::string& udf_filename,
126  bool uses_gpus,
127  const size_t max_gpu_mem,
128  const int reserved_gpu_mem,
129  const bool create_user,
130  const bool create_db,
131  const File_Namespace::DiskCacheConfig* disk_cache_config) {
132  // Whitelist root path for tests by default
134  ddl_utils::FilePathWhitelist::initialize(db_path, "[\"/\"]", "[\"/\"]");
135  LOG_IF(FATAL, !leaf_servers.empty()) << "Distributed test runner not supported.";
136  CHECK(leaf_servers.empty());
137  qr_instance_.reset(new QueryRunner(db_path,
138  user,
139  pass,
140  db_name,
141  string_servers,
142  leaf_servers,
143  udf_filename,
144  uses_gpus,
145  max_gpu_mem,
146  reserved_gpu_mem,
147  create_user,
148  create_db,
149  disk_cache_config));
150  return qr_instance_.get();
151 }
152 
153 QueryRunner::QueryRunner(const char* db_path,
154  const std::string& user_name,
155  const std::string& passwd,
156  const std::string& db_name,
157  const std::vector<LeafHostInfo>& string_servers,
158  const std::vector<LeafHostInfo>& leaf_servers,
159  const std::string& udf_filename,
160  bool uses_gpus,
161  const size_t max_gpu_mem,
162  const int reserved_gpu_mem,
163  const bool create_user,
164  const bool create_db,
165  const File_Namespace::DiskCacheConfig* cache_config)
166  : dispatch_queue_(std::make_unique<QueryDispatchQueue>(1)) {
168  boost::filesystem::path base_path{db_path};
169  CHECK(boost::filesystem::exists(base_path));
170  auto system_db_file =
172  CHECK(boost::filesystem::exists(system_db_file));
173  auto data_dir = base_path / shared::kDataDirectoryName;
174  File_Namespace::DiskCacheConfig disk_cache_config{
175  (base_path / shared::kDefaultDiskCacheDirName).string(),
177  if (cache_config) {
178  disk_cache_config = *cache_config;
179  }
181 
184  g_calcite =
185  std::make_shared<Calcite>(-1, CALCITEPORT, db_path, 1024, 5000, true, udf_filename);
186  ExtensionFunctionsWhitelist::add(g_calcite->getExtensionFunctionWhitelist());
187  if (!udf_filename.empty()) {
188  ExtensionFunctionsWhitelist::addUdfs(g_calcite->getUserDefinedFunctionWhitelist());
189  }
190 
192  auto udtfs = ThriftSerializers::to_thrift(
194  std::vector<TUserDefinedFunction> udfs = {};
195  g_calcite->setRuntimeExtensionFunctions(udfs, udtfs, /*is_runtime=*/false);
196 
197  std::unique_ptr<CudaMgr_Namespace::CudaMgr> cuda_mgr;
198 #ifdef HAVE_CUDA
199  if (uses_gpus) {
200  cuda_mgr = std::make_unique<CudaMgr_Namespace::CudaMgr>(-1, 0);
201  }
202 #else
203  uses_gpus = false;
204 #endif
205  SystemParameters mapd_params;
206  mapd_params.gpu_buffer_mem_bytes = max_gpu_mem;
207  mapd_params.aggregator = !leaf_servers.empty();
208 
209  auto& sys_cat = Catalog_Namespace::SysCatalog::instance();
210 
211  g_base_path = base_path.string();
212 
213  if (!sys_cat.isInitialized()) {
214  auto data_mgr = std::make_shared<Data_Namespace::DataMgr>(data_dir.string(),
215  mapd_params,
216  std::move(cuda_mgr),
217  uses_gpus,
218  reserved_gpu_mem,
219  0,
220  disk_cache_config);
221  sys_cat.init(g_base_path,
222  data_mgr,
223  {},
224  g_calcite,
225  false,
226  mapd_params.aggregator,
227  string_servers);
228  }
229 
230  query_engine_ =
231  QueryEngine::createInstance(sys_cat.getDataMgr().getCudaMgr(), !uses_gpus);
232 
233  if (create_user) {
234  if (!sys_cat.getMetadataForUser(user_name, user)) {
235  sys_cat.createUser(
236  user_name,
238  passwd, /*is_super=*/false, /*default_db=*/"", /*can_login=*/true},
239  g_read_only);
240  }
241  }
242  CHECK(sys_cat.getMetadataForUser(user_name, user));
243  CHECK(bcrypt_checkpw(passwd.c_str(), user.passwd_hash.c_str()) == 0);
244 
245  if (create_db) {
246  if (!sys_cat.getMetadataForDB(db_name, db_metadata_)) {
247  sys_cat.createDatabase(db_name, user.userId);
248  }
249  }
250  CHECK(sys_cat.getMetadataForDB(db_name, db_metadata_));
251  CHECK(user.isSuper || (user.userId == db_metadata_.dbOwner));
252  auto cat = sys_cat.getCatalog(db_metadata_, create_db);
253  CHECK(cat);
254  session_info_ = std::make_unique<Catalog_Namespace::SessionInfo>(
255  cat, user, ExecutorDeviceType::GPU, "");
256 }
257 
258 void QueryRunner::resizeDispatchQueue(const size_t num_executors) {
259  dispatch_queue_ = std::make_unique<QueryDispatchQueue>(num_executors);
260 }
261 
262 QueryRunner::QueryRunner(std::unique_ptr<Catalog_Namespace::SessionInfo> session)
263  : session_info_(std::move(session))
264  , dispatch_queue_(std::make_unique<QueryDispatchQueue>(1)) {}
265 
266 std::shared_ptr<Catalog_Namespace::Catalog> QueryRunner::getCatalog() const {
268  return session_info_->get_catalog_ptr();
269 }
270 
271 std::shared_ptr<Calcite> QueryRunner::getCalcite() const {
272  // TODO: Embed Calcite shared_ptr ownership in QueryRunner
273  return g_calcite;
274 }
275 
276 bool QueryRunner::gpusPresent() const {
278  return session_info_->getCatalog().getDataMgr().gpusPresent();
279 }
280 
281 void QueryRunner::clearGpuMemory() const {
284 }
285 
286 void QueryRunner::clearCpuMemory() const {
289 }
290 
291 std::vector<MemoryInfo> QueryRunner::getMemoryInfo(
292  const Data_Namespace::MemoryLevel memory_level) const {
294  return session_info_->getCatalog().getDataMgr().getMemoryInfo(memory_level);
295 }
296 
297 BufferPoolStats QueryRunner::getBufferPoolStats(
298  const Data_Namespace::MemoryLevel memory_level,
299  const bool current_db_only) const {
300  // Only works single-node for now
302  const std::vector<MemoryInfo> memory_infos =
303  session_info_->getCatalog().getDataMgr().getMemoryInfo(memory_level);
304  if (memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
305  CHECK_EQ(memory_infos.size(), static_cast<size_t>(1));
306  }
307  std::set<std::vector<int32_t>> chunk_keys;
308  std::set<std::vector<int32_t>> table_keys;
309  std::set<std::vector<int32_t>> column_keys;
310  std::set<std::vector<int32_t>> fragment_keys;
311  size_t total_num_buffers{
312  0}; // can be greater than chunk keys set size due to table replication
313  size_t total_num_bytes{0};
314  for (auto& pool_memory_info : memory_infos) {
315  const std::vector<MemoryData>& memory_data = pool_memory_info.nodeMemoryData;
316  for (auto& memory_datum : memory_data) {
317  total_num_buffers++;
318  const auto& chunk_key = memory_datum.chunk_key;
319  if (memory_datum.memStatus == Buffer_Namespace::MemStatus::FREE ||
320  chunk_key.size() < 4) {
321  continue;
322  }
323  if (current_db_only) {
324  if (chunk_key[0] != db_metadata_.dbId) {
325  continue;
326  }
327  }
328  total_num_bytes += (memory_datum.numPages * pool_memory_info.pageSize);
329  table_keys.insert({chunk_key[0], chunk_key[1]});
330  column_keys.insert({chunk_key[0], chunk_key[1], chunk_key[2]});
331  fragment_keys.insert({chunk_key[0], chunk_key[1], chunk_key[3]});
332  chunk_keys.insert(chunk_key);
333  }
334  }
335  return {total_num_buffers,
336  total_num_bytes,
337  table_keys.size(),
338  column_keys.size(),
339  fragment_keys.size(),
340  chunk_keys.size()};
341 }
342 
343 RegisteredQueryHint QueryRunner::getParsedQueryHint(const std::string& query_str) {
346  auto query_state = create_query_state(session_info_, query_str);
347  auto& cat = session_info_->getCatalog();
349 
350  auto calcite_mgr = cat.getCalciteMgr();
351  const auto calciteQueryParsingOption =
352  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
353  const auto calciteOptimizationOption =
354  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
355  const auto query_ra = calcite_mgr
356  ->process(query_state->createQueryStateProxy(),
357  pg_shim(query_str),
358  calciteQueryParsingOption,
359  calciteOptimizationOption)
360  .plan_result;
361  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
362  auto query_hints =
363  ra_executor.getParsedQueryHint(ra_executor.getRootRelAlgNodeShPtr().get());
364  return query_hints ? *query_hints : RegisteredQueryHint::defaults();
365 }
366 
367 std::shared_ptr<const RelAlgNode> QueryRunner::getRootNodeFromParsedQuery(
368  const std::string& query_str) {
371  auto query_state = create_query_state(session_info_, query_str);
372  auto& cat = session_info_->getCatalog();
374 
375  auto calcite_mgr = cat.getCalciteMgr();
376  const auto calciteQueryParsingOption =
377  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
378  const auto calciteOptimizationOption =
379  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
380  const auto query_ra = calcite_mgr
381  ->process(query_state->createQueryStateProxy(),
382  pg_shim(query_str),
383  calciteQueryParsingOption,
384  calciteOptimizationOption)
385  .plan_result;
386  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
387  return ra_executor.getRootRelAlgNodeShPtr();
388 }
389 
391  std::unordered_map<size_t, std::unordered_map<unsigned, RegisteredQueryHint>>>
392 QueryRunner::getParsedQueryHints(const std::string& query_str) {
395  auto query_state = create_query_state(session_info_, query_str);
396  auto& cat = session_info_->getCatalog();
398  auto calcite_mgr = cat.getCalciteMgr();
399  const auto calciteQueryParsingOption =
400  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
401  const auto calciteOptimizationOption =
402  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
403  const auto query_ra = calcite_mgr
404  ->process(query_state->createQueryStateProxy(),
405  pg_shim(query_str),
406  calciteQueryParsingOption,
407  calciteOptimizationOption)
408  .plan_result;
409  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
410  return ra_executor.getParsedQueryHints();
411 }
412 
413 std::optional<RegisteredQueryHint> QueryRunner::getParsedGlobalQueryHints(
414  const std::string& query_str) {
417  auto query_state = create_query_state(session_info_, query_str);
418  auto& cat = session_info_->getCatalog();
420  auto calcite_mgr = cat.getCalciteMgr();
421  const auto calciteQueryParsingOption =
422  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
423  const auto calciteOptimizationOption =
424  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
425  const auto query_ra = calcite_mgr
426  ->process(query_state->createQueryStateProxy(),
427  pg_shim(query_str),
428  calciteQueryParsingOption,
429  calciteOptimizationOption)
430  .plan_result;
431  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
432  return ra_executor.getGlobalQueryHint();
433 }
434 
435 RaExecutionSequence QueryRunner::getRaExecutionSequence(const std::string& query_str) {
438  auto query_state = create_query_state(session_info_, query_str);
439  auto& cat = session_info_->getCatalog();
441  auto calcite_mgr = cat.getCalciteMgr();
442  const auto calciteQueryParsingOption =
443  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
444  const auto calciteOptimizationOption =
445  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
446  const auto query_ra = calcite_mgr
447  ->process(query_state->createQueryStateProxy(),
448  pg_shim(query_str),
449  calciteQueryParsingOption,
450  calciteOptimizationOption)
451  .plan_result;
452  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
453  return ra_executor.getRaExecutionSequence(ra_executor.getRootRelAlgNodeShPtr().get(),
454  executor.get());
455 }
456 
457 // used to validate calcite ddl statements
458 void QueryRunner::validateDDLStatement(const std::string& stmt_str_in) {
460 
461  std::string stmt_str = stmt_str_in;
462  // First remove special chars
463  boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
464  // Then remove spaces
465  boost::algorithm::trim_left(stmt_str);
466 
467  auto query_state = create_query_state(session_info_, stmt_str);
468  auto stdlog = STDLOG(query_state);
469 
470  auto& cat = session_info_->getCatalog();
471  auto calcite_mgr = cat.getCalciteMgr();
472  const auto calciteQueryParsingOption =
473  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
474  const auto calciteOptimizationOption =
475  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
476  calcite_mgr->process(query_state->createQueryStateProxy(),
477  pg_shim(stmt_str),
478  calciteQueryParsingOption,
479  calciteOptimizationOption);
480 }
481 
482 std::shared_ptr<RelAlgTranslator> QueryRunner::getRelAlgTranslator(
483  const std::string& query_str,
484  Executor* executor) {
487  auto query_state = create_query_state(session_info_, query_str);
488  auto& cat = session_info_->getCatalog();
489  auto calcite_mgr = cat.getCalciteMgr();
490  const auto calciteQueryParsingOption =
491  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
492  const auto calciteOptimizationOption =
493  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
494  const auto query_ra = calcite_mgr
495  ->process(query_state->createQueryStateProxy(),
496  pg_shim(query_str),
497  calciteQueryParsingOption,
498  calciteOptimizationOption)
499  .plan_result;
500  auto ra_executor = RelAlgExecutor(executor, query_ra);
501  auto root_node_shared_ptr = ra_executor.getRootRelAlgNodeShPtr();
502  return ra_executor.getRelAlgTranslator(root_node_shared_ptr.get());
503 }
504 
505 QueryPlanDagInfo QueryRunner::getQueryInfoForDataRecyclerTest(
506  const std::string& query_str) {
509  auto query_state = create_query_state(session_info_, query_str);
510  auto& cat = session_info_->getCatalog();
512  auto calcite_mgr = cat.getCalciteMgr();
513  const auto calciteQueryParsingOption =
514  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
515  const auto calciteOptimizationOption =
516  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
517  const auto query_ra = calcite_mgr
518  ->process(query_state->createQueryStateProxy(),
519  pg_shim(query_str),
520  calciteQueryParsingOption,
521  calciteOptimizationOption)
522  .plan_result;
523  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
524  // note that we assume the test for data recycler that needs to have join_info
525  // does not contain any ORDER BY clause; this is necessary to create work_unit
526  // without actually performing the query
527  auto root_node_shared_ptr = ra_executor.getRootRelAlgNodeShPtr();
528  auto join_info = ra_executor.getJoinInfo(root_node_shared_ptr.get());
529  auto relAlgTranslator = ra_executor.getRelAlgTranslator(root_node_shared_ptr.get());
530  return {root_node_shared_ptr, join_info.first, join_info.second, relAlgTranslator};
531 }
532 
533 std::unique_ptr<Parser::Stmt> QueryRunner::createStatement(
534  const std::string& stmt_str_in) {
537 
538  std::string stmt_str = stmt_str_in;
539  // First remove special chars
540  boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
541  // Then remove spaces
542  boost::algorithm::trim_left(stmt_str);
543 
544  ParserWrapper pw{stmt_str};
545 
546  auto query_state = create_query_state(session_info_, stmt_str);
547  auto stdlog = STDLOG(query_state);
548 
549  if (pw.is_ddl) {
550  const auto& cat = session_info_->getCatalog();
551  auto calcite_mgr = cat.getCalciteMgr();
552  const auto calciteQueryParsingOption =
553  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
554  const auto calciteOptimizationOption =
555  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
556  const auto query_json = calcite_mgr
557  ->process(query_state->createQueryStateProxy(),
558  pg_shim(stmt_str),
559  calciteQueryParsingOption,
560  calciteOptimizationOption)
561  .plan_result;
562  return Parser::create_stmt_for_json(query_json);
563  }
564 
565  // simply fail here as non-Calcite parsing is about to be removed
566  UNREACHABLE();
567  return nullptr;
568 }
569 
570 void QueryRunner::runDDLStatement(const std::string& stmt_str_in) {
573 
574  std::string stmt_str = stmt_str_in;
575  // First remove special chars
576  boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
577  // Then remove spaces
578  boost::algorithm::trim_left(stmt_str);
579 
580  ParserWrapper pw{stmt_str};
581 
582  auto query_state = create_query_state(session_info_, stmt_str);
583  auto stdlog = STDLOG(query_state);
584 
585  if (pw.is_ddl || pw.getDMLType() == ParserWrapper::DMLType::Insert) {
586  auto& cat = session_info_->getCatalog();
587  auto calcite_mgr = cat.getCalciteMgr();
588  const auto calciteQueryParsingOption =
589  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
590  const auto calciteOptimizationOption =
591  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
592  const auto query_ra = calcite_mgr
593  ->process(query_state->createQueryStateProxy(),
594  pg_shim(stmt_str),
595  calciteQueryParsingOption,
596  calciteOptimizationOption)
597  .plan_result;
598  if (pw.getDMLType() == ParserWrapper::DMLType::Insert) {
599  rapidjson::Document ddl_query;
600  ddl_query.Parse(query_ra);
601  CHECK(ddl_query.HasMember("payload"));
602  CHECK(ddl_query["payload"].IsObject());
603  auto stmt = Parser::InsertValuesStmt(ddl_query["payload"].GetObject());
604  stmt.execute(*session_info_, false /* read only */);
605  return;
606  }
608  executor.execute(false /* read only */);
609  return;
610  }
611 }
612 
613 std::shared_ptr<ResultSet> QueryRunner::runSQL(const std::string& query_str,
615  ExecutionOptions eo) {
618 
619  ParserWrapper pw{query_str};
620  if (pw.getDMLType() == ParserWrapper::DMLType::Insert) {
621  runDDLStatement(query_str);
622  return nullptr;
623  }
624  const auto execution_result = runSelectQuery(query_str, std::move(co), std::move(eo));
625  VLOG(1) << session_info_->getCatalog().getDataMgr().getSystemMemoryUsage();
626  return execution_result->getRows();
627 }
628 
629 std::shared_ptr<ResultSet> QueryRunner::runSQL(const std::string& query_str,
630  const ExecutorDeviceType device_type,
631  const bool hoist_literals,
632  const bool allow_loop_joins) {
633  auto co = CompilationOptions::defaults(device_type);
634  co.hoist_literals = hoist_literals;
635  return runSQL(
636  query_str, std::move(co), defaultExecutionOptionsForRunSQL(allow_loop_joins));
637 }
638 
639 ExecutionOptions QueryRunner::defaultExecutionOptionsForRunSQL(bool allow_loop_joins,
640  bool just_explain) {
641  return {g_enable_columnar_output,
642  false,
643  true,
644  just_explain,
645  allow_loop_joins,
646  false,
647  false,
648  false,
649  false,
650  10000,
651  false,
652  false,
654  false,
655  1000,
656  false};
657 }
658 
659 std::shared_ptr<Executor> QueryRunner::getExecutor() const {
662  auto query_state = create_query_state(session_info_, "");
663  auto stdlog = STDLOG(query_state);
665  return executor;
666 }
667 
668 std::shared_ptr<ResultSet> QueryRunner::runSQLWithAllowingInterrupt(
669  const std::string& query_str,
670  const std::string& session_id,
671  const ExecutorDeviceType device_type,
672  const double running_query_check_freq,
673  const unsigned pending_query_check_freq) {
676  auto current_user = session_info_->get_currentUser();
677  auto session_info = std::make_shared<Catalog_Namespace::SessionInfo>(
678  session_info_->get_catalog_ptr(), current_user, device_type, session_id);
679  auto query_state = create_query_state(session_info, query_str);
680  auto stdlog = STDLOG(query_state);
681  auto& cat = query_state->getConstSessionInfo()->getCatalog();
682  std::string query_ra{""};
683 
684  std::shared_ptr<ExecutionResult> result;
685  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
686  [&cat,
687  &query_ra,
688  &device_type,
689  &query_state,
690  &result,
691  &running_query_check_freq,
692  &pending_query_check_freq,
693  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
694  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
695  auto executor = Executor::getExecutor(worker_id);
697 
699  false,
700  true,
701  false,
702  true,
703  false,
704  false,
705  false,
706  false,
707  10000,
708  false,
709  false,
711  true,
712  running_query_check_freq,
713  pending_query_check_freq,
714  false};
715  {
716  // async query initiation for interrupt test
717  // incurs data race warning in TSAN since
718  // calcite_mgr is shared across multiple query threads
719  // so here we lock the manager during query parsing
720  std::lock_guard<std::mutex> calcite_lock_guard(calcite_lock);
721  auto calcite_mgr = cat.getCalciteMgr();
722  const auto calciteQueryParsingOption =
723  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
724  const auto calciteOptimizationOption =
725  calcite_mgr->getCalciteOptimizationOption(
726  false, g_enable_watchdog, {}, false);
727  query_ra = calcite_mgr
728  ->process(query_state->createQueryStateProxy(),
729  pg_shim(query_state->getQueryStr()),
730  calciteQueryParsingOption,
731  calciteOptimizationOption)
732  .plan_result;
733  }
734  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
735  result = std::make_shared<ExecutionResult>(
736  ra_executor.executeRelAlgQuery(co, eo, false, nullptr));
737  });
739  executor->enrollQuerySession(session_id,
740  query_str,
741  query_state->getQuerySubmittedTime(),
743  QuerySessionStatus::QueryStatus::PENDING_QUEUE);
745  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
746  auto result_future = query_launch_task->get_future();
747  result_future.get();
748  CHECK(result);
749  return result->getRows();
750 }
751 
752 std::vector<std::shared_ptr<ResultSet>> QueryRunner::runMultipleStatements(
753  const std::string& sql,
754  const ExecutorDeviceType dt) {
755  std::vector<std::shared_ptr<ResultSet>> results;
756  // TODO: Need to properly handle escaped semicolons instead of doing a naive split().
757  auto fields = split(sql, ";");
758  for (const auto& field : fields) {
759  auto text = strip(field) + ";";
760  if (text == ";") {
761  continue;
762  }
763 
764  ParserWrapper pw{text};
765  if (pw.is_ddl || pw.getDMLType() == ParserWrapper::DMLType::Insert) {
766  runDDLStatement(text);
767  results.push_back(nullptr);
768  } else {
769  // is not DDL, then assume it's DML and try to execute
770  results.push_back(runSQL(text, dt, true, true));
771  }
772  }
773  return results;
774 }
775 
776 void QueryRunner::runImport(Parser::CopyTableStmt* import_stmt) {
777  CHECK(import_stmt);
778  import_stmt->execute(*session_info_, false /* read only */);
779 }
780 
781 std::unique_ptr<import_export::Loader> QueryRunner::getLoader(
782  const TableDescriptor* td) const {
783  auto cat = getCatalog();
784  return std::make_unique<import_export::Loader>(*cat, td);
785 }
786 
787 namespace {
788 
789 std::shared_ptr<ExecutionResult> run_select_query_with_filter_push_down(
790  QueryStateProxy query_state_proxy,
791  const ExecutorDeviceType device_type,
792  const bool hoist_literals,
793  const bool allow_loop_joins,
794  const bool just_explain,
795  const ExecutorExplainType explain_type,
796  const bool with_filter_push_down) {
797  auto& cat = query_state_proxy->getConstSessionInfo()->getCatalog();
800  co.explain_type = explain_type;
801 
804  eo.just_explain = just_explain;
805  eo.allow_loop_joins = allow_loop_joins;
806  eo.find_push_down_candidates = with_filter_push_down;
808 
809  auto calcite_mgr = cat.getCalciteMgr();
810  const auto calciteQueryParsingOption =
811  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
812  auto calciteOptimizationOption =
813  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
814  const auto query_ra = calcite_mgr
815  ->process(query_state_proxy,
816  pg_shim(query_state_proxy->getQueryStr()),
817  calciteQueryParsingOption,
818  calciteOptimizationOption)
819  .plan_result;
820  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
821  auto result = std::make_shared<ExecutionResult>(
822  ra_executor.executeRelAlgQuery(co, eo, false, nullptr));
823  const auto& filter_push_down_requests = result->getPushedDownFilterInfo();
824  if (!filter_push_down_requests.empty()) {
825  std::vector<TFilterPushDownInfo> filter_push_down_info;
826  for (const auto& req : filter_push_down_requests) {
827  TFilterPushDownInfo filter_push_down_info_for_request;
828  filter_push_down_info_for_request.input_prev = req.input_prev;
829  filter_push_down_info_for_request.input_start = req.input_start;
830  filter_push_down_info_for_request.input_next = req.input_next;
831  filter_push_down_info.push_back(filter_push_down_info_for_request);
832  }
833  calciteOptimizationOption.filter_push_down_info = filter_push_down_info;
834  const auto new_query_ra = calcite_mgr
835  ->process(query_state_proxy,
836  pg_shim(query_state_proxy->getQueryStr()),
837  calciteQueryParsingOption,
838  calciteOptimizationOption)
839  .plan_result;
840  auto eo_modified = eo;
841  eo_modified.find_push_down_candidates = false;
842  eo_modified.just_calcite_explain = false;
843  auto new_ra_executor = RelAlgExecutor(executor.get(), new_query_ra);
844  return std::make_shared<ExecutionResult>(
845  new_ra_executor.executeRelAlgQuery(co, eo_modified, false, nullptr));
846  } else {
847  return result;
848  }
849 }
850 
851 } // namespace
852 
853 std::shared_ptr<ResultSet> QueryRunner::getCalcitePlan(const std::string& query_str,
854  bool enable_watchdog,
855  bool as_json_str) const {
858  const auto& cat = session_info_->getCatalog();
859  auto query_state = create_query_state(session_info_, query_str);
860  auto stdlog = STDLOG(query_state);
861 
862  std::shared_ptr<ResultSet> result;
863  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
864  [&cat,
865  &query_str,
866  &enable_watchdog,
867  &as_json_str,
868  &query_state,
869  &result,
870  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
871  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
872  auto executor = Executor::getExecutor(worker_id);
873  auto calcite_mgr = cat.getCalciteMgr();
874  const auto calciteQueryParsingOption =
875  calcite_mgr->getCalciteQueryParsingOption(true, as_json_str, false);
876  const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
877  g_enable_calcite_view_optimize, enable_watchdog, {}, false);
878  const auto query_ra = calcite_mgr
879  ->process(query_state->createQueryStateProxy(),
880  pg_shim(query_str),
881  calciteQueryParsingOption,
882  calciteOptimizationOption)
883  .plan_result;
884  result = std::make_shared<ResultSet>(query_ra);
885  return result;
886  });
888  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
889  auto result_future = query_launch_task->get_future();
890  result_future.get();
891  CHECK(result);
892  return result;
893 }
894 
895 std::shared_ptr<ExecutionResult> QueryRunner::runSelectQuery(const std::string& query_str,
897  ExecutionOptions eo) {
900  auto query_state = create_query_state(session_info_, query_str);
901  auto stdlog = STDLOG(query_state);
903  return run_select_query_with_filter_push_down(query_state->createQueryStateProxy(),
904  co.device_type,
905  co.hoist_literals,
906  eo.allow_loop_joins,
907  eo.just_explain,
910  }
911 
912  auto& cat = session_info_->getCatalog();
913 
914  std::shared_ptr<ExecutionResult> result;
915  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
916  [&cat,
917  &query_str,
918  &co,
919  explain_type = this->explain_type_,
920  &eo,
921  &query_state,
922  &result,
923  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
924  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
925  auto executor = Executor::getExecutor(worker_id);
926  // TODO The next line should be deleted since it overwrites co, but then
927  // NycTaxiTest.RunSelectsEncodingDictWhereGreater fails due to co not getting
928  // reset to its default values.
929  co = CompilationOptions::defaults(co.device_type);
930  co.explain_type = explain_type;
931  auto calcite_mgr = cat.getCalciteMgr();
932  const auto calciteQueryParsingOption =
933  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
934  const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
936  const auto query_ra = calcite_mgr
937  ->process(query_state->createQueryStateProxy(),
938  pg_shim(query_str),
939  calciteQueryParsingOption,
940  calciteOptimizationOption)
941  .plan_result;
942  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
943  result = std::make_shared<ExecutionResult>(
944  ra_executor.executeRelAlgQuery(co, eo, false, nullptr));
945  });
947  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
948  auto result_future = query_launch_task->get_future();
949  result_future.get();
950  CHECK(result);
951  return result;
952 }
953 
954 std::shared_ptr<ExecutionResult> QueryRunner::runSelectQuery(
955  const std::string& query_str,
956  const ExecutorDeviceType device_type,
957  const bool hoist_literals,
958  const bool allow_loop_joins,
959  const bool just_explain) {
960  auto co = CompilationOptions::defaults(device_type);
961  co.hoist_literals = hoist_literals;
962  return runSelectQuery(query_str,
963  std::move(co),
964  defaultExecutionOptionsForRunSQL(allow_loop_joins, just_explain));
965 }
966 
967 ExtractedQueryPlanDag QueryRunner::extractQueryPlanDag(const std::string& query_str) {
968  auto query_dag_info = getQueryInfoForDataRecyclerTest(query_str);
970  auto extracted_dag_info = QueryPlanDagExtractor::extractQueryPlanDag(
971  query_dag_info.root_node.get(), executor);
972  return extracted_dag_info;
973 }
974 
975 std::unique_ptr<RelAlgDag> QueryRunner::getRelAlgDag(const std::string& query_str) {
978  auto query_state = create_query_state(session_info_, query_str);
979  auto stdlog = STDLOG(query_state);
980  auto& cat = session_info_->getCatalog();
981 
982  std::unique_ptr<RelAlgDag> rel_alg_dag;
983  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
984  [&cat,
985  &query_str,
986  &query_state,
987  &rel_alg_dag,
988  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
989  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
990  auto executor = Executor::getExecutor(worker_id);
991  auto eo = ExecutionOptions::defaults();
992  auto calcite_mgr = cat.getCalciteMgr();
993  const auto calciteQueryParsingOption =
994  calcite_mgr->getCalciteQueryParsingOption(true, false, true);
995  const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
997  const auto query_ra = calcite_mgr
998  ->process(query_state->createQueryStateProxy(),
999  pg_shim(query_str),
1000  calciteQueryParsingOption,
1001  calciteOptimizationOption)
1002  .plan_result;
1003  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
1004  rel_alg_dag = ra_executor.getOwnedRelAlgDag();
1005  });
1007  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
1008  auto result_future = query_launch_task->get_future();
1009  result_future.get();
1010  CHECK(rel_alg_dag);
1011  return rel_alg_dag;
1012 }
1013 
1014 // this function exists to test data recycler
1015 // specifically, it is tricky to get a hashtable cache key when we only know
1016 // a target query sql in test code
1017 // so this function utilizes an incorrect way to manipulate our hashtable recycler
1018 // but provides the cached hashtable for performing the test
1019 // a set "visited" contains cached hashtable keys that we have retrieved so far
1020 // based on that, this function iterates hashtable cache and return a cached one
1021 // when its hashtable cache key has not been visited yet
1022 // for instance, if we call this funtion with an empty "visited" key, we return
1023 // the first hashtable that its iterator visits
1024 std::tuple<QueryPlanHash,
1025  std::shared_ptr<HashTable>,
1026  std::optional<HashtableCacheMetaInfo>>
1027 QueryRunner::getCachedHashtableWithoutCacheKey(std::set<size_t>& visited,
1028  CacheItemType hash_table_type,
1029  DeviceIdentifier device_identifier) {
1030  HashtableRecycler* hash_table_cache{nullptr};
1031  switch (hash_table_type) {
1033  hash_table_cache = PerfectJoinHashTable::getHashTableCache();
1034  break;
1035  }
1037  hash_table_cache = BaselineJoinHashTable::getHashTableCache();
1038  break;
1039  }
1041  hash_table_cache = OverlapsJoinHashTable::getHashTableCache();
1042  break;
1043  }
1044  default: {
1045  UNREACHABLE();
1046  break;
1047  }
1048  }
1049  CHECK(hash_table_cache);
1050  return hash_table_cache->getCachedHashtableWithoutCacheKey(
1051  visited, hash_table_type, device_identifier);
1052 }
1053 
1054 std::shared_ptr<CacheItemMetric> QueryRunner::getCacheItemMetric(
1055  QueryPlanHash cache_key,
1056  CacheItemType hash_table_type,
1057  DeviceIdentifier device_identifier) {
1058  HashtableRecycler* hash_table_cache{nullptr};
1059  switch (hash_table_type) {
1061  hash_table_cache = PerfectJoinHashTable::getHashTableCache();
1062  break;
1063  }
1065  hash_table_cache = BaselineJoinHashTable::getHashTableCache();
1066  break;
1067  }
1069  hash_table_cache = OverlapsJoinHashTable::getHashTableCache();
1070  break;
1071  }
1072  default: {
1073  UNREACHABLE();
1074  break;
1075  }
1076  }
1077  CHECK(hash_table_cache);
1078  return hash_table_cache->getCachedItemMetric(
1079  hash_table_type, device_identifier, cache_key);
1080 }
1081 
1082 size_t QueryRunner::getNumberOfCachedItem(CacheItemStatus item_status,
1083  CacheItemType hash_table_type,
1084  bool with_overlaps_tuning_param) const {
1085  auto get_num_cached_auto_tuner_param = [&item_status]() {
1086  auto auto_tuner_cache = OverlapsJoinHashTable::getOverlapsTuningParamCache();
1087  CHECK(auto_tuner_cache);
1088  switch (item_status) {
1089  case CacheItemStatus::ALL: {
1090  return auto_tuner_cache->getCurrentNumCachedItems(
1093  }
1095  return auto_tuner_cache->getCurrentNumCleanCachedItems(
1098  }
1100  return auto_tuner_cache->getCurrentNumDirtyCachedItems(
1103  }
1104  default: {
1105  UNREACHABLE();
1106  return static_cast<size_t>(0);
1107  }
1108  }
1109  };
1110 
1111  auto get_num_cached_hashtable =
1112  [&item_status,
1113  &hash_table_type,
1114  &with_overlaps_tuning_param,
1115  &get_num_cached_auto_tuner_param](HashtableRecycler* hash_table_cache) {
1116  switch (item_status) {
1117  case CacheItemStatus::ALL: {
1118  if (with_overlaps_tuning_param) {
1119  // we assume additional consideration of turing param cache is only valid
1120  // for overlaps join hashtable
1121  CHECK_EQ(hash_table_type, CacheItemType::OVERLAPS_HT);
1122  return hash_table_cache->getCurrentNumCachedItems(
1123  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER) +
1124  get_num_cached_auto_tuner_param();
1125  }
1126  return hash_table_cache->getCurrentNumCachedItems(
1127  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER);
1128  }
1130  if (with_overlaps_tuning_param) {
1131  CHECK_EQ(hash_table_type, CacheItemType::OVERLAPS_HT);
1132  return hash_table_cache->getCurrentNumCleanCachedItems(
1133  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER) +
1134  get_num_cached_auto_tuner_param();
1135  }
1136  return hash_table_cache->getCurrentNumCleanCachedItems(
1137  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER);
1138  }
1140  if (with_overlaps_tuning_param) {
1141  CHECK_EQ(hash_table_type, CacheItemType::OVERLAPS_HT);
1142  return hash_table_cache->getCurrentNumDirtyCachedItems(
1143  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER) +
1144  get_num_cached_auto_tuner_param();
1145  }
1146  return hash_table_cache->getCurrentNumDirtyCachedItems(
1147  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER);
1148  }
1149  default: {
1150  UNREACHABLE();
1151  return static_cast<size_t>(0);
1152  }
1153  }
1154  };
1155 
1156  switch (hash_table_type) {
1158  auto hash_table_cache = PerfectJoinHashTable::getHashTableCache();
1159  CHECK(hash_table_cache);
1160  return get_num_cached_hashtable(hash_table_cache);
1161  }
1163  auto hash_table_cache = BaselineJoinHashTable::getHashTableCache();
1164  CHECK(hash_table_cache);
1165  return get_num_cached_hashtable(hash_table_cache);
1166  }
1168  auto hash_table_cache = OverlapsJoinHashTable::getHashTableCache();
1169  CHECK(hash_table_cache);
1170  return get_num_cached_hashtable(hash_table_cache);
1171  }
1173  return get_num_cached_auto_tuner_param();
1174  }
1175  default: {
1176  UNREACHABLE();
1177  return 0;
1178  }
1179  }
1180  return 0;
1181 }
1182 
1183 void QueryRunner::reset() {
1184  qr_instance_->query_engine_.reset();
1185  qr_instance_.reset(nullptr);
1187 }
1188 
1189 ImportDriver::ImportDriver(std::shared_ptr<Catalog_Namespace::Catalog> cat,
1190  const Catalog_Namespace::UserMetadata& user,
1191  const ExecutorDeviceType dt,
1192  const std::string session_id)
1193  : QueryRunner(
1194  std::make_unique<Catalog_Namespace::SessionInfo>(cat, user, dt, session_id)) {}
1195 
1196 void ImportDriver::importGeoTable(const std::string& file_path,
1197  const std::string& table_name,
1198  const bool compression,
1199  const bool create_table,
1200  const bool explode_collections) {
1201  using namespace import_export;
1202 
1203  static constexpr bool kIsGeoRaster{false};
1204 
1206 
1207  CopyParams copy_params;
1209  if (compression) {
1210  copy_params.geo_coords_encoding = EncodingType::kENCODING_GEOINT;
1211  copy_params.geo_coords_comp_param = 32;
1212  } else {
1213  copy_params.geo_coords_encoding = EncodingType::kENCODING_NONE;
1214  copy_params.geo_coords_comp_param = 0;
1215  }
1216  copy_params.geo_assign_render_groups = false;
1217  copy_params.geo_explode_collections = explode_collections;
1218 
1219  std::map<std::string, std::string> colname_to_src;
1220  auto& cat = session_info_->getCatalog();
1221  auto cds = Importer::gdalToColumnDescriptors(
1222  file_path, kIsGeoRaster, Geospatial::kGeoColumnName, copy_params);
1223 
1224  for (auto& cd : cds) {
1225  const auto col_name_sanitized = ImportHelpers::sanitize_name(cd.columnName);
1226  const auto ret =
1227  colname_to_src.insert(std::make_pair(col_name_sanitized, cd.columnName));
1228  CHECK(ret.second);
1229  cd.columnName = col_name_sanitized;
1230  }
1231 
1232  if (create_table) {
1233  const auto td = cat.getMetadataForTable(table_name);
1234  if (td != nullptr) {
1235  throw std::runtime_error(
1236  "Error: Table " + table_name +
1237  " already exists. Possible failure to correctly re-create " +
1238  shared::kDataDirectoryName + " directory.");
1239  }
1240  if (table_name != ImportHelpers::sanitize_name(table_name)) {
1241  throw std::runtime_error("Invalid characters in table name: " + table_name);
1242  }
1243 
1244  std::string stmt{"CREATE TABLE " + table_name};
1245  std::vector<std::string> col_stmts;
1246 
1247  for (auto& cd : cds) {
1248  if (cd.columnType.get_type() == SQLTypes::kINTERVAL_DAY_TIME ||
1249  cd.columnType.get_type() == SQLTypes::kINTERVAL_YEAR_MONTH) {
1250  throw std::runtime_error(
1251  "Unsupported type: INTERVAL_DAY_TIME or INTERVAL_YEAR_MONTH for col " +
1252  cd.columnName + " (table: " + table_name + ")");
1253  }
1254 
1255  if (cd.columnType.get_type() == SQLTypes::kDECIMAL) {
1256  if (cd.columnType.get_precision() == 0 && cd.columnType.get_scale() == 0) {
1257  cd.columnType.set_precision(14);
1258  cd.columnType.set_scale(7);
1259  }
1260  }
1261 
1262  std::string col_stmt;
1263  col_stmt.append(cd.columnName + " " + cd.columnType.get_type_name() + " ");
1264 
1265  if (cd.columnType.get_compression() != EncodingType::kENCODING_NONE) {
1266  col_stmt.append("ENCODING " + cd.columnType.get_compression_name() + " ");
1267  } else {
1268  if (cd.columnType.is_string()) {
1269  col_stmt.append("ENCODING NONE");
1270  } else if (cd.columnType.is_geometry()) {
1271  if (cd.columnType.get_output_srid() == 4326) {
1272  col_stmt.append("ENCODING NONE");
1273  }
1274  }
1275  }
1276  col_stmts.push_back(col_stmt);
1277  }
1278 
1279  stmt.append(" (" + boost::algorithm::join(col_stmts, ",") + ");");
1280  runDDLStatement(stmt);
1281 
1282  LOG(INFO) << "Created table: " << table_name;
1283  } else {
1284  LOG(INFO) << "Not creating table: " << table_name;
1285  }
1286 
1287  const auto td = cat.getMetadataForTable(table_name);
1288  if (td == nullptr) {
1289  throw std::runtime_error("Error: Failed to create table " + table_name);
1290  }
1291 
1292  import_export::Importer importer(cat, td, file_path, copy_params);
1293  auto ms = measure<>::execution(
1294  [&]() { importer.importGDAL(colname_to_src, session_info_.get(), kIsGeoRaster); });
1295  LOG(INFO) << "Import Time for " << table_name << ": " << (double)ms / 1000.0 << " s";
1296 }
1297 
1298 } // namespace QueryRunner
bool g_enable_calcite_view_optimize
Definition: QueryRunner.cpp:56
Classes used to wrap parser calls for calcite redirection.
static void addUdfs(const std::string &json_func_sigs)
#define CHECK_EQ(x, y)
Definition: Logger.h:301
ImportStatus importGDAL(const std::map< std::string, std::string > &colname_to_src, const Catalog_Namespace::SessionInfo *session_info, const bool is_raster)
Definition: Importer.cpp:5326
#define CALCITEPORT
Definition: QueryRunner.cpp:48
size_t DeviceIdentifier
Definition: DataRecycler.h:129
const std::string kDataDirectoryName
static std::vector< TableFunction > get_table_funcs()
static ExtractedQueryPlanDag extractQueryPlanDag(const RelAlgNode *top_node, Executor *executor)
std::string cat(Ts &&...args)
std::unique_ptr< QueryDispatchQueue > dispatch_queue_
Definition: QueryRunner.h:331
static TimeT::rep execution(F func, Args &&...args)
Definition: sample.cpp:29
std::string const & getQueryStr() const
Definition: QueryState.h:159
ExecutorDeviceType
static void initialize(const std::string &data_dir, const std::string &allowed_import_paths, const std::string &allowed_export_paths)
Definition: DdlUtils.cpp:841
const std::string kDefaultDiskCacheDirName
std::string strip(std::string_view str)
trim any whitespace from the left and right ends of a string
ImportDriver(std::shared_ptr< Catalog_Namespace::Catalog > cat, const Catalog_Namespace::UserMetadata &user, const ExecutorDeviceType dt=ExecutorDeviceType::GPU, const std::string session_id="")
#define LOG(tag)
Definition: Logger.h:285
ExecutorExplainType explain_type_
Definition: QueryRunner.h:327
std::string join(T const &container, std::string const &delim)
static void add(const std::string &json_func_sigs)
#define UNREACHABLE()
Definition: Logger.h:337
static HashtableRecycler * getHashTableCache()
std::mutex calcite_lock
Definition: QueryRunner.cpp:57
std::optional< std::unordered_map< size_t, std::unordered_map< unsigned, RegisteredQueryHint > > > getParsedQueryHints()
std::optional< RegisteredQueryHint > getParsedQueryHint(const RelAlgNode *node)
void set_once_fatal_func(FatalFunc fatal_func)
Definition: Logger.cpp:390
Catalog_Namespace::DBMetadata db_metadata_
Definition: QueryRunner.h:329
static ExecutionOptions defaultExecutionOptionsForRunSQL(bool allow_loop_joins=true, bool just_explain=false)
virtual std::shared_ptr< ResultSet > runSQL(const std::string &query_str, CompilationOptions co, ExecutionOptions eo)
const std::string kGeoColumnName
Definition: ColumnNames.h:23
std::vector< std::string > split(std::string_view str, std::string_view delim, std::optional< size_t > maxsplit)
split apart a string into a vector of substrings
#define LOG_IF(severity, condition)
Definition: Logger.h:383
static void clearMemory(const Data_Namespace::MemoryLevel memory_level)
Definition: Execute.cpp:497
static void addShutdownCallback(std::function< void()> shutdown_callback)
std::shared_ptr< const RelAlgNode > getRootRelAlgNodeShPtr() const
static std::shared_ptr< Executor > getExecutor(const ExecutorId id, const std::string &debug_dir="", const std::string &debug_file="", const SystemParameters &system_parameters=SystemParameters())
Definition: Execute.cpp:475
std::shared_ptr< QueryEngine > query_engine_
Definition: QueryRunner.h:332
This file contains the class specification and related data structures for Catalog.
RaExecutionSequence getRaExecutionSequence(const RelAlgNode *root_node, Executor *executor)
const rapidjson::Value & field(const rapidjson::Value &obj, const char field[]) noexcept
Definition: JsonAccessors.h:31
bool g_enable_columnar_output
Definition: Execute.cpp:99
Supported runtime functions management and retrieval.
static SysCatalog & instance()
Definition: SysCatalog.h:343
void execute(const Catalog_Namespace::SessionInfo &session, bool read_only_mode) override
Classes representing a parse tree.
CacheItemType
Definition: DataRecycler.h:38
const std::string kDefaultDbName
std::string g_base_path
Definition: SysCatalog.cpp:62
void init(LogOptions const &log_opts)
Definition: Logger.cpp:360
std::unique_ptr< Parser::Stmt > create_stmt_for_json(const std::string &query_json)
static HashtableRecycler * getHashTableCache()
static std::shared_ptr< QueryEngine > createInstance(CudaMgr_Namespace::CudaMgr *cuda_mgr, bool cpu_only)
Definition: QueryEngine.h:89
A container for relational algebra descriptors defining the execution order for a relational algebra ...
ExecutorExplainType explain_type
bool g_enable_watchdog
virtual void runDDLStatement(const std::string &)
static std::unique_ptr< QueryRunner > qr_instance_
Definition: QueryRunner.h:325
double g_gpu_mem_limit_percent
Definition: QueryRunner.cpp:53
import_export::SourceType source_type
Definition: CopyParams.h:57
static OverlapsTuningParamRecycler * getOverlapsTuningParamCache()
bool g_serialize_temp_tables
Definition: Catalog.cpp:106
ExecutorDeviceType device_type
std::optional< RegisteredQueryHint > getGlobalQueryHint()
void importGeoTable(const std::string &file_path, const std::string &table_name, const bool compression, const bool create_table, const bool explode_collections)
const std::string kRootUsername
static RegisteredQueryHint defaults()
Definition: QueryHint.h:329
TExtArgumentType::type to_thrift(const ExtArgumentType &t)
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)
ExecutionResult execute(bool read_only_mode)
bool g_read_only
Definition: File.cpp:40
std::string sanitize_name(const std::string &name, const bool underscore=false)
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryRunner.h:330
size_t QueryPlanHash
virtual std::shared_ptr< ExecutionResult > runSelectQuery(const std::string &query_str, CompilationOptions co, ExecutionOptions eo)
std::shared_ptr< Calcite > g_calcite
Definition: QueryRunner.cpp:62
const std::string kCatalogDirectoryName
static std::shared_ptr< query_state::QueryState > create_query_state(Ts &&...args)
Definition: QueryRunner.h:303
static CompilationOptions defaults(const ExecutorDeviceType device_type=ExecutorDeviceType::GPU)
bool g_enable_filter_push_down
Definition: Execute.cpp:95
QueryPlanDagInfo getQueryInfoForDataRecyclerTest(const std::string &)
#define CHECK(condition)
Definition: Logger.h:291
static HashtableRecycler * getHashTableCache()
double gpu_input_mem_limit_percent
Serializers for query engine types to/from thrift.
std::shared_ptr< Catalog_Namespace::Catalog > getCatalog() const
size_t g_leaf_count
Definition: ParserNode.cpp:77
std::unique_ptr< RelAlgDag > getOwnedRelAlgDag()
static constexpr DeviceIdentifier CPU_DEVICE_IDENTIFIER
Definition: DataRecycler.h:136
static ExecutionOptions defaults()
ExecutorExplainType
std::shared_ptr< Catalog_Namespace::SessionInfo const > getConstSessionInfo() const
Definition: QueryState.cpp:84
std::string pg_shim(const std::string &query)
ThreadLocalIds thread_local_ids()
Definition: Logger.cpp:874
#define STDLOG(...)
Definition: QueryState.h:234
#define VLOG(n)
Definition: Logger.h:387
std::atomic< bool > isSuper
Definition: SysCatalog.h:107
static const ExecutorId UNITARY_EXECUTOR_ID
Definition: Execute.h:373