| 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.List; |
| 9 |
import java.util.Map.Entry; |
| 10 |
import java.util.concurrent.atomic.AtomicLong; |
| 11 |
import org.h2.api.ErrorCode; |
| 12 |
import org.h2.command.query.AllColumnsForPlan; |
| 13 |
import org.h2.engine.Database; |
| 14 |
import org.h2.engine.SessionLocal; |
| 15 |
import org.h2.index.Cursor; |
| 16 |
import org.h2.index.IndexType; |
| 17 |
import org.h2.index.SingleRowCursor; |
| 18 |
import org.h2.message.DbException; |
| 19 |
import org.h2.mvstore.MVMap; |
| 20 |
import org.h2.mvstore.MVStoreException; |
| 21 |
import org.h2.mvstore.tx.Transaction; |
| 22 |
import org.h2.mvstore.tx.TransactionMap; |
| 23 |
import org.h2.mvstore.tx.TransactionMap.TMIterator; |
| 24 |
import org.h2.mvstore.type.LongDataType; |
| 25 |
import org.h2.result.Row; |
| 26 |
import org.h2.result.SearchRow; |
| 27 |
import org.h2.result.SortOrder; |
| 28 |
import org.h2.table.Column; |
| 29 |
import org.h2.table.IndexColumn; |
| 30 |
import org.h2.table.TableFilter; |
| 31 |
import org.h2.value.Value; |
| 32 |
import org.h2.value.ValueLob; |
| 33 |
import org.h2.value.ValueNull; |
| 34 |
import org.h2.value.VersionedValue; |
| 35 |
|
| 36 |
/** |
| 37 |
* A table stored in a MVStore. |
| 38 |
*/ |
| 39 |
public class MVPrimaryIndex extends MVIndex<Long, SearchRow> { |
| 40 |
|
| 41 |
private final MVTable mvTable; |
| 42 |
private final String mapName; |
| 43 |
private final TransactionMap<Long, SearchRow> dataMap; |
| 44 |
private final AtomicLong lastKey = new AtomicLong(); |
| 45 |
private int mainIndexColumn = SearchRow.ROWID_INDEX; |
| 46 |
|
| 47 |
public MVPrimaryIndex(Database db, MVTable table, int id, IndexColumn[] columns, IndexType indexType) { |
| 48 |
super(table, id, table.getName() + "_DATA", columns, 0, indexType); |
| 49 |
this.mvTable = table; |
| 50 |
RowDataType valueType = table.getRowFactory().getRowDataType(); |
| 51 |
mapName = "table." + getId(); |
| 52 |
Transaction t = mvTable.getTransactionBegin(); |
| 53 |
dataMap = t.openMap(mapName, LongDataType.INSTANCE, valueType); |
| 54 |
dataMap.map.setVolatile(!table.isPersistData() || !indexType.isPersistent()); |
| 55 |
if (!db.isStarting()) { |
| 56 |
dataMap.clear(); |
| 57 |
} |
| 58 |
t.commit(); |
| 59 |
Long k = dataMap.map.lastKey(); // include uncommitted keys as well |
| 60 |
lastKey.set(k == null ? 0 : k); |
| 61 |
} |
| 62 |
|
| 63 |
@Override |
| 64 |
public String getCreateSQL() { |
| 65 |
return null; |
| 66 |
} |
| 67 |
|
| 68 |
@Override |
| 69 |
public String getPlanSQL() { |
| 70 |
return table.getSQL(new StringBuilder(), TRACE_SQL_FLAGS).append(".tableScan").toString(); |
| 71 |
} |
| 72 |
|
| 73 |
public void setMainIndexColumn(int mainIndexColumn) { |
| 74 |
this.mainIndexColumn = mainIndexColumn; |
| 75 |
} |
| 76 |
|
| 77 |
public int getMainIndexColumn() { |
| 78 |
return mainIndexColumn; |
| 79 |
} |
| 80 |
|
| 81 |
@Override |
| 82 |
public void close(SessionLocal session) { |
| 83 |
// ok |
| 84 |
} |
| 85 |
|
| 86 |
@Override |
| 87 |
public void add(SessionLocal session, Row row) { |
| 88 |
if (mainIndexColumn == SearchRow.ROWID_INDEX) { |
| 89 |
if (row.getKey() == 0) { |
| 90 |
row.setKey(lastKey.incrementAndGet()); |
| 91 |
} |
| 92 |
} else { |
| 93 |
long c = row.getValue(mainIndexColumn).getLong(); |
| 94 |
row.setKey(c); |
| 95 |
} |
| 96 |
|
| 97 |
if (mvTable.getContainsLargeObject()) { |
| 98 |
for (int i = 0, len = row.getColumnCount(); i < len; i++) { |
| 99 |
Value v = row.getValue(i); |
| 100 |
if (v instanceof ValueLob) { |
| 101 |
ValueLob lob = ((ValueLob) v).copy(database, getId()); |
| 102 |
session.removeAtCommitStop(lob); |
| 103 |
if (v != lob) { |
| 104 |
row.setValue(i, lob); |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 111 |
long rowKey = row.getKey(); |
| 112 |
try { |
| 113 |
Row old = (Row)map.putIfAbsent(rowKey, row); |
| 114 |
if (old != null) { |
| 115 |
int errorCode = ErrorCode.CONCURRENT_UPDATE_1; |
| 116 |
if (map.getImmediate(rowKey) != null || map.getFromSnapshot(rowKey) != null) { |
| 117 |
// committed |
| 118 |
errorCode = ErrorCode.DUPLICATE_KEY_1; |
| 119 |
} |
| 120 |
DbException e = DbException.get(errorCode, |
| 121 |
getDuplicatePrimaryKeyMessage(mainIndexColumn).append(' ').append(old).toString()); |
| 122 |
e.setSource(this); |
| 123 |
throw e; |
| 124 |
} |
| 125 |
} catch (MVStoreException e) { |
| 126 |
throw mvTable.convertException(e); |
| 127 |
} |
| 128 |
// because it's possible to directly update the key using the _rowid_ |
| 129 |
// syntax |
| 130 |
long last; |
| 131 |
while (rowKey > (last = lastKey.get())) { |
| 132 |
if(lastKey.compareAndSet(last, rowKey)) break; |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
@Override |
| 137 |
public void remove(SessionLocal session, Row row) { |
| 138 |
if (mvTable.getContainsLargeObject()) { |
| 139 |
for (int i = 0, len = row.getColumnCount(); i < len; i++) { |
| 140 |
Value v = row.getValue(i); |
| 141 |
if (v instanceof ValueLob) { |
| 142 |
session.removeAtCommit((ValueLob) v); |
| 143 |
} |
| 144 |
} |
| 145 |
} |
| 146 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 147 |
try { |
| 148 |
Row existing = (Row)map.remove(row.getKey()); |
| 149 |
if (existing == null) { |
| 150 |
StringBuilder builder = new StringBuilder(); |
| 151 |
getSQL(builder, TRACE_SQL_FLAGS).append(": ").append(row.getKey()); |
| 152 |
throw DbException.get(ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1, builder.toString()); |
| 153 |
} |
| 154 |
} catch (MVStoreException e) { |
| 155 |
throw mvTable.convertException(e); |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
@Override |
| 160 |
public void update(SessionLocal session, Row oldRow, Row newRow) { |
| 161 |
if (mainIndexColumn != SearchRow.ROWID_INDEX) { |
| 162 |
long c = newRow.getValue(mainIndexColumn).getLong(); |
| 163 |
newRow.setKey(c); |
| 164 |
} |
| 165 |
long key = oldRow.getKey(); |
| 166 |
assert mainIndexColumn != SearchRow.ROWID_INDEX || key != 0; |
| 167 |
assert key == newRow.getKey() : key + " != " + newRow.getKey(); |
| 168 |
if (mvTable.getContainsLargeObject()) { |
| 169 |
for (int i = 0, len = oldRow.getColumnCount(); i < len; i++) { |
| 170 |
Value oldValue = oldRow.getValue(i); |
| 171 |
Value newValue = newRow.getValue(i); |
| 172 |
if (oldValue != newValue) { |
| 173 |
if (oldValue instanceof ValueLob) { |
| 174 |
session.removeAtCommit((ValueLob) oldValue); |
| 175 |
} |
| 176 |
if (newValue instanceof ValueLob) { |
| 177 |
ValueLob lob = ((ValueLob) newValue).copy(database, getId()); |
| 178 |
session.removeAtCommitStop(lob); |
| 179 |
if (newValue != lob) { |
| 180 |
newRow.setValue(i, lob); |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 188 |
try { |
| 189 |
Row existing = (Row)map.put(key, newRow); |
| 190 |
if (existing == null) { |
| 191 |
StringBuilder builder = new StringBuilder(); |
| 192 |
getSQL(builder, TRACE_SQL_FLAGS).append(": ").append(key); |
| 193 |
throw DbException.get(ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1, builder.toString()); |
| 194 |
} |
| 195 |
} catch (MVStoreException e) { |
| 196 |
throw mvTable.convertException(e); |
| 197 |
} |
| 198 |
|
| 199 |
|
| 200 |
// because it's possible to directly update the key using the _rowid_ |
| 201 |
// syntax |
| 202 |
if (newRow.getKey() > lastKey.get()) { |
| 203 |
lastKey.set(newRow.getKey()); |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
/** |
| 208 |
* Lock a single row. |
| 209 |
* |
| 210 |
* @param session database session |
| 211 |
* @param row to lock |
| 212 |
* @param timeoutMillis |
| 213 |
* timeout in milliseconds, {@code -1} for default, {@code -2} to |
| 214 |
* skip locking if row is already locked by another session |
| 215 |
* @return row object if it exists |
| 216 |
*/ |
| 217 |
Row lockRow(SessionLocal session, Row row, int timeoutMillis) { |
| 218 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 219 |
long key = row.getKey(); |
| 220 |
return lockRow(map, key, timeoutMillis); |
| 221 |
} |
| 222 |
|
| 223 |
private Row lockRow(TransactionMap<Long,SearchRow> map, long key, int timeoutMillis) { |
| 224 |
try { |
| 225 |
return setRowKey((Row) map.lock(key, timeoutMillis), key); |
| 226 |
} catch (MVStoreException ex) { |
| 227 |
throw mvTable.convertLockException(ex); |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
@Override |
| 232 |
public Cursor find(SessionLocal session, SearchRow first, SearchRow last) { |
| 233 |
long min = extractPKFromRow(first, Long.MIN_VALUE); |
| 234 |
long max = extractPKFromRow(last, Long.MAX_VALUE); |
| 235 |
return find(session, min, max); |
| 236 |
} |
| 237 |
|
| 238 |
private long extractPKFromRow(SearchRow row, long defaultValue) { |
| 239 |
long result; |
| 240 |
if (row == null) { |
| 241 |
result = defaultValue; |
| 242 |
} else if (mainIndexColumn == SearchRow.ROWID_INDEX) { |
| 243 |
result = row.getKey(); |
| 244 |
} else { |
| 245 |
Value v = row.getValue(mainIndexColumn); |
| 246 |
if (v == null) { |
| 247 |
result = row.getKey(); |
| 248 |
} else if (v == ValueNull.INSTANCE) { |
| 249 |
result = 0L; |
| 250 |
} else { |
| 251 |
result = v.getLong(); |
| 252 |
} |
| 253 |
} |
| 254 |
return result; |
| 255 |
} |
| 256 |
|
| 257 |
|
| 258 |
@Override |
| 259 |
public MVTable getTable() { |
| 260 |
return mvTable; |
| 261 |
} |
| 262 |
|
| 263 |
@Override |
| 264 |
public Row getRow(SessionLocal session, long key) { |
| 265 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 266 |
Row row = (Row) map.getFromSnapshot(key); |
| 267 |
if (row == null) { |
| 268 |
throw DbException.get(ErrorCode.ROW_NOT_FOUND_IN_PRIMARY_INDEX, getTraceSQL(), String.valueOf(key)); |
| 269 |
} |
| 270 |
return setRowKey(row, key); |
| 271 |
} |
| 272 |
|
| 273 |
@Override |
| 274 |
public double getCost(SessionLocal session, int[] masks, |
| 275 |
TableFilter[] filters, int filter, SortOrder sortOrder, |
| 276 |
AllColumnsForPlan allColumnsSet) { |
| 277 |
try { |
| 278 |
return 10 * getCostRangeIndex(masks, dataMap.sizeAsLongMax(), |
| 279 |
filters, filter, sortOrder, true, allColumnsSet); |
| 280 |
} catch (MVStoreException e) { |
| 281 |
throw DbException.get(ErrorCode.OBJECT_CLOSED, e); |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
@Override |
| 286 |
public int getColumnIndex(Column col) { |
| 287 |
// can not use this index - use the delegate index instead |
| 288 |
return SearchRow.ROWID_INDEX; |
| 289 |
} |
| 290 |
|
| 291 |
@Override |
| 292 |
public boolean isFirstColumn(Column column) { |
| 293 |
return false; |
| 294 |
} |
| 295 |
|
| 296 |
@Override |
| 297 |
public void remove(SessionLocal session) { |
| 298 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 299 |
if (!map.isClosed()) { |
| 300 |
Transaction t = session.getTransaction(); |
| 301 |
t.removeMap(map); |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
@Override |
| 306 |
public void truncate(SessionLocal session) { |
| 307 |
if (mvTable.getContainsLargeObject()) { |
| 308 |
database.getLobStorage().removeAllForTable(table.getId()); |
| 309 |
} |
| 310 |
getMap(session).clear(); |
| 311 |
} |
| 312 |
|
| 313 |
@Override |
| 314 |
public boolean canGetFirstOrLast() { |
| 315 |
return true; |
| 316 |
} |
| 317 |
|
| 318 |
@Override |
| 319 |
public Cursor findFirstOrLast(SessionLocal session, boolean first) { |
| 320 |
TransactionMap<Long, SearchRow> map = getMap(session); |
| 321 |
Entry<Long, SearchRow> entry = first ? map.firstEntry() : map.lastEntry(); |
| 322 |
return new SingleRowCursor(entry != null ? setRowKey((Row) entry.getValue(), entry.getKey()) : null); |
| 323 |
} |
| 324 |
|
| 325 |
@Override |
| 326 |
public boolean needRebuild() { |
| 327 |
return false; |
| 328 |
} |
| 329 |
|
| 330 |
@Override |
| 331 |
public long getRowCount(SessionLocal session) { |
| 332 |
return getMap(session).sizeAsLong(); |
| 333 |
} |
| 334 |
|
| 335 |
/** |
| 336 |
* The maximum number of rows, including uncommitted rows of any session. |
| 337 |
* |
| 338 |
* @return the maximum number of rows |
| 339 |
*/ |
| 340 |
public long getRowCountMax() { |
| 341 |
return dataMap.sizeAsLongMax(); |
| 342 |
} |
| 343 |
|
| 344 |
@Override |
| 345 |
public long getRowCountApproximation(SessionLocal session) { |
| 346 |
return getRowCountMax(); |
| 347 |
} |
| 348 |
|
| 349 |
@Override |
| 350 |
public long getDiskSpaceUsed() { |
| 351 |
return dataMap.map.getRootPage().getDiskSpaceUsed(); |
| 352 |
} |
| 353 |
|
| 354 |
public String getMapName() { |
| 355 |
return mapName; |
| 356 |
} |
| 357 |
|
| 358 |
@Override |
| 359 |
public void addRowsToBuffer(List<Row> rows, String bufferName) { |
| 360 |
throw new UnsupportedOperationException(); |
| 361 |
} |
| 362 |
|
| 363 |
@Override |
| 364 |
public void addBufferedRows(List<String> bufferNames) { |
| 365 |
throw new UnsupportedOperationException(); |
| 366 |
} |
| 367 |
|
| 368 |
private Cursor find(SessionLocal session, Long first, Long last) { |
| 369 |
TransactionMap<Long,SearchRow> map = getMap(session); |
| 370 |
if (first != null && last != null && first.longValue() == last.longValue()) { |
| 371 |
return new SingleRowCursor(setRowKey((Row) map.getFromSnapshot(first), first)); |
| 372 |
} |
| 373 |
return new MVStoreCursor(map.entryIterator(first, last)); |
| 374 |
} |
| 375 |
|
| 376 |
@Override |
| 377 |
public boolean isRowIdIndex() { |
| 378 |
return true; |
| 379 |
} |
| 380 |
|
| 381 |
/** |
| 382 |
* Get the map to store the data. |
| 383 |
* |
| 384 |
* @param session the session |
| 385 |
* @return the map |
| 386 |
*/ |
| 387 |
TransactionMap<Long,SearchRow> getMap(SessionLocal session) { |
| 388 |
if (session == null) { |
| 389 |
return dataMap; |
| 390 |
} |
| 391 |
Transaction t = session.getTransaction(); |
| 392 |
return dataMap.getInstance(t); |
| 393 |
} |
| 394 |
|
| 395 |
@Override |
| 396 |
public MVMap<Long, VersionedValue<SearchRow>> getMVMap() { |
| 397 |
return dataMap.map; |
| 398 |
} |
| 399 |
|
| 400 |
private static Row setRowKey(Row row, long key) { |
| 401 |
if (row != null && row.getKey() == 0) { |
| 402 |
row.setKey(key); |
| 403 |
} |
| 404 |
return row; |
| 405 |
} |
| 406 |
|
| 407 |
/** |
| 408 |
* A cursor. |
| 409 |
*/ |
| 410 |
static final class MVStoreCursor implements Cursor { |
| 411 |
|
| 412 |
private final TMIterator<Long, SearchRow, Entry<Long, SearchRow>> it; |
| 413 |
private Entry<Long, SearchRow> current; |
| 414 |
private Row row; |
| 415 |
|
| 416 |
public MVStoreCursor(TMIterator<Long, SearchRow, Entry<Long, SearchRow>> it) { |
| 417 |
this.it = it; |
| 418 |
} |
| 419 |
|
| 420 |
@Override |
| 421 |
public Row get() { |
| 422 |
if (row == null) { |
| 423 |
if (current != null) { |
| 424 |
row = (Row)current.getValue(); |
| 425 |
if (row.getKey() == 0) { |
| 426 |
row.setKey(current.getKey()); |
| 427 |
} |
| 428 |
} |
| 429 |
} |
| 430 |
return row; |
| 431 |
} |
| 432 |
|
| 433 |
@Override |
| 434 |
public SearchRow getSearchRow() { |
| 435 |
return get(); |
| 436 |
} |
| 437 |
|
| 438 |
@Override |
| 439 |
public boolean next() { |
| 440 |
current = it.fetchNext(); |
| 441 |
row = null; |
| 442 |
return current != null; |
| 443 |
} |
| 444 |
|
| 445 |
@Override |
| 446 |
public boolean previous() { |
| 447 |
throw DbException.getUnsupportedException("previous"); |
| 448 |
} |
| 449 |
} |
| 450 |
} |