/
opt.cpp
3757 lines (3077 loc) · 107 KB
/
opt.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
/*
* PROGRAM: JRD Access Method
* MODULE: opt.cpp
* DESCRIPTION: Optimizer / record selection expression compiler
*
* 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/rse.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/opt_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 "../jrd/Optimizer.h"
#include "../dsql/BoolNodes.h"
#include "../dsql/ExprNodes.h"
#include "../dsql/StmtNodes.h"
#include "../jrd/ConfigTable.h"
using namespace Jrd;
using namespace Firebird;
#ifdef DEV_BUILD
#define OPT_DEBUG
#endif
namespace
{
class River;
typedef HalfStaticArray<River*, OPT_STATIC_ITEMS> RiverList;
inline void compose(MemoryPool& pool, BoolExprNode** node1, BoolExprNode* node2)
{
if (node2)
*node1 = (*node1) ? FB_NEW_POOL(pool) BinaryBoolNode(pool, blr_and, *node1, node2) : node2;
}
struct SortField
{
SortField() : stream(INVALID_STREAM), id(0), desc(NULL)
{}
SortField(StreamType _stream, ULONG _id, const dsc* _desc)
: stream(_stream), id(_id), desc(_desc)
{}
StreamType stream;
ULONG id;
const dsc* desc;
};
class River
{
public:
River(CompilerScratch* csb, RecordSource* rsb, RecordSourceNode* node, const StreamList& streams)
: m_rsb(rsb), m_nodes(csb->csb_pool), m_streams(csb->csb_pool)
{
if (node)
m_nodes.add(node);
m_streams.assign(streams);
}
River(CompilerScratch* csb, RecordSource* rsb, RiverList& rivers)
: m_rsb(rsb), m_nodes(csb->csb_pool), m_streams(csb->csb_pool)
{
for (River** iter = rivers.begin(); iter < rivers.end(); iter++)
{
River* const sub_river = *iter;
const size_t count = m_streams.getCount();
const size_t delta = sub_river->m_streams.getCount();
if (count + delta >= MAX_STREAMS)
ERR_post(Arg::Gds(isc_too_many_contexts));
m_nodes.join(sub_river->m_nodes);
m_streams.join(sub_river->m_streams);
}
}
RecordSource* getRecordSource() const
{
return m_rsb;
}
const StreamList& getStreams() const
{
return m_streams;
}
void activate(CompilerScratch* csb)
{
for (const StreamType* iter = m_streams.begin(); iter < m_streams.end(); iter++)
csb->csb_rpt[*iter].activate();
}
void deactivate(CompilerScratch* csb)
{
for (const StreamType* iter = m_streams.begin(); iter < m_streams.end(); iter++)
csb->csb_rpt[*iter].deactivate();
}
bool isReferenced(CompilerScratch* csb, const ExprNode* node) const
{
SortedStreamList nodeStreams;
node->collectStreams(csb, nodeStreams);
if (!nodeStreams.hasData())
return false;
for (const StreamType* iter = nodeStreams.begin(); iter != nodeStreams.end(); ++iter)
{
if (!m_streams.exist(*iter))
return false;
}
return true;
}
bool isComputable(CompilerScratch* csb) const
{
for (RecordSourceNode* const* iter = m_nodes.begin(); iter < m_nodes.end(); iter++)
{
if (!(*iter)->computable(csb, INVALID_STREAM, false))
return false;
}
return true;
}
RecordSource* applyLocalBoolean(OptimizerBlk* opt)
{
fb_assert(m_rsb);
CompilerScratch* const csb = opt->opt_csb;
StreamStateHolder stateHolder(csb);
stateHolder.deactivate();
activate(csb);
BoolExprNode* boolean = NULL;
const OptimizerBlk::opt_conjunct* const opt_end =
opt->opt_conjuncts.begin() + opt->opt_base_conjuncts;
for (OptimizerBlk::opt_conjunct* tail = opt->opt_conjuncts.begin();
tail < opt_end; tail++)
{
BoolExprNode* const node = tail->opt_conjunct_node;
if (!(tail->opt_conjunct_flags & opt_conjunct_used) &&
!(node->nodFlags & ExprNode::FLAG_RESIDUAL) &&
node->computable(csb, INVALID_STREAM, false))
{
compose(csb->csb_pool, &boolean, node);
tail->opt_conjunct_flags |= opt_conjunct_used;
}
}
if (boolean)
m_rsb = FB_NEW_POOL(csb->csb_pool) FilteredStream(csb, m_rsb, boolean);
return m_rsb;
}
protected:
RecordSource* m_rsb;
HalfStaticArray<RecordSourceNode*, OPT_STATIC_ITEMS> m_nodes;
StreamList m_streams;
};
class CrossJoin : public River
{
public:
CrossJoin(CompilerScratch* csb, RiverList& rivers)
: River(csb, NULL, rivers)
{
// Save states of the underlying streams and restore them afterwards
StreamStateHolder stateHolder(csb, m_streams);
// 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.
fb_assert(false);
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());
}
}
};
} // namespace
static bool augment_stack(ValueExprNode*, ValueExprNodeStack&);
static bool augment_stack(BoolExprNode*, BoolExprNodeStack&);
static void check_indices(const CompilerScratch::csb_repeat*);
static void check_sorts(CompilerScratch*, RseNode*);
static void class_mask(USHORT, ValueExprNode**, ULONG*);
static SLONG decompose(thread_db* tdbb, BoolExprNode* boolNode, BoolExprNodeStack& stack,
CompilerScratch* csb);
static USHORT distribute_equalities(BoolExprNodeStack& org_stack, CompilerScratch* csb,
USHORT base_count);
static void find_index_relationship_streams(thread_db* tdbb, OptimizerBlk* opt,
const StreamList& streams, StreamList& dependent_streams, StreamList& free_streams);
static void form_rivers(thread_db* tdbb, OptimizerBlk* opt, const StreamList& streams,
RiverList& river_list, SortNode** sort_clause, PlanNode* plan_clause);
static bool form_river(thread_db* tdbb, OptimizerBlk* opt, StreamType count, size_t stream_count,
StreamList& temp, RiverList& river_list, SortNode** sort_clause);
static void gen_join(thread_db* tdbb, OptimizerBlk* opt, const StreamList& streams,
RiverList& river_list, SortNode** sort_clause, PlanNode* plan_clause);
static RecordSource* gen_outer(thread_db* tdbb, OptimizerBlk* opt, RseNode* rse,
RiverList& river_list, SortNode** sort_clause);
static RecordSource* gen_residual_boolean(thread_db* tdbb, OptimizerBlk* opt, RecordSource* prior_rsb);
static RecordSource* gen_retrieval(thread_db* tdbb, OptimizerBlk* opt, StreamType stream,
SortNode** sort_ptr, bool outer_flag, bool inner_flag, BoolExprNode** return_boolean);
static bool gen_equi_join(thread_db*, OptimizerBlk*, RiverList&);
static double get_cardinality(thread_db*, jrd_rel*, const Format*);
static BoolExprNode* make_inference_node(CompilerScratch*, BoolExprNode*, ValueExprNode*, ValueExprNode*);
static bool map_equal(const ValueExprNode*, const ValueExprNode*, const MapNode*);
static void mark_indices(CompilerScratch::csb_repeat* csbTail, SSHORT relationId);
static bool node_equality(const ValueExprNode*, const ValueExprNode*);
static bool node_equality(const BoolExprNode*, const BoolExprNode*);
static ValueExprNode* optimize_like(thread_db*, CompilerScratch*, ComparativeBoolNode*);
static USHORT river_count(USHORT count, ValueExprNode** eq_class);
static bool search_stack(const ValueExprNode*, const ValueExprNodeStack&);
static void set_direction(SortNode*, SortNode*);
static void set_position(const SortNode*, SortNode*, const MapNode*);
static void sort_indices_by_selectivity(CompilerScratch::csb_repeat* csbTail);
// macro definitions
#ifdef OPT_DEBUG
const int DEBUG_PUNT = 5;
const int DEBUG_RELATIONSHIPS = 4;
const int DEBUG_ALL = 3;
const int DEBUG_CANDIDATE = 2;
const int DEBUG_BEST = 1;
const int DEBUG_NONE = 0;
FILE *opt_debug_file = 0;
static int opt_debug_flag = DEBUG_NONE;
#endif
inline void SET_DEP_BIT(ULONG* array, const SLONG bit)
{
array[bit / BITS_PER_LONG] |= (1L << (bit % BITS_PER_LONG));
}
/*
inline void CLEAR_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;
}
/*
inline bool TEST_DEP_ARRAYS(const ULONG* ar1, const ULONG* ar2)
{
//return (ar1[0] & ar2[0]) || (ar1[1] & ar2[1]) || (ar1[2] & ar2[2]) || (ar1[3] & ar2[3]) ||
// (ar1[4] & ar2[4]) || (ar1[5] & ar2[5]) || (ar1[6] & ar2[6]) || (ar1[7] & ar2[7]);
for (SLONG i = 0; i < BITS_PER_LONG; i++)
{
if (ar1[i] & ar2[i])
return true;
}
return false;
}
*/
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
};
string OPT_get_plan(thread_db* tdbb, const jrd_req* request, bool detailed)
{
/**************************************
*
* O P T _ g e t _ p l a n
*
**************************************
*
* Functional description
* Returns a formatted textual plan for all RseNode's in the specified request.
*
**************************************/
string plan;
if (request)
{
const Array<const RecordSource*>& fors = request->getStatement()->fors;
for (FB_SIZE_T i = 0; i < fors.getCount(); i++)
{
plan += detailed ? "\nSelect Expression" : "\nPLAN ";
fors[i]->print(tdbb, plan, detailed, 0);
}
}
return plan;
}
// Compile and optimize a record selection expression into a set of record source blocks (rsb's).
RecordSource* OPT_compile(thread_db* tdbb, CompilerScratch* csb, RseNode* rse,
BoolExprNodeStack* parent_stack)
{
DEV_BLKCHK(csb, type_csb);
DEV_BLKCHK(rse, type_nod);
SET_TDBB(tdbb);
#ifdef OPT_DEBUG
if (opt_debug_flag != DEBUG_NONE && !opt_debug_file)
opt_debug_file = os_utils::fopen(OPTIMIZER_DEBUG_FILE, "w");
#endif
// 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.
// Do not allocate the index_desc struct. Let BTR_all do the job. The allocated
// memory will then be in csb->csb_rpt[stream].csb_idx_allocation, which
// gets cleaned up before this function exits.
MemoryPool* const pool = tdbb->getDefaultPool();
AutoPtr<OptimizerBlk> opt(FB_NEW_POOL(*pool) OptimizerBlk(pool, rse));
opt->opt_streams.grow(csb->csb_n_stream);
opt->favorFirstRows = (rse->flags & RseNode::FLAG_OPT_FIRST_ROWS) != 0;
RecordSource* rsb = NULL;
try {
opt->opt_csb = csb;
RiverList rivers;
check_sorts(csb, rse);
SortNode* sort = rse->rse_sorted;
SortNode* project = rse->rse_projection;
SortNode* aggregate = rse->rse_aggregate;
BoolExprNodeStack conjunct_stack;
SLONG conjunct_count = 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)
conjunct_count = decompose(tdbb, rse->rse_boolean, conjunct_stack, csb);
conjunct_count += distribute_equalities(conjunct_stack, csb, conjunct_count);
// 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)
parent_stack = NULL;
// Set base-point before the parent/distributed nodes begin.
const USHORT base_count = (USHORT) conjunct_count;
opt->opt_base_conjuncts = base_count;
// 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.
USHORT parent_count = 0, distributed_count = 0;
BoolExprNodeStack missing_stack;
if (parent_stack)
{
for (BoolExprNodeStack::iterator iter(*parent_stack);
iter.hasData() && conjunct_count < MAX_CONJUNCTS; ++iter)
{
BoolExprNode* const node = iter.object();
if (rse->rse_jointype != blr_inner && node->possiblyUnknown(opt))
{
// parent missing conjunctions shouldn't be
// distributed to FULL OUTER JOIN streams at all
if (rse->rse_jointype != blr_full)
missing_stack.push(node);
}
else
{
conjunct_stack.push(node);
conjunct_count++;
parent_count++;
}
}
// We've now merged parent, try again to make more conjunctions.
distributed_count = distribute_equalities(conjunct_stack, csb, conjunct_count);
conjunct_count += distributed_count;
}
// The newly created conjunctions belong to the base conjunctions.
// After them are starting the parent conjunctions.
opt->opt_base_parent_conjuncts = opt->opt_base_conjuncts + distributed_count;
// Set base-point before the parent IS NULL nodes begin
opt->opt_base_missing_conjuncts = (USHORT) conjunct_count;
// Check if size of optimizer block exceeded.
if (conjunct_count > 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.
opt->opt_conjuncts.grow(conjunct_count);
SSHORT nodeBase = -1, j = -1;
for (SLONG i = conjunct_count; i > 0; i--, j--)
{
BoolExprNode* const node = conjunct_stack.pop();
if (i == base_count)
{
// The base conjunctions
j = base_count - 1;
nodeBase = 0;
}
else if (i == conjunct_count - distributed_count)
{
// The parent conjunctions
j = parent_count - 1;
nodeBase = opt->opt_base_parent_conjuncts;
}
else if (i == conjunct_count)
{
// The new conjunctions created by "distribution" from the stack
j = distributed_count - 1;
nodeBase = opt->opt_base_conjuncts;
}
fb_assert(nodeBase >= 0 && j >= 0 && nodeBase + j < MAX_CONJUNCTS);
opt->opt_conjuncts[nodeBase + j].opt_conjunct_node = node;
}
// Put the parent missing nodes on the stack
for (BoolExprNodeStack::iterator iter(missing_stack);
iter.hasData() && conjunct_count < MAX_CONJUNCTS; ++iter)
{
BoolExprNode* const node = iter.object();
opt->opt_conjuncts.grow(conjunct_count + 1);
opt->opt_conjuncts[conjunct_count].opt_conjunct_node = node;
conjunct_count++;
}
// clear the csb_active flag of all streams in the RseNode
StreamList rseStreams;
rse->computeRseStreams(rseStreams);
for (StreamList::iterator i = rseStreams.begin(); i != rseStreams.end(); ++i)
csb->csb_rpt[*i].deactivate();
// go through the record selection expression generating
// record source blocks for all streams
NestConst<RecordSourceNode>* ptr = rse->rse_relations.begin();
for (NestConst<RecordSourceNode>* const end = rse->rse_relations.end(); ptr != end; ++ptr)
{
const bool innerSubStream = (ptr != rse->rse_relations.begin());
RecordSourceNode* const node = *ptr;
opt->localStreams.clear();
fb_assert(sort == rse->rse_sorted);
fb_assert(aggregate == rse->rse_aggregate);
// find the stream number and place it at the end of the beds array
// (if this is really a stream and not another RseNode)
rsb = node->compile(tdbb, opt, 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)
{
// AB: Save all outer-part streams
if (rse->rse_jointype == blr_inner ||
(rse->rse_jointype == blr_left && !innerSubStream))
{
rsb->findUsedStreams(opt->subStreams);
rsb->findUsedStreams(opt->outerStreams);
}
const auto river = FB_NEW_POOL(*pool) River(csb, rsb, node, opt->localStreams);
river->deactivate(csb);
rivers.add(river);
}
else
{
// We have a relation, just add its stream
fb_assert(opt->beds.hasData());
opt->outerStreams.add(opt->beds.back());
}
}
// 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 (opt->compileStreams.getCount() > 5)
CCH_expand(tdbb, (ULONG) (opt->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 = NULL;
// AB: Mark the previous used streams (sub-RseNode's) as active
for (StreamList::iterator i = opt->subStreams.begin(); i != opt->subStreams.end(); ++i)
csb->csb_rpt[*i].activate();
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 = NULL;
sortCanBeUsed = false;
}
// outer joins require some extra processing
if (rse->rse_jointype != blr_inner)
rsb = gen_outer(tdbb, opt, rse, rivers, &sort);
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 = NULL;
sortCanBeUsed = false;
// AB: We could already have multiple rivers at this
// point so try to do some hashing or sort/merging now.
while (gen_equi_join(tdbb, opt, rivers))
;
// AB: Mark the previous used streams (sub-RseNode's) again
// as active, because a SORT/MERGE could reset the flags
for (StreamList::iterator i = opt->subStreams.begin(); i != opt->subStreams.end(); ++i)
csb->csb_rpt[*i].activate();
}
fb_assert(opt->compileStreams.getCount() != 1 || csb->csb_rpt[opt->compileStreams[0]].csb_relation != 0);
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 dependent_streams, free_streams;
find_index_relationship_streams(tdbb, opt, opt->compileStreams, dependent_streams, free_streams);
// If we have dependent and free streams then we can't rely on
// the sort node to be used for index navigation.
if (dependent_streams.getCount() && free_streams.getCount())
{
sort = NULL;
sortCanBeUsed = false;
}
if (dependent_streams.getCount())
{
// copy free streams
opt->compileStreams.assign(free_streams);
// Make rivers from the dependent streams
gen_join(tdbb, opt, dependent_streams, rivers, &sort, rse->rse_plan);
// Generate one river which holds a cross join rsb between
// all currently available rivers
rivers.add(FB_NEW_POOL(*pool) CrossJoin(csb, rivers));
rivers.back()->activate(csb);
}
else
{
if (free_streams.getCount())
{
// Deactivate streams from rivers on stack, because
// the remaining streams don't have any indexed relationship with them
for (River** iter = rivers.begin(); iter < rivers.end(); iter++)
(*iter)->deactivate(csb);
}
break;
}
}
// attempt to form joins in decreasing order of desirability
gen_join(tdbb, opt, opt->compileStreams, rivers, &sort, rse->rse_plan);
// If there are multiple rivers, try some hashing or sort/merging
while (gen_equi_join(tdbb, opt, rivers))
;
rsb = CrossJoin(csb, rivers).getRecordSource();
// Pick up any residual boolean that may have fallen thru the cracks
rsb = gen_residual_boolean(tdbb, opt, rsb);
}
// Assign the sort node back if it wasn't used by the index navigation
if (orgSortNode && !sortCanBeUsed)
sort = orgSortNode;
// if the aggregate was not optimized via an index, get rid of the
// sort and flag the fact to the calling routine
if (aggregate && sort)
{
rse->rse_aggregate = NULL;
sort = NULL;
}
// check index usage in all the base streams to ensure
// that any user-specified access plan is followed
for (StreamType i = 0; i < opt->compileStreams.getCount(); i++)
check_indices(&csb->csb_rpt[opt->compileStreams[i]]);
if (project || sort)
{
// CVC: I'm not sure how to do this with Array in a clearer way.
// Please, once you agree with my changes or fix them, you can delete the comments.
// Eliminate any duplicate dbkey streams
const StreamType* const b_end = opt->beds.end();
const StreamType* const k_end = opt->keyStreams.end();
StreamType* k = opt->keyStreams.begin();
for (const StreamType* p2 = k; p2 < k_end; ++p2)
{
const StreamType* q = opt->beds.begin();
while (q < b_end && *q != *p2)
q++;
if (q >= b_end)
*k++ = *p2;
}
opt->keyStreams.shrink(k - opt->keyStreams.begin());
// Handle project clause, if present
if (project)
rsb = OPT_gen_sort(tdbb, opt->opt_csb, opt->beds, &opt->keyStreams, rsb, project, opt->favorFirstRows, true);
// Handle sort clause if present
if (sort)
rsb = OPT_gen_sort(tdbb, opt->opt_csb, opt->beds, &opt->keyStreams, rsb, sort, opt->favorFirstRows, false);
}
// Handle first and/or skip. The skip MUST (if present)
// appear in the rsb list AFTER the first. Since the gen_first and gen_skip
// functions add their nodes at the beginning of the rsb list we MUST call
// gen_skip before gen_first.
if (rse->rse_skip)
rsb = FB_NEW_POOL(*pool) SkipRowsStream(csb, rsb, rse->rse_skip);
if (rse->rse_first)
rsb = FB_NEW_POOL(*pool) FirstRowsStream(csb, rsb, rse->rse_first);
if (rse->flags & RseNode::FLAG_WRITELOCK)
{
for (StreamType i = 0; i < opt->compileStreams.getCount(); ++i)
{
const StreamType loopStream = opt->compileStreams[i];
CompilerScratch::csb_repeat* r = &csb->csb_rpt[loopStream];
r->csb_flags |= csb_update;
if (r->csb_relation)
{
CMP_post_access(tdbb, csb, r->csb_relation->rel_security_name,
r->csb_view ? r->csb_view->rel_id : 0,
SCL_update, SCL_object_table, r->csb_relation->rel_name);
}
}
}
// release memory allocated for index descriptions
for (StreamType i = 0; i < opt->compileStreams.getCount(); ++i)
{
const StreamType loopStream = opt->compileStreams[i];
delete csb->csb_rpt[loopStream].csb_idx;
csb->csb_rpt[loopStream].csb_idx = NULL;
// CVC: The following line added because OPT_compile is recursive, both directly
// and through gen_union(), too. Otherwise, we happen to step on deallocated memory
// and this is the cause of the crashes with indices that have plagued IB since v4.
csb->csb_rpt[loopStream].csb_indices = 0;
}
#ifdef OPT_DEBUG
if (opt_debug_file)
{
fflush(opt_debug_file);
//fclose(opt_debug_file);
//opt_debug_file = 0;
}
#endif
} // try
catch (const Exception&)
{
for (StreamType i = 0; i < opt->compileStreams.getCount(); ++i)
{
const StreamType loopStream = opt->compileStreams[i];
delete csb->csb_rpt[loopStream].csb_idx;
csb->csb_rpt[loopStream].csb_idx = NULL;
csb->csb_rpt[loopStream].csb_indices = 0; // Probably needed to be safe
}
throw;
}
return rsb;
}
// Prepare relation and its indices for optimization.
void OPT_compile_relation(thread_db* tdbb, jrd_rel* relation, CompilerScratch* csb,
StreamType stream, bool needIndices)
{
CompilerScratch::csb_repeat* const tail = &csb->csb_rpt[stream];
RelationPages* const relPages = relation->getPages(tdbb);
if (needIndices && !relation->rel_file && !relation->isVirtual())
{
tail->csb_indices = BTR_all(tdbb, relation, &tail->csb_idx, relPages);
if (tail->csb_plan)
mark_indices(tail, relation->rel_id);
else
sort_indices_by_selectivity(tail);
}
else
tail->csb_indices = 0;
tail->csb_cardinality =
get_cardinality(tdbb, relation, CMP_format(tdbb, csb, stream));
}
// Add node (ValueExprNode) to stack unless node is already on stack.
static bool augment_stack(ValueExprNode* node, ValueExprNodeStack& stack)
{
/**************************************
*
* a u g m e n t _ s t a c k
*
**************************************
*
* Functional description
*
**************************************/
for (ValueExprNodeStack::const_iterator temp(stack); temp.hasData(); ++temp)
{
if (node_equality(node, temp.object()))
return false;
}
stack.push(node);
return true;
}
// Add node (BoolExprNode) to stack unless node is already on stack.
static bool augment_stack(BoolExprNode* node, BoolExprNodeStack& stack)
{
for (BoolExprNodeStack::const_iterator temp(stack); temp.hasData(); ++temp)
{
if (node_equality(node, temp.object()))
return false;
}
stack.push(node);
return true;
}
static void check_indices(const CompilerScratch::csb_repeat* csb_tail)
{
/**************************************
*
* c h e c k _ i n d i c e s
*
**************************************
*
* Functional description
* Check to make sure that the user-specified
* indices were actually utilized by the optimizer.