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