fgerlits commented on a change in pull request #1004:
URL: https://github.com/apache/nifi-minifi-cpp/pull/1004#discussion_r601357523



##########
File path: extensions/sql/patch/iodbc.patch
##########
@@ -0,0 +1,12 @@
+diff -rupN orig/configure.ac patched/configure.ac
+--- orig/configure.ac  2019-07-23 13:37:26.000000000 +0200
++++ patched/configure.ac       2021-02-15 12:43:35.000000000 +0100
+@@ -398,7 +398,7 @@ if test x"$libltdl_cv_uscore" = xyes; th
+ #include <dlfcn.h>
+ #endif
+ 
+-#include <stdio.h>
++#include <stdlib.h>

Review comment:
       can you add a link somewhere to the issue or PR related to this patch, 
so we'll know when we can remove it?

##########
File path: extensions/sql/processors/ExecuteSQL.cpp
##########
@@ -51,72 +41,87 @@ namespace processors {
 
 const std::string ExecuteSQL::ProcessorName("ExecuteSQL");
 
-const core::Property ExecuteSQL::s_sqlSelectQuery(
-  core::PropertyBuilder::createProperty("SQL select 
query")->isRequired(true)->withDescription(
+const core::Property ExecuteSQL::SQLSelectQuery(
+  core::PropertyBuilder::createProperty("SQL select query")
+  ->withDescription(
     "The SQL select query to execute. The query can be empty, a constant 
value, or built from attributes using Expression Language. "
     "If this property is specified, it will be used regardless of the content 
of incoming flowfiles. "
     "If this property is empty, the content of the incoming flow file is 
expected to contain a valid SQL select query, to be issued by the processor to 
the database. "
-    "Note that Expression Language is not evaluated for flow file 
contents.")->supportsExpressionLanguage(true)->build());
+    "Note that Expression Language is not evaluated for flow file contents.")
+  ->supportsExpressionLanguage(true)->build());
 
-const core::Property ExecuteSQL::s_maxRowsPerFlowFile(
-  core::PropertyBuilder::createProperty("Max Rows Per Flow 
File")->isRequired(true)->withDefaultValue<int>(0)->withDescription(
-    "The maximum number of result rows that will be included intoi a flow 
file. If zero then all will be placed into the flow 
file")->supportsExpressionLanguage(true)->build());
+const core::Relationship ExecuteSQL::Success("success", "Successfully created 
FlowFile from SQL query result set.");
 
-const core::Relationship ExecuteSQL::s_success("success", "Successfully 
created FlowFile from SQL query result set.");
-
-static const std::string ResultRowCount = "executesql.row.count";
+const std::string ExecuteSQL::RESULT_ROW_COUNT = "executesql.row.count";
+const std::string ExecuteSQL::INPUT_FLOW_FILE_UUID = "input.flowfile.uuid";
 
 ExecuteSQL::ExecuteSQL(const std::string& name, utils::Identifier uuid)
-  : SQLProcessor(name, uuid), max_rows_(0) {
+  : SQLProcessor(name, uuid, logging::LoggerFactory<ExecuteSQL>::getLogger()) {
 }
 
-ExecuteSQL::~ExecuteSQL() = default;
-
 void ExecuteSQL::initialize() {
   //! Set the supported properties
-  setSupportedProperties({ dbControllerService(), outputFormat(), 
s_sqlSelectQuery, s_maxRowsPerFlowFile});
+  setSupportedProperties({ DBControllerService, OutputFormat, SQLSelectQuery, 
MaxRowsPerFlowFile});
 
   //! Set the supported relationships
-  setSupportedRelationships({ s_success });
+  setSupportedRelationships({ Success });
 }
 
-void ExecuteSQL::processOnSchedule(core::ProcessContext &context) {
-  initOutputFormat(context);
+void ExecuteSQL::processOnSchedule(core::ProcessContext& context) {
+  context.getProperty(OutputFormat.getName(), output_format_);
 
-  context.getProperty(s_sqlSelectQuery.getName(), sqlSelectQuery_);
-  context.getProperty(s_maxRowsPerFlowFile.getName(), max_rows_);
+  max_rows_ = [&] {
+    uint64_t max_rows;
+    context.getProperty(MaxRowsPerFlowFile.getName(), max_rows);
+    return gsl::narrow<size_t>(max_rows);
+  }();
 }
 
-void ExecuteSQL::processOnTrigger(core::ProcessSession& session) {
-  auto statement = connection_->prepareStatement(sqlSelectQuery_);
+void ExecuteSQL::processOnTrigger(core::ProcessContext& context, 
core::ProcessSession& session) {
+  auto input_flow_file = session.get();
 
-  auto rowset = statement->execute();
-
-  int count = 0;
-  size_t rowCount = 0;
-  sql::JSONSQLWriter sqlWriter(isJSONPretty());
-  sql::SQLRowsetProcessor sqlRowsetProcessor(rowset, { &sqlWriter });
+  std::string query;
+  if (!context.getProperty(SQLSelectQuery, query, input_flow_file)) {
+    if (!input_flow_file) {
+      throw Exception(PROCESSOR_EXCEPTION,
+                      "No incoming FlowFile and the \"SQL select query\" 
processor property is not specified");

Review comment:
       minor, but using `SQLSelectQuery.getName()` would be better

##########
File path: extensions/sql/processors/FlowFileSource.cpp
##########
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "FlowFileSource.h"
+
+#include "FlowFile.h"
+#include "data/JSONSQLWriter.h"
+
+namespace org {
+namespace apache {
+namespace nifi {
+namespace minifi {
+namespace processors {
+
+const core::Property FlowFileSource::OutputFormat(
+  core::PropertyBuilder::createProperty("Output Format")
+  ->isRequired(true)
+  ->supportsExpressionLanguage(true)
+  ->withDefaultValue(toString(OutputType::JSONPretty))
+  ->withAllowableValues<std::string>(OutputType::values())
+  ->withDescription("Set the output format type.")->build());
+
+const core::Property FlowFileSource::MaxRowsPerFlowFile(
+  core::PropertyBuilder::createProperty("Max Rows Per Flow File")
+  ->isRequired(true)
+  ->supportsExpressionLanguage(true)
+  ->withDefaultValue<uint64_t>(0)
+  ->withDescription(
+      "The maximum number of result rows that will be included in a single 
FlowFile. This will allow you to break up very large result sets into multiple 
FlowFiles. "
+      "If the value specified is zero, then all rows are returned in a single 
FlowFile.")->build());
+
+const std::string FlowFileSource::FRAGMENT_IDENTIFIER = "fragment.identifier";
+const std::string FlowFileSource::FRAGMENT_COUNT = "fragment.count";
+const std::string FlowFileSource::FRAGMENT_INDEX = "fragment.index";
+
+void FlowFileSource::FlowFileGenerator::endProcessBatch(Progress progress) {
+  if (progress == Progress::DONE) {
+    // annotate the flow files with the fragment.count
+    std::string fragment_count = std::to_string(flow_files_.size());
+    for (const auto& flow_file : flow_files_) {
+      flow_file->addAttribute(FRAGMENT_COUNT, fragment_count);
+    }
+    return;
+  }

Review comment:
       It looks like `endProcessBatch(CONTINUE)` and `endProcessBatch(DONE)` 
are completely different functions with no common code in any of the 
implementations.  It might be simpler if they were separate virtual functions, 
e.g. `endProcessBatch()` and `finishProcessing()`.

##########
File path: extensions/sql/processors/ExecuteSQL.cpp
##########
@@ -51,72 +41,87 @@ namespace processors {
 
 const std::string ExecuteSQL::ProcessorName("ExecuteSQL");
 
-const core::Property ExecuteSQL::s_sqlSelectQuery(
-  core::PropertyBuilder::createProperty("SQL select 
query")->isRequired(true)->withDescription(
+const core::Property ExecuteSQL::SQLSelectQuery(
+  core::PropertyBuilder::createProperty("SQL select query")
+  ->withDescription(
     "The SQL select query to execute. The query can be empty, a constant 
value, or built from attributes using Expression Language. "
     "If this property is specified, it will be used regardless of the content 
of incoming flowfiles. "
     "If this property is empty, the content of the incoming flow file is 
expected to contain a valid SQL select query, to be issued by the processor to 
the database. "
-    "Note that Expression Language is not evaluated for flow file 
contents.")->supportsExpressionLanguage(true)->build());
+    "Note that Expression Language is not evaluated for flow file contents.")
+  ->supportsExpressionLanguage(true)->build());
 
-const core::Property ExecuteSQL::s_maxRowsPerFlowFile(
-  core::PropertyBuilder::createProperty("Max Rows Per Flow 
File")->isRequired(true)->withDefaultValue<int>(0)->withDescription(
-    "The maximum number of result rows that will be included intoi a flow 
file. If zero then all will be placed into the flow 
file")->supportsExpressionLanguage(true)->build());
+const core::Relationship ExecuteSQL::Success("success", "Successfully created 
FlowFile from SQL query result set.");
 
-const core::Relationship ExecuteSQL::s_success("success", "Successfully 
created FlowFile from SQL query result set.");
-
-static const std::string ResultRowCount = "executesql.row.count";
+const std::string ExecuteSQL::RESULT_ROW_COUNT = "executesql.row.count";
+const std::string ExecuteSQL::INPUT_FLOW_FILE_UUID = "input.flowfile.uuid";
 
 ExecuteSQL::ExecuteSQL(const std::string& name, utils::Identifier uuid)
-  : SQLProcessor(name, uuid), max_rows_(0) {
+  : SQLProcessor(name, uuid, logging::LoggerFactory<ExecuteSQL>::getLogger()) {
 }
 
-ExecuteSQL::~ExecuteSQL() = default;
-
 void ExecuteSQL::initialize() {
   //! Set the supported properties
-  setSupportedProperties({ dbControllerService(), outputFormat(), 
s_sqlSelectQuery, s_maxRowsPerFlowFile});
+  setSupportedProperties({ DBControllerService, OutputFormat, SQLSelectQuery, 
MaxRowsPerFlowFile});
 
   //! Set the supported relationships
-  setSupportedRelationships({ s_success });
+  setSupportedRelationships({ Success });
 }
 
-void ExecuteSQL::processOnSchedule(core::ProcessContext &context) {
-  initOutputFormat(context);
+void ExecuteSQL::processOnSchedule(core::ProcessContext& context) {
+  context.getProperty(OutputFormat.getName(), output_format_);
 
-  context.getProperty(s_sqlSelectQuery.getName(), sqlSelectQuery_);
-  context.getProperty(s_maxRowsPerFlowFile.getName(), max_rows_);
+  max_rows_ = [&] {
+    uint64_t max_rows;
+    context.getProperty(MaxRowsPerFlowFile.getName(), max_rows);
+    return gsl::narrow<size_t>(max_rows);
+  }();
 }
 
-void ExecuteSQL::processOnTrigger(core::ProcessSession& session) {
-  auto statement = connection_->prepareStatement(sqlSelectQuery_);
+void ExecuteSQL::processOnTrigger(core::ProcessContext& context, 
core::ProcessSession& session) {
+  auto input_flow_file = session.get();
 
-  auto rowset = statement->execute();
-
-  int count = 0;
-  size_t rowCount = 0;
-  sql::JSONSQLWriter sqlWriter(isJSONPretty());
-  sql::SQLRowsetProcessor sqlRowsetProcessor(rowset, { &sqlWriter });
+  std::string query;
+  if (!context.getProperty(SQLSelectQuery, query, input_flow_file)) {
+    if (!input_flow_file) {
+      throw Exception(PROCESSOR_EXCEPTION,
+                      "No incoming FlowFile and the \"SQL select query\" 
processor property is not specified");
+    }
+    logger_->log_debug("Using the contents of the flow file as the SQL 
statement");
+    auto buffer = std::make_shared<io::BufferStream>();
+    InputStreamPipe content_reader{buffer};
+    session.read(input_flow_file, &content_reader);
+    query = std::string{reinterpret_cast<const char *>(buffer->getBuffer()), 
buffer->size()};
+  }
+  if (query.empty()) {
+    throw Exception(PROCESSOR_EXCEPTION, "Empty SQL statement");
+  }
+
+  auto row_set = 
connection_->prepareStatement(query)->execute(collectArguments(input_flow_file));
+
+  sql::JSONSQLWriter sqlWriter{output_format_ == OutputType::JSONPretty};

Review comment:
       very minor, but I would call this `json_writer`, as it writes JSON, not 
SQL

##########
File path: extensions/sql/processors/FlowFileSource.h
##########
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include <memory>
+
+#include "core/Property.h"
+#include "utils/Enum.h"
+#include "data/SQLRowsetProcessor.h"
+#include "ProcessSession.h"
+#include "data/JSONSQLWriter.h"
+
+namespace org {
+namespace apache {
+namespace nifi {
+namespace minifi {
+namespace processors {
+
+class FlowFileSource {
+ public:
+  static const std::string FRAGMENT_IDENTIFIER;
+  static const std::string FRAGMENT_COUNT;
+  static const std::string FRAGMENT_INDEX;
+
+  static const core::Property OutputFormat;
+  static const core::Property MaxRowsPerFlowFile;
+
+  SMART_ENUM(OutputType,
+    (JSON, "JSON"),
+    (JSONPretty, "JSON-Pretty")
+  )
+
+ protected:
+  class FlowFileGenerator : public sql::SQLRowSubscriber {
+   public:
+    FlowFileGenerator(core::ProcessSession& session, sql::JSONSQLWriter& 
json_writer)
+      : session_(session),
+        json_writer_(json_writer) {}
+
+    void beginProcessBatch() override {
+      current_batch_size_ = 0;
+    }
+    void endProcessBatch(Progress progress) override;
+    void beginProcessRow() override {}
+    void endProcessRow() override {
+      ++current_batch_size_;
+    }
+    void processColumnNames(const std::vector<std::string>& /*names*/) 
override {}
+    void processColumn(const std::string& /*name*/, const std::string& 
/*value*/) override {}
+    void processColumn(const std::string& /*name*/, double /*value*/) override 
{}
+    void processColumn(const std::string& /*name*/, int /*value*/) override {}
+    void processColumn(const std::string& /*name*/, long long /*value*/) 
override {}
+    void processColumn(const std::string& /*name*/, unsigned long long 
/*value*/) override {}
+    void processColumn(const std::string& /*name*/, const char* /*value*/) 
override {}
+
+    std::shared_ptr<core::FlowFile> getLastFlowFile() const {
+      if (!flow_files_.empty()) {
+        return flow_files_.back();
+      }
+      return {};
+    }
+
+    std::vector<std::shared_ptr<core::FlowFile>>& getFlowFiles() {
+      return flow_files_;
+    }
+
+   private:
+    core::ProcessSession& session_;
+    sql::JSONSQLWriter& json_writer_;
+    const utils::Identifier 
batch_id_{utils::IdGenerator::getIdGenerator()->generate()};
+    size_t current_batch_size_{0};

Review comment:
       `current_batch_size_` is not read anywhere, it can be removed

##########
File path: extensions/sql/processors/ExecuteSQL.cpp
##########
@@ -51,72 +41,87 @@ namespace processors {
 
 const std::string ExecuteSQL::ProcessorName("ExecuteSQL");
 
-const core::Property ExecuteSQL::s_sqlSelectQuery(
-  core::PropertyBuilder::createProperty("SQL select 
query")->isRequired(true)->withDescription(
+const core::Property ExecuteSQL::SQLSelectQuery(
+  core::PropertyBuilder::createProperty("SQL select query")
+  ->withDescription(
     "The SQL select query to execute. The query can be empty, a constant 
value, or built from attributes using Expression Language. "
     "If this property is specified, it will be used regardless of the content 
of incoming flowfiles. "
     "If this property is empty, the content of the incoming flow file is 
expected to contain a valid SQL select query, to be issued by the processor to 
the database. "
-    "Note that Expression Language is not evaluated for flow file 
contents.")->supportsExpressionLanguage(true)->build());
+    "Note that Expression Language is not evaluated for flow file contents.")
+  ->supportsExpressionLanguage(true)->build());
 
-const core::Property ExecuteSQL::s_maxRowsPerFlowFile(
-  core::PropertyBuilder::createProperty("Max Rows Per Flow 
File")->isRequired(true)->withDefaultValue<int>(0)->withDescription(
-    "The maximum number of result rows that will be included intoi a flow 
file. If zero then all will be placed into the flow 
file")->supportsExpressionLanguage(true)->build());
+const core::Relationship ExecuteSQL::Success("success", "Successfully created 
FlowFile from SQL query result set.");
 
-const core::Relationship ExecuteSQL::s_success("success", "Successfully 
created FlowFile from SQL query result set.");
-
-static const std::string ResultRowCount = "executesql.row.count";
+const std::string ExecuteSQL::RESULT_ROW_COUNT = "executesql.row.count";
+const std::string ExecuteSQL::INPUT_FLOW_FILE_UUID = "input.flowfile.uuid";
 
 ExecuteSQL::ExecuteSQL(const std::string& name, utils::Identifier uuid)
-  : SQLProcessor(name, uuid), max_rows_(0) {
+  : SQLProcessor(name, uuid, logging::LoggerFactory<ExecuteSQL>::getLogger()) {
 }
 
-ExecuteSQL::~ExecuteSQL() = default;
-
 void ExecuteSQL::initialize() {
   //! Set the supported properties
-  setSupportedProperties({ dbControllerService(), outputFormat(), 
s_sqlSelectQuery, s_maxRowsPerFlowFile});
+  setSupportedProperties({ DBControllerService, OutputFormat, SQLSelectQuery, 
MaxRowsPerFlowFile});
 
   //! Set the supported relationships
-  setSupportedRelationships({ s_success });
+  setSupportedRelationships({ Success });
 }
 
-void ExecuteSQL::processOnSchedule(core::ProcessContext &context) {
-  initOutputFormat(context);
+void ExecuteSQL::processOnSchedule(core::ProcessContext& context) {
+  context.getProperty(OutputFormat.getName(), output_format_);
 
-  context.getProperty(s_sqlSelectQuery.getName(), sqlSelectQuery_);
-  context.getProperty(s_maxRowsPerFlowFile.getName(), max_rows_);
+  max_rows_ = [&] {
+    uint64_t max_rows;
+    context.getProperty(MaxRowsPerFlowFile.getName(), max_rows);
+    return gsl::narrow<size_t>(max_rows);
+  }();
 }
 
-void ExecuteSQL::processOnTrigger(core::ProcessSession& session) {
-  auto statement = connection_->prepareStatement(sqlSelectQuery_);
+void ExecuteSQL::processOnTrigger(core::ProcessContext& context, 
core::ProcessSession& session) {
+  auto input_flow_file = session.get();
 
-  auto rowset = statement->execute();
-
-  int count = 0;
-  size_t rowCount = 0;
-  sql::JSONSQLWriter sqlWriter(isJSONPretty());
-  sql::SQLRowsetProcessor sqlRowsetProcessor(rowset, { &sqlWriter });
+  std::string query;
+  if (!context.getProperty(SQLSelectQuery, query, input_flow_file)) {
+    if (!input_flow_file) {
+      throw Exception(PROCESSOR_EXCEPTION,
+                      "No incoming FlowFile and the \"SQL select query\" 
processor property is not specified");
+    }
+    logger_->log_debug("Using the contents of the flow file as the SQL 
statement");
+    auto buffer = std::make_shared<io::BufferStream>();
+    InputStreamPipe content_reader{buffer};
+    session.read(input_flow_file, &content_reader);
+    query = std::string{reinterpret_cast<const char *>(buffer->getBuffer()), 
buffer->size()};
+  }
+  if (query.empty()) {
+    throw Exception(PROCESSOR_EXCEPTION, "Empty SQL statement");
+  }
+
+  auto row_set = 
connection_->prepareStatement(query)->execute(collectArguments(input_flow_file));
+
+  sql::JSONSQLWriter sqlWriter{output_format_ == OutputType::JSONPretty};
+  FlowFileGenerator flow_file_creator{session, sqlWriter};
+  sql::SQLRowsetProcessor sqlRowsetProcessor(row_set, {sqlWriter, 
flow_file_creator});
 
   // Process rowset.
-  do {
-    rowCount = sqlRowsetProcessor.process(max_rows_ == 0 ? 
std::numeric_limits<size_t>::max() : max_rows_);
-    count++;
-    if (rowCount == 0)
-      break;
-
-    const auto output = sqlWriter.toString();
-    if (!output.empty()) {
-      WriteCallback writer(output);
-      auto newflow = session.create();
-      newflow->addAttribute(ResultRowCount, std::to_string(rowCount));
-      session.write(newflow, &writer);
-      session.transfer(newflow, s_success);
+  while (size_t row_count = sqlRowsetProcessor.process(max_rows_)) {
+    auto new_file = flow_file_creator.getLastFlowFile();
+    new_file->addAttribute(RESULT_ROW_COUNT, std::to_string(row_count));

Review comment:
       it would be useful (at least for the peace of mind of someone reading 
this code) to check that `new_file` is not null




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to