Debian Codegraph @

src/main/org/h2/index/RangeIndex.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.index;
7
8 import org.h2.api.ErrorCode;
9 import org.h2.command.query.AllColumnsForPlan;
10 import org.h2.engine.SessionLocal;
11 import org.h2.message.DbException;
12 import org.h2.result.Row;
13 import org.h2.result.SearchRow;
14 import org.h2.result.SortOrder;
15 import org.h2.table.IndexColumn;
16 import org.h2.table.RangeTable;
17 import org.h2.table.TableFilter;
18 import org.h2.value.Value;
19 import org.h2.value.ValueBigint;
20
21 /**
22 * An index for the SYSTEM_RANGE table.
23 * This index can only scan through all rows, search is not supported.
24 */
25 public class RangeIndex extends VirtualTableIndex {
26
27 private final RangeTable rangeTable;
28
29 public RangeIndex(RangeTable table, IndexColumn[] columns) {
30 super(table, "RANGE_INDEX", columns);
31 this.rangeTable = table;
32 }
33
34 @Override
35 public Cursor find(SessionLocal session, SearchRow first, SearchRow last) {
36 long min = rangeTable.getMin(session);
37 long max = rangeTable.getMax(session);
38 long step = rangeTable.getStep(session);
39 if (step == 0L) {
40 throw DbException.get(ErrorCode.STEP_SIZE_MUST_NOT_BE_ZERO);
41 }
42 if (first != null) {
43 try {
44 long v = first.getValue(0).getLong();
45 if (step > 0) {
46 if (v > min) {
47 min += (v - min + step - 1) / step * step;
48 }
49 } else if (v > max) {
50 max = v;
51 }
52 } catch (DbException e) {
53 // error when converting the value - ignore
54 }
55 }
56 if (last != null) {
57 try {
58 long v = last.getValue(0).getLong();
59 if (step > 0) {
60 if (v < max) {
61 max = v;
62 }
63 } else if (v < min) {
64 min -= (min - v - step - 1) / step * step;
65 }
66 } catch (DbException e) {
67 // error when converting the value - ignore
68 }
69 }
70 return new RangeCursor(min, max, step);
71 }
72
73 @Override
74 public double getCost(SessionLocal session, int[] masks,
75 TableFilter[] filters, int filter, SortOrder sortOrder,
76 AllColumnsForPlan allColumnsSet) {
77 return 1d;
78 }
79
80 @Override
81 public String getCreateSQL() {
82 return null;
83 }
84
85 @Override
86 public boolean canGetFirstOrLast() {
87 return true;
88 }
89
90 @Override
91 public Cursor findFirstOrLast(SessionLocal session, boolean first) {
92 long min = rangeTable.getMin(session);
93 long max = rangeTable.getMax(session);
94 long step = rangeTable.getStep(session);
95 if (step == 0L) {
96 throw DbException.get(ErrorCode.STEP_SIZE_MUST_NOT_BE_ZERO);
97 }
98 return new SingleRowCursor((step > 0 ? min <= max : min >= max)
99 ? Row.get(new Value[]{ ValueBigint.get(first ^ min >= max ? min : max) }, 1) : null);
100 }
101
102 @Override
103 public String getPlanSQL() {
104 return "range index";
105 }
106
107 }