aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/healthmarketscience/jackcess/CursorBuilder.java
blob: 41b1d472cde2b408fc9a0583059b62e00e23149f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
Copyright (c) 2007 Health Market Science, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.healthmarketscience.jackcess;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.healthmarketscience.jackcess.impl.CursorImpl;
import com.healthmarketscience.jackcess.impl.IndexCursorImpl;
import com.healthmarketscience.jackcess.impl.IndexData;
import com.healthmarketscience.jackcess.impl.IndexImpl;
import com.healthmarketscience.jackcess.impl.TableImpl;
import com.healthmarketscience.jackcess.util.CaseInsensitiveColumnMatcher;
import com.healthmarketscience.jackcess.util.ColumnMatcher;


/**
 * Builder style class for constructing a {@link Cursor}.  By default, a
 * cursor is created at the beginning of the table, and any start/end rows are
 * inclusive.
 * <p>
 * Simple example traversal:
 * <pre>
 *   for(Row row : table.newCursor().toCursor()) {
 *     // ... process each row ...
 *   }
 * </pre>
 * <p>
 * Simple example search:
 * <pre>
 *   Row row = CursorBuilder.findRow(table, Collections.singletonMap(col, "foo"));
 * </pre>
 *
 * @author James Ahlborn
 * @usage _general_class_
 */
public class CursorBuilder {
  /** the table which the cursor will traverse */
  private final TableImpl _table;
  /** optional index to use in traversal */
  private IndexImpl _index;
  /** optional start row for an index cursor */
  private Object[] _startRow;
  /** whether or not start row for an index cursor is inclusive */
  private boolean _startRowInclusive = true;
  /** optional end row for an index cursor */
  private Object[] _endRow;
  /** whether or not end row for an index cursor is inclusive */
  private boolean _endRowInclusive = true;
  /** whether to start at beginning or end of cursor */
  private boolean _beforeFirst = true;
  /** optional save point to restore to the cursor */
  private Cursor.Savepoint _savepoint;
  /** ColumnMatcher to be used when matching column values */
  private ColumnMatcher _columnMatcher;

  public CursorBuilder(Table table) {
    _table = (TableImpl)table;
  }

  /**
   * Sets the cursor so that it will start at the beginning (unless a
   * savepoint is given).
   */
  public CursorBuilder beforeFirst() {
    _beforeFirst = true;
    return this;
  }

  /**
   * Sets the cursor so that it will start at the end (unless a savepoint is
   * given).
   */
  public CursorBuilder afterLast() {
    _beforeFirst = false;
    return this;
  }

  /**
   * Sets a savepoint to restore for the initial position of the cursor.
   */
  public CursorBuilder restoreSavepoint(Cursor.Savepoint savepoint) {
    _savepoint = savepoint;
    return this;
  }

  /**
   * Sets an index to use for the cursor.
   */
  public CursorBuilder setIndex(Index index) {
    _index = (IndexImpl)index;
    return this;
  }

  /**
   * Sets an index to use for the cursor by searching the table for an index
   * with the given name.
   * @throws IllegalArgumentException if no index can be found on the table
   *         with the given name
   */
  public CursorBuilder setIndexByName(String indexName) {
    return setIndex(_table.getIndex(indexName));
  }

  /**
   * Sets an index to use for the cursor by searching the table for an index
   * with exactly the given columns.
   * @throws IllegalArgumentException if no index can be found on the table
   *         with the given columns
   */
  public CursorBuilder setIndexByColumnNames(String... columnNames) {
    return setIndexByColumns(Arrays.asList(columnNames));
  }

  /**
   * Sets an index to use for the cursor by searching the table for an index
   * with exactly the given columns.
   * @throws IllegalArgumentException if no index can be found on the table
   *         with the given columns
   */
  public CursorBuilder setIndexByColumns(Column... columns) {
    List<String> colNames = new ArrayList<String>();
    for(Column col : columns) {
      colNames.add(col.getName());
    }
    return setIndexByColumns(colNames);
  }

