Debian Codegraph @

src/main/org/h2/mvstore/db/MVSpatialIndex.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 static org.h2.util.geometry.GeometryUtils.MAX_X;
9 import static org.h2.util.geometry.GeometryUtils.MAX_Y;
10 import static org.h2.util.geometry.GeometryUtils.MIN_X;
11 import static org.h2.util.geometry.GeometryUtils.MIN_Y;
12
13 import java.util.Iterator;
14 import java.util.List;
15 import org.h2.api.ErrorCode;
16 import org.h2.command.query.AllColumnsForPlan;
17 import org.h2.engine.Database;
18 import org.h2.engine.SessionLocal;
19 import org.h2.index.Cursor;
20 import org.h2.index.IndexCondition;
21 import org.h2.index.IndexType;
22 import org.h2.index.SpatialIndex;
23 import org.h2.message.DbException;
24 import org.h2.mvstore.MVMap;
25 import org.h2.mvstore.MVStoreException;
26 import org.h2.mvstore.Page;
27 import org.h2.mvstore.rtree.MVRTreeMap;
28 import org.h2.mvstore.rtree.MVRTreeMap.RTreeCursor;
29 import org.h2.mvstore.rtree.Spatial;
30 import org.h2.mvstore.tx.Transaction;
31 import org.h2.mvstore.tx.TransactionMap;
32 import org.h2.mvstore.tx.VersionedValueType;
33 import org.h2.result.Row;
34 import org.h2.result.SearchRow;
35 import org.h2.result.SortOrder;
36 import org.h2.table.Column;
37 import org.h2.table.IndexColumn;
38 import org.h2.table.TableFilter;
39 import org.h2.value.Value;
40 import org.h2.value.ValueGeometry;
41 import org.h2.value.ValueNull;
42 import org.h2.value.VersionedValue;
43
44 /**
45 * This is an index based on a MVRTreeMap.
46 *
47 * @author Thomas Mueller
48 * @author Noel Grandin
49 * @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
50 */
51 public class MVSpatialIndex extends MVIndex<Spatial, Value> implements SpatialIndex {
52
53 /**
54 * The multi-value table.
55 */
56 final MVTable mvTable;
57
58 private final TransactionMap<Spatial, Value> dataMap;
59 private final MVRTreeMap<VersionedValue<Value>> spatialMap;
60
61 /**
62 * Constructor.
63 *
64 * @param db the database
65 * @param table the table instance
66 * @param id the index id
67 * @param indexName the index name
68 * @param columns the indexed columns (only one geometry column allowed)
69 * @param uniqueColumnCount count of unique columns (0 or 1)
70 * @param indexType the index type (only spatial index)
71 */
72 public MVSpatialIndex(Database db, MVTable table, int id, String indexName, IndexColumn[] columns,
73 int uniqueColumnCount, IndexType indexType) {
74 super(table, id, indexName, columns, uniqueColumnCount, indexType);
75 if (columns.length != 1) {
76 throw DbException.getUnsupportedException(
77 "Can only index one column");
78 }
79 IndexColumn col = columns[0];
80 if ((col.sortType & SortOrder.DESCENDING) != 0) {
81 throw DbException.getUnsupportedException(
82 "Cannot index in descending order");
83 }
84 if ((col.sortType & SortOrder.NULLS_FIRST) != 0) {
85 throw DbException.getUnsupportedException(
86 "Nulls first is not supported");
87 }
88 if ((col.sortType & SortOrder.NULLS_LAST) != 0) {
89 throw DbException.getUnsupportedException(
90 "Nulls last is not supported");
91 }
92 if (col.column.getType().getValueType() != Value.GEOMETRY) {
93 throw DbException.getUnsupportedException(
94 "Spatial index on non-geometry column, "
95 + col.column.getCreateSQL());
96 }
97 this.mvTable = table;
98 if (!database.isStarting()) {
99 checkIndexColumnTypes(columns);
100 }
101 String mapName = "index." + getId();
102 VersionedValueType<Value, Database> valueType = new VersionedValueType<>(NullValueDataType.INSTANCE);
103 MVRTreeMap.Builder<VersionedValue<Value>> mapBuilder =
104 new MVRTreeMap.Builder<VersionedValue<Value>>().
105 valueType(valueType);
106 spatialMap = db.getStore().getMvStore().openMap(mapName, mapBuilder);
107 Transaction t = mvTable.getTransactionBegin();
108 dataMap = t.openMapX(spatialMap);
109 dataMap.map.setVolatile(!table.isPersistData() || !indexType.isPersistent());
110 t.commit();
111 }
112
113 @Override
114 public void addRowsToBuffer(List<Row> rows, String bufferName) {
115 throw DbException.getInternalError();
116 }
117
118 @Override
119 public void addBufferedRows(List<String> bufferNames) {
120 throw DbException.getInternalError();
121 }
122
123 @Override
124 public void close(SessionLocal session) {
125 // ok
126 }
127
128 @Override
129 public void add(SessionLocal session, Row row) {
130 TransactionMap<Spatial, Value> map = getMap(session);
131 SpatialKey key = getKey(row);
132
133 if (key.isNull()) {
134 return;
135 }
136
137 if (uniqueColumnColumn > 0) {
138 // this will detect committed entries only
139 RTreeCursor<VersionedValue<Value>> cursor = spatialMap.findContainedKeys(key);
140 Iterator<Spatial> it = new SpatialKeyIterator(map, cursor, false);
141 while (it.hasNext()) {
142 Spatial k = it.next();
143 if (k.equalsIgnoringId(key)) {
144 throw getDuplicateKeyException(key.toString());
145 }
146 }
147 }
148 try {
149 map.put(key, ValueNull.INSTANCE);
150 } catch (MVStoreException e) {
151 throw mvTable.convertException(e);
152 }
153 if (uniqueColumnColumn > 0) {
154 // check if there is another (uncommitted) entry
155 RTreeCursor<VersionedValue<Value>> cursor = spatialMap.findContainedKeys(key);
156 Iterator<Spatial> it = new SpatialKeyIterator(map, cursor, true);
157 while (it.hasNext()) {
158 Spatial k = it.next();
159 if (k.equalsIgnoringId(key)) {
160 if (map.isSameTransaction(k)) {
161 continue;
162 }
163 map.remove(key);
164 if (map.getImmediate(k) != null) {
165 // committed
166 throw getDuplicateKeyException(k.toString());
167 }
168 throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, table.getName());
169 }
170 }
171 }
172 }
173
174 @Override
175 public void remove(SessionLocal session, Row row) {
176 SpatialKey key = getKey(row);
177
178 if (key.isNull()) {
179 return;
180 }
181
182 TransactionMap<Spatial, Value> map = getMap(session);
183 try {
184 Value old = map.remove(key);
185 if (old == null) {
186 StringBuilder builder = new StringBuilder();
187 getSQL(builder, TRACE_SQL_FLAGS).append(": ").append(row.getKey());
188 throw DbException.get(ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1, builder.toString());
189 }
190 } catch (MVStoreException e) {
191 throw mvTable.convertException(e);
192 }
193 }
194
195 @Override
196 public Cursor find(SessionLocal session, SearchRow first, SearchRow last) {
197 Iterator<Spatial> cursor = spatialMap.keyIterator(null);
198 TransactionMap<Spatial, Value> map = getMap(session);
199 Iterator<Spatial> it = new SpatialKeyIterator(map, cursor, false);
200 return new MVStoreCursor(session, it, mvTable);
201 }
202
203 @Override
204 public Cursor findByGeometry(SessionLocal session, SearchRow first, SearchRow last, SearchRow intersection) {
205 if (intersection == null) {
206 return find(session, first, last);
207 }
208 Iterator<Spatial> cursor =
209 spatialMap.findIntersectingKeys(getKey(intersection));
210 TransactionMap<Spatial, Value> map = getMap(session);
211 Iterator<Spatial> it = new SpatialKeyIterator(map, cursor, false);
212 return new MVStoreCursor(session, it, mvTable);
213 }
214
215 /**
216 * Returns the minimum bounding box that encloses all keys.
217 *
218 * @param session the session
219 * @return the minimum bounding box that encloses all keys, or null
220 */
221 public Value getBounds(SessionLocal session) {
222 FindBoundsCursor cursor = new FindBoundsCursor(spatialMap.getRootPage(), new SpatialKey(0), session,
223 getMap(session), columnIds[0]);
224 while (cursor.hasNext()) {
225 cursor.next();
226 }
227 return cursor.getBounds();
228 }
229
230 /**
231 * Returns the estimated minimum bounding box that encloses all keys.
232 *
233 * The returned value may be incorrect.
234 *
235 * @param session the session
236 * @return the estimated minimum bounding box that encloses all keys, or null
237 */
238 public Value getEstimatedBounds(SessionLocal session) {
239 Page<Spatial,VersionedValue<Value>> p = spatialMap.getRootPage();
240 int count = p.getKeyCount();
241 if (count > 0) {
242 Spatial key = p.getKey(0);
243 float bminxf = key.min(0), bmaxxf = key.max(0), bminyf = key.min(1), bmaxyf = key.max(1);
244 for (int i = 1; i < count; i++) {
245 key = p.getKey(i);
246 float minxf = key.min(0), maxxf = key.max(0), minyf = key.min(1), maxyf = key.max(1);
247 if (minxf < bminxf) {
248 bminxf = minxf;
249 }
250 if (maxxf > bmaxxf) {
251 bmaxxf = maxxf;
252 }
253 if (minyf < bminyf) {
254 bminyf = minyf;
255 }
256 if (maxyf > bmaxyf) {
257 bmaxyf = maxyf;
258 }
259 }
260 return ValueGeometry.fromEnvelope(new double[] {bminxf, bmaxxf, bminyf, bmaxyf});
261 }
262 return ValueNull.INSTANCE;
263 }
264
265 private SpatialKey getKey(SearchRow row) {
266 Value v = row.getValue(columnIds[0]);
267 double[] env;
268 if (v == ValueNull.INSTANCE || (env = v.convertToGeometry(null).getEnvelopeNoCopy()) == null) {
269 return new SpatialKey(row.getKey());
270 }
271 return new SpatialKey(row.getKey(),
272 (float) env[MIN_X], (float) env[MAX_X],
273 (float) env[MIN_Y], (float) env[MAX_Y]);
274 }
275
276 @Override
277 public MVTable getTable() {
278 return mvTable;
279 }
280
281 @Override
282 public double getCost(SessionLocal session, int[] masks, TableFilter[] filters,
283 int filter, SortOrder sortOrder,
284 AllColumnsForPlan allColumnsSet) {
285 return getCostRangeIndex(masks, columns);
286 }
287
288 /**
289 * Compute spatial index cost
290 * @param masks Search mask
291 * @param columns Table columns
292 * @return Index cost hint
293 */
294 public static long getCostRangeIndex(int[] masks, Column[] columns) {
295 // Never use spatial tree index without spatial filter
296 if (columns.length == 0) {
297 return Long.MAX_VALUE;
298 }
299 for (Column column : columns) {
300 int index = column.getColumnId();
301 int mask = masks[index];
302 if ((mask & IndexCondition.SPATIAL_INTERSECTS) != IndexCondition.SPATIAL_INTERSECTS) {
303 return Long.MAX_VALUE;
304 }
305 }
306 return 2;
307 }
308
309 @Override
310 public void remove(SessionLocal session) {
311 TransactionMap<Spatial, 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<Spatial, Value> map = getMap(session);
321 map.clear();
322 }
323
324 @Override
325 public boolean needRebuild() {
326 try {
327 return dataMap.sizeAsLongMax() == 0;
328 } catch (MVStoreException e) {
329 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
330 }
331 }
332
333 @Override
334 public long getRowCount(SessionLocal session) {
335 TransactionMap<Spatial, Value> map = getMap(session);
336 return map.sizeAsLong();
337 }
338
339 @Override
340 public long getRowCountApproximation(SessionLocal session) {
341 try {
342 return dataMap.sizeAsLongMax();
343 } catch (MVStoreException e) {
344 throw DbException.get(ErrorCode.OBJECT_CLOSED, e);
345 }
346 }
347
348 @Override
349 public long getDiskSpaceUsed() {
350 // TODO estimate disk space usage
351 return 0;
352 }
353
354 /**
355 * Get the map to store the data.
356 *
357 * @param session the session
358 * @return the map
359 */
360 private TransactionMap<Spatial, Value> getMap(SessionLocal session) {
361 if (session == null) {
362 return dataMap;
363 }
364 Transaction t = session.getTransaction();
365 return dataMap.getInstance(t);
366 }
367
368 @Override
369 public MVMap<Spatial, VersionedValue<Value>> getMVMap() {
370 return dataMap.map;
371 }
372
373
374 /**
375 * A cursor.
376 */
377 private static class MVStoreCursor implements Cursor {
378
379 private final SessionLocal session;
380 private final Iterator<Spatial> it;
381 private final MVTable mvTable;
382 private Spatial current;
383 private SearchRow searchRow;
384 private Row row;
385
386 MVStoreCursor(SessionLocal session, Iterator<Spatial> it, MVTable mvTable) {
387 this.session = session;
388 this.it = it;
389 this.mvTable = mvTable;
390 }
391
392 @Override
393 public Row get() {
394 if (row == null) {
395 SearchRow r = getSearchRow();
396 if (r != null) {
397 row = mvTable.getRow(session, r.getKey());
398 }
399 }
400 return row;
401 }
402
403 @Override
404 public SearchRow getSearchRow() {
405 if (searchRow == null) {
406 if (current != null) {
407 searchRow = mvTable.getTemplateRow();
408 searchRow.setKey(current.getId());
409 }
410 }
411 return searchRow;
412 }
413
414 @Override
415 public boolean next() {
416 current = it.hasNext() ? it.next() : null;
417 searchRow = null;
418 row = null;
419 return current != null;
420 }
421
422 @Override
423 public boolean previous() {
424 throw DbException.getUnsupportedException("previous");
425 }
426
427 }
428
429 private static class SpatialKeyIterator implements Iterator<Spatial> {
430
431 private final TransactionMap<Spatial, Value> map;
432 private final Iterator<Spatial> iterator;
433 private final boolean includeUncommitted;
434 private Spatial current;
435
436 SpatialKeyIterator(TransactionMap<Spatial, Value> map,
437 Iterator<Spatial> iterator, boolean includeUncommitted) {
438 this.map = map;
439 this.iterator = iterator;
440 this.includeUncommitted = includeUncommitted;
441 fetchNext();
442 }
443
444 private void fetchNext() {
445 while (iterator.hasNext()) {
446 current = iterator.next();
447 if (includeUncommitted || map.containsKey(current)) {
448 return;
449 }
450 }
451 current = null;
452 }
453
454 @Override
455 public boolean hasNext() {
456 return current != null;
457 }
458
459 @Override
460 public Spatial next() {
461 Spatial result = current;
462 fetchNext();
463 return result;
464 }
465 }
466
467 /**
468 * A cursor for getBounds() method.
469 */
470 private final class FindBoundsCursor extends RTreeCursor<VersionedValue<Value>> {
471
472 private final SessionLocal session;
473
474 private final TransactionMap<Spatial, Value> map;
475
476 private final int columnId;
477
478 private boolean hasBounds;
479
480 private float bminxf, bmaxxf, bminyf, bmaxyf;
481
482 private double bminxd, bmaxxd, bminyd, bmaxyd;
483
484 FindBoundsCursor(Page<Spatial,VersionedValue<Value>> root, Spatial filter, SessionLocal session,
485 TransactionMap<Spatial, Value> map, int columnId) {
486 super(root, filter);
487 this.session = session;
488 this.map = map;
489 this.columnId = columnId;
490 }
491
492 @Override
493 protected boolean check(boolean leaf, Spatial key, Spatial test) {
494 float minxf = key.min(0), maxxf = key.max(0), minyf = key.min(1), maxyf = key.max(1);
495 if (leaf) {
496 if (hasBounds) {
497 if ((minxf <= bminxf || maxxf >= bmaxxf || minyf <= bminyf || maxyf >= bmaxyf)
498 && map.containsKey(key)) {
499 double[] env = ((ValueGeometry) mvTable.getRow(session, key.getId()).getValue(columnId))
500 .getEnvelopeNoCopy();
501 double minxd = env[MIN_X], maxxd = env[MAX_X], minyd = env[MIN_Y], maxyd = env[MAX_Y];
502 if (minxd < bminxd) {
503 bminxf = minxf;
504 bminxd = minxd;
505 }
506 if (maxxd > bmaxxd) {
507 bmaxxf = maxxf;
508 bmaxxd = maxxd;
509 }
510 if (minyd < bminyd) {
511 bminyf = minyf;
512 bminyd = minyd;
513 }
514 if (maxyd > bmaxyd) {
515 bmaxyf = maxyf;
516 bmaxyd = maxyd;
517 }
518 }
519 } else if (map.containsKey(key)) {
520 hasBounds = true;
521 double[] env = ((ValueGeometry) mvTable.getRow(session, key.getId()).getValue(columnId))
522 .getEnvelopeNoCopy();
523 bminxf = minxf;
524 bminxd = env[MIN_X];
525 bmaxxf = maxxf;
526 bmaxxd = env[MAX_X];
527 bminyf = minyf;
528 bminyd = env[MIN_Y];
529 bmaxyf = maxyf;
530 bmaxyd = env[MAX_Y];
531 }
532 } else if (hasBounds) {
533 if (minxf <= bminxf || maxxf >= bmaxxf || minyf <= bminyf || maxyf >= bmaxyf) {
534 return true;
535 }
536 } else {
537 return true;
538 }
539 return false;
540 }
541
542 Value getBounds() {
543 return hasBounds ? ValueGeometry.fromEnvelope(new double[] {bminxd, bmaxxd, bminyd, bmaxyd})
544 : ValueNull.INSTANCE;
545 }
546
547 }
548
549 }
550