aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Interpreters/MergeTreeTransactionHolder.cpp
blob: 2944fb78b7699782a2e59eca5e91906c552fec68 (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
74
75
76
77
78
79
80
81
82
83
84
#include <Interpreters/MergeTreeTransactionHolder.h>
#include <Interpreters/MergeTreeTransaction.h>
#include <Interpreters/TransactionLog.h>
#include <Interpreters/Context.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
}

MergeTreeTransactionHolder::MergeTreeTransactionHolder(const MergeTreeTransactionPtr & txn_, bool autocommit_ = false, const Context * owned_by_session_context_)
    : txn(txn_)
    , autocommit(autocommit_)
    , owned_by_session_context(owned_by_session_context_)
{
    assert(!txn || txn->getState() == MergeTreeTransaction::RUNNING);
    assert(!owned_by_session_context || owned_by_session_context == owned_by_session_context->getSessionContext().get());
}

MergeTreeTransactionHolder::MergeTreeTransactionHolder(MergeTreeTransactionHolder && rhs) noexcept
{
    *this = std::move(rhs);
}

MergeTreeTransactionHolder & MergeTreeTransactionHolder::operator=(MergeTreeTransactionHolder && rhs) noexcept
{
    onDestroy();
    txn = NO_TRANSACTION_PTR;
    autocommit = false;
    owned_by_session_context = nullptr;
    std::swap(txn, rhs.txn);
    std::swap(autocommit, rhs.autocommit);
    std::swap(owned_by_session_context, rhs.owned_by_session_context);
    return *this;
}

MergeTreeTransactionHolder::~MergeTreeTransactionHolder()
{
    onDestroy();
}

void MergeTreeTransactionHolder::onDestroy() noexcept
{
    if (!txn)
        return;
    if (txn->getState() != MergeTreeTransaction::RUNNING)
        return;

    if (autocommit && std::uncaught_exceptions() == 0)
    {
        try
        {
            TransactionLog::instance().commitTransaction(txn, /* throw_on_unknown_status */ false);
            return;
        }
        catch (...)
        {
            tryLogCurrentException(__PRETTY_FUNCTION__);
        }
    }

    TransactionLog::instance().rollbackTransaction(txn);
}

MergeTreeTransactionHolder::MergeTreeTransactionHolder(const MergeTreeTransactionHolder & rhs)
{
    *this = rhs;
}

MergeTreeTransactionHolder & MergeTreeTransactionHolder::operator=(const MergeTreeTransactionHolder & rhs)  // NOLINT
{
    if (rhs.txn && !rhs.owned_by_session_context)
        throw Exception(ErrorCodes::LOGICAL_ERROR,
                        "Tried to copy non-empty MergeTreeTransactionHolder that is not owned by session context. It's a bug");
    assert(!txn);
    assert(!autocommit);
    assert(!owned_by_session_context);
    return *this;
}

}