-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpy_query_result.cpp
More file actions
380 lines (350 loc) · 14.4 KB
/
py_query_result.cpp
File metadata and controls
380 lines (350 loc) · 14.4 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#include "include/py_query_result.h"
#include <string>
#include "cached_import/py_cached_import.h"
#include "common/arrow/arrow_converter.h"
#include "common/arrow/arrow_row_batch.h"
#include "common/constants.h"
#include "common/exception/not_implemented.h"
#include "common/types/uuid.h"
#include "common/types/value/nested.h"
#include "common/types/value/node.h"
#include "common/types/value/rel.h"
#include "datetime.h" // python lib
#include "include/py_query_result_converter.h"
using namespace lbug::common;
using lbug::importCache;
#define PyDateTimeTZ_FromDateAndTime(year, month, day, hour, min, sec, usec, timezone) \
PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, min, sec, usec, timezone, \
PyDateTimeAPI->DateTimeType)
void PyQueryResult::initialize(py::handle& m) {
py::class_<PyQueryResult>(m, "result")
.def("hasNext", &PyQueryResult::hasNext)
.def("getNext", &PyQueryResult::getNext)
.def("hasNextQueryResult", &PyQueryResult::hasNextQueryResult)
.def("getNextQueryResult", &PyQueryResult::getNextQueryResult)
.def("close", &PyQueryResult::close)
.def("getAsDF", &PyQueryResult::getAsDF)
.def("getAsArrow", &PyQueryResult::getAsArrow)
.def("getColumnNames", &PyQueryResult::getColumnNames)
.def("getColumnDataTypes", &PyQueryResult::getColumnDataTypes)
.def("resetIterator", &PyQueryResult::resetIterator)
.def("isSuccess", &PyQueryResult::isSuccess)
.def("getErrorMessage", &PyQueryResult::getErrorMessage)
.def("getCompilingTime", &PyQueryResult::getCompilingTime)
.def("getExecutionTime", &PyQueryResult::getExecutionTime)
.def("getNumTuples", &PyQueryResult::getNumTuples);
// PyDateTime_IMPORT is a macro that must be invoked before calling any other cpython datetime
// macros. One could also invoke this in a separate function like constructor. See
// https://docs.python.org/3/c-api/datetime.html for details.
PyDateTime_IMPORT;
}
PyQueryResult::~PyQueryResult() {
close();
}
bool PyQueryResult::hasNext() {
return queryResult->hasNext();
}
py::list PyQueryResult::getNext() {
auto tuple = queryResult->getNext();
py::tuple result(tuple->len());
for (auto i = 0u; i < tuple->len(); ++i) {
result[i] = convertValueToPyObject(*tuple->getValue(i));
}
return result;
}
bool PyQueryResult::hasNextQueryResult() {
return queryResult->hasNextQueryResult();
}
std::unique_ptr<PyQueryResult> PyQueryResult::getNextQueryResult() {
py::gil_scoped_release release;
auto nextQueryResult = queryResult->getNextQueryResult();
py::gil_scoped_acquire acquire;
auto pyQueryResult = std::make_unique<PyQueryResult>();
pyQueryResult->queryResult = nextQueryResult;
pyQueryResult->isOwned = false;
return pyQueryResult;
}
void PyQueryResult::close() {
// Note: Python does not guarantee objects to be deleted in the reverse order. Therefore, we
// expose close() interface so that users can explicitly call close() and ensure that
// QueryResult is destroyed before Database.
if (isOwned) {
delete queryResult;
queryResult = nullptr;
}
}
static py::object converTimestampToPyObject(timestamp_t& timestamp) {
int32_t year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0, micros = 0;
date_t date;
dtime_t time;
Timestamp::convert(timestamp, date, time);
Date::convert(date, year, month, day);
Time::convert(time, hour, min, sec, micros);
return py::cast<py::object>(
PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, micros));
}
py::object PyQueryResult::convertValueToPyObject(const Value& value) {
if (value.isNull()) {
return py::none();
}
const auto& dataType = value.getDataType();
switch (dataType.getLogicalTypeID()) {
case LogicalTypeID::BOOL: {
return py::cast(value.getValue<bool>());
}
case LogicalTypeID::INT8: {
return py::cast(value.getValue<int8_t>());
}
case LogicalTypeID::INT16: {
return py::cast(value.getValue<int16_t>());
}
case LogicalTypeID::INT32: {
return py::cast(value.getValue<int32_t>());
}
case LogicalTypeID::INT64:
case LogicalTypeID::SERIAL: {
return py::cast(value.getValue<int64_t>());
}
case LogicalTypeID::UINT8: {
return py::cast(value.getValue<uint8_t>());
}
case LogicalTypeID::UINT16: {
return py::cast(value.getValue<uint16_t>());
}
case LogicalTypeID::UINT32: {
return py::cast(value.getValue<uint32_t>());
}
case LogicalTypeID::UINT64: {
return py::cast(value.getValue<uint64_t>());
}
case LogicalTypeID::INT128: {
lbug::common::int128_t result = value.getValue<lbug::common::int128_t>();
std::string int128_string = lbug::common::Int128_t::toString(result);
auto Decimal = importCache->decimal.Decimal();
py::object largeInt = Decimal(int128_string);
return largeInt;
}
case LogicalTypeID::FLOAT: {
return py::cast(value.getValue<float>());
}
case LogicalTypeID::DOUBLE: {
return py::cast(value.getValue<double>());
}
case LogicalTypeID::DECIMAL: {
auto Decimal = importCache->decimal.Decimal();
return Decimal(value.toString());
}
case LogicalTypeID::STRING:
case LogicalTypeID::JSON: {
return py::cast(value.getValue<std::string>());
}
case LogicalTypeID::BLOB: {
auto blobStr = value.getValue<std::string>();
auto blobBytesArray = blobStr.c_str();
return py::bytes(blobBytesArray, blobStr.size());
}
case LogicalTypeID::UUID: {
lbug::common::int128_t result = value.getValue<lbug::common::int128_t>();
std::string uuidString = lbug::common::UUID::toString(result);
auto UUID = importCache->uuid.UUID();
return UUID(uuidString);
}
case LogicalTypeID::DATE: {
auto dateVal = value.getValue<date_t>();
int32_t year = 0, month = 0, day = 0;
Date::convert(dateVal, year, month, day);
return py::cast<py::object>(PyDate_FromDate(year, month, day));
}
case LogicalTypeID::TIMESTAMP: {
auto timestampVal = value.getValue<timestamp_t>();
return converTimestampToPyObject(timestampVal);
}
case LogicalTypeID::TIMESTAMP_TZ: {
auto timestampVal = value.getValue<timestamp_tz_t>();
int32_t year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0, micros = 0;
date_t date;
dtime_t time;
Timestamp::convert(timestampVal, date, time);
Date::convert(date, year, month, day);
Time::convert(time, hour, min, sec, micros);
return py::cast<py::object>(PyDateTimeTZ_FromDateAndTime(year, month, day, hour, min, sec,
micros, PyDateTime_TimeZone_UTC));
}
case LogicalTypeID::TIMESTAMP_NS: {
timestamp_t timestampVal =
Timestamp::fromEpochNanoSeconds(value.getValue<timestamp_ns_t>().value);
return converTimestampToPyObject(timestampVal);
}
case LogicalTypeID::TIMESTAMP_MS: {
timestamp_t timestampVal =
Timestamp::fromEpochMilliSeconds(value.getValue<timestamp_ms_t>().value);
return converTimestampToPyObject(timestampVal);
}
case LogicalTypeID::TIMESTAMP_SEC: {
timestamp_t timestampVal =
Timestamp::fromEpochSeconds(value.getValue<timestamp_sec_t>().value);
return converTimestampToPyObject(timestampVal);
}
case LogicalTypeID::INTERVAL: {
auto intervalVal = value.getValue<interval_t>();
auto days = Interval::DAYS_PER_MONTH * intervalVal.months + intervalVal.days;
return py::cast<py::object>(importCache->datetime.timedelta()(py::arg("days") = days,
py::arg("microseconds") = intervalVal.micros));
}
case LogicalTypeID::LIST:
case LogicalTypeID::ARRAY: {
py::list list;
for (auto i = 0u; i < NestedVal::getChildrenSize(&value); ++i) {
list.append(convertValueToPyObject(*NestedVal::getChildVal(&value, i)));
}
return list;
}
case LogicalTypeID::MAP: {
py::dict dict;
for (auto i = 0u; i < NestedVal::getChildrenSize(&value); ++i) {
auto childVal = NestedVal::getChildVal(&value, i);
auto k = convertValueToPyObject(*NestedVal::getChildVal(childVal, 0));
auto v = convertValueToPyObject(*NestedVal::getChildVal(childVal, 1));
dict[std::move(k)] = std::move(v);
}
return dict;
}
case LogicalTypeID::UNION: {
return convertValueToPyObject(*NestedVal::getChildVal(&value, 0 /* idx */));
}
case LogicalTypeID::STRUCT: {
auto fieldNames = StructType::getFieldNames(dataType);
py::dict dict;
for (auto i = 0u; i < NestedVal::getChildrenSize(&value); ++i) {
auto key = py::str(fieldNames[i]);
auto val = convertValueToPyObject(*NestedVal::getChildVal(&value, i));
dict[key] = val;
}
return dict;
}
case LogicalTypeID::RECURSIVE_REL: {
py::dict dict;
dict[InternalKeyword::NODES] = convertValueToPyObject(*NestedVal::getChildVal(&value, 0));
dict[InternalKeyword::RELS] = convertValueToPyObject(*NestedVal::getChildVal(&value, 1));
return dict;
}
case LogicalTypeID::NODE: {
py::dict dict;
auto nodeIdVal = NodeVal::getNodeIDVal(&value);
dict[InternalKeyword::ID] = nodeIdVal ? convertValueToPyObject(*nodeIdVal) : py::none();
auto labelVal = NodeVal::getLabelVal(&value);
dict[InternalKeyword::LABEL] = labelVal ? convertValueToPyObject(*labelVal) : py::none();
auto numProperties = NodeVal::getNumProperties(&value);
for (auto i = 0u; i < numProperties; ++i) {
auto key = py::str(NodeVal::getPropertyName(&value, i));
auto val = convertValueToPyObject(*NodeVal::getPropertyVal(&value, i));
dict[key] = val;
}
return dict;
}
case LogicalTypeID::REL: {
py::dict dict;
auto srcIdVal = RelVal::getSrcNodeIDVal(&value);
dict[InternalKeyword::SRC] = srcIdVal ? convertValueToPyObject(*srcIdVal) : py::none();
auto dstIdVal = RelVal::getDstNodeIDVal(&value);
dict[InternalKeyword::DST] = dstIdVal ? convertValueToPyObject(*dstIdVal) : py::none();
auto labelVal = RelVal::getLabelVal(&value);
dict[InternalKeyword::LABEL] = labelVal ? convertValueToPyObject(*labelVal) : py::none();
auto internalIdVal = RelVal::getIDVal(&value);
dict[InternalKeyword::ID] =
internalIdVal ? convertValueToPyObject(*internalIdVal) : py::none();
auto numProperties = RelVal::getNumProperties(&value);
for (auto i = 0u; i < numProperties; ++i) {
auto key = py::str(RelVal::getPropertyName(&value, i));
auto val = convertValueToPyObject(*RelVal::getPropertyVal(&value, i));
dict[key] = val;
}
return dict;
}
case LogicalTypeID::INTERNAL_ID: {
return convertNodeIdToPyDict(value.getValue<nodeID_t>());
}
default:
throw NotImplementedException("Unsupported type: " + dataType.toString());
}
}
py::object PyQueryResult::getAsDF() {
return QueryResultConverter(queryResult).toDF();
}
void PyQueryResult::getNextArrowChunk(const std::vector<LogicalType>& types,
const std::vector<std::string>& names, py::list& batches, std::int64_t chunkSize,
bool fallbackExtensionTypes) {
auto rowBatch = std::make_unique<ArrowRowBatch>(types, chunkSize, fallbackExtensionTypes);
auto rowBatchSize = 0u;
while (rowBatchSize < chunkSize) {
if (!queryResult->hasNext()) {
break;
}
auto tuple = queryResult->getNext();
rowBatch->append(*tuple);
rowBatchSize++;
}
auto data = rowBatch->toArray(types);
auto batchImportFunc = importCache->pyarrow.lib.RecordBatch._import_from_c();
auto schema = ArrowConverter::toArrowSchema(types, names, fallbackExtensionTypes);
batches.append(batchImportFunc((std::uint64_t)&data, (std::uint64_t)schema.get()));
}
py::object PyQueryResult::getArrowChunks(const std::vector<LogicalType>& types,
const std::vector<std::string>& names, std::int64_t chunkSize, bool fallbackExtensionTypes) {
py::list batches;
while (queryResult->hasNext()) {
getNextArrowChunk(types, names, batches, chunkSize, fallbackExtensionTypes);
}
return batches;
}
lbug::pyarrow::Table PyQueryResult::getAsArrow(std::int64_t chunkSize,
bool fallbackExtensionTypes) {
auto types = queryResult->getColumnDataTypes();
auto names = queryResult->getColumnNames();
py::list batches = getArrowChunks(types, names, chunkSize, fallbackExtensionTypes);
auto schema = ArrowConverter::toArrowSchema(types, names, fallbackExtensionTypes);
auto fromBatchesFunc = importCache->pyarrow.lib.Table.from_batches();
auto schemaImportFunc = importCache->pyarrow.lib.Schema._import_from_c();
auto schemaObj = schemaImportFunc((std::uint64_t)schema.get());
return py::cast<lbug::pyarrow::Table>(fromBatchesFunc(batches, schemaObj));
}
py::list PyQueryResult::getColumnDataTypes() {
auto columnDataTypes = queryResult->getColumnDataTypes();
py::tuple result(columnDataTypes.size());
for (auto i = 0u; i < columnDataTypes.size(); ++i) {
result[i] = py::cast(columnDataTypes[i].toString());
}
return result;
}
py::list PyQueryResult::getColumnNames() {
auto columnNames = queryResult->getColumnNames();
py::tuple result(columnNames.size());
for (auto i = 0u; i < columnNames.size(); ++i) {
result[i] = py::cast(columnNames[i]);
}
return result;
}
void PyQueryResult::resetIterator() {
queryResult->resetIterator();
}
bool PyQueryResult::isSuccess() const {
return queryResult->isSuccess();
}
std::string PyQueryResult::getErrorMessage() const {
return queryResult->getErrorMessage();
}
py::dict PyQueryResult::convertNodeIdToPyDict(const nodeID_t& nodeId) {
py::dict idDict;
idDict["offset"] = py::cast(nodeId.offset);
idDict["table"] = py::cast(nodeId.tableID);
return idDict;
}
double PyQueryResult::getExecutionTime() {
return queryResult->getQuerySummary()->getExecutionTime();
}
double PyQueryResult::getCompilingTime() {
return queryResult->getQuerySummary()->getCompilingTime();
}
size_t PyQueryResult::getNumTuples() {
return queryResult->getNumTuples();
}