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

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