OmniSciDB  72c90bc290
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ParquetImporter.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 "ParquetImporter.h"
18 
19 #include <queue>
20 
21 #include <arrow/filesystem/localfs.h>
22 #include <boost/filesystem.hpp>
23 
24 #include "Catalog/Catalog.h"
25 #include "Catalog/ForeignTable.h"
26 #include "DataMgr/Chunk/Chunk.h"
28 #include "LazyParquetChunkLoader.h"
29 #include "ParquetShared.h"
30 #include "Shared/misc.h"
32 #include "Utils/DdlUtils.h"
33 
34 namespace foreign_storage {
35 
37  public:
38  RowGroupIntervalTracker(const std::set<std::string>& file_paths,
39  FileReaderMap* file_reader_cache,
40  std::shared_ptr<arrow::fs::FileSystem> file_system)
41  : file_paths_(file_paths)
42  , file_reader_cache_(file_reader_cache)
43  , file_system_(file_system)
45  , num_row_groups_(0)
47  , current_file_iter_(file_paths_.begin()) {}
48 
49  std::optional<RowGroupInterval> getNextRowGroupInterval() override {
51  if (filesAreExhausted()) {
52  return {};
53  }
54  return RowGroupInterval{
55  *current_file_iter_, current_row_group_index_, current_row_group_index_};
56  }
57 
58  private:
59  bool filesAreExhausted() { return current_file_iter_ == file_paths_.end(); }
60 
64  return;
65  }
66  if (!is_initialized_) {
68  is_initialized_ = true;
69  } else {
70  if (filesAreExhausted()) { // can be possible if many concurrent requests
71  return;
72  }
73  current_file_iter_++; // advance iterator
74  }
76  if (filesAreExhausted()) {
77  num_row_groups_ = 0;
78  } else {
79  auto file_reader =
81  num_row_groups_ = file_reader->parquet_reader()->metadata()->num_row_groups();
82  }
83  }
84 
85  std::set<std::string> file_paths_;
87  std::shared_ptr<arrow::fs::FileSystem> file_system_;
88 
92  std::set<std::string>::const_iterator current_file_iter_;
93 };
94 
96  public:
97  ParquetImportBatchResult() = default;
98  ParquetImportBatchResult(const ForeignTable* foreign_table,
99  const int db_id,
100  const ForeignTableSchema* schema);
102 
103  std::optional<Fragmenter_Namespace::InsertData> getInsertData() const override;
105 
106  std::pair<std::map<int, Chunk_NS::Chunk>, std::map<int, StringDictionary*>>
107  getChunksAndDictionaries() const;
108 
109  void populateInsertData(const std::map<int, Chunk_NS::Chunk>& chunks);
110  void populateImportStatus(const size_t num_rows_completed,
111  const size_t num_rows_rejected);
112 
113  private:
114  std::optional<Fragmenter_Namespace::InsertData> insert_data_;
115  std::map<int, std::unique_ptr<AbstractBuffer>> import_buffers_; // holds data
116 
118  int db_id_;
121 };
122 
123 void ParquetImportBatchResult::populateImportStatus(const size_t num_rows_completed,
124  const size_t num_rows_rejected) {
125  import_status_.rows_completed = num_rows_completed;
126  import_status_.rows_rejected = num_rows_rejected;
127 }
128 
130  const std::map<int, Chunk_NS::Chunk>& chunks) {
132  size_t num_rows = chunks.begin()->second.getBuffer()->getEncoder()->getNumElems();
133  for (const auto& [column_id, chunk] : chunks) {
134  auto column_descriptor = chunk.getColumnDesc();
135  CHECK(chunk.getBuffer()->getEncoder()->getNumElems() == num_rows);
136  insert_data_->columnIds.emplace_back(column_id);
137  auto buffer = chunk.getBuffer();
138  DataBlockPtr block_ptr;
139  if (column_descriptor->columnType.is_array()) {
140  auto array_buffer = dynamic_cast<TypedParquetStorageBuffer<ArrayDatum>*>(buffer);
141  block_ptr.arraysPtr = array_buffer->getBufferPtr();
142  } else if ((column_descriptor->columnType.is_string() &&
143  !column_descriptor->columnType.is_dict_encoded_string()) ||
144  column_descriptor->columnType.is_geometry()) {
145  auto string_buffer = dynamic_cast<TypedParquetStorageBuffer<std::string>*>(buffer);
146  block_ptr.stringsPtr = string_buffer->getBufferPtr();
147  } else {
148  block_ptr.numbersPtr = buffer->getMemoryPtr();
149  }
150  insert_data_->data.emplace_back(block_ptr);
151  }
152  insert_data_->databaseId = db_id_;
153  insert_data_->tableId = foreign_table_->tableId;
154  insert_data_->is_default.assign(insert_data_->columnIds.size(), false);
155  insert_data_->numRows = num_rows;
156 }
157 
158 std::pair<std::map<int, Chunk_NS::Chunk>, std::map<int, StringDictionary*>>
160  std::map<int, Chunk_NS::Chunk> chunks;
161  std::map<int, StringDictionary*> string_dictionaries;
163 
164  for (const auto column_descriptor : schema_->getLogicalAndPhysicalColumns()) {
165  const bool is_dictionary_encoded_string_column =
166  column_descriptor->columnType.is_dict_encoded_string() ||
167  (column_descriptor->columnType.is_array() &&
168  column_descriptor->columnType.get_elem_type().is_dict_encoded_string());
169 
170  if (is_dictionary_encoded_string_column) {
171  auto dict_descriptor = catalog->getMetadataForDict(
172  column_descriptor->columnType.get_comp_param(), true);
173  CHECK(dict_descriptor);
174  auto string_dictionary = dict_descriptor->stringDict.get();
175  string_dictionaries[column_descriptor->columnId] = string_dictionary;
176  }
177 
178  Chunk_NS::Chunk chunk{column_descriptor};
179  chunk.setBuffer(import_buffers_.at(column_descriptor->columnId).get());
180  if (column_descriptor->columnType.is_varlen_indeed()) {
181  chunk.setIndexBuffer(nullptr); // index buffers are unused
182  }
183  chunk.initEncoder();
184  chunks[column_descriptor->columnId] = chunk;
185  }
186  return {chunks, string_dictionaries};
187 }
188 
190  const int db_id,
191  const ForeignTableSchema* schema)
192  : foreign_table_(foreign_table), db_id_(db_id), schema_(schema) {
193  for (const auto column_descriptor : schema_->getLogicalAndPhysicalColumns()) {
194  if (column_descriptor->columnType.is_array()) {
195  import_buffers_[column_descriptor->columnId] =
196  std::make_unique<TypedParquetStorageBuffer<ArrayDatum>>();
197  } else if ((column_descriptor->columnType.is_string() &&
198  !column_descriptor->columnType.is_dict_encoded_string()) ||
199  column_descriptor->columnType.is_geometry()) {
200  import_buffers_[column_descriptor->columnId] =
201  std::make_unique<TypedParquetStorageBuffer<std::string>>();
202  } else {
203  import_buffers_[column_descriptor->columnId] =
204  std::make_unique<ForeignStorageBuffer>();
205  }
206  }
207 }
208 
209 std::optional<Fragmenter_Namespace::InsertData> ParquetImportBatchResult::getInsertData()
210  const {
211  return insert_data_;
212 }
213 
215  return import_status_;
216 }
217 
219  return schema_->numLogicalColumns();
220 }
221 
222 void ParquetImporter::setNumThreads(const int num_threads) {
223  num_threads_ = num_threads;
224 }
225 
227  : db_id_(-1), foreign_table_(nullptr), num_threads_(1) {}
228 
230  const ForeignTable* foreign_table,
231  const UserMapping* user_mapping)
232  : db_id_(db_id)
233  , foreign_table_(foreign_table)
234  , num_threads_(1)
235  , schema_(std::make_unique<ForeignTableSchema>(db_id, foreign_table))
236  , file_reader_cache_(std::make_unique<FileReaderMap>()) {
237  auto& server_options = foreign_table->foreign_server->options;
238  if (server_options.find(STORAGE_TYPE_KEY)->second == LOCAL_FILE_STORAGE_TYPE) {
239  file_system_ = std::make_shared<arrow::fs::LocalFileSystem>();
240  } else {
241  UNREACHABLE();
242  }
243 }
244 
245 std::set<std::string> ParquetImporter::getAllFilePaths() {
246  auto timer = DEBUG_TIMER(__func__);
247  std::set<std::string> file_paths;
248  auto file_path = getFullFilePath(foreign_table_);
249  arrow::Result<arrow::fs::FileInfo> file_info_result;
250  arrow::Result<std::vector<arrow::fs::FileInfo>> selector_result;
251  {
252  auto get_file_info_timer = DEBUG_TIMER("GetFileInfo-file_info");
253  file_info_result = file_system_->GetFileInfo(file_path);
254  }
255  if (!file_info_result.ok()) {
256  throw_file_access_error(file_path, file_info_result.status().message());
257  } else {
258  auto& file_info = file_info_result.ValueOrDie();
259  if (file_info.type() == arrow::fs::FileType::NotFound) {
260  throw_file_not_found_error(file_path);
261  } else if (file_info.type() == arrow::fs::FileType::File) {
262  file_paths.emplace(file_path);
263  } else {
264  CHECK_EQ(arrow::fs::FileType::Directory, file_info.type());
265  arrow::fs::FileSelector file_selector{};
266  file_selector.base_dir = file_path;
267  file_selector.recursive = true;
268  {
269  auto get_file_info_timer = DEBUG_TIMER("GetFileInfo-selector");
270  selector_result = file_system_->GetFileInfo(file_selector);
271  }
272  if (!selector_result.ok()) {
273  throw_file_access_error(file_path, selector_result.status().message());
274  } else {
275  auto& file_info_vector = selector_result.ValueOrDie();
276  for (const auto& file_info : file_info_vector) {
277  if (file_info.type() == arrow::fs::FileType::File) {
278  file_paths.emplace(file_info.path());
279  }
280  }
281  }
282  }
283  }
284  return file_paths;
285 }
286 
288  UNREACHABLE();
289 }
290 
292  const ChunkToBufferMap& optional_buffers,
293  AbstractBuffer* delete_buffer) {
294  UNREACHABLE();
295 }
296 
298  UNREACHABLE();
299  return {};
300 }
301 
302 std::vector<std::pair<const ColumnDescriptor*, StringDictionary*>>
305 }
306 
307 std::unique_ptr<import_export::ImportBatchResult> ParquetImporter::getNextImportBatch() {
308  {
309  std::unique_lock row_group_interval_tracker_lock(row_group_interval_tracker_mutex_);
311  row_group_interval_tracker_ = std::make_unique<RowGroupIntervalTracker>(
313  }
314  }
315 
316  auto import_batch_result =
317  std::make_unique<ParquetImportBatchResult>(foreign_table_, db_id_, schema_.get());
318  auto [chunks, string_dictionaries] = import_batch_result->getChunksAndDictionaries();
319 
320  {
321  std::unique_lock string_dictionaries_per_column_lock(
323  if (!string_dictionaries_per_column_.size()) {
324  for (const auto& [column_id, dict] : string_dictionaries) {
325  string_dictionaries_per_column_.emplace_back(chunks[column_id].getColumnDesc(),
326  dict);
327  }
328  }
329  }
330 
331  LazyParquetChunkLoader chunk_loader(
333 
334  std::optional<RowGroupInterval> next_row_group;
335  {
336  std::unique_lock row_group_interval_tracker_lock(row_group_interval_tracker_mutex_);
337  next_row_group = row_group_interval_tracker_->getNextRowGroupInterval();
338  }
339  size_t num_rows_completed, num_rows_rejected;
340  if (next_row_group.has_value()) {
341  std::tie(num_rows_completed, num_rows_rejected) = chunk_loader.loadRowGroups(
342  *next_row_group, chunks, *schema_, string_dictionaries, num_threads_);
343  } else {
344  return import_batch_result; // terminate without populating data, read the last row
345  // group
346  }
347 
348  import_batch_result->populateImportStatus(num_rows_completed, num_rows_rejected);
349  import_batch_result->populateInsertData(chunks);
350 
351  return import_batch_result;
352 }
353 
355  const std::string& file_path,
356  const ChunkMetadataVector& chunk_metadata_vector) {
357  UNREACHABLE();
358 }
359 
361  UNREACHABLE();
362  return {};
363 }
364 
365 } // namespace foreign_storage
std::set< std::string > getAllFilePaths()
#define CHECK_EQ(x, y)
Definition: Logger.h:301
std::shared_mutex row_group_interval_tracker_mutex_
void populateImportStatus(const size_t num_rows_completed, const size_t num_rows_rejected)
std::pair< std::map< int, Chunk_NS::Chunk >, std::map< int, StringDictionary * > > getChunksAndDictionaries() const
std::shared_ptr< arrow::fs::FileSystem > file_system_
std::vector< std::string > * stringsPtr
Definition: sqltypes.h:234
void setNumThreads(const int num_threads)
std::unique_ptr< AbstractRowGroupIntervalTracker > row_group_interval_tracker_
std::vector< ArrayDatum > * arraysPtr
Definition: sqltypes.h:235
std::unique_ptr< ForeignTableSchema > schema_
void throw_file_access_error(const std::string &file_path, const std::string &message)
std::optional< Fragmenter_Namespace::InsertData > insert_data_
void restoreDataWrapperInternals(const std::string &file_path, const ChunkMetadataVector &chunk_metadata_vector) override
#define UNREACHABLE()
Definition: Logger.h:338
std::map< ChunkKey, AbstractBuffer * > ChunkToBufferMap
std::shared_mutex string_dictionaries_per_column_mutex_
std::optional< RowGroupInterval > getNextRowGroupInterval() override
std::vector< std::pair< const ColumnDescriptor *, StringDictionary * > > getStringDictionaries() const
void throw_file_not_found_error(const std::string &file_path)
void setBuffer(AbstractBuffer *b)
Definition: Chunk.h:150
This file contains the class specification and related data structures for Catalog.
std::set< std::string >::const_iterator current_file_iter_
static SysCatalog & instance()
Definition: SysCatalog.h:343
const ReaderPtr getOrInsert(const std::string &path, std::shared_ptr< arrow::fs::FileSystem > &file_system)
Definition: ParquetShared.h:70
void populateChunkBuffers(const ChunkToBufferMap &required_buffers, const ChunkToBufferMap &optional_buffers, AbstractBuffer *delete_buffer) override
void populateChunkMetadata(ChunkMetadataVector &chunk_metadata_vector) override
std::unique_lock< T > unique_lock
std::vector< std::pair< ChunkKey, std::shared_ptr< ChunkMetadata >>> ChunkMetadataVector
An AbstractBuffer is a unit of data management for a data manager.
const std::list< const ColumnDescriptor * > & getLogicalAndPhysicalColumns() const
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
std::map< int, std::unique_ptr< AbstractBuffer > > import_buffers_
std::optional< Fragmenter_Namespace::InsertData > getInsertData() const override
std::string getSerializedDataWrapper() const override
void populateInsertData(const std::map< int, Chunk_NS::Chunk > &chunks)
const ForeignTable * foreign_table_
RowGroupIntervalTracker(const std::set< std::string > &file_paths, FileReaderMap *file_reader_cache, std::shared_ptr< arrow::fs::FileSystem > file_system)
import_export::ImportStatus getImportStatus() const override
std::unique_ptr< FileReaderMap > file_reader_cache_
const ForeignServer * foreign_server
Definition: ForeignTable.h:57
bool g_enable_watchdog false
Definition: Execute.cpp:80
#define CHECK(condition)
Definition: Logger.h:291
#define DEBUG_TIMER(name)
Definition: Logger.h:412
The data to be inserted using the fragment manager.
Definition: Fragmenter.h:68
std::shared_ptr< arrow::fs::FileSystem > file_system_
int8_t * numbersPtr
Definition: sqltypes.h:233
std::unique_ptr< import_export::ImportBatchResult > getNextImportBatch()
static std::string getFullFilePath(const ForeignTable *foreign_table)
Returns the path to the source file/dir of the table. Depending on options this may result from a con...
import_export::ImportStatus import_status_
std::vector< std::pair< const ColumnDescriptor *, StringDictionary * > > string_dictionaries_per_column_