001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import java.io.IOException;
021import java.util.ArrayList;
022import java.util.HashMap;
023import java.util.List;
024import java.util.Map;
025import java.util.NavigableSet;
026import java.util.TreeMap;
027import java.util.TreeSet;
028import java.util.stream.Collectors;
029import org.apache.hadoop.hbase.HConstants;
030import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
031import org.apache.hadoop.hbase.filter.Filter;
032import org.apache.hadoop.hbase.filter.IncompatibleFilterException;
033import org.apache.hadoop.hbase.io.TimeRange;
034import org.apache.hadoop.hbase.security.access.Permission;
035import org.apache.hadoop.hbase.security.visibility.Authorizations;
036import org.apache.hadoop.hbase.util.Bytes;
037import org.apache.yetus.audience.InterfaceAudience;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041/**
042 * Used to perform Scan operations.
043 * <p>
044 * All operations are identical to {@link Get} with the exception of instantiation. Rather than
045 * specifying a single row, an optional startRow and stopRow may be defined. If rows are not
046 * specified, the Scanner will iterate over all rows.
047 * <p>
048 * To get all columns from all rows of a Table, create an instance with no constraints; use the
049 * {@link #Scan()} constructor. To constrain the scan to specific column families, call
050 * {@link #addFamily(byte[]) addFamily} for each family to retrieve on your Scan instance.
051 * <p>
052 * To get specific columns, call {@link #addColumn(byte[], byte[]) addColumn} for each column to
053 * retrieve.
054 * <p>
055 * To only retrieve columns within a specific range of version timestamps, call
056 * {@link #setTimeRange(long, long) setTimeRange}.
057 * <p>
058 * To only retrieve columns with a specific timestamp, call {@link #setTimestamp(long) setTimestamp}
059 * .
060 * <p>
061 * To limit the number of versions of each column to be returned, call {@link #readVersions(int)}.
062 * <p>
063 * To limit the maximum number of values returned for each call to next(), call
064 * {@link #setBatch(int) setBatch}.
065 * <p>
066 * To add a filter, call {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}.
067 * <p>
068 * For small scan, it is deprecated in 2.0.0. Now we have a {@link #setLimit(int)} method in Scan
069 * object which is used to tell RS how many rows we want. If the rows return reaches the limit, the
070 * RS will close the RegionScanner automatically. And we will also fetch data when openScanner in
071 * the new implementation, this means we can also finish a scan operation in one rpc call. And we
072 * have also introduced a {@link #setReadType(ReadType)} method. You can use this method to tell RS
073 * to use pread explicitly.
074 * <p>
075 * Expert: To explicitly disable server-side block caching for this scan, execute
076 * {@link #setCacheBlocks(boolean)}.
077 * <p>
078 * <em>Note:</em> Usage alters Scan instances. Internally, attributes are updated as the Scan runs
079 * and if enabled, metrics accumulate in the Scan instance. Be aware this is the case when you go to
080 * clone a Scan instance or if you go to reuse a created Scan instance; safer is create a Scan
081 * instance per usage.
082 */
083@InterfaceAudience.Public
084public class Scan extends Query {
085  private static final Logger LOG = LoggerFactory.getLogger(Scan.class);
086
087  private static final String RAW_ATTR = "_raw_";
088
089  private byte[] startRow = HConstants.EMPTY_START_ROW;
090  private boolean includeStartRow = true;
091  private byte[] stopRow = HConstants.EMPTY_END_ROW;
092  private boolean includeStopRow = false;
093  private int maxVersions = 1;
094  private int batch = -1;
095
096  /**
097   * Partial {@link Result}s are {@link Result}s must be combined to form a complete {@link Result}.
098   * The {@link Result}s had to be returned in fragments (i.e. as partials) because the size of the
099   * cells in the row exceeded max result size on the server. Typically partial results will be
100   * combined client side into complete results before being delivered to the caller. However, if
101   * this flag is set, the caller is indicating that they do not mind seeing partial results (i.e.
102   * they understand that the results returned from the Scanner may only represent part of a
103   * particular row). In such a case, any attempt to combine the partials into a complete result on
104   * the client side will be skipped, and the caller will be able to see the exact results returned
105   * from the server.
106   */
107  private boolean allowPartialResults = false;
108
109  private int storeLimit = -1;
110  private int storeOffset = 0;
111
112  private static final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable";
113
114  // If an application wants to use multiple scans over different tables each scan must
115  // define this attribute with the appropriate table name by calling
116  // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName))
117  static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name";
118  static private final String SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE =
119    "scan.attributes.metrics.byregion.enable";
120
121  /**
122   * -1 means no caching specified and the value of {@link HConstants#HBASE_CLIENT_SCANNER_CACHING}
123   * (default to {@link HConstants#DEFAULT_HBASE_CLIENT_SCANNER_CACHING}) will be used
124   */
125  private int caching = -1;
126  private long maxResultSize = -1;
127  private boolean cacheBlocks = true;
128  private boolean reversed = false;
129  private TimeRange tr = TimeRange.allTime();
130  private Map<byte[], NavigableSet<byte[]>> familyMap =
131    new TreeMap<byte[], NavigableSet<byte[]>>(Bytes.BYTES_COMPARATOR);
132  private Boolean asyncPrefetch = null;
133
134  /**
135   * Parameter name for client scanner sync/async prefetch toggle. When using async scanner,
136   * prefetching data from the server is done at the background. The parameter currently won't have
137   * any effect in the case that the user has set Scan#setSmall or Scan#setReversed
138   */
139  public static final String HBASE_CLIENT_SCANNER_ASYNC_PREFETCH =
140    "hbase.client.scanner.async.prefetch";
141
142  /**
143   * Default value of {@link #HBASE_CLIENT_SCANNER_ASYNC_PREFETCH}.
144   */
145  public static final boolean DEFAULT_HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = false;
146
147  /**
148   * The mvcc read point to use when open a scanner. Remember to clear it after switching regions as
149   * the mvcc is only valid within region scope.
150   */
151  private long mvccReadPoint = -1L;
152
153  /**
154   * The number of rows we want for this scan. We will terminate the scan if the number of return
155   * rows reaches this value.
156   */
157  private int limit = -1;
158
159  /**
160   * Control whether to use pread at server side.
161   */
162  private ReadType readType = ReadType.DEFAULT;
163
164  private boolean needCursorResult = false;
165
166  /**
167   * Create a Scan operation across all rows.
168   */
169  public Scan() {
170  }
171
172  /**
173   * Creates a new instance of this class while copying all values.
174   * @param scan The scan instance to copy from.
175   * @throws IOException When copying the values fails.
176   */
177  public Scan(Scan scan) throws IOException {
178    startRow = scan.getStartRow();
179    includeStartRow = scan.includeStartRow();
180    stopRow = scan.getStopRow();
181    includeStopRow = scan.includeStopRow();
182    maxVersions = scan.getMaxVersions();
183    batch = scan.getBatch();
184    storeLimit = scan.getMaxResultsPerColumnFamily();
185    storeOffset = scan.getRowOffsetPerColumnFamily();
186    caching = scan.getCaching();
187    maxResultSize = scan.getMaxResultSize();
188    cacheBlocks = scan.getCacheBlocks();
189    filter = scan.getFilter(); // clone?
190    loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
191    consistency = scan.getConsistency();
192    this.setIsolationLevel(scan.getIsolationLevel());
193    reversed = scan.isReversed();
194    asyncPrefetch = scan.isAsyncPrefetch();
195    allowPartialResults = scan.getAllowPartialResults();
196    tr = scan.getTimeRange(); // TimeRange is immutable
197    Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap();
198    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) {
199      byte[] fam = entry.getKey();
200      NavigableSet<byte[]> cols = entry.getValue();
201      if (cols != null && cols.size() > 0) {
202        for (byte[] col : cols) {
203          addColumn(fam, col);
204        }
205      } else {
206        addFamily(fam);
207      }
208    }
209    for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) {
210      setAttribute(attr.getKey(), attr.getValue());
211    }
212    for (Map.Entry<byte[], TimeRange> entry : scan.getColumnFamilyTimeRange().entrySet()) {
213      TimeRange tr = entry.getValue();
214      setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
215    }
216    this.mvccReadPoint = scan.getMvccReadPoint();
217    this.limit = scan.getLimit();
218    this.needCursorResult = scan.isNeedCursorResult();
219    setPriority(scan.getPriority());
220    readType = scan.getReadType();
221    super.setReplicaId(scan.getReplicaId());
222    super.setQueryMetricsEnabled(scan.isQueryMetricsEnabled());
223  }
224
225  /**
226   * Builds a scan object with the same specs as get.
227   * @param get get to model scan after
228   */
229  public Scan(Get get) {
230    this.startRow = get.getRow();
231    this.includeStartRow = true;
232    this.stopRow = get.getRow();
233    this.includeStopRow = true;
234    this.filter = get.getFilter();
235    this.cacheBlocks = get.getCacheBlocks();
236    this.maxVersions = get.getMaxVersions();
237    this.storeLimit = get.getMaxResultsPerColumnFamily();
238    this.storeOffset = get.getRowOffsetPerColumnFamily();
239    this.tr = get.getTimeRange();
240    this.familyMap = get.getFamilyMap();
241    this.asyncPrefetch = false;
242    this.consistency = get.getConsistency();
243    this.setIsolationLevel(get.getIsolationLevel());
244    this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue();
245    for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) {
246      setAttribute(attr.getKey(), attr.getValue());
247    }
248    for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) {
249      TimeRange tr = entry.getValue();
250      setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax());
251    }
252    this.mvccReadPoint = -1L;
253    setPriority(get.getPriority());
254    super.setReplicaId(get.getReplicaId());
255    super.setQueryMetricsEnabled(get.isQueryMetricsEnabled());
256  }
257
258  public boolean isGetScan() {
259    return includeStartRow && includeStopRow
260      && ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow);
261  }
262
263  /**
264   * Get all columns from the specified family.
265   * <p>
266   * Overrides previous calls to addColumn for this family.
267   * @param family family name
268   */
269  public Scan addFamily(byte[] family) {
270    familyMap.remove(family);
271    familyMap.put(family, null);
272    return this;
273  }
274
275  /**
276   * Get the column from the specified family with the specified qualifier.
277   * <p>
278   * Overrides previous calls to addFamily for this family.
279   * @param family    family name
280   * @param qualifier column qualifier
281   */
282  public Scan addColumn(byte[] family, byte[] qualifier) {
283    NavigableSet<byte[]> set = familyMap.get(family);
284    if (set == null) {
285      set = new TreeSet<>(Bytes.BYTES_COMPARATOR);
286      familyMap.put(family, set);
287    }
288    if (qualifier == null) {
289      qualifier = HConstants.EMPTY_BYTE_ARRAY;
290    }
291    set.add(qualifier);
292    return this;
293  }
294
295  /**
296   * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp). Note,
297   * default maximum versions to return is 1. If your time range spans more than one version and you
298   * want all versions returned, up the number of versions beyond the default.
299   * @param minStamp minimum timestamp value, inclusive
300   * @param maxStamp maximum timestamp value, exclusive
301   * @see #readAllVersions()
302   * @see #readVersions(int)
303   */
304  public Scan setTimeRange(long minStamp, long maxStamp) throws IOException {
305    tr = TimeRange.between(minStamp, maxStamp);
306    return this;
307  }
308
309  /**
310   * Get versions of columns with the specified timestamp. Note, default maximum versions to return
311   * is 1. If your time range spans more than one version and you want all versions returned, up the
312   * number of versions beyond the defaut.
313   * @param timestamp version timestamp
314   * @see #readAllVersions()
315   * @see #readVersions(int)
316   */
317  public Scan setTimestamp(long timestamp) {
318    try {
319      tr = TimeRange.at(timestamp);
320    } catch (Exception e) {
321      // This should never happen, unless integer overflow or something extremely wrong...
322      LOG.error("TimeRange failed, likely caused by integer overflow. ", e);
323      throw e;
324    }
325
326    return this;
327  }
328
329  @Override
330  public Scan setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) {
331    super.setColumnFamilyTimeRange(cf, minStamp, maxStamp);
332    return this;
333  }
334
335  /**
336   * Set the start row of the scan.
337   * <p>
338   * If the specified row does not exist, the Scanner will start from the next closest row after the
339   * specified row.
340   * <p>
341   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
342   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
343   * unexpected or even undefined.
344   * </p>
345   * @param startRow row to start scanner at or after
346   * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length
347   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
348   */
349  public Scan withStartRow(byte[] startRow) {
350    return withStartRow(startRow, true);
351  }
352
353  /**
354   * Set the start row of the scan.
355   * <p>
356   * If the specified row does not exist, or the {@code inclusive} is {@code false}, the Scanner
357   * will start from the next closest row after the specified row.
358   * <p>
359   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
360   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
361   * unexpected or even undefined.
362   * </p>
363   * @param startRow  row to start scanner at or after
364   * @param inclusive whether we should include the start row when scan
365   * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length
366   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
367   */
368  public Scan withStartRow(byte[] startRow, boolean inclusive) {
369    if (Bytes.len(startRow) > HConstants.MAX_ROW_LENGTH) {
370      throw new IllegalArgumentException("startRow's length must be less than or equal to "
371        + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key.");
372    }
373    this.startRow = startRow;
374    this.includeStartRow = inclusive;
375    return this;
376  }
377
378  /**
379   * Set the stop row of the scan.
380   * <p>
381   * The scan will include rows that are lexicographically less than the provided stopRow.
382   * <p>
383   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
384   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
385   * unexpected or even undefined.
386   * </p>
387   * @param stopRow row to end at (exclusive)
388   * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length
389   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
390   */
391  public Scan withStopRow(byte[] stopRow) {
392    return withStopRow(stopRow, false);
393  }
394
395  /**
396   * Set the stop row of the scan.
397   * <p>
398   * The scan will include rows that are lexicographically less than (or equal to if
399   * {@code inclusive} is {@code true}) the provided stopRow.
400   * <p>
401   * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or
402   * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result
403   * unexpected or even undefined.
404   * </p>
405   * @param stopRow   row to end at
406   * @param inclusive whether we should include the stop row when scan
407   * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length
408   *                                  exceeds {@link HConstants#MAX_ROW_LENGTH})
409   */
410  public Scan withStopRow(byte[] stopRow, boolean inclusive) {
411    if (Bytes.len(stopRow) > HConstants.MAX_ROW_LENGTH) {
412      throw new IllegalArgumentException("stopRow's length must be less than or equal to "
413        + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key.");
414    }
415    this.stopRow = stopRow;
416    this.includeStopRow = inclusive;
417    return this;
418  }
419
420  /**
421   * <p>
422   * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey
423   * starts with the specified prefix.
424   * </p>
425   * <p>
426   * This is a utility method that converts the desired rowPrefix into the appropriate values for
427   * the startRow and stopRow to achieve the desired result.
428   * </p>
429   * <p>
430   * This can safely be used in combination with setFilter.
431   * </p>
432   * <p>
433   * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such
434   * a combination will yield unexpected and even undefined results.
435   * </p>
436   * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.)
437   * @deprecated since 2.5.0, will be removed in 4.0.0. The name of this method is considered to be
438   *             confusing as it does not use a {@link Filter} but uses setting the startRow and
439   *             stopRow instead. Use {@link #setStartStopRowForPrefixScan(byte[])} instead.
440   */
441  @Deprecated
442  public Scan setRowPrefixFilter(byte[] rowPrefix) {
443    return setStartStopRowForPrefixScan(rowPrefix);
444  }
445
446  /**
447   * <p>
448   * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey
449   * starts with the specified prefix.
450   * </p>
451   * <p>
452   * This is a utility method that converts the desired rowPrefix into the appropriate values for
453   * the startRow and stopRow to achieve the desired result.
454   * </p>
455   * <p>
456   * This can safely be used in combination with setFilter.
457   * </p>
458   * <p>
459   * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such
460   * a combination will yield unexpected and even undefined results.
461   * </p>
462   * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.)
463   */
464  public Scan setStartStopRowForPrefixScan(byte[] rowPrefix) {
465    if (rowPrefix == null) {
466      withStartRow(HConstants.EMPTY_START_ROW);
467      withStopRow(HConstants.EMPTY_END_ROW);
468    } else {
469      this.withStartRow(rowPrefix);
470      this.withStopRow(ClientUtil.calculateTheClosestNextRowKeyForPrefix(rowPrefix));
471    }
472    return this;
473  }
474
475  /**
476   * Get all available versions.
477   */
478  public Scan readAllVersions() {
479    this.maxVersions = Integer.MAX_VALUE;
480    return this;
481  }
482
483  /**
484   * Get up to the specified number of versions of each column.
485   * @param versions specified number of versions for each column
486   */
487  public Scan readVersions(int versions) {
488    this.maxVersions = versions;
489    return this;
490  }
491
492  /**
493   * Set the maximum number of cells to return for each call to next(). Callers should be aware that
494   * this is not equivalent to calling {@link #setAllowPartialResults(boolean)}. If you don't allow
495   * partial results, the number of cells in each Result must equal to your batch setting unless it
496   * is the last Result for current row. So this method is helpful in paging queries. If you just
497   * want to prevent OOM at client, use setAllowPartialResults(true) is better.
498   * @param batch the maximum number of values
499   * @see Result#mayHaveMoreCellsInRow()
500   */
501  public Scan setBatch(int batch) {
502    if (this.hasFilter() && this.filter.hasFilterRow()) {
503      throw new IncompatibleFilterException(
504        "Cannot set batch on a scan using a filter" + " that returns true for filter.hasFilterRow");
505    }
506    this.batch = batch;
507    return this;
508  }
509
510  /**
511   * Set the maximum number of values to return per row per Column Family
512   * @param limit the maximum number of values returned / row / CF
513   */
514  public Scan setMaxResultsPerColumnFamily(int limit) {
515    this.storeLimit = limit;
516    return this;
517  }
518
519  /**
520   * Set offset for the row per Column Family.
521   * @param offset is the number of kvs that will be skipped.
522   */
523  public Scan setRowOffsetPerColumnFamily(int offset) {
524    this.storeOffset = offset;
525    return this;
526  }
527
528  /**
529   * Set the number of rows for caching that will be passed to scanners. If not set, the
530   * Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will apply. Higher
531   * caching values will enable faster scanners but will use more memory.
532   * @param caching the number of rows for caching
533   */
534  public Scan setCaching(int caching) {
535    this.caching = caching;
536    return this;
537  }
538
539  /** Returns the maximum result size in bytes. See {@link #setMaxResultSize(long)} */
540  public long getMaxResultSize() {
541    return maxResultSize;
542  }
543
544  /**
545   * Set the maximum result size. The default is -1; this means that no specific maximum result size
546   * will be set for this scan, and the global configured value will be used instead. (Defaults to
547   * unlimited).
548   * @param maxResultSize The maximum result size in bytes.
549   */
550  public Scan setMaxResultSize(long maxResultSize) {
551    this.maxResultSize = maxResultSize;
552    return this;
553  }
554
555  @Override
556  public Scan setFilter(Filter filter) {
557    if (filter != null && filter.hasFilterRow() && this.batch > 0) {
558      throw new IncompatibleFilterException(
559        "Cannot set a filter that returns true for filter.hasFilterRow on a scan with batch set");
560    }
561    super.setFilter(filter);
562    return this;
563  }
564
565  /**
566   * Setting the familyMap
567   * @param familyMap map of family to qualifier
568   */
569  public Scan setFamilyMap(Map<byte[], NavigableSet<byte[]>> familyMap) {
570    this.familyMap = familyMap;
571    return this;
572  }
573
574  /**
575   * Getting the familyMap
576   */
577  public Map<byte[], NavigableSet<byte[]>> getFamilyMap() {
578    return this.familyMap;
579  }
580
581  /** Returns the number of families in familyMap */
582  public int numFamilies() {
583    if (hasFamilies()) {
584      return this.familyMap.size();
585    }
586    return 0;
587  }
588
589  /** Returns true if familyMap is non empty, false otherwise */
590  public boolean hasFamilies() {
591    return !this.familyMap.isEmpty();
592  }
593
594  /** Returns the keys of the familyMap */
595  public byte[][] getFamilies() {
596    if (hasFamilies()) {
597      return this.familyMap.keySet().toArray(new byte[0][0]);
598    }
599    return null;
600  }
601
602  /** Returns the startrow */
603  public byte[] getStartRow() {
604    return this.startRow;
605  }
606
607  /** Returns if we should include start row when scan */
608  public boolean includeStartRow() {
609    return includeStartRow;
610  }
611
612  /** Returns the stoprow */
613  public byte[] getStopRow() {
614    return this.stopRow;
615  }
616
617  /** Returns if we should include stop row when scan */
618  public boolean includeStopRow() {
619    return includeStopRow;
620  }
621
622  /** Returns the max number of versions to fetch */
623  public int getMaxVersions() {
624    return this.maxVersions;
625  }
626
627  /** Returns maximum number of values to return for a single call to next() */
628  public int getBatch() {
629    return this.batch;
630  }
631
632  /** Returns maximum number of values to return per row per CF */
633  public int getMaxResultsPerColumnFamily() {
634    return this.storeLimit;
635  }
636
637  /**
638   * Method for retrieving the scan's offset per row per column family (#kvs to be skipped)
639   * @return row offset
640   */
641  public int getRowOffsetPerColumnFamily() {
642    return this.storeOffset;
643  }
644
645  /** Returns caching the number of rows fetched when calling next on a scanner */
646  public int getCaching() {
647    return this.caching;
648  }
649
650  /** Returns TimeRange */
651  public TimeRange getTimeRange() {
652    return this.tr;
653  }
654
655  /** Returns RowFilter */
656  @Override
657  public Filter getFilter() {
658    return filter;
659  }
660
661  /** Returns true is a filter has been specified, false if not */
662  public boolean hasFilter() {
663    return filter != null;
664  }
665
666  /**
667   * Set whether blocks should be cached for this Scan.
668   * <p>
669   * This is true by default. When true, default settings of the table and family are used (this
670   * will never override caching blocks if the block cache is disabled for that family or entirely).
671   * @param cacheBlocks if false, default settings are overridden and blocks will not be cached
672   */
673  public Scan setCacheBlocks(boolean cacheBlocks) {
674    this.cacheBlocks = cacheBlocks;
675    return this;
676  }
677
678  /**
679   * Get whether blocks should be cached for this Scan.
680   * @return true if default caching should be used, false if blocks should not be cached
681   */
682  public boolean getCacheBlocks() {
683    return cacheBlocks;
684  }
685
686  /**
687   * Set whether this scan is a reversed one
688   * <p>
689   * This is false by default which means forward(normal) scan.
690   * @param reversed if true, scan will be backward order
691   */
692  public Scan setReversed(boolean reversed) {
693    this.reversed = reversed;
694    return this;
695  }
696
697  /**
698   * Get whether this scan is a reversed one.
699   * @return true if backward scan, false if forward(default) scan
700   */
701  public boolean isReversed() {
702    return reversed;
703  }
704
705  /**
706   * Setting whether the caller wants to see the partial results when server returns
707   * less-than-expected cells. It is helpful while scanning a huge row to prevent OOM at client. By
708   * default this value is false and the complete results will be assembled client side before being
709   * delivered to the caller.
710   * @see Result#mayHaveMoreCellsInRow()
711   * @see #setBatch(int)
712   */
713  public Scan setAllowPartialResults(final boolean allowPartialResults) {
714    this.allowPartialResults = allowPartialResults;
715    return this;
716  }
717
718  /**
719   * Returns true when the constructor of this scan understands that the results they will see may
720   * only represent a partial portion of a row. The entire row would be retrieved by subsequent
721   * calls to {@link ResultScanner#next()}
722   */
723  public boolean getAllowPartialResults() {
724    return allowPartialResults;
725  }
726
727  @Override
728  public Scan setLoadColumnFamiliesOnDemand(boolean value) {
729    super.setLoadColumnFamiliesOnDemand(value);
730    return this;
731  }
732
733  /**
734   * Compile the table and column family (i.e. schema) information into a String. Useful for parsing
735   * and aggregation by debugging, logging, and administration tools.
736   */
737  @Override
738  public Map<String, Object> getFingerprint() {
739    Map<String, Object> map = new HashMap<>();
740    List<String> families = new ArrayList<>();
741    if (this.familyMap.isEmpty()) {
742      map.put("families", "ALL");
743      return map;
744    } else {
745      map.put("families", families);
746    }
747    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) {
748      families.add(Bytes.toStringBinary(entry.getKey()));
749    }
750    return map;
751  }
752
753  /**
754   * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a
755   * Map along with the fingerprinted information. Useful for debugging, logging, and administration
756   * tools.
757   * @param maxCols a limit on the number of columns output prior to truncation
758   */
759  @Override
760  public Map<String, Object> toMap(int maxCols) {
761    // start with the fingerprint map and build on top of it
762    Map<String, Object> map = getFingerprint();
763    // map from families to column list replaces fingerprint's list of families
764    Map<String, List<String>> familyColumns = new HashMap<>();
765    map.put("families", familyColumns);
766    // add scalar information first
767    map.put("startRow", Bytes.toStringBinary(this.startRow));
768    map.put("stopRow", Bytes.toStringBinary(this.stopRow));
769    map.put("maxVersions", this.maxVersions);
770    map.put("batch", this.batch);
771    map.put("caching", this.caching);
772    map.put("maxResultSize", this.maxResultSize);
773    map.put("cacheBlocks", this.cacheBlocks);
774    map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand);
775    List<Long> timeRange = new ArrayList<>(2);
776    timeRange.add(this.tr.getMin());
777    timeRange.add(this.tr.getMax());
778    map.put("timeRange", timeRange);
779    int colCount = 0;
780    // iterate through affected families and list out up to maxCols columns
781    for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) {
782      List<String> columns = new ArrayList<>();
783      familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns);
784      if (entry.getValue() == null) {
785        colCount++;
786        --maxCols;
787        columns.add("ALL");
788      } else {
789        colCount += entry.getValue().size();
790        if (maxCols <= 0) {
791          continue;
792        }
793        for (byte[] column : entry.getValue()) {
794          if (--maxCols <= 0) {
795            continue;
796          }
797          columns.add(Bytes.toStringBinary(column));
798        }
799      }
800    }
801    map.put("totalColumns", colCount);
802    if (this.filter != null) {
803      map.put("filter", this.filter.toString());
804    }
805    // add the id if set
806    if (getId() != null) {
807      map.put("id", getId());
808    }
809    map.put("includeStartRow", includeStartRow);
810    map.put("includeStopRow", includeStopRow);
811    map.put("allowPartialResults", allowPartialResults);
812    map.put("storeLimit", storeLimit);
813    map.put("storeOffset", storeOffset);
814    map.put("reversed", reversed);
815    if (null != asyncPrefetch) {
816      map.put("asyncPrefetch", asyncPrefetch);
817    }
818    map.put("mvccReadPoint", mvccReadPoint);
819    map.put("limit", limit);
820    map.put("readType", readType);
821    map.put("needCursorResult", needCursorResult);
822    map.put("targetReplicaId", targetReplicaId);
823    map.put("consistency", consistency);
824    if (!colFamTimeRangeMap.isEmpty()) {
825      Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream()
826        .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> {
827          TimeRange value = e.getValue();
828          List<Long> rangeList = new ArrayList<>();
829          rangeList.add(value.getMin());
830          rangeList.add(value.getMax());
831          return rangeList;
832        }));
833
834      map.put("colFamTimeRangeMap", colFamTimeRangeMapStr);
835    }
836    map.put("priority", getPriority());
837    map.put("queryMetricsEnabled", queryMetricsEnabled);
838    return map;
839  }
840
841  /**
842   * Enable/disable "raw" mode for this scan. If "raw" is enabled the scan will return all delete
843   * marker and deleted rows that have not been collected, yet. This is mostly useful for Scan on
844   * column families that have KEEP_DELETED_ROWS enabled. It is an error to specify any column when
845   * "raw" is set.
846   * @param raw True/False to enable/disable "raw" mode.
847   */
848  public Scan setRaw(boolean raw) {
849    setAttribute(RAW_ATTR, Bytes.toBytes(raw));
850    return this;
851  }
852
853  /** Returns True if this Scan is in "raw" mode. */
854  public boolean isRaw() {
855    byte[] attr = getAttribute(RAW_ATTR);
856    return attr == null ? false : Bytes.toBoolean(attr);
857  }
858
859  @Override
860  public Scan setAttribute(String name, byte[] value) {
861    super.setAttribute(name, value);
862    return this;
863  }
864
865  @Override
866  public Scan setId(String id) {
867    super.setId(id);
868    return this;
869  }
870
871  @Override
872  public Scan setAuthorizations(Authorizations authorizations) {
873    super.setAuthorizations(authorizations);
874    return this;
875  }
876
877  @Override
878  public Scan setACL(Map<String, Permission> perms) {
879    super.setACL(perms);
880    return this;
881  }
882
883  @Override
884  public Scan setACL(String user, Permission perms) {
885    super.setACL(user, perms);
886    return this;
887  }
888
889  @Override
890  public Scan setConsistency(Consistency consistency) {
891    super.setConsistency(consistency);
892    return this;
893  }
894
895  @Override
896  public Scan setReplicaId(int Id) {
897    super.setReplicaId(Id);
898    return this;
899  }
900
901  @Override
902  public Scan setIsolationLevel(IsolationLevel level) {
903    super.setIsolationLevel(level);
904    return this;
905  }
906
907  @Override
908  public Scan setPriority(int priority) {
909    super.setPriority(priority);
910    return this;
911  }
912
913  /**
914   * Enable collection of {@link ScanMetrics}. For advanced users. While disabling scan metrics,
915   * will also disable region level scan metrics.
916   * @param enabled Set to true to enable accumulating scan metrics
917   */
918  public Scan setScanMetricsEnabled(final boolean enabled) {
919    setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled)));
920    if (!enabled) {
921      setEnableScanMetricsByRegion(false);
922    }
923    return this;
924  }
925
926  /** Returns True if collection of scan metrics is enabled. For advanced users. */
927  public boolean isScanMetricsEnabled() {
928    byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE);
929    return attr == null ? false : Bytes.toBoolean(attr);
930  }
931
932  public Boolean isAsyncPrefetch() {
933    return asyncPrefetch;
934  }
935
936  /**
937   * @deprecated Since 3.0.0, will be removed in 4.0.0. After building sync client upon async
938   *             client, the implementation is always 'async prefetch', so this flag is useless now.
939   */
940  @Deprecated
941  public Scan setAsyncPrefetch(boolean asyncPrefetch) {
942    this.asyncPrefetch = asyncPrefetch;
943    return this;
944  }
945
946  /** Returns the limit of rows for this scan */
947  public int getLimit() {
948    return limit;
949  }
950
951  /**
952   * Set the limit of rows for this scan. We will terminate the scan if the number of returned rows
953   * reaches this value.
954   * <p>
955   * This condition will be tested at last, after all other conditions such as stopRow, filter, etc.
956   * @param limit the limit of rows for this scan
957   */
958  public Scan setLimit(int limit) {
959    this.limit = limit;
960    return this;
961  }
962
963  /**
964   * Call this when you only want to get one row. It will set {@code limit} to {@code 1}, and also
965   * set {@code readType} to {@link ReadType#PREAD}.
966   */
967  public Scan setOneRowLimit() {
968    return setLimit(1).setReadType(ReadType.PREAD);
969  }
970
971  @InterfaceAudience.Public
972  public enum ReadType {
973    DEFAULT,
974    STREAM,
975    PREAD
976  }
977
978  /** Returns the read type for this scan */
979  public ReadType getReadType() {
980    return readType;
981  }
982
983  /**
984   * Set the read type for this scan.
985   * <p>
986   * Notice that we may choose to use pread even if you specific {@link ReadType#STREAM} here. For
987   * example, we will always use pread if this is a get scan.
988   */
989  public Scan setReadType(ReadType readType) {
990    this.readType = readType;
991    return this;
992  }
993
994  /**
995   * Get the mvcc read point used to open a scanner.
996   */
997  long getMvccReadPoint() {
998    return mvccReadPoint;
999  }
1000
1001  /**
1002   * Set the mvcc read point used to open a scanner.
1003   */
1004  Scan setMvccReadPoint(long mvccReadPoint) {
1005    this.mvccReadPoint = mvccReadPoint;
1006    return this;
1007  }
1008
1009  /**
1010   * Set the mvcc read point to -1 which means do not use it.
1011   */
1012  Scan resetMvccReadPoint() {
1013    return setMvccReadPoint(-1L);
1014  }
1015
1016  /**
1017   * When the server is slow or we scan a table with many deleted data or we use a sparse filter,
1018   * the server will response heartbeat to prevent timeout. However the scanner will return a Result
1019   * only when client can do it. So if there are many heartbeats, the blocking time on
1020   * ResultScanner#next() may be very long, which is not friendly to online services. Set this to
1021   * true then you can get a special Result whose #isCursor() returns true and is not contains any
1022   * real data. It only tells you where the server has scanned. You can call next to continue
1023   * scanning or open a new scanner with this row key as start row whenever you want. Users can get
1024   * a cursor when and only when there is a response from the server but we can not return a Result
1025   * to users, for example, this response is a heartbeat or there are partial cells but users do not
1026   * allow partial result. Now the cursor is in row level which means the special Result will only
1027   * contains a row key. {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor}
1028   */
1029  public Scan setNeedCursorResult(boolean needCursorResult) {
1030    this.needCursorResult = needCursorResult;
1031    return this;
1032  }
1033
1034  public boolean isNeedCursorResult() {
1035    return needCursorResult;
1036  }
1037
1038  /**
1039   * Create a new Scan with a cursor. It only set the position information like start row key. The
1040   * others (like cfs, stop row, limit) should still be filled in by the user.
1041   * {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor}
1042   */
1043  public static Scan createScanFromCursor(Cursor cursor) {
1044    return new Scan().withStartRow(cursor.getRow());
1045  }
1046
1047  /**
1048   * Enables region level scan metrics. If scan metrics are disabled then first enables scan metrics
1049   * followed by region level scan metrics.
1050   * @param enable Set to true to enable region level scan metrics.
1051   */
1052  public Scan setEnableScanMetricsByRegion(final boolean enable) {
1053    if (enable) {
1054      setScanMetricsEnabled(true);
1055    }
1056    setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE, Bytes.toBytes(enable));
1057    return this;
1058  }
1059
1060  public boolean isScanMetricsByRegionEnabled() {
1061    byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE);
1062    return attr != null && Bytes.toBoolean(attr);
1063  }
1064}