OmniSciDB  95562058bd
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
import_export::QueryExporterGDAL Class Reference

#include <QueryExporterGDAL.h>

+ Inheritance diagram for import_export::QueryExporterGDAL:
+ Collaboration diagram for import_export::QueryExporterGDAL:

Public Member Functions

 QueryExporterGDAL (const FileType file_type)
 
 QueryExporterGDAL ()=delete
 
 ~QueryExporterGDAL ()
 
void beginExport (const std::string &file_path, const std::string &layer_name, const CopyParams &copy_params, const std::vector< TargetMetaInfo > &column_infos, const FileCompression file_compression, const ArrayNullHandling array_null_handling) final
 
void exportResults (const std::vector< AggregatedResult > &query_results) final
 
void endExport () final
 
- Public Member Functions inherited from import_export::QueryExporter
 QueryExporter (const FileType file_type)
 
 QueryExporter ()=delete
 
virtual ~QueryExporter ()
 

Private Member Functions

void cleanUp ()
 

Private Attributes

CopyParams copy_params_
 
GDALDataset * gdal_dataset_
 
OGRLayer * ogr_layer_
 
std::vector< int > field_indices_
 
ArrayNullHandling array_null_handling_
 

Additional Inherited Members

- Public Types inherited from import_export::QueryExporter
enum  FileType { FileType::kCSV, FileType::kGeoJSON, FileType::kGeoJSONL, FileType::kShapefile }
 
enum  FileCompression { FileCompression::kNone, FileCompression::kGZip, FileCompression::kZip }
 
enum  ArrayNullHandling { ArrayNullHandling::kAbortWithWarning, ArrayNullHandling::kExportSentinels, ArrayNullHandling::kExportZeros, ArrayNullHandling::kNullEntireField }
 
- Static Public Member Functions inherited from import_export::QueryExporter
static std::unique_ptr
< QueryExporter
create (const FileType file_type)
 
- Protected Member Functions inherited from import_export::QueryExporter
void validateFileExtensions (const std::string &file_path, const std::string &file_type, const std::unordered_set< std::string > &valid_extensions) const
 
std::string safeColumnName (const std::string &resname, const int column_index)
 
- Protected Attributes inherited from import_export::QueryExporter
const FileType file_type_
 

Detailed Description

Definition at line 31 of file QueryExporterGDAL.h.

Constructor & Destructor Documentation

import_export::QueryExporterGDAL::QueryExporterGDAL ( const FileType  file_type)
explicit
import_export::QueryExporterGDAL::QueryExporterGDAL ( )
delete
import_export::QueryExporterGDAL::~QueryExporterGDAL ( )

Definition at line 42 of file QueryExporterGDAL.cpp.

References cleanUp().

42  {
43  cleanUp();
44 }

+ Here is the call graph for this function:

Member Function Documentation

void import_export::QueryExporterGDAL::beginExport ( const std::string &  file_path,
const std::string &  layer_name,
const CopyParams copy_params,
const std::vector< TargetMetaInfo > &  column_infos,
const FileCompression  file_compression,
const ArrayNullHandling  array_null_handling 
)
finalvirtual

Implements import_export::QueryExporter.

Definition at line 159 of file QueryExporterGDAL.cpp.

References array_null_handling_, CHECK, cleanUp(), import_export::anonymous_namespace{QueryExporterGDAL.cpp}::compression_implemented, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::compression_prefix, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::compression_suffix, copy_params_, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::driver_names, field_indices_, import_export::QueryExporter::file_type_, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::file_type_names, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::file_type_valid_extensions, logger::filename(), gdal_dataset_, logger::INFO, import_export::GDAL::init(), kLINESTRING, kMULTIPOLYGON, import_export::QueryExporter::kNone, kPOINT, kPOLYGON, LOG, ogr_layer_, import_export::QueryExporter::safeColumnName(), SCI, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::sql_type_info_to_ogr_field_type(), to_string(), and import_export::QueryExporter::validateFileExtensions().

