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.

CursorBuilder.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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;
  14. import java.io.IOException;
  15. import java.util.ArrayList;
  16. import java.util.Arrays;
  17. import java.util.Collection;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import com.healthmarketscience.jackcess.impl.TableImpl;
  22. import com.healthmarketscience.jackcess.impl.IndexImpl;
  23. import com.healthmarketscience.jackcess.impl.CursorImpl;
  24. import com.healthmarketscience.jackcess.impl.IndexCursorImpl;
  25. import com.healthmarketscience.jackcess.util.ColumnMatcher;
  26. /**
  27. * Builder style class for constructing a {@link Cursor}. By default, a
  28. * cursor is created at the beginning of the table, and any start/end rows are
  29. * inclusive.
  30. * <p/>
  31. * Simple example traversal:
  32. * <pre>
  33. * for(Row row : table.newCursor().toCursor()) {
  34. * // ... process each row ...
  35. * }
  36. * </pre>
  37. * <p/>
  38. * Simple example search:
  39. * <pre>
  40. * Row row = CursorBuilder.findRow(table, Collections.singletonMap(col, "foo"));
  41. * </pre>
  42. *
  43. * @author James Ahlborn
  44. * @usage _general_class_
  45. */
  46. public class CursorBuilder {
  47. /** the table which the cursor will traverse */
  48. private final TableImpl _table;
  49. /** optional index to use in traversal */
  50. private IndexImpl _index;
  51. /** optional start row for an index cursor */
  52. private Object[] _startRow;
  53. /** whether or not start row for an index cursor is inclusive */
  54. private boolean _startRowInclusive = true;
  55. /** optional end row for an index cursor */
  56. private Object[] _endRow;
  57. /** whether or not end row for an index cursor is inclusive */
  58. private boolean _endRowInclusive = true;
  59. /** whether to start at beginning or end of cursor */
  60. private boolean _beforeFirst = true;
  61. /** optional save point to restore to the cursor */
  62. private Cursor.Savepoint _savepoint;
  63. /** ColumnMatcher to be used when matching column values */
  64. private ColumnMatcher _columnMatcher;
  65. public CursorBuilder(Table table) {
  66. _table = (TableImpl)table;
  67. }
  68. /**
  69. * Sets the cursor so that it will start at the beginning (unless a
  70. * savepoint is given).
  71. */
  72. public CursorBuilder beforeFirst() {
  73. _beforeFirst = true;
  74. return this;
  75. }
  76. /**
  77. * Sets the cursor so that it will start at the end (unless a savepoint is
  78. * given).
  79. */
  80. public CursorBuilder afterLast() {
  81. _beforeFirst = false;
  82. return this;
  83. }
  84. /**
  85. * Sets a savepoint to restore for the initial position of the cursor.
  86. */
  87. public CursorBuilder restoreSavepoint(Cursor.Savepoint savepoint) {
  88. _savepoint = savepoint;
  89. return this;
  90. }
  91. /**
  92. * Sets an index to use for the cursor.
  93. */
  94. public CursorBuilder setIndex(Index index) {
  95. _index = (IndexImpl)index;
  96. return this;
  97. }
  98. /**
  99. * Sets an index to use for the cursor by searching the table for an index
  100. * with the given name.
  101. * @throws IllegalArgumentException if no index can be found on the table
  102. * with the given name
  103. */
  104. public CursorBuilder setIndexByName(String indexName) {
  105. return setIndex(_table.getIndex(indexName));
  106. }
  107. /**
  108. * Sets an index to use for the cursor by searching the table for an index
  109. * with exactly the given columns.
  110. * @throws IllegalArgumentException if no index can be found on the table
  111. * with the given columns
  112. */
  113. public CursorBuilder setIndexByColumnNames(String... columnNames) {
  114. return setIndexByColumns(Arrays.asList(columnNames));
  115. }
  116. /**
  117. * Sets an index to use for the cursor by searching the table for an index
  118. * with exactly the given columns.
  119. * @throws IllegalArgumentException if no index can be found on the table
  120. * with the given columns
  121. */
  122. public CursorBuilder setIndexByColumns(Column... columns) {
  123. List<String> colNames = new ArrayList<String>();
  124. for(Column col : columns) {
  125. colNames.add(col.getName());
  126. }
  127. return setIndexByColumns(colNames);
  128. }
  129. /**
  130. * Searches for an index with the given column names.
  131. */
  132. private CursorBuilder setIndexByColumns(List<String> searchColumns) {
  133. boolean found = false;
  134. for(IndexImpl index : _table.getIndexes()) {
  135. Collection<? extends Index.Column> indexColumns = index.getColumns();
  136. if(indexColumns.size() != searchColumns.size()) {
  137. continue;
  138. }
  139. Iterator<String> sIter = searchColumns.iterator();
  140. Iterator<? extends Index.Column> iIter = indexColumns.iterator();
  141. boolean matches = true;
  142. while(sIter.hasNext()) {
  143. String sColName = sIter.next();
  144. String iColName = iIter.next().getName();
  145. if((sColName != iColName) &&
  146. ((sColName == null) || !sColName.equalsIgnoreCase(iColName))) {
  147. matches = false;
  148. break;
  149. }
  150. }
  151. if(matches) {
  152. _index = index;
  153. found = true;
  154. break;
  155. }
  156. }
  157. if(!found) {
  158. throw new IllegalArgumentException("Index with columns " +
  159. searchColumns +
  160. " does not exist in table " + _table);
  161. }
  162. return this;
  163. }
  164. /**
  165. * Sets the starting and ending row for a range based index cursor.
  166. * <p>
  167. * A valid index must be specified before calling this method.
  168. */
  169. public CursorBuilder setSpecificRow(Object... specificRow) {
  170. setStartRow(specificRow);
  171. setEndRow(specificRow);
  172. return this;
  173. }
  174. /**
  175. * Sets the starting and ending row for a range based index cursor to the
  176. * given entry (where the given values correspond to the index's columns).
  177. * <p>
  178. * A valid index must be specified before calling this method.
  179. */
  180. public CursorBuilder setSpecificEntry(Object... specificEntry) {
  181. if(specificEntry != null) {
  182. setSpecificRow(_index.constructIndexRowFromEntry(specificEntry));
  183. }
  184. return this;
  185. }
  186. /**
  187. * Sets the starting row for a range based index cursor.
  188. * <p>
  189. * A valid index must be specified before calling this method.
  190. */
  191. public CursorBuilder setStartRow(Object... startRow) {
  192. _startRow = startRow;
  193. return this;
  194. }
  195. /**
  196. * Sets the starting row for a range based index cursor to the given entry
  197. * (where the given values correspond to the index's columns).
  198. * <p>
  199. * A valid index must be specified before calling this method.
  200. */
  201. public CursorBuilder setStartEntry(Object... startEntry) {
  202. if(startEntry != null) {
  203. setStartRow(_index.constructIndexRowFromEntry(startEntry));
  204. }
  205. return this;
  206. }
  207. /**
  208. * Sets whether the starting row for a range based index cursor is inclusive
  209. * or exclusive.
  210. */
  211. public CursorBuilder setStartRowInclusive(boolean inclusive) {
  212. _startRowInclusive = inclusive;
  213. return this;
  214. }
  215. /**
  216. * Sets the ending row for a range based index cursor.
  217. * <p>
  218. * A valid index must be specified before calling this method.
  219. */
  220. public CursorBuilder setEndRow(Object... endRow) {
  221. _endRow = endRow;
  222. return this;
  223. }
  224. /**
  225. * Sets the ending row for a range based index cursor to the given entry
  226. * (where the given values correspond to the index's columns).
  227. * <p>
  228. * A valid index must be specified before calling this method.
  229. */
  230. public CursorBuilder setEndEntry(Object... endEntry) {
  231. if(endEntry != null) {
  232. setEndRow(_index.constructIndexRowFromEntry(endEntry));
  233. }
  234. return this;
  235. }
  236. /**
  237. * Sets whether the ending row for a range based index cursor is inclusive
  238. * or exclusive.
  239. */
  240. public CursorBuilder setEndRowInclusive(boolean inclusive) {
  241. _endRowInclusive = inclusive;
  242. return this;
  243. }
  244. /**
  245. * Sets the ColumnMatcher to use for matching row patterns.
  246. */
  247. public CursorBuilder setColumnMatcher(ColumnMatcher columnMatcher) {
  248. _columnMatcher = columnMatcher;
  249. return this;
  250. }
  251. /**
  252. * Returns a new cursor for the table, constructed to the given
  253. * specifications.
  254. */
  255. public Cursor toCursor() throws IOException
  256. {
  257. CursorImpl cursor = null;
  258. if(_index == null) {
  259. cursor = CursorImpl.createCursor(_table);
  260. } else {
  261. cursor = IndexCursorImpl.createCursor(_table, _index,
  262. _startRow, _startRowInclusive,
  263. _endRow, _endRowInclusive);
  264. }
  265. cursor.setColumnMatcher(_columnMatcher);
  266. if(_savepoint == null) {
  267. if(!_beforeFirst) {
  268. cursor.afterLast();
  269. }
  270. } else {
  271. cursor.restoreSavepoint(_savepoint);
  272. }
  273. return cursor;
  274. }
  275. /**
  276. * Returns a new index cursor for the table, constructed to the given
  277. * specifications.
  278. */
  279. public IndexCursor toIndexCursor() throws IOException
  280. {
  281. return (IndexCursorImpl)toCursor();
  282. }
  283. /**
  284. * Creates a normal, un-indexed cursor for the given table.
  285. * @param table the table over which this cursor will traverse
  286. */
  287. public static Cursor createCursor(Table table) throws IOException {
  288. return table.newCursor().toCursor();
  289. }
  290. /**
  291. * Creates an indexed cursor for the given table.
  292. * <p>
  293. * Note, index based table traversal may not include all rows, as certain
  294. * types of indexes do not include all entries (namely, some indexes ignore
  295. * null entries, see {@link Index#shouldIgnoreNulls}).
  296. *
  297. * @param index index for the table which will define traversal order as
  298. * well as enhance certain lookups
  299. */
  300. public static IndexCursor createCursor(Index index)
  301. throws IOException
  302. {
  303. return index.getTable().newCursor().setIndex(index).toIndexCursor();
  304. }
  305. /**
  306. * Creates an indexed cursor for the primary key cursor of the given table.
  307. * @param table the table over which this cursor will traverse
  308. */
  309. public static IndexCursor createPrimaryKeyCursor(Table table)
  310. throws IOException
  311. {
  312. return createCursor(table.getPrimaryKeyIndex());
  313. }
  314. /**
  315. * Creates an indexed cursor for the given table, narrowed to the given
  316. * range.
  317. * <p>
  318. * Note, index based table traversal may not include all rows, as certain
  319. * types of indexes do not include all entries (namely, some indexes ignore
  320. * null entries, see {@link Index#shouldIgnoreNulls}).
  321. *
  322. * @param index index for the table which will define traversal order as
  323. * well as enhance certain lookups
  324. * @param startRow the first row of data for the cursor (inclusive), or
  325. * {@code null} for the first entry
  326. * @param endRow the last row of data for the cursor (inclusive), or
  327. * {@code null} for the last entry
  328. */
  329. public static IndexCursor createCursor(Index index,
  330. Object[] startRow, Object[] endRow)
  331. throws IOException
  332. {
  333. return index.getTable().newCursor().setIndex(index)
  334. .setStartRow(startRow)
  335. .setEndRow(endRow)
  336. .toIndexCursor();
  337. }
  338. /**
  339. * Creates an indexed cursor for the given table, narrowed to the given
  340. * range.
  341. * <p>
  342. * Note, index based table traversal may not include all rows, as certain
  343. * types of indexes do not include all entries (namely, some indexes ignore
  344. * null entries, see {@link Index#shouldIgnoreNulls}).
  345. *
  346. * @param index index for the table which will define traversal order as
  347. * well as enhance certain lookups
  348. * @param startRow the first row of data for the cursor, or {@code null} for
  349. * the first entry
  350. * @param startInclusive whether or not startRow is inclusive or exclusive
  351. * @param endRow the last row of data for the cursor, or {@code null} for
  352. * the last entry
  353. * @param endInclusive whether or not endRow is inclusive or exclusive
  354. */
  355. public static IndexCursor createCursor(Index index,
  356. Object[] startRow,
  357. boolean startInclusive,
  358. Object[] endRow,
  359. boolean endInclusive)
  360. throws IOException
  361. {
  362. return index.getTable().newCursor().setIndex(index)
  363. .setStartRow(startRow)
  364. .setStartRowInclusive(startInclusive)
  365. .setEndRow(endRow)
  366. .setEndRowInclusive(endInclusive)
  367. .toIndexCursor();
  368. }
  369. /**
  370. * Convenience method for finding a specific row in a table which matches a
  371. * given row "pattern". See {@link Cursor#findFirstRow(Map)} for details on
  372. * the rowPattern.
  373. * <p>
  374. * Warning, this method <i>always</i> starts searching from the beginning of
  375. * the Table (you cannot use it to find successive matches).
  376. *
  377. * @param table the table to search
  378. * @param rowPattern pattern to be used to find the row
  379. * @return the matching row or {@code null} if a match could not be found.
  380. */
  381. public static Row findRow(Table table, Map<String,?> rowPattern)
  382. throws IOException
  383. {
  384. Cursor cursor = createCursor(table);
  385. if(cursor.findFirstRow(rowPattern)) {
  386. return cursor.getCurrentRow();
  387. }
  388. return null;
  389. }
  390. /**
  391. * Convenience method for finding a specific row (as defined by the cursor)
  392. * where the index entries match the given values. See {@link
  393. * IndexCursor#findRowByEntry(Object...)} for details on the entryValues.
  394. *
  395. * @param index the index to search
  396. * @param entryValues the column values for the index's columns.
  397. * @return the matching row or {@code null} if a match could not be found.
  398. */
  399. public static Row findRowByEntry(Index index, Object... entryValues)
  400. throws IOException
  401. {
  402. return createCursor(index).findRowByEntry(entryValues);
  403. }
  404. /**
  405. * Convenience method for finding a specific row by the primary key of the
  406. * table. See {@link IndexCursor#findRowByEntry(Object...)} for details on
  407. * the entryValues.
  408. *
  409. * @param table the table to search
  410. * @param entryValues the column values for the table's primary key columns.
  411. * @return the matching row or {@code null} if a match could not be found.
  412. */
  413. public static Row findRowByPrimaryKey(Table table, Object... entryValues)
  414. throws IOException
  415. {
  416. return findRowByEntry(table.getPrimaryKeyIndex(), entryValues);
  417. }
  418. /**
  419. * Convenience method for finding a specific row in a table which matches a
  420. * given row "pattern". See {@link Cursor#findFirstRow(Column,Object)} for
  421. * details on the pattern.
  422. * <p>
  423. * Note, a {@code null} result value is ambiguous in that it could imply no
  424. * match or a matching row with {@code null} for the desired value. If
  425. * distinguishing this situation is important, you will need to use a Cursor
  426. * directly instead of this convenience method.
  427. *
  428. * @param table the table to search
  429. * @param column column whose value should be returned
  430. * @param columnPattern column being matched by the valuePattern
  431. * @param valuePattern value from the columnPattern which will match the
  432. * desired row
  433. * @return the matching row or {@code null} if a match could not be found.
  434. */
  435. public static Object findValue(Table table, Column column,
  436. Column columnPattern, Object valuePattern)
  437. throws IOException
  438. {
  439. Cursor cursor = createCursor(table);
  440. if(cursor.findFirstRow(columnPattern, valuePattern)) {
  441. return cursor.getCurrentRowValue(column);
  442. }
  443. return null;
  444. }
  445. /**
  446. * Convenience method for finding a specific row in an indexed table which
  447. * matches a given row "pattern". See {@link Cursor#findFirstRow(Map)} for
  448. * details on the rowPattern.
  449. * <p>
  450. * Warning, this method <i>always</i> starts searching from the beginning of
  451. * the Table (you cannot use it to find successive matches).
  452. *
  453. * @param index index to assist the search
  454. * @param rowPattern pattern to be used to find the row
  455. * @return the matching row or {@code null} if a match could not be found.
  456. */
  457. public static Row findRow(Index index, Map<String,?> rowPattern)
  458. throws IOException
  459. {
  460. Cursor cursor = createCursor(index);
  461. if(cursor.findFirstRow(rowPattern)) {
  462. return cursor.getCurrentRow();
  463. }
  464. return null;
  465. }
  466. /**
  467. * Convenience method for finding a specific row in a table which matches a
  468. * given row "pattern". See {@link Cursor#findFirstRow(Column,Object)} for
  469. * details on the pattern.
  470. * <p>
  471. * Note, a {@code null} result value is ambiguous in that it could imply no
  472. * match or a matching row with {@code null} for the desired value. If
  473. * distinguishing this situation is important, you will need to use a Cursor
  474. * directly instead of this convenience method.
  475. *
  476. * @param index index to assist the search
  477. * @param column column whose value should be returned
  478. * @param columnPattern column being matched by the valuePattern
  479. * @param valuePattern value from the columnPattern which will match the
  480. * desired row
  481. * @return the matching row or {@code null} if a match could not be found.
  482. */
  483. public static Object findValue(Index index, Column column,
  484. Column columnPattern, Object valuePattern)
  485. throws IOException
  486. {
  487. Cursor cursor = createCursor(index);
  488. if(cursor.findFirstRow(columnPattern, valuePattern)) {
  489. return cursor.getCurrentRowValue(column);
  490. }
  491. return null;
  492. }
  493. }