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.

IndexCursorImpl.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. Copyright (c) 2011 James Ahlborn
  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.Collection;
  16. import java.util.HashSet;
  17. import java.util.Iterator;
  18. import java.util.LinkedHashMap;
  19. import java.util.Map;
  20. import java.util.Set;
  21. import com.healthmarketscience.jackcess.Index;
  22. import com.healthmarketscience.jackcess.IndexCursor;
  23. import com.healthmarketscience.jackcess.Row;
  24. import com.healthmarketscience.jackcess.RuntimeIOException;
  25. import com.healthmarketscience.jackcess.impl.TableImpl.RowState;
  26. import com.healthmarketscience.jackcess.util.CaseInsensitiveColumnMatcher;
  27. import com.healthmarketscience.jackcess.util.ColumnMatcher;
  28. import com.healthmarketscience.jackcess.util.EntryIterableBuilder;
  29. import com.healthmarketscience.jackcess.util.SimpleColumnMatcher;
  30. import org.apache.commons.logging.Log;
  31. import org.apache.commons.logging.LogFactory;
  32. /**
  33. * Cursor backed by an index with extended traversal options.
  34. *
  35. * @author James Ahlborn
  36. */
  37. public class IndexCursorImpl extends CursorImpl implements IndexCursor
  38. {
  39. private static final Log LOG = LogFactory.getLog(IndexCursorImpl.class);
  40. /** IndexDirHandler for forward traversal */
  41. private final IndexDirHandler _forwardDirHandler =
  42. new ForwardIndexDirHandler();
  43. /** IndexDirHandler for backward traversal */
  44. private final IndexDirHandler _reverseDirHandler =
  45. new ReverseIndexDirHandler();
  46. /** logical index which this cursor is using */
  47. private final IndexImpl _index;
  48. /** Cursor over the entries of the relevant index */
  49. private final IndexData.EntryCursor _entryCursor;
  50. /** column names for the index entry columns */
  51. private Set<String> _indexEntryPattern;
  52. private IndexCursorImpl(TableImpl table, IndexImpl index,
  53. IndexData.EntryCursor entryCursor)
  54. throws IOException
  55. {
  56. super(new IdImpl(table, index), table,
  57. new IndexPosition(entryCursor.getFirstEntry()),
  58. new IndexPosition(entryCursor.getLastEntry()));
  59. _index = index;
  60. _index.initialize();
  61. _entryCursor = entryCursor;
  62. }
  63. /**
  64. * Creates an indexed cursor for the given table, narrowed to the given
  65. * range.
  66. * <p>
  67. * Note, index based table traversal may not include all rows, as certain
  68. * types of indexes do not include all entries (namely, some indexes ignore
  69. * null entries, see {@link Index#shouldIgnoreNulls}).
  70. *
  71. * @param table the table over which this cursor will traverse
  72. * @param index index for the table which will define traversal order as
  73. * well as enhance certain lookups
  74. * @param startRow the first row of data for the cursor, or {@code null} for
  75. * the first entry
  76. * @param startInclusive whether or not startRow is inclusive or exclusive
  77. * @param endRow the last row of data for the cursor, or {@code null} for
  78. * the last entry
  79. * @param endInclusive whether or not endRow is inclusive or exclusive
  80. */
  81. public static IndexCursorImpl createCursor(TableImpl table, IndexImpl index,
  82. Object[] startRow,
  83. boolean startInclusive,
  84. Object[] endRow,
  85. boolean endInclusive)
  86. throws IOException
  87. {
  88. if(table != index.getTable()) {
  89. throw new IllegalArgumentException(
  90. "Given index is not for given table: " + index + ", " + table);
  91. }
  92. if(!table.getFormat().INDEXES_SUPPORTED) {
  93. throw new IllegalArgumentException(
  94. "JetFormat " + table.getFormat() +
  95. " does not currently support index lookups");
  96. }
  97. if(index.getIndexData().getUnsupportedReason() != null) {
  98. throw new IllegalArgumentException(
  99. "Given index " + index +
  100. " is not usable for indexed lookups due to " +
  101. index.getIndexData().getUnsupportedReason());
  102. }
  103. IndexCursorImpl cursor = new IndexCursorImpl(
  104. table, index, index.cursor(startRow, startInclusive,
  105. endRow, endInclusive));
  106. // init the column matcher appropriately for the index type
  107. cursor.setColumnMatcher(null);
  108. return cursor;
  109. }
  110. private Set<String> getIndexEntryPattern()
  111. {
  112. if(_indexEntryPattern == null) {
  113. // init our set of index column names
  114. _indexEntryPattern = new HashSet<String>();
  115. for(IndexData.ColumnDescriptor col : getIndex().getColumns()) {
  116. _indexEntryPattern.add(col.getName());
  117. }
  118. }
  119. return _indexEntryPattern;
  120. }
  121. public IndexImpl getIndex() {
  122. return _index;
  123. }
  124. public Row findRowByEntry(Object... entryValues)
  125. throws IOException
  126. {
  127. if(findFirstRowByEntry(entryValues)) {
  128. return getCurrentRow();
  129. }
  130. return null;
  131. }
  132. public boolean findFirstRowByEntry(Object... entryValues)
  133. throws IOException
  134. {
  135. PositionImpl curPos = _curPos;
  136. PositionImpl prevPos = _prevPos;
  137. boolean found = false;
  138. try {
  139. found = findFirstRowByEntryImpl(toRowValues(entryValues), true,
  140. _columnMatcher);
  141. return found;
  142. } finally {
  143. if(!found) {
  144. try {
  145. restorePosition(curPos, prevPos);
  146. } catch(IOException e) {
  147. LOG.error("Failed restoring position", e);
  148. }
  149. }
  150. }
  151. }
  152. public void findClosestRowByEntry(Object... entryValues)
  153. throws IOException
  154. {
  155. PositionImpl curPos = _curPos;
  156. PositionImpl prevPos = _prevPos;
  157. boolean found = false;
  158. try {
  159. findFirstRowByEntryImpl(toRowValues(entryValues), false,
  160. _columnMatcher);
  161. found = true;
  162. } finally {
  163. if(!found) {
  164. try {
  165. restorePosition(curPos, prevPos);
  166. } catch(IOException e) {
  167. LOG.error("Failed restoring position", e);
  168. }
  169. }
  170. }
  171. }
  172. public boolean currentRowMatchesEntry(Object... entryValues)
  173. throws IOException
  174. {
  175. return currentRowMatchesEntryImpl(toRowValues(entryValues), _columnMatcher);
  176. }
  177. public EntryIterableBuilder newEntryIterable(Object... entryValues) {
  178. return new EntryIterableBuilder(this, entryValues);
  179. }
  180. public Iterator<Row> entryIterator(EntryIterableBuilder iterBuilder) {
  181. return new EntryIterator(iterBuilder.getColumnNames(),
  182. toRowValues(iterBuilder.getEntryValues()),
  183. iterBuilder.getColumnMatcher());
  184. }
  185. @Override
  186. protected IndexDirHandler getDirHandler(boolean moveForward) {
  187. return (moveForward ? _forwardDirHandler : _reverseDirHandler);
  188. }
  189. @Override
  190. protected boolean isUpToDate() {
  191. return(super.isUpToDate() && _entryCursor.isUpToDate());
  192. }
  193. @Override
  194. protected void reset(boolean moveForward) {
  195. _entryCursor.reset(moveForward);
  196. super.reset(moveForward);
  197. }
  198. @Override
  199. protected void restorePositionImpl(PositionImpl curPos, PositionImpl prevPos)
  200. throws IOException
  201. {
  202. if(!(curPos instanceof IndexPosition) ||
  203. !(prevPos instanceof IndexPosition)) {
  204. throw new IllegalArgumentException(
  205. "Restored positions must be index positions");
  206. }
  207. _entryCursor.restorePosition(((IndexPosition)curPos).getEntry(),
  208. ((IndexPosition)prevPos).getEntry());
  209. super.restorePositionImpl(curPos, prevPos);
  210. }
  211. @Override
  212. protected PositionImpl getRowPosition(RowIdImpl rowId) throws IOException
  213. {
  214. // we need to get the index entry which corresponds with this row
  215. Row row = getTable().getRow(getRowState(), rowId, getIndexEntryPattern());
  216. _entryCursor.beforeEntry(getTable().asRow(row));
  217. return new IndexPosition(_entryCursor.getNextEntry());
  218. }
  219. @Override
  220. protected boolean findAnotherRowImpl(
  221. ColumnImpl columnPattern, Object valuePattern, boolean moveForward,
  222. ColumnMatcher columnMatcher, Object searchInfo)
  223. throws IOException
  224. {
  225. Object[] rowValues = (Object[])searchInfo;
  226. if((rowValues == null) || !isAtBeginning(moveForward)) {
  227. // use the default table scan if we don't have index data or we are
  228. // mid-cursor
  229. return super.findAnotherRowImpl(columnPattern, valuePattern, moveForward,
  230. columnMatcher, rowValues);
  231. }
  232. // sweet, we can use our index
  233. if(!findPotentialRow(rowValues, true)) {
  234. return false;
  235. }
  236. // either we found a row with the given value, or none exist in the
  237. // table
  238. return currentRowMatchesImpl(columnPattern, valuePattern, columnMatcher);
  239. }
  240. /**
  241. * Moves to the first row (as defined by the cursor) where the index entries
  242. * match the given values. Caller manages save/restore on failure.
  243. *
  244. * @param rowValues the column values built from the index column values
  245. * @param requireMatch whether or not an exact match is found
  246. * @return {@code true} if a valid row was found with the given values,
  247. * {@code false} if no row was found
  248. */
  249. protected boolean findFirstRowByEntryImpl(Object[] rowValues,
  250. boolean requireMatch,
  251. ColumnMatcher columnMatcher)
  252. throws IOException
  253. {
  254. if(!findPotentialRow(rowValues, requireMatch)) {
  255. return false;
  256. } else if(!requireMatch) {
  257. // nothing more to do, we have moved to the closest row
  258. return true;
  259. }
  260. return currentRowMatchesEntryImpl(rowValues, columnMatcher);
  261. }
  262. @Override
  263. protected boolean findAnotherRowImpl(
  264. Map<String,?> rowPattern, boolean moveForward,
  265. ColumnMatcher columnMatcher, Object searchInfo)
  266. throws IOException
  267. {
  268. Object[] rowValues = (Object[])searchInfo;
  269. if((rowValues == null) || !isAtBeginning(moveForward)) {
  270. // use the default table scan if we don't have index data or we are
  271. // mid-cursor
  272. return super.findAnotherRowImpl(rowPattern, moveForward, columnMatcher,
  273. rowValues);
  274. }
  275. // sweet, we can use our index
  276. if(!findPotentialRow(rowValues, true)) {
  277. // at end of index, no potential matches
  278. return false;
  279. }
  280. // find actual matching row
  281. IndexData indexData = _entryCursor.getIndexData();
  282. Map<String,?> indexRowPattern = null;
  283. if(rowPattern.size() == indexData.getColumns().size()) {
  284. // the rowPattern matches our index columns exactly, so we can
  285. // streamline our testing below
  286. indexRowPattern = rowPattern;
  287. } else {
  288. // the rowPattern has more columns than just the index, so we need to
  289. // do more work when testing below
  290. Map<String,Object> tmpRowPattern = new LinkedHashMap<String,Object>();
  291. indexRowPattern = tmpRowPattern;
  292. for(IndexData.ColumnDescriptor idxCol : indexData.getColumns()) {
  293. tmpRowPattern.put(idxCol.getName(), rowValues[idxCol.getColumnIndex()]);
  294. }
  295. }
  296. // there may be multiple columns which fit the pattern subset used by
  297. // the index, so we need to keep checking until our index values no
  298. // longer match
  299. do {
  300. if(!currentRowMatchesImpl(indexRowPattern, columnMatcher)) {
  301. // there are no more rows which could possibly match
  302. break;
  303. }
  304. // note, if rowPattern == indexRowPattern, no need to do an extra
  305. // comparison with the current row
  306. if((rowPattern == indexRowPattern) ||
  307. currentRowMatchesImpl(rowPattern, columnMatcher)) {
  308. // found it!
  309. return true;
  310. }
  311. } while(moveToAnotherRow(moveForward));
  312. // none of the potential rows matched
  313. return false;
  314. }
  315. private boolean currentRowMatchesEntryImpl(Object[] rowValues,
  316. ColumnMatcher columnMatcher)
  317. throws IOException
  318. {
  319. // check the next row to see if it actually matches
  320. Row row = getCurrentRow(getIndexEntryPattern());
  321. for(IndexData.ColumnDescriptor col : getIndex().getColumns()) {
  322. String columnName = col.getName();
  323. Object patValue = rowValues[col.getColumnIndex()];
  324. Object rowValue = row.get(columnName);
  325. if(!columnMatcher.matches(getTable(), columnName, patValue, rowValue)) {
  326. return false;
  327. }
  328. }
  329. return true;
  330. }
  331. private boolean findPotentialRow(Object[] rowValues, boolean requireMatch)
  332. throws IOException
  333. {
  334. _entryCursor.beforeEntry(rowValues);
  335. IndexData.Entry startEntry = _entryCursor.getNextEntry();
  336. if(requireMatch && !startEntry.getRowId().isValid()) {
  337. // at end of index, no potential matches
  338. return false;
  339. }
  340. // move to position and check it out
  341. restorePosition(new IndexPosition(startEntry));
  342. return true;
  343. }
  344. @Override
  345. protected Object prepareSearchInfo(ColumnImpl columnPattern, Object valuePattern)
  346. {
  347. // attempt to generate a lookup row for this index
  348. return _entryCursor.getIndexData().constructIndexRow(
  349. columnPattern.getName(), valuePattern);
  350. }
  351. @Override
  352. protected Object prepareSearchInfo(Map<String,?> rowPattern)
  353. {
  354. // attempt to generate a lookup row for this index
  355. return _entryCursor.getIndexData().constructIndexRow(rowPattern);
  356. }
  357. @Override
  358. protected boolean keepSearching(ColumnMatcher columnMatcher,
  359. Object searchInfo)
  360. throws IOException
  361. {
  362. if(searchInfo instanceof Object[]) {
  363. // if we have a lookup row for this index, then we only need to continue
  364. // searching while we are looking at rows which match the index lookup
  365. // value(s). once we move past those rows, no other rows could possibly
  366. // match.
  367. return currentRowMatchesEntryImpl((Object[])searchInfo, columnMatcher);
  368. }
  369. // we are doing a full table scan
  370. return true;
  371. }
  372. private Object[] toRowValues(Object[] entryValues)
  373. {
  374. return _entryCursor.getIndexData().constructIndexRowFromEntry(entryValues);
  375. }
  376. @Override
  377. protected PositionImpl findAnotherPosition(
  378. RowState rowState, PositionImpl curPos, boolean moveForward)
  379. throws IOException
  380. {
  381. IndexDirHandler handler = getDirHandler(moveForward);
  382. IndexPosition endPos = (IndexPosition)handler.getEndPosition();
  383. IndexData.Entry entry = handler.getAnotherEntry();
  384. return ((!entry.equals(endPos.getEntry())) ?
  385. new IndexPosition(entry) : endPos);
  386. }
  387. @Override
  388. protected ColumnMatcher getDefaultColumnMatcher() {
  389. if(getIndex().isUnique()) {
  390. // text indexes are case-insensitive, therefore we should always use a
  391. // case-insensitive matcher for unique indexes.
  392. return CaseInsensitiveColumnMatcher.INSTANCE;
  393. }
  394. return SimpleColumnMatcher.INSTANCE;
  395. }
  396. /**
  397. * Handles moving the table index cursor in a given direction. Separates
  398. * cursor logic from value storage.
  399. */
  400. private abstract class IndexDirHandler extends DirHandler {
  401. public abstract IndexData.Entry getAnotherEntry()
  402. throws IOException;
  403. }
  404. /**
  405. * Handles moving the table index cursor forward.
  406. */
  407. private final class ForwardIndexDirHandler extends IndexDirHandler {
  408. @Override
  409. public PositionImpl getBeginningPosition() {
  410. return getFirstPosition();
  411. }
  412. @Override
  413. public PositionImpl getEndPosition() {
  414. return getLastPosition();
  415. }
  416. @Override
  417. public IndexData.Entry getAnotherEntry() throws IOException {
  418. return _entryCursor.getNextEntry();
  419. }
  420. }
  421. /**
  422. * Handles moving the table index cursor backward.
  423. */
  424. private final class ReverseIndexDirHandler extends IndexDirHandler {
  425. @Override
  426. public PositionImpl getBeginningPosition() {
  427. return getLastPosition();
  428. }
  429. @Override
  430. public PositionImpl getEndPosition() {
  431. return getFirstPosition();
  432. }
  433. @Override
  434. public IndexData.Entry getAnotherEntry() throws IOException {
  435. return _entryCursor.getPreviousEntry();
  436. }
  437. }
  438. /**
  439. * Value object which maintains the current position of an IndexCursor.
  440. */
  441. private static final class IndexPosition extends PositionImpl
  442. {
  443. private final IndexData.Entry _entry;
  444. private IndexPosition(IndexData.Entry entry) {
  445. _entry = entry;
  446. }
  447. @Override
  448. public RowIdImpl getRowId() {
  449. return getEntry().getRowId();
  450. }
  451. public IndexData.Entry getEntry() {
  452. return _entry;
  453. }
  454. @Override
  455. protected boolean equalsImpl(Object o) {
  456. return getEntry().equals(((IndexPosition)o).getEntry());
  457. }
  458. @Override
  459. public String toString() {
  460. return "Entry = " + getEntry();
  461. }
  462. }
  463. /**
  464. * Row iterator (by matching entry) for this cursor, modifiable.
  465. */
  466. private final class EntryIterator extends BaseIterator
  467. {
  468. private final Object[] _rowValues;
  469. private EntryIterator(Collection<String> columnNames, Object[] rowValues,
  470. ColumnMatcher columnMatcher)
  471. {
  472. super(columnNames, false, MOVE_FORWARD, columnMatcher);
  473. _rowValues = rowValues;
  474. try {
  475. _hasNext = findFirstRowByEntryImpl(rowValues, true, _columnMatcher);
  476. _validRow = _hasNext;
  477. } catch(IOException e) {
  478. throw new RuntimeIOException(e);
  479. }
  480. }
  481. @Override
  482. protected boolean findNext() throws IOException {
  483. return (moveToNextRow() &&
  484. currentRowMatchesEntryImpl(_rowValues, _colMatcher));
  485. }
  486. }
  487. }