forked from duckdb/duckdb-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyrelation.cpp
More file actions
1840 lines (1628 loc) · 68.3 KB
/
pyrelation.cpp
File metadata and controls
1840 lines (1628 loc) · 68.3 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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "duckdb_python/pybind11/pybind_wrapper.hpp"
#include "duckdb_python/pyrelation.hpp"
#include "duckdb_python/pyconnection/pyconnection.hpp"
#include "duckdb_python/pytype.hpp"
#include "duckdb_python/pyresult.hpp"
#include "duckdb/parser/qualified_name.hpp"
#include "duckdb/main/client_context.hpp"
#include "duckdb_python/numpy/numpy_type.hpp"
#include "duckdb/main/relation/query_relation.hpp"
#include "duckdb/main/relation/join_relation.hpp"
#include "duckdb/parser/parser.hpp"
#include "duckdb/main/relation/view_relation.hpp"
#include "duckdb/function/pragma/pragma_functions.hpp"
#include "duckdb/parser/statement/pragma_statement.hpp"
#include "duckdb/common/box_renderer.hpp"
#include "duckdb/main/query_result.hpp"
#include "duckdb/main/materialized_query_result.hpp"
#include "duckdb/parser/statement/explain_statement.hpp"
#include "duckdb/catalog/default/default_types.hpp"
#include "duckdb/main/relation/value_relation.hpp"
#include "duckdb/main/relation/filter_relation.hpp"
#include "duckdb_python/expression/pyexpression.hpp"
#include "duckdb/common/arrow/physical_arrow_collector.hpp"
#include "duckdb_python/arrow/arrow_export_utils.hpp"
namespace duckdb {
DuckDBPyRelation::DuckDBPyRelation(shared_ptr<Relation> rel_p) : rel(std::move(rel_p)) {
if (!rel) {
throw InternalException("DuckDBPyRelation created without a relation");
}
this->executed = false;
auto &columns = rel->Columns();
for (auto &col : columns) {
names.push_back(col.GetName());
types.push_back(col.GetType());
}
}
bool DuckDBPyRelation::CanBeRegisteredBy(Connection &con) {
return CanBeRegisteredBy(con.context);
}
bool DuckDBPyRelation::CanBeRegisteredBy(ClientContext &context) {
if (!rel) {
// PyRelation without an internal relation can not be registered
return false;
}
auto this_context = rel->context->TryGetContext();
if (!this_context) {
return false;
}
return &context == this_context.get();
}
bool DuckDBPyRelation::CanBeRegisteredBy(shared_ptr<ClientContext> &con) {
if (!con) {
return false;
}
return CanBeRegisteredBy(*con);
}
DuckDBPyRelation::~DuckDBPyRelation() {
D_ASSERT(py::gil_check());
py::gil_scoped_release gil;
rel.reset();
}
DuckDBPyRelation::DuckDBPyRelation(shared_ptr<DuckDBPyResult> result_p) : rel(nullptr), result(std::move(result_p)) {
if (!result) {
throw InternalException("DuckDBPyRelation created without a result");
}
this->executed = true;
this->types = result->GetTypes();
this->names = result->GetNames();
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::ProjectFromExpression(const string &expression) {
auto projected_relation = make_uniq<DuckDBPyRelation>(rel->Project(expression));
for (auto &dep : this->rel->external_dependencies) {
projected_relation->rel->AddExternalDependency(dep);
}
return projected_relation;
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Project(const py::args &args, const string &groups) {
if (!rel) {
return nullptr;
}
auto arg_count = args.size();
if (arg_count == 0) {
return nullptr;
}
py::handle first_arg = args[0];
if (arg_count == 1 && py::isinstance<py::str>(first_arg)) {
string expr_string = py::str(first_arg);
return ProjectFromExpression(expr_string);
} else {
vector<unique_ptr<ParsedExpression>> expressions;
for (auto arg : args) {
shared_ptr<DuckDBPyExpression> py_expr;
if (!py::try_cast<shared_ptr<DuckDBPyExpression>>(arg, py_expr)) {
throw InvalidInputException("Please provide arguments of type Expression!");
}
auto expr = py_expr->GetExpression().Copy();
expressions.push_back(std::move(expr));
}
vector<string> empty_aliases;
if (groups.empty()) {
// No groups provided
return make_uniq<DuckDBPyRelation>(rel->Project(std::move(expressions), empty_aliases));
}
return make_uniq<DuckDBPyRelation>(rel->Aggregate(std::move(expressions), groups));
}
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::ProjectFromTypes(const py::object &obj) {
if (!rel) {
return nullptr;
}
if (!py::isinstance<py::list>(obj)) {
throw InvalidInputException("'columns_by_type' expects a list containing types");
}
auto list = py::list(obj);
vector<LogicalType> types_filter;
// Collect the list of types specified that will be our filter
for (auto &item : list) {
LogicalType type;
if (py::isinstance<py::str>(item)) {
string type_str = py::str(item);
type = TransformStringToLogicalType(type_str, *rel->context->GetContext());
} else if (py::isinstance<DuckDBPyType>(item)) {
auto *type_p = item.cast<DuckDBPyType *>();
type = type_p->Type();
} else {
string actual_type = py::str(item.get_type());
throw InvalidInputException("Can only project on objects of type DuckDBPyType or str, not '%s'",
actual_type);
}
types_filter.push_back(std::move(type));
}
if (types_filter.empty()) {
throw InvalidInputException("List of types can not be empty!");
}
string projection = "";
for (idx_t i = 0; i < types.size(); i++) {
auto &type = types[i];
// Check if any of the types in the filter match the current type
if (std::find_if(types_filter.begin(), types_filter.end(),
[&](const LogicalType &filter) { return filter == type; }) != types_filter.end()) {
if (!projection.empty()) {
projection += ", ";
}
projection += names[i];
}
}
if (projection.empty()) {
throw InvalidInputException("None of the columns matched the provided type filter!");
}
return ProjectFromExpression(projection);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::EmptyResult(const shared_ptr<ClientContext> &context,
const vector<LogicalType> &types, vector<string> names) {
vector<Value> dummy_values;
D_ASSERT(types.size() == names.size());
dummy_values.reserve(types.size());
D_ASSERT(!types.empty());
for (auto &type : types) {
dummy_values.emplace_back(type);
}
vector<vector<Value>> single_row(1, dummy_values);
auto values_relation =
make_uniq<DuckDBPyRelation>(make_shared_ptr<ValueRelation>(context, single_row, std::move(names)));
// Add a filter on an impossible condition
return values_relation->FilterFromExpression("true = false");
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::SetAlias(const string &expr) {
return make_uniq<DuckDBPyRelation>(rel->Alias(expr));
}
py::str DuckDBPyRelation::GetAlias() {
return py::str(string(rel->GetAlias()));
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Filter(const py::object &expr) {
if (py::isinstance<py::str>(expr)) {
string expression = py::cast<py::str>(expr);
return FilterFromExpression(expression);
}
shared_ptr<DuckDBPyExpression> expression;
if (!py::try_cast(expr, expression)) {
throw InvalidInputException("Please provide either a string or a DuckDBPyExpression object to 'filter'");
}
auto expr_p = expression->GetExpression().Copy();
return make_uniq<DuckDBPyRelation>(rel->Filter(std::move(expr_p)));
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::FilterFromExpression(const string &expr) {
return make_uniq<DuckDBPyRelation>(rel->Filter(expr));
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Limit(int64_t n, int64_t offset) {
return make_uniq<DuckDBPyRelation>(rel->Limit(n, offset));
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Order(const string &expr) {
return make_uniq<DuckDBPyRelation>(rel->Order(expr));
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Sort(const py::args &args) {
vector<OrderByNode> order_nodes;
order_nodes.reserve(args.size());
for (auto arg : args) {
shared_ptr<DuckDBPyExpression> py_expr;
if (!py::try_cast<shared_ptr<DuckDBPyExpression>>(arg, py_expr)) {
string actual_type = py::str(arg.get_type());
throw InvalidInputException("Expected argument of type Expression, received '%s' instead", actual_type);
}
auto expr = py_expr->GetExpression().Copy();
order_nodes.emplace_back(py_expr->order_type, py_expr->null_order, std::move(expr));
}
if (order_nodes.empty()) {
throw InvalidInputException("Please provide at least one expression to sort on");
}
return make_uniq<DuckDBPyRelation>(rel->Order(std::move(order_nodes)));
}
vector<unique_ptr<ParsedExpression>> GetExpressions(ClientContext &context, const py::object &expr) {
if (py::is_list_like(expr)) {
vector<unique_ptr<ParsedExpression>> expressions;
auto aggregate_list = py::list(expr);
for (auto &item : aggregate_list) {
shared_ptr<DuckDBPyExpression> py_expr;
if (!py::try_cast<shared_ptr<DuckDBPyExpression>>(item, py_expr)) {
throw InvalidInputException("Please provide arguments of type Expression!");
}
auto expr = py_expr->GetExpression().Copy();
expressions.push_back(std::move(expr));
}
return expressions;
} else if (py::isinstance<py::str>(expr)) {
auto aggregate_list = std::string(py::str(expr));
return Parser::ParseExpressionList(aggregate_list, context.GetParserOptions());
} else {
string actual_type = py::str(expr.get_type());
throw InvalidInputException("Please provide either a string or list of Expression objects, not %s",
actual_type);
}
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Aggregate(const py::object &expr, const string &groups) {
AssertRelation();
auto expressions = GetExpressions(*rel->context->GetContext(), expr);
if (!groups.empty()) {
return make_uniq<DuckDBPyRelation>(rel->Aggregate(std::move(expressions), groups));
}
return make_uniq<DuckDBPyRelation>(rel->Aggregate(std::move(expressions)));
}
void DuckDBPyRelation::AssertResult() const {
if (!result) {
throw InvalidInputException("No open result set");
}
}
void DuckDBPyRelation::AssertRelation() const {
if (!rel) {
throw InvalidInputException("This relation was created from a result");
}
}
void DuckDBPyRelation::AssertResultOpen() const {
if (!result || result->IsClosed()) {
throw InvalidInputException("No open result set");
}
}
py::list DuckDBPyRelation::Description() {
return DuckDBPyResult::GetDescription(names, types);
}
Relation &DuckDBPyRelation::GetRel() {
if (!rel) {
throw InternalException("DuckDBPyRelation - calling GetRel, but no rel was present");
}
return *rel;
}
struct DescribeAggregateInfo {
explicit DescribeAggregateInfo(string name_p, bool numeric_only = false)
: name(std::move(name_p)), numeric_only(numeric_only) {
}
string name;
bool numeric_only;
};
vector<string> CreateExpressionList(const vector<ColumnDefinition> &columns,
const vector<DescribeAggregateInfo> &aggregates) {
vector<string> expressions;
expressions.reserve(columns.size());
string aggr_names = "UNNEST([";
for (idx_t i = 0; i < aggregates.size(); i++) {
if (i > 0) {
aggr_names += ", ";
}
aggr_names += "'";
aggr_names += aggregates[i].name;
aggr_names += "'";
}
aggr_names += "])";
aggr_names += " AS aggr";
expressions.push_back(aggr_names);
for (idx_t c = 0; c < columns.size(); c++) {
auto &col = columns[c];
string expr = "UNNEST([";
for (idx_t i = 0; i < aggregates.size(); i++) {
if (i > 0) {
expr += ", ";
}
if (aggregates[i].numeric_only && !col.GetType().IsNumeric()) {
expr += "NULL";
continue;
}
expr += aggregates[i].name;
expr += "(";
expr += KeywordHelper::WriteOptionallyQuoted(col.GetName());
expr += ")";
if (col.GetType().IsNumeric()) {
expr += "::DOUBLE";
} else {
expr += "::VARCHAR";
}
}
expr += "])";
expr += " AS " + KeywordHelper::WriteOptionallyQuoted(col.GetName());
expressions.push_back(expr);
}
return expressions;
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Describe() {
auto &columns = rel->Columns();
vector<DescribeAggregateInfo> aggregates;
aggregates = {DescribeAggregateInfo("count"), DescribeAggregateInfo("mean", true),
DescribeAggregateInfo("stddev", true), DescribeAggregateInfo("min"),
DescribeAggregateInfo("max"), DescribeAggregateInfo("median", true)};
auto expressions = CreateExpressionList(columns, aggregates);
return make_uniq<DuckDBPyRelation>(rel->Aggregate(expressions));
}
string DuckDBPyRelation::ToSQL() {
if (!rel) {
// This relation is just a wrapper around a result set, can't figure out what the SQL was
return "";
}
try {
return rel->GetQueryNode()->ToString();
} catch (const std::exception &) {
return "";
}
}
string DuckDBPyRelation::GenerateExpressionList(const string &function_name, const string &aggregated_columns,
const string &groups, const string &function_parameter,
bool ignore_nulls, const string &projected_columns,
const string &window_spec) {
auto input = StringUtil::Split(aggregated_columns, ',');
return GenerateExpressionList(function_name, std::move(input), groups, function_parameter, ignore_nulls,
projected_columns, window_spec);
}
string DuckDBPyRelation::GenerateExpressionList(const string &function_name, vector<string> input, const string &groups,
const string &function_parameter, bool ignore_nulls,
const string &projected_columns, const string &window_spec) {
string expr;
if (StringUtil::CIEquals("count", function_name) && input.empty()) {
// Insert an artificial '*'
input.push_back("*");
}
if (!projected_columns.empty()) {
expr = projected_columns + ", ";
}
if (input.empty() && !function_parameter.empty()) {
return expr +=
function_name + "(" + function_parameter + ((ignore_nulls) ? " ignore nulls) " : ") ") + window_spec;
}
for (idx_t i = 0; i < input.size(); i++) {
// We parse the input as an expression to validate it.
auto trimmed_input = input[i];
StringUtil::Trim(trimmed_input);
unique_ptr<ParsedExpression> expression;
try {
auto expressions = Parser::ParseExpressionList(trimmed_input);
if (expressions.size() == 1) {
expression = std::move(expressions[0]);
}
} catch (const ParserException &) {
// First attempt at parsing failed, the input might be a column name that needs quoting.
auto quoted_input = KeywordHelper::WriteQuoted(trimmed_input, '"');
auto expressions = Parser::ParseExpressionList(quoted_input);
if (expressions.size() == 1 && expressions[0]->GetExpressionClass() == ExpressionClass::COLUMN_REF) {
expression = std::move(expressions[0]);
}
}
if (!expression) {
throw ParserException("Invalid column expression: %s", trimmed_input);
}
// ToString() handles escaping for all expression types
auto escaped_input = expression->ToString();
if (function_parameter.empty()) {
expr += function_name + "(" + escaped_input + ((ignore_nulls) ? " ignore nulls) " : ") ") + window_spec;
} else {
expr += function_name + "(" + escaped_input + "," + function_parameter +
((ignore_nulls) ? " ignore nulls) " : ") ") + window_spec;
}
if (i < input.size() - 1) {
expr += ",";
}
}
return expr;
}
/* General aggregate functions */
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::GenericAggregator(const string &function_name,
const string &aggregated_columns, const string &groups,
const string &function_parameter,
const string &projected_columns) {
//! Construct Aggregation Expression
auto expr = GenerateExpressionList(function_name, aggregated_columns, groups, function_parameter, false,
projected_columns, "");
return Aggregate(py::str(expr), groups);
}
unique_ptr<DuckDBPyRelation>
DuckDBPyRelation::GenericWindowFunction(const string &function_name, const string &function_parameters,
const string &aggr_columns, const string &window_spec, const bool &ignore_nulls,
const string &projected_columns) {
auto expr = GenerateExpressionList(function_name, aggr_columns, "", function_parameters, ignore_nulls,
projected_columns, window_spec);
return make_uniq<DuckDBPyRelation>(rel->Project(expr));
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::ApplyAggOrWin(const string &function_name, const string &agg_columns,
const string &function_parameters, const string &groups,
const string &window_spec, const string &projected_columns,
bool ignore_nulls) {
if (!groups.empty() && !window_spec.empty()) {
throw InvalidInputException("Either groups or window must be set (can't be both at the same time)");
}
if (!window_spec.empty()) {
return GenericWindowFunction(function_name, function_parameters, agg_columns, window_spec, ignore_nulls,
projected_columns);
} else {
return GenericAggregator(function_name, agg_columns, groups, function_parameters, projected_columns);
}
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::AnyValue(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("any_value", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::ArgMax(const std::string &arg_column, const std::string &value_column,
const std::string &groups, const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("arg_max", arg_column, value_column, groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::ArgMin(const std::string &arg_column, const std::string &value_column,
const std::string &groups, const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("arg_min", arg_column, value_column, groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Avg(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("avg", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::BitAnd(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("bit_and", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::BitOr(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("bit_or", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::BitXor(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("bit_xor", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::BitStringAgg(const std::string &column, const Optional<py::object> &min,
const Optional<py::object> &max, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
if ((min.is_none() && !max.is_none()) || (!min.is_none() && max.is_none())) {
throw InvalidInputException("Both min and max values must be set");
}
if (!min.is_none()) {
if (!py::isinstance<py::int_>(min) || !py::isinstance<py::int_>(max)) {
throw InvalidTypeException("min and max must be of type int");
}
}
auto bitstring_agg_params =
min.is_none() ? "" : (std::to_string(min.cast<int>()) + "," + std::to_string(max.cast<int>()));
return ApplyAggOrWin("bitstring_agg", column, bitstring_agg_params, groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::BoolAnd(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("bool_and", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::BoolOr(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("bool_or", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::ValueCounts(const std::string &column, const std::string &groups) {
return Count(column, groups, "", column);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Count(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("count", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::FAvg(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("favg", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::First(const string &column, const std::string &groups,
const string &projected_columns) {
return GenericAggregator("first", column, groups, "", projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::FSum(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("fsum", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::GeoMean(const std::string &column, const std::string &groups,
const std::string &projected_columns) {
return GenericAggregator("geomean", column, groups, "", projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Histogram(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("histogram", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::List(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("list", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Last(const std::string &column, const std::string &groups,
const std::string &projected_columns) {
return GenericAggregator("last", column, groups, "", projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Max(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("max", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Min(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("min", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Product(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("product", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::StringAgg(const std::string &column, const std::string &sep,
const std::string &groups, const std::string &window_spec,
const std::string &projected_columns) {
auto string_agg_params = KeywordHelper::WriteOptionallyQuoted(sep, '\'');
return ApplyAggOrWin("string_agg", column, string_agg_params, groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Sum(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("sum", column, "", groups, window_spec, projected_columns);
}
/* TODO: Approximate aggregate functions */
/* TODO: Statistical aggregate functions */
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Median(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("median", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Mode(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("mode", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::QuantileCont(const std::string &column, const py::object &q,
const std::string &groups, const std::string &window_spec,
const std::string &projected_columns) {
string quantile_params = "";
if (py::isinstance<py::float_>(q)) {
quantile_params = std::to_string(q.cast<float>());
} else if (py::isinstance<py::list>(q)) {
auto aux = q.cast<std::vector<double>>();
quantile_params += "[";
for (idx_t i = 0; i < aux.size(); i++) {
quantile_params += std::to_string(aux[i]);
if (i < aux.size() - 1) {
quantile_params += ",";
}
}
quantile_params += "]";
} else {
throw InvalidTypeException("Unsupported type for quantile");
}
return ApplyAggOrWin("quantile_cont", column, quantile_params, groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::QuantileDisc(const std::string &column, const py::object &q,
const std::string &groups, const std::string &window_spec,
const std::string &projected_columns) {
string quantile_params = "";
if (py::isinstance<py::float_>(q)) {
quantile_params = std::to_string(q.cast<float>());
} else if (py::isinstance<py::list>(q)) {
auto aux = q.cast<std::vector<double>>();
quantile_params += "[";
for (idx_t i = 0; i < aux.size(); i++) {
quantile_params += std::to_string(aux[i]);
if (i < aux.size() - 1) {
quantile_params += ",";
}
}
quantile_params += "]";
} else {
throw InvalidTypeException("Unsupported type for quantile");
}
return ApplyAggOrWin("quantile_disc", column, quantile_params, groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::StdPop(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("stddev_pop", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::StdSamp(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("stddev_samp", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::VarPop(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("var_pop", column, "", groups, window_spec, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::VarSamp(const std::string &column, const std::string &groups,
const std::string &window_spec,
const std::string &projected_columns) {
return ApplyAggOrWin("var_samp", column, "", groups, window_spec, projected_columns);
}
idx_t DuckDBPyRelation::Length() {
auto aggregate_rel = GenericAggregator("count", "*");
aggregate_rel->Execute();
D_ASSERT(aggregate_rel->result);
auto tmp_res = std::move(aggregate_rel->result);
return tmp_res->FetchChunk()->GetValue(0, 0).GetValue<idx_t>();
}
py::tuple DuckDBPyRelation::Shape() {
auto length = Length();
return py::make_tuple(length, rel->Columns().size());
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Unique(const string &std_columns) {
return make_uniq<DuckDBPyRelation>(rel->Project(std_columns)->Distinct());
}
/* General-purpose window functions */
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::RowNumber(const string &window_spec, const string &projected_columns) {
return GenericWindowFunction("row_number", "", "*", window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Rank(const string &window_spec, const string &projected_columns) {
return GenericWindowFunction("rank", "", "*", window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::DenseRank(const string &window_spec, const string &projected_columns) {
return GenericWindowFunction("dense_rank", "", "*", window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::PercentRank(const string &window_spec, const string &projected_columns) {
return GenericWindowFunction("percent_rank", "", "*", window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::CumeDist(const string &window_spec, const string &projected_columns) {
return GenericWindowFunction("cume_dist", "", "*", window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::FirstValue(const string &column, const string &window_spec,
const string &projected_columns) {
return GenericWindowFunction("first_value", "", column, window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::NTile(const string &window_spec, const int &num_buckets,
const string &projected_columns) {
return GenericWindowFunction("ntile", std::to_string(num_buckets), "", window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Lag(const string &column, const string &window_spec, const int &offset,
const string &default_value, const bool &ignore_nulls,
const string &projected_columns) {
string lag_params = "";
if (offset != 0) {
lag_params += std::to_string(offset);
}
if (!default_value.empty()) {
lag_params += "," + default_value;
}
return GenericWindowFunction("lag", lag_params, column, window_spec, ignore_nulls, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::LastValue(const std::string &column, const std::string &window_spec,
const std::string &projected_columns) {
return GenericWindowFunction("last_value", "", column, window_spec, false, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Lead(const string &column, const string &window_spec, const int &offset,
const string &default_value, const bool &ignore_nulls,
const string &projected_columns) {
string lead_params = "";
if (offset != 0) {
lead_params += std::to_string(offset);
}
if (!default_value.empty()) {
lead_params += "," + default_value;
}
return GenericWindowFunction("lead", lead_params, column, window_spec, ignore_nulls, projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::NthValue(const string &column, const string &window_spec,
const int &offset, const bool &ignore_nulls,
const string &projected_columns) {
return GenericWindowFunction("nth_value", std::to_string(offset), column, window_spec, ignore_nulls,
projected_columns);
}
unique_ptr<DuckDBPyRelation> DuckDBPyRelation::Distinct() {
return make_uniq<DuckDBPyRelation>(rel->Distinct());
}
duckdb::pyarrow::RecordBatchReader DuckDBPyRelation::FetchRecordBatchReader(idx_t rows_per_batch) {
AssertResult();
return result->FetchRecordBatchReader(rows_per_batch);
}
static unique_ptr<QueryResult> PyExecuteRelation(const shared_ptr<Relation> &rel, bool stream_result = false) {
if (!rel) {
return nullptr;
}
auto context = rel->context->GetContext();
D_ASSERT(py::gil_check());
py::gil_scoped_release release;
auto pending_query = context->PendingQuery(rel, stream_result);
return DuckDBPyConnection::CompletePendingQuery(*pending_query);
}
unique_ptr<QueryResult> DuckDBPyRelation::ExecuteInternal(bool stream_result) {
this->executed = true;
return PyExecuteRelation(rel, stream_result);
}
void DuckDBPyRelation::ExecuteOrThrow(bool stream_result) {
py::gil_scoped_acquire gil;
result.reset();
auto query_result = ExecuteInternal(stream_result);
if (!query_result) {
throw InternalException("ExecuteOrThrow - no query available to execute");
}
if (query_result->HasError()) {
query_result->ThrowError();
}
result = make_uniq<DuckDBPyResult>(std::move(query_result));
}
PandasDataFrame DuckDBPyRelation::FetchDF(bool date_as_object) {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow();
}
if (result->IsClosed()) {
return py::none();
}
auto df = result->FetchDF(date_as_object);
result = nullptr;
return df;
}
Optional<py::tuple> DuckDBPyRelation::FetchOne() {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow(true);
}
if (result->IsClosed()) {
return py::none();
}
return result->Fetchone();
}
py::list DuckDBPyRelation::FetchMany(idx_t size) {
if (!result) {
if (!rel) {
return py::list();
}
ExecuteOrThrow(true);
D_ASSERT(result);
}
if (result->IsClosed()) {
return py::list();
}
return result->Fetchmany(size);
}
py::list DuckDBPyRelation::FetchAll() {
if (!result) {
if (!rel) {
return py::list();
}
ExecuteOrThrow();
}
if (result->IsClosed()) {
return py::list();
}
auto res = result->Fetchall();
result = nullptr;
return res;
}
py::dict DuckDBPyRelation::FetchNumpy() {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow();
}
if (result->IsClosed()) {
return py::none();
}
auto res = result->FetchNumpy();
result = nullptr;
return res;
}
py::dict DuckDBPyRelation::FetchPyTorch() {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow();
}
if (result->IsClosed()) {
return py::none();
}
auto res = result->FetchPyTorch();
result = nullptr;
return res;
}
py::dict DuckDBPyRelation::FetchTF() {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow();
}
if (result->IsClosed()) {
return py::none();
}
auto res = result->FetchTF();
result = nullptr;
return res;
}
py::dict DuckDBPyRelation::FetchNumpyInternal(bool stream, idx_t vectors_per_chunk) {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow();
}
AssertResultOpen();
auto res = result->FetchNumpyInternal(stream, vectors_per_chunk);
result = nullptr;
return res;
}
//! Should this also keep track of when the result is empty and set result->result_closed accordingly?
PandasDataFrame DuckDBPyRelation::FetchDFChunk(idx_t vectors_per_chunk, bool date_as_object) {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow(true);
}
AssertResultOpen();
return result->FetchDFChunk(vectors_per_chunk, date_as_object);
}
duckdb::pyarrow::Table DuckDBPyRelation::ToArrowTableInternal(idx_t batch_size, bool to_polars) {
if (!result) {
if (!rel) {
return py::none();
}
auto &config = ClientConfig::GetConfig(*rel->context->GetContext());
ScopedConfigSetting scoped_setting(
config,
[&batch_size](ClientConfig &config) {
config.get_result_collector = [&batch_size](ClientContext &context,
PreparedStatementData &data) -> PhysicalOperator & {
return PhysicalArrowCollector::Create(context, data, batch_size);
};
},
[](ClientConfig &config) { config.get_result_collector = nullptr; });
ExecuteOrThrow();
}
AssertResultOpen();
auto res = result->FetchArrowTable(batch_size, to_polars);
result = nullptr;
return res;
}
duckdb::pyarrow::Table DuckDBPyRelation::ToArrowTable(idx_t batch_size) {
return ToArrowTableInternal(batch_size, false);
}
py::object DuckDBPyRelation::ToArrowCapsule(const py::object &requested_schema) {
if (!result) {
if (!rel) {
return py::none();
}
ExecuteOrThrow();
}
AssertResultOpen();
auto res = result->FetchArrowCapsule();
result = nullptr;
return res;
}