Move query result helper class to maxsql

Added some asserts to ensure the class is used correctly.
This commit is contained in:
Esa Korhonen
2019-01-09 17:50:20 +02:00
parent 07cbda7771
commit b4d91d4b9a
8 changed files with 230 additions and 190 deletions

View File

@ -14,6 +14,7 @@
#include <maxsql/ccdefs.hh>
#include <string>
#include <unordered_map>
#include <mysql.h>
namespace maxsql
@ -51,4 +52,91 @@ void mysql_set_log_statements(bool enable);
* @return True, if statements are logged, false otherwise.
*/
bool mysql_get_log_statements();
/**
* Helper class for simplifying working with resultsets.
*/
class QueryResult
{
QueryResult(const QueryResult&) = delete;
QueryResult& operator=(const QueryResult&) = delete;
public:
/**
* Construct a new resultset.
*
* @param resultset The results from mysql_query(). Must not be NULL.
*/
QueryResult(MYSQL_RES* resultset);
~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 next_row() has not been called yet or all rows have been processed.
*/
int64_t get_current_row_index() const;
/**
* How many columns the result set has.
*
* @return Column count
*/
int64_t get_col_count() const;
/**
* How many rows does the result set have?
*
* @return The number of rows
*/
int64_t get_row_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 std::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
*/
std::string get_string(int64_t column_ind) const;
/**
* Read a non-negative integer value from the current row and given column.
*
* @param column_ind Column index
* @return Value as integer. 0 or greater indicates success, -1 is returned if the data
* could not be parsed or the result was negative.
*/
int64_t get_uint(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 = NULL; // Underlying result set, freed at dtor.
std::unordered_map<std::string, int64_t> m_col_indexes; // Map of column name -> index
MYSQL_ROW m_rowdata = NULL; // Data for current row
int64_t m_current_row_ind = -1;// Index of current row
};
}