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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
|
/*
Copyright (c) 2007 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.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import com.healthmarketscience.jackcess.Table.RowState;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Manages iteration for a Table. Different cursors provide different methods
* of traversing a table. Cursors should be fairly robust in the face of
* table modification during traversal (although depending on how the table is
* traversed, row updates may or may not be seen). Multiple cursors may
* traverse the same table simultaneously.
* <p>
* The Cursor provides a variety of static utility methods to construct
* cursors with given characteristics or easily search for specific values.
* For even friendlier and more flexible construction, see
* {@link CursorBuilder}.
* <p>
* Is not thread-safe.
*
* @author James Ahlborn
*/
public abstract class Cursor implements Iterable<Map<String, Object>>
{
private static final Log LOG = LogFactory.getLog(Cursor.class);
/** boolean value indicating forward movement */
public static final boolean MOVE_FORWARD = true;
/** boolean value indicating reverse movement */
public static final boolean MOVE_REVERSE = false;
/** first position for the TableScanCursor */
private static final ScanPosition FIRST_SCAN_POSITION =
new ScanPosition(RowId.FIRST_ROW_ID);
/** last position for the TableScanCursor */
private static final ScanPosition LAST_SCAN_POSITION =
new ScanPosition(RowId.LAST_ROW_ID);
/** identifier for this cursor */
private final Id _id;
/** owning table */
private final Table _table;
/** State used for reading the table rows */
private final RowState _rowState;
/** the first (exclusive) row id for this cursor */
private final Position _firstPos;
/** the last (exclusive) row id for this cursor */
private final Position _lastPos;
/** the previous row */
private Position _prevPos;
/** the current row */
private Position _curPos;
protected Cursor(Id id, Table table, Position firstPos, Position lastPos) {
_id = id;
_table = table;
_rowState = _table.createRowState();
_firstPos = firstPos;
_lastPos = lastPos;
_curPos = firstPos;
_prevPos = firstPos;
}
/**
* Creates a normal, un-indexed cursor for the given table.
* @param table the table over which this cursor will traverse
*/
public static Cursor createCursor(Table table) {
return new TableScanCursor(table);
}
/**
* Creates an indexed cursor for the given table.
* <p>
* Note, index based table traversal may not include all rows, as certain
* types of indexes do not include all entries (namely, some indexes ignore
* null entries, see {@link Index#shouldIgnoreNulls}).
*
* @param table the table over which this cursor will traverse
* @param index index for the table which will define traversal order as
* well as enhance certain lookups
*/
public static Cursor createIndexCursor(Table table, Index index)
throws IOException
{
return createIndexCursor(table, index, null, null);
}
/**
* Creates an indexed cursor for the given table, narrowed to the given
* range.
* <p>
* Note, index based table traversal may not include all rows, as certain
* types of indexes do not include all entries (namely, some indexes ignore
* null entries, see {@link Index#shouldIgnoreNulls}).
*
* @param table the table over which this cursor will traverse
* @param index index for the table which will define traversal order as
* well as enhance certain lookups
* @param startRow the first row of data for the cursor (inclusive), or
* {@code null} for the first entry
* @param endRow the last row of data for the cursor (inclusive), or
* {@code null} for the last entry
*/
public static Cursor createIndexCursor(Table table, Index index,
Object[] startRow, Object[] endRow)
throws IOException
{
return createIndexCursor(table, index, startRow, true, endRow, true);
}
/**
* Creates an indexed cursor for the given table, narrowed to the given
* range.
* <p>
* Note, index based table traversal may not include all rows, as certain
* types of indexes do not include all entries (namely, some indexes ignore
* null entries, see {@link Index#shouldIgnoreNulls}).
*
* @param table the table over which this cursor will traverse
* @param index index for the table which will define traversal order as
* well as enhance certain lookups
* @param startRow the first row of data for the cursor, or {@code null} for
* the first entry
* @param startInclusive whether or not startRow is inclusive or exclusive
* @param endRow the last row of data for the cursor, or {@code null} for
* the last entry
* @param endInclusive whether or not endRow is inclusive or exclusive
*/
public static Cursor createIndexCursor(Table table, Index index,
Object[] startRow,
boolean startInclusive,
Object[] endRow,
boolean endInclusive)
throws IOException
{
if(table != index.getTable()) {
throw new IllegalArgumentException(
"Given index is not for given table: " + index + ", " + table);
}
return new IndexCursor(table, index,
index.cursor(startRow, startInclusive,
endRow, endInclusive));
}
/**
* Convenience method for finding a specific row in a table which matches a
* given row "pattern". See {@link #findRow(Map)} for details on the
* rowPattern.
*
* @param table the table to search
* @param rowPattern pattern to be used to find the row
* @return the matching row or {@code null} if a match could not be found.
*/
public static Map<String,Object> findRow(Table table,
Map<String,Object> rowPattern)
throws IOException
{
Cursor cursor = createCursor(table);
if(cursor.findRow(rowPattern)) {
return cursor.getCurrentRow();
}
return null;
}
/**
* Convenience method for finding a specific row in a table which matches a
* given row "pattern". See {@link #findRow(Column,Object)} for details on
* the pattern.
* <p>
* Note, a {@code null} result value is ambiguous in that it could imply no
* match or a matching row with {@code null} for the desired value. If
* distinguishing this situation is important, you will need to use a Cursor
* directly instead of this convenience method.
*
* @param table the table to search
* @param column column whose value should be returned
* @param columnPattern column being matched by the valuePattern
* @param valuePattern value from the columnPattern which will match the
* desired row
* @return the matching row or {@code null} if a match could not be found.
*/
public static Object findValue(Table table, Column column,
Column columnPattern, Object valuePattern)
throws IOException
{
Cursor cursor = createCursor(table);
if(cursor.findRow(columnPattern, valuePattern)) {
return cursor.getCurrentRowValue(column);
}
return null;
}
/**
* Convenience method for finding a specific row in an indexed table which
* matches a given row "pattern". See {@link #findRow(Map)} for details on
* the rowPattern.
*
* @param table the table to search
* @param index index to assist the search
* @param rowPattern pattern to be used to find the row
* @return the matching row or {@code null} if a match could not be found.
*/
public static Map<String,Object> findRow(Table table, Index index,
Map<String,Object> rowPattern)
throws IOException
{
Cursor cursor = createIndexCursor(table, index);
if(cursor.findRow(rowPattern)) {
return cursor.getCurrentRow();
}
return null;
}
/**
* Convenience method for finding a specific row in a table which matches a
* given row "pattern". See {@link #findRow(Column,Object)} for details on
* the pattern.
* <p>
* Note, a {@code null} result value is ambiguous in that it could imply no
* match or a matching row with {@code null} for the desired value. If
* distinguishing this situation is important, you will need to use a Cursor
* directly instead of this convenience method.
*
* @param table the table to search
* @param index index to assist the search
* @param column column whose value should be returned
* @param columnPattern column being matched by the valuePattern
* @param valuePattern value from the columnPattern which will match the
* desired row
* @return the matching row or {@code null} if a match could not be found.
*/
public static Object findValue(Table table, Index index, Column column,
Column columnPattern, Object valuePattern)
throws IOException
{
Cursor cursor = createIndexCursor(table, index);
if(cursor.findRow(columnPattern, valuePattern)) {
return cursor.getCurrentRowValue(column);
}
return null;
}
public Id getId() {
return _id;
}
public Table getTable() {
return _table;
}
public Index getIndex() {
return null;
}
public JetFormat getFormat() {
return getTable().getFormat();
}
public PageChannel getPageChannel() {
return getTable().getPageChannel();
}
/**
* Gets the currently configured ErrorHandler (always non-{@code null}).
* This will be used to handle all errors.
*/
public ErrorHandler getErrorHandler() {
return _rowState.getErrorHandler();
}
/**
* Sets a new ErrorHandler. If {@code null}, resets to using the
* ErrorHandler configured at the Table level.
*/
public void setErrorHandler(ErrorHandler newErrorHandler) {
_rowState.setErrorHandler(newErrorHandler);
}
/**
* Returns the current state of the cursor which can be restored at a future
* point in time by a call to {@link #restoreSavepoint}.
* <p>
* Savepoints may be used across different cursor instances for the same
* table, but they must have the same {@link Id}.
*/
public Savepoint getSavepoint() {
return new Savepoint(_id, _curPos, _prevPos);
}
/**
* Moves the cursor to a savepoint previously returned from
* {@link #getSavepoint}.
* @throws IllegalArgumentException if the given savepoint does not have a
* cursorId equal to this cursor's id
*/
public void restoreSavepoint(Savepoint savepoint)
throws IOException
{
if(!_id.equals(savepoint.getCursorId())) {
throw new IllegalArgumentException(
"Savepoint " + savepoint + " is not valid for this cursor with id "
+ _id);
}
restorePosition(savepoint.getCurrentPosition(),
savepoint.getPreviousPosition());
}
/**
* Returns the first row id (exclusive) as defined by this cursor.
*/
protected Position getFirstPosition() {
return _firstPos;
}
/**
* Returns the last row id (exclusive) as defined by this cursor.
*/
protected Position getLastPosition() {
return _lastPos;
}
/**
* Resets this cursor for forward traversal. Calls {@link #beforeFirst}.
*/
public void reset() {
beforeFirst();
}
/**
* Resets this cursor for forward traversal (sets cursor to before the first
* row).
*/
public void beforeFirst() {
reset(MOVE_FORWARD);
}
/**
* Resets this cursor for reverse traversal (sets cursor to after the last
* row).
*/
public void afterLast() {
reset(MOVE_REVERSE);
}
/**
* Returns {@code true} if the cursor is currently positioned before the
* first row, {@code false} otherwise.
*/
public boolean isBeforeFirst()
throws IOException
{
if(getFirstPosition().equals(_curPos)) {
return !recheckPosition(MOVE_REVERSE);
}
return false;
}
/**
* Returns {@code true} if the cursor is currently positioned after the
* last row, {@code false} otherwise.
*/
public boolean isAfterLast()
throws IOException
{
if(getLastPosition().equals(_curPos)) {
return !recheckPosition(MOVE_FORWARD);
}
return false;
}
/**
* Returns {@code true} if the row at which the cursor is currently
* positioned is deleted, {@code false} otherwise (including invalid rows).
*/
public boolean isCurrentRowDeleted()
throws IOException
{
// we need to ensure that the "deleted" flag has been read for this row
// (or re-read if the table has been recently modified)
Table.positionAtRowData(_rowState, _curPos.getRowId());
return _rowState.isDeleted();
}
/**
* Resets this cursor for traversing the given direction.
*/
protected void reset(boolean moveForward) {
_curPos = getDirHandler(moveForward).getBeginningPosition();
_prevPos = _curPos;
_rowState.reset();
}
/**
* Returns an Iterable whose iterator() method calls <code>afterLast</code>
* on this cursor and returns an unmodifiable Iterator which will iterate
* through all the rows of this table in reverse order. Use of the Iterator
* follows the same restrictions as a call to <code>getPreviousRow</code>.
* @throws IllegalStateException if an IOException is thrown by one of the
* operations, the actual exception will be contained within
*/
public Iterable<Map<String, Object>> reverseIterable() {
return reverseIterable(null);
}
/**
* Returns an Iterable whose iterator() method calls <code>afterLast</code>
* on this table and returns an unmodifiable Iterator which will iterate
* through all the rows of this table in reverse order, returning only the
* given columns. Use of the Iterator follows the same restrictions as a
* call to <code>getPreviousRow</code>.
* @throws IllegalStateException if an IOException is thrown by one of the
* operations, the actual exception will be contained within
*/
public Iterable<Map<String, Object>> reverseIterable(
final Collection<String> columnNames)
{
return new Iterable<Map<String, Object>>() {
public Iterator<Map<String, Object>> iterator() {
return new RowIterator(columnNames, MOVE_REVERSE);
}
};
}
/**
* Calls <code>beforeFirst</code> on this cursor and returns an unmodifiable
* Iterator which will iterate through all the rows of this table. Use of
* the Iterator follows the same restrictions as a call to
* <code>getNextRow</code>.
* @throws IllegalStateException if an IOException is thrown by one of the
* operations, the actual exception will be contained within
*/
public Iterator<Map<String, Object>> iterator()
{
return iterator(null);
}
/**
* Returns an Iterable whose iterator() method returns the result of a call
* to {@link #iterator(Collection)}
* @throws IllegalStateException if an IOException is thrown by one of the
* operations, the actual exception will be contained within
*/
public Iterable<Map<String, Object>> iterable(
final Collection<String> columnNames)
{
return new Iterable<Map<String, Object>>() {
public Iterator<Map<String, Object>> iterator() {
return Cursor.this.iterator(columnNames);
}
};
}
/**
* Calls <code>beforeFirst</code> on this table and returns an unmodifiable
* Iterator which will iterate through all the rows of this table, returning
* only the given columns. Use of the Iterator follows the same
* restrictions as a call to <code>getNextRow</code>.
* @throws IllegalStateException if an IOException is thrown by one of the
* operations, the actual exception will be contained within
*/
public Iterator<Map<String, Object>> iterator(Collection<String> columnNames)
{
return new RowIterator(columnNames, MOVE_FORWARD);
}
/**
* Delete the current row.
* @throws IllegalStateException if the current row is not valid (at
* beginning or end of table), or already deleted.
*/
public void deleteCurrentRow() throws IOException {
_table.deleteRow(_rowState, _curPos.getRowId());
}
/**
* Update the current row.
* @throws IllegalStateException if the current row is not valid (at
* beginning or end of table), or deleted.
*/
public void updateCurrentRow(Object... row) throws IOException {
_table.updateRow(_rowState, _curPos.getRowId(), row);
}
/**
* Moves to the next row in the table and returns it.
* @return The next row in this table (Column name -> Column value), or
* {@code null} if no next row is found
*/
public Map<String, Object> getNextRow() throws IOException {
return getNextRow(null);
}
/**
* Moves to the next row in the table and returns it.
* @param columnNames Only column names in this collection will be returned
* @return The next row in this table (Column name -> Column value), or
* {@code null} if no next row is found
*/
public Map<String, Object> getNextRow(Collection<String> columnNames)
throws IOException
{
return getAnotherRow(columnNames, MOVE_FORWARD);
}
/**
* Moves to the previous row in the table and returns it.
* @return The previous row in this table (Column name -> Column value), or
* {@code null} if no previous row is found
*/
public Map<String, Object> getPreviousRow() throws IOException {
return getPreviousRow(null);
}
/**
* Moves to the previous row in the table and returns it.
* @param columnNames Only column names in this collection will be returned
* @return The previous row in this table (Column name -> Column value), or
* {@code null} if no previous row is found
*/
public Map<String, Object> getPreviousRow(Collection<String> columnNames)
throws IOException
{
return getAnotherRow(columnNames, MOVE_REVERSE);
}
/**
* Moves to another row in the table based on the given direction and
* returns it.
* @param columnNames Only column names in this collection will be returned
* @return another row in this table (Column name -> Column value), where
* "next" may be backwards if moveForward is {@code false}, or
* {@code null} if there is not another row in the given direction.
*/
private Map<String, Object> getAnotherRow(Collection<String> columnNames,
boolean moveForward)
throws IOException
{
if(moveToAnotherRow(moveForward)) {
return getCurrentRow(columnNames);
}
return null;
}
/**
* Moves to the next row as defined by this cursor.
* @return {@code true} if a valid next row was found, {@code false}
* otherwise
*/
public boolean moveToNextRow()
throws IOException
{
return moveToAnotherRow(MOVE_FORWARD);
}
/**
* Moves to the previous row as defined by this cursor.
* @return {@code true} if a valid previous row was found, {@code false}
* otherwise
*/
public boolean moveToPreviousRow()
throws IOException
{
return moveToAnotherRow(MOVE_REVERSE);
}
/**
* Moves to another row in the given direction as defined by this cursor.
* @return {@code true} if another valid row was found in the given
* direction, {@code false} otherwise
*/
private boolean moveToAnotherRow(boolean moveForward)
throws IOException
{
if(_curPos.equals(getDirHandler(moveForward).getEndPosition())) {
// already at end, make sure nothing has changed
return recheckPosition(moveForward);
}
return moveToAnotherRowImpl(moveForward);
}
/**
* Restores a current position for the cursor (current position becomes
* previous position).
*/
protected void restorePosition(Position curPos)
throws IOException
{
restorePosition(curPos, _curPos);
}
/**
* Restores a current and previous position for the cursor if the given
* positions are different from the current positions.
*/
protected final void restorePosition(Position curPos, Position prevPos)
throws IOException
{
if(!curPos.equals(_curPos) || !prevPos.equals(_prevPos)) {
restorePositionImpl(curPos, prevPos);
}
}
/**
* Restores a current and previous position for the cursor.
*/
protected void restorePositionImpl(Position curPos, Position prevPos)
throws IOException
{
// make the current position previous, and the new position current
_prevPos = _curPos;
_curPos = curPos;
_rowState.reset();
}
/**
* Rechecks the current position if the underlying data structures have been
* modified.
* @return {@code true} if the cursor ended up in a new position,
* {@code false} otherwise.
*/
private boolean recheckPosition(boolean moveForward)
throws IOException
{
if(isUpToDate()) {
// nothing has changed
return false;
}
// move the cursor back to the previous position
restorePosition(_prevPos);
return moveToAnotherRowImpl(moveForward);
}
/**
* Does the grunt work of moving the cursor to another position in the given
* direction.
*/
private boolean moveToAnotherRowImpl(boolean moveForward)
throws IOException
{
_rowState.reset();
_prevPos = _curPos;
_curPos = findAnotherPosition(_rowState, _curPos, moveForward);
Table.positionAtRowHeader(_rowState, _curPos.getRowId());
return(!_curPos.equals(getDirHandler(moveForward).getEndPosition()));
}
/**
* Moves to the first row (as defined by the cursor) where the given column
* has the given value. This may be more efficient on some cursors than
* others. If a match is not found (or an exception is thrown), the cursor
* is restored to its previous state.
*
* @param columnPattern column from the table for this cursor which is being
* matched by the valuePattern
* @param valuePattern value which is equal to the corresponding value in
* the matched row
* @return {@code true} if a valid row was found with the given value,
* {@code false} if no row was found
*/
public boolean findRow(Column columnPattern, Object valuePattern)
throws IOException
{
Position curPos = _curPos;
Position prevPos = _prevPos;
boolean found = false;
try {
found = findRowImpl(columnPattern, valuePattern);
return found;
} finally {
if(!found) {
try {
restorePosition(curPos, prevPos);
} catch(IOException e) {
LOG.error("Failed restoring position", e);
}
}
}
}
/**
* Moves to the first row (as defined by the cursor) where the given columns
* have the given values. This may be more efficient on some cursors than
* others. If a match is not found (or an exception is thrown), the cursor
* is restored to its previous state.
*
* @param rowPattern column names and values which must be equal to the
* corresponding values in the matched row
* @return {@code true} if a valid row was found with the given values,
* {@code false} if no row was found
*/
public boolean findRow(Map<String,Object> rowPattern)
throws IOException
{
Position curPos = _curPos;
Position prevPos = _prevPos;
boolean found = false;
try {
found = findRowImpl(rowPattern);
return found;
} finally {
if(!found) {
try {
restorePosition(curPos, prevPos);
} catch(IOException e) {
LOG.error("Failed restoring position", e);
}
}
}
}
/**
* Returns {@code true} if the current row matches the given pattern.
* @param columnPattern column from the table for this cursor which is being
* matched by the valuePattern
* @param valuePattern value which is tested for equality with the
* corresponding value in the current row
*/
public boolean currentRowMatches(Column columnPattern, Object valuePattern)
throws IOException
{
return ObjectUtils.equals(valuePattern, getCurrentRowValue(columnPattern));
}
/**
* Returns {@code true} if the current row matches the given pattern.
* @param rowPattern column names and values which must be equal to the
* corresponding values in the current row
*/
public boolean currentRowMatches(Map<String,Object> rowPattern)
throws IOException
{
return ObjectUtils.equals(rowPattern, getCurrentRow(rowPattern.keySet()));
}
/**
* Moves to the first row (as defined by the cursor) where the given column
* has the given value. Caller manages save/restore on failure.
* <p>
* Default implementation scans the table from beginning to end.
*
* @param columnPattern column from the table for this cursor which is being
* matched by the valuePattern
* @param valuePattern value which is equal to the corresponding value in
* the matched row
* @return {@code true} if a valid row was found with the given value,
* {@code false} if no row was found
*/
protected boolean findRowImpl(Column columnPattern, Object valuePattern)
throws IOException
{
beforeFirst();
while(moveToNextRow()) {
if(currentRowMatches(columnPattern, valuePattern)) {
return true;
}
}
return false;
}
/**
* Moves to the first row (as defined by the cursor) where the given columns
* have the given values. Caller manages save/restore on failure.
* <p>
* Default implementation scans the table from beginning to end.
*
* @param rowPattern column names and values which must be equal to the
* corresponding values in the matched row
* @return {@code true} if a valid row was found with the given values,
* {@code false} if no row was found
*/
protected boolean findRowImpl(Map<String,Object> rowPattern)
throws IOException
{
beforeFirst();
while(moveToNextRow()) {
if(currentRowMatches(rowPattern)) {
return true;
}
}
return false;
}
/**
* Moves forward as many rows as possible up to the given number of rows.
* @return the number of rows moved.
*/
public int moveNextRows(int numRows)
throws IOException
{
return moveSomeRows(numRows, MOVE_FORWARD);
}
/**
* Moves backward as many rows as possible up to the given number of rows.
* @return the number of rows moved.
*/
public int movePreviousRows(int numRows)
throws IOException
{
return moveSomeRows(numRows, MOVE_REVERSE);
}
/**
* Moves as many rows as possible in the given direction up to the given
* number of rows.
* @return the number of rows moved.
*/
private int moveSomeRows(int numRows, boolean moveForward)
throws IOException
{
int numMovedRows = 0;
while((numMovedRows < numRows) && moveToAnotherRow(moveForward)) {
++numMovedRows;
}
return numMovedRows;
}
/**
* Returns the current row in this cursor (Column name -> Column value).
*/
public Map<String, Object> getCurrentRow()
throws IOException
{
return getCurrentRow(null);
}
/**
* Returns the current row in this cursor (Column name -> Column value).
* @param columnNames Only column names in this collection will be returned
*/
public Map<String, Object> getCurrentRow(Collection<String> columnNames)
throws IOException
{
return _table.getRow(_rowState, _curPos.getRowId(), columnNames);
}
/**
* Returns the given column from the current row.
*/
public Object getCurrentRowValue(Column column)
throws IOException
{
return _table.getRowValue(_rowState, _curPos.getRowId(), column);
}
/**
* Returns {@code true} if this cursor is up-to-date with respect to the
* relevant table and related table objects, {@code false} otherwise.
*/
protected boolean isUpToDate() {
return _rowState.isUpToDate();
}
@Override
public String toString() {
return getClass().getSimpleName() + " CurPosition " + _curPos +
", PrevPosition " + _prevPos;
}
/**
* Finds the next non-deleted row after the given row (as defined by this
* cursor) and returns the id of the row, where "next" may be backwards if
* moveForward is {@code false}. If there are no more rows, the returned
* rowId should equal the value returned by {@link #getLastPosition} if moving
* forward and {@link #getFirstPosition} if moving backward.
*/
protected abstract Position findAnotherPosition(RowState rowState,
Position curPos,
boolean moveForward)
throws IOException;
/**
* Returns the DirHandler for the given movement direction.
*/
protected abstract DirHandler getDirHandler(boolean moveForward);
/**
* Row iterator for this table, unmodifiable.
*/
private final class RowIterator implements Iterator<Map<String, Object>>
{
private final Collection<String> _columnNames;
private final boolean _moveForward;
private boolean _hasNext = false;
private RowIterator(Collection<String> columnNames, boolean moveForward)
{
try {
_columnNames = columnNames;
_moveForward = moveForward;
reset(_moveForward);
_hasNext = moveToAnotherRow(_moveForward);
} catch(IOException e) {
throw new IllegalStateException(e);
}
}
public boolean hasNext() { return _hasNext; }
public void remove() {
throw new UnsupportedOperationException();
}
public Map<String, Object> next() {
if(!hasNext()) {
throw new NoSuchElementException();
}
try {
Map<String, Object> rtn = getCurrentRow(_columnNames);
_hasNext = moveToAnotherRow(_moveForward);
return rtn;
} catch(IOException e) {
throw new IllegalStateException(e);
}
}
}
/**
* Handles moving the cursor in a given direction. Separates cursor
* logic from value storage.
*/
protected abstract class DirHandler
{
public abstract Position getBeginningPosition();
public abstract Position getEndPosition();
}
/**
* Simple un-indexed cursor.
*/
private static final class TableScanCursor extends Cursor
{
/** ScanDirHandler for forward traversal */
private final ScanDirHandler _forwardDirHandler =
new ForwardScanDirHandler();
/** ScanDirHandler for backward traversal */
private final ScanDirHandler _reverseDirHandler =
new ReverseScanDirHandler();
/** Cursor over the pages that this table owns */
private final UsageMap.PageCursor _ownedPagesCursor;
private TableScanCursor(Table table) {
super(new Id(table, null), table,
FIRST_SCAN_POSITION, LAST_SCAN_POSITION);
_ownedPagesCursor = table.getOwnedPagesCursor();
}
@Override
protected ScanDirHandler getDirHandler(boolean moveForward) {
return (moveForward ? _forwardDirHandler : _reverseDirHandler);
}
@Override
protected boolean isUpToDate() {
return(super.isUpToDate() && _ownedPagesCursor.isUpToDate());
}
@Override
protected void reset(boolean moveForward) {
_ownedPagesCursor.reset(moveForward);
super.reset(moveForward);
}
@Override
protected void restorePositionImpl(Position curPos, Position prevPos)
throws IOException
{
if(!(curPos instanceof ScanPosition) ||
!(prevPos instanceof ScanPosition)) {
throw new IllegalArgumentException(
"Restored positions must be scan positions");
}
_ownedPagesCursor.restorePosition(curPos.getRowId().getPageNumber(),
prevPos.getRowId().getPageNumber());
super.restorePositionImpl(curPos, prevPos);
}
@Override
protected Position findAnotherPosition(RowState rowState, Position curPos,
boolean moveForward)
throws IOException
{
ScanDirHandler handler = getDirHandler(moveForward);
// figure out how many rows are left on this page so we can find the
// next row
RowId curRowId = curPos.getRowId();
Table.positionAtRowHeader(rowState, curRowId);
int currentRowNumber = curRowId.getRowNumber();
// loop until we find the next valid row or run out of pages
while(true) {
currentRowNumber = handler.getAnotherRowNumber(currentRowNumber);
curRowId = new RowId(curRowId.getPageNumber(), currentRowNumber);
Table.positionAtRowHeader(rowState, curRowId);
if(!rowState.isValid()) {
// load next page
curRowId = new RowId(handler.getAnotherPageNumber(),
RowId.INVALID_ROW_NUMBER);
Table.positionAtRowHeader(rowState, curRowId);
if(!rowState.isHeaderPageNumberValid()) {
//No more owned pages. No more rows.
return handler.getEndPosition();
}
// update row count and initial row number
currentRowNumber = handler.getInitialRowNumber(
rowState.getRowsOnHeaderPage());
} else if(!rowState.isDeleted()) {
// we found a valid, non-deleted row, return it
return new ScanPosition(curRowId);
}
}
}
/**
* Handles moving the table scan cursor in a given direction. Separates
* cursor logic from value storage.
*/
private abstract class ScanDirHandler extends DirHandler {
public abstract int getAnotherRowNumber(int curRowNumber);
public abstract int getAnotherPageNumber();
public abstract int getInitialRowNumber(int rowsOnPage);
}
/**
* Handles moving the table scan cursor forward.
*/
private final class ForwardScanDirHandler extends ScanDirHandler {
@Override
public Position getBeginningPosition() {
return getFirstPosition();
}
@Override
public Position getEndPosition() {
return getLastPosition();
}
@Override
public int getAnotherRowNumber(int curRowNumber) {
return curRowNumber + 1;
}
@Override
public int getAnotherPageNumber() {
return _ownedPagesCursor.getNextPage();
}
@Override
public int getInitialRowNumber(int rowsOnPage) {
return -1;
}
}
/**
* Handles moving the table scan cursor backward.
*/
private final class ReverseScanDirHandler extends ScanDirHandler {
@Override
public Position getBeginningPosition() {
return getLastPosition();
}
@Override
public Position getEndPosition() {
return getFirstPosition();
}
@Override
public int getAnotherRowNumber(int curRowNumber) {
return curRowNumber - 1;
}
@Override
public int getAnotherPageNumber() {
return _ownedPagesCursor.getPreviousPage();
}
@Override
public int getInitialRowNumber(int rowsOnPage) {
return rowsOnPage;
}
}
}
/**
* Indexed cursor.
*/
private static final class IndexCursor extends Cursor
{
/** IndexDirHandler for forward traversal */
private final IndexDirHandler _forwardDirHandler =
new ForwardIndexDirHandler();
/** IndexDirHandler for backward traversal */
private final IndexDirHandler _reverseDirHandler =
new ReverseIndexDirHandler();
/** Cursor over the entries of the relvant index */
private final Index.EntryCursor _entryCursor;
private IndexCursor(Table table, Index index,
Index.EntryCursor entryCursor)
throws IOException
{
super(new Id(table, index), table,
new IndexPosition(entryCursor.getFirstEntry()),
new IndexPosition(entryCursor.getLastEntry()));
_entryCursor = entryCursor;
}
@Override
public Index getIndex() {
return _entryCursor.getIndex();
}
@Override
protected IndexDirHandler getDirHandler(boolean moveForward) {
return (moveForward ? _forwardDirHandler : _reverseDirHandler);
}
@Override
protected boolean isUpToDate() {
return(super.isUpToDate() && _entryCursor.isUpToDate());
}
@Override
protected void reset(boolean moveForward) {
_entryCursor.reset(moveForward);
super.reset(moveForward);
}
@Override
protected void restorePositionImpl(Position curPos, Position prevPos)
throws IOException
{
if(!(curPos instanceof IndexPosition) ||
!(prevPos instanceof IndexPosition)) {
throw new IllegalArgumentException(
"Restored positions must be index positions");
}
_entryCursor.restorePosition(((IndexPosition)curPos).getEntry(),
((IndexPosition)prevPos).getEntry());
super.restorePositionImpl(curPos, prevPos);
}
@Override
protected boolean findRowImpl(Column columnPattern, Object valuePattern)
throws IOException
{
Object[] rowValues = _entryCursor.getIndex().constructIndexRow(
columnPattern.getName(), valuePattern);
if(rowValues == null) {
// bummer, use the default table scan
return super.findRowImpl(columnPattern, valuePattern);
}
// sweet, we can use our index
_entryCursor.beforeEntry(rowValues);
Index.Entry startEntry = _entryCursor.getNextEntry();
if(!startEntry.getRowId().isValid()) {
// at end of index, no potential matches
return false;
}
// either we found a row with the given value, or none exist in the
// table
restorePosition(new IndexPosition(startEntry));
return currentRowMatches(columnPattern, valuePattern);
}
@Override
protected boolean findRowImpl(Map<String,Object> rowPattern)
throws IOException
{
Index index = _entryCursor.getIndex();
Object[] rowValues = index.constructIndexRow(rowPattern);
if(rowValues == null) {
// bummer, use the default table scan
return super.findRowImpl(rowPattern);
}
// sweet, we can use our index
_entryCursor.beforeEntry(rowValues);
Index.Entry startEntry = _entryCursor.getNextEntry();
if(!startEntry.getRowId().isValid()) {
// at end of index, no potential matches
return false;
}
restorePosition(new IndexPosition(startEntry));
Map<String,Object> indexRowPattern = null;
if(rowPattern.size() == index.getColumns().size()) {
// the rowPattern matches our index columns exactly, so we can
// streamline our testing below
indexRowPattern = rowPattern;
} else {
// the rowPattern has more columns than just the index, so we need to
// do more work when testing below
indexRowPattern =
new LinkedHashMap<String,Object>();
for(Index.ColumnDescriptor idxCol : index.getColumns()) {
indexRowPattern.put(idxCol.getName(),
rowValues[idxCol.getColumnIndex()]);
}
}
// there may be multiple columns which fit the pattern subset used by
// the index, so we need to keep checking until our index values no
// longer match
do {
if(!currentRowMatches(indexRowPattern)) {
// there are no more rows which could possibly match
break;
}
// note, if rowPattern == indexRowPattern, no need to do an extra
// comparison with the current row
if((rowPattern == indexRowPattern) || currentRowMatches(rowPattern)) {
// found it!
return true;
}
} while(moveToNextRow());
// none of the potential rows matched
return false;
}
@Override
protected Position findAnotherPosition(RowState rowState, Position curPos,
boolean moveForward)
throws IOException
{
IndexDirHandler handler = getDirHandler(moveForward);
IndexPosition endPos = (IndexPosition)handler.getEndPosition();
Index.Entry entry = handler.getAnotherEntry();
return ((!entry.equals(endPos.getEntry())) ?
new IndexPosition(entry) : endPos);
}
/**
* Handles moving the table index cursor in a given direction. Separates
* cursor logic from value storage.
*/
private abstract class IndexDirHandler extends DirHandler {
public abstract Index.Entry getAnotherEntry()
throws IOException;
}
/**
* Handles moving the table index cursor forward.
*/
private final class ForwardIndexDirHandler extends IndexDirHandler {
@Override
public Position getBeginningPosition() {
return getFirstPosition();
}
@Override
public Position getEndPosition() {
return getLastPosition();
}
@Override
public Index.Entry getAnotherEntry() throws IOException {
return _entryCursor.getNextEntry();
}
}
/**
* Handles moving the table index cursor backward.
*/
private final class ReverseIndexDirHandler extends IndexDirHandler {
@Override
public Position getBeginningPosition() {
return getLastPosition();
}
@Override
public Position getEndPosition() {
return getFirstPosition();
}
@Override
public Index.Entry getAnotherEntry() throws IOException {
return _entryCursor.getPreviousEntry();
}
}
}
/**
* Identifier for a cursor. Will be equal to any other cursor of the same
* type for the same table. Primarily used to check the validity of a
* Savepoint.
*/
public static final class Id
{
private final String _tableName;
private final String _indexName;
private Id(Table table, Index index) {
_tableName = table.getName();
_indexName = ((index != null) ? index.getName() : null);
}
@Override
public int hashCode() {
return _tableName.hashCode();
}
@Override
public boolean equals(Object o) {
return((this == o) ||
((o != null) && (getClass() == o.getClass()) &&
ObjectUtils.equals(_tableName, ((Id)o)._tableName) &&
ObjectUtils.equals(_indexName, ((Id)o)._indexName)));
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + _tableName + ":" + _indexName;
}
}
/**
* Value object which represents a complete save state of the cursor.
*/
public static final class Savepoint
{
private final Id _cursorId;
private final Position _curPos;
private final Position _prevPos;
private Savepoint(Id cursorId, Position curPos, Position prevPos) {
_cursorId = cursorId;
_curPos = curPos;
_prevPos = prevPos;
}
public Id getCursorId() {
return _cursorId;
}
public Position getCurrentPosition() {
return _curPos;
}
private Position getPreviousPosition() {
return _prevPos;
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + _cursorId + " CurPosition " +
_curPos + ", PrevPosition " + _prevPos;
}
}
/**
* Value object which maintains the current position of the cursor.
*/
public static abstract class Position
{
protected Position() {
}
@Override
public final int hashCode() {
return getRowId().hashCode();
}
@Override
public final boolean equals(Object o) {
return((this == o) ||
((o != null) && (getClass() == o.getClass()) && equalsImpl(o)));
}
/**
* Returns the unique RowId of the position of the cursor.
*/
public abstract RowId getRowId();
/**
* Returns {@code true} if the subclass specific info in a Position is
* equal, {@code false} otherwise.
* @param o object being tested for equality, guaranteed to be the same
* class as this object
*/
protected abstract boolean equalsImpl(Object o);
}
/**
* Value object which maintains the current position of a TableScanCursor.
*/
private static final class ScanPosition extends Position
{
private final RowId _rowId;
private ScanPosition(RowId rowId) {
_rowId = rowId;
}
@Override
public RowId getRowId() {
return _rowId;
}
@Override
protected boolean equalsImpl(Object o) {
return getRowId().equals(((ScanPosition)o).getRowId());
}
@Override
public String toString() {
return "RowId = " + getRowId();
}
}
/**
* Value object which maintains the current position of an IndexCursor.
*/
private static final class IndexPosition extends Position
{
private final Index.Entry _entry;
private IndexPosition(Index.Entry entry) {
_entry = entry;
}
@Override
public RowId getRowId() {
return getEntry().getRowId();
}
public Index.Entry getEntry() {
return _entry;
}
@Override
protected boolean equalsImpl(Object o) {
return getEntry().equals(((IndexPosition)o).getEntry());
}
@Override
public String toString() {
return "Entry = " + getEntry();
}
}
}
|