164  {
165  validateFileExtensions(file_path,
168 
169  // lazy init GDAL
170  GDAL::init();
171 
172  // capture these
173  copy_params_ = copy_params;
174  array_null_handling_ = array_null_handling;
175 
176  try {
177  // determine OGR geometry type and SRID and validate other column types
178  OGRwkbGeometryType ogr_geometry_type = wkbUnknown;
179  int num_geo_columns = 0;
180  int geo_column_srid = 0;
181  uint32_t num_columns = 0;
182  std::string geo_column_name;
183  for (auto const& column_info : column_infos) {
184  auto const& type_info = column_info.get_type_info();
185  if (type_info.is_geometry()) {
186  switch (type_info.get_type()) {
187  case kPOINT:
188  ogr_geometry_type = wkbPoint;
189  break;
190  case kLINESTRING:
191  ogr_geometry_type = wkbLineString;
192  break;
193  case kPOLYGON:
194  ogr_geometry_type = wkbPolygon;
195  break;
196  case kMULTIPOLYGON:
197  ogr_geometry_type = wkbMultiPolygon;
198  break;
199  default:
200  CHECK(false);
201  }
202  geo_column_srid = type_info.get_output_srid();
203  geo_column_name = safeColumnName(column_info.get_resname(), num_columns + 1);
204  num_geo_columns++;
205  } else {
206  auto column_name = safeColumnName(column_info.get_resname(), num_columns + 1);
207  // this will throw if column type is unsupported for this file type
208  sql_type_info_to_ogr_field_type(column_name, type_info, file_type_);
209  }
210  num_columns++;
211  }
212  if (num_geo_columns != 1) {
213  throw std::runtime_error("File type '" +
214  std::string(file_type_names[SCI(file_type_)]) +
215  "' requires exactly one geo column in query results");
216  }
217 
218  // validate SRID
219  if (geo_column_srid <= 0) {
220  throw std::runtime_error("Geo column '" + geo_column_name + "' has invalid SRID (" +
221  std::to_string(geo_column_srid) +
222  "). Use ST_SetSRID() in query to override.");
223  }
224 
225  // get driver
226  auto const& driver_name = driver_names[SCI(file_type_)];
227  auto gdal_driver = GetGDALDriverManager()->GetDriverByName(driver_name);
228  if (gdal_driver == nullptr) {
229  throw std::runtime_error("Failed to find Driver '" + std::string(driver_name) +
230  "'");
231  }
232 
233  // compression?
234  auto gdal_file_path{file_path};
235  auto user_file_path{file_path};
236  if (file_compression != FileCompression::kNone) {
237  auto impl = compression_implemented[SCI(file_type_)][SCI(file_compression)];
238  if (!impl) {
239  // @TODO(se) implement more compression options
240  throw std::runtime_error(
241  "Selected file compression option not yet supported for file type '" +
242  std::string(file_type_names[SCI(file_type_)]) + "'");
243  }
244  gdal_file_path.insert(0, compression_prefix[SCI(file_compression)]);
245  gdal_file_path.append(compression_suffix[SCI(file_compression)]);
246  user_file_path.append(compression_suffix[SCI(file_compression)]);
247  }
248 
249  // delete any existing file(s) (with and without compression suffix)
250  // GeoJSON driver occasionally refuses to overwrite
251  auto remove_file = [](const std::string& filename) {
252  if (boost::filesystem::exists(filename)) {
253  LOG(INFO) << "Deleting existing file '" << filename << "'";
254  boost::filesystem::remove(filename);
255  }
256  };
257  remove_file(file_path);
258  remove_file(user_file_path);
259 
260  LOG(INFO) << "Exporting to file '" << user_file_path << "'";
261 
262  // create dataset
263  gdal_dataset_ =
264  gdal_driver->Create(gdal_file_path.c_str(), 0, 0, 0, GDT_Unknown, NULL);
265  if (gdal_dataset_ == nullptr) {
266  throw std::runtime_error("Failed to create File '" + file_path + "'");
267  }
268 
269  // create spatial reference
270  OGRSpatialReference ogr_spatial_reference;
271  if (ogr_spatial_reference.importFromEPSG(geo_column_srid)) {
272  throw std::runtime_error("Failed to create Spatial Reference for SRID " +
273  std::to_string(geo_column_srid) + "");
274  }
275 #if GDAL_VERSION_MAJOR >= 3
276  ogr_spatial_reference.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
277 #endif
278 
279  // create layer
280  ogr_layer_ = gdal_dataset_->CreateLayer(
281  layer_name.c_str(), &ogr_spatial_reference, ogr_geometry_type, NULL);
282  if (ogr_layer_ == nullptr) {
283  throw std::runtime_error("Failed to create Layer '" + layer_name + "'");
284  }
285 
286  // create fields
287  int column_index = 0;
288  int field_index = 0;
289  field_indices_.resize(num_columns);
290  for (auto const& column_info : column_infos) {
291  auto column_name = safeColumnName(column_info.get_resname(), column_index + 1);
292  // create fields for non-geo columns
293  auto const& type_info = column_info.get_type_info();
294  if (!type_info.is_geometry()) {
295  OGRFieldDefn field_defn(
296  column_name.c_str(),
297  sql_type_info_to_ogr_field_type(column_name, type_info, file_type_));
298  if (ogr_layer_->CreateField(&field_defn) != OGRERR_NONE) {
299  throw std::runtime_error("Failed to create Field '" + column_name + "'");
300  }
301  field_indices_[column_index] = field_index;
302  field_index++;
303  } else {
304  field_indices_[column_index] = -1;
305  }
306  column_index++;
307  }
308  } catch (std::exception& e) {
309  LOG(INFO) << "GDAL Query Export failed to start: " << e.what();
310  cleanUp();
311  throw;
312  }
313 }
std::string filename(char const *path)
Definition: Logger.cpp:62
static constexpr std::array< std::array< bool, 3 >, 4 > compression_implemented
#define LOG(tag)
Definition: Logger.h:188
std::string safeColumnName(const std::string &resname, const int column_index)
static void init()
Definition: GDAL.cpp:56
#define SCI(x)
std::string to_string(char const *&&v)
static constexpr std::array< const char *, 3 > compression_prefix
OGRFieldType sql_type_info_to_ogr_field_type(const std::string &name, const SQLTypeInfo &type_info, const QueryExporter::FileType file_type)
static constexpr std::array< const char *, 4 > driver_names
static constexpr std::array< const char *, 3 > compression_suffix
static constexpr std::array< const char *, 4 > file_type_names
#define CHECK(condition)
Definition: Logger.h:197
static std::array< std::unordered_set< std::string >, 4 > file_type_valid_extensions
void validateFileExtensions(const std::string &file_path, const std::string &file_type, const std::unordered_set< std::string > &valid_extensions) const

+ Here is the call graph for this function:

void import_export::QueryExporterGDAL::cleanUp ( )
private

Definition at line 46 of file QueryExporterGDAL.cpp.

References field_indices_, gdal_dataset_, and ogr_layer_.

Referenced by beginExport(), endExport(), exportResults(), and ~QueryExporterGDAL().

46  {
47  // close dataset
48  if (gdal_dataset_) {
49  GDALClose(gdal_dataset_);
50  gdal_dataset_ = nullptr;
51  }
52 
53  // forget layer
54  ogr_layer_ = nullptr;
55 
56  // forget field indices
57  field_indices_.clear();
58 }

+ Here is the caller graph for this function:

void import_export::QueryExporterGDAL::endExport ( )
finalvirtual

Implements import_export::QueryExporter.

Definition at line 707 of file QueryExporterGDAL.cpp.

References cleanUp().

707  {
708  cleanUp();
709 }

+ Here is the call graph for this function:

void import_export::QueryExporterGDAL::exportResults ( const std::vector< AggregatedResult > &  query_results)
finalvirtual

Implements import_export::QueryExporter.

Definition at line 639 of file QueryExporterGDAL.cpp.

References array_null_handling_, CHECK, cleanUp(), field_indices_, ResultSet::GeoTargetValue, logger::INFO, import_export::anonymous_namespace{QueryExporterGDAL.cpp}::insert_array_column(), import_export::anonymous_namespace{QueryExporterGDAL.cpp}::insert_geo_column(), import_export::anonymous_namespace{QueryExporterGDAL.cpp}::insert_scalar_column(), LOG, ogr_layer_, and import_export::QueryExporter::safeColumnName().

640  {
641  try {
642  for (auto const& agg_result : query_results) {
643  auto results = agg_result.rs;
644  auto const& targets = agg_result.targets_meta;
645 
646  // configure ResultSet to return geo as raw data
647  results->setGeoReturnType(ResultSet::GeoReturnType::GeoTargetValue);
648 
649  while (true) {
650  auto const crt_row = results->getNextRow(true, true);
651  if (crt_row.empty()) {
652  break;
653  }
654 
655  // create feature for this row
656  auto ogr_feature = OGRFeature::CreateFeature(ogr_layer_->GetLayerDefn());
657  CHECK(ogr_feature);
658 
659  // destroy feature on exiting this scope
660  ScopeGuard destroy_feature = [ogr_feature] {
661  OGRFeature::DestroyFeature(ogr_feature);
662  };
663 
664  for (size_t i = 0; i < results->colCount(); ++i) {
665  auto const tv = crt_row[i];
666  auto const& ti = targets[i].get_type_info();
667  auto const column_name = safeColumnName(targets[i].get_resname(), i + 1);
668  auto const field_index = field_indices_[i];
669 
670  // insert this column into the feature
671  auto const scalar_tv = boost::get<ScalarTargetValue>(&tv);
672  if (scalar_tv) {
673  insert_scalar_column(scalar_tv, ti, field_index, ogr_feature);
674  } else {
675  auto const array_tv = boost::get<ArrayTargetValue>(&tv);
676  if (array_tv) {
677  insert_array_column(array_tv,
678  ti,
679  field_index,
680  ogr_feature,
681  column_name,
683  } else {
684  auto const geo_tv = boost::get<GeoTargetValue>(&tv);
685  if (geo_tv && geo_tv->is_initialized()) {
686  insert_geo_column(geo_tv, ti, field_index, ogr_feature);
687  } else {
688  ogr_feature->SetGeometry(nullptr);
689  }
690  }
691  }
692  }
693 
694  // add feature to layer
695  if (ogr_layer_->CreateFeature(ogr_feature) != OGRERR_NONE) {
696  throw std::runtime_error("Failed to create Feature");
697  }
698  }
699  }
700  } catch (std::exception& e) {
701  LOG(INFO) << "GDAL Query Export failed: " << e.what();
702  cleanUp();
703  throw;
704  }
705 }
#define LOG(tag)
Definition: Logger.h:188
void insert_array_column(const ArrayTargetValue *array_tv, const SQLTypeInfo &ti, const int field_index, OGRFeature *ogr_feature, const std::string &column_name, QueryExporter::ArrayNullHandling array_null_handling)
std::string safeColumnName(const std::string &resname, const int column_index)
void insert_geo_column(const GeoTargetValue *geo_tv, const SQLTypeInfo &ti, const int field_index, OGRFeature *ogr_feature)
void insert_scalar_column(const ScalarTargetValue *scalar_tv, const SQLTypeInfo &ti, const int field_index, OGRFeature *ogr_feature)
#define CHECK(condition)
Definition: Logger.h:197

+ Here is the call graph for this function:

Member Data Documentation

ArrayNullHandling import_export::QueryExporterGDAL::array_null_handling_
private

Definition at line 51 of file QueryExporterGDAL.h.

Referenced by beginExport(), and exportResults().

CopyParams import_export::QueryExporterGDAL::copy_params_
private

Definition at line 47 of file QueryExporterGDAL.h.

Referenced by beginExport().

std::vector<int> import_export::QueryExporterGDAL::field_indices_
private

Definition at line 50 of file QueryExporterGDAL.h.

Referenced by beginExport(), cleanUp(), and exportResults().

GDALDataset* import_export::QueryExporterGDAL::gdal_dataset_
private

Definition at line 48 of file QueryExporterGDAL.h.

Referenced by beginExport(), and cleanUp().

OGRLayer* import_export::QueryExporterGDAL::ogr_layer_
private

Definition at line 49 of file QueryExporterGDAL.h.

Referenced by beginExport(), cleanUp(), and exportResults().


The documentation for this class was generated from the following files: