Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

CursorBuilder.java 17KB

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