  /**
   * Searches for an index with the given column names.
   */
  private CursorBuilder setIndexByColumns(List<String> searchColumns) {
    IndexImpl index = _table.findIndexForColumns(
        searchColumns, TableImpl.IndexFeature.ANY_MATCH);
    if(index == null) {
      throw new IllegalArgumentException("Index with columns " +
                                         searchColumns +
                                         " does not exist in table " + _table);
    }
    _index = index;
    return this;
  }

  /**
   * Sets the starting and ending row for a range based index cursor.
   * <p>
   * A valid index must be specified before calling this method.
   */
  public CursorBuilder setSpecificRow(Object... specificRow) {
    setStartRow(specificRow);
    setEndRow(specificRow);
    return this;
  }

  /**
   * Sets the starting and ending row for a range based index cursor to the
   * given entry (where the given values correspond to the index's columns).
   * <p>
   * A valid index must be specified before calling this method.
   */
  public CursorBuilder setSpecificEntry(Object... specificEntry) {
    if(specificEntry != null) {
      setSpecificRow(_index.constructIndexRowFromEntry(specificEntry));
    }
    return this;
  }


  /**
   * Sets the starting row for a range based index cursor.
   * <p>
   * A valid index must be specified before calling this method.
   */
  public CursorBuilder setStartRow(Object... startRow) {
    _startRow = startRow;
    return this;
  }

  /**
   * Sets the starting row for a range based index cursor to the given entry
   * (where the given values correspond to the index's columns).
   * <p>
   * A valid index must be specified before calling this method.
   */
  public CursorBuilder setStartEntry(Object... startEntry) {
    if(startEntry != null) {
      setStartRow(_index.constructPartialIndexRowFromEntry(
                      IndexData.MIN_VALUE, startEntry));
    }
    return this;
  }

  /**
   * Sets whether the starting row for a range based index cursor is inclusive
   * or exclusive.
   */
  public CursorBuilder setStartRowInclusive(boolean inclusive) {
    _startRowInclusive = inclusive;
    return this;
  }

  /**
   * Sets the ending row for a range based index cursor.
   * <p>
   * A valid index must be specified before calling this method.
   */
  public CursorBuilder setEndRow(Object... endRow) {
    _endRow = endRow;
    return this;
  }

  /**
   * Sets the ending row for a range based index cursor to the given entry
   * (where the given values correspond to the index's columns).
   * <p>
   * A valid index must be specified before calling this method.
   */
  public CursorBuilder setEndEntry(Object... endEntry) {
    if(endEntry != null) {
      setEndRow(_index.constructPartialIndexRowFromEntry(
                    IndexData.MAX_VALUE, endEntry));
    }
    return this;
  }

  /**
   * Sets whether the ending row for a range based index cursor is inclusive
   * or exclusive.
   */
  public CursorBuilder setEndRowInclusive(boolean inclusive) {
    _endRowInclusive = inclusive;
    return this;
  }

  /**
   * Sets the ColumnMatcher to use for matching row patterns.
   */
  public CursorBuilder setColumnMatcher(ColumnMatcher columnMatcher) {
    _columnMatcher = columnMatcher;
    return this;
  }

  /**
   * Sets the ColumnMatcher to an instance of CaseInsensitiveColumnMatcher
   */
  public CursorBuilder setCaseInsensitive() {
    return setColumnMatcher(CaseInsensitiveColumnMatcher.INSTANCE);
  }

  /**
   * Returns a new cursor for the table, constructed to the given
   * specifications.
   */
  public Cursor toCursor() throws IOException
  {
    CursorImpl cursor = null;
    if(_index == null) {
      cursor = CursorImpl.createCursor(_table);
    } else {
      cursor = IndexCursorImpl.createCursor(_table, _index,
                                            _startRow, _startRowInclusive,
                                            _endRow, _endRowInclusive);
    }
    cursor.setColumnMatcher(_columnMatcher);
    if(_savepoint == null) {
      if(!_beforeFirst) {
        cursor.afterLast();
      }
    } else {
      cursor.restoreSavepoint(_savepoint);
    }
    return cursor;
  }

