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

#include "clickhouse_config.h"

#if USE_LIBPQXX

#error #include <pqxx/pqxx>
#include <Core/Types.h>
#include <base/BorrowedObjectPool.h>
#include "Connection.h"


namespace postgres
{

using Pool = BorrowedObjectPool<ConnectionPtr>;
using PoolPtr = std::shared_ptr<Pool>;

class ConnectionHolder
{

public:
    ConnectionHolder(PoolPtr pool_, ConnectionPtr connection_, bool auto_close_)
        : pool(pool_)
        , connection(std::move(connection_))
        , auto_close(auto_close_)
    {}

    ConnectionHolder(const ConnectionHolder & other) = delete;

    void setBroken() { is_broken = true; }

    ~ConnectionHolder()
    {
        if (auto_close)
        {
            connection.reset();
        }
        else if (is_broken)
        {
            try
            {
                connection->getRef().reset();
            }
            catch (...)
            {
                connection.reset();
            }
        }
        pool->returnObject(std::move(connection));
    }

    pqxx::connection & get()
    {
        return connection->getRef();
    }

    void update()
    {
        connection->updateConnection();
    }

private:
    PoolPtr pool;
    ConnectionPtr connection;
    bool auto_close;
    bool is_broken = false;
};

using ConnectionHolderPtr = std::unique_ptr<ConnectionHolder>;
}

#endif