Repository navigation
Expand file tree
/
Copy pathuHashIndexFile.pas
More file actions
executable file
·3452 lines (3138 loc) · 157 KB
/
Copy pathuHashIndexFile.pas
File metadata and controls
executable file
·3452 lines (3138 loc) · 157 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
unit uHashIndexFile;
{ ThinkSQL Relational Database Management System
Copyright © 2000-2012 Greg Gaughan
See LICENCE.txt for details
}
{Hashed index file
Currently uses extendible hashing - may change in future
Initially implemented for primary/unique/foreign-key lookups during constraint
checking.
Indexes are used internally throughout, so these routines must be very solid,
else very strange things will happen...
Note: these indexes are noisy, but duplicate keys for the same rid are prevented.
todo: wrap assertions in IFDEF SAFETY after development testing ok
}
{$DEFINE SAFETY}
//{$DEFINE DEBUGDETAIL}
//{$DEFINE DEBUGDETAIL2} //directory doubling/split testing
//{$DEFINE DEBUGDETAIL3} //slot packing after split & during insert
//{$DEFINE DEBUGDETAIL4} //dump after open!
//{$DEFINE DEBUGDETAIL5} //worthsplitting
//{$DEFINE DEBUGDETAIL6} //buffer status &/or index dump after each insert!
//{$DEFINE DEBUGDETAIL7} //lookup detail
//{$DEFINE DEBUGDETAIL8} //lookup/scan summary
//{$DEFINE DEBUGDETAIL9} //dump to log
//{$DEFINE DEBUGDETAIL10} //debug hash algorithm
//{$DEFINE DEBUGDETAIL11} //delete detail
//{$DEFINE DEBUGDETAIL12} //iteration loop detail
interface
uses uIndexFile, uStmt, uGlobal, uGlobalDef, uPage, uTuple, IdTCPConnection{debug only};
const
THashIndexFileDirSize=sizeof(pageId);
//note: if we make HashIndexFileDirPerBlock a multiple of 2, then we can use SHR to DIV and get MOD faster...
HashIndexFileDirPerBlock=BlockSize div THashIndexFileDirSize;
THashSlotSize=sizeof(cardinal)+sizeof(Trid); //Note: sizeof(Trid) currently wastes 2 bytes
//note: if we make HashSlotPerBlock a multiple of 2, then we can use SHR to DIV and get MOD faster...
HashSlotPerBlock=BlockSize div THashSlotSize;
{TODO:
calculate maximum capacity (without overflows)
=ceiling(HashIndexFileDirPerBlock-1,power of 2) * HashSlotPerBlock-1
=number of pages in table
for 512 blocks= maybe 10 rows per page
124-1 = 64 * 41 = 2624 = around 26240 rows
and again for each extra bucket directory page, e.g. 5248
for 4096 blocks= maybe 100 rows per page
1024-1 = 512 * 341 = 174592 = around 17459200 rows
and again for each extra bucket directory page, e.g. 349184
}
type
{Within 1st page (chain) - hash bucket index}
ThashIndexFileDir=record //note: see THashIndexFileDirSize above - keep in sync!!
pid:PageId;
end; {TfileDir}
{ThashIndexFileDir[0]=hash-bucket-dir header, 1..N = buckets available
ThashIndexFileDir[0].pid=extendible-hash-global-depth => 2^this = N
}
HashBucketId=word;
{Within a page - hash key + RID}
THashSlot=record //note: see THashSlotSize above - keep in sync!!
HashValue:cardinal;//hash value (1st few bits give bucket)
RID:Trid; //record pointer
//note: in future, may add timestamp/full-key here to save false reads...
end; {TSlot}
{HashSlot[0]=hash-slot header, 1..N = used hash-slots hashSlot[0].hashValue=N i.e. count
hashSlot[0].RID.pid=extendible-hash-local-depth
}
HashSlotId=cardinal; //limits max per overflow chain
THashIndexFile=class(TIndexFile)
private
fHashValue:cardinal; //current hash value from last findStart
fPid:PageId; //current hash scan page
//note: uses TDBfile.fCurrentPage for current page storage
fhsId:HashSlotId; //current hash scan hash slot
fhsHeader:THashSlot; //current hash scan root page header (contains page-chain count for findNext)
fdirpage:TPage; //current hash dir page for duplicate scan
fhashBucket:cardinal;//current bucket for duplicate scan
fHashPrevious:THashSlot; //previous duplicate hash slot for duplicate scan & normal scan
fglobalDepth:pageId; //global depth for duplicate scan (read from 1st dir page during start)
function extendDirectory(st:TStmt;var id:PageId):integer;
function allocateBucket(st:TStmt;localDepth:pageId;var id:PageId):integer;
function Hash(t:TTuple):cardinal;
function slotCompare(ahashvalue:cardinal;arid:Trid;b:THashSlot):integer;
public
statHashClash:integer; //count number of misses due to hash clash (i.e. found tuple does not match)
statVersionMiss:integer; //count number of misses due to wrong version (e.g. found to be too old/young/deleted/uncommitted etc.)
function Dump(st:TStmt;connection:TIdTCPConnection;summary:boolean):integer;
function createFile(st:TStmt;const fname:string):integer; override;
function deleteFile(st:TStmt):integer; override;
function openFile(st:TStmt;const filename:string;startPage:PageId):integer; override;
function freeSpace(st:TStmt;page:TPage):integer; override;
function AddKeyPtr(st:TStmt;t:TTuple;rid:Trid):integer; override;
{DeleteKey notes (may be out of date)
need to ensure we don't leave overflow pages that are empty (check full test assumes all are used)
}
function FindStart(st:TStmt;FindData:TTuple):integer; override;
function FindNext(st:TStmt;var noMore:boolean;var RID:Trid):integer; override;
function FindStop(st:TStmt):integer; override;
function FindStartDuplicate(st:TStmt):integer; override;
function FindNextDuplicate(st:TStmt;var noMore:boolean;var RID1,RID2:TRid):integer; override;
function FindStopDuplicate(st:TStmt):integer; override;
end; {THashIndexFile}
implementation
uses
{$IFDEF Debug_Log}
uLog,
{$ENDIF}
SysUtils, Math {for power}, uServer, uTransaction,
uMarshalGlobal {in '..\Odbc\uMarshalGlobal.pas'} {for date/time structures}
,uEvsHelpers;
const
who='';
where='uHashIndexFile';
function THashIndexFile.createFile(st:TStmt;const fname:string):integer;
{Creates a hash index file in the specified database
IN : db the database
: fname the new filename
RETURN : +ve=ok, else fail
}
const
routine=':createFile';
InitialGlobalDepth=1; //i.e. allocate 2^1 bucket pages & set bucket directory size=2^1
// InitialGlobalDepth=3; //i.e. allocate 2^3 bucket pages & set bucket directory size=2^3
//note: make 2+ to prevent early duplicate-overflow dead-end
//todo: pass initialGlobalDepth from caller!
var
page:Tpage;
pid,bucketPid:PageId;
hashIndexFileDir:THashIndexFileDir;
dirSlot:DirSlotId;
dirPageId,prevDirSlotPageId:PageId;
i:integer;
begin
result:=inherited CreateFile(st,fname);
if result<>ok then exit; //abort
result:=Fail; //default
//todo: assert 2^InitialGlobalDepth <= HashIndexFileDirPerBlock
// otherwise we would need extra bucket-dir-pages & currently assume 1
// - also add this assumption to routine header comments!
//todo write hash bucket directory page
//todo call extendDirectory instead of below...
{No page with room was found, so we allocate and add a new one}
if Ttransaction(st.owner).db.allocatePage(st,pid)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed allocating new page',vError);
{$ELSE}
;
{$ENDIF}
exit;
end;
{Initialise this new page as a hashIndexFile directory page}
with (Ttransaction(st.owner).db.owner as TDBserver) do
begin
if buffer.pinPage(st,pid,page)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading new page to initialise it, %d',[pid]),vError);
{$ELSE}
;
{$ENDIF}
exit; //abort
end;
try
{Ok, add the page to the file's directory}
{Note: we do this now because this must be the 1st data page added to this file, because
we assume dirSlot=0=start of bucket-directory}
if DirPageAdd(st,pid,freespace(st,page),prevDirSlotPageId,dirPageId,dirSlot)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed allocating new bucket directory page to page dir',vError);
{$ENDIF}
exit;
end;
//todo: assert dirSlot=0!
{Initialise blank directory page}
if page.latch(st)=ok then //note: no real need since newpage=local/new?
begin
try
page.block.pageType:=ptIndexData; //todo: use new type, e.g. ptHashIndexFileDir?
{Write zeroised bucket pointers}
hashIndexFileDir.pid:=InvalidPageId;
for i:=0 to HashIndexFileDirPerBlock-1 do
begin
page.SetBlock(st,i*sizeof(hashIndexFileDir),sizeof(hashIndexFileDir),@hashIndexFileDir);
end;
{Create initial hash-directory}
{Write hash-directory header}
hashIndexFileDir.pid:=InitialGlobalDepth; //global-depth => # buckets = 2^global-depth
page.SetBlock(st,0*sizeof(hashIndexFileDir),sizeof(hashIndexFileDir),@hashIndexFileDir);
{Write allocate initial bucket pages and set bucket directory pointers}
for i:=0 to trunc(power(2,InitialGlobalDepth))-1 do
begin
if allocateBucket(st,InitialGlobalDepth,bucketPid)<>ok then
exit; //abort
//Note: we don't set the new page's prevPage to itself here (maybe we should?) - no point until we have a proper chain
hashIndexFileDir.pid:=bucketPid;
page.SetBlock(st,(i+1){0 is reserved for dir-header}*sizeof(hashIndexFileDir),sizeof(hashIndexFileDir),@hashIndexFileDir);
end;
finally
page.unlatch(st);
end; {try}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Initialised hash file with bucket directory global depth=%d',[InitialGlobalDepth]),vDebugLow);
{$ELSE}
;
{$ENDIF}
page.dirty:=True;
result:=ok;
end
else
exit; //abort
finally
buffer.unpinPage(st,pid);
end; {try}
end; {with}
if result=ok then
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Hash-index-file %s created',[fname]),vDebug);
{$ELSE}
;
{$ENDIF}
end; {createFile}
function slotToPageSlot(slot:HashSlotId):HashSlotId;
{Needed to map chain-scale slot-id to page slot-id for writing
and some reading (but most reads count separately per page)
Note: if we based everything at 0 this might not be needed...
}
begin
result:=slot MOD (HashSlotPerBlock-1);
if result=0 then result:=(HashSlotPerBlock-1);
end; {slotToPageSlot}
function bucketToDirBucket(bucket:HashBucketId):HashBucketId;
{Needed to map dir-scale bucket-id to dir page slot-id for writing
and some reading (but most reads count separately per page)
Note: if we based everything at 0 this might not be needed...
}
begin
result:=bucket MOD (HashIndexFileDirPerBlock-1);
if result=0 then result:=(HashIndexFileDirPerBlock-1);
end; {bucketToDirBucket}
function THashIndexFile.deleteFile(st:TStmt):integer;
{Deletes a hash index file in the specified database
IN : db the database
: fname the new filename
RETURN : +ve=ok, else fail
}
const
routine=':deleteFile';
var
page:Tpage;
pid,bucketPid,nextfPid:PageId;
dirSlot:DirSlotId;
dirPageId:PageId;
i:integer;
hashMap:cardinal;
dirpid:pageId;
space:word;
dirpage:TPage;
hashIndexFileDir,hd:THashIndexFileDir;
globalDepth,localDepth:pageId;
hsHeader,hs:THashSlot;
overflowCount:cardinal;
noMoreOverflow:boolean;
lastPid:PageId;
begin
result:=Fail; //default
{Structure summary:
dirslot[0]=start of bucket-directory (currently type=ptIndexData)
each bucket-dir page:
0:hashIndexFileDir.pid=globalDepth
for i:=0 to trunc(power(2,InitialGlobalDepth))-1 do
//for i:=1 to HashIndexFileDirPerBlock-1 do
i+1:hashIndexFileDir.pid -> chain of index data pages
Note: the following was based on the dump code.
It runs in such as way as to be recoverable after a crash, i.e. links are kept consistent (hopefully!)
}
result:=self.DirPage(st,InvalidPageId,0,dirpid,space); //get 1st dir slot page = 1st bucket dir page
if result<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed reading first dir slot',vDebugError);
{$ENDIF}
exit; //abort
end;
if dirpid<>InvalidPageId then //only if we have the bucket dir
begin
if (Ttransaction(st.owner).db.owner as TDBserver).buffer.pinPage(st,dirpid,dirpage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading bucket directory page %d',[dirpid]),vError);
{$ENDIF}
exit; //abort
end;
try
{Read hash-directory header}
dirpage.AsBlock(st,0*sizeof(hashIndexFileDir),sizeof(hashIndexFileDir),@hashIndexFileDir);
globalDepth:=hashIndexFileDir.pid; //global-depth => # buckets = 2^global-depth
{$IFDEF DEBUGDETAIL11}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Global depth: %d (%d entries)',[globalDepth,trunc(power(2,globalDepth))]),vDebugMedium);
{$ENDIF}
{$ENDIF}
{Go through the bucket directory and zap each bucket page chain}
for hashMap:=0 to trunc(power(2,globalDepth))-1 do
begin
overflowCount:=0; //indent level
if (((hashMap+1) MOD (HashIndexFileDirPerBlock-1))=1) and ((hashMap+1)<>1) then
begin //need next dir page
if dirpage.block.nextPage=InvalidPageId then
begin //error - not enough pages for count! Possibly crashed during last attempt so ignore...
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('No more directory pages after %d, but count says there should be %d slot entries & we have only read %d so far - continuing with the deletion...',[dirpage.block.thispage,trunc(power(2,globalDepth)),hashMap+1]),vDebugError);
{$ENDIF}
break; //continue with the deallocation... just abandon any further bucket slot reading...
end;
dirpid:=dirpage.block.nextPage;
(Ttransaction(st.owner).db.owner as TDBServer).buffer.unpinPage(st,dirpage.block.thisPage);
{Now we can deallocate this directory page}
if self.DirPageRemove(st,dirpage.block.thisPage,0)<>ok then exit; //reset 1st dir slot - we will move the next dir page here
//note: temporarily lost the rest of the index directory! But can be sure that no-one else will flush our garbage startpage before we do: (at least when transaction flushing is implemented)
if Ttransaction(st.owner).db.deAllocatePage(st,dirpage.block.thisPage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed de-allocating index file page',vError);
{$ENDIF}
exit;
end;
if (Ttransaction(st.owner).db.owner as TDBserver).buffer.pinPage(st,dirpid,dirpage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading bucket directory page %d [next]',[dirpid]),vError);
{$ENDIF}
exit; //abort
end;
{Now re-point the directory start to this directory page (in case we crash & restart)}
//Note: this next bit is a bit dodgy: we should use a file.dirPageSwap routine(?)
if self.DirPageSet(st,InvalidPageId,0,dirpid,freespace(st,dirpage),True{don't check})<>ok then exit; //set 1st dir slot page = new 1st bucket dir page
if self.DirPageFindFromPID(st,dirpage.block.thisPage,dirPageId,dirSlot)<>ok then exit; //find previous slot for this new dir page
if self.DirPageRemove(st,dirpage.block.thisPage,dirSlot)<>ok then exit; //reset the previous slot - we have moved it to slot 0 //Note: currently if this is 1st slot on an extended file directory page, the page will be deleted!
(Ttransaction(st.owner).db.owner as TDBServer).buffer.flushPage(st,startPage,nil);
//note: also should flush the dirpage containing dirSlot: if we can't find it out, flush all!
// - worst case=double entry for same page: de-allocation will remove 1st one, so file dir-page won't be empty...
end;
dirpage.AsBlock(st,bucketToDirBucket(hashMap+1)*sizeof(hd),sizeof(hd),@hd);
fpid:=hd.pid;
{Now pin the bucket page}
if (Ttransaction(st.owner).db.owner as TDBserver).buffer.pinPage(st,fpid,fCurrentPage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading bucket page %d',[fpid]),vError);
{$ENDIF}
exit; //abort
end;
{Zap this page and any overflow pages}
{Read hash-slot header}
fCurrentPage.AsBlock(st,0*sizeof(hsHeader),sizeof(hsHeader),@hsHeader);
localDepth:=hsHeader.RID.pid;
{Note: we've no need to go through the slots: just remove pages from the chain
}
begin
fhsId:=1; //start at 1st hash slot
//while fhsId<=hsHeader.hashValue do
while fCurrentPage.block.nextPage<>InvalidPageId do
begin
//fCurrentPage.AsBlock(st,slotToPageSlot(fhsId)*sizeof(hs),sizeof(hs),@hs);
//inc(fhsId);
//if ((fhsId MOD (HashSlotPerBlock-1))=1) and (fhsId<>1) then
begin //end of this read page, move to next one
//if fCurrentPage.block.nextPage<>InvalidPageId then
begin //get and pin next overflow page in this chain
inc(overflowCount);
lastPid:=fCurrentPage.block.prevPage; //i.e. save root page's prev pointer to end of chain
nextfPid:=fCurrentPage.block.nextPage; //save before we unpin
(Ttransaction(st.owner).db.owner as TDBServer).buffer.unpinPage(st,fpid); //un-pin current page
{Now we can deallocate this page}
if dirpage.latch(st)<>ok then //would be faster to latch once at start of routine
exit; //abort - todo make more resiliant?
try
{Re-point the bucket page to the next in the chain, i.e. skip this one before it's de-allocated}
hd.pid:=nextfPid;
dirpage.SetBlock(st,bucketToDirBucket(hashMap+1)*sizeof(hd),sizeof(hd),@hd);
{$IFDEF DEBUGDETAIL11}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Linking root to page (%d) to skip page (%d)',[hd.pid,fpid]),vDebugLow);
{$ENDIF}
{$ENDIF}
dirPage.dirty:=True;
finally
dirpage.unlatch(st);
end; {try}
if self.DirPageFindFromPID(st,fPid,dirPageId,dirSlot)<>ok then exit; //find slot for this page
if self.DirPageRemove(st,fPid,dirSlot)<>ok then exit; //reset the slot //Note: currently if this is 1st slot on an extended file directory page, the page will be deleted!
if Ttransaction(st.owner).db.deAllocatePage(st,fPid)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed de-allocating index file page',vError);
{$ENDIF}
exit;
end;
fpid:=nextfPid;
if (Ttransaction(st.owner).db.owner as TDBserver).buffer.pinPage(st,fpid,fCurrentPage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading bucket page %d',[fpid]),vError);
{$ENDIF}
exit; //abort
end;
if fCurrentPage.latch(st)<>ok then
exit; //abort - todo make more resiliant?
try
{Re-point the new root page to the last in the chain}
fCurrentPage.block.prevPage:=lastPid;
{$IFDEF DEBUGDETAIL11}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Linking end-of-chain-page (%d) to new root(%d).prevPage',[lastPid,fpid]),vDebugLow);
{$ENDIF}
{$ENDIF}
fCurrentPage.dirty:=True;
finally
fCurrentPage.unlatch(st);
end; {try}
(Ttransaction(st.owner).db.owner as TDBServer).buffer.flushPage(st,dirpid,nil);
(Ttransaction(st.owner).db.owner as TDBServer).buffer.flushPage(st,fpid,nil);
end
end;
end;
end;
//else skip detail
(Ttransaction(st.owner).db.owner as TDBServer).buffer.unpinPage(st,fpid); //un-pin current page
{Now we can deallocate this page}
if self.DirPageFindFromPID(st,fPid,dirPageId,dirSlot)<>ok then exit; //find slot for this page
if self.DirPageRemove(st,fPid,dirSlot)<>ok then exit; //reset the slot //Note: currently if this is 1st slot on an extended file directory page, the page will be deleted!
if Ttransaction(st.owner).db.deAllocatePage(st,fPid)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed de-allocating index file page',vError);
{$ENDIF}
exit;
end;
if dirpage.latch(st)<>ok then //would be faster to latch once at start of routine
exit; //abort - todo make more resiliant?
try
{Reset the bucket page}
hd.pid:=InvalidPageId;
dirpage.SetBlock(st,bucketToDirBucket(hashMap+1)*sizeof(hd),sizeof(hd),@hd);
{$IFDEF DEBUGDETAIL11}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Resetting bucket slot %d',[(hashMap+1)]),vDebugLow);
{$ENDIF}
{$ENDIF}
dirPage.dirty:=True;
finally
dirpage.unlatch(st);
end; {try}
(Ttransaction(st.owner).db.owner as TDBServer).buffer.flushPage(st,dirpid,nil);
end;
result:=ok;
finally
(Ttransaction(st.owner).db.owner as TDBServer).buffer.unpinPage(st,dirpid);
end; {try}
if result=ok then
begin
{Now we can deallocate this directory page}
if self.DirPageFindFromPID(st,dirPid,dirPageId,dirSlot)<>ok then exit; //find slot for this directory page
{Note: this is the last directory page so it should be at dirSlot=0, so assert! (we will have moved it there if there was originally more than 1 dir page)}
if self.DirPageRemove(st,dirPid,dirSlot)<>ok then exit; //reset the slot //Note: currently if this is 1st slot on an extended file directory page, the page will be deleted!
if Ttransaction(st.owner).db.deAllocatePage(st,dirpid)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed de-allocating index file page',vError);
{$ENDIF}
exit;
end;
{The above should have re-set the directory start}
end;
end
else
{there are no data pages for this file (yet) - should never happen for this type of file
- so assertion!}
;
result:=inherited DeleteFile(st);
if result=ok then
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Hash-index-file %s deleted',[fname]),vDebug);
{$ELSE}
;
{$ENDIF}
end; {deleteFile}
function THashIndexFile.extendDirectory(st:TStmt;var id:PageId):integer;
{Allocate a new page for this file directory and format it as a new directory page
IN:
OUT: id - new page id
}
const routine=':extendDirectory';
var
newpid:PageId;
newPage:TPage;
hashIndexFileDir:THashIndexFileDir;
dirSlot:DirSlotId;
dirPageId,prevDirSlotPageId:PageId;
i:integer;
begin
id:=InvalidPageId; //note not required, but safer
result:=Fail;
{Allocate and add a new page}
if Ttransaction(st.owner).db.allocatePage(st,newpid)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed allocating new page',vError);
{$ELSE}
;
{$ENDIF}
exit;
end;
{Initialise this new page as a hashIndexFile directory page}
with (Ttransaction(st.owner).db.owner as TDBserver) do
begin
if buffer.pinPage(st,newpid,newpage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading new page to initialise it, %d',[newpid]),vError);
{$ELSE}
;
{$ENDIF}
exit; //abort
end;
try
{Ok, add the page to the file's directory}
if DirPageAdd(st,newpid,freespace(st,newpage),prevDirSlotPageId,dirPageId,dirSlot)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed allocating new bucket directory page to page dir',vError);
{$ENDIF}
exit;
end;
{Initialise blank directory page}
if newpage.latch(st)=ok then //note: no real need since newpage=local/new?
begin
try
newpage.block.pageType:=ptIndexData; //todo: use new type, e.g. ptHashIndexFileDir?
{Write zeroised bucket pointers}
hashIndexFileDir.pid:=InvalidPageId;
for i:=0 to HashIndexFileDirPerBlock-1 do
begin
newpage.SetBlock(st,i*sizeof(hashIndexFileDir),sizeof(hashIndexFileDir),@hashIndexFileDir);
end;
newpage.dirty:=True;
finally
newpage.unlatch(st);
end; {try}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Extended hash file with directory page %d',[newpid]),vDebugLow);
{$ENDIF}
id:=newpid;
result:=ok;
end
else
exit; //abort
finally
buffer.unpinPage(st,newpid);
end; {try}
end; {with}
end; {extendDirectory}
function THashIndexFile.openFile(st:TStmt;const filename:string;startPage:PageId):integer;
{Opens a hash index file in the specified database
i.e. goes to the file's page directory header page
IN : db the database
: filename the existing filename
: startPage the start page for this file (found by caller from catalog)
RETURN : +ve=ok, else fail
Side effects:
sets fStartPage for this file
sets fname for this file
Assumes:
filename and startpage are valid
}
const routine=':openFile';
begin
result:=inherited openFile(st,filename,startPage);
if result=ok then
begin
//goto first record?
//goto bucket directory page? always = dirSlot=0
{$IFDEF DEBUGDETAIL4}
{$IFDEF DEBUG_LOG}
self.dump(st,nil);
{$ENDIF}
{$ENDIF}
end;
end; {openFile}
function THashIndexFile.freeSpace(st:TStmt;page:TPage):integer;
{Returns amount of free record space in the specified page
IN : page the page to examine
RETURN : the amount of free space
Note: this is not necessarily contiguous free space
Assumes:
we have the page pinned
(& latched if we are going to make use of the result...)
}
const routine=':freeSpace';
var
parentFreeSpace:integer;
begin
parentFreeSpace:=inherited freeSpace(st,page); //starting point
result:=parentFreeSpace;
result:=0; //for now... i.e. better for client to fail if it calls this than to assume space is available
//note if page[1] then n/a? or return free buckets?
end; {FreeSpace}
function THashIndexFile.allocateBucket(st:TStmt;localDepth:pageId;var id:PageId):integer;
{Allocate a new page for this file and format it as a new bucket
IN: localDepth - initial page local-depth
Note: type=pageId=>integer (only pageId because we overuse hash-slot [0]'s pid
OUT: id - new page id
}
const routine=':allocateBucket';
var
newpid:PageId;
newPage:TPage;
dirSlot:DirSlotId;
dirPageId,prevDirSlotPageId:PageId;
hsHeader:THashSlot;
begin
id:=InvalidPageId; //not required, but safer
result:=Fail;
{Todo move!}
if THashSlotSize<>sizeof(hsHeader) then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('THashSlotSize[%d]<>sizeof(hsHeader)[%d]',[THashSlotSize,sizeof(hsHeader)]),vAssertion);
{$ELSE}
;
{$ENDIF}
exit; //abort
end;
if Ttransaction(st.owner).db.allocatePage(st,newpid)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed allocating new file page',vError);
{$ELSE}
;
{$ENDIF}
exit;
end;
{Initialise this new page as a bucket page}
with (Ttransaction(st.owner).db.owner as TDBserver) do
begin
if buffer.pinPage(st,newpid,Newpage)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Failed reading new file page to initialise it, %d',[newpid]),vError);
{$ELSE}
;
{$ENDIF}
exit; //abort
end;
try
//todo remove: debug only!
{$IFDEF SAFETY}
{$IFDEF DEBUG_LOG} //todo: what if live?
if (Newpage.block.nextPage<>InvalidPageId) or (Newpage.block.prevPage<>InvalidPageId) then
log.add(st.who,where+routine,format('...newly allocated bucket page %d still has page links %d and %d (type=%d)! - continuing with risk of corruption...',[newpid,Newpage.block.prevPage,Newpage.block.nextPage,Newpage.block.pageType]),vAssertion);
{$ENDIF}
{$ENDIF}
{Initialise blank bucket page}
if newpage.latch(st)=ok then //note: no real need since newpage=local/new?
begin
try
newpage.block.pageType:=ptIndexData;
{Write blank hash-slot header}
hsHeader.hashValue:=0; //hash-slot count
hsHeader.RID.pid:=localDepth;
hsHeader.RID.sid:=InvalidSlotId; //unused
newpage.SetBlock(st,0,sizeof(hsHeader),@hsHeader);
//rest of page is left zeroised
newpage.dirty:=True;
finally
newpage.unlatch(st);
end; {try}
{Ok, add the page to the file's directory}
if DirPageAdd(st,newpid,freespace(st,newpage),prevDirSlotPageId,dirPageId,dirSlot)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,'Failed allocating new page to page dir',vError);
{$ENDIF}
exit;
end;
id:=newpid;
result:=ok;
end
else
exit; //abort
//Note: the prev/next page links are not used in this file's data pages
// (except bucket directory header if it grows past initial 1 page
// and except overflow pages needed when bucket is full of same hashvalue)
finally
buffer.unpinPage(st,newpid);
end; {try}
end; {with}
{$IFDEF DEBUG_LOG}
log.add(st.who,where+routine,format('Extended hash file with bucket page %d, local depth %d',[newpid,localDepth]),vDebugLow);
{$ENDIF}
end; {allocateBucket}
function THashIndexFile.Hash(t:TTuple):cardinal;
{Hash function
RETURNS: 0=fail, else hash value
Based on djb2 algorithm which is supposed to be good
Assumes:
length returned from TTuple.getDataPointer is in bytes
}
const routine=':Hash';
var
i:integer;
// pv:byte;
// p:^byte;
pv:char;
// pvi:integer;
p:pchar;
len,j:ColOffset;
isnull:boolean;
isString:boolean;
//todo remove need for these: speed
dt:TsqlDate;
tm:TsqlTime;
ts:TsqlTimestamp;
dayCarry:shortint;
s:string;
begin
result:=5381;
for i:=1 to colCount do
begin
isString:=(DataTypeDef[t.fColDef[colMap[i].cref].dataType] in [stString])
or (t.fColDef[colMap[i].cref].dataType in [ctClob]);
if DataTypeDef[t.fColDef[colMap[i].cref].dataType] in [stDate,stTime,stTimestamp] then
begin //we need to hash the string representation (else got different answers each time! -not sure why...)
case DataTypeDef[t.fColDef[colMap[i].cref].dataType] of
stDate: begin t.GetDate(colMap[i].cref,dt,isnull); s:=format(DATE_FORMAT,[dt.year,dt.month,dt.day]); end;
stTime: begin t.GetTime(colMap[i].cref,tm,isnull); s:=sqlTimeToStr(TIMEZONE_ZERO,tm,t.fColDef[colMap[i].cref].scale,dayCarry); end;
stTimestamp: begin t.GetTimestamp(colMap[i].cref,ts,isnull); s:=sqlTimestampToStr(TIMEZONE_ZERO,ts,t.fColDef[colMap[i].cref].scale); end;
end; {case}
t.colIsNull(colMap[i].cref,isnull);
len:=length(s);
p:=pchar(s);
end
else //get direct pointer to raw data
if t.GetDataPointer(colMap[i].cref,pointer(p),len,isnull)<>ok then
begin
{$IFDEF DEBUG_LOG}
log.add(who,where+routine,format('Failed reading column data %d',[i]),vDebugError);
{$ELSE}
;
{$ENDIF}
result:=0; //=don't use
exit; //abort, pointer is unsafe to use
end;
if not isnull then
for j:=0 to len-1 do
begin
pv:=p^;
{Note: we uppercase any text characters to ensure index searches ignore case}
if isString then pv:={byte(}upcase(char(pv)){)}; //todo assembly=speed
//todo: should also ignore trailing spaces, i.e. NO PAD, so that user passed values will match properly
//todo: ensure/check that caller converts comparand type to match the index type, e.g. date & string don't directly hash-compare this way here...
{$IFDEF DEBUGDETAIL10}
{$IFDEF DEBUG_LOG}
log.add(who,where+routine,format('Hashing byte %d %s',[j,char(pv)]),vDebugLow); //assertion?
{$ENDIF}
{$ENDIF}
//pvi:=ord(pv); //copy to 4-byte integer because assembly ADD wouldn't accept DWORD cast in Kylix beta //todo re-instate:speed
{We use assembly here because:
1. it prevents Delphi from raising overflow exceptions that we'd otherwise need to trap with expensive try...excepts
2. it's fast!
todo: use assembly to control the loop and key-character access...
Note: downside = less portable (but simple to port!)
}
{$IFDEF CPU64}
//todo remove once assembly code is working...
try
{$IFDEF FPC}
{$Push}
{$ENDIF}
{$OverflowChecks off}
Result := Result + (Result shl 5) + integer(p^); //hash * 33 + c
{$IFDEF FPC}
{$Pop}
{$ELSE}
{$ENDIF}
except //todo: maybe we need $Q+ to be able to trap this correctly?
;//continue, even if we have overflow...
end;
{$ELSE}
asm //result:=result + (result shl 5) + p^; //hash * 33 + c
MOV EAX,result
MOV ECX,result
SHL ECX,5
ADD ECX,DWORD(pv)
//todo remove: no need after Kylix released: ADD ECX,pvi
ADD EAX,ECX
MOV @result,EAX
end; {asm}
{$ENDIF}
inc(p);
end;
end;
if result=0 then result:=1; //avoid returning 0 = failure!
{$IFDEF DEBUGDETAIL10}
{$IFDEF DEBUG_LOG}
log.add(who,where+routine,format('Hash result=%d',[result]),vDebugLow); //assertion?
{$ENDIF}
{$ENDIF}
end; {Hash}
function THashIndexFile.slotCompare(ahashvalue:cardinal;arid:Trid;b:THashSlot):integer;
{Hash key/rid comparison function: needed for ordering the keys within page chains
RETURNS: -ve= a<b
0= a=b
+ve= a>b
Notes: includes rid in the comparison to allow duplicate entries to be spotted/prevented
still use hashvalue compares for finding routines
}
const routine=':slotCompare';
begin
result:=0;
if ahashvalue>b.HashValue then
result:=+1
else
if ahashvalue<b.HashValue then
result:=-1
else //result=0
if arid.pid>b.rid.pid then
result:=+1
else
if arid.pid<b.rid.pid then
result:=-1
else //result=0
if arid.sid>b.rid.sid then
result:=+1
else
if arid.sid<b.rid.sid then
result:=-1;
end; {slotCompare}
function THashIndexFile.AddKeyPtr(st:TStmt;t:TTuple;rid:Trid):integer;
{Add a new key+ptr to this file
IN: tr - transaction
t - tuple containing key data
rid - rid
RETURN: ok, else fail
Notes:
re-written to ensure page overflow chains are in order
first page in chain has slot 0 storing count and local depth
rest of pages in chain have slot 0 unused (although local depth is correct (but not used?))
i.e. we treat the overflow chain of pages as part of the root page = faster searching (slower inserts maybe, but more effective splitting)
todo: if we abort without inserting the new key it would be better to
set the index status to 'dodgy-needs a rebuild' rather than just failing...!
i.e. better to degrade to table scanning correctly than have missing rows
}
const routine=':AddKeyPtr';
function worthSplitting(rPid:PageId;newDepth:pageId;var lastP:Tpage):boolean;
{Checks whether it's worth splitting this page/chain
IN: rPid - page id of start of chain
newDepth - candidate depth to check against
OUT: lastP - last page in chain
(only if result=False)
RETURNS: True - worth splitting, else False
Side-effects:
if result=False then we leave the last page in the chain pinned and return a pointer to it
(so the caller can append an overflow page) - we'd need to read it anyway to prove result=False
Note: this might be = rPid, so it would be pinned again (assuming caller already pinned it)
Assumes:
all pages are full
Note:
may need to follow all page chain - doesn't leave all pinned
//todo may help if it did in a busy environment? since caller may need them again...
//todo: we should take account of the new key to be inserted -speed
// i.e. if it is different from all the ones in the chain (and they are the same)
// then it would be better in the long-run to split now
// rather than add another overflow when we would only split next time anyway
// - this logic should be in caller?