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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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(index.getIndexData().getUnsupportedReason() != null) {
  92. throw new IllegalArgumentException(
  93. "Given index " + index +
  94. " is not usable for indexed lookups due to " +
  95. index.getIndexData().getUnsupportedReason());
  96. }
  97. IndexCursorImpl cursor = new IndexCursorImpl(
  98. table, index, index.cursor(startRow, startInclusive,
  99. endRow, endInclusive));
  100. // init the column matcher appropriately for the index type
  101. cursor.setColumnMatcher(null);
  102. return cursor;
  103. }
  104. private Set<String> getIndexEntryPattern()
  105. {
  106. if(_indexEntryPattern == null) {
  107. // init our set of index column names
  108. _indexEntryPattern = new HashSet<String>();
  109. for(IndexData.ColumnDescriptor col : getIndex().getColumns()) {
  110. _indexEntryPattern.add(col.getName());
  111. }
  112. }
  113. return _indexEntryPattern;
  114. }
  115. @Override
  116. public IndexImpl getIndex() {
  117. return _index;
  118. }
  119. @Override
  120. public Row findRowByEntry(Object... entryValues)
  121. throws IOException
  122. {
  123. if(findFirstRowByEntry(entryValues)) {
  124. return getCurrentRow();
  125. }
  126. return null;
  127. }
  128. @Override
  129. public boolean findFirstRowByEntry(Object... entryValues)
  130. throws IOException
  131. {
  132. PositionImpl curPos = _curPos;
  133. PositionImpl prevPos = _prevPos;
  134. boolean found = false;
  135. try {
  136. found = findFirstRowByEntryImpl(toRowValues(entryValues), true,
  137. _columnMatcher);
  138. return found;
  139. } finally {
  140. if(!found) {
  141. try {
  142. restorePosition(curPos, prevPos);
  143. } catch(IOException e) {
  144. LOG.error("Failed restoring position", e);
  145. }
  146. }
  147. }
  148. }
  149. @Override
  150. public void findClosestRowByEntry(Object... entryValues)
  151. throws IOException
  152. {
  153. PositionImpl curPos = _curPos;
  154. PositionImpl prevPos = _prevPos;
  155. boolean found = false;
  156. try {
  157. findFirstRowByEntryImpl(toRowValues(entryValues), false,
  158. _columnMatcher);
  159. found = true;
  160. } finally {
  161. if(!found) {
  162. try {
  163. restorePosition(curPos, prevPos);
  164. } catch(IOException e) {
  165. LOG.error("Failed restoring position", e);
  166. }
  167. }
  168. }
  169. }
  170. @Override
  171. public boolean currentRowMatchesEntry(Object... entryValues)
  172. throws IOException
  173. {
  174. return currentRowMatchesEntryImpl(toRowValues(entryValues), _columnMatcher);
  175. }
  176. @Override
  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 table
  237. return currentRowMatchesImpl(columnPattern, valuePattern, columnMatcher);
  238. }
  239. /**
  240. * Moves to the first row (as defined by the cursor) where the index entries
  241. * match the given values. Caller manages save/restore on failure.
  242. *
  243. * @param rowValues the column values built from the index column values
  244. * @param requireMatch whether or not an exact match is desired
  245. * @return {@code true} if a valid row was found with the given values,
  246. * {@code false} if no row was found
  247. */
  248. protected boolean findFirstRowByEntryImpl(Object[] rowValues,
  249. boolean requireMatch,
  250. ColumnMatcher columnMatcher)
  251. throws IOException
  252. {
  253. if(!findPotentialRow(rowValues, requireMatch)) {
  254. return false;
  255. } else if(!requireMatch) {
  256. // nothing more to do, we have moved to the closest row
  257. return true;
  258. }
  259. return currentRowMatchesEntryImpl(rowValues, columnMatcher);
  260. }
  261. @Override
  262. protected boolean findAnotherRowImpl(
  263. Map<String,?> rowPattern, boolean moveForward,
  264. ColumnMatcher columnMatcher, Object searchInfo)
  265. throws IOException
  266. {
  267. Object[] rowValues = (Object[])searchInfo;
  268. if((rowValues == null) || !isAtBeginning(moveForward)) {
  269. // use the default table scan if we don't have index data or we are
  270. // mid-cursor
  271. return super.findAnotherRowImpl(rowPattern, moveForward, columnMatcher,
  272. rowValues);
  273. }
  274. // sweet, we can use our index
  275. if(!findPotentialRow(rowValues, true)) {
  276. // at end of index, no potential matches
  277. return false;
  278. }
  279. // determine if the pattern columns exactly match the index columns
  280. boolean exactColumnMatch = rowPattern.keySet().equals(
  281. getIndexEntryPattern());
  282. // there may be multiple rows which fit the pattern subset used by
  283. // the index, so we need to keep checking until our index values no
  284. // longer match
  285. do {
  286. if(!currentRowMatchesEntryImpl(rowValues, columnMatcher)) {
  287. // there are no more rows which could possibly match
  288. break;
  289. }
  290. // note, if exactColumnMatch, no need to do an extra comparison with the
  291. // current row (since the entry match check above is equivalent to this
  292. // check)
  293. if(exactColumnMatch || currentRowMatchesImpl(rowPattern, columnMatcher)) {
  294. // found it!
  295. return true;
  296. }
  297. } while(moveToAnotherRow(moveForward));
  298. // none of the potential rows matched
  299. return false;
  300. }
  301. private boolean currentRowMatchesEntryImpl(Object[] rowValues,
  302. ColumnMatcher columnMatcher)
  303. throws IOException
  304. {
  305. // check the next row to see if it actually matches
  306. Row row = getCurrentRow(getIndexEntryPattern());
  307. for(IndexData.ColumnDescriptor col : getIndex().getColumns()) {
  308. Object patValue = rowValues[col.getColumnIndex()];
  309. if((patValue == IndexData.MIN_VALUE) ||
  310. (patValue == IndexData.MAX_VALUE)) {
  311. // all remaining entry values are "special" (used for partial lookups)
  312. return true;
  313. }
  314. String columnName = col.getName();
  315. Object rowValue = row.get(columnName);
  316. if(!columnMatcher.matches(getTable(), columnName, patValue, rowValue)) {
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. private boolean findPotentialRow(Object[] rowValues, boolean requireMatch)
  323. throws IOException
  324. {
  325. _entryCursor.beforeEntry(rowValues);
  326. IndexData.Entry startEntry = _entryCursor.getNextEntry();
  327. if(requireMatch && !startEntry.getRowId().isValid()) {
  328. // at end of index, no potential matches
  329. return false;
  330. }
  331. // move to position and check it out
  332. restorePosition(new IndexPosition(startEntry));
  333. return true;
  334. }
  335. @Override
  336. protected Object prepareSearchInfo(ColumnImpl columnPattern, Object valuePattern)
  337. {
  338. // attempt to generate a lookup row for this index
  339. return _entryCursor.getIndexData().constructPartialIndexRow(
  340. IndexData.MIN_VALUE, columnPattern.getName(), valuePattern);
  341. }
  342. @Override
  343. protected Object prepareSearchInfo(Map<String,?> rowPattern)
  344. {
  345. // attempt to generate a lookup row for this index
  346. return _entryCursor.getIndexData().constructPartialIndexRow(
  347. IndexData.MIN_VALUE, rowPattern);
  348. }
  349. @Override
  350. protected boolean keepSearching(ColumnMatcher columnMatcher,
  351. Object searchInfo)
  352. throws IOException
  353. {
  354. if(searchInfo instanceof Object[]) {
  355. // if we have a lookup row for this index, then we only need to continue
  356. // searching while we are looking at rows which match the index lookup
  357. // value(s). once we move past those rows, no other rows could possibly
  358. // match.
  359. return currentRowMatchesEntryImpl((Object[])searchInfo, columnMatcher);
  360. }
  361. // we are doing a full table scan
  362. return true;
  363. }
  364. private Object[] toRowValues(Object[] entryValues)
  365. {
  366. return _entryCursor.getIndexData().constructPartialIndexRowFromEntry(
  367. IndexData.MIN_VALUE, entryValues);
  368. }
  369. @Override
  370. protected PositionImpl findAnotherPosition(
  371. RowState rowState, PositionImpl curPos, boolean moveForward)
  372. throws IOException
  373. {
  374. IndexDirHandler handler = getDirHandler(moveForward);
  375. IndexPosition endPos = (IndexPosition)handler.getEndPosition();
  376. IndexData.Entry entry = handler.getAnotherEntry();
  377. return ((!entry.equals(endPos.getEntry())) ?
  378. new IndexPosition(entry) : endPos);
  379. }
  380. @Override
  381. protected ColumnMatcher getDefaultColumnMatcher() {
  382. if(getIndex().isUnique()) {
  383. // text indexes are case-insensitive, therefore we should always use a
  384. // case-insensitive matcher for unique indexes.
  385. return CaseInsensitiveColumnMatcher.INSTANCE;
  386. }
  387. return SimpleColumnMatcher.INSTANCE;
  388. }
  389. /**
  390. * Handles moving the table index cursor in a given direction. Separates
  391. * cursor logic from value storage.
  392. */
  393. private abstract class IndexDirHandler extends DirHandler {
  394. public abstract IndexData.Entry getAnotherEntry()
  395. throws IOException;
  396. }
  397. /**
  398. * Handles moving the table index cursor forward.
  399. */
  400. private final class ForwardIndexDirHandler extends IndexDirHandler {
  401. @Override
  402. public PositionImpl getBeginningPosition() {
  403. return getFirstPosition();
  404. }
  405. @Override
  406. public PositionImpl getEndPosition() {
  407. return getLastPosition();
  408. }
  409. @Override
  410. public IndexData.Entry getAnotherEntry() throws IOException {
  411. return _entryCursor.getNextEntry();
  412. }
  413. }
  414. /**
  415. * Handles moving the table index cursor backward.
  416. */
  417. private final class ReverseIndexDirHandler extends IndexDirHandler {
  418. @Override
  419. public PositionImpl getBeginningPosition() {
  420. return getLastPosition();
  421. }
  422. @Override
  423. public PositionImpl getEndPosition() {
  424. return getFirstPosition();
  425. }
  426. @Override
  427. public IndexData.Entry getAnotherEntry() throws IOException {
  428. return _entryCursor.getPreviousEntry();
  429. }
  430. }
  431. /**
  432. * Value object which maintains the current position of an IndexCursor.
  433. */
  434. private static final class IndexPosition extends PositionImpl
  435. {
  436. private final IndexData.Entry _entry;
  437. private IndexPosition(IndexData.Entry entry) {
  438. _entry = entry;
  439. }
  440. @Override
  441. public RowIdImpl getRowId() {
  442. return getEntry().getRowId();
  443. }
  444. public IndexData.Entry getEntry() {
  445. return _entry;
  446. }
  447. @Override
  448. protected boolean equalsImpl(Object o) {
  449. return getEntry().equals(((IndexPosition)o).getEntry());
  450. }
  451. @Override
  452. public String toString() {
  453. return "Entry = " + getEntry();
  454. }
  455. }
  456. /**
  457. * Row iterator (by matching entry) for this cursor, modifiable.
  458. */
  459. private final class EntryIterator extends BaseIterator
  460. {
  461. private final Object[] _rowValues;
  462. private EntryIterator(Collection<String> columnNames, Object[] rowValues,
  463. ColumnMatcher columnMatcher)
  464. {
  465. super(columnNames, false, MOVE_FORWARD, columnMatcher);
  466. _rowValues = rowValues;
  467. try {
  468. _hasNext = findFirstRowByEntryImpl(rowValues, true, _columnMatcher);
  469. _validRow = _hasNext;
  470. } catch(IOException e) {
  471. throw new RuntimeIOException(e);
  472. }
  473. }
  474. @Override
  475. protected boolean findNext() throws IOException {
  476. return (moveToNextRow() &&
  477. currentRowMatchesEntryImpl(_rowValues, _colMatcher));
  478. }
  479. }
  480. }