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 31KB

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