Mercurial > code
changeset 171:e47c4e9e3f9d
Add SQL drivers
author | David Demelier <markand@malikania.fr> |
---|---|
date | Tue, 10 Sep 2013 17:28:32 +0200 |
parents | fd138f2a9773 |
children | a61cddaf7547 |
files | C++/Driver.cpp C++/Driver.h C++/DriverPG.cpp C++/DriverPG.h |
diffstat | 4 files changed, 803 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/C++/Driver.cpp Tue Sep 10 17:28:32 2013 +0200 @@ -0,0 +1,140 @@ +/* + * Driver.cpp -- generic SQL driver access + * + * Copyright (c) 2013, David Demelier <markand@malikania.fr> + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include <map> +#include <string> +#include <sstream> + +#include "Driver.h" + +/* --------------------------------------------------------- + * Query class + * ---------------------------------------------------------*/ + +Query::Query() +{ +} + +Query::~Query() +{ +} + +void Query::checkValidRequest(int row, const std::string &column, QueryCheck check) +{ + std::ostringstream oss; + + switch (check) { + case QueryCheck::InvalidColumn: + oss << "Invalid column '" << column << "'"; + throw QueryError(oss.str()); + case QueryCheck::InvalidRow: + oss << "Invalid row number '" << row << "'"; + throw QueryError(oss.str()); + case QueryCheck::InvalidType: + oss << "Column " << column; + oss << " type does not match requested type"; + + throw QueryError(oss.str()); + default: + break; + } +} + +bool Query::getBool(int row, const std::string &column) +{ + // Throw an exception on bad arguments + checkValidRequest(row, column, + checkRequest(row, column, ColumnType::Boolean)); + + return checkBool(row, column); +} + +Date Query::getDate(int row, const std::string &column) +{ + // Throw an exception on bad arguments + checkValidRequest(row, column, + checkRequest(row, column, ColumnType::Date)); + + return checkDate(row, column); +} + +double Query::getDouble(int row, const std::string &column) +{ + // Throw an exception on bad arguments + checkValidRequest(row, column, + checkRequest(row, column, ColumnType::Double)); + + return checkDouble(row, column); +} + +int Query::getInt(int row, const std::string &column) +{ + // Throw an exception on bad arguments + checkValidRequest(row, column, + checkRequest(row, column, ColumnType::Integer)); + + return checkInt(row, column); +} + +std::string Query::getString(int row, const std::string &column) +{ + // Throw an exception on bad arguments + checkValidRequest(row, column, + checkRequest(row, column, ColumnType::String)); + + return checkString(row, column); +} + +/* --------------------------------------------------------- + * QueryError class + * --------------------------------------------------------- */ + +QueryError::QueryError() +{ +} + +QueryError::QueryError(const std::string &error) + : m_error(error) +{ +} + +QueryError::~QueryError() +{ +} + +const char *QueryError::what() const throw() +{ + return m_error.c_str(); +} + +/* -------------------------------------------------------- + * Driver class + * -------------------------------------------------------- */ + +Driver::Driver() +{ +} + +Driver::~Driver() +{ +} + +const std::string &Driver::getError() const +{ + return m_error; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/C++/Driver.h Tue Sep 10 17:28:32 2013 +0200 @@ -0,0 +1,296 @@ +/* + * Driver.h -- generic SQL driver access + * + * Copyright (c) 2013, David Demelier <markand@malikania.fr> + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef _DRIVER_H_ +#define _DRIVER_H_ + +#include <iostream> +#include <map> +#include <memory> +#include <string> + +class Query; + +class Date +{ +private: + time_t m_timestamp; + +public: + Date() + { + } + + Date(time_t) + { + } + + ~Date() + { + } +}; + +/** + * @enum ColumnType + * @brief The column type request + * + * Used for the drivers. + */ +enum class ColumnType { + Boolean, //! bool or 0 / 1 + Date, //! date see Common/Date.h + Double, //! double + Integer, //! 32 or 64 bit int + String, //! varchar to std::string +}; + +/** + * @enum QueryCheck + * @brief Result enumeration for check* functions + * + * This is used for the Query drivers check functions so we can now which + * kind of error happened. + */ +enum class QueryCheck { + NoError = 0, //! success + InvalidColumn, //! non existent column + InvalidRow, //! out of range row + InvalidType, //! bad column type requested +}; + +/** + * @class QueryError + * @brief Query exception on driver error + * + * Exception thrown usually when an error appeared in driver. + */ +class QueryError : public std::exception +{ +private: + std::string m_error; +public: + QueryError(); + + QueryError(const std::string &error); + + ~QueryError(); + + virtual const char *what() const throw(); +}; + +/** + * @class Query + * @brief Class for querying the database + */ +class Query { +private: + /** + * Check if the request is valid and throws an exception + * on error. + * + * @param row the row number + * @param column the column name + * @param check the result + * @throw Query::ErrorException on erro + */ + void checkValidRequest(int row, const std::string &column, QueryCheck check); + +protected: + /** + * Check if the request is correct, if the row is not out of range + * if the column exist and if the type is correct. + * + * @param row the row number + * @param column the column name + * @param type the type requested + * @return true if request is correct + */ + virtual QueryCheck checkRequest(int row, const std::string &column, ColumnType type) = 0; + + /** + * Get a bool. + * + * @param row the row number + * @param column the column + * @return the value + */ + virtual bool checkBool(int row, const std::string &column) = 0; + + /** + * Get a Date. + * + * @param row the row number + * @param column the column + * @return the value + */ + virtual Date checkDate(int row, const std::string &column) = 0; + + /** + * Get a double. + * + * @param row the row number + * @param column the column + * @return the value + */ + virtual double checkDouble(int row, const std::string &column) = 0; + + /** + * Get a integer. + * + * @param row the row number + * @param column the column + * @return the value + */ + virtual int checkInt(int row, const std::string &column) = 0; + + /** + * Get a string. + * + * @param row the row number + * @param column the column + * @return the value + */ + virtual std::string checkString(int row, const std::string &column) = 0; + +public: + Query(void); + virtual ~Query(void); + + /** + * Get bool at a specified row / column. + * + * @param row the row number + * @param column the column + * @return a boolean + * @throw Query::ErrorException on error + */ + bool getBool(int row, const std::string &column); + + /** + * Get a Date at a specified row / column. + * + * @param row the row number + * @param column the column + * @return a Date + * @throw Query::ErrorException on error + */ + Date getDate(int row, const std::string &column); + + /** + * Get a double at a specified row / column. + * + * @param row the row number + * @param column the column + * @return a double + * @throw Query::ErrorException on error + */ + double getDouble(int row, const std::string &column); + + /** + * Get an integer at a specified row / column. + * + * @param row the row number + * @param column the column + * @return an integer + * @throw Query::ErrorException on error + */ + int getInt(int row, const std::string &column); + + /** + * Get a string at a specified row / column. + * + * @param row the row number + * @param column the column + * @return a string + * @throw Query::ErrorException on error + */ + std::string getString(int row, const std::string &column); + + /** + * Tells how many rows has been fetched. + * + * @return the number of rows + */ + virtual int countRows(void) = 0; + + /** + * Tells how many number of columns are present for each + * row. + * + * @return the number of columns + */ + virtual int countColumns(void) = 0; + + /** + * Tells if the column is null or not. + * + * @param row the row number + * @param column the column + * @return an true if null + */ + virtual bool isNull(int row, const std::string &column) = 0; + + /** + * Dump all rows and columns. + */ + virtual void dump(void) = 0; +}; + +class Driver { +protected: + std::string m_error; + +public: + typedef std::map<std::string, std::string> Params; + + Driver(); + virtual ~Driver(); + + /** + * Get the error. + * + * @return the error + */ + const std::string & getError() const; + + /** + * Create a synchronous connection, it waits and block until + * the connection is made up to a specified timeout max. + * + * @param params a list of parameters. + */ + virtual bool connect(const Params ¶ms) = 0; + + /** + * Execute a query. + * + * @param query the SQL command + * @return a result + * @throw Query::Exception on failure + */ + virtual std::unique_ptr<Query> query(const std::string &command) = 0; + + /** + * Get the driver connection description. + * + * @return the description + */ + virtual std::string description() const = 0; +}; + +#endif // !_DRIVER_H_
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/C++/DriverPG.cpp Tue Sep 10 17:28:32 2013 +0200 @@ -0,0 +1,248 @@ +/* + * DriverPostgres.cpp -- PostgreSQL driver + * + * Copyright (c) 2013, David Demelier <markand@malikania.fr> + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include <sstream> + +#include "DriverPG.h" + +/* -------------------------------------------------------- + * Query PostgreSQL (protected methods) + * -------------------------------------------------------- */ + +QueryCheck QueryPG::checkRequest(int row, const std::string &column, ColumnType type) +{ + QueryCheck ret = QueryCheck::InvalidType; + Oid pqType; + int colIndex; + bool success = false; + + // Invalid row + if (row >= PQntuples(m_result.get())) + return QueryCheck::InvalidRow; + if ((colIndex = PQfnumber(m_result.get(), column.c_str())) == -1) + return QueryCheck::InvalidColumn; + + pqType = PQftype(m_result.get(), colIndex); + switch (type) { + case ColumnType::Boolean: + success = (pqType == 16); + break; + case ColumnType::Date: + success = (pqType == 1082) || (pqType == 1083) || (pqType == 1114); + break; + case ColumnType::Double: + success = (pqType = 1700) || (pqType == 700) || (pqType == 701); + break; + case ColumnType::Integer: + success = (pqType == 20) || (pqType == 21) || (pqType == 23) || (pqType == 1700); + break; + case ColumnType::String: + success = (pqType == 25) || (pqType == 1042) || (pqType == 1043); + break; + default: + ret = QueryCheck::InvalidType; + } + + // valid type requested? + if (success) + ret = QueryCheck::NoError; + + return ret; +} + +/* -------------------------------------------------------- + * Query PostgreSQL (public methods) + * -------------------------------------------------------- */ + +QueryPG::QueryPG(PostgresResult result) +{ + m_result = std::move(result); +} + +QueryPG::~QueryPG() +{ +} + +int QueryPG::countRows() +{ + return PQntuples(m_result.get()); +} + +int QueryPG::countColumns() +{ + return PQnfields(m_result.get()); +} + +bool QueryPG::checkBool(int row, const std::string &column) +{ + int idx = PQfnumber(m_result.get(), column.c_str()); + std::string code = PQgetvalue(m_result.get(), row, idx); + + return code[0] == 't'; +} + +Date QueryPG::checkDate(int row, const std::string &column) +{ + int idx = PQfnumber(m_result.get(), column.c_str()); + long timestamp = static_cast<long>(time(0)); + + try { + timestamp = std::stol(PQgetvalue(m_result.get(), row, idx)); + } catch (std::invalid_argument) { + } + + return Date(static_cast<time_t>(timestamp)); +} + +double QueryPG::checkDouble(int row, const std::string &column) +{ + int idx = PQfnumber(m_result.get(), column.c_str()); + double d = 0; + + try { + d = std::stod(PQgetvalue(m_result.get(), row, idx)); + } catch (std::invalid_argument) { + } + + return d; +} + +int QueryPG::checkInt(int row, const std::string &column) +{ + int idx = PQfnumber(m_result.get(), column.c_str()); + int i = 0; + + try { + i = std::stoi(PQgetvalue(m_result.get(), row, idx)); + } catch (std::invalid_argument) { + } + + return i; +} + +std::string QueryPG::checkString(int row, const std::string &column) +{ + int idx = PQfnumber(m_result.get(), column.c_str()); + + return std::string(PQgetvalue(m_result.get(), row, idx)); +} + +bool QueryPG::isNull(int row, const std::string &column) +{ + int idx = PQfnumber(m_result.get(), column.c_str()); + + return PQgetisnull(m_result.get(), row, idx) == 1; +} + +void QueryPG::dump(void) +{ + std::cout << "Dumping PostgreSQL result, "; + std::cout << countRows() << " rows, "; + std::cout << countColumns() << " columns" << std::endl; + + for (int r = 0; r < countRows(); ++r) { + std::cout << "Dumping row " << r << std::endl; + std::cout << "==============================" << std::endl; + + for (int c = 0; c < countColumns(); ++c) + { + std::cout << "\t" << PQfname(m_result.get(), c); + std::cout << " = " << PQgetvalue(m_result.get(), r, c) << std::endl; + } + } +} + +/* -------------------------------------------------------- + * Driver PostgreSQL + * -------------------------------------------------------- */ + +DriverPG::DriverPG() +{ +} + +DriverPG::~DriverPG() +{ +} + +std::string DriverPG::convert(Params ¶ms) +{ + std::ostringstream oss; + + oss << "host = " << params["host"] << " "; + oss << "port = " << params["port"] << " "; + oss << "user = " << params["user"] << " "; + oss << "dbname = " << params["database"] << " "; + oss << "password = " << params["password"]; + + return oss.str(); +} + +bool DriverPG::connect(const Params ¶ms) +{ + Params copy = params; + PGconn *conn = PQconnectdb(convert(copy).c_str()); + + if (conn == nullptr) { + m_error = strerror(ENOMEM); + return false; + } + + if (PQstatus(conn) == CONNECTION_BAD) { + m_error = PQerrorMessage(conn); + PQfinish(conn); + + return false; + } + + m_connection = PostgresConn(conn); + + return true; +} + +std::unique_ptr<Query> DriverPG::query(const std::string &cmd) +{ + PGresult *info; + + // If NULL, the libpq said no memory + info = PQexec(m_connection.get(), cmd.c_str()); + if (info == nullptr) + throw QueryError(strerror(ENOMEM)); + + // If an error occured + int errorCode = PQresultStatus(info); + if (errorCode != PGRES_COMMAND_OK && errorCode != PGRES_TUPLES_OK) { + std::string error = PQresultErrorMessage(info); + PQclear(info); + throw QueryError(error); + } + + return std::unique_ptr<Query>(new QueryPG(QueryPG::PostgresResult(info))); +} + +std::string DriverPG::description() const +{ + std::ostringstream oss; + + oss << "Connected on PostgreSQL database: " << std::endl; + oss << " host: " << PQhost(m_connection.get()) << std::endl; + oss << " port: " << PQport(m_connection.get()) << std::endl; + oss << " user: " << PQuser(m_connection.get()) << std::endl; + oss << " database: " << PQdb(m_connection.get()) << std::endl; + + return oss.str(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/C++/DriverPG.h Tue Sep 10 17:28:32 2013 +0200 @@ -0,0 +1,119 @@ +/* + * DriverPostgres.h -- PostgreSQL driver + * + * Copyright (c) 2013, David Demelier <markand@malikania.fr> + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * http://www.postgresql.org/docs/9.2/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS + */ + +#ifndef _DRIVER_PG_H_ +#define _DRIVER_PG_H_ + +#include <map> +#include <memory> +#include <string> + +#include <libpq-fe.h> + +#include "Driver.h" + +/** + * Query implementation for PostgreSQL. + */ +class QueryPG : public Query +{ +public: + struct PQQueryDeleter + { + void operator()(PGresult *result) + { + PQclear(result); + } + }; + + typedef std::unique_ptr<PGresult, PQQueryDeleter> PostgresResult; + +private: + PostgresResult m_result; + +protected: + virtual QueryCheck checkRequest(int row, const std::string &column, ColumnType type); + + virtual Date checkDate(int row, const std::string &column); + + virtual bool checkBool(int row, const std::string &column); + + virtual double checkDouble(int row, const std::string &column); + + virtual int checkInt(int row, const std::string &column); + + virtual std::string checkString(int row, const std::string &column); + + // Avoid copy + QueryPG(const QueryPG &src); + + // Avoid copy + QueryPG & operator=(const QueryPG &src); + +public: + QueryPG(PostgresResult); + ~QueryPG(); + + virtual int countRows(); + + virtual int countColumns(); + + virtual bool isNull(int row, const std::string &column); + + virtual void dump(); +}; + +class DriverPG : public Driver +{ +public: + struct PGDeleter { + void operator()(PGconn *conn) { + PQfinish(conn); + } + }; + + typedef std::unique_ptr<PGconn, PGDeleter> PostgresConn; + +private: + PostgresConn m_connection; + + /** + * Convert the Params from the config + * to the PostgreSQL string. + * + * @param settings the table + * @return a string to be used + */ + std::string convert(Params &settings); + +public: + DriverPG(); + ~DriverPG(); + + virtual bool connect(const Params ¶ms); + + virtual std::unique_ptr<Query> query(const std::string &command); + + virtual std::string description() const; +}; + +#endif // !_DRIVER_PG_H_