From: Andrei Pavel Date: Mon, 15 Feb 2021 19:02:22 +0000 (+0200) Subject: [#1708] MySqlConnection:rawStatement() X-Git-Tag: Kea-1.9.5~36 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f16d07754acf77f3d268bd1ccb7bd82c55c53f92;p=thirdparty%2Fkea.git [#1708] MySqlConnection:rawStatement() used to run any statement that has no placeholder question mark where you would normally bind variables --- diff --git a/src/lib/mysql/mysql_connection.cc b/src/lib/mysql/mysql_connection.cc index 4d205ce14a..c70d9f0e28 100644 --- a/src/lib/mysql/mysql_connection.cc +++ b/src/lib/mysql/mysql_connection.cc @@ -437,5 +437,31 @@ MySqlConnection::rollback() { } } +std::vector> +MySqlConnection::rawStatement(std::string const& statement) const { + // Execute a SQL statement. + if (mysql_query(mysql_, statement.c_str())) { + isc_throw(DbOperationError, statement << ": " << mysql_error(mysql_)); + } + + // Get a result set. + MySqlResult result(mysql_use_result(mysql_)); + + // Fetch a result set. + std::vector> output; + size_t r(0); + MYSQL_ROW row; + size_t const column_count(mysql_num_fields(result.result_)); + while ((row = mysql_fetch_row(result.result_)) != NULL) { + output.push_back(std::vector()); + for (size_t i = 0; i < column_count; ++i) { + output[r].push_back(row[i]); + } + ++r; + } + + return output; +} + } // namespace isc::db } // namespace isc diff --git a/src/lib/mysql/mysql_connection.h b/src/lib/mysql/mysql_connection.h index c48221f1c5..6583898fcf 100644 --- a/src/lib/mysql/mysql_connection.h +++ b/src/lib/mysql/mysql_connection.h @@ -67,6 +67,19 @@ private: MYSQL_STMT* statement_; ///< Statement for which results are freed }; +/// @brief RAII wrapper oer MYSQL_RES obtained from MySQL library functions like +/// mysql_use_result(). +struct MySqlResult { + MySqlResult(MYSQL_RES* result) : result_(result) { + } + + ~MySqlResult() { + mysql_free_result(result_); + } + + MYSQL_RES* const result_; +}; + /// @brief MySQL Selection Statements /// /// Each statement is associated with an index, which is used to reference the @@ -565,6 +578,20 @@ public: return (static_cast(mysql_stmt_affected_rows(statements_[index]))); } + /// @brief Run a raw, unprepared statement. + /// + /// This is useful when running statements that can't be parametrized with a + /// question mark in place of a binded variable e.g. "SHOW GLOBAL VARIABLES" + /// and thus cannot be prepared beforehand. All the results are string, the + /// output should be the same as that which one would see in a mysql command + /// line client. + /// + /// @param statement the statement in string form + /// @throw DbOperationError if the statement could not be run + /// @return the list of rows, each row consisting of a list of values for + /// each column + std::vector> + rawStatement(std::string const& statement) const; /// @brief Commit Transactions ///