-
-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathbtr.cpp
More file actions
6981 lines (5830 loc) · 201 KB
/
btr.cpp
File metadata and controls
6981 lines (5830 loc) · 201 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PROGRAM: JRD Access Method
* MODULE: btr.cpp
* DESCRIPTION: B-tree management code
*
* 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.30 Sean Leyne - Removed support for obsolete "PC_PLATFORM" define
*
*/
#include "firebird.h"
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "memory_routines.h"
#include "../common/TimeZoneUtil.h"
#include "../common/classes/vector.h"
#include "../common/classes/VaryStr.h"
#include <stdio.h>
#include "../jrd/jrd.h"
#include "../jrd/ods.h"
#include "../jrd/val.h"
#include "../jrd/btr.h"
#include "../jrd/btn.h"
#include "../jrd/req.h"
#include "../jrd/tra.h"
#include "../jrd/intl.h"
#include "iberror.h"
#include "../jrd/lck.h"
#include "../jrd/cch.h"
#include "../jrd/sort.h"
#include "../jrd/val.h"
#include "../common/gdsassert.h"
#include "../jrd/btr_proto.h"
#include "../jrd/cch_proto.h"
#include "../jrd/dpm_proto.h"
#include "../jrd/err_proto.h"
#include "../jrd/evl_proto.h"
#include "../jrd/exe_proto.h"
#include "../yvalve/gds_proto.h"
#include "../jrd/intl_proto.h"
#include "../jrd/jrd_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/met_proto.h"
#include "../jrd/mov_proto.h"
#include "../jrd/pag_proto.h"
#include "../jrd/tra_proto.h"
using namespace Jrd;
using namespace Ods;
using namespace Firebird;
//#define DEBUG_BTR_SPLIT
//Debug page numbers into log file
//#define DEBUG_BTR_PAGES
namespace
{
constexpr unsigned MAX_LEVELS = 16;
constexpr size_t OVERSIZE = (MAX_PAGE_SIZE + BTN_PAGE_SIZE + MAX_KEY + sizeof(SLONG) - 1) / sizeof(SLONG);
// END_LEVEL (~0) is choosen here as a unknown/none value, because it's
// already reserved as END_LEVEL marker for page number and record number.
//
// NO_VALUE_PAGE and NO_VALUE are the same constant, but with different size
// Sign-extension mechanizm guaranties that they may be compared to each other safely
constexpr ULONG NO_VALUE_PAGE = END_LEVEL;
const RecordNumber NO_VALUE(END_LEVEL);
// A split page will never have the number 0, because that's the value
// of the main page.
inline constexpr ULONG NO_SPLIT = 0;
// Thresholds for determing of a page should be garbage collected
// Garbage collect if page size is below GARBAGE_COLLECTION_THRESHOLD
#define GARBAGE_COLLECTION_BELOW_THRESHOLD (dbb->dbb_page_size / 4)
// Garbage collect only if new merged page will
// be lower as GARBAGE_COLLECTION_NEW_PAGE_MAX_THRESHOLD
// 256 is the old maximum possible key_length.
#define GARBAGE_COLLECTION_NEW_PAGE_MAX_THRESHOLD ((dbb->dbb_page_size - 256))
struct INT64_KEY
{
double d_part;
SSHORT s_part;
};
// I assume this wasn't done sizeof(INT64_KEY) on purpose, since alignment might affect it.
constexpr size_t INT64_KEY_LENGTH = sizeof (double) + sizeof (SSHORT);
constexpr double pow10_table[] =
{
1.e00, 1.e01, 1.e02, 1.e03, 1.e04, 1.e05, 1.e06, 1.e07, 1.e08, 1.e09,
1.e10, 1.e11, 1.e12, 1.e13, 1.e14, 1.e15, 1.e16, 1.e17, 1.e18, 1.e19,
1.e20, 1.e21, 1.e22, 1.e23, 1.e24, 1.e25, 1.e26, 1.e27, 1.e28, 1.e29,
1.e30, 1.e31, 1.e32, 1.e33, 1.e34, 1.e35, 1.e36
};
inline double powerof10(int index) noexcept
{
return (index <= 0) ? pow10_table[-index] : 1.0 / pow10_table[index];
}
constexpr struct // Used in make_int64_key()
{
FB_UINT64 limit;
SINT64 factor;
SSHORT scale_change;
} int64_scale_control[] =
{
{ QUADCONST(922337203685470000), QUADCONST(1), 0 },
{ QUADCONST(92233720368547000), QUADCONST(10), 1 },
{ QUADCONST(9223372036854700), QUADCONST(100), 2 },
{ QUADCONST(922337203685470), QUADCONST(1000), 3 },
{ QUADCONST(92233720368548), QUADCONST(10000), 4 },
{ QUADCONST(9223372036855), QUADCONST(100000), 5 },
{ QUADCONST(922337203686), QUADCONST(1000000), 6 },
{ QUADCONST(92233720369), QUADCONST(10000000), 7 },
{ QUADCONST(9223372035), QUADCONST(100000000), 8 },
{ QUADCONST(922337204), QUADCONST(1000000000), 9 },
{ QUADCONST(92233721), QUADCONST(10000000000), 10 },
{ QUADCONST(9223373), QUADCONST(100000000000), 11 },
{ QUADCONST(922338), QUADCONST(1000000000000), 12 },
{ QUADCONST(92234), QUADCONST(10000000000000), 13 },
{ QUADCONST(9224), QUADCONST(100000000000000), 14 },
{ QUADCONST(923), QUADCONST(1000000000000000), 15 },
{ QUADCONST(93), QUADCONST(10000000000000000), 16 },
{ QUADCONST(10), QUADCONST(100000000000000000), 17 },
{ QUADCONST(1), QUADCONST(1000000000000000000), 18 },
{ QUADCONST(0), QUADCONST(0), 0 }
};
/* The first four entries in the array int64_scale_control[] ends with the
* limit having 0's in the end. This is to inhibit any rounding off that
* DOUBLE precision can introduce. DOUBLE can easily store upto 92233720368547
* uniquely. Values after this tend to round off to the upper limit during
* division. Hence the ending with 0's so that values will be bunched together
* in the same limit range and scale control for INT64 index temporary_key calculation.
*
* This part was changed as a fix for bug 10267. - bsriram 04-Mar-1999
*/
// enumerate the possible outcomes of deleting a node
enum contents {
contents_empty = 0,
contents_single,
contents_below_threshold,
contents_above_threshold
};
typedef HalfStaticArray<IndexJumpNode, 32> JumpNodeList;
struct FastLoadLevel
{
temporary_key key;
btree_page* bucket;
win_for_array window;
ULONG splitPage;
RecordNumber splitRecordNumber;
UCHAR* pointer;
UCHAR* newAreaPointer;
USHORT totalJumpSize;
IndexNode levelNode;
JumpNodeList* jumpNodes;
temporary_key jumpKey;
};
} // namespace
static ULONG add_node(thread_db*, WIN*, index_insertion*, temporary_key*, RecordNumber*,
ULONG*, ULONG*);
static void compress(thread_db*, const dsc*, const SSHORT scale, temporary_key*,
USHORT, bool, USHORT, bool*);
static USHORT compress_root(thread_db*, index_root_page*);
static void copy_key(const temporary_key*, temporary_key*);
static contents delete_node(thread_db*, WIN*, UCHAR*);
static void delete_tree(thread_db*, USHORT, USHORT, PageNumber, PageNumber);
static ULONG fast_load(thread_db*, IndexCreation&, SelectivityList&);
static index_root_page* fetch_root(thread_db*, WIN*, const jrd_rel*, const RelationPages*);
static UCHAR* find_node_start_point(btree_page*, temporary_key*, UCHAR*, USHORT*,
bool, int, bool = false, RecordNumber = NO_VALUE);
static UCHAR* find_area_start_point(btree_page*, const temporary_key*, UCHAR*,
USHORT*, bool, int, RecordNumber = NO_VALUE);
static ULONG find_page(btree_page*, const temporary_key*, const index_desc*, RecordNumber = NO_VALUE,
int = 0);
static contents garbage_collect(thread_db*, WIN*, ULONG);
static void generate_jump_nodes(thread_db*, btree_page*, JumpNodeList*, USHORT,
USHORT*, USHORT*, USHORT*, USHORT);
static ULONG insert_node(thread_db*, WIN*, index_insertion*, temporary_key*,
RecordNumber*, ULONG*, ULONG*);
static INT64_KEY make_int64_key(SINT64, SSHORT);
#ifdef DEBUG_INDEXKEY
static void print_int64_key(SINT64, SSHORT, INT64_KEY);
#endif
static string print_key(thread_db*, jrd_rel*, index_desc*, Record*);
static contents remove_node(thread_db*, index_insertion*, WIN*);
static contents remove_leaf_node(thread_db*, index_insertion*, WIN*);
static bool scan(thread_db*, UCHAR*, RecordBitmap**, RecordBitmap*, index_desc*,
const IndexRetrieval*, USHORT, temporary_key*,
bool&, const temporary_key&, USHORT);
static void update_selectivity(index_root_page*, USHORT, const SelectivityList&);
static void checkForLowerKeySkip(bool&, const bool, const IndexNode&, const temporary_key&,
const index_desc&, const IndexRetrieval*);
// BtrPageLock class
BtrPageGCLock::BtrPageGCLock(thread_db* tdbb)
: Lock(tdbb, PageNumber::getLockLen(), LCK_btr_dont_gc)
{
}
BtrPageGCLock::~BtrPageGCLock()
{
// assert in debug build
fb_assert(!lck_id);
// lck_id might be set only if exception occurs
if (lck_id)
LCK_release(JRD_get_thread_data(), this);
}
void BtrPageGCLock::disablePageGC(thread_db* tdbb, const PageNumber& page)
{
page.getLockStr(getKeyPtr());
LCK_lock(tdbb, this, LCK_read, LCK_WAIT);
}
void BtrPageGCLock::enablePageGC(thread_db* tdbb)
{
fb_assert(lck_id);
if (lck_id)
LCK_release(tdbb, this);
}
bool BtrPageGCLock::isPageGCAllowed(thread_db* tdbb, const PageNumber& page)
{
BtrPageGCLock lock(tdbb);
page.getLockStr(lock.getKeyPtr());
ThreadStatusGuard temp_status(tdbb);
if (!LCK_lock(tdbb, &lock, LCK_write, LCK_NO_WAIT))
return false;
LCK_release(tdbb, &lock);
return true;
}
// IndexErrorContext class
void IndexErrorContext::raise(thread_db* tdbb, idx_e result, Record* record)
{
fb_assert(result != idx_e_ok);
if (result == idx_e_conversion || result == idx_e_interrupt)
ERR_punt();
const auto& relationName = isLocationDefined ? m_location.relation->rel_name : m_relation->rel_name;
const USHORT indexId = isLocationDefined ? m_location.indexId : m_index->idx_id;
QualifiedName indexName(m_indexName);
MetaName constraintName;
if (indexName.object.isEmpty())
MET_lookup_index(tdbb, indexName, relationName, indexId + 1);
if (indexName.object.hasData())
MET_lookup_cnstrt_for_index(tdbb, constraintName, indexName);
else
indexName.object = "***unknown***";
const bool haveConstraint = constraintName.hasData();
if (!haveConstraint)
constraintName = "***unknown***";
switch (result)
{
case idx_e_keytoobig:
ERR_post_nothrow(Arg::Gds(isc_imp_exc) <<
Arg::Gds(isc_keytoobig) << indexName.toQuotedString());
break;
case idx_e_foreign_target_doesnt_exist:
ERR_post_nothrow(Arg::Gds(isc_foreign_key) <<
constraintName.toQuotedString() << relationName.toQuotedString() <<
Arg::Gds(isc_foreign_key_target_doesnt_exist));
break;
case idx_e_foreign_references_present:
ERR_post_nothrow(Arg::Gds(isc_foreign_key) <<
constraintName.toQuotedString() << relationName.toQuotedString() <<
Arg::Gds(isc_foreign_key_references_present));
break;
case idx_e_duplicate:
if (haveConstraint)
{
ERR_post_nothrow(Arg::Gds(isc_unique_key_violation) <<
constraintName.toQuotedString() << relationName.toQuotedString());
}
else
ERR_post_nothrow(Arg::Gds(isc_no_dup) << indexName.toQuotedString());
break;
default:
fb_assert(false);
}
if (record)
{
const string keyString = print_key(tdbb, m_relation, m_index, record);
if (keyString.hasData())
ERR_post_nothrow(Arg::Gds(isc_idx_key_value) << Arg::Str(keyString));
}
ERR_punt();
}
// IndexCondition class
IndexCondition::IndexCondition(thread_db* tdbb, index_desc* idx)
: m_tdbb(tdbb)
{
if (!(idx->idx_flags & idx_condition))
return;
fb_assert(idx->idx_condition);
m_condition = idx->idx_condition;
fb_assert(idx->idx_condition_statement);
const auto orgRequest = tdbb->getRequest();
m_request = idx->idx_condition_statement->findRequest(tdbb, true);
if (!m_request)
ERR_post(Arg::Gds(isc_random) << "Attempt to evaluate index condition recursively");
fb_assert(m_request != orgRequest);
fb_assert(!m_request->req_caller);
m_request->req_caller = orgRequest;
m_request->req_flags &= req_in_use;
m_request->req_flags |= req_active;
TRA_attach_request(tdbb->getTransaction(), m_request);
fb_assert(m_request->req_transaction);
if (orgRequest)
m_request->setGmtTimeStamp(orgRequest->getGmtTimeStamp());
else
m_request->validateTimeStamp();
m_request->req_rpb[0].rpb_number.setValue(BOF_NUMBER);
m_request->req_rpb[0].rpb_number.setValid(true);
}
IndexCondition::~IndexCondition()
{
if (m_request)
{
EXE_unwind(m_tdbb, m_request);
m_request->req_flags &= ~req_in_use;
m_request->req_attachment = nullptr;
}
}
bool IndexCondition::evaluate(Record* record) const
{
if (!m_request || !m_condition)
return true;
const auto orgRequest = m_tdbb->getRequest();
m_tdbb->setRequest(m_request);
m_request->req_rpb[0].rpb_record = record;
m_request->req_flags &= ~req_null;
FbLocalStatus status;
bool result = false;
try
{
Jrd::ContextPoolHolder context(m_tdbb, m_request->req_pool);
result = m_condition->execute(m_tdbb, m_request);
}
catch (const Exception& ex)
{
ex.stuffException(&status);
}
m_tdbb->setRequest(orgRequest);
status.check();
return result;
}
TriState IndexCondition::check(Record* record, idx_e* errCode)
{
TriState result;
try
{
result = evaluate(record);
if (errCode)
*errCode = idx_e_ok;
}
catch (const Exception& ex)
{
if (errCode)
{
*errCode = idx_e_conversion;
ex.stuffException(m_tdbb->tdbb_status_vector);
}
}
return result;
}
// IndexExpression class
IndexExpression::IndexExpression(thread_db* tdbb, index_desc* idx)
: m_tdbb(tdbb)
{
if (!(idx->idx_flags & idx_expression))
return;
fb_assert(idx->idx_expression);
m_expression = idx->idx_expression;
fb_assert(idx->idx_expression_statement);
const auto orgRequest = tdbb->getRequest();
m_request = idx->idx_expression_statement->findRequest(tdbb, true);
if (!m_request)
ERR_post(Arg::Gds(isc_random) << "Attempt to evaluate index expression recursively");
fb_assert(m_request != orgRequest);
fb_assert(!m_request->req_caller);
m_request->req_caller = orgRequest;
m_request->req_flags &= req_in_use;
m_request->req_flags |= req_active;
TRA_attach_request(tdbb->getTransaction(), m_request);
fb_assert(m_request->req_transaction);
TRA_setup_request_snapshot(tdbb, m_request);
if (orgRequest)
m_request->setGmtTimeStamp(orgRequest->getGmtTimeStamp());
else
m_request->validateTimeStamp();
m_request->req_rpb[0].rpb_number.setValue(BOF_NUMBER);
m_request->req_rpb[0].rpb_number.setValid(true);
}
IndexExpression::~IndexExpression()
{
if (m_request)
{
EXE_unwind(m_tdbb, m_request);
m_request->req_flags &= ~req_in_use;
m_request->req_attachment = nullptr;
}
}
dsc* IndexExpression::evaluate(Record* record) const
{
if (!m_request || !m_expression)
return nullptr;
const auto orgRequest = m_tdbb->getRequest();
m_tdbb->setRequest(m_request);
m_request->req_rpb[0].rpb_record = record;
m_request->req_flags &= ~req_null;
FbLocalStatus status;
dsc* result = nullptr;
try
{
Jrd::ContextPoolHolder context(m_tdbb, m_request->req_pool);
result = EVL_expr(m_tdbb, m_request, m_expression);
}
catch (const Exception& ex)
{
ex.stuffException(&status);
}
m_tdbb->setRequest(orgRequest);
status.check();
return result;
}
// IndexKey class
idx_e IndexKey::compose(Record* record)
{
// Compute a key from a record and an index descriptor.
// Note that compound keys are expanded by 25%.
// If this changes, both BTR_key_length and GDEF exe.e have to change.
const auto dbb = m_tdbb->getDatabase();
const auto maxKeyLength = dbb->getMaxIndexKeyLength();
temporary_key temp;
temp.key_flags = 0;
temp.key_length = 0;
dsc desc;
dsc* desc_ptr;
auto tail = m_index->idx_rpt;
m_key.key_flags = 0;
m_key.key_nulls = 0;
const bool descending = (m_index->idx_flags & idx_descending);
try
{
if (m_index->idx_count == 1)
{
// For expression indices, compute the value of the expression
if (m_index->idx_flags & idx_expression)
{
if (!m_expression)
m_expression = FB_NEW_POOL(*m_tdbb->getDefaultPool()) IndexExpression(m_tdbb, m_index);
desc_ptr = m_expression->evaluate(record);
// Multi-byte text descriptor is returned already adjusted.
}
else
{
// In order to "map a null to a default" value (in EVL_field()),
// the relation block is referenced.
// Reference: Bug 10116, 10424
if (EVL_field(m_relation, record, tail->idx_field, &desc))
{
desc_ptr = &desc;
if (desc_ptr->dsc_dtype == dtype_text &&
tail->idx_field < record->getFormat()->fmt_desc.getCount())
{
// That's necessary for NO-PAD collations.
INTL_adjust_text_descriptor(m_tdbb, desc_ptr);
}
}
else
{
desc_ptr = nullptr;
}
}
if (!desc_ptr)
m_key.key_nulls = 1;
m_key.key_flags |= key_empty;
compress(m_tdbb, desc_ptr, 0, &m_key, tail->idx_itype, descending, m_keyType, nullptr);
}
else
{
UCHAR* p = m_key.key_data;
SSHORT stuff_count = 0;
temp.key_flags |= key_empty;
for (USHORT n = 0; n < m_segments; n++, tail++)
{
for (; stuff_count; --stuff_count)
{
*p++ = 0;
if (p - m_key.key_data >= maxKeyLength)
return idx_e_keytoobig;
}
// In order to "map a null to a default" value (in EVL_field()),
// the relation block is referenced.
// Reference: Bug 10116, 10424
if (EVL_field(m_relation, record, tail->idx_field, &desc))
{
desc_ptr = &desc;
if (desc_ptr->dsc_dtype == dtype_text &&
tail->idx_field < record->getFormat()->fmt_desc.getCount())
{
// That's necessary for NO-PAD collations.
INTL_adjust_text_descriptor(m_tdbb, desc_ptr);
}
}
else
{
desc_ptr = nullptr;
m_key.key_nulls |= 1 << n;
}
compress(m_tdbb, desc_ptr, 0, &temp, tail->idx_itype, descending, m_keyType, nullptr);
const UCHAR* q = temp.key_data;
for (USHORT l = temp.key_length; l; --l, --stuff_count)
{
if (stuff_count == 0)
{
*p++ = m_index->idx_count - n;
stuff_count = STUFF_COUNT;
if (p - m_key.key_data >= maxKeyLength)
return idx_e_keytoobig;
}
*p++ = *q++;
if (p - m_key.key_data >= maxKeyLength)
return idx_e_keytoobig;
}
}
m_key.key_length = (p - m_key.key_data);
if (temp.key_flags & key_empty)
m_key.key_flags |= key_empty;
}
if (m_key.key_length >= maxKeyLength)
return idx_e_keytoobig;
if (descending)
BTR_complement_key(&m_key);
}
catch (const Exception& ex)
{
if (!(m_tdbb->tdbb_flags & TDBB_sys_error))
{
Arg::StatusVector error(ex);
if (!(error.length() > 1 &&
error.value()[0] == isc_arg_gds &&
error.value()[1] == isc_expression_eval_index))
{
QualifiedName indexName;
MET_lookup_index(m_tdbb, indexName, m_relation->rel_name, m_index->idx_id + 1);
if (indexName.object.isEmpty())
indexName.object = "***unknown***";
error.prepend(Arg::Gds(isc_expression_eval_index) <<
indexName.toQuotedString() <<
m_relation->rel_name.toQuotedString());
}
error.copyTo(m_tdbb->tdbb_status_vector);
}
else
ex.stuffException(m_tdbb->tdbb_status_vector);
m_key.key_length = 0;
return (m_tdbb->tdbb_flags & TDBB_sys_error) ? idx_e_interrupt : idx_e_conversion;
}
return idx_e_ok;
}
// IndexScanListIterator class
IndexScanListIterator::IndexScanListIterator(thread_db* tdbb, const IndexRetrieval* retrieval)
: m_retrieval(retrieval),
m_listValues(*tdbb->getDefaultPool(), retrieval->irb_list->getCount()),
m_lowerValues(*tdbb->getDefaultPool()), m_upperValues(*tdbb->getDefaultPool()),
m_iterator(m_listValues.begin())
{
// Find and store the position of the variable key segment
const auto count = MIN(retrieval->irb_lower_count, retrieval->irb_upper_count);
fb_assert(count);
for (unsigned i = 0; i < count; i++)
{
if (!retrieval->irb_value[i])
{
m_segno = i;
break;
}
}
fb_assert(m_segno < count);
// Copy the sorted values, skipping NULLs and duplicates
const auto sortedList = retrieval->irb_list->init(tdbb, tdbb->getRequest());
fb_assert(sortedList);
const SortValueItem* prior = nullptr;
for (const auto& item : *sortedList)
{
if (item.desc && (!prior || *prior != item))
m_listValues.add(item.value);
prior = &item;
}
if (m_listValues.hasData())
{
// Reverse the list if index is descending
if (retrieval->irb_generic & irb_descending)
std::reverse(m_listValues.begin(), m_listValues.end());
// Prepare the lower/upper key expressions for evaluation
auto values = m_retrieval->irb_value;
m_lowerValues.assign(values, m_retrieval->irb_lower_count);
fb_assert(!m_lowerValues[m_segno]);
m_lowerValues[m_segno] = *m_iterator;
values += m_retrieval->irb_desc.idx_count;
m_upperValues.assign(values, m_retrieval->irb_upper_count);
fb_assert(!m_upperValues[m_segno]);
m_upperValues[m_segno] = *m_iterator;
}
}
void IndexScanListIterator::makeKeys(thread_db* tdbb, temporary_key* lower, temporary_key* upper)
{
m_lowerValues[m_segno] = *m_iterator;
m_upperValues[m_segno] = *m_iterator;
const auto keyType =
(m_retrieval->irb_generic & irb_multi_starting) ? INTL_KEY_MULTI_STARTING :
(m_retrieval->irb_generic & irb_starting) ? INTL_KEY_PARTIAL :
(m_retrieval->irb_desc.idx_flags & idx_unique) ? INTL_KEY_UNIQUE :
INTL_KEY_SORT;
// Make the lower bound key
idx_e errorCode = BTR_make_key(tdbb, m_retrieval->irb_lower_count, getLowerValues(),
getScale(), &m_retrieval->irb_desc, lower, keyType, nullptr);
if (errorCode == idx_e_ok)
{
if (m_retrieval->irb_generic & irb_equality)
{
// If we have an equality search, lower/upper bounds are actually the same key
copy_key(lower, upper);
}
else
{
// Make the upper bound key
errorCode = BTR_make_key(tdbb, m_retrieval->irb_upper_count, getUpperValues(),
getScale(), &m_retrieval->irb_desc, upper, keyType, nullptr);
}
}
if (errorCode != idx_e_ok)
{
index_desc temp_idx = m_retrieval->irb_desc;
IndexErrorContext context(m_retrieval->irb_relation, &temp_idx);
context.raise(tdbb, errorCode);
}
}
void BTR_all(thread_db* tdbb, jrd_rel* relation, IndexDescList& idxList, RelationPages* relPages)
{
/**************************************
*
* B T R _ a l l
*
**************************************
*
* Functional description
* Return descriptions of all indices for relation. If there isn't
* a known index root, assume we were called during optimization
* and return no indices.
*
**************************************/
SET_TDBB(tdbb);
const Database* dbb = tdbb->getDatabase();
CHECK_DBB(dbb);
WIN window(relPages->rel_pg_space_id, -1);
index_root_page* const root = fetch_root(tdbb, &window, relation, relPages);
if (!root)
return;
Cleanup release_root([&] {
CCH_RELEASE(tdbb, &window);
});
for (USHORT i = 0; i < root->irt_count; i++)
{
index_desc idx;
if (BTR_description(tdbb, relation, root, &idx, i))
idxList.add(idx);
}
}
void BTR_complement_key(temporary_key* key)
{
/**************************************
*
* B T R _ c o m p l e m e n t _ k e y
*
**************************************
*
* Functional description
* Negate a key for descending index.
*
**************************************/
do
{
UCHAR* p = key->key_data;
for (const UCHAR* const end = p + key->key_length; p < end; p++)
*p ^= -1;
} while ((key = key->key_next.get()));
}
void BTR_create(thread_db* tdbb,
IndexCreation& creation,
SelectivityList& selectivity)
{
/**************************************
*
* B T R _ c r e a t e
*
**************************************
*
* Functional description
* Create a new index.
*
**************************************/
SET_TDBB(tdbb);
const Database* const dbb = tdbb->getDatabase();
CHECK_DBB(dbb);
jrd_rel* const relation = creation.relation;
index_desc* const idx = creation.index;
// Now that the index id has been checked out, create the index.
idx->idx_root = fast_load(tdbb, creation, selectivity);
// Index is created. Go back to the index root page and update it to
// point to the index.
RelationPages* const relPages = relation->getPages(tdbb);
WIN window(relPages->rel_pg_space_id, relPages->rel_index_root);
index_root_page* const root = (index_root_page*) CCH_FETCH(tdbb, &window, LCK_write, pag_root);
CCH_MARK(tdbb, &window);
root->irt_rpt[idx->idx_id].setRoot(idx->idx_root);
update_selectivity(root, idx->idx_id, selectivity);
CCH_RELEASE(tdbb, &window);
}
bool BTR_delete_index(thread_db* tdbb, WIN* window, USHORT id)
{
/**************************************
*
* B T R _ d e l e t e _ i n d e x
*
**************************************
*
* Functional description
* Delete an index if it exists.
* Return true if index tree was there.
*
**************************************/
SET_TDBB(tdbb);
const Database* dbb = tdbb->getDatabase();
CHECK_DBB(dbb);
// Get index descriptor. If index doesn't exist, just leave.
index_root_page* const root = (index_root_page*) window->win_buffer;
bool tree_exists = false;
if (id >= root->irt_count)
CCH_RELEASE(tdbb, window);
else
{
index_root_page::irt_repeat* irt_desc = root->irt_rpt + id;
CCH_MARK(tdbb, window);
const ULONG rootPage = irt_desc->getRoot();
const PageNumber next(window->win_page.getPageSpaceID(), rootPage);
tree_exists = (rootPage != 0);
// remove the pointer to the top-level index page before we delete it
irt_desc->setEmpty();
const PageNumber prior = window->win_page;
const USHORT relation_id = root->irt_relation;
CCH_RELEASE(tdbb, window);
delete_tree(tdbb, relation_id, id, next, prior);
}
return tree_exists;
}
bool BTR_description(thread_db* tdbb, jrd_rel* relation, index_root_page* root, index_desc* idx,
USHORT id)
{
/**************************************
*
* B T R _ d e s c r i p t i o n
*
**************************************
*
* Functional description
* See if index exists, and if so, pick up its description.
* Index id's must fit in a short - formerly a UCHAR.
*
**************************************/
SET_TDBB(tdbb);
if (id >= root->irt_count)
return false;
const index_root_page::irt_repeat* irt_desc = &root->irt_rpt[id];
const ULONG rootPage = irt_desc->getRoot();
if (!rootPage)
return false;
idx->idx_id = id;
idx->idx_root = rootPage;
idx->idx_count = irt_desc->irt_keys;
idx->idx_flags = irt_desc->irt_flags;
idx->idx_runtime_flags = 0;
idx->idx_foreign_primaries = nullptr;
idx->idx_foreign_relations = nullptr;
idx->idx_foreign_indexes = nullptr;
idx->idx_primary_relation = 0;
idx->idx_primary_index = 0;
idx->idx_expression = nullptr;
idx->idx_expression_statement = nullptr;
idx->idx_condition = nullptr;
idx->idx_condition_statement = nullptr;
idx->idx_fraction = 1.0;
// pick up field ids and type descriptions for each of the fields
const UCHAR* ptr = (UCHAR*) root + irt_desc->irt_desc;
index_desc::idx_repeat* idx_desc = idx->idx_rpt;
for (int i = 0; i < idx->idx_count; i++, idx_desc++)
{
const irtd* key_descriptor = (irtd*) ptr;
idx_desc->idx_field = key_descriptor->irtd_field;
idx_desc->idx_itype = key_descriptor->irtd_itype;
idx_desc->idx_selectivity = key_descriptor->irtd_selectivity;
ptr += sizeof(irtd);
}
idx->idx_selectivity = idx->idx_rpt[idx->idx_count - 1].idx_selectivity;
ISC_STATUS error = 0;
if (idx->idx_flags & idx_expression)