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

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