forked from UWQuickstep/quickstep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExecutionGenerator.cpp
2500 lines (2181 loc) · 114 KB
/
ExecutionGenerator.cpp
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#include "query_optimizer/ExecutionGenerator.hpp"
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <functional>
#include <memory>
#include <numeric>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "query_optimizer/QueryOptimizerConfig.h" // For QUICKSTEP_DISTRIBUTED.
#ifdef QUICKSTEP_DISTRIBUTED
#include "catalog/Catalog.pb.h"
#endif
#include "catalog/CatalogAttribute.hpp"
#include "catalog/CatalogDatabase.hpp"
#include "catalog/CatalogRelation.hpp"
#include "catalog/CatalogRelationSchema.hpp"
#include "catalog/CatalogTypedefs.hpp"
#include "catalog/PartitionScheme.hpp"
#include "catalog/PartitionSchemeHeader.hpp"
#include "cli/Flags.hpp"
#include "expressions/Expressions.pb.h"
#include "expressions/aggregation/AggregateFunction.hpp"
#include "expressions/aggregation/AggregateFunction.pb.h"
#include "expressions/aggregation/AggregationID.hpp"
#include "expressions/predicate/Predicate.hpp"
#include "expressions/scalar/Scalar.hpp"
#include "expressions/scalar/ScalarAttribute.hpp"
#include "expressions/window_aggregation/WindowAggregateFunction.hpp"
#include "expressions/window_aggregation/WindowAggregateFunction.pb.h"
#include "query_execution/QueryContext.hpp"
#include "query_execution/QueryContext.pb.h"
#include "query_optimizer/LIPFilterGenerator.hpp"
#include "query_optimizer/OptimizerContext.hpp"
#include "query_optimizer/QueryHandle.hpp"
#include "query_optimizer/QueryPlan.hpp"
#include "query_optimizer/cost_model/SimpleCostModel.hpp"
#include "query_optimizer/cost_model/StarSchemaSimpleCostModel.hpp"
#include "query_optimizer/expressions/AggregateFunction.hpp"
#include "query_optimizer/expressions/Alias.hpp"
#include "query_optimizer/expressions/AttributeReference.hpp"
#include "query_optimizer/expressions/ComparisonExpression.hpp"
#include "query_optimizer/expressions/ExprId.hpp"
#include "query_optimizer/expressions/ExpressionType.hpp"
#include "query_optimizer/expressions/PatternMatcher.hpp"
#include "query_optimizer/expressions/Scalar.hpp"
#include "query_optimizer/expressions/ScalarLiteral.hpp"
#include "query_optimizer/expressions/WindowAggregateFunction.hpp"
#include "query_optimizer/physical/Aggregate.hpp"
#include "query_optimizer/physical/CopyFrom.hpp"
#include "query_optimizer/physical/CopyTo.hpp"
#include "query_optimizer/physical/CreateIndex.hpp"
#include "query_optimizer/physical/CreateTable.hpp"
#include "query_optimizer/physical/CrossReferenceCoalesceAggregate.hpp"
#include "query_optimizer/physical/DeleteTuples.hpp"
#include "query_optimizer/physical/DropTable.hpp"
#include "query_optimizer/physical/FilterJoin.hpp"
#include "query_optimizer/physical/HashJoin.hpp"
#include "query_optimizer/physical/InsertSelection.hpp"
#include "query_optimizer/physical/InsertTuple.hpp"
#include "query_optimizer/physical/LIPFilterConfiguration.hpp"
#include "query_optimizer/physical/NestedLoopsJoin.hpp"
#include "query_optimizer/physical/PartitionSchemeHeader.hpp"
#include "query_optimizer/physical/PatternMatcher.hpp"
#include "query_optimizer/physical/Physical.hpp"
#include "query_optimizer/physical/PhysicalType.hpp"
#include "query_optimizer/physical/Sample.hpp"
#include "query_optimizer/physical/Selection.hpp"
#include "query_optimizer/physical/SharedSubplanReference.hpp"
#include "query_optimizer/physical/Sort.hpp"
#include "query_optimizer/physical/TableGenerator.hpp"
#include "query_optimizer/physical/TableReference.hpp"
#include "query_optimizer/physical/TopLevelPlan.hpp"
#include "query_optimizer/physical/UnionAll.hpp"
#include "query_optimizer/physical/UpdateTable.hpp"
#include "query_optimizer/physical/WindowAggregate.hpp"
#include "relational_operators/AggregationOperator.hpp"
#include "relational_operators/BuildAggregationExistenceMapOperator.hpp"
#include "relational_operators/BuildHashOperator.hpp"
#include "relational_operators/BuildLIPFilterOperator.hpp"
#include "relational_operators/CreateIndexOperator.hpp"
#include "relational_operators/CreateTableOperator.hpp"
#include "relational_operators/DeleteOperator.hpp"
#include "relational_operators/DestroyAggregationStateOperator.hpp"
#include "relational_operators/DestroyHashOperator.hpp"
#include "relational_operators/DropTableOperator.hpp"
#include "relational_operators/FinalizeAggregationOperator.hpp"
#include "relational_operators/HashJoinOperator.hpp"
#include "relational_operators/InitializeAggregationOperator.hpp"
#include "relational_operators/InsertOperator.hpp"
#include "relational_operators/NestedLoopsJoinOperator.hpp"
#include "relational_operators/RelationalOperator.hpp"
#include "relational_operators/SampleOperator.hpp"
#include "relational_operators/SaveBlocksOperator.hpp"
#include "relational_operators/SelectOperator.hpp"
#include "relational_operators/SortMergeRunOperator.hpp"
#include "relational_operators/SortRunGenerationOperator.hpp"
#include "relational_operators/TableExportOperator.hpp"
#include "relational_operators/TableGeneratorOperator.hpp"
#include "relational_operators/TextScanOperator.hpp"
#include "relational_operators/UnionAllOperator.hpp"
#include "relational_operators/UpdateOperator.hpp"
#include "relational_operators/WindowAggregationOperator.hpp"
#include "storage/AggregationOperationState.pb.h"
#include "storage/HashTable.pb.h"
#include "storage/HashTableFactory.hpp"
#include "storage/InsertDestination.pb.h"
#include "storage/StorageBlockLayout.hpp"
#include "storage/StorageBlockLayout.pb.h"
#include "storage/StorageConstants.hpp"
#include "storage/SubBlockTypeRegistry.hpp"
#include "types/Type.hpp"
#include "types/Type.pb.h"
#include "types/TypedValue.hpp"
#include "types/TypedValue.pb.h"
#include "types/containers/Tuple.pb.h"
#include "utility/BarrieredReadWriteConcurrentBitVector.hpp"
#include "utility/SqlError.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
using std::atomic;
using std::make_unique;
using std::move;
using std::pair;
using std::static_pointer_cast;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
namespace quickstep {
namespace optimizer {
DEFINE_string(join_hashtable_type, "SeparateChaining",
"HashTable implementation to use for hash joins (valid options "
"are SeparateChaining or LinearOpenAddressing)");
static const volatile bool join_hashtable_type_dummy
= gflags::RegisterFlagValidator(&FLAGS_join_hashtable_type,
&ValidateHashTableImplTypeString);
DEFINE_string(aggregate_hashtable_type, "SeparateChaining",
"HashTable implementation to use for aggregates with GROUP BY "
"(valid options are SeparateChaining or LinearOpenAddressing)");
static const volatile bool aggregate_hashtable_type_dummy
= gflags::RegisterFlagValidator(&FLAGS_aggregate_hashtable_type,
&ValidateHashTableImplTypeString);
DEFINE_bool(parallelize_load, true, "Parallelize loading data files.");
static bool ValidateNumAggregationPartitions(const char *flagname, int value) {
return value > 0;
}
DEFINE_int32(num_aggregation_partitions,
41,
"The number of partitions in PartitionedHashTablePool used for "
"performing the aggregation");
static const volatile bool num_aggregation_partitions_dummy
= gflags::RegisterFlagValidator(&FLAGS_num_aggregation_partitions, &ValidateNumAggregationPartitions);
DEFINE_uint64(partition_aggregation_num_groups_threshold,
100000,
"The threshold used for deciding whether the aggregation is done "
"in a partitioned way or not");
namespace E = ::quickstep::optimizer::expressions;
namespace P = ::quickstep::optimizer::physical;
namespace S = ::quickstep::serialization;
namespace {
size_t CacheLineAlignedBytes(const size_t actual_bytes) {
return (actual_bytes + kCacheLineBytes - 1) / kCacheLineBytes * kCacheLineBytes;
}
size_t CalculateNumInitializationPartitionsForCollisionFreeVectorTable(const size_t memory_size) {
// At least 1 partition, at most (#workers * 2) partitions.
return std::max(1uL, std::min(memory_size / kCollisonFreeVectorInitBlobSize,
static_cast<size_t>(2 * FLAGS_num_workers)));
}
void CalculateCollisionFreeAggregationInfo(
const size_t num_entries, const vector<pair<AggregationID, vector<const Type *>>> &group_by_aggrs_info,
S::CollisionFreeVectorInfo *collision_free_vector_info) {
size_t memory_size = CacheLineAlignedBytes(
BarrieredReadWriteConcurrentBitVector::BytesNeeded(num_entries));
for (std::size_t i = 0; i < group_by_aggrs_info.size(); ++i) {
const auto &group_by_aggr_info = group_by_aggrs_info[i];
size_t state_size = 0;
switch (group_by_aggr_info.first) {
case AggregationID::kCount: {
state_size = sizeof(atomic<size_t>);
break;
}
case AggregationID::kSum: {
const vector<const Type *> &argument_types = group_by_aggr_info.second;
DCHECK_EQ(1u, argument_types.size());
switch (argument_types.front()->getTypeID()) {
case TypeID::kInt:
case TypeID::kLong:
state_size = sizeof(atomic<std::int64_t>);
break;
case TypeID::kFloat:
case TypeID::kDouble:
state_size = sizeof(atomic<double>);
break;
default:
LOG(FATAL) << "No support by CollisionFreeVector";
}
break;
}
default:
LOG(FATAL) << "No support by CollisionFreeVector";
}
collision_free_vector_info->add_state_offsets(memory_size);
memory_size += CacheLineAlignedBytes(state_size * num_entries);
}
collision_free_vector_info->set_memory_size(memory_size);
collision_free_vector_info->set_num_init_partitions(
CalculateNumInitializationPartitionsForCollisionFreeVectorTable(memory_size));
}
size_t CalculateNumFinalizationPartitionsForCollisionFreeVectorTable(const size_t num_entries) {
// Set finalization segment size as 4096 entries.
constexpr size_t kFinalizeSegmentSize = 4uL * 1024L;
// At least 1 partition, at most (#workers * 2) partitions.
return std::max(1uL, std::min(num_entries / kFinalizeSegmentSize,
static_cast<size_t>(2 * FLAGS_num_workers)));
}
bool CheckAggregatePartitioned(const std::size_t num_aggregate_functions,
const std::vector<bool> &is_distincts,
const std::vector<attribute_id> &group_by_attrs,
const std::size_t estimated_num_groups) {
// If there's no aggregation, return false.
if (num_aggregate_functions == 0) {
return false;
}
// If there is only only aggregate function, we allow distinct aggregation.
// Otherwise it can't be partitioned with distinct aggregation.
if (num_aggregate_functions > 1) {
for (const bool distinct : is_distincts) {
if (distinct) {
return false;
}
}
}
// There's no distinct aggregation involved, Check if there's at least one
// GROUP BY operation.
if (group_by_attrs.empty()) {
return false;
}
// Currently we require that all the group-by keys are ScalarAttributes for
// the convenient of implementing copy elision.
// TODO(jianqiao): relax this requirement.
for (const attribute_id group_by_attr : group_by_attrs) {
if (group_by_attr == kInvalidAttributeID) {
return false;
}
}
// Currently we always use partitioned aggregation to parallelize distinct
// aggregation.
const bool all_distinct = std::accumulate(is_distincts.begin(), is_distincts.end(),
!is_distincts.empty(), std::logical_and<bool>());
if (all_distinct) {
return true;
}
// There are GROUP BYs without DISTINCT. Check if the estimated number of
// groups is large enough to warrant a partitioned aggregation.
return estimated_num_groups >= FLAGS_partition_aggregation_num_groups_threshold;
}
} // namespace
constexpr QueryPlan::DAGNodeIndex ExecutionGenerator::CatalogRelationInfo::kInvalidOperatorIndex;
void ExecutionGenerator::generatePlan(const P::PhysicalPtr &physical_plan) {
CHECK(P::SomeTopLevelPlan::MatchesWithConditionalCast(physical_plan, &top_level_physical_plan_))
<< "The physical plan must be rooted by a TopLevelPlan";
cost_model_for_aggregation_.reset(
new cost::StarSchemaSimpleCostModel(top_level_physical_plan_->shared_subplans()));
cost_model_for_hash_join_.reset(
new cost::SimpleCostModel(top_level_physical_plan_->shared_subplans()));
const auto &lip_filter_configuration =
top_level_physical_plan_->lip_filter_configuration();
if (lip_filter_configuration != nullptr) {
lip_filter_generator_.reset(new LIPFilterGenerator(lip_filter_configuration));
}
const CatalogRelation *result_relation = nullptr;
try {
for (const P::PhysicalPtr &shared_subplan : top_level_physical_plan_->shared_subplans()) {
generatePlanInternal(shared_subplan);
}
generatePlanInternal(top_level_physical_plan_->plan());
// Deploy LIPFilters if enabled.
if (lip_filter_generator_ != nullptr) {
lip_filter_generator_->deployLIPFilters(execution_plan_, query_context_proto_);
}
// Set the query result relation if the input plan exists in physical_to_execution_map_,
// which indicates the plan is the result of a SELECT query.
const std::unordered_map<P::PhysicalPtr, CatalogRelationInfo>::const_iterator it =
physical_to_output_relation_map_.find(top_level_physical_plan_->plan());
if (it != physical_to_output_relation_map_.end()) {
result_relation = it->second.relation;
}
#ifdef QUICKSTEP_DEBUG
std::unordered_set<relation_id> temp_relations;
for (const CatalogRelationInfo &temporary_relation_info : temporary_relation_info_vec_) {
temp_relations.insert(temporary_relation_info.relation->getID());
}
DCHECK_EQ(temporary_relation_info_vec_.size(), temp_relations.size());
#endif
} catch (...) {
// Drop all temporary relations.
dropAllTemporaryRelations();
throw;
}
// Add one DropTableOperator per temporary relation, except for the result relation, if any.
// NOTE(zuyu): the Cli shell drops the result relation after printing, if enabled.
for (const CatalogRelationInfo &temporary_relation_info : temporary_relation_info_vec_) {
const CatalogRelation *temporary_relation = temporary_relation_info.relation;
if (temporary_relation == result_relation) {
query_handle_->setQueryResultRelation(
catalog_database_->getRelationByIdMutable(result_relation->getID()));
continue;
}
const QueryPlan::DAGNodeIndex drop_table_index =
execution_plan_->addRelationalOperator(
new DropTableOperator(query_handle_->query_id(),
*temporary_relation,
catalog_database_,
false /* only_drop_blocks */));
DCHECK(!temporary_relation_info.isStoredRelation());
execution_plan_->addDependenciesForDropOperator(
drop_table_index,
temporary_relation_info.producer_operator_index);
}
#ifdef QUICKSTEP_DISTRIBUTED
catalog_database_cache_proto_->set_name(catalog_database_->getName());
LOG(INFO) << "CatalogDatabaseCache proto has " << referenced_relation_ids_.size() << " relation(s)";
for (const relation_id rel_id : referenced_relation_ids_) {
const CatalogRelationSchema &relation =
catalog_database_->getRelationSchemaById(rel_id);
LOG(INFO) << "RelationSchema " << rel_id
<< ", name: " << relation.getName()
<< ", " << relation.size() << " attribute(s)";
catalog_database_cache_proto_->add_relations()->MergeFrom(relation.getProto());
}
#endif
}
void ExecutionGenerator::generatePlanInternal(
const P::PhysicalPtr &physical_plan) {
// Generate the execution plan in bottom-up.
for (const P::PhysicalPtr &child : physical_plan->children()) {
generatePlanInternal(child);
}
// If enabled, collect attribute substitution map for LIPFilterGenerator.
if (lip_filter_generator_ != nullptr) {
lip_filter_generator_->registerAttributeMap(physical_plan, attribute_substitution_map_);
}
switch (physical_plan->getPhysicalType()) {
case P::PhysicalType::kAggregate:
return convertAggregate(
std::static_pointer_cast<const P::Aggregate>(physical_plan));
case P::PhysicalType::kCrossReferenceCoalesceAggregate:
return convertCrossReferenceCoalesceAggregate(
std::static_pointer_cast<const P::CrossReferenceCoalesceAggregate>(physical_plan));
case P::PhysicalType::kCopyFrom:
return convertCopyFrom(
std::static_pointer_cast<const P::CopyFrom>(physical_plan));
case P::PhysicalType::kCopyTo:
return convertCopyTo(
std::static_pointer_cast<const P::CopyTo>(physical_plan));
case P::PhysicalType::kCreateIndex:
return convertCreateIndex(
std::static_pointer_cast<const P::CreateIndex>(physical_plan));
case P::PhysicalType::kCreateTable:
return convertCreateTable(
std::static_pointer_cast<const P::CreateTable>(physical_plan));
case P::PhysicalType::kDeleteTuples:
return convertDeleteTuples(
std::static_pointer_cast<const P::DeleteTuples>(physical_plan));
case P::PhysicalType::kDropTable:
return convertDropTable(
std::static_pointer_cast<const P::DropTable>(physical_plan));
case P::PhysicalType::kFilterJoin:
return convertFilterJoin(
std::static_pointer_cast<const P::FilterJoin>(physical_plan));
case P::PhysicalType::kHashJoin:
return convertHashJoin(
std::static_pointer_cast<const P::HashJoin>(physical_plan));
case P::PhysicalType::kInsertSelection:
return convertInsertSelection(
std::static_pointer_cast<const P::InsertSelection>(physical_plan));
case P::PhysicalType::kInsertTuple:
return convertInsertTuple(
std::static_pointer_cast<const P::InsertTuple>(physical_plan));
case P::PhysicalType::kNestedLoopsJoin:
return convertNestedLoopsJoin(
std::static_pointer_cast<const P::NestedLoopsJoin>(physical_plan));
case P::PhysicalType::kSample:
return convertSample(
std::static_pointer_cast<const P::Sample>(physical_plan));
case P::PhysicalType::kSelection:
return convertSelection(
std::static_pointer_cast<const P::Selection>(physical_plan));
case P::PhysicalType::kSharedSubplanReference:
return convertSharedSubplanReference(
std::static_pointer_cast<const P::SharedSubplanReference>(physical_plan));
case P::PhysicalType::kSort:
return convertSort(
std::static_pointer_cast<const P::Sort>(physical_plan));
case P::PhysicalType::kTableGenerator:
return convertTableGenerator(
std::static_pointer_cast<const P::TableGenerator>(physical_plan));
case P::PhysicalType::kTableReference:
return convertTableReference(
std::static_pointer_cast<const P::TableReference>(physical_plan));
case P::PhysicalType::kUnionAll:
return convertUnionAll(
std::static_pointer_cast<const P::UnionAll>(physical_plan));
case P::PhysicalType::kUpdateTable:
return convertUpdateTable(
std::static_pointer_cast<const P::UpdateTable>(physical_plan));
case P::PhysicalType::kWindowAggregate:
return convertWindowAggregate(
std::static_pointer_cast<const P::WindowAggregate>(physical_plan));
default:
LOG(FATAL) << "Unknown physical plan node "
<< physical_plan->getShortString();
}
}
std::string ExecutionGenerator::getNewRelationName() {
std::ostringstream out;
out << OptimizerContext::kInternalTemporaryRelationNamePrefix
<< query_handle_->query_id() << "_" << rel_id_;
++rel_id_;
return out.str();
}
void ExecutionGenerator::createTemporaryCatalogRelation(
const P::PhysicalPtr &physical,
const CatalogRelation **catalog_relation_output,
S::InsertDestination *insert_destination_proto) {
auto catalog_relation =
make_unique<CatalogRelation>(catalog_database_, getNewRelationName(), -1 /* id */, true /* is_temporary*/);
const P::PartitionSchemeHeader *partition_scheme_header = physical->getOutputPartitionSchemeHeader();
if (partition_scheme_header) {
PartitionSchemeHeader::PartitionAttributeIds output_partition_attr_ids;
for (const auto &partition_equivalent_expr_ids : partition_scheme_header->partition_expr_ids) {
DCHECK(!partition_equivalent_expr_ids.empty());
const E::ExprId partition_expr_id = *partition_equivalent_expr_ids.begin();
DCHECK(attribute_substitution_map_.find(partition_expr_id) != attribute_substitution_map_.end());
// Use the attribute id from the input relation.
// NOTE(zuyu): The following line should be before changing
// 'attribute_substitution_map_' with the output attributes.
output_partition_attr_ids.push_back(attribute_substitution_map_[partition_expr_id]->getID());
}
const size_t num_partition = partition_scheme_header->num_partitions;
unique_ptr<PartitionSchemeHeader> output_partition_scheme_header;
switch (partition_scheme_header->partition_type) {
case P::PartitionSchemeHeader::PartitionType::kHash:
output_partition_scheme_header =
make_unique<HashPartitionSchemeHeader>(num_partition, move(output_partition_attr_ids));
break;
case P::PartitionSchemeHeader::PartitionType::kRandom:
output_partition_scheme_header =
make_unique<RandomPartitionSchemeHeader>(num_partition);
break;
case P::PartitionSchemeHeader::PartitionType::kRange:
LOG(FATAL) << "Unimplemented";
default:
LOG(FATAL) << "Unknown partition type";
}
auto output_partition_scheme = make_unique<PartitionScheme>(output_partition_scheme_header.release());
insert_destination_proto->set_insert_destination_type(S::InsertDestinationType::PARTITION_AWARE);
insert_destination_proto->MutableExtension(S::PartitionAwareInsertDestination::partition_scheme)
->MergeFrom(output_partition_scheme->getProto());
catalog_relation->setPartitionScheme(output_partition_scheme.release());
} else {
insert_destination_proto->set_insert_destination_type(S::InsertDestinationType::BLOCK_POOL);
}
attribute_id aid = 0;
for (const auto &project_expression :
physical->getOutputAttributes()) {
// The attribute name is simply set to the attribute id to make it distinct.
auto catalog_attribute =
make_unique<CatalogAttribute>(catalog_relation.get(), std::to_string(aid),
project_expression->getValueType(), aid,
project_expression->attribute_alias());
attribute_substitution_map_[project_expression->id()] =
catalog_attribute.get();
catalog_relation->addAttribute(catalog_attribute.release());
++aid;
}
*catalog_relation_output = catalog_relation.get();
const relation_id output_rel_id = catalog_database_->addRelation(
catalog_relation.release());
insert_destination_proto->set_relation_id(output_rel_id);
#ifdef QUICKSTEP_DISTRIBUTED
referenced_relation_ids_.insert(output_rel_id);
#endif
}
void ExecutionGenerator::dropAllTemporaryRelations() {
for (const CatalogRelationInfo &temporary_relation_info :
temporary_relation_info_vec_) {
DCHECK_EQ(temporary_relation_info.relation->size_blocks(), 0u);
catalog_database_->dropRelationById(temporary_relation_info.relation->getID());
}
}
void ExecutionGenerator::convertNamedExpressions(
const std::vector<E::NamedExpressionPtr> &named_expressions,
S::QueryContext::ScalarGroup *scalar_group_proto,
const std::unordered_set<E::ExprId> &left_expr_ids,
const std::unordered_set<E::ExprId> &right_expr_ids) {
for (const E::NamedExpressionPtr &project_expression : named_expressions) {
unique_ptr<const Scalar> execution_scalar;
E::AliasPtr alias;
if (E::SomeAlias::MatchesWithConditionalCast(project_expression, &alias)) {
E::ScalarPtr scalar;
// We have not added aggregate expressions yet,
// so all child expressions of an Alias should be a Scalar.
CHECK(E::SomeScalar::MatchesWithConditionalCast(alias->expression(), &scalar))
<< alias->toString();
execution_scalar.reset(
scalar->concretize(attribute_substitution_map_, left_expr_ids, right_expr_ids));
} else {
execution_scalar.reset(
project_expression->concretize(attribute_substitution_map_, left_expr_ids, right_expr_ids));
}
scalar_group_proto->add_scalars()->MergeFrom(execution_scalar->getProto());
}
}
Predicate* ExecutionGenerator::convertPredicate(
const expressions::PredicatePtr &optimizer_predicate,
const std::unordered_set<E::ExprId> &left_expr_ids,
const std::unordered_set<E::ExprId> &right_expr_ids) const {
return optimizer_predicate->concretize(attribute_substitution_map_, left_expr_ids, right_expr_ids);
}
void ExecutionGenerator::convertTableReference(
const P::TableReferencePtr &physical_table_reference) {
// TableReference is not converted to an execution operator;
// instead it just provides CatalogRelation info for its
// parent (e.g. the substitution map from an AttributeReference
// to a CatalogAttribute).
const CatalogRelation *catalog_relation = physical_table_reference->relation();
#ifdef QUICKSTEP_DISTRIBUTED
referenced_relation_ids_.insert(catalog_relation->getID());
#endif
const std::vector<E::AttributeReferencePtr> &attribute_references =
physical_table_reference->attribute_list();
DCHECK_EQ(attribute_references.size(), catalog_relation->size());
for (CatalogRelation::size_type i = 0; i < catalog_relation->size(); ++i) {
attribute_substitution_map_.emplace(attribute_references[i]->id(),
catalog_relation->getAttributeById(i));
}
physical_to_output_relation_map_.emplace(
std::piecewise_construct,
std::forward_as_tuple(physical_table_reference),
std::forward_as_tuple(CatalogRelationInfo::kInvalidOperatorIndex,
catalog_relation));
}
void ExecutionGenerator::convertSample(const P::SamplePtr &physical_sample) {
// Create InsertDestination proto.
const CatalogRelation *output_relation = nullptr;
const QueryContext::insert_destination_id insert_destination_index =
query_context_proto_->insert_destinations_size();
S::InsertDestination *insert_destination_proto =
query_context_proto_->add_insert_destinations();
createTemporaryCatalogRelation(physical_sample,
&output_relation,
insert_destination_proto);
// Create and add a Sample operator.
const CatalogRelationInfo *input_relation_info =
findRelationInfoOutputByPhysical(physical_sample->input());
DCHECK(input_relation_info != nullptr);
SampleOperator *sample_op =
new SampleOperator(query_handle_->query_id(),
*input_relation_info->relation,
*output_relation,
insert_destination_index,
input_relation_info->isStoredRelation(),
physical_sample->is_block_sample(),
physical_sample->percentage());
const QueryPlan::DAGNodeIndex sample_index =
execution_plan_->addRelationalOperator(sample_op);
insert_destination_proto->set_relational_op_index(sample_index);
if (!input_relation_info->isStoredRelation()) {
execution_plan_->addDirectDependency(sample_index,
input_relation_info->producer_operator_index,
false /* is_pipeline_breaker */);
}
physical_to_output_relation_map_.emplace(
std::piecewise_construct,
std::forward_as_tuple(physical_sample),
std::forward_as_tuple(sample_index,
output_relation));
temporary_relation_info_vec_.emplace_back(sample_index, output_relation);
}
bool ExecutionGenerator::convertSimpleProjection(
const QueryContext::scalar_group_id project_expressions_group_index,
std::vector<attribute_id> *attributes) const {
const S::QueryContext::ScalarGroup &scalar_group_proto =
query_context_proto_->scalar_groups(project_expressions_group_index);
for (int i = 0; i < scalar_group_proto.scalars_size(); ++i) {
if (scalar_group_proto.scalars(i).data_source() != S::Scalar::ATTRIBUTE) {
return false;
}
}
for (int i = 0; i < scalar_group_proto.scalars_size(); ++i) {
attributes->push_back(
scalar_group_proto.scalars(i).GetExtension(S::ScalarAttribute::attribute_id));
}
return true;
}
void ExecutionGenerator::convertSelection(
const P::SelectionPtr &physical_selection) {
const P::PhysicalPtr &input = physical_selection->input();
const CatalogRelationInfo *input_relation_info =
findRelationInfoOutputByPhysical(input);
DCHECK(input_relation_info != nullptr);
const CatalogRelation &input_relation = *input_relation_info->relation;
// Check if the Selection is only for renaming columns.
if (physical_selection->filter_predicate() == nullptr) {
const P::PartitionSchemeHeader *physical_select_partition_scheme_header =
physical_selection->getOutputPartitionSchemeHeader();
const P::PartitionSchemeHeader *physical_input_partition_scheme_header = input->getOutputPartitionSchemeHeader();
const bool are_same_physical_partition_scheme_headers =
(!physical_select_partition_scheme_header && !physical_input_partition_scheme_header) ||
(physical_select_partition_scheme_header && physical_input_partition_scheme_header &&
physical_select_partition_scheme_header->equal(*physical_input_partition_scheme_header));
const std::vector<E::AttributeReferencePtr> input_attributes = input->getOutputAttributes();
const std::vector<E::NamedExpressionPtr> &project_expressions =
physical_selection->project_expressions();
if (project_expressions.size() == input_attributes.size() && are_same_physical_partition_scheme_headers) {
bool has_different_attrs = false;
for (std::size_t attr_idx = 0; attr_idx < input_attributes.size(); ++attr_idx) {
if (project_expressions[attr_idx]->id() != input_attributes[attr_idx]->id()) {
has_different_attrs = true;
break;
}
}
if (!has_different_attrs) {
if (!input_relation_info->isStoredRelation()) {
CatalogRelation *catalog_relation =
const_cast<CatalogRelation*>(input_relation_info->relation);
for (std::size_t attr_idx = 0; attr_idx < project_expressions.size(); ++attr_idx) {
CatalogAttribute *catalog_attribute =
catalog_relation->getAttributeByIdMutable(attr_idx);
DCHECK(catalog_attribute != nullptr);
catalog_attribute->setDisplayName(
project_expressions[attr_idx]->attribute_alias());
}
physical_to_output_relation_map_.emplace(physical_selection,
*input_relation_info);
return;
}
}
}
}
// Convert the project expressions proto.
const QueryContext::scalar_group_id project_expressions_group_index =
query_context_proto_->scalar_groups_size();
convertNamedExpressions(physical_selection->project_expressions(),
query_context_proto_->add_scalar_groups());
// Convert the predicate proto.
QueryContext::predicate_id execution_predicate_index = QueryContext::kInvalidPredicateId;
if (physical_selection->filter_predicate()) {
execution_predicate_index = query_context_proto_->predicates_size();
unique_ptr<const Predicate> execution_predicate(convertPredicate(physical_selection->filter_predicate()));
query_context_proto_->add_predicates()->MergeFrom(execution_predicate->getProto());
}
// Create InsertDestination proto.
const CatalogRelation *output_relation = nullptr;
const QueryContext::insert_destination_id insert_destination_index =
query_context_proto_->insert_destinations_size();
S::InsertDestination *insert_destination_proto = query_context_proto_->add_insert_destinations();
createTemporaryCatalogRelation(physical_selection,
&output_relation,
insert_destination_proto);
// Create and add a Select operator.
const bool has_repartition = physical_selection->hasRepartition();
// Use the "simple" form of the selection operator (a pure projection that
// doesn't require any expression evaluation or intermediate copies) if
// possible.
std::vector<attribute_id> attributes;
SelectOperator *op =
convertSimpleProjection(project_expressions_group_index, &attributes)
? new SelectOperator(query_handle_->query_id(),
input_relation,
has_repartition,
*output_relation,
insert_destination_index,
execution_predicate_index,
move(attributes),
input_relation_info->isStoredRelation())
: new SelectOperator(query_handle_->query_id(),
input_relation,
has_repartition,
*output_relation,
insert_destination_index,
execution_predicate_index,
project_expressions_group_index,
input_relation_info->isStoredRelation());
const QueryPlan::DAGNodeIndex select_index =
execution_plan_->addRelationalOperator(op);
insert_destination_proto->set_relational_op_index(select_index);
if (!input_relation_info->isStoredRelation()) {
execution_plan_->addDirectDependency(select_index,
input_relation_info->producer_operator_index,
false /* is_pipeline_breaker */);
} else if (input_relation.isTemporary()) {
// NOTE(zuyu): drop the temp relation created by EliminateEmptyNode rule.
temporary_relation_info_vec_.emplace_back(select_index, &input_relation);
}
physical_to_output_relation_map_.emplace(
std::piecewise_construct,
std::forward_as_tuple(physical_selection),
std::forward_as_tuple(select_index,
output_relation));
temporary_relation_info_vec_.emplace_back(select_index, output_relation);
if (lip_filter_generator_ != nullptr) {
lip_filter_generator_->addSelectionInfo(physical_selection, select_index);
}
}
void ExecutionGenerator::convertSharedSubplanReference(const physical::SharedSubplanReferencePtr &physical_plan) {
const std::unordered_map<physical::PhysicalPtr, CatalogRelationInfo>::const_iterator found_it =
physical_to_output_relation_map_.find(
top_level_physical_plan_->shared_subplan_at(physical_plan->subplan_id()));
if (found_it != physical_to_output_relation_map_.end()) {
physical_to_output_relation_map_.emplace(physical_plan, found_it->second);
// Propagate the (ExprId -> CatalogAttribute) mapping.
const std::vector<E::AttributeReferencePtr> &referenced_attributes =
physical_plan->referenced_attributes();
const std::vector<E::AttributeReferencePtr> &output_attributes =
physical_plan->output_attributes();
for (std::size_t i = 0; i < referenced_attributes.size(); ++i) {
attribute_substitution_map_[output_attributes[i]->id()] =
attribute_substitution_map_[referenced_attributes[i]->id()];
}
}
}
void ExecutionGenerator::convertFilterJoin(const P::FilterJoinPtr &physical_plan) {
const P::PhysicalPtr &probe_physical = physical_plan->left();
P::PhysicalPtr build_physical = physical_plan->right();
// Let B denote the build side child. If B is also a FilterJoin, then the
// actual "concrete" input relation is B's probe side child, and B's build
// side becomes a LIPFilter that is attached to the BuildLIPFilterOperator
// created below.
P::FilterJoinPtr filter_join;
if (P::SomeFilterJoin::MatchesWithConditionalCast(build_physical, &filter_join)) {
build_physical = filter_join->left();
DCHECK(build_physical->getPhysicalType() != P::PhysicalType::kFilterJoin);
}
// Convert the predicate proto.
QueryContext::predicate_id build_side_predicate_index = QueryContext::kInvalidPredicateId;
if (physical_plan->build_side_filter_predicate()) {
build_side_predicate_index = query_context_proto_->predicates_size();
std::unique_ptr<const Predicate> build_side_predicate(
convertPredicate(physical_plan->build_side_filter_predicate()));
query_context_proto_->add_predicates()->MergeFrom(build_side_predicate->getProto());
}
const CatalogRelationInfo *probe_relation_info =
findRelationInfoOutputByPhysical(probe_physical);
const CatalogRelationInfo *build_relation_info =
findRelationInfoOutputByPhysical(build_physical);
const CatalogRelation &build_relation = *build_relation_info->relation;
// Create a BuildLIPFilterOperator for the FilterJoin. This operator builds
// LIP filters that are applied properly in downstream operators to achieve
// the filter-join semantics.
const QueryPlan::DAGNodeIndex build_filter_operator_index =
execution_plan_->addRelationalOperator(
new BuildLIPFilterOperator(
query_handle_->query_id(),
build_relation,
build_side_predicate_index,
build_relation_info->isStoredRelation()));
if (!build_relation_info->isStoredRelation()) {
execution_plan_->addDirectDependency(build_filter_operator_index,
build_relation_info->producer_operator_index,
false /* is_pipeline_breaker */);
}
physical_to_output_relation_map_.emplace(
std::piecewise_construct,
std::forward_as_tuple(physical_plan),
std::forward_as_tuple(probe_relation_info->producer_operator_index,
probe_relation_info->relation));
DCHECK(lip_filter_generator_ != nullptr);
lip_filter_generator_->addFilterJoinInfo(physical_plan,
build_filter_operator_index);
}
void ExecutionGenerator::convertHashJoin(const P::HashJoinPtr &physical_plan) {
// HashJoin is converted to three operators:
// BuildHash, HashJoin, DestroyHash. The second is the primary operator.
const P::PhysicalPtr &probe_physical = physical_plan->left();
const P::PhysicalPtr &build_physical = physical_plan->right();
std::vector<attribute_id> probe_attribute_ids;
std::vector<attribute_id> build_attribute_ids;
const std::size_t build_cardinality =
cost_model_for_hash_join_->estimateCardinality(build_physical);
bool any_probe_attributes_nullable = false;
bool any_build_attributes_nullable = false;
const std::vector<E::AttributeReferencePtr> &left_join_attributes =
physical_plan->left_join_attributes();
for (const E::AttributeReferencePtr &left_join_attribute : left_join_attributes) {
const CatalogAttribute *probe_catalog_attribute
= attribute_substitution_map_[left_join_attribute->id()];
probe_attribute_ids.emplace_back(probe_catalog_attribute->getID());
if (probe_catalog_attribute->getType().isNullable()) {
any_probe_attributes_nullable = true;
}
}
const std::vector<E::AttributeReferencePtr> &right_join_attributes =
physical_plan->right_join_attributes();
for (const E::AttributeReferencePtr &right_join_attribute : right_join_attributes) {
const CatalogAttribute *build_catalog_attribute
= attribute_substitution_map_[right_join_attribute->id()];
build_attribute_ids.emplace_back(build_catalog_attribute->getID());
if (build_catalog_attribute->getType().isNullable()) {
any_build_attributes_nullable = true;
}
}
// Remember key types for call to SimplifyHashTableImplTypeProto() below.
std::vector<const Type*> key_types;
for (std::vector<E::AttributeReferencePtr>::size_type attr_idx = 0;
attr_idx < left_join_attributes.size();
++attr_idx) {
const Type &left_attribute_type = left_join_attributes[attr_idx]->getValueType();
const Type &right_attribute_type = right_join_attributes[attr_idx]->getValueType();
if (left_attribute_type.getTypeID() != right_attribute_type.getTypeID()) {
THROW_SQL_ERROR() << "Equality join predicate between two attributes of different types "
"is not allowed in HashJoin";
}
key_types.push_back(&left_attribute_type);
}
std::unordered_set<E::ExprId> probe_expr_ids;
const auto probe_output_attributes = probe_physical->getOutputAttributes();
probe_expr_ids.reserve(probe_output_attributes.size());
for (const auto &probe_output_attribute : probe_output_attributes) {
probe_expr_ids.insert(probe_output_attribute->id());
}
std::unordered_set<E::ExprId> build_expr_ids;
const auto build_output_attributes = build_physical->getOutputAttributes();
build_expr_ids.reserve(build_output_attributes.size());
for (const auto &build_output_attribute : build_output_attributes) {
build_expr_ids.insert(build_output_attribute->id());
}
// Convert the residual predicate proto.
QueryContext::predicate_id residual_predicate_index = QueryContext::kInvalidPredicateId;
if (physical_plan->residual_predicate()) {
residual_predicate_index = query_context_proto_->predicates_size();
unique_ptr<const Predicate> residual_predicate(
convertPredicate(physical_plan->residual_predicate(), probe_expr_ids, build_expr_ids));
query_context_proto_->add_predicates()->MergeFrom(residual_predicate->getProto());
}
// Convert the build predicate proto.
QueryContext::predicate_id build_predicate_index = QueryContext::kInvalidPredicateId;
if (physical_plan->build_predicate()) {
build_predicate_index = query_context_proto_->predicates_size();
unique_ptr<const Predicate> build_predicate(
convertPredicate(physical_plan->build_predicate(), probe_expr_ids, build_expr_ids));
query_context_proto_->add_predicates()->MergeFrom(build_predicate->getProto());
}
// Convert the project expressions proto.
const QueryContext::scalar_group_id project_expressions_group_index =
query_context_proto_->scalar_groups_size();
convertNamedExpressions(physical_plan->project_expressions(),
query_context_proto_->add_scalar_groups(), probe_expr_ids, build_expr_ids);
const CatalogRelationInfo *build_relation_info =
findRelationInfoOutputByPhysical(build_physical);
const CatalogRelationInfo *probe_relation_info =
findRelationInfoOutputByPhysical(probe_physical);
// Create a vector that indicates whether each project expression is using
// attributes from the build relation as input. This information is required
// by the current implementation of hash left outer join
std::unique_ptr<std::vector<bool>> is_selection_on_build;
if (physical_plan->join_type() == P::HashJoin::JoinType::kLeftOuterJoin) {
is_selection_on_build.reset(
new std::vector<bool>(
E::MarkExpressionsReferingAnyAttribute(
physical_plan->project_expressions(),