You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CursorImpl.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. /*
  2. Copyright (c) 2007 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.IOException;
  15. import java.util.Arrays;
  16. import java.util.Collection;
  17. import java.util.Iterator;
  18. import java.util.Map;
  19. import java.util.NoSuchElementException;
  20. import com.healthmarketscience.jackcess.Column;
  21. import com.healthmarketscience.jackcess.Cursor;
  22. import com.healthmarketscience.jackcess.CursorBuilder;
  23. import com.healthmarketscience.jackcess.Row;
  24. import com.healthmarketscience.jackcess.RowId;
  25. import com.healthmarketscience.jackcess.RuntimeIOException;
  26. import com.healthmarketscience.jackcess.impl.TableImpl.RowState;
  27. import com.healthmarketscience.jackcess.util.ColumnMatcher;
  28. import com.healthmarketscience.jackcess.util.ErrorHandler;
  29. import com.healthmarketscience.jackcess.util.IterableBuilder;
  30. import com.healthmarketscience.jackcess.util.SimpleColumnMatcher;
  31. import org.apache.commons.logging.Log;
  32. import org.apache.commons.logging.LogFactory;
  33. /**
  34. * Manages iteration for a Table. Different cursors provide different methods
  35. * of traversing a table. Cursors should be fairly robust in the face of
  36. * table modification during traversal (although depending on how the table is
  37. * traversed, row updates may or may not be seen). Multiple cursors may
  38. * traverse the same table simultaneously.
  39. * <p>
  40. * The Cursor provides a variety of static utility methods to construct
  41. * cursors with given characteristics or easily search for specific values.
  42. * For even friendlier and more flexible construction, see
  43. * {@link CursorBuilder}.
  44. * <p>
  45. * Is not thread-safe.
  46. *
  47. * @author James Ahlborn
  48. */
  49. public abstract class CursorImpl implements Cursor
  50. {
  51. private static final Log LOG = LogFactory.getLog(CursorImpl.class);
  52. /** boolean value indicating forward movement */
  53. public static final boolean MOVE_FORWARD = true;
  54. /** boolean value indicating reverse movement */
  55. public static final boolean MOVE_REVERSE = false;
  56. /** identifier for this cursor */
  57. private final IdImpl _id;
  58. /** owning table */
  59. private final TableImpl _table;
  60. /** State used for reading the table rows */
  61. private final RowState _rowState;
  62. /** the first (exclusive) row id for this cursor */
  63. private final PositionImpl _firstPos;
  64. /** the last (exclusive) row id for this cursor */
  65. private final PositionImpl _lastPos;
  66. /** the previous row */
  67. protected PositionImpl _prevPos;
  68. /** the current row */
  69. protected PositionImpl _curPos;
  70. /** ColumnMatcher to be used when matching column values */
  71. protected ColumnMatcher _columnMatcher = SimpleColumnMatcher.INSTANCE;
  72. protected CursorImpl(IdImpl id, TableImpl table, PositionImpl firstPos,
  73. PositionImpl lastPos) {
  74. _id = id;
  75. _table = table;
  76. _rowState = _table.createRowState();
  77. _firstPos = firstPos;
  78. _lastPos = lastPos;
  79. _curPos = firstPos;
  80. _prevPos = firstPos;
  81. }
  82. /**
  83. * Creates a normal, un-indexed cursor for the given table.
  84. * @param table the table over which this cursor will traverse
  85. */
  86. public static CursorImpl createCursor(TableImpl table) {
  87. return new TableScanCursor(table);
  88. }
  89. public RowState getRowState() {
  90. return _rowState;
  91. }
  92. public IdImpl getId() {
  93. return _id;
  94. }
  95. public TableImpl getTable() {
  96. return _table;
  97. }
  98. public JetFormat getFormat() {
  99. return getTable().getFormat();
  100. }
  101. public PageChannel getPageChannel() {
  102. return getTable().getPageChannel();
  103. }
  104. public ErrorHandler getErrorHandler() {
  105. return _rowState.getErrorHandler();
  106. }
  107. public void setErrorHandler(ErrorHandler newErrorHandler) {
  108. _rowState.setErrorHandler(newErrorHandler);
  109. }
  110. public ColumnMatcher getColumnMatcher() {
  111. return _columnMatcher;
  112. }
  113. public void setColumnMatcher(ColumnMatcher columnMatcher) {
  114. if(columnMatcher == null) {
  115. columnMatcher = getDefaultColumnMatcher();
  116. }
  117. _columnMatcher = columnMatcher;
  118. }
  119. /**
  120. * Returns the default ColumnMatcher for this Cursor.
  121. */
  122. protected ColumnMatcher getDefaultColumnMatcher() {
  123. return SimpleColumnMatcher.INSTANCE;
  124. }
  125. public SavepointImpl getSavepoint() {
  126. return new SavepointImpl(_id, _curPos, _prevPos);
  127. }
  128. public void restoreSavepoint(Savepoint savepoint)
  129. throws IOException
  130. {
  131. restoreSavepoint((SavepointImpl)savepoint);
  132. }
  133. public void restoreSavepoint(SavepointImpl savepoint)
  134. throws IOException
  135. {
  136. if(!_id.equals(savepoint.getCursorId())) {
  137. throw new IllegalArgumentException(
  138. "Savepoint " + savepoint + " is not valid for this cursor with id "
  139. + _id);
  140. }
  141. restorePosition(savepoint.getCurrentPosition(),
  142. savepoint.getPreviousPosition());
  143. }
  144. /**
  145. * Returns the first row id (exclusive) as defined by this cursor.
  146. */
  147. protected PositionImpl getFirstPosition() {
  148. return _firstPos;
  149. }
  150. /**
  151. * Returns the last row id (exclusive) as defined by this cursor.
  152. */
  153. protected PositionImpl getLastPosition() {
  154. return _lastPos;
  155. }
  156. public void reset() {
  157. beforeFirst();
  158. }
  159. public void beforeFirst() {
  160. reset(MOVE_FORWARD);
  161. }
  162. public void afterLast() {
  163. reset(MOVE_REVERSE);
  164. }
  165. public boolean isBeforeFirst() throws IOException {
  166. return isAtBeginning(MOVE_FORWARD);
  167. }
  168. public boolean isAfterLast() throws IOException {
  169. return isAtBeginning(MOVE_REVERSE);
  170. }
  171. protected boolean isAtBeginning(boolean moveForward) throws IOException {
  172. if(getDirHandler(moveForward).getBeginningPosition().equals(_curPos)) {
  173. return !recheckPosition(!moveForward);
  174. }
  175. return false;
  176. }
  177. public boolean isCurrentRowDeleted() throws IOException
  178. {
  179. // we need to ensure that the "deleted" flag has been read for this row
  180. // (or re-read if the table has been recently modified)
  181. TableImpl.positionAtRowData(_rowState, _curPos.getRowId());
  182. return _rowState.isDeleted();
  183. }
  184. /**
  185. * Resets this cursor for traversing the given direction.
  186. */
  187. protected void reset(boolean moveForward) {
  188. _curPos = getDirHandler(moveForward).getBeginningPosition();
  189. _prevPos = _curPos;
  190. _rowState.reset();
  191. }
  192. public Iterator<Row> iterator() {
  193. return new RowIterator(null, true, MOVE_FORWARD);
  194. }
  195. public IterableBuilder newIterable() {
  196. return new IterableBuilder(this);
  197. }
  198. public Iterator<Row> iterator(IterableBuilder iterBuilder) {
  199. switch(iterBuilder.getType()) {
  200. case SIMPLE:
  201. return new RowIterator(iterBuilder.getColumnNames(),
  202. iterBuilder.isReset(), iterBuilder.isForward());
  203. case COLUMN_MATCH: {
  204. @SuppressWarnings("unchecked")
  205. Map.Entry<Column,Object> matchPattern = (Map.Entry<Column,Object>)
  206. iterBuilder.getMatchPattern();
  207. return new ColumnMatchIterator(
  208. iterBuilder.getColumnNames(), (ColumnImpl)matchPattern.getKey(),
  209. matchPattern.getValue(), iterBuilder.isReset(),
  210. iterBuilder.isForward(), iterBuilder.getColumnMatcher());
  211. }
  212. case ROW_MATCH: {
  213. @SuppressWarnings("unchecked")
  214. Map<String,?> matchPattern = (Map<String,?>)
  215. iterBuilder.getMatchPattern();
  216. return new RowMatchIterator(
  217. iterBuilder.getColumnNames(), matchPattern,iterBuilder.isReset(),
  218. iterBuilder.isForward(), iterBuilder.getColumnMatcher());
  219. }
  220. default:
  221. throw new RuntimeException("unknown match type " + iterBuilder.getType());
  222. }
  223. }
  224. public void deleteCurrentRow() throws IOException {
  225. _table.deleteRow(_rowState, _curPos.getRowId());
  226. }
  227. public Object[] updateCurrentRow(Object... row) throws IOException {
  228. return _table.updateRow(_rowState, _curPos.getRowId(), row);
  229. }
  230. public <M extends Map<String,Object>> M updateCurrentRowFromMap(M row)
  231. throws IOException
  232. {
  233. return _table.updateRowFromMap(_rowState, _curPos.getRowId(), row);
  234. }
  235. public Row getNextRow() throws IOException {
  236. return getNextRow(null);
  237. }
  238. public Row getNextRow(Collection<String> columnNames)
  239. throws IOException
  240. {
  241. return getAnotherRow(columnNames, MOVE_FORWARD);
  242. }
  243. public Row getPreviousRow() throws IOException {
  244. return getPreviousRow(null);
  245. }
  246. public Row getPreviousRow(Collection<String> columnNames)
  247. throws IOException
  248. {
  249. return getAnotherRow(columnNames, MOVE_REVERSE);
  250. }
  251. /**
  252. * Moves to another row in the table based on the given direction and
  253. * returns it.
  254. * @param columnNames Only column names in this collection will be returned
  255. * @return another row in this table (Column name -> Column value), where
  256. * "next" may be backwards if moveForward is {@code false}, or
  257. * {@code null} if there is not another row in the given direction.
  258. */
  259. private Row getAnotherRow(Collection<String> columnNames,
  260. boolean moveForward)
  261. throws IOException
  262. {
  263. if(moveToAnotherRow(moveForward)) {
  264. return getCurrentRow(columnNames);
  265. }
  266. return null;
  267. }
  268. public boolean moveToNextRow() throws IOException
  269. {
  270. return moveToAnotherRow(MOVE_FORWARD);
  271. }
  272. public boolean moveToPreviousRow() throws IOException
  273. {
  274. return moveToAnotherRow(MOVE_REVERSE);
  275. }
  276. /**
  277. * Moves to another row in the given direction as defined by this cursor.
  278. * @return {@code true} if another valid row was found in the given
  279. * direction, {@code false} otherwise
  280. */
  281. protected boolean moveToAnotherRow(boolean moveForward)
  282. throws IOException
  283. {
  284. if(_curPos.equals(getDirHandler(moveForward).getEndPosition())) {
  285. // already at end, make sure nothing has changed
  286. return recheckPosition(moveForward);
  287. }
  288. return moveToAnotherRowImpl(moveForward);
  289. }
  290. /**
  291. * Restores a current position for the cursor (current position becomes
  292. * previous position).
  293. */
  294. protected void restorePosition(PositionImpl curPos)
  295. throws IOException
  296. {
  297. restorePosition(curPos, _curPos);
  298. }
  299. /**
  300. * Restores a current and previous position for the cursor if the given
  301. * positions are different from the current positions.
  302. */
  303. protected final void restorePosition(PositionImpl curPos,
  304. PositionImpl prevPos)
  305. throws IOException
  306. {
  307. if(!curPos.equals(_curPos) || !prevPos.equals(_prevPos)) {
  308. restorePositionImpl(curPos, prevPos);
  309. }
  310. }
  311. /**
  312. * Restores a current and previous position for the cursor.
  313. */
  314. protected void restorePositionImpl(PositionImpl curPos, PositionImpl prevPos)
  315. throws IOException
  316. {
  317. // make the current position previous, and the new position current
  318. _prevPos = _curPos;
  319. _curPos = curPos;
  320. _rowState.reset();
  321. }
  322. /**
  323. * Rechecks the current position if the underlying data structures have been
  324. * modified.
  325. * @return {@code true} if the cursor ended up in a new position,
  326. * {@code false} otherwise.
  327. */
  328. private boolean recheckPosition(boolean moveForward)
  329. throws IOException
  330. {
  331. if(isUpToDate()) {
  332. // nothing has changed
  333. return false;
  334. }
  335. // move the cursor back to the previous position
  336. restorePosition(_prevPos);
  337. return moveToAnotherRowImpl(moveForward);
  338. }
  339. /**
  340. * Does the grunt work of moving the cursor to another position in the given
  341. * direction.
  342. */
  343. private boolean moveToAnotherRowImpl(boolean moveForward)
  344. throws IOException
  345. {
  346. _rowState.reset();
  347. _prevPos = _curPos;
  348. _curPos = findAnotherPosition(_rowState, _curPos, moveForward);
  349. TableImpl.positionAtRowHeader(_rowState, _curPos.getRowId());
  350. return(!_curPos.equals(getDirHandler(moveForward).getEndPosition()));
  351. }
  352. public boolean findRow(RowId rowId) throws IOException
  353. {
  354. RowIdImpl rowIdImpl = (RowIdImpl)rowId;
  355. PositionImpl curPos = _curPos;
  356. PositionImpl prevPos = _prevPos;
  357. boolean found = false;
  358. try {
  359. reset(MOVE_FORWARD);
  360. if(TableImpl.positionAtRowHeader(_rowState, rowIdImpl) == null) {
  361. return false;
  362. }
  363. restorePosition(getRowPosition(rowIdImpl));
  364. if(!isCurrentRowValid()) {
  365. return false;
  366. }
  367. found = true;
  368. return true;
  369. } finally {
  370. if(!found) {
  371. try {
  372. restorePosition(curPos, prevPos);
  373. } catch(IOException e) {
  374. LOG.error("Failed restoring position", e);
  375. }
  376. }
  377. }
  378. }
  379. public boolean findFirstRow(Column columnPattern, Object valuePattern)
  380. throws IOException
  381. {
  382. return findFirstRow((ColumnImpl)columnPattern, valuePattern);
  383. }
  384. public boolean findFirstRow(ColumnImpl columnPattern, Object valuePattern)
  385. throws IOException
  386. {
  387. return findAnotherRow(columnPattern, valuePattern, true, MOVE_FORWARD,
  388. _columnMatcher,
  389. prepareSearchInfo(columnPattern, valuePattern));
  390. }
  391. public boolean findNextRow(Column columnPattern, Object valuePattern)
  392. throws IOException
  393. {
  394. return findNextRow((ColumnImpl)columnPattern, valuePattern);
  395. }
  396. public boolean findNextRow(ColumnImpl columnPattern, Object valuePattern)
  397. throws IOException
  398. {
  399. return findAnotherRow(columnPattern, valuePattern, false, MOVE_FORWARD,
  400. _columnMatcher,
  401. prepareSearchInfo(columnPattern, valuePattern));
  402. }
  403. protected boolean findAnotherRow(ColumnImpl columnPattern, Object valuePattern,
  404. boolean reset, boolean moveForward,
  405. ColumnMatcher columnMatcher, Object searchInfo)
  406. throws IOException
  407. {
  408. PositionImpl curPos = _curPos;
  409. PositionImpl prevPos = _prevPos;
  410. boolean found = false;
  411. try {
  412. if(reset) {
  413. reset(moveForward);
  414. }
  415. found = findAnotherRowImpl(columnPattern, valuePattern, moveForward,
  416. columnMatcher, searchInfo);
  417. return found;
  418. } finally {
  419. if(!found) {
  420. try {
  421. restorePosition(curPos, prevPos);
  422. } catch(IOException e) {
  423. LOG.error("Failed restoring position", e);
  424. }
  425. }
  426. }
  427. }
  428. public boolean findFirstRow(Map<String,?> rowPattern) throws IOException
  429. {
  430. return findAnotherRow(rowPattern, true, MOVE_FORWARD, _columnMatcher,
  431. prepareSearchInfo(rowPattern));
  432. }
  433. public boolean findNextRow(Map<String,?> rowPattern)
  434. throws IOException
  435. {
  436. return findAnotherRow(rowPattern, false, MOVE_FORWARD, _columnMatcher,
  437. prepareSearchInfo(rowPattern));
  438. }
  439. protected boolean findAnotherRow(Map<String,?> rowPattern, boolean reset,
  440. boolean moveForward,
  441. ColumnMatcher columnMatcher, Object searchInfo)
  442. throws IOException
  443. {
  444. PositionImpl curPos = _curPos;
  445. PositionImpl prevPos = _prevPos;
  446. boolean found = false;
  447. try {
  448. if(reset) {
  449. reset(moveForward);
  450. }
  451. found = findAnotherRowImpl(rowPattern, moveForward, columnMatcher,
  452. searchInfo);
  453. return found;
  454. } finally {
  455. if(!found) {
  456. try {
  457. restorePosition(curPos, prevPos);
  458. } catch(IOException e) {
  459. LOG.error("Failed restoring position", e);
  460. }
  461. }
  462. }
  463. }
  464. public boolean currentRowMatches(Column columnPattern, Object valuePattern)
  465. throws IOException
  466. {
  467. return currentRowMatches((ColumnImpl)columnPattern, valuePattern);
  468. }
  469. public boolean currentRowMatches(ColumnImpl columnPattern, Object valuePattern)
  470. throws IOException
  471. {
  472. return currentRowMatchesImpl(columnPattern, valuePattern, _columnMatcher);
  473. }
  474. protected boolean currentRowMatchesImpl(ColumnImpl columnPattern,
  475. Object valuePattern,
  476. ColumnMatcher columnMatcher)
  477. throws IOException
  478. {
  479. return columnMatcher.matches(getTable(), columnPattern.getName(),
  480. valuePattern,
  481. getCurrentRowValue(columnPattern));
  482. }
  483. public boolean currentRowMatches(Map<String,?> rowPattern)
  484. throws IOException
  485. {
  486. return currentRowMatchesImpl(rowPattern, _columnMatcher);
  487. }
  488. protected boolean currentRowMatchesImpl(Map<String,?> rowPattern,
  489. ColumnMatcher columnMatcher)
  490. throws IOException
  491. {
  492. Row row = getCurrentRow(rowPattern.keySet());
  493. if(rowPattern.size() != row.size()) {
  494. return false;
  495. }
  496. for(Map.Entry<String,Object> e : row.entrySet()) {
  497. String columnName = e.getKey();
  498. if(!columnMatcher.matches(getTable(), columnName,
  499. rowPattern.get(columnName), e.getValue())) {
  500. return false;
  501. }
  502. }
  503. return true;
  504. }
  505. /**
  506. * Moves to the next row (as defined by the cursor) where the given column
  507. * has the given value. Caller manages save/restore on failure.
  508. * <p>
  509. * Default implementation scans the table from beginning to end.
  510. *
  511. * @param columnPattern column from the table for this cursor which is being
  512. * matched by the valuePattern
  513. * @param valuePattern value which is equal to the corresponding value in
  514. * the matched row
  515. * @return {@code true} if a valid row was found with the given value,
  516. * {@code false} if no row was found
  517. */
  518. protected boolean findAnotherRowImpl(
  519. ColumnImpl columnPattern, Object valuePattern, boolean moveForward,
  520. ColumnMatcher columnMatcher, Object searchInfo)
  521. throws IOException
  522. {
  523. while(moveToAnotherRow(moveForward)) {
  524. if(currentRowMatchesImpl(columnPattern, valuePattern, columnMatcher)) {
  525. return true;
  526. }
  527. if(!keepSearching(columnMatcher, searchInfo)) {
  528. break;
  529. }
  530. }
  531. return false;
  532. }
  533. /**
  534. * Moves to the next row (as defined by the cursor) where the given columns
  535. * have the given values. Caller manages save/restore on failure.
  536. * <p>
  537. * Default implementation scans the table from beginning to end.
  538. *
  539. * @param rowPattern column names and values which must be equal to the
  540. * corresponding values in the matched row
  541. * @return {@code true} if a valid row was found with the given values,
  542. * {@code false} if no row was found
  543. */
  544. protected boolean findAnotherRowImpl(Map<String,?> rowPattern,
  545. boolean moveForward,
  546. ColumnMatcher columnMatcher,
  547. Object searchInfo)
  548. throws IOException
  549. {
  550. while(moveToAnotherRow(moveForward)) {
  551. if(currentRowMatchesImpl(rowPattern, columnMatcher)) {
  552. return true;
  553. }
  554. if(!keepSearching(columnMatcher, searchInfo)) {
  555. break;
  556. }
  557. }
  558. return false;
  559. }
  560. /**
  561. * Called before a search commences to allow for search specific data to be
  562. * generated (which is cached for re-use by the iterators).
  563. */
  564. protected Object prepareSearchInfo(ColumnImpl columnPattern, Object valuePattern)
  565. {
  566. return null;
  567. }
  568. /**
  569. * Called before a search commences to allow for search specific data to be
  570. * generated (which is cached for re-use by the iterators).
  571. */
  572. protected Object prepareSearchInfo(Map<String,?> rowPattern)
  573. {
  574. return null;
  575. }
  576. /**
  577. * Called by findAnotherRowImpl to determine if the search should continue
  578. * after finding a row which does not match the current pattern.
  579. */
  580. protected boolean keepSearching(ColumnMatcher columnMatcher,
  581. Object searchInfo)
  582. throws IOException
  583. {
  584. return true;
  585. }
  586. public int moveNextRows(int numRows) throws IOException
  587. {
  588. return moveSomeRows(numRows, MOVE_FORWARD);
  589. }
  590. public int movePreviousRows(int numRows) throws IOException
  591. {
  592. return moveSomeRows(numRows, MOVE_REVERSE);
  593. }
  594. /**
  595. * Moves as many rows as possible in the given direction up to the given
  596. * number of rows.
  597. * @return the number of rows moved.
  598. */
  599. private int moveSomeRows(int numRows, boolean moveForward)
  600. throws IOException
  601. {
  602. int numMovedRows = 0;
  603. while((numMovedRows < numRows) && moveToAnotherRow(moveForward)) {
  604. ++numMovedRows;
  605. }
  606. return numMovedRows;
  607. }
  608. public Row getCurrentRow() throws IOException
  609. {
  610. return getCurrentRow(null);
  611. }
  612. public Row getCurrentRow(Collection<String> columnNames)
  613. throws IOException
  614. {
  615. return _table.getRow(_rowState, _curPos.getRowId(), columnNames);
  616. }
  617. public Object getCurrentRowValue(Column column)
  618. throws IOException
  619. {
  620. return getCurrentRowValue((ColumnImpl)column);
  621. }
  622. public Object getCurrentRowValue(ColumnImpl column)
  623. throws IOException
  624. {
  625. return _table.getRowValue(_rowState, _curPos.getRowId(), column);
  626. }
  627. public void setCurrentRowValue(Column column, Object value)
  628. throws IOException
  629. {
  630. setCurrentRowValue((ColumnImpl)column, value);
  631. }
  632. public void setCurrentRowValue(ColumnImpl column, Object value)
  633. throws IOException
  634. {
  635. Object[] row = new Object[_table.getColumnCount()];
  636. Arrays.fill(row, Column.KEEP_VALUE);
  637. column.setRowValue(row, value);
  638. _table.updateRow(_rowState, _curPos.getRowId(), row);
  639. }
  640. /**
  641. * Returns {@code true} if this cursor is up-to-date with respect to the
  642. * relevant table and related table objects, {@code false} otherwise.
  643. */
  644. protected boolean isUpToDate() {
  645. return _rowState.isUpToDate();
  646. }
  647. /**
  648. * Returns {@code true} of the current row is valid, {@code false} otherwise.
  649. */
  650. protected boolean isCurrentRowValid() throws IOException {
  651. return(_curPos.getRowId().isValid() && !isCurrentRowDeleted() &&
  652. !isBeforeFirst() && !isAfterLast());
  653. }
  654. @Override
  655. public String toString() {
  656. return getClass().getSimpleName() + " CurPosition " + _curPos +
  657. ", PrevPosition " + _prevPos;
  658. }
  659. /**
  660. * Returns the appropriate position information for the given row (which is
  661. * the current row and is valid).
  662. */
  663. protected abstract PositionImpl getRowPosition(RowIdImpl rowId)
  664. throws IOException;
  665. /**
  666. * Finds the next non-deleted row after the given row (as defined by this
  667. * cursor) and returns the id of the row, where "next" may be backwards if
  668. * moveForward is {@code false}. If there are no more rows, the returned
  669. * rowId should equal the value returned by {@link #getLastPosition} if
  670. * moving forward and {@link #getFirstPosition} if moving backward.
  671. */
  672. protected abstract PositionImpl findAnotherPosition(RowState rowState,
  673. PositionImpl curPos,
  674. boolean moveForward)
  675. throws IOException;
  676. /**
  677. * Returns the DirHandler for the given movement direction.
  678. */
  679. protected abstract DirHandler getDirHandler(boolean moveForward);
  680. /**
  681. * Base implementation of iterator for this cursor, modifiable.
  682. */
  683. protected abstract class BaseIterator implements Iterator<Row>
  684. {
  685. protected final Collection<String> _columnNames;
  686. protected final boolean _moveForward;
  687. protected final ColumnMatcher _colMatcher;
  688. protected Boolean _hasNext;
  689. protected boolean _validRow;
  690. protected BaseIterator(Collection<String> columnNames,
  691. boolean reset, boolean moveForward,
  692. ColumnMatcher columnMatcher)
  693. {
  694. _columnNames = columnNames;
  695. _moveForward = moveForward;
  696. _colMatcher = ((columnMatcher != null) ? columnMatcher : _columnMatcher);
  697. try {
  698. if(reset) {
  699. reset(_moveForward);
  700. } else if(isCurrentRowValid()) {
  701. _hasNext = _validRow = true;
  702. }
  703. } catch(IOException e) {
  704. throw new RuntimeIOException(e);
  705. }
  706. }
  707. public boolean hasNext() {
  708. if(_hasNext == null) {
  709. try {
  710. _hasNext = findNext();
  711. _validRow = _hasNext;
  712. } catch(IOException e) {
  713. throw new RuntimeIOException(e);
  714. }
  715. }
  716. return _hasNext;
  717. }
  718. public Row next() {
  719. if(!hasNext()) {
  720. throw new NoSuchElementException();
  721. }
  722. try {
  723. Row rtn = getCurrentRow(_columnNames);
  724. _hasNext = null;
  725. return rtn;
  726. } catch(IOException e) {
  727. throw new RuntimeIOException(e);
  728. }
  729. }
  730. public void remove() {
  731. if(_validRow) {
  732. try {
  733. deleteCurrentRow();
  734. _validRow = false;
  735. } catch(IOException e) {
  736. throw new RuntimeIOException(e);
  737. }
  738. } else {
  739. throw new IllegalStateException("Not at valid row");
  740. }
  741. }
  742. protected abstract boolean findNext() throws IOException;
  743. }
  744. /**
  745. * Row iterator for this cursor, modifiable.
  746. */
  747. private final class RowIterator extends BaseIterator
  748. {
  749. private RowIterator(Collection<String> columnNames, boolean reset,
  750. boolean moveForward)
  751. {
  752. super(columnNames, reset, moveForward, null);
  753. }
  754. @Override
  755. protected boolean findNext() throws IOException {
  756. return moveToAnotherRow(_moveForward);
  757. }
  758. }
  759. /**
  760. * Row iterator for this cursor, modifiable.
  761. */
  762. private final class ColumnMatchIterator extends BaseIterator
  763. {
  764. private final ColumnImpl _columnPattern;
  765. private final Object _valuePattern;
  766. private final Object _searchInfo;
  767. private ColumnMatchIterator(Collection<String> columnNames,
  768. ColumnImpl columnPattern, Object valuePattern,
  769. boolean reset, boolean moveForward,
  770. ColumnMatcher columnMatcher)
  771. {
  772. super(columnNames, reset, moveForward, columnMatcher);
  773. _columnPattern = columnPattern;
  774. _valuePattern = valuePattern;
  775. _searchInfo = prepareSearchInfo(columnPattern, valuePattern);
  776. }
  777. @Override
  778. protected boolean findNext() throws IOException {
  779. return findAnotherRow(_columnPattern, _valuePattern, false, _moveForward,
  780. _colMatcher, _searchInfo);
  781. }
  782. }
  783. /**
  784. * Row iterator for this cursor, modifiable.
  785. */
  786. private final class RowMatchIterator extends BaseIterator
  787. {
  788. private final Map<String,?> _rowPattern;
  789. private final Object _searchInfo;
  790. private RowMatchIterator(Collection<String> columnNames,
  791. Map<String,?> rowPattern,
  792. boolean reset, boolean moveForward,
  793. ColumnMatcher columnMatcher)
  794. {
  795. super(columnNames, reset, moveForward, columnMatcher);
  796. _rowPattern = rowPattern;
  797. _searchInfo = prepareSearchInfo(rowPattern);
  798. }
  799. @Override
  800. protected boolean findNext() throws IOException {
  801. return findAnotherRow(_rowPattern, false, _moveForward, _colMatcher,
  802. _searchInfo);
  803. }
  804. }
  805. /**
  806. * Handles moving the cursor in a given direction. Separates cursor
  807. * logic from value storage.
  808. */
  809. protected abstract class DirHandler
  810. {
  811. public abstract PositionImpl getBeginningPosition();
  812. public abstract PositionImpl getEndPosition();
  813. }
  814. /**
  815. * Identifier for a cursor. Will be equal to any other cursor of the same
  816. * type for the same table. Primarily used to check the validity of a
  817. * Savepoint.
  818. */
  819. protected static final class IdImpl implements Id
  820. {
  821. private final int _tablePageNumber;
  822. private final int _indexNumber;
  823. protected IdImpl(TableImpl table, IndexImpl index) {
  824. _tablePageNumber = table.getTableDefPageNumber();
  825. _indexNumber = ((index != null) ? index.getIndexNumber() : -1);
  826. }
  827. @Override
  828. public int hashCode() {
  829. return _tablePageNumber;
  830. }
  831. @Override
  832. public boolean equals(Object o) {
  833. return((this == o) ||
  834. ((o != null) && (getClass() == o.getClass()) &&
  835. (_tablePageNumber == ((IdImpl)o)._tablePageNumber) &&
  836. (_indexNumber == ((IdImpl)o)._indexNumber)));
  837. }
  838. @Override
  839. public String toString() {
  840. return getClass().getSimpleName() + " " + _tablePageNumber + ":" + _indexNumber;
  841. }
  842. }
  843. /**
  844. * Value object which maintains the current position of the cursor.
  845. */
  846. protected static abstract class PositionImpl implements Position
  847. {
  848. protected PositionImpl() {
  849. }
  850. @Override
  851. public final int hashCode() {
  852. return getRowId().hashCode();
  853. }
  854. @Override
  855. public final boolean equals(Object o) {
  856. return((this == o) ||
  857. ((o != null) && (getClass() == o.getClass()) && equalsImpl(o)));
  858. }
  859. /**
  860. * Returns the unique RowId of the position of the cursor.
  861. */
  862. public abstract RowIdImpl getRowId();
  863. /**
  864. * Returns {@code true} if the subclass specific info in a Position is
  865. * equal, {@code false} otherwise.
  866. * @param o object being tested for equality, guaranteed to be the same
  867. * class as this object
  868. */
  869. protected abstract boolean equalsImpl(Object o);
  870. }
  871. /**
  872. * Value object which represents a complete save state of the cursor.
  873. */
  874. protected static final class SavepointImpl implements Savepoint
  875. {
  876. private final IdImpl _cursorId;
  877. private final PositionImpl _curPos;
  878. private final PositionImpl _prevPos;
  879. private SavepointImpl(IdImpl cursorId, PositionImpl curPos,
  880. PositionImpl prevPos) {
  881. _cursorId = cursorId;
  882. _curPos = curPos;
  883. _prevPos = prevPos;
  884. }
  885. public IdImpl getCursorId() {
  886. return _cursorId;
  887. }
  888. public PositionImpl getCurrentPosition() {
  889. return _curPos;
  890. }
  891. private PositionImpl getPreviousPosition() {
  892. return _prevPos;
  893. }
  894. @Override
  895. public String toString() {
  896. return getClass().getSimpleName() + " " + _cursorId + " CurPosition " +
  897. _curPos + ", PrevPosition " + _prevPos;
  898. }
  899. }
  900. }