1 | // |
---|---|
2 | // Transaction.cpp |
3 | // |
4 | // Library: SQL |
5 | // Package: SQLCore |
6 | // Module: Transaction |
7 | // |
8 | // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. |
9 | // and Contributors. |
10 | // |
11 | // SPDX-License-Identifier: BSL-1.0 |
12 | // |
13 | |
14 | |
15 | #include "Poco/SQL/Transaction.h" |
16 | #include "Poco/Exception.h" |
17 | |
18 | |
19 | namespace Poco { |
20 | namespace SQL { |
21 | |
22 | |
23 | Transaction::Transaction(Poco::SQL::Session& rSession, Poco::Logger::Ptr pLogger): |
24 | _rSession(rSession), |
25 | _pLogger(pLogger) |
26 | { |
27 | begin(); |
28 | } |
29 | |
30 | |
31 | Transaction::Transaction(Poco::SQL::Session& rSession, bool start): |
32 | _rSession(rSession), |
33 | _pLogger(0) |
34 | { |
35 | if (start) begin(); |
36 | } |
37 | |
38 | |
39 | Transaction::~Transaction() |
40 | { |
41 | try |
42 | { |
43 | if (_rSession.isTransaction()) |
44 | { |
45 | try |
46 | { |
47 | if (_pLogger) |
48 | _pLogger->debug("Rolling back transaction."); |
49 | |
50 | _rSession.rollback(); |
51 | } |
52 | catch (Poco::Exception& exc) |
53 | { |
54 | if (_pLogger) |
55 | _pLogger->error("Error while rolling back database transaction: %s", exc.displayText()); |
56 | } |
57 | catch (...) |
58 | { |
59 | if (_pLogger) |
60 | _pLogger->error("Error while rolling back database transaction."); |
61 | } |
62 | } |
63 | } |
64 | catch (...) |
65 | { |
66 | poco_unexpected(); |
67 | } |
68 | } |
69 | |
70 | |
71 | void Transaction::begin() |
72 | { |
73 | if (!_rSession.isTransaction()) |
74 | _rSession.begin(); |
75 | else |
76 | throw InvalidAccessException("Transaction in progress."); |
77 | } |
78 | |
79 | |
80 | void Transaction::execute(const std::string& sql, bool doCommit) |
81 | { |
82 | if (!_rSession.isTransaction()) _rSession.begin(); |
83 | _rSession << sql, Keywords::now; |
84 | if (doCommit) commit(); |
85 | } |
86 | |
87 | |
88 | void Transaction::execute(const std::vector<std::string>& sql) |
89 | { |
90 | try |
91 | { |
92 | std::vector<std::string>::const_iterator it = sql.begin(); |
93 | std::vector<std::string>::const_iterator end = sql.end(); |
94 | for (; it != end; ++it) execute(*it, it + 1 == end ? true : false); |
95 | return; |
96 | } |
97 | catch (Exception& ex) |
98 | { |
99 | if (_pLogger) _pLogger->log(ex); |
100 | } |
101 | |
102 | rollback(); |
103 | } |
104 | |
105 | |
106 | void Transaction::commit() |
107 | { |
108 | if (_pLogger) |
109 | _pLogger->debug("Committing transaction."); |
110 | |
111 | _rSession.commit(); |
112 | } |
113 | |
114 | |
115 | void Transaction::rollback() |
116 | { |
117 | if (_pLogger) |
118 | _pLogger->debug("Rolling back transaction."); |
119 | |
120 | _rSession.rollback(); |
121 | } |
122 | |
123 | |
124 | } } // namespace Poco::SQL |
125 |