OmniSciDB  8fa3bf436f
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
InsertOrderFragmenter.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 OmniSci, 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 
18 
19 #include <algorithm>
20 #include <boost/lexical_cast.hpp>
21 #include <cassert>
22 #include <cmath>
23 #include <iostream>
24 #include <limits>
25 #include <memory>
26 #include <thread>
27 #include <type_traits>
28 
29 #include "DataMgr/AbstractBuffer.h"
30 #include "DataMgr/DataMgr.h"
32 #include "LockMgr/LockMgr.h"
33 #include "Logger/Logger.h"
34 
35 #include "Shared/checked_alloc.h"
36 #include "Shared/thread_count.h"
37 
38 #define DROP_FRAGMENT_FACTOR \
39  0.97 // drop to 97% of max so we don't keep adding and dropping fragments
40 
41 using Chunk_NS::Chunk;
44 
46 
47 using namespace std;
48 
49 namespace Fragmenter_Namespace {
50 
51 InsertOrderFragmenter::InsertOrderFragmenter(
52  const vector<int> chunkKeyPrefix,
53  vector<Chunk>& chunkVec,
54  Data_Namespace::DataMgr* dataMgr,
56  const int physicalTableId,
57  const int shard,
58  const size_t maxFragmentRows,
59  const size_t maxChunkSize,
60  const size_t pageSize,
61  const size_t maxRows,
62  const Data_Namespace::MemoryLevel defaultInsertLevel,
63  const bool uses_foreign_storage)
64  : chunkKeyPrefix_(chunkKeyPrefix)
65  , dataMgr_(dataMgr)
66  , catalog_(catalog)
67  , physicalTableId_(physicalTableId)
68  , shard_(shard)
69  , maxFragmentRows_(std::min<size_t>(maxFragmentRows, maxRows))
70  , pageSize_(pageSize)
71  , numTuples_(0)
72  , maxFragmentId_(-1)
73  , maxChunkSize_(maxChunkSize)
74  , maxRows_(maxRows)
75  , fragmenterType_("insert_order")
76  , defaultInsertLevel_(defaultInsertLevel)
77  , uses_foreign_storage_(uses_foreign_storage)
78  , hasMaterializedRowId_(false)
79  , mutex_access_inmem_states(new std::mutex) {
80  // Note that Fragmenter is not passed virtual columns and so should only
81  // find row id column if it is non virtual
82 
83  for (auto colIt = chunkVec.begin(); colIt != chunkVec.end(); ++colIt) {
84  int columnId = colIt->getColumnDesc()->columnId;
85  columnMap_[columnId] = *colIt;
86  if (colIt->getColumnDesc()->columnName == "rowid") {
87  hasMaterializedRowId_ = true;
88  rowIdColId_ = columnId;
89  }
90  }
91  conditionallyInstantiateFileMgrWithParams();
92  getChunkMetadata();
93 }
94 
95 InsertOrderFragmenter::~InsertOrderFragmenter() {}
96 
97 namespace {
98 
103 int compute_device_for_fragment(const int table_id,
104  const int fragment_id,
105  const int num_devices) {
107  return (table_id + fragment_id) % num_devices;
108  } else {
109  return fragment_id % num_devices;
110  }
111 }
112 
113 } // namespace
114 
115 void InsertOrderFragmenter::conditionallyInstantiateFileMgrWithParams() {
116  // Somewhat awkward to do this in Fragmenter, but FileMgrs are not instantiated until
117  // first use by Fragmenter, and until maxRollbackEpochs param, no options were set in
118  // storage per table
119  if (defaultInsertLevel_ == Data_Namespace::MemoryLevel::DISK_LEVEL) {
120  const TableDescriptor* td =
121  catalog_->getMetadataForTable(physicalTableId_, false /*populateFragmenter*/);
122  File_Namespace::FileMgrParams fileMgrParams;
123  fileMgrParams.max_rollback_epochs = td->maxRollbackEpochs;
124  dataMgr_->getGlobalFileMgr()->setFileMgrParams(
125  chunkKeyPrefix_[0], chunkKeyPrefix_[1], fileMgrParams);
126  }
127 }
128 
129 void InsertOrderFragmenter::getChunkMetadata() {
130  if (uses_foreign_storage_ ||
131  defaultInsertLevel_ == Data_Namespace::MemoryLevel::DISK_LEVEL) {
132  // memory-resident tables won't have anything on disk
133  ChunkMetadataVector chunk_metadata;
134  dataMgr_->getChunkMetadataVecForKeyPrefix(chunk_metadata, chunkKeyPrefix_);
135 
136  // data comes like this - database_id, table_id, column_id, fragment_id
137  // but lets sort by database_id, table_id, fragment_id, column_id
138 
139  int fragment_subkey_index = 3;
140  std::sort(chunk_metadata.begin(),
141  chunk_metadata.end(),
142  [&](const auto& pair1, const auto& pair2) {
143  return pair1.first[3] < pair2.first[3];
144  });
145 
146  for (auto chunk_itr = chunk_metadata.begin(); chunk_itr != chunk_metadata.end();
147  ++chunk_itr) {
148  int cur_column_id = chunk_itr->first[2];
149  int cur_fragment_id = chunk_itr->first[fragment_subkey_index];
150 
151  if (fragmentInfoVec_.empty() ||
152  cur_fragment_id != fragmentInfoVec_.back()->fragmentId) {
153  auto new_fragment_info = std::make_unique<Fragmenter_Namespace::FragmentInfo>();
154  CHECK(new_fragment_info);
155  maxFragmentId_ = cur_fragment_id;
156  new_fragment_info->fragmentId = cur_fragment_id;
157  new_fragment_info->setPhysicalNumTuples(chunk_itr->second->numElements);
158  numTuples_ += new_fragment_info->getPhysicalNumTuples();
159  for (const auto level_size : dataMgr_->levelSizes_) {
160  new_fragment_info->deviceIds.push_back(
161  compute_device_for_fragment(physicalTableId_, cur_fragment_id, level_size));
162  }
163  new_fragment_info->shadowNumTuples = new_fragment_info->getPhysicalNumTuples();
164  new_fragment_info->physicalTableId = physicalTableId_;
165  new_fragment_info->shard = shard_;
166  fragmentInfoVec_.emplace_back(std::move(new_fragment_info));
167  } else {
168  if (chunk_itr->second->numElements !=
169  fragmentInfoVec_.back()->getPhysicalNumTuples()) {
170  LOG(FATAL) << "Inconsistency in num tuples within fragment for table " +
171  std::to_string(physicalTableId_) + ", Column " +
172  std::to_string(cur_column_id) + ". Fragment Tuples: " +
174  fragmentInfoVec_.back()->getPhysicalNumTuples()) +
175  ", Chunk Tuples: " +
176  std::to_string(chunk_itr->second->numElements);
177  }
178  }
179  CHECK(fragmentInfoVec_.back().get());
180  fragmentInfoVec_.back().get()->setChunkMetadata(cur_column_id, chunk_itr->second);
181  }
182  }
183 
184  size_t maxFixedColSize = 0;
185 
186  for (auto colIt = columnMap_.begin(); colIt != columnMap_.end(); ++colIt) {
187  auto size = colIt->second.getColumnDesc()->columnType.get_size();
188  if (size == -1) { // variable length
189  varLenColInfo_.insert(std::make_pair(colIt->first, 0));
190  size = 8; // b/c we use this for string and array indices - gross to have magic
191  // number here
192  }
193  CHECK_GE(size, 0);
194  maxFixedColSize = std::max(maxFixedColSize, static_cast<size_t>(size));
195  }
196 
197  // this is maximum number of rows assuming everything is fixed length
198  maxFragmentRows_ = std::min(maxFragmentRows_, maxChunkSize_ / maxFixedColSize);
199 
200  if (!uses_foreign_storage_ && fragmentInfoVec_.size() > 0) {
201  // Now need to get the insert buffers for each column - should be last
202  // fragment
203  int lastFragmentId = fragmentInfoVec_.back()->fragmentId;
204  // TODO: add accessor here for safe indexing
205  int deviceId =
206  fragmentInfoVec_.back()->deviceIds[static_cast<int>(defaultInsertLevel_)];
207  for (auto colIt = columnMap_.begin(); colIt != columnMap_.end(); ++colIt) {
208  ChunkKey insertKey = chunkKeyPrefix_; // database_id and table_id
209  insertKey.push_back(colIt->first); // column id
210  insertKey.push_back(lastFragmentId); // fragment id
211  colIt->second.getChunkBuffer(dataMgr_, insertKey, defaultInsertLevel_, deviceId);
212  auto varLenColInfoIt = varLenColInfo_.find(colIt->first);
213  if (varLenColInfoIt != varLenColInfo_.end()) {
214  varLenColInfoIt->second = colIt->second.getBuffer()->size();
215  }
216  }
217  }
218 }
219 
220 void InsertOrderFragmenter::dropFragmentsToSize(const size_t max_rows) {
221  mapd_unique_lock<mapd_shared_mutex> insert_lock(insertMutex_);
222  dropFragmentsToSizeNoInsertLock(max_rows);
223 }
224 
225 void InsertOrderFragmenter::dropFragmentsToSizeNoInsertLock(const size_t max_rows) {
226  // not safe to call from outside insertData
227  // b/c depends on insertLock around numTuples_
228 
229  // don't ever drop the only fragment!
230  if (numTuples_ == fragmentInfoVec_.back()->getPhysicalNumTuples()) {
231  return;
232  }
233 
234  if (numTuples_ > max_rows) {
235  size_t preNumTuples = numTuples_;
236  vector<int> dropFragIds;
237  size_t targetRows = max_rows * DROP_FRAGMENT_FACTOR;
238  while (numTuples_ > targetRows) {
239  CHECK_GT(fragmentInfoVec_.size(), size_t(0));
240  size_t numFragTuples = fragmentInfoVec_[0]->getPhysicalNumTuples();
241  dropFragIds.push_back(fragmentInfoVec_[0]->fragmentId);
242  fragmentInfoVec_.pop_front();
243  CHECK_GE(numTuples_, numFragTuples);
244  numTuples_ -= numFragTuples;
245  }
246  deleteFragments(dropFragIds);
247  LOG(INFO) << "dropFragmentsToSize, numTuples pre: " << preNumTuples
248  << " post: " << numTuples_ << " maxRows: " << max_rows;
249  }
250 }
251 
252 void InsertOrderFragmenter::deleteFragments(const vector<int>& dropFragIds) {
253  // Fix a verified loophole on sharded logical table which is locked using logical
254  // tableId while it's its physical tables that can come here when fragments overflow
255  // during COPY. Locks on a logical table and its physical tables never intersect, which
256  // means potential races. It'll be an overkill to resolve a logical table to physical
257  // tables in DBHandler, ParseNode or other higher layers where the logical table is
258  // locked with Table Read/Write locks; it's easier to lock the logical table of its
259  // physical tables. A downside of this approach may be loss of parallel execution of
260  // deleteFragments across physical tables. Because deleteFragments is a short in-memory
261  // operation, the loss seems not a big deal.
262  auto chunkKeyPrefix = chunkKeyPrefix_;
263  if (shard_ >= 0) {
264  chunkKeyPrefix[1] = catalog_->getLogicalTableId(chunkKeyPrefix[1]);
265  }
266 
267  // need to keep lock seq as TableLock >> fragmentInfoMutex_ or
268  // SELECT and COPY may enter a deadlock
269  const auto delete_lock =
271 
272  mapd_unique_lock<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
273 
274  for (const auto fragId : dropFragIds) {
275  for (const auto& col : columnMap_) {
276  int colId = col.first;
277  vector<int> fragPrefix = chunkKeyPrefix_;
278  fragPrefix.push_back(colId);
279  fragPrefix.push_back(fragId);
280  dataMgr_->deleteChunksWithPrefix(fragPrefix);
281  }
282  }
283 }
284 
285 void InsertOrderFragmenter::updateColumnChunkMetadata(
286  const ColumnDescriptor* cd,
287  const int fragment_id,
288  const std::shared_ptr<ChunkMetadata> metadata) {
289  // synchronize concurrent accesses to fragmentInfoVec_
290  mapd_unique_lock<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
291 
292  CHECK(metadata.get());
293  auto fragment_info = getFragmentInfo(fragment_id);
294  CHECK(fragment_info);
295  fragment_info->setChunkMetadata(cd->columnId, metadata);
296 }
297 
298 void InsertOrderFragmenter::updateChunkStats(
299  const ColumnDescriptor* cd,
300  std::unordered_map</*fragment_id*/ int, ChunkStats>& stats_map,
301  std::optional<Data_Namespace::MemoryLevel> memory_level) {
302  // synchronize concurrent accesses to fragmentInfoVec_
303  mapd_unique_lock<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
309  if (shard_ >= 0) {
310  LOG(WARNING) << "Skipping chunk stats update for logical table " << physicalTableId_;
311  }
312 
313  CHECK(cd);
314  const auto column_id = cd->columnId;
315  const auto col_itr = columnMap_.find(column_id);
316  CHECK(col_itr != columnMap_.end());
317 
318  for (auto const& fragment : fragmentInfoVec_) {
319  auto stats_itr = stats_map.find(fragment->fragmentId);
320  if (stats_itr != stats_map.end()) {
321  auto chunk_meta_it = fragment->getChunkMetadataMapPhysical().find(column_id);
322  CHECK(chunk_meta_it != fragment->getChunkMetadataMapPhysical().end());
323  ChunkKey chunk_key{catalog_->getCurrentDB().dbId,
324  physicalTableId_,
325  column_id,
326  fragment->fragmentId};
327  auto chunk = Chunk_NS::Chunk::getChunk(cd,
328  &catalog_->getDataMgr(),
329  chunk_key,
330  memory_level.value_or(defaultInsertLevel_),
331  0,
332  chunk_meta_it->second->numBytes,
333  chunk_meta_it->second->numElements);
334  auto buf = chunk->getBuffer();
335  CHECK(buf);
336  if (!buf->hasEncoder()) {
337  throw std::runtime_error("No encoder for chunk " + show_chunk(chunk_key));
338  }
339  auto encoder = buf->getEncoder();
340 
341  auto chunk_stats = stats_itr->second;
342 
343  auto old_chunk_metadata = std::make_shared<ChunkMetadata>();
344  encoder->getMetadata(old_chunk_metadata);
345  auto& old_chunk_stats = old_chunk_metadata->chunkStats;
346 
347  const bool didResetStats = encoder->resetChunkStats(chunk_stats);
348  // Use the logical type to display data, since the encoding should be ignored
349  const auto logical_ti = cd->columnType.is_dict_encoded_string()
352  if (!didResetStats) {
353  VLOG(3) << "Skipping chunk stats reset for " << show_chunk(chunk_key);
354  VLOG(3) << "Max: " << DatumToString(old_chunk_stats.max, logical_ti) << " -> "
355  << DatumToString(chunk_stats.max, logical_ti);
356  VLOG(3) << "Min: " << DatumToString(old_chunk_stats.min, logical_ti) << " -> "
357  << DatumToString(chunk_stats.min, logical_ti);
358  VLOG(3) << "Nulls: " << (chunk_stats.has_nulls ? "True" : "False");
359  continue; // move to next fragment
360  }
361 
362  VLOG(2) << "Resetting chunk stats for " << show_chunk(chunk_key);
363  VLOG(2) << "Max: " << DatumToString(old_chunk_stats.max, logical_ti) << " -> "
364  << DatumToString(chunk_stats.max, logical_ti);
365  VLOG(2) << "Min: " << DatumToString(old_chunk_stats.min, logical_ti) << " -> "
366  << DatumToString(chunk_stats.min, logical_ti);
367  VLOG(2) << "Nulls: " << (chunk_stats.has_nulls ? "True" : "False");
368 
369  // Reset fragment metadata map and set buffer to dirty
370  auto new_metadata = std::make_shared<ChunkMetadata>();
371  // Run through fillChunkStats to ensure any transformations to the raw metadata
372  // values get applied (e.g. for date in days)
373  encoder->getMetadata(new_metadata);
374 
375  fragment->setChunkMetadata(column_id, new_metadata);
376  fragment->shadowChunkMetadataMap =
377  fragment->getChunkMetadataMap(); // TODO(adb): needed?
378  if (defaultInsertLevel_ == Data_Namespace::DISK_LEVEL) {
379  buf->setDirty();
380  }
381  } else {
382  LOG(WARNING) << "No chunk stats update found for fragment " << fragment->fragmentId
383  << ", table " << physicalTableId_ << ", "
384  << ", column " << column_id;
385  }
386  }
387 }
388 
389 FragmentInfo* InsertOrderFragmenter::getFragmentInfo(const int fragment_id) const {
390  auto fragment_it = std::find_if(fragmentInfoVec_.begin(),
391  fragmentInfoVec_.end(),
392  [fragment_id](const auto& fragment) -> bool {
393  return fragment->fragmentId == fragment_id;
394  });
395  CHECK(fragment_it != fragmentInfoVec_.end());
396  return fragment_it->get();
397 }
398 
399 bool InsertOrderFragmenter::isAddingNewColumns(const InsertData& insert_data) const {
400  bool all_columns_already_exist = true, all_columns_are_new = true;
401  for (const auto column_id : insert_data.columnIds) {
402  if (columnMap_.find(column_id) == columnMap_.end()) {
403  all_columns_already_exist = false;
404  } else {
405  all_columns_are_new = false;
406  }
407  }
408  // only one should be TRUE
409  bool either_all_exist_or_all_new = all_columns_already_exist ^ all_columns_are_new;
410  CHECK(either_all_exist_or_all_new);
411  return all_columns_are_new;
412 }
413 
414 void InsertOrderFragmenter::insertData(InsertData& insert_data_struct) {
415  // TODO: this local lock will need to be centralized when ALTER COLUMN is added, bc
416  try {
417  // prevent two threads from trying to insert into the same table simultaneously
418  mapd_unique_lock<mapd_shared_mutex> insertLock(insertMutex_);
419  if (!isAddingNewColumns(insert_data_struct)) {
420  insertDataImpl(insert_data_struct);
421  } else {
422  addColumns(insert_data_struct);
423  }
424  if (defaultInsertLevel_ ==
425  Data_Namespace::DISK_LEVEL) { // only checkpoint if data is resident on disk
426  dataMgr_->checkpoint(
427  chunkKeyPrefix_[0],
428  chunkKeyPrefix_[1]); // need to checkpoint here to remove window for corruption
429  }
430  } catch (...) {
431  auto table_epochs = catalog_->getTableEpochs(insert_data_struct.databaseId,
432  insert_data_struct.tableId);
433  // the statement below deletes *this* object!
434  // relying on exception propagation at this stage
435  // until we can sort this out in a cleaner fashion
436  catalog_->setTableEpochs(insert_data_struct.databaseId, table_epochs);
437  throw;
438  }
439 }
440 
441 void InsertOrderFragmenter::insertDataNoCheckpoint(InsertData& insert_data_struct) {
442  // TODO: this local lock will need to be centralized when ALTER COLUMN is added, bc
443  mapd_unique_lock<mapd_shared_mutex> insertLock(
444  insertMutex_); // prevent two threads from trying to insert into the same table
445  // simultaneously
446  if (!isAddingNewColumns(insert_data_struct)) {
447  insertDataImpl(insert_data_struct);
448  } else {
449  addColumns(insert_data_struct);
450  }
451 }
452 
453 void InsertOrderFragmenter::addColumns(const InsertData& insertDataStruct) {
454  // synchronize concurrent accesses to fragmentInfoVec_
455  mapd_unique_lock<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
456  size_t numRowsLeft = insertDataStruct.numRows;
457  for (const auto columnId : insertDataStruct.columnIds) {
458  CHECK(columnMap_.end() == columnMap_.find(columnId));
459  const auto columnDesc = catalog_->getMetadataForColumn(physicalTableId_, columnId);
460  CHECK(columnDesc);
461  columnMap_.emplace(columnId, Chunk_NS::Chunk(columnDesc));
462  }
463  try {
464  for (auto const& fragmentInfo : fragmentInfoVec_) {
465  fragmentInfo->shadowChunkMetadataMap = fragmentInfo->getChunkMetadataMapPhysical();
466  auto numRowsToInsert = fragmentInfo->getPhysicalNumTuples(); // not getNumTuples()
467  size_t numRowsCanBeInserted;
468  for (size_t i = 0; i < insertDataStruct.columnIds.size(); i++) {
469  auto columnId = insertDataStruct.columnIds[i];
470  auto colDesc = catalog_->getMetadataForColumn(physicalTableId_, columnId);
471  CHECK(colDesc);
472  CHECK(columnMap_.find(columnId) != columnMap_.end());
473 
474  ChunkKey chunkKey = chunkKeyPrefix_;
475  chunkKey.push_back(columnId);
476  chunkKey.push_back(fragmentInfo->fragmentId);
477 
478  auto colMapIt = columnMap_.find(columnId);
479  auto& chunk = colMapIt->second;
480  if (chunk.isChunkOnDevice(
481  dataMgr_,
482  chunkKey,
483  defaultInsertLevel_,
484  fragmentInfo->deviceIds[static_cast<int>(defaultInsertLevel_)])) {
485  dataMgr_->deleteChunksWithPrefix(chunkKey);
486  }
487  chunk.createChunkBuffer(
488  dataMgr_,
489  chunkKey,
490  defaultInsertLevel_,
491  fragmentInfo->deviceIds[static_cast<int>(defaultInsertLevel_)]);
492  chunk.initEncoder();
493 
494  try {
495  DataBlockPtr dataCopy = insertDataStruct.data[i];
496  auto size = colDesc->columnType.get_size();
497  if (0 > size) {
498  std::unique_lock<std::mutex> lck(*mutex_access_inmem_states);
499  varLenColInfo_[columnId] = 0;
500  numRowsCanBeInserted = chunk.getNumElemsForBytesInsertData(
501  dataCopy, numRowsToInsert, 0, maxChunkSize_, true);
502  } else {
503  numRowsCanBeInserted = maxChunkSize_ / size;
504  }
505 
506  // FIXME: abort a case in which new column is wider than existing columns
507  if (numRowsCanBeInserted < numRowsToInsert) {
508  throw std::runtime_error("new column '" + colDesc->columnName +
509  "' wider than existing columns is not supported");
510  }
511 
512  auto chunkMetadata = chunk.appendData(dataCopy, numRowsToInsert, 0, true);
513  fragmentInfo->shadowChunkMetadataMap[columnId] = chunkMetadata;
514 
515  // update total size of var-len column in (actually the last) fragment
516  if (0 > size) {
517  std::unique_lock<std::mutex> lck(*mutex_access_inmem_states);
518  varLenColInfo_[columnId] = chunk.getBuffer()->size();
519  }
520  } catch (...) {
521  dataMgr_->deleteChunksWithPrefix(chunkKey);
522  throw;
523  }
524  }
525  numRowsLeft -= numRowsToInsert;
526  }
527  CHECK(0 == numRowsLeft);
528  } catch (const std::exception& e) {
529  for (const auto columnId : insertDataStruct.columnIds) {
530  columnMap_.erase(columnId);
531  }
532  throw e;
533  }
534 
535  for (auto const& fragmentInfo : fragmentInfoVec_) {
536  fragmentInfo->setChunkMetadataMap(fragmentInfo->shadowChunkMetadataMap);
537  }
538 }
539 
540 void InsertOrderFragmenter::dropColumns(const std::vector<int>& columnIds) {
541  // prevent concurrent insert rows and drop column
542  mapd_unique_lock<mapd_shared_mutex> insertLock(insertMutex_);
543  // synchronize concurrent accesses to fragmentInfoVec_
544  mapd_unique_lock<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
545  for (auto const& fragmentInfo : fragmentInfoVec_) {
546  fragmentInfo->shadowChunkMetadataMap = fragmentInfo->getChunkMetadataMapPhysical();
547  }
548 
549  for (const auto columnId : columnIds) {
550  auto cit = columnMap_.find(columnId);
551  if (columnMap_.end() != cit) {
552  columnMap_.erase(cit);
553  }
554 
555  vector<int> fragPrefix = chunkKeyPrefix_;
556  fragPrefix.push_back(columnId);
557  dataMgr_->deleteChunksWithPrefix(fragPrefix);
558 
559  for (const auto& fragmentInfo : fragmentInfoVec_) {
560  auto cmdit = fragmentInfo->shadowChunkMetadataMap.find(columnId);
561  if (fragmentInfo->shadowChunkMetadataMap.end() != cmdit) {
562  fragmentInfo->shadowChunkMetadataMap.erase(cmdit);
563  }
564  }
565  }
566  for (const auto& fragmentInfo : fragmentInfoVec_) {
567  fragmentInfo->setChunkMetadataMap(fragmentInfo->shadowChunkMetadataMap);
568  }
569 }
570 
571 bool InsertOrderFragmenter::hasDeletedRows(const int delete_column_id) {
572  mapd_shared_lock<mapd_shared_mutex> read_lock(fragmentInfoMutex_);
573 
574  for (auto const& fragment : fragmentInfoVec_) {
575  auto chunk_meta_it = fragment->getChunkMetadataMapPhysical().find(delete_column_id);
576  CHECK(chunk_meta_it != fragment->getChunkMetadataMapPhysical().end());
577  const auto& chunk_stats = chunk_meta_it->second->chunkStats;
578  if (chunk_stats.max.tinyintval == 1) {
579  return true;
580  }
581  }
582  return false;
583 }
584 
585 void InsertOrderFragmenter::insertDataImpl(InsertData& insert_data) {
586  // populate deleted system column if it should exist, as it will not come from client
587  std::unique_ptr<int8_t[]> data_for_deleted_column;
588  for (const auto& cit : columnMap_) {
589  if (cit.second.getColumnDesc()->isDeletedCol) {
590  data_for_deleted_column.reset(new int8_t[insert_data.numRows]);
591  memset(data_for_deleted_column.get(), 0, insert_data.numRows);
592  insert_data.data.emplace_back(DataBlockPtr{data_for_deleted_column.get()});
593  insert_data.columnIds.push_back(cit.second.getColumnDesc()->columnId);
594  insert_data.is_default.push_back(false);
595  break;
596  }
597  }
598  CHECK(insert_data.is_default.size() == insert_data.columnIds.size());
599  std::unordered_map<int, int> inverseInsertDataColIdMap;
600  for (size_t insertId = 0; insertId < insert_data.columnIds.size(); ++insertId) {
601  inverseInsertDataColIdMap.insert(
602  std::make_pair(insert_data.columnIds[insertId], insertId));
603  }
604 
605  size_t numRowsLeft = insert_data.numRows;
606  size_t numRowsInserted = 0;
607  vector<DataBlockPtr> dataCopy =
608  insert_data.data; // bc append data will move ptr forward and this violates
609  // constness of InsertData
610  if (numRowsLeft <= 0) {
611  return;
612  }
613 
614  FragmentInfo* currentFragment{nullptr};
615 
616  // Access to fragmentInfoVec_ is protected as we are under the insertMutex_ lock but it
617  // feels fragile
618  if (fragmentInfoVec_.empty()) { // if no fragments exist for table
619  currentFragment = createNewFragment(defaultInsertLevel_);
620  } else {
621  currentFragment = fragmentInfoVec_.back().get();
622  }
623  CHECK(currentFragment);
624 
625  size_t startFragment = fragmentInfoVec_.size() - 1;
626 
627  while (numRowsLeft > 0) { // may have to create multiple fragments for bulk insert
628  // loop until done inserting all rows
629  CHECK_LE(currentFragment->shadowNumTuples, maxFragmentRows_);
630  size_t rowsLeftInCurrentFragment =
631  maxFragmentRows_ - currentFragment->shadowNumTuples;
632  size_t numRowsToInsert = min(rowsLeftInCurrentFragment, numRowsLeft);
633  if (rowsLeftInCurrentFragment != 0) {
634  for (auto& varLenColInfoIt : varLenColInfo_) {
635  CHECK_LE(varLenColInfoIt.second, maxChunkSize_);
636  size_t bytesLeft = maxChunkSize_ - varLenColInfoIt.second;
637  auto insertIdIt = inverseInsertDataColIdMap.find(varLenColInfoIt.first);
638  if (insertIdIt != inverseInsertDataColIdMap.end()) {
639  auto colMapIt = columnMap_.find(varLenColInfoIt.first);
640  numRowsToInsert = std::min(numRowsToInsert,
641  colMapIt->second.getNumElemsForBytesInsertData(
642  dataCopy[insertIdIt->second],
643  numRowsToInsert,
644  numRowsInserted,
645  bytesLeft,
646  insert_data.is_default[insertIdIt->second]));
647  }
648  }
649  }
650 
651  if (rowsLeftInCurrentFragment == 0 || numRowsToInsert == 0) {
652  currentFragment = createNewFragment(defaultInsertLevel_);
653  if (numRowsInserted == 0) {
654  startFragment++;
655  }
656  rowsLeftInCurrentFragment = maxFragmentRows_;
657  for (auto& varLenColInfoIt : varLenColInfo_) {
658  varLenColInfoIt.second = 0; // reset byte counter
659  }
660  numRowsToInsert = min(rowsLeftInCurrentFragment, numRowsLeft);
661  for (auto& varLenColInfoIt : varLenColInfo_) {
662  CHECK_LE(varLenColInfoIt.second, maxChunkSize_);
663  size_t bytesLeft = maxChunkSize_ - varLenColInfoIt.second;
664  auto insertIdIt = inverseInsertDataColIdMap.find(varLenColInfoIt.first);
665  if (insertIdIt != inverseInsertDataColIdMap.end()) {
666  auto colMapIt = columnMap_.find(varLenColInfoIt.first);
667  numRowsToInsert = std::min(numRowsToInsert,
668  colMapIt->second.getNumElemsForBytesInsertData(
669  dataCopy[insertIdIt->second],
670  numRowsToInsert,
671  numRowsInserted,
672  bytesLeft,
673  insert_data.is_default[insertIdIt->second]));
674  }
675  }
676  }
677 
678  CHECK_GT(numRowsToInsert, size_t(0)); // would put us into an endless loop as we'd
679  // never be able to insert anything
680 
681  {
682  mapd_unique_lock<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
683  // for each column, append the data in the appropriate insert buffer
684  for (size_t i = 0; i < insert_data.columnIds.size(); ++i) {
685  int columnId = insert_data.columnIds[i];
686  auto colMapIt = columnMap_.find(columnId);
687  CHECK(colMapIt != columnMap_.end());
688  currentFragment->shadowChunkMetadataMap[columnId] = colMapIt->second.appendData(
689  dataCopy[i], numRowsToInsert, numRowsInserted, insert_data.is_default[i]);
690  auto varLenColInfoIt = varLenColInfo_.find(columnId);
691  if (varLenColInfoIt != varLenColInfo_.end()) {
692  varLenColInfoIt->second = colMapIt->second.getBuffer()->size();
693  }
694  }
695  if (hasMaterializedRowId_) {
696  size_t startId = maxFragmentRows_ * currentFragment->fragmentId +
697  currentFragment->shadowNumTuples;
698  auto row_id_data = std::make_unique<int64_t[]>(numRowsToInsert);
699  for (size_t i = 0; i < numRowsToInsert; ++i) {
700  row_id_data[i] = i + startId;
701  }
702  DataBlockPtr rowIdBlock;
703  rowIdBlock.numbersPtr = reinterpret_cast<int8_t*>(row_id_data.get());
704  auto colMapIt = columnMap_.find(rowIdColId_);
705  currentFragment->shadowChunkMetadataMap[rowIdColId_] =
706  colMapIt->second.appendData(rowIdBlock, numRowsToInsert, numRowsInserted);
707  }
708 
709  currentFragment->shadowNumTuples =
710  fragmentInfoVec_.back()->getPhysicalNumTuples() + numRowsToInsert;
711  numRowsLeft -= numRowsToInsert;
712  numRowsInserted += numRowsToInsert;
713  for (auto partIt = fragmentInfoVec_.begin() + startFragment;
714  partIt != fragmentInfoVec_.end();
715  ++partIt) {
716  auto fragment_ptr = partIt->get();
717  fragment_ptr->setPhysicalNumTuples(fragment_ptr->shadowNumTuples);
718  fragment_ptr->setChunkMetadataMap(fragment_ptr->shadowChunkMetadataMap);
719  }
720  }
721  }
722  numTuples_ += insert_data.numRows;
723  dropFragmentsToSizeNoInsertLock(maxRows_);
724 }
725 
726 FragmentInfo* InsertOrderFragmenter::createNewFragment(
727  const Data_Namespace::MemoryLevel memoryLevel) {
728  // also sets the new fragment as the insertBuffer for each column
729 
730  maxFragmentId_++;
731  auto newFragmentInfo = std::make_unique<FragmentInfo>();
732  newFragmentInfo->fragmentId = maxFragmentId_;
733  newFragmentInfo->shadowNumTuples = 0;
734  newFragmentInfo->setPhysicalNumTuples(0);
735  for (const auto levelSize : dataMgr_->levelSizes_) {
736  newFragmentInfo->deviceIds.push_back(compute_device_for_fragment(
737  physicalTableId_, newFragmentInfo->fragmentId, levelSize));
738  }
739  newFragmentInfo->physicalTableId = physicalTableId_;
740  newFragmentInfo->shard = shard_;
741 
742  for (map<int, Chunk>::iterator colMapIt = columnMap_.begin();
743  colMapIt != columnMap_.end();
744  ++colMapIt) {
745  ChunkKey chunkKey = chunkKeyPrefix_;
746  chunkKey.push_back(colMapIt->second.getColumnDesc()->columnId);
747  chunkKey.push_back(maxFragmentId_);
748  colMapIt->second.createChunkBuffer(
749  dataMgr_,
750  chunkKey,
751  memoryLevel,
752  newFragmentInfo->deviceIds[static_cast<int>(memoryLevel)],
753  pageSize_);
754  colMapIt->second.initEncoder();
755  }
756 
757  mapd_lock_guard<mapd_shared_mutex> writeLock(fragmentInfoMutex_);
758  fragmentInfoVec_.push_back(std::move(newFragmentInfo));
759  return fragmentInfoVec_.back().get();
760 }
761 
762 TableInfo InsertOrderFragmenter::getFragmentsForQuery() {
763  mapd_shared_lock<mapd_shared_mutex> readLock(fragmentInfoMutex_);
764  TableInfo queryInfo;
765  queryInfo.chunkKeyPrefix = chunkKeyPrefix_;
766  // right now we don't test predicate, so just return (copy of) all fragments
767  bool fragmentsExist = false;
768  if (fragmentInfoVec_.empty()) {
769  // If we have no fragments add a dummy empty fragment to make the executor
770  // not have separate logic for 0-row tables
771  int maxFragmentId = 0;
772  FragmentInfo emptyFragmentInfo;
773  emptyFragmentInfo.fragmentId = maxFragmentId;
774  emptyFragmentInfo.shadowNumTuples = 0;
775  emptyFragmentInfo.setPhysicalNumTuples(0);
776  emptyFragmentInfo.deviceIds.resize(dataMgr_->levelSizes_.size());
777  emptyFragmentInfo.physicalTableId = physicalTableId_;
778  emptyFragmentInfo.shard = shard_;
779  queryInfo.fragments.push_back(emptyFragmentInfo);
780  } else {
781  fragmentsExist = true;
782  std::for_each(
783  fragmentInfoVec_.begin(),
784  fragmentInfoVec_.end(),
785  [&queryInfo](const auto& fragment_owned_ptr) {
786  queryInfo.fragments.emplace_back(*fragment_owned_ptr); // makes a copy
787  });
788  }
789  readLock.unlock();
790  queryInfo.setPhysicalNumTuples(0);
791  auto partIt = queryInfo.fragments.begin();
792  if (fragmentsExist) {
793  while (partIt != queryInfo.fragments.end()) {
794  if (partIt->getPhysicalNumTuples() == 0) {
795  // this means that a concurrent insert query inserted tuples into a new fragment
796  // but when the query came in we didn't have this fragment. To make sure we
797  // don't mess up the executor we delete this fragment from the metadatamap
798  // (fixes earlier bug found 2015-05-08)
799  partIt = queryInfo.fragments.erase(partIt);
800  } else {
801  queryInfo.setPhysicalNumTuples(queryInfo.getPhysicalNumTuples() +
802  partIt->getPhysicalNumTuples());
803  ++partIt;
804  }
805  }
806  } else {
807  // We added a dummy fragment and know the table is empty
808  queryInfo.setPhysicalNumTuples(0);
809  }
810  return queryInfo;
811 }
812 
813 } // namespace Fragmenter_Namespace
int32_t maxRollbackEpochs
catalog_(nullptr)
bool g_use_table_device_offset
std::vector< int > ChunkKey
Definition: types.h:37
std::string DatumToString(Datum d, const SQLTypeInfo &ti)
Definition: Datum.cpp:356
class for a per-database catalog. also includes metadata for the current database and the current use...
Definition: Catalog.h:102
#define LOG(tag)
Definition: Logger.h:194
static WriteLock getWriteLockForTable(const Catalog_Namespace::Catalog &cat, const std::string &table_name)
Definition: LockMgrImpl.h:155
DEVICE void sort(ARGS &&...args)
Definition: gpu_enabled.h:105
#define CHECK_GE(x, y)
Definition: Logger.h:216
SQLTypeInfo get_logical_type_info(const SQLTypeInfo &type_info)
Definition: sqltypes.h:911
std::vector< bool > is_default
Definition: Fragmenter.h:66
std::vector< FragmentInfo > fragments
Definition: Fragmenter.h:160
std::vector< int > chunkKeyPrefix
Definition: Fragmenter.h:159
#define CHECK_GT(x, y)
Definition: Logger.h:215
std::string to_string(char const *&&v)
std::string show_chunk(const ChunkKey &key)
Definition: types.h:85
int tableId
identifies the database into which the data is being inserted
Definition: Fragmenter.h:61
size_t getPhysicalNumTuples() const
Definition: Fragmenter.h:153
size_t numRows
a vector of column ids for the row(s) being inserted
Definition: Fragmenter.h:63
Used by Fragmenter classes to store info about each fragment - the fragment id and number of tuples(r...
Definition: Fragmenter.h:77
std::vector< std::pair< ChunkKey, std::shared_ptr< ChunkMetadata >>> ChunkMetadataVector
static std::shared_ptr< Chunk > getChunk(const ColumnDescriptor *cd, DataMgr *data_mgr, const ChunkKey &key, const MemoryLevel mem_level, const int deviceId, const size_t num_bytes, const size_t num_elems)
Definition: Chunk.cpp:28
An AbstractBuffer is a unit of data management for a data manager.
specifies the content in-memory of a row in the column metadata table
#define CHECK_LE(x, y)
Definition: Logger.h:214
std::vector< DataBlockPtr > data
the number of rows being inserted
Definition: Fragmenter.h:64
mapd_shared_lock< mapd_shared_mutex > read_lock
bool g_enable_watchdog false
Definition: Execute.cpp:76
#define CHECK(condition)
Definition: Logger.h:203
void setPhysicalNumTuples(const size_t physNumTuples)
Definition: Fragmenter.h:155
#define DROP_FRAGMENT_FACTOR
void setPhysicalNumTuples(const size_t physNumTuples)
Definition: Fragmenter.h:107
FileBuffer Chunk
A Chunk is the fundamental unit of execution in Map-D.
Definition: FileMgr.h:68
The data to be inserted using the fragment manager.
Definition: Fragmenter.h:59
bool is_dict_encoded_string() const
Definition: sqltypes.h:526
SQLTypeInfo columnType
int8_t * numbersPtr
Definition: sqltypes.h:220
std::vector< int > columnIds
identifies the table into which the data is being inserted
Definition: Fragmenter.h:62
#define VLOG(n)
Definition: Logger.h:297
int compute_device_for_fragment(const int table_id, const int fragment_id, const int num_devices)