aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Core/PostgreSQL/PoolWithFailover.h
blob: 7a924e8953c04444ace808e121ae8e554ef7bb79 (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
72
#pragma once

#include "clickhouse_config.h"

#if USE_LIBPQXX


#include "ConnectionHolder.h"
#include <mutex>
#include <Poco/Util/AbstractConfiguration.h>
#include <Storages/ExternalDataSourceConfiguration.h>
#include <Storages/StoragePostgreSQL.h>


static constexpr inline auto POSTGRESQL_POOL_DEFAULT_SIZE = 16;
static constexpr inline auto POSTGRESQL_POOL_WAIT_TIMEOUT = 5000;
static constexpr inline auto POSTGRESQL_POOL_WITH_FAILOVER_DEFAULT_MAX_TRIES = 5;

namespace postgres
{

class PoolWithFailover
{

using RemoteDescription = std::vector<std::pair<String, uint16_t>>;

public:
    PoolWithFailover(
        const DB::ExternalDataSourcesConfigurationByPriority & configurations_by_priority,
        size_t pool_size,
        size_t pool_wait_timeout,
        size_t max_tries_,
        bool auto_close_connection_);

    explicit PoolWithFailover(
        const DB::StoragePostgreSQL::Configuration & configuration,
        size_t pool_size,
        size_t pool_wait_timeout,
        size_t max_tries_,
        bool auto_close_connection_);

    PoolWithFailover(const PoolWithFailover & other) = delete;

    ConnectionHolderPtr get();

private:
    struct PoolHolder
    {
        ConnectionInfo connection_info;
        PoolPtr pool;

        PoolHolder(const ConnectionInfo & connection_info_, size_t pool_size)
            : connection_info(connection_info_), pool(std::make_shared<Pool>(pool_size)) {}
    };

    /// Highest priority is 0, the bigger the number in map, the less the priority
    using Replicas = std::vector<PoolHolder>;
    using ReplicasWithPriority = std::map<size_t, Replicas>;

    ReplicasWithPriority replicas_with_priority;
    size_t pool_wait_timeout;
    size_t max_tries;
    bool auto_close_connection;
    std::mutex mutex;
    Poco::Logger * log = &Poco::Logger::get("PostgreSQLConnectionPool");
};

using PoolWithFailoverPtr = std::shared_ptr<PoolWithFailover>;

}

#endif