pgLab/src/pglab/ASyncDBConnection.h

82 lines
2.4 KiB
C
Raw Normal View History

#ifndef ASYNCDBCONNECTION_H
#define ASYNCDBCONNECTION_H
#include "Pgsql_Connection.h"
#include "Pgsql_Params.h"
#include "ConnectionConfig.h"
#include <QElapsedTimer>
// #include <functional>
// #include <condition_variable>
#include <mutex>
// #include <queue>
// #include <vector>
// #include <thread>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/io_service.hpp>
2017-02-02 07:18:44 +01:00
/** \brief Class that handles asynchronous execution of queries.
*
* Queries are passed to this class with a routine to call on completion
* when the result is on that routine is called.
*/
class ASyncDBConnection {
public:
enum class State {
NotConnected,
Connecting,
Connected, ///< connected and idle
QuerySend, ///< connected query send expecting result
CancelSend, ///< cancel send expecting result
Terminating ///< shutting down
};
using on_result_callback = std::function<void(std::shared_ptr<Pgsql::Result>, qint64)>;
using on_state_callback = std::function<void(State)>;
using on_notice_callback = std::function<void(Pgsql::ErrorDetails)>;
explicit ASyncDBConnection(boost::asio::io_service &ios);
~ASyncDBConnection();
State state() const;
void setupConnection(const ConnectionConfig &config);
void closeConnection();
void setStateCallback(on_state_callback state_callback);
void setNoticeCallback(on_notice_callback notice_callback);
/** Sends command to the server.
When the result is in on_result will be called directly within the thread.
If the command gives multiple results on_result will be called for each result.
*/
bool send(const std::string &command, on_result_callback on_result);
bool send(const std::string &command, Pgsql::Params params, on_result_callback on_result);
bool cancel();
private:
Pgsql::Connection m_connection;
boost::asio::ip::tcp::socket m_asioSock;
ConnectionConfig m_config;
State m_state = State::NotConnected;
Pgsql::Canceller m_canceller;
struct {
std::mutex m_mutex;
on_state_callback m_func;
} m_stateCallback;
struct {
std::mutex m_mutex;
on_notice_callback m_func;
} m_noticeCallback;
QElapsedTimer m_timer;
void async_connect_handler(boost::system::error_code ec, std::size_t s);
void async_query_handler(boost::system::error_code ec, std::size_t s, on_result_callback on_result);
void doStateCallback(State state);
void processNotice(const PGresult *result);
};
#endif // ASYNCDBCONNECTION_H