MXS-1703 Add convenience function + class for querying and storing results

An object of the class is returned as an auto_ptr to simplify memory management.
This commit is contained in:
Esa Korhonen
2018-03-22 14:15:35 +02:00
parent 3b26db8e01
commit a4a5641f5b
4 changed files with 187 additions and 8 deletions

View File

@ -71,3 +71,79 @@ string get_connection_errors(const ServerVector& servers);
* @return Server names
*/
string monitored_servers_to_string(const ServerVector& array);
/**
* Helper class for simplifying working with resultsets. Used in MariaDBServer.
*/
class QueryResult
{
// These need to be banned to avoid premature destruction.
QueryResult(const QueryResult&) = delete;
QueryResult& operator = (const QueryResult&) = delete;
public:
QueryResult(MYSQL_RES* resultset = NULL);
~QueryResult();
/**
* Advance to next row. Affects all result returning functions.
*
* @return True if the next row has data, false if the current row was the last one.
*/
bool next_row();
/**
* Get the index of the current row.
*
* @return Current row index, or -1 if no data or next_row() has not been called yet.
*/
int64_t get_row_index() const;
/**
* How many columns the result set has.
*
* @return Column count, or -1 if no data.
*/
int64_t get_column_count() const;
/**
* Get a numeric index for a column name. May give wrong results if column names are not unique.
*
* @param col_name Column name
* @return Index or -1 if not found.
*/
int64_t get_col_index(const string& col_name) const;
/**
* Read a string value from the current row and given column. Empty string and (null) are both interpreted
* as the empty string.
*
* @param column_ind Column index
* @return Value as string
*/
string get_string(int64_t column_ind) const;
/**
* Read an integer value from the current row and given column. No error checking is done on the parsing.
* The parsing is performed by @c strtoll(), so the caller may check errno for errors.
*
* @param column_ind Column index
* @return Value as integer
*/
int64_t get_int(int64_t column_ind) const;
/**
* Read a boolean value from the current row and given column.
*
* @param column_ind Column index
* @return Value as boolean. Returns true if the text is either 'Y' or '1'.
*/
bool get_bool(int64_t column_ind) const;
private:
MYSQL_RES* m_resultset; // Underlying result set, freed at dtor.
std::tr1::unordered_map<string, int64_t> m_col_indexes; // Map of column name -> index
int64_t m_columns; // How many columns does the data have. Usually equal to column index map size.
MYSQL_ROW m_rowdata; // Data for current row
int64_t m_current_row; // Index of current row
};