Debian Codegraph @

src/main/org/h2/mvstore/db/MVSecondaryIndex.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.mvstore.db;
7
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Objects;
11 import java.util.PriorityQueue;
12 import java.util.Queue;
13 import org.h2.api.ErrorCode;
14 import org.h2.command.query.AllColumnsForPlan;
15 import org.h2.engine.Database;
16 import org.h2.engine.SessionLocal;
17 import org.h2.index.Cursor;
18 import org.h2.index.IndexType;
19 import org.h2.index.SingleRowCursor;
20 import org.h2.message.DbException;
21 import org.h2.mvstore.MVMap;
22 import org.h2.mvstore.MVStore;
23 import org.h2.mvstore.MVStoreException;
24 import org.h2.mvstore.tx.Transaction;
25 import org.h2.mvstore.tx.TransactionMap;
26 import org.h2.mvstore.tx.TransactionMap.TMIterator;
27 import org.h2.mvstore.type.DataType;
28 import org.h2.result.Row;
29 import org.h2.result.RowFactory;
30 import org.h2.result.SearchRow;
31 import org.h2.result.SortOrder;
32 import org.h2.table.IndexColumn;
33 import org.h2.table.TableFilter;
34 import org.h2.value.Value;
35 import org.h2.value.ValueNull;
36 import org.h2.value.VersionedValue;
37
38 /**
39 * An index stored in a MVStore.
40 */
41 public final class MVSecondaryIndex extends MVIndex<SearchRow, Value> {
42
43 /**
44 * The multi-value table.
45 */
46 private final MVTable mvTable;
47 private final TransactionMap<SearchRow,Value> dataMap;
48
49 public MVSecondaryIndex(Database db, MVTable table, int id, String indexName,
50 IndexColumn[] columns, int uniqueColumnCount, IndexType indexType) {
51 super(table, id, indexName, columns, uniqueColumnCount, indexType);
52 this.mvTable = table;
53 if (!database.isStarting()) {
54 checkIndexColumnTypes(columns);
55 }
56 String mapName = "index." + getId();
57 RowDataType keyType = getRowFactory().getRowDataType();
58 Transaction t = mvTable.getTransactionBegin();
59 dataMap = t.openMap(mapName, keyType, NullValueDataType.INSTANCE);
60 dataMap.map.setVolatile(!table.isPersistData() || !indexType.isPersistent());
61 if (!db.isStarting()) {
62 dataMap.clear();
63 }
64 t.commit();
65 if (!keyType.equals(dataMap.getKeyType())) {
66 throw DbException.getInternalError(
67 "Incompatible key type, expected " + keyType + " but got "
68 + dataMap.getKeyType() + " for index " + indexName);
69 }
70 }
71
72 @Override
73 public void addRowsToBuffer(List<Row> rows, String bufferName) {
74 MVMap<SearchRow,Value> map = openMap(bufferName);
75 for (Row row : rows) {
76 SearchRow r = getRowFactory().createRow();
77 r.copyFrom(row);
78 map.append(r, ValueNull.INSTANCE);
79 }
80 }
81
82 private static final class Source {
83
84 private final Iterator<SearchRow> iterator;
85
86 SearchRow currentRowData;
87
88 public Source(Iterator<SearchRow> iterator) {
89 assert iterator.hasNext();
90 this.iterator = iterator;
91 this.currentRowData = iterator.next();
92 }
93
94 public boolean hasNext() {
95 boolean result = iterator.hasNext();
96 if(result) {
97 currentRowData = iterator.next();
98 }
99 return result;
100 }
101
102 public SearchRow next() {
103 return currentRowData;
104 }
105
106 static final class Comparator implements java.util.Comparator<Source> {
107
108 private final DataType<SearchRow> type;
109
110 public Comparator(DataType<SearchRow> type) {
111 this.type = type;
112 }
113
114 @Override
115 public int compare(Source one, Source two) {
116 return type.compare(one.currentRowData, two.currentRowData);
117 }
118 }
119 }
120
121 @Override
122 public void addBufferedRows(List<String> bufferNames) {
123 int buffersCount = bufferNames.size();
124 Queue<Source> queue = new PriorityQueue<>(buffersCount,
125 new Source.Comparator(getRowFactory().getRowDataType()));
126 for (String bufferName : bufferNames) {
127 Iterator<SearchRow> iter = openMap(bufferName).keyIterator(null);
128 if (iter.hasNext()) {
129 queue.offer(new Source(iter));
130 }
131 }
132
133 try {
134 while (!queue.isEmpty()) {
135 Source s = queue.poll();
136 SearchRow row = s.next();
137
138 if (needsUniqueCheck(row)) {
139 checkUnique(false, dataMap, row, Long.MIN_VALUE);
140 }
141
142 dataMap.putCommitted(row, ValueNull.INSTANCE);
143
144 if (s.hasNext()) {
145 queue.offer(s);
146 }
147 }
148 } finally {
149 MVStore mvStore = database.getStore().getMvStore();
150 for (String tempMapName : bufferNames) {
151 mvStore.removeMap(tempMapName);
152 }
153 }
154 }
155
156 private MVMap<SearchRow,Value> openMap(String mapName) {
157 RowDataType keyType = getRowFactory().getRowDataType();
158 MVMap.Builder<SearchRow,Value> builder = new MVMap.Builder<SearchRow,Value>()
159 .singleWriter()
160 .keyType(keyType)
161 .valueType(NullValueDataType.INSTANCE);
162 MVMap<SearchRow, Value> map = database.getStore().getMvStore()
163 .openMap(mapName, builder);
164 if (!keyType.equals(map.getKeyType())) {
165 throw DbException.getInternalError(
166 "Incompatible key type, expected " + keyType + " but got "
167 + map.getKeyType() + " for map " + mapName);
168 }
169 return map;
170 }
171
172 @Override
173 public void close(SessionLocal session) {
174 // ok
175 }
176
177 @Override
178 public void add(SessionLocal session, Row row) {
179 TransactionMap<SearchRow,Value> map = getMap(session);
180 SearchRow key = convertToKey(row, null);
181 boolean checkRequired = needsUniqueCheck(row);
182 if (checkRequired) {
183 boolean repeatableRead = !session.getTransaction().allowNonRepeatableRead();
184 checkUnique(repeatableRead, map, row, Long.MIN_VALUE);
185 }
186
187 try {
188 map.put(key, ValueNull.INSTANCE);
189 } catch (MVStoreException e) {
190 throw mvTable.convertException(e);
191 }
192
193 if (checkRequired) {
194 checkUnique(false, map, row, row.getKey());
195 }
196 }
197
198 private void checkUnique(boolean repeatableRead, TransactionMap<SearchRow,Value> map, SearchRow row,
199 long newKey) {
200 RowFactory uniqueRowFactory = getUniqueRowFactory();
201 SearchRow from = uniqueRowFactory.createRow();
202 from.copyFrom(row);
203 from.setKey(Long.MIN_VALUE);
204 SearchRow to = uniqueRowFactory.createRow();
205 to.copyFrom(row);
206 to.setKey(Long.MAX_VALUE);
207 if (repeatableRead) {
208 // In order to guarantee repeatable reads, snapshot taken at the beginning of the statement or transaction
209 // need to be checked additionally, because existence of the key should be accounted for,
210 // even if since then, it was already deleted by another (possibly committed) transaction.
211 TMIterator<SearchRow, Value, SearchRow> it = map.keyIterator(from, to);
212 for (SearchRow k; (k = it.fetchNext()) != null;) {
213 if (newKey != k.getKey() && !map.isDeletedByCurrentTransaction(k)) {
214 throw getDuplicateKeyException(k.toString());
215 }
216 }
217 }
218 TMIterator<SearchRow, Value, SearchRow> it = map.keyIteratorUncommitted(from, to);
219 for (SearchRow k; (k = it.fetchNext()) != null;) {
220 if (newKey != k.getKey()) {
221 if (map.getImmediate(k) != null) {
222 // committed
223 throw getDuplicateKeyException(k.toString());
224 }
225 throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, table.getName());
226 }
227 }
228 }
229
230 @Override
231 public void remove(SessionLocal session, Row row) {
232 SearchRow searchRow = convertToKey(row, null);
233 TransactionMap<SearchRow,Value> map = getMap(session);
234 try {
235 if (map.remove(searchRow) == null) {
236 StringBuilder builder = new StringBuilder();
237 getSQL(builder, TRACE_SQL_FLAGS).append(": ").append(row.getKey());
238 throw DbException.get(ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1, builder.toString());
239 }
240 } catch (MVStoreException e) {
241 throw mvTable.convertException(e);
242 }
243 }
244
245 @Override
246 public void update(SessionLocal session, Row oldRow, Row newRow) {
247 SearchRow searchRowOld = convertToKey(oldRow, null);
248 SearchRow searchRowNew = convertToKey(newRow, null);
249 if (!rowsAreEqual(searchRowOld, searchRowNew)) {
250 super.update(session, oldRow, newRow);
251 }
252 }
253
254 private boolean rowsAreEqual(SearchRow rowOne, SearchRow rowTwo) {
255 if (rowOne == rowTwo) {
256 return true;
257 }
258 for (int index : columnIds) {
259 Value v1 = rowOne.getValue(index);
260 Value v2 = rowTwo.getValue(index);
261 if (!Objects.equals(v1, v2)) {
262 return false;
263 }
264 }
265 return rowOne.getKey() == rowTwo.getKey();
266 }
267
268 @Override
269 public Cursor find(SessionLocal session, SearchRow first, SearchRow last) {
270 return find(session, first, false, last);
271 }
272
273 private Cursor find(SessionLocal session, SearchRow first, boolean bigger, SearchRow last) {
274 SearchRow min = convertToKey(first, bigger);
275 SearchRow max = convertToKey(last, Boolean.TRUE);
276 return new MVStoreCursor(session, getMap(session).keyIterator(min, max), mvTable);
277 }
278
279 private SearchRow convertToKey(SearchRow r, Boolean minMax) {
280 if (r == null) {
281 return null;
282 }
283
284 SearchRow row = getRowFactory().createRow();
285 row.copyFrom(r);
286 if (minMax != null) {
287 row.setKey(minMax ? Long.MAX_VALUE : Long.MIN_VALUE);
288 }
289 return row;
290 }
291
292 @Override
293 public MVTable getTable() {
294 return mvTable;
295 }
296
297 @Override
298 public double getCost(SessionLocal session, int[] masks,
299 TableFilter[] filters, int filter, SortOrder sortOrder,
300 AllColumnsForPlan allColumnsSet) {
301 try {
302 return 10 * getCostRangeIndex(masks, dataMap.sizeAsLongMax(),
303 filters, filter, sortOrder, false, allColumnsSet);
304 } catch (MVStoreException e) {
305 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
306 }
307 }
308
309 @Override
310 public void remove(SessionLocal session) {
311 TransactionMap<SearchRow,Value> map = getMap(session);
312 if (!map.isClosed()) {
313 Transaction t = session.getTransaction();
314 t.removeMap(map);
315 }
316 }
317
318 @Override
319 public void truncate(SessionLocal session) {
320 TransactionMap<SearchRow,Value> map = getMap(session);
321 map.clear();
322 }
323
324 @Override
325 public boolean canGetFirstOrLast() {
326 return true;
327 }
328
329 @Override
330 public Cursor findFirstOrLast(SessionLocal session, boolean first) {
331 TMIterator<SearchRow, Value, SearchRow> iter = getMap(session).keyIterator(null, !first);
332 for (SearchRow key; (key = iter.fetchNext()) != null;) {
333 if (key.getValue(columnIds[0]) != ValueNull.INSTANCE) {
334 return new SingleRowCursor(mvTable.getRow(session, key.getKey()));
335 }
336 }
337 return new SingleRowCursor(null);
338 }
339
340 @Override
341 public boolean needRebuild() {
342 try {
343 return dataMap.sizeAsLongMax() == 0;
344 } catch (MVStoreException e) {
345 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
346 }
347 }
348
349 @Override
350 public long getRowCount(SessionLocal session) {
351 TransactionMap<SearchRow,Value> map = getMap(session);
352 return map.sizeAsLong();
353 }
354
355 @Override
356 public long getRowCountApproximation(SessionLocal session) {
357 try {
358 return dataMap.sizeAsLongMax();
359 } catch (MVStoreException e) {
360 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
361 }
362 }
363
364 @Override
365 public long getDiskSpaceUsed() {
366 // TODO estimate disk space usage
367 return 0;
368 }
369
370 @Override
371 public boolean canFindNext() {
372 return true;
373 }
374
375 @Override
376 public Cursor findNext(SessionLocal session, SearchRow higherThan, SearchRow last) {
377 return find(session, higherThan, true, last);
378 }
379
380 /**
381 * Get the map to store the data.
382 *
383 * @param session the session
384 * @return the map
385 */
386 private TransactionMap<SearchRow,Value> getMap(SessionLocal session) {
387 if (session == null) {
388 return dataMap;
389 }
390 Transaction t = session.getTransaction();
391 return dataMap.getInstance(t);
392 }
393
394 @Override
395 public MVMap<SearchRow,VersionedValue<Value>> getMVMap() {
396 return dataMap.map;
397 }
398
399 /**
400 * A cursor.
401 */
402 static final class MVStoreCursor implements Cursor {
403
404 private final SessionLocal session;
405 private final TMIterator<SearchRow, Value, SearchRow> it;
406 private final MVTable mvTable;
407 private SearchRow current;
408 private Row row;
409
410 MVStoreCursor(SessionLocal session, TMIterator<SearchRow, Value, SearchRow> it, MVTable mvTable) {
411 this.session = session;
412 this.it = it;
413 this.mvTable = mvTable;
414 }
415
416 @Override
417 public Row get() {
418 if (row == null) {
419 SearchRow r = getSearchRow();
420 if (r != null) {
421 row = mvTable.getRow(session, r.getKey());
422 }
423 }
424 return row;
425 }
426
427 @Override
428 public SearchRow getSearchRow() {
429 return current;
430 }
431
432 @Override
433 public boolean next() {
434 current = it.fetchNext();
435 row = null;
436 return current != null;
437 }
438
439 @Override
440 public boolean previous() {
441 throw DbException.getUnsupportedException("previous");
442 }
443 }
444
445 }