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
|
/*
Copyright (c) 2008 Health Market Science, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
You can contact Health Market Science at info@healthmarketscience.com
or at the following address:
Health Market Science
2700 Horizon Drive
Suite 200
King of Prussia, PA 19406
*/
package com.healthmarketscience.jackcess;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ObjectUtils;
import static com.healthmarketscience.jackcess.Index.*;
/**
* Manager of the index pages for a BigIndex.
* @author James Ahlborn
*/
public class IndexPageCache
{
/** the index whose pages this cache is managing */
private final BigIndex _index;
/** the root page for the index */
private DataPageMain _rootPage;
/** the currently loaded pages for this index, pageNumber -> page */
private final Map<Integer, DataPageMain> _dataPages =
new HashMap<Integer, DataPageMain>();
/** the currently modified index pages */
private final List<CacheDataPage> _modifiedPages =
new ArrayList<CacheDataPage>();
public IndexPageCache(BigIndex index) {
_index = index;
}
public BigIndex getIndex() {
return _index;
}
public JetFormat getFormat() {
return getIndex().getFormat();
}
public PageChannel getPageChannel() {
return getIndex().getPageChannel();
}
public void setRootPageNumber(int pageNumber) throws IOException {
_rootPage = getDataPage(pageNumber);
// root page has no parent
_rootPage.setParentPage(INVALID_INDEX_PAGE_NUMBER, false);
}
public void write()
throws IOException
{
preparePagesForWriting();
writeDataPages();
}
private void preparePagesForWriting()
throws IOException
{
// FIXME, writeme
}
private void writeDataPages()
throws IOException
{
for(CacheDataPage cacheDataPage : _modifiedPages) {
writeDataPage(cacheDataPage);
}
_modifiedPages.clear();
}
public CacheDataPage getCacheDataPage(Integer pageNumber)
throws IOException
{
DataPageMain main = getDataPage(pageNumber);
return((main != null) ? new CacheDataPage(main) : null);
}
private DataPageMain getChildDataPage(Integer childPageNumber,
DataPageMain parent,
boolean isTail)
throws IOException
{
DataPageMain child = getDataPage(childPageNumber);
if(child != null) {
// set the parent info for this child (if necessary)
child.setParentPage(parent._pageNumber, isTail);
}
return child;
}
private DataPageMain getDataPage(Integer pageNumber)
throws IOException
{
DataPageMain dataPage = _dataPages.get(pageNumber);
if((dataPage == null) && (pageNumber > INVALID_INDEX_PAGE_NUMBER)) {
dataPage = readDataPage(pageNumber)._main;
_dataPages.put(pageNumber, dataPage);
}
return dataPage;
}
/**
* Writes the given index page to the file.
*/
private void writeDataPage(CacheDataPage cacheDataPage)
throws IOException
{
getIndex().writeDataPage(cacheDataPage);
// lastly, mark the page as no longer modified
cacheDataPage._extra._modified = false;
}
/**
* Reads the given index page from the file.
*/
private CacheDataPage readDataPage(Integer pageNumber)
throws IOException
{
DataPageMain dataPage = new DataPageMain(pageNumber);
DataPageExtra extra = new DataPageExtra();
CacheDataPage cacheDataPage = new CacheDataPage(dataPage, extra);
getIndex().readDataPage(cacheDataPage);
// associate the extra info with the main data page
dataPage.setExtra(extra, true);
return cacheDataPage;
}
private void removeEntry(CacheDataPage cacheDataPage, int entryIdx)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
setModified(cacheDataPage);
boolean updateFirst = (entryIdx == 0);
boolean updateLast = (entryIdx == (dpExtra._entries.size() - 1));
Entry oldEntry = dpExtra._entries.remove(entryIdx);
dpExtra._totalEntrySize -= oldEntry.size();
// note, we don't need to futz with the _entryPrefix because a prefix is
// always still valid on removal
if(dpExtra._entries.isEmpty()) {
// this page is dead
deleteDataPage(cacheDataPage);
} else {
if(updateFirst) {
updateFirstEntry(cacheDataPage);
}
if(updateLast) {
dpMain._lastEntry = dpExtra.getLastEntry();
}
}
}
private void deleteDataPage(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
if(dpMain.isRoot()) {
// clear out this page (we don't actually delete it)
dpMain._firstEntry = null;
dpMain._lastEntry = null;
dpExtra._entryPrefix = EMPTY_PREFIX;
if(dpExtra._totalEntrySize != 0) {
throw new IllegalStateException("Empty page but size is not 0? " +
cacheDataPage);
}
return;
}
// remove this page from it's parent page
removeFromParent(cacheDataPage);
// remove this page from any next/prev pages
removeFromPeers(cacheDataPage);
// FIXME, deallocate index page?
}
private void removeFromParent(CacheDataPage childDataPage)
throws IOException
{
DataPageMain childMain = childDataPage._main;
DataPageExtra childExtra = childDataPage._extra;
CacheDataPage parentDataPage =
new CacheDataPage(childMain.getParentPage());
setModified(parentDataPage);
DataPageMain parentMain = parentDataPage._main;
DataPageExtra parentExtra = parentDataPage._extra;
if(childMain.isTail()) {
parentMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
} else {
Entry oldParentEntry = childMain._firstEntry.asNodeEntry(
childMain._pageNumber);
int idx = parentExtra.findEntry(oldParentEntry);
if(idx < 0) {
throw new IllegalStateException(
"Could not find child entry in parent; child " + childDataPage +
"; parent " + parentDataPage);
}
removeEntry(parentDataPage, idx);
}
}
private void removeFromPeers(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
Integer prevPageNumber = dpMain._prevPageNumber;
Integer nextPageNumber = dpMain._nextPageNumber;
DataPageMain prevMain = dpMain.getPrevPage();
if(prevMain != null) {
setModified(new CacheDataPage(prevMain));
prevMain._nextPageNumber = nextPageNumber;
}
DataPageMain nextMain = dpMain.getNextPage();
if(nextMain != null) {
setModified(new CacheDataPage(nextMain));
nextMain._prevPageNumber = prevPageNumber;
}
}
private void updateFirstEntry(CacheDataPage cacheDataPage)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
Entry oldEntry = dpMain._firstEntry;
dpMain._firstEntry = dpExtra.getFirstEntry();
DataPageMain parentMain = dpMain.getParentPage();
if(parentMain != null) {
Entry oldParentEntry = oldEntry.asNodeEntry(dpMain._pageNumber);
Entry newParentEntry =
dpMain._firstEntry.asNodeEntry(dpMain._pageNumber);
updateParentEntry(new CacheDataPage(parentMain),
oldParentEntry, newParentEntry);
}
}
private void updateParentEntry(CacheDataPage parentDataPage,
Entry oldEntry, Entry newEntry)
throws IOException
{
DataPageMain parentMain = parentDataPage._main;
DataPageExtra parentExtra = parentDataPage._extra;
setModified(parentDataPage);
int idx = parentExtra.findEntry(oldEntry);
if(idx < 0) {
throw new IllegalStateException(
"Could not find child entry in parent; childEntry " + oldEntry +
"; parent " + parentDataPage);
}
replaceEntry(parentDataPage, idx, newEntry);
}
private void addEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry)
throws IOException
{
addOrReplaceEntry(cacheDataPage, entryIdx, newEntry, true);
}
private void replaceEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry)
throws IOException
{
addOrReplaceEntry(cacheDataPage, entryIdx, newEntry, false);
}
private void addOrReplaceEntry(CacheDataPage cacheDataPage,
int entryIdx,
Entry newEntry,
boolean isAdd)
throws IOException
{
DataPageMain dpMain = cacheDataPage._main;
DataPageExtra dpExtra = cacheDataPage._extra;
validateEntryForPage(dpMain, newEntry);
setModified(cacheDataPage);
boolean updateFirst = false;
boolean updateLast = false;
if(isAdd) {
updateFirst = (entryIdx == 0);
updateLast = (entryIdx == dpExtra._entries.size());
dpExtra._entries.add(entryIdx, newEntry);
dpExtra._totalEntrySize += newEntry.size();
} else {
updateFirst = (entryIdx == 0);
updateLast = (entryIdx == (dpExtra._entries.size() - 1));
Entry oldEntry = dpExtra._entries.set(entryIdx, newEntry);
dpExtra._totalEntrySize += newEntry.size() - oldEntry.size();
}
if(updateFirst) {
updateFirstEntry(cacheDataPage);
}
if(updateLast) {
dpMain._lastEntry = newEntry;
}
if(updateFirst || updateLast) {
// update the prefix
dpExtra._entryPrefix = findNewPrefix(dpExtra._entryPrefix, newEntry);
}
}
private void validateEntryForPage(DataPageMain dataPage, Entry entry) {
if(dataPage._leaf != entry.isLeafEntry()) {
throw new IllegalStateException(
"Trying to update page with wrong entry type; pageLeaf " +
dataPage._leaf + ", entryLeaf " + entry.isLeafEntry());
}
}
public CacheDataPage findCacheDataPage(Entry e)
throws IOException
{
DataPageMain curPage = _rootPage;
while(true) {
int pageCmp = curPage.compareToPage(e);
if(pageCmp < 0) {
// find first leaf
while(!curPage._leaf) {
curPage = curPage.getChildPage(curPage._firstEntry);
}
return new CacheDataPage(curPage);
} else if(pageCmp > 0) {
if(!curPage._leaf) {
// we need to handle any "childTail" pages, so we aren't done yet
DataPageMain childTailPage = curPage.getChildTailPage();
if((childTailPage != null) &&
(childTailPage.compareToPage(e) >= 0)) {
curPage = childTailPage;
} else {
curPage = curPage.getChildPage(curPage._lastEntry);
}
} else {
return new CacheDataPage(curPage);
}
} else if(pageCmp == 0) {
DataPageExtra extra = curPage.getExtra();
if(curPage._leaf) {
return new CacheDataPage(curPage, extra);
}
// need to descend
int idx = extra.findEntry(e);
if(idx < 0) {
idx = missingIndexToInsertionPoint(idx);
if((idx == 0) || (idx == extra._entries.size())) {
// this should never happen, cause we already checked first/last
// entries in compareToPage
throw new IllegalStateException("first/last entries incorrect");
}
// the insertion point index is actually the entry after the one we
// want, so move back one element
--idx;
}
Entry nodeEntry = extra._entries.get(idx);
curPage = curPage.getChildPage(nodeEntry);
}
}
}
private void setModified(CacheDataPage cacheDataPage)
{
if(!cacheDataPage._extra._modified) {
_modifiedPages.add(cacheDataPage);
cacheDataPage._extra._modified = true;
}
}
private static byte[] findNewPrefix(byte[] curPrefix, Entry newEntry)
throws IOException
{
byte[] newEntryBytes = newEntry.getEntryBytes();
if(curPrefix.length > newEntryBytes.length) {
// the entry bytes may include the page number. need to encode the
// entire entry
newEntryBytes = new byte[newEntry.size()];
newEntry.write(ByteBuffer.wrap(newEntryBytes), EMPTY_PREFIX);
}
return findCommonPrefix(curPrefix, newEntryBytes);
}
private static byte[] findCommonPrefix(Entry e1, Entry e2)
{
return findCommonPrefix(e1.getEntryBytes(), e2.getEntryBytes());
}
private static byte[] findCommonPrefix(byte[] b1, byte[] b2)
{
int maxLen = b1.length;
byte[] prefix = b1;
if(b1.length > b2.length) {
maxLen = b2.length;
prefix = b2;
}
int len = 0;
while((len < maxLen) && (b1[len] == b2[len])) {
++len;
}
if(len < prefix.length) {
if(len == 0) {
return EMPTY_PREFIX;
}
// need new prefix
byte[] tmpPrefix = new byte[len];
System.arraycopy(prefix, 0, tmpPrefix, 0, len);
prefix = tmpPrefix;
}
return prefix;
}
private class DataPageMain implements Comparable<DataPageMain>
{
public final int _pageNumber;
public Integer _prevPageNumber;
public Integer _nextPageNumber;
public Integer _childTailPageNumber;
public Integer _parentPageNumber;
public Entry _firstEntry;
public Entry _lastEntry;
public boolean _leaf;
public boolean _tail;
private Reference<DataPageExtra> _extra;
private DataPageMain(int pageNumber) {
_pageNumber = pageNumber;
}
public IndexPageCache getCache() {
return IndexPageCache.this;
}
public boolean isRoot() {
return(this == _rootPage);
}
public boolean isTail() throws IOException
{
resolveParent();
return _tail;
}
public DataPageMain getParentPage() throws IOException
{
resolveParent();
return IndexPageCache.this.getDataPage(_parentPageNumber);
}
public void setParentPage(Integer parentPageNumber, boolean isTail) {
if(_parentPageNumber == null) {
_parentPageNumber = parentPageNumber;
_tail = isTail;
}
}
public DataPageMain getPrevPage() throws IOException
{
return IndexPageCache.this.getDataPage(_prevPageNumber);
}
public DataPageMain getNextPage() throws IOException
{
return IndexPageCache.this.getDataPage(_nextPageNumber);
}
public DataPageMain getChildPage(Entry e) throws IOException
{
return IndexPageCache.this.getChildDataPage(
e.getSubPageNumber(), this, false);
}
public DataPageMain getChildTailPage() throws IOException
{
return IndexPageCache.this.getChildDataPage(
_childTailPageNumber, this, true);
}
public DataPageExtra getExtra() throws IOException
{
DataPageExtra extra = _extra.get();
if(extra == null) {
extra = readDataPage(_pageNumber)._extra;
setExtra(extra, false);
}
return extra;
}
public void setExtra(DataPageExtra extra, boolean isNew) throws IOException
{
if(isNew) {
// save first/last entries
_firstEntry = extra.getFirstEntry();
_lastEntry = extra.getLastEntry();
} else {
// check first/last entries, to be safe
if(!ObjectUtils.equals(_firstEntry, extra.getFirstEntry()) ||
!ObjectUtils.equals(_lastEntry, extra.getLastEntry())) {
throw new IOException("Unexpected first or last entry found" +
"; had " + _firstEntry + ", " + _lastEntry +
"; found " + extra.getFirstEntry() + ", " +
extra.getLastEntry());
}
}
_extra = new SoftReference<DataPageExtra>(extra);
}
public int compareToPage(Entry e)
{
return((_firstEntry == null) ? 0 :
((e.compareTo(_firstEntry) < 0) ? -1 :
((e.compareTo(_lastEntry) > 0) ? 1 : 0)));
}
public int compareTo(DataPageMain other)
{
// note, only leaf pages can be meaningfully compared
if(!_leaf || !other._leaf) {
throw new IllegalArgumentException("Only leaf pages can be compared");
}
if(this == other) {
return 0;
}
// note, if there is more than one leaf page, neither should have null
// entries
return _firstEntry.compareTo(other._firstEntry);
}
private void resolveParent() throws IOException {
if(_parentPageNumber == null) {
// the act of searching for the first entry should resolve any parent
// pages along the path
findCacheDataPage(_firstEntry);
if(_parentPageNumber == null) {
throw new IllegalStateException("Parent was not resolved");
}
}
}
@Override
public String toString() {
return "DPMain[" + _pageNumber + "] " + _leaf + ", " + _firstEntry +
", " + _lastEntry + ", " + _extra.get();
}
}
private static class DataPageExtra
{
/** sorted collection of index entries. this is kept in a list instead of
a SortedSet because the SortedSet has lame traversal utilities */
public List<Entry> _entries;
public byte[] _entryPrefix;
public int _totalEntrySize;
public boolean _modified;
private DataPageExtra()
{
}
public int findEntry(Entry e) {
return Collections.binarySearch(_entries, e);
}
public Entry getFirstEntry() {
return (!_entries.isEmpty() ? _entries.get(0) : null);
}
public Entry getLastEntry() {
return (!_entries.isEmpty() ? _entries.get(_entries.size() - 1) : null);
}
@Override
public String toString() {
return "DPExtra: " + _entries;
}
}
public static final class CacheDataPage
extends Index.DataPage
{
public final DataPageMain _main;
public final DataPageExtra _extra;
private CacheDataPage(DataPageMain dataPage) throws IOException {
this(dataPage, dataPage.getExtra());
}
private CacheDataPage(DataPageMain dataPage, DataPageExtra extra) {
_main = dataPage;
_extra = extra;
}
@Override
public int getPageNumber() {
return _main._pageNumber;
}
@Override
public boolean isLeaf() {
return _main._leaf;
}
@Override
public void setLeaf(boolean isLeaf) {
_main._leaf = isLeaf;
}
@Override
public int getPrevPageNumber() {
return _main._prevPageNumber;
}
@Override
public void setPrevPageNumber(int pageNumber) {
_main._prevPageNumber = pageNumber;
}
@Override
public int getNextPageNumber() {
return _main._nextPageNumber;
}
@Override
public void setNextPageNumber(int pageNumber) {
_main._nextPageNumber = pageNumber;
}
@Override
public int getChildTailPageNumber() {
return _main._childTailPageNumber;
}
@Override
public void setChildTailPageNumber(int pageNumber) {
_main._childTailPageNumber = pageNumber;
}
@Override
public int getTotalEntrySize() {
return _extra._totalEntrySize;
}
@Override
public void setTotalEntrySize(int totalSize) {
_extra._totalEntrySize = totalSize;
}
@Override
public byte[] getEntryPrefix() {
return _extra._entryPrefix;
}
@Override
public void setEntryPrefix(byte[] entryPrefix) {
_extra._entryPrefix = entryPrefix;
}
@Override
public List<Entry> getEntries() {
return _extra._entries;
}
@Override
public void setEntries(List<Entry> entries) {
_extra._entries = entries;
}
@Override
public void addEntry(int idx, Entry entry) throws IOException {
_main.getCache().addEntry(this, idx, entry);
}
@Override
public void removeEntry(int idx) throws IOException {
_main.getCache().removeEntry(this, idx);
}
}
}
|