OmniSciDB  72c90bc290
 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 #ifdef HAVE_RUNTIME_LIBS
38 #endif
39 #include "Shared/StringTransform.h"
40 #include "Shared/SysDefinitions.h"
42 #include "Shared/import_helpers.h"
44 #include "gen-cpp/CalciteServer.h"
45 #include "include/bcrypt.h"
46 
47 #include <boost/filesystem/operations.hpp>
48 #include <csignal>
49 #include <random>
50 
51 #define CALCITEPORT 3279
52 
53 extern size_t g_leaf_count;
54 extern bool g_enable_filter_push_down;
55 
57 
58 extern bool g_serialize_temp_tables;
60 std::mutex calcite_lock;
61 
62 using namespace Catalog_Namespace;
63 namespace {
64 
65 std::shared_ptr<Calcite> g_calcite = nullptr;
66 
67 void calcite_shutdown_handler() noexcept {
68  if (g_calcite) {
69  g_calcite->close_calcite_server();
70  g_calcite.reset();
71  }
72 }
73 
77 }
78 
79 } // namespace
80 
81 namespace QueryRunner {
82 
83 std::unique_ptr<QueryRunner> QueryRunner::qr_instance_ = nullptr;
84 
85 query_state::QueryStates QueryRunner::query_states_;
86 
87 QueryRunner* QueryRunner::init(const char* db_path,
88  const std::string& udf_filename,
89  const size_t max_gpu_mem,
90  const int reserved_gpu_mem) {
91  return QueryRunner::init(db_path,
93  "HyperInteractive",
95  {},
96  {},
97  udf_filename,
98  true,
99  max_gpu_mem,
100  reserved_gpu_mem);
101 }
102 
104  const char* db_path,
105  const std::vector<LeafHostInfo>& string_servers,
106  const std::vector<LeafHostInfo>& leaf_servers) {
107  return QueryRunner::init(db_path,
109  "HyperInteractive",
111  string_servers,
112  leaf_servers,
113  "",
114  true,
115  0,
116  256 << 20,
117  false,
118  false,
119  disk_cache_config);
120 }
121 
122 QueryRunner* QueryRunner::init(const char* db_path,
123  const std::string& user,
124  const std::string& pass,
125  const std::string& db_name,
126  const std::vector<LeafHostInfo>& string_servers,
127  const std::vector<LeafHostInfo>& leaf_servers,
128  const std::string& udf_filename,
129  bool uses_gpus,
130  const size_t max_gpu_mem,
131  const int reserved_gpu_mem,
132  const bool create_user,
133  const bool create_db,
134  const File_Namespace::DiskCacheConfig* disk_cache_config) {
135  // Whitelist root path for tests by default
137  ddl_utils::FilePathWhitelist::initialize(db_path, "[\"/\"]", "[\"/\"]");
138  LOG_IF(FATAL, !leaf_servers.empty()) << "Distributed test runner not supported.";
139  CHECK(leaf_servers.empty());
140  qr_instance_.reset(new QueryRunner(db_path,
141  user,
142  pass,
143  db_name,
144  string_servers,
145  leaf_servers,
146  udf_filename,
147  uses_gpus,
148  max_gpu_mem,
149  reserved_gpu_mem,
150  create_user,
151  create_db,
152  disk_cache_config));
153  return qr_instance_.get();
154 }
155 
156 QueryRunner::QueryRunner(const char* db_path,
157  const std::string& user_name,
158  const std::string& passwd,
159  const std::string& db_name,
160  const std::vector<LeafHostInfo>& string_servers,
161  const std::vector<LeafHostInfo>& leaf_servers,
162  const std::string& udf_filename,
163  bool uses_gpus,
164  const size_t max_gpu_mem,
165  const int reserved_gpu_mem,
166  const bool create_user,
167  const bool create_db,
168  const File_Namespace::DiskCacheConfig* cache_config)
169  : dispatch_queue_(std::make_unique<QueryDispatchQueue>(1)) {
171  boost::filesystem::path base_path{db_path};
172  CHECK(boost::filesystem::exists(base_path));
173  auto system_db_file =
175  CHECK(boost::filesystem::exists(system_db_file));
176  auto data_dir = base_path / shared::kDataDirectoryName;
177  File_Namespace::DiskCacheConfig disk_cache_config{
178  (base_path / shared::kDefaultDiskCacheDirName).string(),
180  if (cache_config) {
181  disk_cache_config = *cache_config;
182  }
184 
187  g_calcite =
188  std::make_shared<Calcite>(-1, CALCITEPORT, db_path, 1024, 5000, true, udf_filename);
189  ExtensionFunctionsWhitelist::add(g_calcite->getExtensionFunctionWhitelist());
190  if (!udf_filename.empty()) {
191  ExtensionFunctionsWhitelist::addUdfs(g_calcite->getUserDefinedFunctionWhitelist());
192  }
193 
195 #ifdef HAVE_RUNTIME_LIBS
198 #endif
199  auto udtfs = ThriftSerializers::to_thrift(
201  std::vector<TUserDefinedFunction> udfs = {};
202  g_calcite->setRuntimeExtensionFunctions(udfs, udtfs, /*is_runtime=*/false);
203 
204  std::unique_ptr<CudaMgr_Namespace::CudaMgr> cuda_mgr;
205 #ifdef HAVE_CUDA
206  if (uses_gpus) {
207  cuda_mgr = std::make_unique<CudaMgr_Namespace::CudaMgr>(-1, 0);
208  }
209 #else
210  uses_gpus = false;
211 #endif
212  const size_t num_gpus = static_cast<size_t>(cuda_mgr ? cuda_mgr->getDeviceCount() : 0);
213  SystemParameters mapd_params;
214  mapd_params.gpu_buffer_mem_bytes = max_gpu_mem;
215  mapd_params.aggregator = !leaf_servers.empty();
216 
217  auto& sys_cat = Catalog_Namespace::SysCatalog::instance();
218 
219  g_base_path = base_path.string();
220 
221  if (!sys_cat.isInitialized()) {
222  auto data_mgr = std::make_shared<Data_Namespace::DataMgr>(data_dir.string(),
223  mapd_params,
224  std::move(cuda_mgr),
225  uses_gpus,
226  reserved_gpu_mem,
227  0,
228  disk_cache_config);
229 
231  // With the exception of cpu_result_mem, the below values essentially mirror
232  // how ExecutorResourceMgr is initialized by DBHandler for normal DB operation.
233  // The static 4GB allowcation of CPU result memory is sufficient for our tests,
234  // and prevents variability based on the DBHandler approach to sizing as a fraction
235  // of CPU buffer pool mem size.
237  cpu_threads() /* num_cpu_slots */,
238  num_gpus /* num_gpu_slots */,
239  static_cast<size_t>(1UL << 32) /* cpu_result_mem */,
240  data_mgr->getCpuBufferPoolSize() /* cpu_buffer_pool_mem */,
241  data_mgr->getGpuBufferPoolSize() /* gpu_buffer_pool_mem */,
242  0.9 /* per_query_max_cpu_slots_ratio */,
243  1.0 /* per_query_max_cpu_result_mem_ratio */,
244  true /* allow_cpu_kernel_concurrency */,
245  true /* allow_cpu_gpu_kernel_concurrency */,
246  false /* allow_cpu_slot_oversubscription_concurrency */,
247  false /* allow_cpu_result_mem_oversubscription_concurrency */,
248  0.9 /* max_available_resource_use_ratio */);
249  }
250 
251  sys_cat.init(g_base_path,
252  data_mgr,
253  {},
254  g_calcite,
255  false,
256  mapd_params.aggregator,
257  string_servers);
258  }
259 
260  query_engine_ =
261  QueryEngine::createInstance(sys_cat.getDataMgr().getCudaMgr(), !uses_gpus);
262 
263  if (create_user) {
264  if (!sys_cat.getMetadataForUser(user_name, user)) {
265  sys_cat.createUser(
266  user_name,
268  passwd, /*is_super=*/false, /*default_db=*/"", /*can_login=*/true},
269  g_read_only);
270  }
271  }
272  CHECK(sys_cat.getMetadataForUser(user_name, user));
273  CHECK(bcrypt_checkpw(passwd.c_str(), user.passwd_hash.c_str()) == 0);
274 
275  if (create_db) {
276  if (!sys_cat.getMetadataForDB(db_name, db_metadata_)) {
277  sys_cat.createDatabase(db_name, user.userId);
278  }
279  }
280  CHECK(sys_cat.getMetadataForDB(db_name, db_metadata_));
281  CHECK(user.isSuper || (user.userId == db_metadata_.dbOwner));
282  auto cat = sys_cat.getCatalog(db_metadata_, create_db);
283  CHECK(cat);
284  session_info_ = std::make_unique<Catalog_Namespace::SessionInfo>(
285  cat, user, ExecutorDeviceType::GPU, "");
286 }
287 
288 void QueryRunner::resizeDispatchQueue(const size_t num_executors) {
289  dispatch_queue_ = std::make_unique<QueryDispatchQueue>(num_executors);
290 }
291 
292 QueryRunner::QueryRunner(std::unique_ptr<Catalog_Namespace::SessionInfo> session)
293  : session_info_(std::move(session))
294  , dispatch_queue_(std::make_unique<QueryDispatchQueue>(1)) {}
295 
296 std::shared_ptr<Catalog_Namespace::Catalog> QueryRunner::getCatalog() const {
298  return session_info_->get_catalog_ptr();
299 }
300 
301 std::shared_ptr<Calcite> QueryRunner::getCalcite() const {
302  // TODO: Embed Calcite shared_ptr ownership in QueryRunner
303  return g_calcite;
304 }
305 
306 bool QueryRunner::gpusPresent() const {
308  return session_info_->getCatalog().getDataMgr().gpusPresent();
309 }
310 
311 void QueryRunner::clearGpuMemory() const {
314 }
315 
316 void QueryRunner::clearCpuMemory() const {
319 }
320 
321 std::vector<MemoryInfo> QueryRunner::getMemoryInfo(
322  const Data_Namespace::MemoryLevel memory_level) const {
324  return session_info_->getCatalog().getDataMgr().getMemoryInfo(memory_level);
325 }
326 
327 BufferPoolStats QueryRunner::getBufferPoolStats(
328  const Data_Namespace::MemoryLevel memory_level,
329  const bool current_db_only) const {
330  // Only works single-node for now
332  const std::vector<MemoryInfo> memory_infos =
333  session_info_->getCatalog().getDataMgr().getMemoryInfo(memory_level);
334  if (memory_level == Data_Namespace::MemoryLevel::CPU_LEVEL) {
335  CHECK_EQ(memory_infos.size(), static_cast<size_t>(1));
336  }
337  std::set<std::vector<int32_t>> chunk_keys;
338  std::set<std::vector<int32_t>> table_keys;
339  std::set<std::vector<int32_t>> column_keys;
340  std::set<std::vector<int32_t>> fragment_keys;
341  size_t total_num_buffers{
342  0}; // can be greater than chunk keys set size due to table replication
343  size_t total_num_bytes{0};
344  for (auto& pool_memory_info : memory_infos) {
345  const std::vector<MemoryData>& memory_data = pool_memory_info.nodeMemoryData;
346  for (auto& memory_datum : memory_data) {
347  total_num_buffers++;
348  const auto& chunk_key = memory_datum.chunk_key;
349  if (memory_datum.memStatus == Buffer_Namespace::MemStatus::FREE ||
350  chunk_key.size() < 4) {
351  continue;
352  }
353  if (current_db_only) {
354  if (chunk_key[0] != db_metadata_.dbId) {
355  continue;
356  }
357  }
358  total_num_bytes += (memory_datum.numPages * pool_memory_info.pageSize);
359  table_keys.insert({chunk_key[0], chunk_key[1]});
360  column_keys.insert({chunk_key[0], chunk_key[1], chunk_key[2]});
361  fragment_keys.insert({chunk_key[0], chunk_key[1], chunk_key[3]});
362  chunk_keys.insert(chunk_key);
363  }
364  }
365  return {total_num_buffers,
366  total_num_bytes,
367  table_keys.size(),
368  column_keys.size(),
369  fragment_keys.size(),
370  chunk_keys.size()};
371 }
372 
373 RegisteredQueryHint QueryRunner::getParsedQueryHint(const std::string& query_str) {
376  auto query_state = create_query_state(session_info_, query_str);
377  auto& cat = session_info_->getCatalog();
379 
380  auto calcite_mgr = cat.getCalciteMgr();
381  const auto calciteQueryParsingOption =
382  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
383  const auto calciteOptimizationOption =
384  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
385  const auto query_ra = calcite_mgr
386  ->process(query_state->createQueryStateProxy(),
387  pg_shim(query_str),
388  calciteQueryParsingOption,
389  calciteOptimizationOption)
390  .plan_result;
391  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
392  auto query_hints =
393  ra_executor.getParsedQueryHint(ra_executor.getRootRelAlgNodeShPtr().get());
394  return query_hints ? *query_hints : RegisteredQueryHint::defaults();
395 }
396 
397 std::shared_ptr<const RelAlgNode> QueryRunner::getRootNodeFromParsedQuery(
398  const std::string& query_str) {
401  auto query_state = create_query_state(session_info_, query_str);
402  auto& cat = session_info_->getCatalog();
404 
405  auto calcite_mgr = cat.getCalciteMgr();
406  const auto calciteQueryParsingOption =
407  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
408  const auto calciteOptimizationOption =
409  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
410  const auto query_ra = calcite_mgr
411  ->process(query_state->createQueryStateProxy(),
412  pg_shim(query_str),
413  calciteQueryParsingOption,
414  calciteOptimizationOption)
415  .plan_result;
416  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
417  return ra_executor.getRootRelAlgNodeShPtr();
418 }
419 
421  std::unordered_map<size_t, std::unordered_map<unsigned, RegisteredQueryHint>>>
422 QueryRunner::getParsedQueryHints(const std::string& query_str) {
425  auto query_state = create_query_state(session_info_, query_str);
426  auto& cat = session_info_->getCatalog();
428  auto calcite_mgr = cat.getCalciteMgr();
429  const auto calciteQueryParsingOption =
430  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
431  const auto calciteOptimizationOption =
432  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
433  const auto query_ra = calcite_mgr
434  ->process(query_state->createQueryStateProxy(),
435  pg_shim(query_str),
436  calciteQueryParsingOption,
437  calciteOptimizationOption)
438  .plan_result;
439  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
440  return ra_executor.getParsedQueryHints();
441 }
442 
443 std::optional<RegisteredQueryHint> QueryRunner::getParsedGlobalQueryHints(
444  const std::string& query_str) {
447  auto query_state = create_query_state(session_info_, query_str);
448  auto& cat = session_info_->getCatalog();
450  auto calcite_mgr = cat.getCalciteMgr();
451  const auto calciteQueryParsingOption =
452  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
453  const auto calciteOptimizationOption =
454  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
455  const auto query_ra = calcite_mgr
456  ->process(query_state->createQueryStateProxy(),
457  pg_shim(query_str),
458  calciteQueryParsingOption,
459  calciteOptimizationOption)
460  .plan_result;
461  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
462  return ra_executor.getGlobalQueryHint();
463 }
464 
465 RaExecutionSequence QueryRunner::getRaExecutionSequence(const std::string& query_str) {
468  auto query_state = create_query_state(session_info_, query_str);
469  auto& cat = session_info_->getCatalog();
471  auto calcite_mgr = cat.getCalciteMgr();
472  const auto calciteQueryParsingOption =
473  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
474  const auto calciteOptimizationOption =
475  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
476  const auto query_ra = calcite_mgr
477  ->process(query_state->createQueryStateProxy(),
478  pg_shim(query_str),
479  calciteQueryParsingOption,
480  calciteOptimizationOption)
481  .plan_result;
482  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
483  return ra_executor.getRaExecutionSequence(ra_executor.getRootRelAlgNodeShPtr().get(),
484  executor.get());
485 }
486 
487 // used to validate calcite ddl statements
488 void QueryRunner::validateDDLStatement(const std::string& stmt_str_in) {
490 
491  std::string stmt_str = stmt_str_in;
492  // First remove special chars
493  boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
494  // Then remove spaces
495  boost::algorithm::trim_left(stmt_str);
496 
497  auto query_state = create_query_state(session_info_, stmt_str);
498  auto stdlog = STDLOG(query_state);
499 
500  auto& cat = session_info_->getCatalog();
501  auto calcite_mgr = cat.getCalciteMgr();
502  const auto calciteQueryParsingOption =
503  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
504  const auto calciteOptimizationOption =
505  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
506  calcite_mgr->process(query_state->createQueryStateProxy(),
507  pg_shim(stmt_str),
508  calciteQueryParsingOption,
509  calciteOptimizationOption);
510 }
511 
512 std::shared_ptr<RelAlgTranslator> QueryRunner::getRelAlgTranslator(
513  const std::string& query_str,
514  Executor* executor) {
517  auto query_state = create_query_state(session_info_, query_str);
518  auto& cat = session_info_->getCatalog();
519  auto calcite_mgr = cat.getCalciteMgr();
520  const auto calciteQueryParsingOption =
521  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
522  const auto calciteOptimizationOption =
523  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
524  const auto query_ra = calcite_mgr
525  ->process(query_state->createQueryStateProxy(),
526  pg_shim(query_str),
527  calciteQueryParsingOption,
528  calciteOptimizationOption)
529  .plan_result;
530  auto ra_executor = RelAlgExecutor(executor, query_ra);
531  auto root_node_shared_ptr = ra_executor.getRootRelAlgNodeShPtr();
532  return ra_executor.getRelAlgTranslator(root_node_shared_ptr.get());
533 }
534 
535 QueryPlanDagInfo QueryRunner::getQueryInfoForDataRecyclerTest(
536  const std::string& query_str) {
539  auto query_state = create_query_state(session_info_, query_str);
540  auto& cat = session_info_->getCatalog();
542  auto calcite_mgr = cat.getCalciteMgr();
543  const auto calciteQueryParsingOption =
544  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
545  const auto calciteOptimizationOption =
546  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
547  const auto query_ra = calcite_mgr
548  ->process(query_state->createQueryStateProxy(),
549  pg_shim(query_str),
550  calciteQueryParsingOption,
551  calciteOptimizationOption)
552  .plan_result;
553  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
554  // note that we assume the test for data recycler that needs to have join_info
555  // does not contain any ORDER BY clause; this is necessary to create work_unit
556  // without actually performing the query
557  auto root_node_shared_ptr = ra_executor.getRootRelAlgNodeShPtr();
558  auto join_info = ra_executor.getJoinInfo(root_node_shared_ptr.get());
559  auto relAlgTranslator = ra_executor.getRelAlgTranslator(root_node_shared_ptr.get());
560  return {root_node_shared_ptr, join_info.first, join_info.second, relAlgTranslator};
561 }
562 
563 std::unique_ptr<Parser::Stmt> QueryRunner::createStatement(
564  const std::string& stmt_str_in) {
567 
568  std::string stmt_str = stmt_str_in;
569  // First remove special chars
570  boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
571  // Then remove spaces
572  boost::algorithm::trim_left(stmt_str);
573 
574  ParserWrapper pw{stmt_str};
575 
576  auto query_state = create_query_state(session_info_, stmt_str);
577  auto stdlog = STDLOG(query_state);
578 
579  if (pw.is_ddl) {
580  const auto& cat = session_info_->getCatalog();
581  auto calcite_mgr = cat.getCalciteMgr();
582  const auto calciteQueryParsingOption =
583  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
584  const auto calciteOptimizationOption =
585  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
586  const auto query_json = calcite_mgr
587  ->process(query_state->createQueryStateProxy(),
588  pg_shim(stmt_str),
589  calciteQueryParsingOption,
590  calciteOptimizationOption)
591  .plan_result;
592  return Parser::create_stmt_for_json(query_json);
593  }
594 
595  // simply fail here as non-Calcite parsing is about to be removed
596  UNREACHABLE();
597  return nullptr;
598 }
599 
600 void QueryRunner::runDDLStatement(const std::string& stmt_str_in) {
603 
604  std::string stmt_str = stmt_str_in;
605  // First remove special chars
606  boost::algorithm::trim_left_if(stmt_str, boost::algorithm::is_any_of("\n"));
607  // Then remove spaces
608  boost::algorithm::trim_left(stmt_str);
609 
610  ParserWrapper pw{stmt_str};
611 
612  auto query_state = create_query_state(session_info_, stmt_str);
613  auto stdlog = STDLOG(query_state);
614 
615  if (pw.is_ddl || pw.getDMLType() == ParserWrapper::DMLType::Insert) {
616  auto& cat = session_info_->getCatalog();
617  auto calcite_mgr = cat.getCalciteMgr();
618  const auto calciteQueryParsingOption =
619  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
620  const auto calciteOptimizationOption =
621  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
622  const auto query_ra = calcite_mgr
623  ->process(query_state->createQueryStateProxy(),
624  pg_shim(stmt_str),
625  calciteQueryParsingOption,
626  calciteOptimizationOption)
627  .plan_result;
628  if (pw.getDMLType() == ParserWrapper::DMLType::Insert) {
629  rapidjson::Document ddl_query;
630  ddl_query.Parse(query_ra);
631  CHECK(ddl_query.HasMember("payload"));
632  CHECK(ddl_query["payload"].IsObject());
633  auto stmt = Parser::InsertValuesStmt(cat, ddl_query["payload"].GetObject());
634  stmt.execute(*session_info_, false /* read only */);
635  return;
636  }
638  executor.execute(false /* read only */);
639  return;
640  }
641 }
642 
643 std::shared_ptr<ResultSet> QueryRunner::runSQL(const std::string& query_str,
645  ExecutionOptions eo) {
648 
649  ParserWrapper pw{query_str};
650  if (pw.getDMLType() == ParserWrapper::DMLType::Insert) {
651  runDDLStatement(query_str);
652  return nullptr;
653  }
654  const auto execution_result = runSelectQuery(query_str, std::move(co), std::move(eo));
655  VLOG(1) << session_info_->getCatalog().getDataMgr().getSystemMemoryUsage();
656  return execution_result->getRows();
657 }
658 
659 std::shared_ptr<ResultSet> QueryRunner::runSQL(const std::string& query_str,
660  const ExecutorDeviceType device_type,
661  const bool hoist_literals,
662  const bool allow_loop_joins) {
663  auto co = CompilationOptions::defaults(device_type);
664  co.hoist_literals = hoist_literals;
665  return runSQL(
666  query_str, std::move(co), defaultExecutionOptionsForRunSQL(allow_loop_joins));
667 }
668 
669 ExecutionOptions QueryRunner::defaultExecutionOptionsForRunSQL(bool allow_loop_joins,
670  bool just_explain) {
671  return {g_enable_columnar_output,
672  false,
673  true,
674  just_explain,
675  allow_loop_joins,
676  false,
677  false,
678  false,
679  false,
680  10000,
681  false,
682  false,
684  false,
685  0.5,
686  1000,
687  false};
688 }
689 
690 std::shared_ptr<Executor> QueryRunner::getExecutor() const {
693  auto query_state = create_query_state(session_info_, "");
694  auto stdlog = STDLOG(query_state);
696  return executor;
697 }
698 
699 std::shared_ptr<ResultSet> QueryRunner::runSQLWithAllowingInterrupt(
700  const std::string& query_str,
701  const std::string& session_id,
702  const ExecutorDeviceType device_type,
703  const double running_query_check_freq,
704  const unsigned pending_query_check_freq) {
707  auto current_user = session_info_->get_currentUser();
708  auto session_info = std::make_shared<Catalog_Namespace::SessionInfo>(
709  session_info_->get_catalog_ptr(), current_user, device_type, session_id);
710  auto query_state = create_query_state(session_info, query_str);
711  auto stdlog = STDLOG(query_state);
712  auto& cat = query_state->getConstSessionInfo()->getCatalog();
713  std::string query_ra{""};
714 
715  std::shared_ptr<ExecutionResult> result;
716  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
717  [&cat,
718  &query_ra,
719  &device_type,
720  &query_state,
721  &result,
722  &running_query_check_freq,
723  &pending_query_check_freq,
724  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
725  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
726  auto executor = Executor::getExecutor(worker_id);
728 
730  false,
731  true,
732  false,
733  true,
734  false,
735  false,
736  false,
737  false,
738  10000,
739  false,
740  false,
742  true,
743  running_query_check_freq,
744  pending_query_check_freq,
745  false};
746  {
747  // async query initiation for interrupt test
748  // incurs data race warning in TSAN since
749  // calcite_mgr is shared across multiple query threads
750  // so here we lock the manager during query parsing
751  std::lock_guard<std::mutex> calcite_lock_guard(calcite_lock);
752  auto calcite_mgr = cat.getCalciteMgr();
753  const auto calciteQueryParsingOption =
754  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
755  const auto calciteOptimizationOption =
756  calcite_mgr->getCalciteOptimizationOption(
757  false, g_enable_watchdog, {}, false);
758  query_ra = calcite_mgr
759  ->process(query_state->createQueryStateProxy(),
760  pg_shim(query_state->getQueryStr()),
761  calciteQueryParsingOption,
762  calciteOptimizationOption)
763  .plan_result;
764  }
765  auto ra_executor = RelAlgExecutor(executor.get(), query_ra, query_state);
766  result = std::make_shared<ExecutionResult>(
767  ra_executor.executeRelAlgQuery(co, eo, false, false, nullptr));
768  });
770  executor->enrollQuerySession(session_id,
771  query_str,
772  query_state->getQuerySubmittedTime(),
774  QuerySessionStatus::QueryStatus::PENDING_QUEUE);
776  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
777  auto result_future = query_launch_task->get_future();
778  result_future.get();
779  CHECK(result);
780  return result->getRows();
781 }
782 
783 std::vector<std::shared_ptr<ResultSet>> QueryRunner::runMultipleStatements(
784  const std::string& sql,
785  const ExecutorDeviceType dt) {
786  std::vector<std::shared_ptr<ResultSet>> results;
787  // TODO: Need to properly handle escaped semicolons instead of doing a naive split().
788  auto fields = split(sql, ";");
789  for (const auto& field : fields) {
790  auto text = strip(field) + ";";
791  if (text == ";") {
792  continue;
793  }
794 
795  ParserWrapper pw{text};
796  if (pw.is_ddl || pw.getDMLType() == ParserWrapper::DMLType::Insert) {
797  runDDLStatement(text);
798  results.push_back(nullptr);
799  } else {
800  // is not DDL, then assume it's DML and try to execute
801  results.push_back(runSQL(text, dt, true, true));
802  }
803  }
804  return results;
805 }
806 
807 void QueryRunner::runImport(Parser::CopyTableStmt* import_stmt) {
808  CHECK(import_stmt);
809  import_stmt->execute(*session_info_, false /* read only */);
810 }
811 
812 std::unique_ptr<import_export::Loader> QueryRunner::getLoader(
813  const TableDescriptor* td) const {
814  auto cat = getCatalog();
815  return std::make_unique<import_export::Loader>(*cat, td);
816 }
817 
818 namespace {
819 
820 std::shared_ptr<ExecutionResult> run_select_query_with_filter_push_down(
821  QueryStateProxy query_state_proxy,
822  const ExecutorDeviceType device_type,
823  const bool hoist_literals,
824  const bool allow_loop_joins,
825  const bool just_explain,
826  const ExecutorExplainType explain_type,
827  const bool with_filter_push_down) {
828  auto& cat = query_state_proxy->getConstSessionInfo()->getCatalog();
831  co.explain_type = explain_type;
832 
835  eo.just_explain = just_explain;
836  eo.allow_loop_joins = allow_loop_joins;
837  eo.find_push_down_candidates = with_filter_push_down;
839 
840  auto calcite_mgr = cat.getCalciteMgr();
841  const auto calciteQueryParsingOption =
842  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
843  auto calciteOptimizationOption =
844  calcite_mgr->getCalciteOptimizationOption(false, g_enable_watchdog, {}, false);
845  const auto query_ra = calcite_mgr
846  ->process(query_state_proxy,
847  pg_shim(query_state_proxy->getQueryStr()),
848  calciteQueryParsingOption,
849  calciteOptimizationOption)
850  .plan_result;
851  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
852  auto result = std::make_shared<ExecutionResult>(
853  ra_executor.executeRelAlgQuery(co, eo, false, false, nullptr));
854  const auto& filter_push_down_requests = result->getPushedDownFilterInfo();
855  if (!filter_push_down_requests.empty()) {
856  std::vector<TFilterPushDownInfo> filter_push_down_info;
857  for (const auto& req : filter_push_down_requests) {
858  TFilterPushDownInfo filter_push_down_info_for_request;
859  filter_push_down_info_for_request.input_prev = req.input_prev;
860  filter_push_down_info_for_request.input_start = req.input_start;
861  filter_push_down_info_for_request.input_next = req.input_next;
862  filter_push_down_info.push_back(filter_push_down_info_for_request);
863  }
864  calciteOptimizationOption.filter_push_down_info = filter_push_down_info;
865  const auto new_query_ra = calcite_mgr
866  ->process(query_state_proxy,
867  pg_shim(query_state_proxy->getQueryStr()),
868  calciteQueryParsingOption,
869  calciteOptimizationOption)
870  .plan_result;
871  auto eo_modified = eo;
872  eo_modified.find_push_down_candidates = false;
873  eo_modified.just_calcite_explain = false;
874  auto new_ra_executor = RelAlgExecutor(executor.get(), new_query_ra);
875  return std::make_shared<ExecutionResult>(
876  new_ra_executor.executeRelAlgQuery(co, eo_modified, false, false, nullptr));
877  } else {
878  return result;
879  }
880 }
881 
882 } // namespace
883 
884 std::shared_ptr<ResultSet> QueryRunner::getCalcitePlan(const std::string& query_str,
885  bool enable_watchdog,
886  bool is_explain_as_json_str,
887  bool is_explain_detailed) const {
890  const auto& cat = session_info_->getCatalog();
891  auto query_state = create_query_state(session_info_, query_str);
892  auto stdlog = STDLOG(query_state);
893 
894  std::shared_ptr<ResultSet> result;
895  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
896  [&cat,
897  &query_str,
898  &enable_watchdog,
899  &is_explain_as_json_str,
900  &is_explain_detailed,
901  &query_state,
902  &result,
903  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
904  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
905  auto executor = Executor::getExecutor(worker_id);
906  auto calcite_mgr = cat.getCalciteMgr();
907  // Calcite returns its plan as a form of `json_str` by default,
908  // so we set `is_explain` to TRUE if `!is_explain_as_json_str`
909  const auto calciteQueryParsingOption = calcite_mgr->getCalciteQueryParsingOption(
910  true, !is_explain_as_json_str, false, is_explain_detailed);
911  const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
912  g_enable_calcite_view_optimize, enable_watchdog, {}, false);
913  const auto query_ra = calcite_mgr
914  ->process(query_state->createQueryStateProxy(),
915  pg_shim(query_str),
916  calciteQueryParsingOption,
917  calciteOptimizationOption)
918  .plan_result;
919  result = std::make_shared<ResultSet>(query_ra);
920  return result;
921  });
923  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
924  auto result_future = query_launch_task->get_future();
925  result_future.get();
926  CHECK(result);
927  return result;
928 }
929 
930 std::shared_ptr<ExecutionResult> QueryRunner::runSelectQuery(const std::string& query_str,
932  ExecutionOptions eo) {
935  auto query_state = create_query_state(session_info_, query_str);
936  auto stdlog = STDLOG(query_state);
938  return run_select_query_with_filter_push_down(query_state->createQueryStateProxy(),
939  co.device_type,
940  co.hoist_literals,
941  eo.allow_loop_joins,
942  eo.just_explain,
945  }
946 
947  auto& cat = session_info_->getCatalog();
948 
949  std::shared_ptr<ExecutionResult> result;
950  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
951  [&cat,
952  &query_str,
953  &co,
954  explain_type = this->explain_type_,
955  &eo,
956  &query_state,
957  &result,
958  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
959  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
960  auto executor = Executor::getExecutor(worker_id);
961  // TODO The next line should be deleted since it overwrites co, but then
962  // NycTaxiTest.RunSelectsEncodingDictWhereGreater fails due to co not getting
963  // reset to its default values.
964  co = CompilationOptions::defaults(co.device_type);
965  co.explain_type = explain_type;
966  auto calcite_mgr = cat.getCalciteMgr();
967  const auto calciteQueryParsingOption =
968  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
969  const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
971  const auto query_ra = calcite_mgr
972  ->process(query_state->createQueryStateProxy(),
973  pg_shim(query_str),
974  calciteQueryParsingOption,
975  calciteOptimizationOption)
976  .plan_result;
977  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
978  result = std::make_shared<ExecutionResult>(
979  ra_executor.executeRelAlgQuery(co, eo, false, false, nullptr));
980  });
982  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
983  auto result_future = query_launch_task->get_future();
984  result_future.get();
985  CHECK(result);
986  return result;
987 }
988 
989 std::shared_ptr<ExecutionResult> QueryRunner::runSelectQuery(
990  const std::string& query_str,
991  const ExecutorDeviceType device_type,
992  const bool hoist_literals,
993  const bool allow_loop_joins,
994  const bool just_explain) {
995  auto co = CompilationOptions::defaults(device_type);
996  co.hoist_literals = hoist_literals;
997  return runSelectQuery(query_str,
998  std::move(co),
999  defaultExecutionOptionsForRunSQL(allow_loop_joins, just_explain));
1000 }
1001 
1002 ExtractedQueryPlanDag QueryRunner::extractQueryPlanDag(const std::string& query_str) {
1003  auto query_dag_info = getQueryInfoForDataRecyclerTest(query_str);
1005  auto extracted_dag_info = QueryPlanDagExtractor::extractQueryPlanDag(
1006  query_dag_info.root_node.get(), executor);
1007  return extracted_dag_info;
1008 }
1009 
1010 std::unique_ptr<RelAlgDag> QueryRunner::getRelAlgDag(const std::string& query_str) {
1013  auto query_state = create_query_state(session_info_, query_str);
1014  auto stdlog = STDLOG(query_state);
1015  auto& cat = session_info_->getCatalog();
1016 
1017  std::unique_ptr<RelAlgDag> rel_alg_dag;
1018  auto query_launch_task = std::make_shared<QueryDispatchQueue::Task>(
1019  [&cat,
1020  &query_str,
1021  &query_state,
1022  &rel_alg_dag,
1023  parent_thread_local_ids = logger::thread_local_ids()](const size_t worker_id) {
1024  logger::LocalIdsScopeGuard lisg = parent_thread_local_ids.setNewThreadId();
1025  auto executor = Executor::getExecutor(worker_id);
1026  auto eo = ExecutionOptions::defaults();
1027  auto calcite_mgr = cat.getCalciteMgr();
1028  const auto calciteQueryParsingOption =
1029  calcite_mgr->getCalciteQueryParsingOption(true, false, true, false);
1030  const auto calciteOptimizationOption = calcite_mgr->getCalciteOptimizationOption(
1032  const auto query_ra = calcite_mgr
1033  ->process(query_state->createQueryStateProxy(),
1034  pg_shim(query_str),
1035  calciteQueryParsingOption,
1036  calciteOptimizationOption)
1037  .plan_result;
1038  auto ra_executor = RelAlgExecutor(executor.get(), query_ra);
1039  rel_alg_dag = ra_executor.getOwnedRelAlgDag();
1040  });
1042  dispatch_queue_->submit(query_launch_task, /*is_update_delete=*/false);
1043  auto result_future = query_launch_task->get_future();
1044  result_future.get();
1045  CHECK(rel_alg_dag);
1046  return rel_alg_dag;
1047 }
1048 
1049 // this function exists to test data recycler
1050 // specifically, it is tricky to get a hashtable cache key when we only know
1051 // a target query sql in test code
1052 // so this function utilizes an incorrect way to manipulate our hashtable recycler
1053 // but provides the cached hashtable for performing the test
1054 // a set "visited" contains cached hashtable keys that we have retrieved so far
1055 // based on that, this function iterates hashtable cache and return a cached one
1056 // when its hashtable cache key has not been visited yet
1057 // for instance, if we call this funtion with an empty "visited" key, we return
1058 // the first hashtable that its iterator visits
1059 std::tuple<QueryPlanHash,
1060  std::shared_ptr<HashTable>,
1061  std::optional<HashtableCacheMetaInfo>>
1062 QueryRunner::getCachedHashtableWithoutCacheKey(std::set<size_t>& visited,
1063  CacheItemType hash_table_type,
1064  DeviceIdentifier device_identifier) {
1065  HashtableRecycler* hash_table_cache{nullptr};
1066  switch (hash_table_type) {
1068  hash_table_cache = PerfectJoinHashTable::getHashTableCache();
1069  break;
1070  }
1072  hash_table_cache = BaselineJoinHashTable::getHashTableCache();
1073  break;
1074  }
1077  break;
1078  }
1079  default: {
1080  UNREACHABLE();
1081  break;
1082  }
1083  }
1084  CHECK(hash_table_cache);
1085  return hash_table_cache->getCachedHashtableWithoutCacheKey(
1086  visited, hash_table_type, device_identifier);
1087 }
1088 
1089 std::shared_ptr<CacheItemMetric> QueryRunner::getCacheItemMetric(
1090  QueryPlanHash cache_key,
1091  CacheItemType hash_table_type,
1092  DeviceIdentifier device_identifier) {
1093  HashtableRecycler* hash_table_cache{nullptr};
1094  switch (hash_table_type) {
1096  hash_table_cache = PerfectJoinHashTable::getHashTableCache();
1097  break;
1098  }
1100  hash_table_cache = BaselineJoinHashTable::getHashTableCache();
1101  break;
1102  }
1105  break;
1106  }
1107  default: {
1108  UNREACHABLE();
1109  break;
1110  }
1111  }
1112  CHECK(hash_table_cache);
1113  return hash_table_cache->getCachedItemMetric(
1114  hash_table_type, device_identifier, cache_key);
1115 }
1116 
1117 size_t QueryRunner::getNumberOfCachedItem(CacheItemStatus item_status,
1118  CacheItemType hash_table_type,
1119  bool with_bbox_intersect_tuning_param) const {
1120  auto get_num_cached_auto_tuner_param = [&item_status]() {
1121  auto auto_tuner_cache =
1123  CHECK(auto_tuner_cache);
1124  switch (item_status) {
1125  case CacheItemStatus::ALL: {
1126  return auto_tuner_cache->getCurrentNumCachedItems(
1129  }
1131  return auto_tuner_cache->getCurrentNumCleanCachedItems(
1134  }
1136  return auto_tuner_cache->getCurrentNumDirtyCachedItems(
1139  }
1140  default: {
1141  UNREACHABLE();
1142  return static_cast<size_t>(0);
1143  }
1144  }
1145  };
1146 
1147  auto get_num_cached_hashtable =
1148  [&item_status,
1149  &hash_table_type,
1150  &with_bbox_intersect_tuning_param,
1151  &get_num_cached_auto_tuner_param](HashtableRecycler* hash_table_cache) {
1152  switch (item_status) {
1153  case CacheItemStatus::ALL: {
1154  if (with_bbox_intersect_tuning_param) {
1155  // we assume additional consideration of turing param cache is only valid
1156  // for bounding box intersection
1157  CHECK_EQ(hash_table_type, CacheItemType::BBOX_INTERSECT_HT);
1158  return hash_table_cache->getCurrentNumCachedItems(
1159  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER) +
1160  get_num_cached_auto_tuner_param();
1161  }
1162  return hash_table_cache->getCurrentNumCachedItems(
1163  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER);
1164  }
1166  if (with_bbox_intersect_tuning_param) {
1167  CHECK_EQ(hash_table_type, CacheItemType::BBOX_INTERSECT_HT);
1168  return hash_table_cache->getCurrentNumCleanCachedItems(
1169  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER) +
1170  get_num_cached_auto_tuner_param();
1171  }
1172  return hash_table_cache->getCurrentNumCleanCachedItems(
1173  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER);
1174  }
1176  if (with_bbox_intersect_tuning_param) {
1177  CHECK_EQ(hash_table_type, CacheItemType::BBOX_INTERSECT_HT);
1178  return hash_table_cache->getCurrentNumDirtyCachedItems(
1179  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER) +
1180  get_num_cached_auto_tuner_param();
1181  }
1182  return hash_table_cache->getCurrentNumDirtyCachedItems(
1183  hash_table_type, DataRecyclerUtil::CPU_DEVICE_IDENTIFIER);
1184  }
1185  default: {
1186  UNREACHABLE();
1187  return static_cast<size_t>(0);
1188  }
1189  }
1190  };
1191 
1192  switch (hash_table_type) {
1194  auto hash_table_cache = PerfectJoinHashTable::getHashTableCache();
1195  CHECK(hash_table_cache);
1196  return get_num_cached_hashtable(hash_table_cache);
1197  }
1199  auto hash_table_cache = BaselineJoinHashTable::getHashTableCache();
1200  CHECK(hash_table_cache);
1201  return get_num_cached_hashtable(hash_table_cache);
1202  }
1204  auto hash_table_cache = BoundingBoxIntersectJoinHashTable::getHashTableCache();
1205  CHECK(hash_table_cache);
1206  return get_num_cached_hashtable(hash_table_cache);
1207  }
1209  return get_num_cached_auto_tuner_param();
1210  }
1211  default: {
1212  UNREACHABLE();
1213  return 0;
1214  }
1215  }
1216  return 0;
1217 }
1218 
1219 void QueryRunner::reset() {
1220  qr_instance_->query_engine_.reset();
1221  qr_instance_.reset(nullptr);
1223 }
1224 
1225 ImportDriver::ImportDriver(std::shared_ptr<Catalog_Namespace::Catalog> cat,
1226  const Catalog_Namespace::UserMetadata& user,
1227  const ExecutorDeviceType dt,
1228  const std::string session_id)
1229  : QueryRunner(
1230  std::make_unique<Catalog_Namespace::SessionInfo>(cat, user, dt, session_id)) {}
1231 
1232 void ImportDriver::importGeoTable(const std::string& file_path,
1233  const std::string& table_name,
1234  const bool compression,
1235  const bool create_table,
1236  const bool explode_collections) {
1237  using namespace import_export;
1238 
1239  static constexpr bool kIsGeoRaster{false};
1240 
1242 
1243  CopyParams copy_params;
1245  if (compression) {
1246  copy_params.geo_coords_encoding = EncodingType::kENCODING_GEOINT;
1247  copy_params.geo_coords_comp_param = 32;
1248  } else {
1249  copy_params.geo_coords_encoding = EncodingType::kENCODING_NONE;
1250  copy_params.geo_coords_comp_param = 0;
1251  }
1252  copy_params.geo_explode_collections = explode_collections;
1253 
1254  std::map<std::string, std::string> colname_to_src;
1255  auto& cat = session_info_->getCatalog();
1256  auto cds = Importer::gdalToColumnDescriptors(
1257  file_path, kIsGeoRaster, Geospatial::kGeoColumnName, copy_params);
1258 
1259  for (auto& cd : cds) {
1260  const auto col_name_sanitized = ImportHelpers::sanitize_name(cd.columnName);
1261  const auto ret =
1262  colname_to_src.insert(std::make_pair(col_name_sanitized, cd.columnName));
1263  CHECK(ret.second);
1264  cd.columnName = col_name_sanitized;
1265  }
1266 
1267  if (create_table) {
1268  const auto td = cat.getMetadataForTable(table_name);
1269  if (td != nullptr) {
1270  throw std::runtime_error(
1271  "Error: Table " + table_name +
1272  " already exists. Possible failure to correctly re-create " +
1273  shared::kDataDirectoryName + " directory.");
1274  }
1275  if (table_name != ImportHelpers::sanitize_name(table_name)) {
1276  throw std::runtime_error("Invalid characters in table name: " + table_name);
1277  }
1278 
1279  std::string stmt{"CREATE TABLE " + table_name};
1280  std::vector<std::string> col_stmts;
1281 
1282  for (auto& cd : cds) {
1283  if (cd.columnType.get_type() == SQLTypes::kINTERVAL_DAY_TIME ||
1284  cd.columnType.get_type() == SQLTypes::kINTERVAL_YEAR_MONTH) {
1285  throw std::runtime_error(
1286  "Unsupported type: INTERVAL_DAY_TIME or INTERVAL_YEAR_MONTH for col " +
1287  cd.columnName + " (table: " + table_name + ")");
1288  }
1289 
1290  if (cd.columnType.get_type() == SQLTypes::kDECIMAL) {
1291  if (cd.columnType.get_precision() == 0 && cd.columnType.get_scale() == 0) {
1292  cd.columnType.set_precision(14);
1293  cd.columnType.set_scale(7);
1294  }
1295  }
1296 
1297  std::string col_stmt;
1298  col_stmt.append(cd.columnName + " " + cd.columnType.get_type_name() + " ");
1299 
1300  if (cd.columnType.get_compression() != EncodingType::kENCODING_NONE) {
1301  col_stmt.append("ENCODING " + cd.columnType.get_compression_name() + " ");
1302  } else {
1303  if (cd.columnType.is_string()) {
1304  col_stmt.append("ENCODING NONE");
1305  } else if (cd.columnType.is_geometry()) {
1306  if (cd.columnType.get_output_srid() == 4326) {
1307  col_stmt.append("ENCODING NONE");
1308  }
1309  }
1310  }
1311  col_stmts.push_back(col_stmt);
1312  }
1313 
1314  stmt.append(" (" + boost::algorithm::join(col_stmts, ",") + ");");
1315  runDDLStatement(stmt);
1316 
1317  LOG(INFO) << "Created table: " << table_name;
1318  } else {
1319  LOG(INFO) << "Not creating table: " << table_name;
1320  }
1321 
1322  const auto td = cat.getMetadataForTable(table_name);
1323  if (td == nullptr) {
1324  throw std::runtime_error("Error: Failed to create table " + table_name);
1325  }
1326 
1327  import_export::Importer importer(cat, td, file_path, copy_params);
1328  auto ms = measure<>::execution(
1329  [&]() { importer.importGDAL(colname_to_src, session_info_.get(), kIsGeoRaster); });
1330  LOG(INFO) << "Import Time for " << table_name << ": " << (double)ms / 1000.0 << " s";
1331 }
1332 
1333 } // namespace QueryRunner
bool g_enable_calcite_view_optimize
Definition: QueryRunner.cpp:59
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:5226
#define CALCITEPORT
Definition: QueryRunner.cpp:51
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)
static void loadTestRuntimeLibs()
std::string cat(Ts &&...args)
std::unique_ptr< QueryDispatchQueue > dispatch_queue_
Definition: QueryRunner.h:332
static TimeT::rep execution(F func, Args &&...args)
Definition: sample.cpp:29
std::string const & getQueryStr() const
Definition: QueryState.h:159
static void initialize(const std::string &data_dir, const std::string &allowed_import_paths, const std::string &allowed_export_paths)
Definition: DdlUtils.cpp:878
const std::string kDefaultDiskCacheDirName
static void loadRuntimeLibs(const std::string &torch_lib_path=std::string())
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:328
std::string join(T const &container, std::string const &delim)
static void add(const std::string &json_func_sigs)
#define UNREACHABLE()
Definition: Logger.h:338
std::mutex calcite_lock
Definition: QueryRunner.cpp:60
std::optional< std::unordered_map< size_t, std::unordered_map< unsigned, RegisteredQueryHint > > > getParsedQueryHints()
std::optional< RegisteredQueryHint > getParsedQueryHint(const RelAlgNode *node)
static void init_resource_mgr(const size_t num_cpu_slots, const size_t num_gpu_slots, const size_t cpu_result_mem, const size_t cpu_buffer_pool_mem, const size_t gpu_buffer_pool_mem, const double per_query_max_cpu_slots_ratio, const double per_query_max_cpu_result_mem_ratio, const bool allow_cpu_kernel_concurrency, const bool allow_cpu_gpu_kernel_concurrency, const bool allow_cpu_slot_oversubscription_concurrency, const bool allow_cpu_result_mem_oversubscription, const double max_available_resource_use_ratio)
Definition: Execute.cpp:5353
void set_once_fatal_func(FatalFunc fatal_func)
Definition: Logger.cpp:394
Catalog_Namespace::DBMetadata db_metadata_
Definition: QueryRunner.h:330
static ExecutionOptions defaultExecutionOptionsForRunSQL(bool allow_loop_joins=true, bool just_explain=false)
ExecutorDeviceType
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:384
static void clearMemory(const Data_Namespace::MemoryLevel memory_level)
Definition: Execute.cpp:531
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:509
std::shared_ptr< QueryEngine > query_engine_
Definition: QueryRunner.h:333
bool g_enable_executor_resource_mgr
Definition: Execute.cpp:174
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:33
bool g_enable_columnar_output
Definition: Execute.cpp:102
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:364
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:97
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:326
double g_gpu_mem_limit_percent
Definition: QueryRunner.cpp:56
import_export::SourceType source_type
Definition: CopyParams.h:57
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:364
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: heavyai_locks.h:21
std::string sanitize_name(const std::string &name, const bool underscore=false)
std::shared_ptr< Catalog_Namespace::SessionInfo > session_info_
Definition: QueryRunner.h:331
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:65
const std::string kCatalogDirectoryName
static std::shared_ptr< query_state::QueryState > create_query_state(Ts &&...args)
Definition: QueryRunner.h:304
static CompilationOptions defaults(const ExecutorDeviceType device_type=ExecutorDeviceType::GPU)
bool g_enable_filter_push_down
Definition: Execute.cpp:98
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
static constexpr ExecutorId UNITARY_EXECUTOR_ID
Definition: Execute.h:423
size_t g_leaf_count
Definition: ParserNode.cpp:78
void init_table_functions()
std::unique_ptr< RelAlgDag > getOwnedRelAlgDag()
static constexpr DeviceIdentifier CPU_DEVICE_IDENTIFIER
Definition: DataRecycler.h:136
int cpu_threads()
Definition: thread_count.h:25
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)
static BoundingBoxIntersectTuningParamRecycler * getBoundingBoxIntersectTuningParamCache()
ThreadLocalIds thread_local_ids()
Definition: Logger.cpp:880
#define STDLOG(...)
Definition: QueryState.h:234
#define VLOG(n)
Definition: Logger.h:388
std::atomic< bool > isSuper
Definition: SysCatalog.h:107