aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Core/PostgreSQL/Connection.h
blob: 8d3d08b9a991da043de0c230f56b7263c6040b34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#pragma once

#include "clickhouse_config.h"

#if USE_LIBPQXX

#error #include <pqxx/pqxx>
#include <Core/Types.h>
#include <boost/noncopyable.hpp>

/** Methods to work with PostgreSQL connection object.
 * Should only be used in case there has to be a single connection object, which
 * is long-lived and there are no concurrent connection queries.
 */

namespace Poco { class Logger; }

namespace pqxx
{
    using ConnectionPtr = std::unique_ptr<pqxx::connection>;
}

namespace postgres
{

struct ConnectionInfo
{
    String connection_string;
    String host_port; /// For logs.
};

class Connection : private boost::noncopyable
{
public:
    explicit Connection(
        const ConnectionInfo & connection_info_,
        bool replication_ = false,
        size_t num_tries = 3);

    void execWithRetry(const std::function<void(pqxx::nontransaction &)> & exec);

    pqxx::connection & getRef();

    void connect();

    void updateConnection();

    void tryUpdateConnection();

    bool isConnected() const { return connection != nullptr && connection->is_open(); }

    const ConnectionInfo & getConnectionInfo() { return connection_info; }

    String getInfoForLog() const { return connection_info.host_port; }

private:

    pqxx::ConnectionPtr connection;
    ConnectionInfo connection_info;

    bool replication;
    size_t num_tries;

    Poco::Logger * log;
};

using ConnectionPtr = std::unique_ptr<Connection>;

}

#endif