  /**
   * Returns a new index cursor for the table, constructed to the given
   * specifications.
   */
  public IndexCursor toIndexCursor() throws IOException
  {
    return (IndexCursorImpl)toCursor();
  }

  /**
   * Creates a normal, un-indexed cursor for the given table.
   * @param table the table over which this cursor will traverse
   */
  public static Cursor createCursor(Table table) throws IOException {
    return table.newCursor().toCursor();
  }

  /**
   * Creates an indexed cursor for the given table.
   * <p>
   * Note, index based table traversal may not include all rows, as certain
   * types of indexes do not include all entries (namely, some indexes ignore
   * null entries, see {@link Index#shouldIgnoreNulls}).
   *
   * @param index index for the table which will define traversal order as
   *              well as enhance certain lookups
   */
  public static IndexCursor createCursor(Index index)
    throws IOException
  {
    return index.getTable().newCursor().setIndex(index).toIndexCursor();
  }

  /**
   * Creates an indexed cursor for the primary key cursor of the given table.
   * @param table the table over which this cursor will traverse
   */
  public static IndexCursor createPrimaryKeyCursor(Table table)
    throws IOException
  {
    return createCursor(table.getPrimaryKeyIndex());
  }

  /**
   * Creates an indexed cursor for the given table, narrowed to the given
   * range.
   * <p>
   * Note, index based table traversal may not include all rows, as certain
   * types of indexes do not include all entries (namely, some indexes ignore
   * null entries, see {@link Index#shouldIgnoreNulls}).
   *
   * @param index index for the table which will define traversal order as
   *              well as enhance certain lookups
   * @param startRow the first row of data for the cursor (inclusive), or
   *                 {@code null} for the first entry
   * @param endRow the last row of data for the cursor (inclusive), or
   *               {@code null} for the last entry
   */
  public static IndexCursor createCursor(Index index,
                                         Object[] startRow, Object[] endRow)
    throws IOException
  {
    return index.getTable().newCursor().setIndex(index)
      .setStartRow(startRow)
      .setEndRow(endRow)
      .toIndexCursor();
  }

  /**
   * Creates an indexed cursor for the given table, narrowed to the given
   * range.
   * <p>
   * Note, index based table traversal may not include all rows, as certain
   * types of indexes do not include all entries (namely, some indexes ignore
   * null entries, see {@link Index#shouldIgnoreNulls}).
   *
   * @param index index for the table which will define traversal order as
   *              well as enhance certain lookups
   * @param startRow the first row of data for the cursor, or {@code null} for
   *                 the first entry
   * @param startInclusive whether or not startRow is inclusive or exclusive
   * @param endRow the last row of data for the cursor, or {@code null} for
   *               the last entry
   * @param endInclusive whether or not endRow is inclusive or exclusive
   */
  public static IndexCursor createCursor(Index index,
                                         Object[] startRow,
                                         boolean startInclusive,
                                         Object[] endRow,
                                         boolean endInclusive)
    throws IOException
  {
    return index.getTable().newCursor().setIndex(index)
      .setStartRow(startRow)
      .setStartRowInclusive(startInclusive)
      .setEndRow(endRow)
      .setEndRowInclusive(endInclusive)
      .toIndexCursor();
  }

  /**
   * Convenience method for finding a specific row in a table which matches a
   * given row "pattern".  See {@link Cursor#findFirstRow(Map)} for details on
   * the rowPattern.
   * <p>
   * Warning, this method <i>always</i> starts searching from the beginning of
   * the Table (you cannot use it to find successive matches).
   *
   * @param table the table to search
   * @param rowPattern pattern to be used to find the row
   * @return the matching row or {@code null} if a match could not be found.
   */
  public static Row findRow(Table table, Map<String,?> rowPattern)
    throws IOException
  {
    Cursor cursor = createCursor(table);
    if(cursor.findFirstRow(rowPattern)) {
      return cursor.getCurrentRow();
    }
    return null;
  }

