Repository navigation
Expand file tree
/
Copy pathPostgreSQLSource.cpp
More file actions
260 lines (214 loc) · 7.09 KB
/
Copy pathPostgreSQLSource.cpp
File metadata and controls
260 lines (214 loc) · 7.09 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#include <Processors/Sources/PostgreSQLSource.h>
#include <Common/Exception.h>
#if USE_LIBPQXX
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnArray.h>
#include <Columns/ColumnsNumber.h>
#include <Columns/ColumnDecimal.h>
#include <DataTypes/IDataType.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypesDecimal.h>
#include <Interpreters/convertFieldToType.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
#include <IO/ReadBufferFromString.h>
#include <Common/assert_cast.h>
#include <base/range.h>
#include <Common/logger_useful.h>
namespace DB
{
namespace ErrorCodes
{
extern const int TOO_MANY_COLUMNS;
}
template<typename T>
PostgreSQLSource<T>::PostgreSQLSource(
postgres::ConnectionHolderPtr connection_holder_,
const std::string & query_str_,
SharedHeader sample_block,
UInt64 max_block_size_)
: ISource(std::make_shared<const Block>(sample_block->cloneEmpty()))
, max_block_size(max_block_size_)
, connection_holder(std::move(connection_holder_))
, query_str(query_str_)
{
init(*sample_block);
}
template<typename T>
PostgreSQLSource<T>::PostgreSQLSource(
std::shared_ptr<T> tx_,
const std::string & query_str_,
SharedHeader sample_block,
UInt64 max_block_size_,
bool auto_commit_)
: ISource(std::make_shared<const Block>(sample_block->cloneEmpty()))
, max_block_size(max_block_size_)
, auto_commit(auto_commit_)
, query_str(query_str_)
, tx(std::move(tx_))
{
init(*sample_block);
}
template<typename T>
void PostgreSQLSource<T>::init(const Block & sample_block)
{
description.init(sample_block);
for (const auto idx : collections::range(0, description.sample_block.columns()))
if (description.types[idx].first == ExternalResultDescription::ValueType::vtArray)
preparePostgreSQLArrayInfo(array_info, idx, description.sample_block.getByPosition(idx).type);
/// pqxx::stream_from uses COPY command, will get error if ';' is present
if (query_str.ends_with(';'))
query_str.resize(query_str.size() - 1);
}
template<typename T>
void PostgreSQLSource<T>::onStart()
{
if (is_completed.load())
return;
if (!tx)
{
try
{
auto & conn = connection_holder->get();
tx = std::make_shared<T>(conn);
}
catch (const pqxx::broken_connection &)
{
connection_holder->update();
tx = std::make_shared<T>(connection_holder->get());
}
}
LOG_TEST(getLogger("PostgreSQLSource"), "Stream data from database");
stream = std::make_unique<pqxx::stream_from>(*tx, pqxx::from_query, std::string_view{query_str});
}
template<typename T>
IProcessor::Status PostgreSQLSource<T>::prepare()
{
if (!started.load())
{
onStart();
started.store(true);
}
auto status = ISource::prepare();
if (status == Status::Finished)
{
if (stream)
stream->close();
if (tx && auto_commit)
tx->commit();
is_completed.store(true);
}
return status;
}
template<typename T>
Chunk PostgreSQLSource<T>::generate()
{
LOG_TEST(getLogger("PostgreSQLSource"), "Generate a chunk from stream");
/// Check if source was cancelled or completed
if (is_completed.load() || isCancelled())
return {};
/// Check if pqxx::stream_from is finished
if (!stream || !(*stream))
return {};
MutableColumns columns = description.sample_block.cloneEmptyColumns();
size_t num_rows = 0;
while (!isCancelled() && !is_completed.load())
{
const std::vector<pqxx::zview> * row{stream->read_row()};
/// row is nullptr if pqxx::stream_from is finished
if (!row)
break;
if (row->size() > description.sample_block.columns())
throw Exception(ErrorCodes::TOO_MANY_COLUMNS,
"Row has too many columns: {}, expected structure: {}",
row->size(), description.sample_block.dumpStructure());
for (const auto idx : collections::range(0, row->size()))
{
const auto & sample = description.sample_block.getByPosition(idx);
/// if got NULL type, then pqxx::zview will return nullptr in c_str()
if ((*row)[idx].c_str())
{
if (description.types[idx].second)
{
ColumnNullable & column_nullable = assert_cast<ColumnNullable &>(*columns[idx]);
const auto & data_type = assert_cast<const DataTypeNullable &>(*sample.type);
insertPostgreSQLValue(
column_nullable.getNestedColumn(), (*row)[idx],
description.types[idx].first, data_type.getNestedType(), array_info, idx);
column_nullable.getNullMapData().emplace_back(false);
}
else
{
insertPostgreSQLValue(
*columns[idx], (*row)[idx], description.types[idx].first, sample.type, array_info, idx);
}
}
else
{
insertDefaultPostgreSQLValue(*columns[idx], *sample.column);
}
}
if (++num_rows == max_block_size)
break;
}
return Chunk(std::move(columns), num_rows);
}
template<typename T>
void PostgreSQLSource<T>::onCancel() noexcept
{
/// Use atomic flag to prevent double-cancellation
if (is_completed.exchange(true))
return;
/// The code is executed only if onStart() was not finished mainly due to freezing on pqxx::from_query
if (!started.load() && tx && tx->conn().is_open())
{
try
{
tx->conn().cancel_query();
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
if (connection_holder)
connection_holder->setBroken();
}
}
template<typename T>
PostgreSQLSource<T>::~PostgreSQLSource()
{
/// Use atomic flag to prevent double cleanup
if (is_completed.exchange(true))
return;
try
{
if (stream)
{
/** Internally libpqxx::stream_from runs PostgreSQL copy query `COPY query TO STDOUT`.
* During transaction abort we try to execute PostgreSQL `ROLLBACK` command and if
* copy query is not cancelled, we wait until it finishes.
*/
tx->conn().cancel_query();
/** If stream is not closed, libpqxx::stream_from closes stream in destructor, but that way
* exception is added into transaction pending error and we can potentially ignore exception message.
*/
stream->close();
}
}
catch (...)
{
tryLogCurrentException(__PRETTY_FUNCTION__);
}
stream.reset();
tx.reset();
if (connection_holder)
connection_holder->setBroken();
}
template
class PostgreSQLSource<pqxx::ReplicationTransaction>;
template
class PostgreSQLSource<pqxx::ReadTransaction>;
}
#endif