forked from duckdb/duckdb-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyarrow_filter_pushdown.cpp
More file actions
314 lines (290 loc) · 12.2 KB
/
Copy pathpyarrow_filter_pushdown.cpp
File metadata and controls
314 lines (290 loc) · 12.2 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
#include "duckdb_python/arrow/pyarrow_filter_pushdown.hpp"
#include "duckdb_python/arrow/filter_pushdown_visitor.hpp"
#include "duckdb_python/pyconnection/pyconnection.hpp"
#include "duckdb_python/python_objects.hpp"
#include "duckdb_python/pyrelation.hpp"
#include "duckdb/function/table/arrow.hpp"
namespace duckdb {
namespace {
string ConvertTimestampUnit(ArrowDateTimeType unit) {
switch (unit) {
case ArrowDateTimeType::MICROSECONDS:
return "us";
case ArrowDateTimeType::MILLISECONDS:
return "ms";
case ArrowDateTimeType::NANOSECONDS:
return "ns";
case ArrowDateTimeType::SECONDS:
return "s";
default:
throw NotImplementedException("DatetimeType not recognized in ConvertTimestampUnit: %d",
static_cast<int>(unit));
}
}
int64_t ConvertTimestampTZValue(int64_t base_value, ArrowDateTimeType datetime_type) {
auto input = timestamp_t(base_value);
if (!Value::IsFinite(input)) {
return base_value;
}
switch (datetime_type) {
case ArrowDateTimeType::MICROSECONDS:
return Timestamp::GetEpochMicroSeconds(input);
case ArrowDateTimeType::MILLISECONDS:
return Timestamp::GetEpochMs(input);
case ArrowDateTimeType::NANOSECONDS:
return Timestamp::GetEpochNanoSeconds(input);
case ArrowDateTimeType::SECONDS:
return Timestamp::GetEpochSeconds(input);
default:
throw NotImplementedException("DatetimeType not recognized in ConvertTimestampTZValue");
}
}
// Build a pyarrow.dataset scalar matching the given DuckDB Value and (optionally) ArrowType.
// The ArrowType is needed for timestamp unit / decimal precision / blob-view disambiguation; the
// DuckDB Value alone is not sufficient.
nb::object MakePyArrowScalar(const Value &constant, const string &timezone_config, const ArrowType *arrow_type) {
auto &import_cache = *DuckDBPyConnection::ImportCache();
auto scalar = import_cache.pyarrow.scalar();
nb::handle dataset_scalar = import_cache.pyarrow.dataset().attr("scalar");
switch (constant.type().id()) {
case LogicalTypeId::BOOLEAN:
return dataset_scalar(constant.GetValue<bool>());
case LogicalTypeId::TINYINT:
return dataset_scalar(constant.GetValue<int8_t>());
case LogicalTypeId::SMALLINT:
return dataset_scalar(constant.GetValue<int16_t>());
case LogicalTypeId::INTEGER:
return dataset_scalar(constant.GetValue<int32_t>());
case LogicalTypeId::BIGINT:
return dataset_scalar(constant.GetValue<int64_t>());
case LogicalTypeId::DATE: {
nb::handle date_type = import_cache.pyarrow.date32();
return dataset_scalar(scalar(constant.GetValue<int32_t>(), date_type()));
}
case LogicalTypeId::TIME: {
nb::handle date_type = import_cache.pyarrow.time64();
return dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type("us")));
}
case LogicalTypeId::TIME_NS: {
// Polars TIME columns round-trip through arrow as time64("ns").
// `Value::GetValue<int64_t>()` has a hand-rolled fast-path switch for TIME but not
// TIME_NS — it falls through to GetValueInternal, which then tries
// Cast::Operation<dtime_ns_t, int64_t> for which no specialization exists, and
// throws "Unimplemented type for cast (INT64 -> INT64)". Use the type-strong
// GetValueUnsafe<dtime_ns_t>() which reads `value_.time_ns` from the union
// directly. dtime_ns_t.value holds nanoseconds (see arrow_conversion.cpp:432).
nb::handle date_type = import_cache.pyarrow.time64();
return dataset_scalar(scalar(constant.GetValueUnsafe<dtime_ns_t>().value, date_type("ns")));
}
case LogicalTypeId::TIMESTAMP: {
nb::handle date_type = import_cache.pyarrow.timestamp();
return dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type("us")));
}
case LogicalTypeId::TIMESTAMP_MS: {
nb::handle date_type = import_cache.pyarrow.timestamp();
return dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type("ms")));
}
case LogicalTypeId::TIMESTAMP_NS: {
nb::handle date_type = import_cache.pyarrow.timestamp();
return dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type("ns")));
}
case LogicalTypeId::TIMESTAMP_SEC: {
nb::handle date_type = import_cache.pyarrow.timestamp();
return dataset_scalar(scalar(constant.GetValue<int64_t>(), date_type("s")));
}
case LogicalTypeId::TIMESTAMP_TZ: {
if (!arrow_type) {
throw NotImplementedException("Cannot push down TIMESTAMP_TZ filter without an arrow type");
}
auto &datetime_info = arrow_type->GetTypeInfo<ArrowDateTimeInfo>();
auto base_value = constant.GetValue<int64_t>();
auto arrow_datetime_type = datetime_info.GetDateTimeType();
auto time_unit_string = ConvertTimestampUnit(arrow_datetime_type);
auto converted_value = ConvertTimestampTZValue(base_value, arrow_datetime_type);
nb::handle date_type = import_cache.pyarrow.timestamp();
return dataset_scalar(scalar(converted_value, date_type(time_unit_string, nb::arg("tz") = timezone_config)));
}
case LogicalTypeId::TIMESTAMP_TZ_NS: {
nb::handle date_type = import_cache.pyarrow.timestamp();
auto converted_value = Timestamp::GetEpochNanoSeconds(timestamp_t(constant.GetValue<int64_t>()));
return dataset_scalar(scalar(converted_value, date_type("ns", nb::arg("tz") = timezone_config)));
}
case LogicalTypeId::UTINYINT: {
nb::handle integer_type = import_cache.pyarrow.uint8();
return dataset_scalar(scalar(constant.GetValue<uint8_t>(), integer_type()));
}
case LogicalTypeId::USMALLINT: {
nb::handle integer_type = import_cache.pyarrow.uint16();
return dataset_scalar(scalar(constant.GetValue<uint16_t>(), integer_type()));
}
case LogicalTypeId::UINTEGER: {
nb::handle integer_type = import_cache.pyarrow.uint32();
return dataset_scalar(scalar(constant.GetValue<uint32_t>(), integer_type()));
}
case LogicalTypeId::UBIGINT: {
nb::handle integer_type = import_cache.pyarrow.uint64();
return dataset_scalar(scalar(constant.GetValue<uint64_t>(), integer_type()));
}
case LogicalTypeId::FLOAT:
return dataset_scalar(constant.GetValue<float>());
case LogicalTypeId::DOUBLE:
return dataset_scalar(constant.GetValue<double>());
case LogicalTypeId::VARCHAR:
return dataset_scalar(constant.ToString());
case LogicalTypeId::BLOB: {
if (arrow_type && arrow_type->GetTypeInfo<ArrowStringInfo>().GetSizeType() == ArrowVariableSizeType::VIEW) {
nb::handle binary_view_type = import_cache.pyarrow.binary_view();
{
auto blob = constant.GetValueUnsafe<string>();
return dataset_scalar(scalar(nb::bytes(blob.data(), blob.size()), binary_view_type()));
}
}
{
auto blob = constant.GetValueUnsafe<string>();
return dataset_scalar(nb::bytes(blob.data(), blob.size()));
}
}
case LogicalTypeId::DECIMAL: {
if (!arrow_type) {
throw NotImplementedException("Cannot push down DECIMAL filter without an arrow type");
}
nb::handle decimal_type;
auto &decimal_info = arrow_type->GetTypeInfo<ArrowDecimalInfo>();
auto bit_width = decimal_info.GetBitWidth();
switch (bit_width) {
case DecimalBitWidth::DECIMAL_32:
decimal_type = import_cache.pyarrow.decimal32();
break;
case DecimalBitWidth::DECIMAL_64:
decimal_type = import_cache.pyarrow.decimal64();
break;
case DecimalBitWidth::DECIMAL_128:
decimal_type = import_cache.pyarrow.decimal128();
break;
default:
throw NotImplementedException("Unsupported precision for Arrow Decimal Type.");
}
uint8_t width;
uint8_t scale;
constant.type().GetDecimalProperties(width, scale);
auto val = import_cache.decimal.Decimal()(constant.ToString());
return dataset_scalar(
scalar(std::move(val), decimal_type(nb::arg("precision") = width, nb::arg("scale") = scale)));
}
default:
throw NotImplementedException("Unimplemented type \"%s\" for Arrow Filter Pushdown",
constant.type().ToString());
}
}
struct PyArrowBackend : public FilterBackend {
explicit PyArrowBackend(const ClientProperties &client_properties_p) : client_properties(client_properties_p) {
auto &import_cache = *DuckDBPyConnection::ImportCache();
field_factory = import_cache.pyarrow.dataset().attr("field");
dataset_scalar = import_cache.pyarrow.dataset().attr("scalar");
}
nb::object MakeColumnRef(const vector<Identifier> &path) override {
vector<string> str_path;
std::transform(path.begin(), path.end(), std::back_inserter(str_path),
[](const Identifier &segment) { return segment.GetIdentifierName(); });
return field_factory(nb::tuple(nb::cast(str_path)));
}
nb::object MakeScalar(const Value &v, const ArrowType *arrow_type, const string &timezone_config) override {
return MakePyArrowScalar(v, timezone_config, arrow_type);
}
nb::object Compare(ExpressionType op, nb::object col, nb::object scalar) override {
switch (op) {
case ExpressionType::COMPARE_EQUAL:
return col.attr("__eq__")(scalar);
case ExpressionType::COMPARE_NOTEQUAL:
return col.attr("__ne__")(scalar);
case ExpressionType::COMPARE_LESSTHAN:
return col.attr("__lt__")(scalar);
case ExpressionType::COMPARE_GREATERTHAN:
return col.attr("__gt__")(scalar);
case ExpressionType::COMPARE_LESSTHANOREQUALTO:
return col.attr("__le__")(scalar);
case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
return col.attr("__ge__")(scalar);
default:
throw NotImplementedException("Comparison Type %s can't be an Arrow Scan Pushdown Filter",
ExpressionTypeToString(op));
}
}
nb::object NaNCompare(ExpressionType op, nb::object col) override {
switch (op) {
case ExpressionType::COMPARE_EQUAL:
case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
return col.attr("is_nan")();
case ExpressionType::COMPARE_LESSTHAN:
case ExpressionType::COMPARE_NOTEQUAL:
return col.attr("is_nan")().attr("__invert__")();
case ExpressionType::COMPARE_GREATERTHAN:
// Nothing is greater than NaN.
return dataset_scalar(false);
case ExpressionType::COMPARE_LESSTHANOREQUALTO:
// Everything is less than or equal to NaN.
return dataset_scalar(true);
default:
throw NotImplementedException("Unsupported comparison type (%s) for NaN values",
ExpressionTypeToString(op));
}
}
nb::object IsNaN(nb::object col) override {
return col.attr("is_nan")();
}
nb::object IsNull(nb::object col) override {
return col.attr("is_null")();
}
nb::object IsNotNull(nb::object col) override {
return col.attr("is_valid")();
}
nb::object IsIn(nb::object col, const vector<Value> &values, const LogicalType &col_logical_type,
const string &timezone_config) override {
// PyArrow accepts a plain Python list of Python-typed scalars; type
// coercion happens inside the scanner. We don't need the column type.
(void)col_logical_type;
(void)timezone_config;
nb::list py_values;
for (auto &val : values) {
py_values.append(PythonObject::FromValue(val, val.type(), client_properties));
}
return col.attr("isin")(std::move(py_values));
}
nb::object And(nb::object a, nb::object b) override {
return a.attr("__and__")(b);
}
nb::object Or(nb::object a, nb::object b) override {
return a.attr("__or__")(b);
}
private:
const ClientProperties &client_properties;
nb::object field_factory;
nb::object dataset_scalar;
};
} // anonymous namespace
nb::object PyArrowFilterPushdown::TransformFilter(TableFilterSet &filter_collection,
unordered_map<idx_t, string> &columns,
unordered_map<idx_t, idx_t> filter_to_col,
const ClientProperties &config, const ArrowTableSchema &arrow_table) {
PyArrowBackend backend(config);
nb::object expression = nb::none();
for (auto &entry : filter_collection) {
auto column_idx = entry.GetIndex();
auto &column_name = columns[column_idx];
D_ASSERT(columns.find(column_idx) != columns.end());
vector<Identifier> column_path = {Identifier(column_name)};
auto &arrow_type = arrow_table.GetColumns().at(filter_to_col.at(column_idx));
nb::object child_expression = duckdb::TransformFilter(entry.Filter(), std::move(column_path), backend,
arrow_type.get(), config.time_zone);
if (child_expression.is(nb::none())) {
continue;
}
if (expression.is(nb::none())) {
expression = std::move(child_expression);
} else {
expression = expression.attr("__and__")(child_expression);
}
}
return expression;
}
} // namespace duckdb