  /**
   * Convenience method for finding a specific row (as defined by the cursor)
   * where the index entries match the given values.  See {@link
   * IndexCursor#findRowByEntry(Object...)} for details on the entryValues.
   *
   * @param index the index to search
   * @param entryValues the column values for the index's columns.
   * @return the matching row or {@code null} if a match could not be found.
   */
  public static Row findRowByEntry(Index index, Object... entryValues)
    throws IOException
  {
    return createCursor(index).findRowByEntry(entryValues);
  }

  /**
   * Convenience method for finding a specific row by the primary key of the
   * table.  See {@link IndexCursor#findRowByEntry(Object...)} for details on
   * the entryValues.
   *
   * @param table the table to search
   * @param entryValues the column values for the table's primary key columns.
   * @return the matching row or {@code null} if a match could not be found.
   */
  public static Row findRowByPrimaryKey(Table table, Object... entryValues)
    throws IOException
  {
    return findRowByEntry(table.getPrimaryKeyIndex(), entryValues);
  }

  /**
   * Convenience method for finding a specific row in a table which matches a
   * given row "pattern".  See {@link Cursor#findFirstRow(Column,Object)} for
   * details on the pattern.
   * <p>
   * Note, a {@code null} result value is ambiguous in that it could imply no
   * match or a matching row with {@code null} for the desired value.  If
   * distinguishing this situation is important, you will need to use a Cursor
   * directly instead of this convenience method.
   *
   * @param table the table to search
   * @param column column whose value should be returned
   * @param columnPattern column being matched by the valuePattern
   * @param valuePattern value from the columnPattern which will match the
   *                     desired row
   * @return the matching row or {@code null} if a match could not be found.
   */
  public static Object findValue(Table table, Column column,
                                 Column columnPattern, Object valuePattern)
    throws IOException
  {
    Cursor cursor = createCursor(table);
    if(cursor.findFirstRow(columnPattern, valuePattern)) {
      return cursor.getCurrentRowValue(column);
    }
    return null;
  }

  /**
   * Convenience method for finding a specific row in an indexed table which
   * matches a given row "pattern".  See {@link Cursor#findFirstRow(Map)} for
   * details on the rowPattern.
   * <p>
   * Warning, this method <i>always</i> starts searching from the beginning of
   * the Table (you cannot use it to find successive matches).
   *
   * @param index index to assist the search
   * @param rowPattern pattern to be used to find the row
   * @return the matching row or {@code null} if a match could not be found.
   */
  public static Row findRow(Index index, Map<String,?> rowPattern)
    throws IOException
  {
    Cursor cursor = createCursor(index);
    if(cursor.findFirstRow(rowPattern)) {
      return cursor.getCurrentRow();
    }
    return null;
  }

  /**
   * Convenience method for finding a specific row in a table which matches a
   * given row "pattern".  See {@link Cursor#findFirstRow(Column,Object)} for
   * details on the pattern.
   * <p>
   * Note, a {@code null} result value is ambiguous in that it could imply no
   * match or a matching row with {@code null} for the desired value.  If
   * distinguishing this situation is important, you will need to use a Cursor
   * directly instead of this convenience method.
   *
   * @param index index to assist the search
   * @param column column whose value should be returned
   * @param columnPattern column being matched by the valuePattern
   * @param valuePattern value from the columnPattern which will match the
   *                     desired row
   * @return the matching row or {@code null} if a match could not be found.
   */
  public static Object findValue(Index index, Column column,
                                 Column columnPattern, Object valuePattern)
    throws IOException
  {
    Cursor cursor = createCursor(index);
    if(cursor.findFirstRow(columnPattern, valuePattern)) {
      return cursor.getCurrentRowValue(column);
    }
    return null;
  }
}