-
-
Notifications
You must be signed in to change notification settings - Fork 233
/
Copy pathOptimizer.cpp
3269 lines (2638 loc) · 89 KB
/
Optimizer.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
/*
* The contents of this file are subject to the Interbase Public
* License Version 1.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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
* 2002.10.12: Nickolay Samofatov: Fixed problems with wrong results produced by
* outer joins
* 2001.07.28: John Bellardo: Added code to handle rse_skip nodes.
* 2001.07.17 Claudio Valderrama: Stop crash with indices and recursive calls
* of OPT_compile: indicator csb_indices set to zero after used memory is
* returned to the free pool.
* 2001.02.15: Claudio Valderrama: Don't obfuscate the plan output if a selectable
* stored procedure doesn't access tables, views or other procedures directly.
* 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
* 2002.10.30: Arno Brinkman: Changes made to gen_retrieval, OPT_compile and make_inversion.
* Procedure sort_indices added. The changes in gen_retrieval are that now
* an index with high field-count has priority to build an index from.
* Procedure make_inversion is changed so that it not pick every index
* that comes away, this was slow performance with bad selectivity indices
* which most are foreign_keys with a reference to a few records.
* 2002.11.01: Arno Brinkman: Added match_indices for better support of OR handling
* in INNER JOIN (gen_join) statements.
* 2002.12.15: Arno Brinkman: Added find_used_streams, so that inside opt_compile all the
* streams are marked active. This causes that more indices can be used for
* a retrieval. With this change BUG SF #219525 is solved too.
*/
#include "firebird.h"
#include <stdio.h>
#include <string.h>
#include "../jrd/jrd.h"
#include "../jrd/align.h"
#include "../jrd/val.h"
#include "../jrd/req.h"
#include "../jrd/exe.h"
#include "../jrd/lls.h"
#include "../jrd/ods.h"
#include "../jrd/btr.h"
#include "../jrd/sort.h"
#include "../jrd/ini.h"
#include "../jrd/intl.h"
#include "../jrd/Collation.h"
#include "../common/gdsassert.h"
#include "../jrd/btr_proto.h"
#include "../jrd/cch_proto.h"
#include "../jrd/cmp_proto.h"
#include "../jrd/cvt2_proto.h"
#include "../jrd/dpm_proto.h"
#include "../common/dsc_proto.h"
#include "../jrd/err_proto.h"
#include "../jrd/ext_proto.h"
#include "../jrd/intl_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/met_proto.h"
#include "../jrd/mov_proto.h"
#include "../jrd/par_proto.h"
#include "../yvalve/gds_proto.h"
#include "../jrd/DataTypeUtil.h"
#include "../jrd/KeywordsTable.h"
#include "../jrd/RecordSourceNodes.h"
#include "../jrd/VirtualTable.h"
#include "../jrd/Monitoring.h"
#include "../jrd/TimeZone.h"
#include "../jrd/UserManagement.h"
#include "../common/classes/array.h"
#include "../common/classes/objects_array.h"
#include "../common/os/os_utils.h"
#include "../jrd/recsrc/RecordSource.h"
#include "../jrd/recsrc/Cursor.h"
#include "../jrd/Mapping.h"
#include "../jrd/DbCreators.h"
#include "../dsql/BoolNodes.h"
#include "../dsql/ExprNodes.h"
#include "../dsql/StmtNodes.h"
#include "../jrd/ConfigTable.h"
#include "../jrd/optimizer/Optimizer.h"
using namespace Jrd;
using namespace Firebird;
#ifdef OPT_DEBUG_RETRIEVAL
#define OPT_DEBUG
#endif
#ifdef OPT_DEBUG_SYS_REQUESTS
#define OPT_DEBUG
#endif
#ifdef OPT_DEBUG
#define OPTIMIZER_DEBUG_FILE "opt_debug.out"
#endif
namespace
{
inline void SET_DEP_BIT(ULONG* array, const SLONG bit)
{
array[bit / BITS_PER_LONG] |= (1L << (bit % BITS_PER_LONG));
}
inline bool TEST_DEP_BIT(const ULONG* array, const ULONG bit)
{
return (array[bit / BITS_PER_LONG] & (1L << (bit % BITS_PER_LONG))) != 0;
}
const int CACHE_PAGES_PER_STREAM = 15;
// enumeration of sort datatypes
static const UCHAR sort_dtypes[] =
{
0, // dtype_unknown
SKD_text, // dtype_text
SKD_cstring, // dtype_cstring
SKD_varying, // dtype_varying
0,
0,
0, // dtype_packed
0, // dtype_byte
SKD_short, // dtype_short
SKD_long, // dtype_long
SKD_quad, // dtype_quad
SKD_float, // dtype_real
SKD_double, // dtype_double
SKD_double, // dtype_d_float
SKD_sql_date, // dtype_sql_date
SKD_sql_time, // dtype_sql_time
SKD_timestamp, // dtype_timestamp
SKD_quad, // dtype_blob
0, // dtype_array
SKD_int64, // dtype_int64
SKD_text, // dtype_dbkey - use text sort for backward compatibility
SKD_bytes, // dtype_boolean
SKD_dec64, // dtype_dec64
SKD_dec128, // dtype_dec128
SKD_int128, // dtype_int128
SKD_sql_time_tz, // dtype_sql_time_tz
SKD_timestamp_tz // dtype_timestamp_tz
};
struct SortField
{
SortField() : stream(INVALID_STREAM), id(0), desc(nullptr)
{}
SortField(StreamType _stream, ULONG _id, const dsc* _desc)
: stream(_stream), id(_id), desc(_desc)
{}
StreamType stream;
ULONG id;
const dsc* desc;
};
class CrossJoin : public River
{
public:
CrossJoin(CompilerScratch* csb, RiverList& rivers)
: River(csb, nullptr, rivers)
{
// Save states of the underlying streams and restore them afterwards
StreamStateHolder stateHolder(csb, m_streams);
stateHolder.deactivate();
// Generate record source objects
const FB_SIZE_T riverCount = rivers.getCount();
if (riverCount == 1)
{
River* const sub_river = rivers.pop();
m_rsb = sub_river->getRecordSource();
}
else
{
HalfStaticArray<RecordSource*, OPT_STATIC_ITEMS> rsbs(riverCount);
// Reorder input rivers according to their possible inter-dependencies
while (rivers.hasData())
{
const auto orgCount = rsbs.getCount();
for (auto& subRiver : rivers)
{
const auto subRsb = subRiver->getRecordSource();
fb_assert(!rsbs.exist(subRsb));
subRiver->activate(csb);
if (subRiver->isComputable(csb))
{
rsbs.add(subRsb);
rivers.remove(&subRiver);
break;
}
subRiver->deactivate(csb);
}
if (rsbs.getCount() == orgCount)
break;
}
if (rivers.hasData())
{
// Ideally, we should never get here. But just in case it happened, handle it.
for (auto& subRiver : rivers)
{
const auto subRsb = subRiver->getRecordSource();
fb_assert(!rsbs.exist(subRsb));
const auto pos = &subRiver - rivers.begin();
rsbs.insert(pos, subRsb);
}
rivers.clear();
}
m_rsb = FB_NEW_POOL(csb->csb_pool) NestedLoopJoin(csb, rsbs.getCount(), rsbs.begin());
}
}
};
inline void compose(MemoryPool& pool, BoolExprNode** node1, BoolExprNode* node2)
{
if (node2)
*node1 = (*node1) ? FB_NEW_POOL(pool) BinaryBoolNode(pool, blr_and, *node1, node2) : node2;
}
void classMask(unsigned count, ValueExprNode** eq_class, ULONG* mask)
{
// Given an sort/merge join equivalence class (vector of node pointers
// of representative values for rivers), return a bit mask of rivers with values
if (count > MAX_CONJUNCTS)
{
ERR_post(Arg::Gds(isc_optimizer_blk_exc));
// Msg442: size of optimizer block exceeded
}
for (unsigned i = 0; i < OPT_STREAM_BITS; i++)
mask[i] = 0;
for (unsigned i = 0; i < count; i++, eq_class++)
{
if (*eq_class)
{
SET_DEP_BIT(mask, i);
DEV_BLKCHK(*eq_class, type_nod);
}
}
}
unsigned getRiverCount(unsigned count, const ValueExprNode* const* eq_class)
{
// Given an sort/merge join equivalence class (vector of node pointers
// of representative values for rivers), return the count of rivers with values
unsigned cnt = 0;
for (unsigned i = 0; i < count; i++)
{
if (*eq_class++)
cnt++;
}
return cnt;
}
bool fieldEqual(const ValueExprNode* node1, const ValueExprNode* node2)
{
if (!node1 || !node2)
return false;
if (node1->getType() != node2->getType())
return false;
if (node1 == node2)
return true;
const auto fieldNode1 = nodeAs<FieldNode>(node1);
const auto fieldNode2 = nodeAs<FieldNode>(node2);
if (fieldNode1 && fieldNode2)
{
return fieldNode1->fieldStream == fieldNode2->fieldStream &&
fieldNode1->fieldId == fieldNode2->fieldId;
}
return false;
}
bool fieldEqual(const BoolExprNode* node1, const BoolExprNode* node2)
{
if (!node1 || !node2)
return false;
if (node1->getType() != node2->getType())
return false;
if (node1 == node2)
return true;
const auto cmpNode = nodeAs<ComparativeBoolNode>(node1);
const auto cmpNode2 = nodeAs<ComparativeBoolNode>(node2);
if (cmpNode && cmpNode2 && cmpNode->blrOp == cmpNode2->blrOp &&
(cmpNode->blrOp == blr_eql || cmpNode->blrOp == blr_equiv))
{
if (fieldEqual(cmpNode->arg1, cmpNode2->arg1) &&
fieldEqual(cmpNode->arg2, cmpNode2->arg2))
{
return true;
}
if (fieldEqual(cmpNode->arg1, cmpNode2->arg2) &&
fieldEqual(cmpNode->arg2, cmpNode2->arg1))
{
return true;
}
}
return false;
}
bool augmentStack(ValueExprNode* node, ValueExprNodeStack& stack)
{
for (ValueExprNodeStack::const_iterator temp(stack); temp.hasData(); ++temp)
{
if (fieldEqual(node, temp.object()))
return false;
}
stack.push(node);
return true;
}
bool augmentStack(BoolExprNode* node, BoolExprNodeStack& stack)
{
for (BoolExprNodeStack::const_iterator temp(stack); temp.hasData(); ++temp)
{
if (fieldEqual(node, temp.object()))
return false;
}
stack.push(node);
return true;
}
bool searchStack(const ValueExprNode* node, const ValueExprNodeStack& stack)
{
for (ValueExprNodeStack::const_iterator iter(stack); iter.hasData(); ++iter)
{
if (fieldEqual(node, iter.object()))
return true;
}
return false;
}
double getCardinality(thread_db* tdbb, jrd_rel* relation, const Format* format)
{
// Return the estimated cardinality for the given relation
double cardinality = DEFAULT_CARDINALITY;
if (relation->rel_file)
cardinality = EXT_cardinality(tdbb, relation);
else if (!relation->isVirtual())
{
MET_post_existence(tdbb, relation);
cardinality = DPM_cardinality(tdbb, relation, format);
MET_release_existence(tdbb, relation);
}
return MAX(cardinality, MINIMUM_CARDINALITY);
}
void markIndices(CompilerScratch::csb_repeat* tail, USHORT relationId)
{
// Mark indices that were not included in the user-specified access plan
const auto plan = tail->csb_plan;
fb_assert(plan);
if (plan->type != PlanNode::TYPE_RETRIEVE)
return;
// Go through each of the indices and mark it unusable
// for indexed retrieval unless it was specifically mentioned
// in the plan; also mark indices for navigational access.
// If there were none indices, this is a sequential retrieval.
const auto relation = tail->csb_relation;
if (!relation)
return;
if (!tail->csb_idx)
return;
for (auto& idx : *tail->csb_idx)
{
if (!plan->accessType)
{
idx.idx_runtime_flags |= idx_plan_dont_use;
continue;
}
bool first = true, found = false;
for (const auto& arg : plan->accessType->items)
{
if (relationId != arg.relationId)
{
// index %s cannot be used in the specified plan
ERR_post(Arg::Gds(isc_index_unused) << arg.indexName);
}
if (idx.idx_id == arg.indexId)
{
if (plan->accessType->type == PlanNode::AccessType::TYPE_NAVIGATIONAL && first)
{
// dimitr: navigational access can use only one index,
// hence the extra check added (see the line above)
idx.idx_runtime_flags |= idx_plan_navigate;
}
else
{
// nod_indices
found = true;
break;
}
}
first = false;
}
if (!found)
idx.idx_runtime_flags |= idx_plan_dont_use;
}
}
bool mapEqual(const ValueExprNode* field1, const ValueExprNode* field2, const MapNode* map)
{
// Test to see if two fields are equal, where the fields are in two different streams
// possibly mapped to each other. Order of the input fields is important.
const auto fieldNode1 = nodeAs<FieldNode>(field1);
const auto fieldNode2 = nodeAs<FieldNode>(field2);
if (!fieldNode1 || !fieldNode2)
return false;
// look through the mapping and see if we can find an equivalence.
auto sourcePtr = map->sourceList.begin();
auto targetPtr = map->targetList.begin();
for (const auto sourceEnd = map->sourceList.end();
sourcePtr != sourceEnd;
++sourcePtr, ++targetPtr)
{
const auto mapFrom = nodeAs<FieldNode>(*sourcePtr);
const auto mapTo = nodeAs<FieldNode>(*targetPtr);
if (!mapFrom || !mapTo)
continue;
if (fieldNode1->fieldStream != mapFrom->fieldStream ||
fieldNode1->fieldId != mapFrom->fieldId)
{
continue;
}
if (fieldNode2->fieldStream != mapTo->fieldStream ||
fieldNode2->fieldId != mapTo->fieldId)
{
continue;
}
return true;
}
return false;
}
void setDirection(SortNode* fromClause, SortNode* toClause)
{
// Update the direction of a GROUP BY, DISTINCT, or ORDER BY
// clause to the same direction as another clause. Do the same
// for the nulls placement flag.
const auto fromCount = fromClause->expressions.getCount();
fb_assert(fromCount <= toClause->expressions.getCount());
fb_assert(fromCount == fromClause->direction.getCount() &&
fromCount == fromClause->nullOrder.getCount());
fb_assert(toClause->expressions.getCount() == toClause->direction.getCount() &&
toClause->expressions.getCount() == toClause->nullOrder.getCount());
for (FB_SIZE_T i = 0; i < fromCount; ++i)
{
toClause->direction[i] = fromClause->direction[i];
toClause->nullOrder[i] = fromClause->nullOrder[i];
}
}
void setPosition(const SortNode* from_clause, SortNode* to_clause, const MapNode* map)
{
// Update the fields in a GROUP BY, DISTINCT, or ORDER BY clause to the same position
// as another clause, possibly using a mapping between the streams.
// Track the position in the from list with "to_swap", and find the corresponding
// field in the from list with "to_ptr", then swap the two fields. By the time
// we get to the end of the from list, all fields in the to list will be reordered.
auto to_swap = to_clause->expressions.begin();
// We need to process no more than the number of nodes in the "from" clause
const auto count = from_clause->expressions.getCount();
fb_assert(count <= to_clause->expressions.getCount());
auto from_ptr = from_clause->expressions.begin();
for (const auto from_end = from_ptr + count; from_ptr != from_end; ++from_ptr)
{
NestConst<ValueExprNode>* to_ptr = to_clause->expressions.begin();
for (const auto to_end = to_ptr + count; to_ptr != to_end; ++to_ptr)
{
if ((map && mapEqual(*to_ptr, *from_ptr, map)) ||
(!map && fieldEqual(*to_ptr, *from_ptr)))
{
ValueExprNode* swap = *to_swap;
*to_swap = *to_ptr;
*to_ptr = swap;
}
}
++to_swap;
}
}
} // namespace
//
// Constructor
//
Optimizer::Optimizer(thread_db* aTdbb, CompilerScratch* aCsb, RseNode* aRse, bool parentFirstRows)
: PermanentStorage(*aTdbb->getDefaultPool()),
tdbb(aTdbb), csb(aCsb), rse(aRse),
firstRows(rse->firstRows.valueOr(parentFirstRows)),
compileStreams(getPool()),
bedStreams(getPool()),
keyStreams(getPool()),
outerStreams(getPool()),
conjuncts(getPool())
{
// Ignore optimization for first rows in impossible cases
if (firstRows)
{
// Projection is currently always performed using an external sort,
// so all underlying records will be fetched anyway
if (rse->rse_projection)
firstRows = false;
// Aggregation without GROUP BY will also cause all records to be fetched.
// Exception is when MIN/MAX functions could be mapped to an index,
// but this is handled separately inside AggregateSourceNode::compile().
else if (rse->rse_relations.getCount() == 1)
{
const auto subRse = rse->rse_relations[0];
const auto aggregate = nodeAs<AggregateSourceNode>(subRse);
if (aggregate && !aggregate->group)
firstRows = false;
}
}
}
//
// Destructor
//
Optimizer::~Optimizer()
{
// Release memory allocated for index descriptions
for (const auto compileStream : compileStreams)
{
delete csb->csb_rpt[compileStream].csb_idx;
csb->csb_rpt[compileStream].csb_idx = nullptr;
}
if (debugFile)
fclose(debugFile);
}
//
// Compile and optimize a record selection expression into a set of record source blocks
//
RecordSource* Optimizer::compile(RseNode* subRse, BoolExprNodeStack* parentStack)
{
Optimizer subOpt(tdbb, csb, subRse, firstRows);
const auto rsb = subOpt.compile(parentStack);
if (parentStack && subOpt.isInnerJoin())
{
// If any parent conjunct was utilized, update our copy of its flags.
// Currently used for inner joins only, although could also be applied
// to conjuncts utilized for outer streams of outer joins.
for (auto subIter = subOpt.getParentConjuncts(); subIter.hasData(); ++subIter)
{
for (auto selfIter = getConjuncts(); selfIter.hasData(); ++selfIter)
{
if (*selfIter == *subIter)
{
selfIter |= subIter.getFlags();
break;
}
}
}
}
return rsb;
}
RecordSource* Optimizer::compile(BoolExprNodeStack* parentStack)
{
// If there is a boolean, there is some work to be done. First,
// decompose the boolean into conjunctions. Then get descriptions
// of all indices for all relations in the RseNode. This will give
// us the info necessary to allocate a optimizer block big
// enough to hold this crud.
RecordSource* rsb = nullptr;
checkSorts();
SortNode* sort = rse->rse_sorted;
SortNode* project = rse->rse_projection;
SortNode* aggregate = rse->rse_aggregate;
BoolExprNodeStack conjunctStack;
unsigned conjunctCount = 0;
// put any additional booleans on the conjunct stack, and see if we
// can generate additional booleans by associativity--this will help
// to utilize indices that we might not have noticed
if (rse->rse_boolean)
conjunctCount = decomposeBoolean(rse->rse_boolean, conjunctStack);
conjunctCount += distributeEqualities(conjunctStack, conjunctCount);
// AB: If we have limit our retrieval with FIRST / SKIP syntax then
// we may not deliver above conditions (from higher rse's) to this
// rse, because the results should be consistent.
if (rse->rse_skip || rse->rse_first)
parentStack = nullptr;
// Set base-point before the parent/distributed nodes begin.
const unsigned baseCount = conjunctCount;
baseConjuncts = baseCount;
// AB: Add parent conjunctions to conjunct_stack, keep in mind
// the outer-streams! For outer streams put missing (IS NULL)
// conjunctions in the missing_stack.
//
// opt_rpt[0..opt_base_conjuncts-1] = defined conjunctions to this stream
// opt_rpt[0..opt_base_parent_conjuncts-1] = defined conjunctions to this
// stream and allowed distributed conjunctions (with parent)
// opt_rpt[0..opt_base_missing_conjuncts-1] = defined conjunctions to this
// stream and allowed distributed conjunctions and allowed parent
// opt_rpt[0..opt_conjuncts_count-1] = all conjunctions
//
// allowed = booleans that can never evaluate to NULL/Unknown or turn
// NULL/Unknown into a True or False.
unsigned parentCount = 0, distributedCount = 0;
BoolExprNodeStack missingStack;
if (parentStack)
{
for (BoolExprNodeStack::iterator iter(*parentStack);
iter.hasData() && conjunctCount < MAX_CONJUNCTS; ++iter)
{
const auto node = iter.object();
if (!isInnerJoin() && node->possiblyUnknown())
{
// parent missing conjunctions shouldn't be
// distributed to FULL OUTER JOIN streams at all
if (!isFullJoin())
missingStack.push(node);
}
else
{
conjunctStack.push(node);
conjunctCount++;
parentCount++;
}
}
// We've now merged parent, try again to make more conjunctions.
distributedCount = distributeEqualities(conjunctStack, conjunctCount);
conjunctCount += distributedCount;
}
// The newly created conjunctions belong to the base conjunctions.
// After them are starting the parent conjunctions.
baseParentConjuncts = baseConjuncts + distributedCount;
// Set base-point before the parent IS NULL nodes begin
baseMissingConjuncts = conjunctCount;
// Check if size of optimizer block exceeded.
if (conjunctCount > MAX_CONJUNCTS)
{
ERR_post(Arg::Gds(isc_optimizer_blk_exc));
// Msg442: size of optimizer block exceeded
}
// Put conjunctions in opt structure.
// Note that it's a stack and we get the nodes in reversed order from the stack.
conjuncts.grow(conjunctCount);
int nodeBase = -1, j = -1;
for (unsigned i = conjunctCount; i > 0; i--, j--)
{
BoolExprNode* const node = conjunctStack.pop();
if (i == baseCount)
{
// The base conjunctions
j = baseCount - 1;
nodeBase = 0;
}
else if (i == conjunctCount - distributedCount)
{
// The parent conjunctions
j = parentCount - 1;
nodeBase = baseParentConjuncts;
}
else if (i == conjunctCount)
{
// The new conjunctions created by "distribution" from the stack
j = distributedCount - 1;
nodeBase = baseConjuncts;
}
fb_assert(nodeBase >= 0 && j >= 0);
conjuncts[nodeBase + j].node = node;
}
// Put the parent missing nodes on the stack
for (BoolExprNodeStack::iterator iter(missingStack);
iter.hasData() && conjunctCount < MAX_CONJUNCTS; ++iter)
{
BoolExprNode* const node = iter.object();
conjuncts.grow(conjunctCount + 1);
conjuncts[conjunctCount].node = node;
conjunctCount++;
}
// Clear the csb_active flag of all streams in the RseNode
StreamList rseStreams;
rse->computeRseStreams(rseStreams);
for (const auto rseStream : rseStreams)
csb->csb_rpt[rseStream].deactivate();
// Find and collect booleans that are invariant in this context
// (i.e. independent from streams in the RseNode). We can do that
// easily because these streams are inactive at this point and
// any node that references them will be not computable.
// Note that we cannot do that for outer joins, as in this case boolean
// represents a join condition which does not filter out the rows.
BoolExprNode* invariantBoolean = nullptr;
if (isInnerJoin())
{
for (auto iter = getBaseConjuncts(); iter.hasData(); ++iter)
{
if (!(iter & CONJUNCT_USED) &&
iter->computable(csb, INVALID_STREAM, false))
{
compose(getPool(), &invariantBoolean, iter);
iter |= CONJUNCT_USED;
}
}
}
// Go through the record selection expression generating
// record source blocks for all streams
RiverList rivers, dependentRivers;
bool innerSubStream = false;
for (auto node : rse->rse_relations)
{
fb_assert(sort == rse->rse_sorted);
fb_assert(aggregate == rse->rse_aggregate);
// Find the stream number and place it at the end of the bedStreams array
// (if this is really a stream and not another RseNode)
node->computeRseStreams(bedStreams);
node->computeDbKeyStreams(keyStreams);
// Compile the node
rsb = node->compile(tdbb, this, innerSubStream);
// If an rsb has been generated, we have a non-relation;
// so it forms a river of its own since it is separately
// optimized from the streams in this rsb
if (rsb)
{
StreamList localStreams;
rsb->findUsedStreams(localStreams);
bool computable = false;
// AB: Save all outer-part streams
if (isInnerJoin() || (isLeftJoin() && !innerSubStream))
{
if (node->computable(csb, INVALID_STREAM, false))
computable = true;
// Apply local booleans, if any. Note that it's done
// only for inner joins and outer streams of left joins.
auto iter = getConjuncts(!isInnerJoin(), false);
rsb = applyLocalBoolean(rsb, localStreams, iter);
}
const auto river = FB_NEW_POOL(getPool()) River(csb, rsb, node, localStreams);
river->deactivate(csb);
if (computable)
{
outerStreams.join(localStreams);
rivers.add(river);
}
else
{
dependentRivers.add(river);
}
}
else
{
// We have a relation, just add its stream
fb_assert(bedStreams.hasData());
outerStreams.add(bedStreams.back());
}
innerSubStream = true;
}
// This is an attempt to make sure we have a large enough cache to
// efficiently retrieve this query; make sure the cache has a minimum
// number of pages for each stream in the RseNode (the number is just a guess)
if (compileStreams.getCount() > 5)
CCH_expand(tdbb, (ULONG) (compileStreams.getCount() * CACHE_PAGES_PER_STREAM));
// At this point we are ready to start optimizing.
// We will use the opt block to hold information of
// a global nature, meaning that it needs to stick
// around for the rest of the optimization process.
// Attempt to optimize aggregates via an index, if possible
if (aggregate && !sort)
sort = aggregate;
else
rse->rse_aggregate = aggregate = nullptr;
// Activate the priorly used rivers
for (const auto river : rivers)
river->activate(csb);
bool sortCanBeUsed = true;
SortNode* const orgSortNode = sort;
// When DISTINCT and ORDER BY are done on different fields,
// and ORDER BY can be mapped to an index, then the records
// are returned in the wrong order because DISTINCT sort is
// performed after the navigational walk of the index.
// For that reason, we need to de-optimize this case so that
// ORDER BY does not use an index.
if (sort && project)
{
sort = nullptr;
sortCanBeUsed = false;
}
// Outer joins are processed their own way
if (!isInnerJoin())
{
rivers.join(dependentRivers);
rsb = OuterJoin(tdbb, this, rse, rivers, &sort).generate();
}
else
{
// AB: If previous rsb's are already on the stack we can't use
// a navigational-retrieval for an ORDER BY because the next
// streams are JOINed to the previous ones
if (rivers.hasData())
{
sort = nullptr;
sortCanBeUsed = false;
// AB: We could already have multiple rivers at this
// point so try to do some hashing or sort/merging now.
while (generateEquiJoin(rivers))
;
}
StreamList joinStreams(compileStreams);
fb_assert(joinStreams.getCount() != 1 || csb->csb_rpt[joinStreams[0]].csb_relation);
while (true)
{
// AB: Determine which streams have an index relationship
// with the currently active rivers. This is needed so that
// no merge is made between a new cross river and the
// currently active rivers. Where in the new cross river
// a stream depends (index) on the active rivers.
StreamList dependentStreams, freeStreams;
findDependentStreams(joinStreams, dependentStreams, freeStreams);
// If we have dependent and free streams then we can't rely on
// the sort node to be used for index navigation
if (dependentStreams.hasData() && freeStreams.hasData())
{
sort = nullptr;
sortCanBeUsed = false;
}
if (dependentStreams.hasData())
{
// Copy free streams
joinStreams.assign(freeStreams);
// Make rivers from the dependent streams
generateInnerJoin(dependentStreams, rivers, &sort, rse->rse_plan);
// Generate one river which holds a cross join rsb between
// all currently available rivers
rivers.add(FB_NEW_POOL(getPool()) CrossJoin(csb, rivers));
rivers.back()->activate(csb);
}
else
{
if (freeStreams.hasData())
{
// Deactivate streams from rivers on stack, because
// the remaining streams don't have any indexed relationship with them
for (const auto river : rivers)
river->deactivate(csb);
}
break;
}
}
// Attempt to form joins in decreasing order of desirability
generateInnerJoin(joinStreams, rivers, &sort, rse->rse_plan);
// Re-activate remaining rivers to be hashable/mergeable
for (const auto river : rivers)
river->activate(csb);
// If there are multiple rivers, try some hashing or sort/merging
while (generateEquiJoin(rivers))
;
rivers.join(dependentRivers);
rsb = CrossJoin(csb, rivers).getRecordSource();
// Pick up any residual boolean that may have fallen thru the cracks