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

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