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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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.CursorImpl;
  20. import com.healthmarketscience.jackcess.impl.IndexCursorImpl;
  21. import com.healthmarketscience.jackcess.impl.IndexData;
  22. import com.healthmarketscience.jackcess.impl.IndexImpl;
  23. import com.healthmarketscience.jackcess.impl.TableImpl;
  24. import com.healthmarketscience.jackcess.util.CaseInsensitiveColumnMatcher;
  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. IndexImpl index = _table.findIndexForColumns(
  134. searchColumns, TableImpl.IndexFeature.ANY_MATCH);
  135. if(index == null) {
  136. throw new IllegalArgumentException("Index with columns " +
  137. searchColumns +
  138. " does not exist in table " + _table);
  139. }
  140. _index = index;
  141. return this;
  142. }
  143. /**
  144. * Sets the starting and ending row for a range based index cursor.
  145. * <p>
  146. * A valid index must be specified before calling this method.
  147. */
  148. public CursorBuilder setSpecificRow(Object... specificRow) {
  149. setStartRow(specificRow);
  150. setEndRow(specificRow);
  151. return this;
  152. }
  153. /**
  154. * Sets the starting and ending row for a range based index cursor to the
  155. * given entry (where the given values correspond to the index's columns).
  156. * <p>
  157. * A valid index must be specified before calling this method.
  158. */
  159. public CursorBuilder setSpecificEntry(Object... specificEntry) {
  160. if(specificEntry != null) {
  161. setSpecificRow(_index.constructIndexRowFromEntry(specificEntry));
  162. }
  163. return this;
  164. }
  165. /**
  166. * Sets the starting row for a range based index cursor.
  167. * <p>
  168. * A valid index must be specified before calling this method.
  169. */
  170. public CursorBuilder setStartRow(Object... startRow) {
  171. _startRow = startRow;
  172. return this;
  173. }
  174. /**
  175. * Sets the starting row for a range based index cursor to the given entry
  176. * (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 setStartEntry(Object... startEntry) {
  181. if(startEntry != null) {
  182. setStartRow(_index.constructPartialIndexRowFromEntry(
  183. IndexData.MIN_VALUE, startEntry));
  184. }
  185. return this;
  186. }
  187. /**
  188. * Sets whether the starting row for a range based index cursor is inclusive
  189. * or exclusive.
  190. */
  191. public CursorBuilder setStartRowInclusive(boolean inclusive) {
  192. _startRowInclusive = inclusive;
  193. return this;
  194. }
  195. /**
  196. * Sets the ending row for a range based index cursor.
  197. * <p>
  198. * A valid index must be specified before calling this method.
  199. */
  200. public CursorBuilder setEndRow(Object... endRow) {
  201. _endRow = endRow;
  202. return this;
  203. }
  204. /**
  205. * Sets the ending 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 setEndEntry(Object... endEntry) {
  211. if(endEntry != null) {
  212. setEndRow(_index.constructPartialIndexRowFromEntry(
  213. IndexData.MAX_VALUE, endEntry));
  214. }
  215. return this;
  216. }
  217. /**
  218. * Sets whether the ending row for a range based index cursor is inclusive
  219. * or exclusive.
  220. */
  221. public CursorBuilder setEndRowInclusive(boolean inclusive) {
  222. _endRowInclusive = inclusive;
  223. return this;
  224. }
  225. /**
  226. * Sets the ColumnMatcher to use for matching row patterns.
  227. */
  228. public CursorBuilder setColumnMatcher(ColumnMatcher columnMatcher) {
  229. _columnMatcher = columnMatcher;
  230. return this;
  231. }
  232. /**
  233. * Sets the ColumnMatcher to an instance of CaseInsensitiveColumnMatcher
  234. */
  235. public CursorBuilder setCaseInsensitive() {
  236. return setColumnMatcher(CaseInsensitiveColumnMatcher.INSTANCE);
  237. }
  238. /**
  239. * Returns a new cursor for the table, constructed to the given
  240. * specifications.
  241. */
  242. public Cursor toCursor() throws IOException
  243. {
  244. CursorImpl cursor = null;
  245. if(_index == null) {
  246. cursor = CursorImpl.createCursor(_table);
  247. } else {
  248. cursor = IndexCursorImpl.createCursor(_table, _index,
  249. _startRow, _startRowInclusive,
  250. _endRow, _endRowInclusive);
  251. }
  252. cursor.setColumnMatcher(_columnMatcher);
  253. if(_savepoint == null) {
  254. if(!_beforeFirst) {
  255. cursor.afterLast();
  256. }
  257. } else {
  258. cursor.restoreSavepoint(_savepoint);
  259. }
  260. return cursor;
  261. }
  262. /**
  263. * Returns a new index cursor for the table, constructed to the given
  264. * specifications.
  265. */
  266. public IndexCursor toIndexCursor() throws IOException
  267. {
  268. return (IndexCursorImpl)toCursor();
  269. }
  270. /**
  271. * Creates a normal, un-indexed cursor for the given table.
  272. * @param table the table over which this cursor will traverse
  273. */
  274. public static Cursor createCursor(Table table) throws IOException {
  275. return table.newCursor().toCursor();
  276. }
  277. /**
  278. * Creates an indexed cursor for the given table.
  279. * <p>
  280. * Note, index based table traversal may not include all rows, as certain
  281. * types of indexes do not include all entries (namely, some indexes ignore
  282. * null entries, see {@link Index#shouldIgnoreNulls}).
  283. *
  284. * @param index index for the table which will define traversal order as
  285. * well as enhance certain lookups
  286. */
  287. public static IndexCursor createCursor(Index index)
  288. throws IOException
  289. {
  290. return index.getTable().newCursor().setIndex(index).toIndexCursor();
  291. }
  292. /**
  293. * Creates an indexed cursor for the primary key cursor of the given table.
  294. * @param table the table over which this cursor will traverse
  295. */
  296. public static IndexCursor createPrimaryKeyCursor(Table table)
  297. throws IOException
  298. {
  299. return createCursor(table.getPrimaryKeyIndex());
  300. }
  301. /**
  302. * Creates an indexed cursor for the given table, narrowed to the given
  303. * range.
  304. * <p>
  305. * Note, index based table traversal may not include all rows, as certain
  306. * types of indexes do not include all entries (namely, some indexes ignore
  307. * null entries, see {@link Index#shouldIgnoreNulls}).
  308. *
  309. * @param index index for the table which will define traversal order as
  310. * well as enhance certain lookups
  311. * @param startRow the first row of data for the cursor (inclusive), or
  312. * {@code null} for the first entry
  313. * @param endRow the last row of data for the cursor (inclusive), or
  314. * {@code null} for the last entry
  315. */
  316. public static IndexCursor createCursor(Index index,
  317. Object[] startRow, Object[] endRow)
  318. throws IOException
  319. {
  320. return index.getTable().newCursor().setIndex(index)
  321. .setStartRow(startRow)
  322. .setEndRow(endRow)
  323. .toIndexCursor();
  324. }
  325. /**
  326. * Creates an indexed cursor for the given table, narrowed to the given
  327. * range.
  328. * <p>
  329. * Note, index based table traversal may not include all rows, as certain
  330. * types of indexes do not include all entries (namely, some indexes ignore
  331. * null entries, see {@link Index#shouldIgnoreNulls}).
  332. *
  333. * @param index index for the table which will define traversal order as
  334. * well as enhance certain lookups
  335. * @param startRow the first row of data for the cursor, or {@code null} for
  336. * the first entry
  337. * @param startInclusive whether or not startRow is inclusive or exclusive
  338. * @param endRow the last row of data for the cursor, or {@code null} for
  339. * the last entry
  340. * @param endInclusive whether or not endRow is inclusive or exclusive
  341. */
  342. public static IndexCursor createCursor(Index index,
  343. Object[] startRow,
  344. boolean startInclusive,
  345. Object[] endRow,
  346. boolean endInclusive)
  347. throws IOException
  348. {
  349. return index.getTable().newCursor().setIndex(index)
  350. .setStartRow(startRow)
  351. .setStartRowInclusive(startInclusive)
  352. .setEndRow(endRow)
  353. .setEndRowInclusive(endInclusive)
  354. .toIndexCursor();
  355. }
  356. /**
  357. * Convenience method for finding a specific row in a table which matches a
  358. * given row "pattern". See {@link Cursor#findFirstRow(Map)} for details on
  359. * the rowPattern.
  360. * <p>
  361. * Warning, this method <i>always</i> starts searching from the beginning of
  362. * the Table (you cannot use it to find successive matches).
  363. *
  364. * @param table the table to search
  365. * @param rowPattern pattern to be used to find the row
  366. * @return the matching row or {@code null} if a match could not be found.
  367. */
  368. public static Row findRow(Table table, Map<String,?> rowPattern)
  369. throws IOException
  370. {
  371. Cursor cursor = createCursor(table);
  372. if(cursor.findFirstRow(rowPattern)) {
  373. return cursor.getCurrentRow();
  374. }
  375. return null;
  376. }
  377. /**
  378. * Convenience method for finding a specific row (as defined by the cursor)
  379. * where the index entries match the given values. See {@link
  380. * IndexCursor#findRowByEntry(Object...)} for details on the entryValues.
  381. *
  382. * @param index the index to search
  383. * @param entryValues the column values for the index's columns.
  384. * @return the matching row or {@code null} if a match could not be found.
  385. */
  386. public static Row findRowByEntry(Index index, Object... entryValues)
  387. throws IOException
  388. {
  389. return createCursor(index).findRowByEntry(entryValues);
  390. }
  391. /**
  392. * Convenience method for finding a specific row by the primary key of the
  393. * table. See {@link IndexCursor#findRowByEntry(Object...)} for details on
  394. * the entryValues.
  395. *
  396. * @param table the table to search
  397. * @param entryValues the column values for the table's primary key columns.
  398. * @return the matching row or {@code null} if a match could not be found.
  399. */
  400. public static Row findRowByPrimaryKey(Table table, Object... entryValues)
  401. throws IOException
  402. {
  403. return findRowByEntry(table.getPrimaryKeyIndex(), entryValues);
  404. }
  405. /**
  406. * Convenience method for finding a specific row in a table which matches a
  407. * given row "pattern". See {@link Cursor#findFirstRow(Column,Object)} for
  408. * details on the pattern.
  409. * <p>
  410. * Note, a {@code null} result value is ambiguous in that it could imply no
  411. * match or a matching row with {@code null} for the desired value. If
  412. * distinguishing this situation is important, you will need to use a Cursor
  413. * directly instead of this convenience method.
  414. *
  415. * @param table the table to search
  416. * @param column column whose value should be returned
  417. * @param columnPattern column being matched by the valuePattern
  418. * @param valuePattern value from the columnPattern which will match the
  419. * desired row
  420. * @return the matching row or {@code null} if a match could not be found.
  421. */
  422. public static Object findValue(Table table, Column column,
  423. Column columnPattern, Object valuePattern)
  424. throws IOException
  425. {
  426. Cursor cursor = createCursor(table);
  427. if(cursor.findFirstRow(columnPattern, valuePattern)) {
  428. return cursor.getCurrentRowValue(column);
  429. }
  430. return null;
  431. }
  432. /**
  433. * Convenience method for finding a specific row in an indexed table which
  434. * matches a given row "pattern". See {@link Cursor#findFirstRow(Map)} for
  435. * details on the rowPattern.
  436. * <p>
  437. * Warning, this method <i>always</i> starts searching from the beginning of
  438. * the Table (you cannot use it to find successive matches).
  439. *
  440. * @param index index to assist the search
  441. * @param rowPattern pattern to be used to find the row
  442. * @return the matching row or {@code null} if a match could not be found.
  443. */
  444. public static Row findRow(Index index, Map<String,?> rowPattern)
  445. throws IOException
  446. {
  447. Cursor cursor = createCursor(index);
  448. if(cursor.findFirstRow(rowPattern)) {
  449. return cursor.getCurrentRow();
  450. }
  451. return null;
  452. }
  453. /**
  454. * Convenience method for finding a specific row in a table which matches a
  455. * given row "pattern". See {@link Cursor#findFirstRow(Column,Object)} for
  456. * details on the pattern.
  457. * <p>
  458. * Note, a {@code null} result value is ambiguous in that it could imply no
  459. * match or a matching row with {@code null} for the desired value. If
  460. * distinguishing this situation is important, you will need to use a Cursor
  461. * directly instead of this convenience method.
  462. *
  463. * @param index index to assist the search
  464. * @param column column whose value should be returned
  465. * @param columnPattern column being matched by the valuePattern
  466. * @param valuePattern value from the columnPattern which will match the
  467. * desired row
  468. * @return the matching row or {@code null} if a match could not be found.
  469. */
  470. public static Object findValue(Index index, Column column,
  471. Column columnPattern, Object valuePattern)
  472. throws IOException
  473. {
  474. Cursor cursor = createCursor(index);
  475. if(cursor.findFirstRow(columnPattern, valuePattern)) {
  476. return cursor.getCurrentRowValue(column);
  477. }
  478. return null;
  479. }
  480. }