| 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.ArrayDeque; |
| 9 |
import java.util.ArrayList; |
| 10 |
import java.util.HashSet; |
| 11 |
import java.util.Set; |
| 12 |
import java.util.concurrent.ConcurrentHashMap; |
| 13 |
import java.util.concurrent.atomic.AtomicInteger; |
| 14 |
import java.util.concurrent.atomic.AtomicLong; |
| 15 |
import org.h2.api.DatabaseEventListener; |
| 16 |
import org.h2.api.ErrorCode; |
| 17 |
import org.h2.command.ddl.CreateTableData; |
| 18 |
import org.h2.constraint.Constraint; |
| 19 |
import org.h2.constraint.ConstraintReferential; |
| 20 |
import org.h2.engine.Constants; |
| 21 |
import org.h2.engine.Database; |
| 22 |
import org.h2.engine.SessionLocal; |
| 23 |
import org.h2.engine.SysProperties; |
| 24 |
import org.h2.index.Cursor; |
| 25 |
import org.h2.index.Index; |
| 26 |
import org.h2.index.IndexType; |
| 27 |
import org.h2.message.DbException; |
| 28 |
import org.h2.message.Trace; |
| 29 |
import org.h2.mode.DefaultNullOrdering; |
| 30 |
import org.h2.mvstore.DataUtils; |
| 31 |
import org.h2.mvstore.MVStoreException; |
| 32 |
import org.h2.mvstore.tx.Transaction; |
| 33 |
import org.h2.mvstore.tx.TransactionStore; |
| 34 |
import org.h2.result.Row; |
| 35 |
import org.h2.result.SearchRow; |
| 36 |
import org.h2.result.SortOrder; |
| 37 |
import org.h2.table.Column; |
| 38 |
import org.h2.table.IndexColumn; |
| 39 |
import org.h2.table.Table; |
| 40 |
import org.h2.table.TableBase; |
| 41 |
import org.h2.table.TableType; |
| 42 |
import org.h2.util.DebuggingThreadLocal; |
| 43 |
import org.h2.util.Utils; |
| 44 |
import org.h2.value.DataType; |
| 45 |
import org.h2.value.TypeInfo; |
| 46 |
|
| 47 |
/** |
| 48 |
* A table stored in a MVStore. |
| 49 |
*/ |
| 50 |
public class MVTable extends TableBase { |
| 51 |
/** |
| 52 |
* The table name this thread is waiting to lock. |
| 53 |
*/ |
| 54 |
public static final DebuggingThreadLocal<String> WAITING_FOR_LOCK; |
| 55 |
|
| 56 |
/** |
| 57 |
* The table names this thread has exclusively locked. |
| 58 |
*/ |
| 59 |
public static final DebuggingThreadLocal<ArrayList<String>> EXCLUSIVE_LOCKS; |
| 60 |
|
| 61 |
/** |
| 62 |
* The tables names this thread has a shared lock on. |
| 63 |
*/ |
| 64 |
public static final DebuggingThreadLocal<ArrayList<String>> SHARED_LOCKS; |
| 65 |
|
| 66 |
/** |
| 67 |
* The type of trace lock events |
| 68 |
*/ |
| 69 |
private enum TraceLockEvent{ |
| 70 |
|
| 71 |
TRACE_LOCK_OK("ok"), |
| 72 |
TRACE_LOCK_WAITING_FOR("waiting for"), |
| 73 |
TRACE_LOCK_REQUESTING_FOR("requesting for"), |
| 74 |
TRACE_LOCK_TIMEOUT_AFTER("timeout after "), |
| 75 |
TRACE_LOCK_UNLOCK("unlock"), |
| 76 |
TRACE_LOCK_ADDED_FOR("added for"), |
| 77 |
TRACE_LOCK_ADD_UPGRADED_FOR("add (upgraded) for "); |
| 78 |
|
| 79 |
private final String eventText; |
| 80 |
|
| 81 |
TraceLockEvent(String eventText) { |
| 82 |
this.eventText = eventText; |
| 83 |
} |
| 84 |
|
| 85 |
public String getEventText() { |
| 86 |
return eventText; |
| 87 |
} |
| 88 |
} |
| 89 |
private static final String NO_EXTRA_INFO = ""; |
| 90 |
|
| 91 |
static { |
| 92 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 93 |
WAITING_FOR_LOCK = new DebuggingThreadLocal<>(); |
| 94 |
EXCLUSIVE_LOCKS = new DebuggingThreadLocal<>(); |
| 95 |
SHARED_LOCKS = new DebuggingThreadLocal<>(); |
| 96 |
} else { |
| 97 |
WAITING_FOR_LOCK = null; |
| 98 |
EXCLUSIVE_LOCKS = null; |
| 99 |
SHARED_LOCKS = null; |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
/** |
| 104 |
* Whether the table contains a CLOB or BLOB. |
| 105 |
*/ |
| 106 |
private final boolean containsLargeObject; |
| 107 |
|
| 108 |
/** |
| 109 |
* The session (if any) that has exclusively locked this table. |
| 110 |
*/ |
| 111 |
private volatile SessionLocal lockExclusiveSession; |
| 112 |
|
| 113 |
/** |
| 114 |
* The set of sessions (if any) that have a shared lock on the table. Here |
| 115 |
* we are using using a ConcurrentHashMap as a set, as there is no |
| 116 |
* ConcurrentHashSet. |
| 117 |
*/ |
| 118 |
private final ConcurrentHashMap<SessionLocal, SessionLocal> lockSharedSessions = new ConcurrentHashMap<>(); |
| 119 |
|
| 120 |
private Column rowIdColumn; |
| 121 |
|
| 122 |
private final MVPrimaryIndex primaryIndex; |
| 123 |
private final ArrayList<Index> indexes = Utils.newSmallArrayList(); |
| 124 |
private final AtomicLong lastModificationId = new AtomicLong(); |
| 125 |
|
| 126 |
/** |
| 127 |
* The queue of sessions waiting to lock the table. It is a FIFO queue to |
| 128 |
* prevent starvation, since Java's synchronized locking is biased. |
| 129 |
*/ |
| 130 |
private final ArrayDeque<SessionLocal> waitingSessions = new ArrayDeque<>(); |
| 131 |
private final Trace traceLock; |
| 132 |
private final AtomicInteger changesUntilAnalyze; |
| 133 |
private int nextAnalyze; |
| 134 |
|
| 135 |
private final Store store; |
| 136 |
private final TransactionStore transactionStore; |
| 137 |
|
| 138 |
public MVTable(CreateTableData data, Store store) { |
| 139 |
super(data); |
| 140 |
this.isHidden = data.isHidden; |
| 141 |
boolean b = false; |
| 142 |
for (Column col : getColumns()) { |
| 143 |
if (DataType.isLargeObject(col.getType().getValueType())) { |
| 144 |
b = true; |
| 145 |
break; |
| 146 |
} |
| 147 |
} |
| 148 |
containsLargeObject = b; |
| 149 |
nextAnalyze = database.getSettings().analyzeAuto; |
| 150 |
changesUntilAnalyze = nextAnalyze <= 0 ? null : new AtomicInteger(nextAnalyze); |
| 151 |
this.store = store; |
| 152 |
this.transactionStore = store.getTransactionStore(); |
| 153 |
traceLock = database.getTrace(Trace.LOCK); |
| 154 |
|
| 155 |
primaryIndex = new MVPrimaryIndex(database, this, getId(), |
| 156 |
IndexColumn.wrap(getColumns()), IndexType.createScan(true)); |
| 157 |
indexes.add(primaryIndex); |
| 158 |
} |
| 159 |
|
| 160 |
public String getMapName() { |
| 161 |
return primaryIndex.getMapName(); |
| 162 |
} |
| 163 |
|
| 164 |
@Override |
| 165 |
public boolean lock(SessionLocal session, int lockType) { |
| 166 |
if (database.getLockMode() == Constants.LOCK_MODE_OFF) { |
| 167 |
session.registerTableAsUpdated(this); |
| 168 |
return false; |
| 169 |
} |
| 170 |
if (lockType == Table.READ_LOCK && lockExclusiveSession == null) { |
| 171 |
return false; |
| 172 |
} |
| 173 |
if (lockExclusiveSession == session) { |
| 174 |
return true; |
| 175 |
} |
| 176 |
if (lockType != Table.EXCLUSIVE_LOCK && lockSharedSessions.containsKey(session)) { |
| 177 |
return true; |
| 178 |
} |
| 179 |
synchronized (this) { |
| 180 |
if (lockType != Table.EXCLUSIVE_LOCK && lockSharedSessions.containsKey(session)) { |
| 181 |
return true; |
| 182 |
} |
| 183 |
session.setWaitForLock(this, Thread.currentThread()); |
| 184 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 185 |
WAITING_FOR_LOCK.set(getName()); |
| 186 |
} |
| 187 |
waitingSessions.addLast(session); |
| 188 |
try { |
| 189 |
doLock1(session, lockType); |
| 190 |
} finally { |
| 191 |
session.setWaitForLock(null, null); |
| 192 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 193 |
WAITING_FOR_LOCK.remove(); |
| 194 |
} |
| 195 |
waitingSessions.remove(session); |
| 196 |
} |
| 197 |
} |
| 198 |
return false; |
| 199 |
} |
| 200 |
|
| 201 |
private void doLock1(SessionLocal session, int lockType) { |
| 202 |
traceLock(session, lockType, TraceLockEvent.TRACE_LOCK_REQUESTING_FOR, NO_EXTRA_INFO); |
| 203 |
// don't get the current time unless necessary |
| 204 |
long max = 0L; |
| 205 |
boolean checkDeadlock = false; |
| 206 |
while (true) { |
| 207 |
// if I'm the next one in the queue |
| 208 |
if (waitingSessions.getFirst() == session && lockExclusiveSession == null) { |
| 209 |
if (doLock2(session, lockType)) { |
| 210 |
return; |
| 211 |
} |
| 212 |
} |
| 213 |
if (checkDeadlock) { |
| 214 |
ArrayList<SessionLocal> sessions = checkDeadlock(session, null, null); |
| 215 |
if (sessions != null) { |
| 216 |
throw DbException.get(ErrorCode.DEADLOCK_1, |
| 217 |
getDeadlockDetails(sessions, lockType)); |
| 218 |
} |
| 219 |
} else { |
| 220 |
// check for deadlocks from now on |
| 221 |
checkDeadlock = true; |
| 222 |
} |
| 223 |
long now = System.nanoTime(); |
| 224 |
if (max == 0L) { |
| 225 |
// try at least one more time |
| 226 |
max = Utils.nanoTimePlusMillis(now, session.getLockTimeout()); |
| 227 |
} else if (now - max >= 0L) { |
| 228 |
traceLock(session, lockType, |
| 229 |
TraceLockEvent.TRACE_LOCK_TIMEOUT_AFTER, Integer.toString(session.getLockTimeout())); |
| 230 |
throw DbException.get(ErrorCode.LOCK_TIMEOUT_1, getName()); |
| 231 |
} |
| 232 |
try { |
| 233 |
traceLock(session, lockType, TraceLockEvent.TRACE_LOCK_WAITING_FOR, NO_EXTRA_INFO); |
| 234 |
// don't wait too long so that deadlocks are detected early |
| 235 |
long sleep = Math.min(Constants.DEADLOCK_CHECK, (max - now) / 1_000_000L); |
| 236 |
if (sleep == 0) { |
| 237 |
sleep = 1; |
| 238 |
} |
| 239 |
wait(sleep); |
| 240 |
} catch (InterruptedException e) { |
| 241 |
// ignore |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
private boolean doLock2(SessionLocal session, int lockType) { |
| 247 |
switch (lockType) { |
| 248 |
case Table.EXCLUSIVE_LOCK: |
| 249 |
int size = lockSharedSessions.size(); |
| 250 |
if (size == 0) { |
| 251 |
traceLock(session, lockType, TraceLockEvent.TRACE_LOCK_ADDED_FOR, NO_EXTRA_INFO); |
| 252 |
session.registerTableAsLocked(this); |
| 253 |
} else if (size == 1 && lockSharedSessions.containsKey(session)) { |
| 254 |
traceLock(session, lockType, TraceLockEvent.TRACE_LOCK_ADD_UPGRADED_FOR, NO_EXTRA_INFO); |
| 255 |
} else { |
| 256 |
return false; |
| 257 |
} |
| 258 |
lockExclusiveSession = session; |
| 259 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 260 |
addLockToDebugList(EXCLUSIVE_LOCKS); |
| 261 |
} |
| 262 |
break; |
| 263 |
case Table.WRITE_LOCK: |
| 264 |
if (lockSharedSessions.putIfAbsent(session, session) == null) { |
| 265 |
traceLock(session, lockType, TraceLockEvent.TRACE_LOCK_OK, NO_EXTRA_INFO); |
| 266 |
session.registerTableAsLocked(this); |
| 267 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 268 |
addLockToDebugList(SHARED_LOCKS); |
| 269 |
} |
| 270 |
} |
| 271 |
} |
| 272 |
return true; |
| 273 |
} |
| 274 |
|
| 275 |
private void addLockToDebugList(DebuggingThreadLocal<ArrayList<String>> locks) { |
| 276 |
ArrayList<String> list = locks.get(); |
| 277 |
if (list == null) { |
| 278 |
list = new ArrayList<>(); |
| 279 |
locks.set(list); |
| 280 |
} |
| 281 |
list.add(getName()); |
| 282 |
} |
| 283 |
|
| 284 |
private void traceLock(SessionLocal session, int lockType, TraceLockEvent eventEnum, String extraInfo) { |
| 285 |
if (traceLock.isDebugEnabled()) { |
| 286 |
traceLock.debug("{0} {1} {2} {3} {4}", session.getId(), |
| 287 |
lockTypeToString(lockType), eventEnum.getEventText(), |
| 288 |
getName(), extraInfo); |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
@Override |
| 293 |
public void unlock(SessionLocal s) { |
| 294 |
if (database != null) { |
| 295 |
int lockType; |
| 296 |
if (lockExclusiveSession == s) { |
| 297 |
lockType = Table.EXCLUSIVE_LOCK; |
| 298 |
lockSharedSessions.remove(s); |
| 299 |
lockExclusiveSession = null; |
| 300 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 301 |
ArrayList<String> exclusiveLocks = EXCLUSIVE_LOCKS.get(); |
| 302 |
if (exclusiveLocks != null) { |
| 303 |
exclusiveLocks.remove(getName()); |
| 304 |
} |
| 305 |
} |
| 306 |
} else { |
| 307 |
lockType = lockSharedSessions.remove(s) != null ? Table.WRITE_LOCK : Table.READ_LOCK; |
| 308 |
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { |
| 309 |
ArrayList<String> sharedLocks = SHARED_LOCKS.get(); |
| 310 |
if (sharedLocks != null) { |
| 311 |
sharedLocks.remove(getName()); |
| 312 |
} |
| 313 |
} |
| 314 |
} |
| 315 |
traceLock(s, lockType, TraceLockEvent.TRACE_LOCK_UNLOCK, NO_EXTRA_INFO); |
| 316 |
if (lockType != Table.READ_LOCK && !waitingSessions.isEmpty()) { |
| 317 |
synchronized (this) { |
| 318 |
notifyAll(); |
| 319 |
} |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
@Override |
| 325 |
public void close(SessionLocal session) { |
| 326 |
// ignore |
| 327 |
} |
| 328 |
|
| 329 |
@Override |
| 330 |
public Row getRow(SessionLocal session, long key) { |
| 331 |
return primaryIndex.getRow(session, key); |
| 332 |
} |
| 333 |
|
| 334 |
@Override |
| 335 |
public Index addIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, |
| 336 |
int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) { |
| 337 |
cols = prepareColumns(database, cols, indexType); |
| 338 |
boolean isSessionTemporary = isTemporary() && !isGlobalTemporary(); |
| 339 |
if (!isSessionTemporary) { |
| 340 |
database.lockMeta(session); |
| 341 |
} |
| 342 |
MVIndex<?,?> index; |
| 343 |
int mainIndexColumn = primaryIndex.getMainIndexColumn() != SearchRow.ROWID_INDEX |
| 344 |
? SearchRow.ROWID_INDEX : getMainIndexColumn(indexType, cols); |
| 345 |
if (database.isStarting()) { |
| 346 |
// if index does exists as a separate map it can't be a delegate |
| 347 |
if (transactionStore.hasMap("index." + indexId)) { |
| 348 |
// we can not reuse primary index |
| 349 |
mainIndexColumn = SearchRow.ROWID_INDEX; |
| 350 |
} |
| 351 |
} else if (primaryIndex.getRowCountMax() != 0) { |
| 352 |
mainIndexColumn = SearchRow.ROWID_INDEX; |
| 353 |
} |
| 354 |
|
| 355 |
if (mainIndexColumn != SearchRow.ROWID_INDEX) { |
| 356 |
primaryIndex.setMainIndexColumn(mainIndexColumn); |
| 357 |
index = new MVDelegateIndex(this, indexId, indexName, primaryIndex, |
| 358 |
indexType); |
| 359 |
} else if (indexType.isSpatial()) { |
| 360 |
index = new MVSpatialIndex(session.getDatabase(), this, indexId, |
| 361 |
indexName, cols, uniqueColumnCount, indexType); |
| 362 |
} else { |
| 363 |
index = new MVSecondaryIndex(session.getDatabase(), this, indexId, |
| 364 |
indexName, cols, uniqueColumnCount, indexType); |
| 365 |
} |
| 366 |
if (index.needRebuild()) { |
| 367 |
rebuildIndex(session, index, indexName); |
| 368 |
} |
| 369 |
index.setTemporary(isTemporary()); |
| 370 |
if (index.getCreateSQL() != null) { |
| 371 |
index.setComment(indexComment); |
| 372 |
if (isSessionTemporary) { |
| 373 |
session.addLocalTempTableIndex(index); |
| 374 |
} else { |
| 375 |
database.addSchemaObject(session, index); |
| 376 |
} |
| 377 |
} |
| 378 |
indexes.add(index); |
| 379 |
setModified(); |
| 380 |
return index; |
| 381 |
} |
| 382 |
|
| 383 |
private void rebuildIndex(SessionLocal session, MVIndex<?,?> index, String indexName) { |
| 384 |
try { |
| 385 |
if (!session.getDatabase().isPersistent() || index instanceof MVSpatialIndex) { |
| 386 |
// in-memory |
| 387 |
rebuildIndexBuffered(session, index); |
| 388 |
} else { |
| 389 |
rebuildIndexBlockMerge(session, index); |
| 390 |
} |
| 391 |
} catch (DbException e) { |
| 392 |
getSchema().freeUniqueName(indexName); |
| 393 |
try { |
| 394 |
index.remove(session); |
| 395 |
} catch (DbException e2) { |
| 396 |
// this could happen, for example on failure in the storage |
| 397 |
// but if that is not the case it means |
| 398 |
// there is something wrong with the database |
| 399 |
trace.error(e2, "could not remove index"); |
| 400 |
throw e2; |
| 401 |
} |
| 402 |
throw e; |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
private void rebuildIndexBlockMerge(SessionLocal session, MVIndex<?,?> index) { |
| 407 |
// Read entries in memory, sort them, write to a new map (in sorted |
| 408 |
// order); repeat (using a new map for every block of 1 MB) until all |
| 409 |
// record are read. Merge all maps to the target (using merge sort; |
| 410 |
// duplicates are detected in the target). For randomly ordered data, |
| 411 |
// this should use relatively few write operations. |
| 412 |
// A possible optimization is: change the buffer size from "row count" |
| 413 |
// to "amount of memory", and buffer index keys instead of rows. |
| 414 |
Index scan = getScanIndex(session); |
| 415 |
long remaining = scan.getRowCount(session); |
| 416 |
long total = remaining; |
| 417 |
Cursor cursor = scan.find(session, null, null); |
| 418 |
long i = 0; |
| 419 |
Store store = session.getDatabase().getStore(); |
| 420 |
|
| 421 |
int bufferSize = (int) Math.min(total, database.getMaxMemoryRows() / 2); |
| 422 |
ArrayList<Row> buffer = new ArrayList<>(bufferSize); |
| 423 |
String n = getName() + ':' + index.getName(); |
| 424 |
ArrayList<String> bufferNames = Utils.newSmallArrayList(); |
| 425 |
while (cursor.next()) { |
| 426 |
Row row = cursor.get(); |
| 427 |
buffer.add(row); |
| 428 |
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n, i++, total); |
| 429 |
if (buffer.size() >= bufferSize) { |
| 430 |
sortRows(buffer, index); |
| 431 |
String mapName = store.nextTemporaryMapName(); |
| 432 |
index.addRowsToBuffer(buffer, mapName); |
| 433 |
bufferNames.add(mapName); |
| 434 |
buffer.clear(); |
| 435 |
} |
| 436 |
remaining--; |
| 437 |
} |
| 438 |
sortRows(buffer, index); |
| 439 |
if (!bufferNames.isEmpty()) { |
| 440 |
String mapName = store.nextTemporaryMapName(); |
| 441 |
index.addRowsToBuffer(buffer, mapName); |
| 442 |
bufferNames.add(mapName); |
| 443 |
buffer.clear(); |
| 444 |
index.addBufferedRows(bufferNames); |
| 445 |
} else { |
| 446 |
addRowsToIndex(session, buffer, index); |
| 447 |
} |
| 448 |
if (remaining != 0) { |
| 449 |
throw DbException.getInternalError("rowcount remaining=" + remaining + ' ' + getName()); |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
private void rebuildIndexBuffered(SessionLocal session, Index index) { |
| 454 |
Index scan = getScanIndex(session); |
| 455 |
long remaining = scan.getRowCount(session); |
| 456 |
long total = remaining; |
| 457 |
Cursor cursor = scan.find(session, null, null); |
| 458 |
long i = 0; |
| 459 |
int bufferSize = (int) Math.min(total, database.getMaxMemoryRows()); |
| 460 |
ArrayList<Row> buffer = new ArrayList<>(bufferSize); |
| 461 |
String n = getName() + ':' + index.getName(); |
| 462 |
while (cursor.next()) { |
| 463 |
Row row = cursor.get(); |
| 464 |
buffer.add(row); |
| 465 |
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n, i++, total); |
| 466 |
if (buffer.size() >= bufferSize) { |
| 467 |
addRowsToIndex(session, buffer, index); |
| 468 |
} |
| 469 |
remaining--; |
| 470 |
} |
| 471 |
addRowsToIndex(session, buffer, index); |
| 472 |
if (remaining != 0) { |
| 473 |
throw DbException.getInternalError("rowcount remaining=" + remaining + ' ' + getName()); |
| 474 |
} |
| 475 |
} |
| 476 |
|
| 477 |
@Override |
| 478 |
public void removeRow(SessionLocal session, Row row) { |
| 479 |
syncLastModificationIdWithDatabase(); |
| 480 |
Transaction t = session.getTransaction(); |
| 481 |
long savepoint = t.setSavepoint(); |
| 482 |
try { |
| 483 |
for (int i = indexes.size() - 1; i >= 0; i--) { |
| 484 |
Index index = indexes.get(i); |
| 485 |
index.remove(session, row); |
| 486 |
} |
| 487 |
} catch (Throwable e) { |
| 488 |
try { |
| 489 |
t.rollbackToSavepoint(savepoint); |
| 490 |
} catch (Throwable nested) { |
| 491 |
e.addSuppressed(nested); |
| 492 |
} |
| 493 |
throw DbException.convert(e); |
| 494 |
} |
| 495 |
analyzeIfRequired(session); |
| 496 |
} |
| 497 |
|
| 498 |
@Override |
| 499 |
public long truncate(SessionLocal session) { |
| 500 |
syncLastModificationIdWithDatabase(); |
| 501 |
long result = getRowCountApproximation(session); |
| 502 |
for (int i = indexes.size() - 1; i >= 0; i--) { |
| 503 |
Index index = indexes.get(i); |
| 504 |
index.truncate(session); |
| 505 |
} |
| 506 |
if (changesUntilAnalyze != null) { |
| 507 |
changesUntilAnalyze.set(nextAnalyze); |
| 508 |
} |
| 509 |
return result; |
| 510 |
} |
| 511 |
|
| 512 |
@Override |
| 513 |
public void addRow(SessionLocal session, Row row) { |
| 514 |
syncLastModificationIdWithDatabase(); |
| 515 |
Transaction t = session.getTransaction(); |
| 516 |
long savepoint = t.setSavepoint(); |
| 517 |
try { |
| 518 |
for (Index index : indexes) { |
| 519 |
index.add(session, row); |
| 520 |
} |
| 521 |
} catch (Throwable e) { |
| 522 |
try { |
| 523 |
t.rollbackToSavepoint(savepoint); |
| 524 |
} catch (Throwable nested) { |
| 525 |
e.addSuppressed(nested); |
| 526 |
} |
| 527 |
throw DbException.convert(e); |
| 528 |
} |
| 529 |
analyzeIfRequired(session); |
| 530 |
} |
| 531 |
|
| 532 |
@Override |
| 533 |
public void updateRow(SessionLocal session, Row oldRow, Row newRow) { |
| 534 |
newRow.setKey(oldRow.getKey()); |
| 535 |
syncLastModificationIdWithDatabase(); |
| 536 |
Transaction t = session.getTransaction(); |
| 537 |
long savepoint = t.setSavepoint(); |
| 538 |
try { |
| 539 |
for (Index index : indexes) { |
| 540 |
index.update(session, oldRow, newRow); |
| 541 |
} |
| 542 |
} catch (Throwable e) { |
| 543 |
try { |
| 544 |
t.rollbackToSavepoint(savepoint); |
| 545 |
} catch (Throwable nested) { |
| 546 |
e.addSuppressed(nested); |
| 547 |
} |
| 548 |
throw DbException.convert(e); |
| 549 |
} |
| 550 |
analyzeIfRequired(session); |
| 551 |
} |
| 552 |
|
| 553 |
@Override |
| 554 |
public Row lockRow(SessionLocal session, Row row, int timeoutMillis) { |
| 555 |
Row lockedRow = primaryIndex.lockRow(session, row, timeoutMillis); |
| 556 |
if (lockedRow == null || !row.hasSharedData(lockedRow)) { |
| 557 |
syncLastModificationIdWithDatabase(); |
| 558 |
} |
| 559 |
return lockedRow; |
| 560 |
} |
| 561 |
|
| 562 |
private void analyzeIfRequired(SessionLocal session) { |
| 563 |
if (changesUntilAnalyze != null) { |
| 564 |
if (changesUntilAnalyze.decrementAndGet() == 0) { |
| 565 |
if (nextAnalyze <= Integer.MAX_VALUE / 2) { |
| 566 |
nextAnalyze *= 2; |
| 567 |
} |
| 568 |
changesUntilAnalyze.set(nextAnalyze); |
| 569 |
session.markTableForAnalyze(this); |
| 570 |
} |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
@Override |
| 575 |
public Index getScanIndex(SessionLocal session) { |
| 576 |
return primaryIndex; |
| 577 |
} |
| 578 |
|
| 579 |
@Override |
| 580 |
public ArrayList<Index> getIndexes() { |
| 581 |
return indexes; |
| 582 |
} |
| 583 |
|
| 584 |
@Override |
| 585 |
public long getMaxDataModificationId() { |
| 586 |
return lastModificationId.get(); |
| 587 |
} |
| 588 |
|
| 589 |
@Override |
| 590 |
public void removeChildrenAndResources(SessionLocal session) { |
| 591 |
if (containsLargeObject) { |
| 592 |
// unfortunately, the data is gone on rollback |
| 593 |
truncate(session); |
| 594 |
database.getLobStorage().removeAllForTable(getId()); |
| 595 |
database.lockMeta(session); |
| 596 |
} |
| 597 |
database.getStore().removeTable(this); |
| 598 |
super.removeChildrenAndResources(session); |
| 599 |
// remove scan index (at position 0 on the list) last |
| 600 |
while (indexes.size() > 1) { |
| 601 |
Index index = indexes.get(1); |
| 602 |
index.remove(session); |
| 603 |
if (index.getName() != null) { |
| 604 |
database.removeSchemaObject(session, index); |
| 605 |
} |
| 606 |
// needed for session temporary indexes |
| 607 |
indexes.remove(index); |
| 608 |
} |
| 609 |
primaryIndex.remove(session); |
| 610 |
indexes.clear(); |
| 611 |
close(session); |
| 612 |
invalidate(); |
| 613 |
} |
| 614 |
|
| 615 |
@Override |
| 616 |
public long getRowCount(SessionLocal session) { |
| 617 |
return primaryIndex.getRowCount(session); |
| 618 |
} |
| 619 |
|
| 620 |
@Override |
| 621 |
public long getRowCountApproximation(SessionLocal session) { |
| 622 |
return primaryIndex.getRowCountApproximation(session); |
| 623 |
} |
| 624 |
|
| 625 |
@Override |
| 626 |
public long getDiskSpaceUsed() { |
| 627 |
return primaryIndex.getDiskSpaceUsed(); |
| 628 |
} |
| 629 |
|
| 630 |
/** |
| 631 |
* Get a new transaction. |
| 632 |
* |
| 633 |
* @return the transaction |
| 634 |
*/ |
| 635 |
Transaction getTransactionBegin() { |
| 636 |
// TODO need to commit/rollback the transaction |
| 637 |
return transactionStore.begin(); |
| 638 |
} |
| 639 |
|
| 640 |
@Override |
| 641 |
public boolean isRowLockable() { |
| 642 |
return true; |
| 643 |
} |
| 644 |
|
| 645 |
/** |
| 646 |
* Mark the transaction as committed, so that the modification counter of |
| 647 |
* the database is incremented. |
| 648 |
*/ |
| 649 |
public void commit() { |
| 650 |
if (database != null) { |
| 651 |
syncLastModificationIdWithDatabase(); |
| 652 |
} |
| 653 |
} |
| 654 |
|
| 655 |
// Field lastModificationId can not be just a volatile, because window of opportunity |
| 656 |
// between reading database's modification id and storing this value in the field |
| 657 |
// could be exploited by another thread. |
| 658 |
// Second thread may do the same with possibly bigger (already advanced) |
| 659 |
// modification id, and when first thread finally updates the field, it will |
| 660 |
// result in lastModificationId jumping back. |
| 661 |
// This is, of course, unacceptable. |
| 662 |
private void syncLastModificationIdWithDatabase() { |
| 663 |
long nextModificationDataId = database.getNextModificationDataId(); |
| 664 |
long currentId; |
| 665 |
do { |
| 666 |
currentId = lastModificationId.get(); |
| 667 |
} while (nextModificationDataId > currentId && |
| 668 |
!lastModificationId.compareAndSet(currentId, nextModificationDataId)); |
| 669 |
} |
| 670 |
|
| 671 |
/** |
| 672 |
* Convert the MVStoreException to a database exception. |
| 673 |
* |
| 674 |
* @param e the illegal state exception |
| 675 |
* @return the database exception |
| 676 |
*/ |
| 677 |
DbException convertException(MVStoreException e) { |
| 678 |
return convertException(e, false); |
| 679 |
} |
| 680 |
|
| 681 |
/** |
| 682 |
* Convert the MVStoreException from attempt to lock a row to a database |
| 683 |
* exception. |
| 684 |
* |
| 685 |
* @param e the illegal state exception |
| 686 |
* @return the database exception |
| 687 |
*/ |
| 688 |
DbException convertLockException(MVStoreException e) { |
| 689 |
return convertException(e, true); |
| 690 |
} |
| 691 |
|
| 692 |
private DbException convertException(MVStoreException e, boolean lockException) { |
| 693 |
int errorCode = e.getErrorCode(); |
| 694 |
if (errorCode == DataUtils.ERROR_TRANSACTION_LOCKED) { |
| 695 |
return DbException.get(lockException ? ErrorCode.LOCK_TIMEOUT_1 : ErrorCode.CONCURRENT_UPDATE_1, |
| 696 |
e, getName()); |
| 697 |
} |
| 698 |
if (errorCode == DataUtils.ERROR_TRANSACTIONS_DEADLOCK) { |
| 699 |
return DbException.get(ErrorCode.DEADLOCK_1, e, getName()); |
| 700 |
} |
| 701 |
return store.convertMVStoreException(e); |
| 702 |
} |
| 703 |
|
| 704 |
@Override |
| 705 |
public int getMainIndexColumn() { |
| 706 |
return primaryIndex.getMainIndexColumn(); |
| 707 |
} |
| 708 |
|
| 709 |
|
| 710 |
/** |
| 711 |
* Appends the specified rows to the specified index. |
| 712 |
* |
| 713 |
* @param session |
| 714 |
* the session |
| 715 |
* @param list |
| 716 |
* the rows, list is cleared on completion |
| 717 |
* @param index |
| 718 |
* the index to append to |
| 719 |
*/ |
| 720 |
private static void addRowsToIndex(SessionLocal session, ArrayList<Row> list, Index index) { |
| 721 |
sortRows(list, index); |
| 722 |
for (Row row : list) { |
| 723 |
index.add(session, row); |
| 724 |
} |
| 725 |
list.clear(); |
| 726 |
} |
| 727 |
|
| 728 |
/** |
| 729 |
* Formats details of a deadlock. |
| 730 |
* |
| 731 |
* @param sessions |
| 732 |
* the list of sessions |
| 733 |
* @param lockType |
| 734 |
* the type of lock |
| 735 |
* @return formatted details of a deadlock |
| 736 |
*/ |
| 737 |
private static String getDeadlockDetails(ArrayList<SessionLocal> sessions, int lockType) { |
| 738 |
// We add the thread details here to make it easier for customers to |
| 739 |
// match up these error messages with their own logs. |
| 740 |
StringBuilder builder = new StringBuilder(); |
| 741 |
for (SessionLocal s : sessions) { |
| 742 |
Table lock = s.getWaitForLock(); |
| 743 |
Thread thread = s.getWaitForLockThread(); |
| 744 |
builder.append("\nSession ").append(s).append(" on thread ").append(thread.getName()) |
| 745 |
.append(" is waiting to lock ").append(lock.toString()) |
| 746 |
.append(" (").append(lockTypeToString(lockType)).append(") while locking "); |
| 747 |
boolean addComma = false; |
| 748 |
for (Table t : s.getLocks()) { |
| 749 |
if (addComma) { |
| 750 |
builder.append(", "); |
| 751 |
} |
| 752 |
addComma = true; |
| 753 |
builder.append(t.toString()); |
| 754 |
if (t instanceof MVTable) { |
| 755 |
if (((MVTable) t).lockExclusiveSession == s) { |
| 756 |
builder.append(" (exclusive)"); |
| 757 |
} else { |
| 758 |
builder.append(" (shared)"); |
| 759 |
} |
| 760 |
} |
| 761 |
} |
| 762 |
builder.append('.'); |
| 763 |
} |
| 764 |
return builder.toString(); |
| 765 |
} |
| 766 |
|
| 767 |
private static String lockTypeToString(int lockType) { |
| 768 |
return lockType == Table.READ_LOCK ? "shared read" |
| 769 |
: lockType == Table.WRITE_LOCK ? "shared write" : "exclusive"; |
| 770 |
} |
| 771 |
|
| 772 |
/** |
| 773 |
* Sorts the specified list of rows for a specified index. |
| 774 |
* |
| 775 |
* @param list |
| 776 |
* the list of rows |
| 777 |
* @param index |
| 778 |
* the index to sort for |
| 779 |
*/ |
| 780 |
private static void sortRows(ArrayList<? extends SearchRow> list, final Index index) { |
| 781 |
list.sort(index::compareRows); |
| 782 |
} |
| 783 |
|
| 784 |
@Override |
| 785 |
public boolean canDrop() { |
| 786 |
return true; |
| 787 |
} |
| 788 |
|
| 789 |
@Override |
| 790 |
public boolean canGetRowCount(SessionLocal session) { |
| 791 |
return true; |
| 792 |
} |
| 793 |
|
| 794 |
@Override |
| 795 |
public boolean canTruncate() { |
| 796 |
if (getCheckForeignKeyConstraints() && database.getReferentialIntegrity()) { |
| 797 |
ArrayList<Constraint> constraints = getConstraints(); |
| 798 |
if (constraints != null) { |
| 799 |
for (Constraint c : constraints) { |
| 800 |
if (c.getConstraintType() != Constraint.Type.REFERENTIAL) { |
| 801 |
continue; |
| 802 |
} |
| 803 |
ConstraintReferential ref = (ConstraintReferential) c; |
| 804 |
if (ref.getRefTable() == this) { |
| 805 |
return false; |
| 806 |
} |
| 807 |
} |
| 808 |
} |
| 809 |
} |
| 810 |
return true; |
| 811 |
} |
| 812 |
|
| 813 |
@Override |
| 814 |
public ArrayList<SessionLocal> checkDeadlock(SessionLocal session, SessionLocal clash, Set<SessionLocal> visited) { |
| 815 |
// only one deadlock check at any given time |
| 816 |
synchronized (getClass()) { |
| 817 |
if (clash == null) { |
| 818 |
// verification is started |
| 819 |
clash = session; |
| 820 |
visited = new HashSet<>(); |
| 821 |
} else if (clash == session) { |
| 822 |
// we found a cycle where this session is involved |
| 823 |
return new ArrayList<>(0); |
| 824 |
} else if (visited.contains(session)) { |
| 825 |
// we have already checked this session. |
| 826 |
// there is a cycle, but the sessions in the cycle need to |
| 827 |
// find it out themselves |
| 828 |
return null; |
| 829 |
} |
| 830 |
visited.add(session); |
| 831 |
ArrayList<SessionLocal> error = null; |
| 832 |
for (SessionLocal s : lockSharedSessions.keySet()) { |
| 833 |
if (s == session) { |
| 834 |
// it doesn't matter if we have locked the object already |
| 835 |
continue; |
| 836 |
} |
| 837 |
Table t = s.getWaitForLock(); |
| 838 |
if (t != null) { |
| 839 |
error = t.checkDeadlock(s, clash, visited); |
| 840 |
if (error != null) { |
| 841 |
error.add(session); |
| 842 |
break; |
| 843 |
} |
| 844 |
} |
| 845 |
} |
| 846 |
// take a local copy so we don't see inconsistent data, since we are |
| 847 |
// not locked while checking the lockExclusiveSession value |
| 848 |
SessionLocal copyOfLockExclusiveSession = lockExclusiveSession; |
| 849 |
if (error == null && copyOfLockExclusiveSession != null) { |
| 850 |
Table t = copyOfLockExclusiveSession.getWaitForLock(); |
| 851 |
if (t != null) { |
| 852 |
error = t.checkDeadlock(copyOfLockExclusiveSession, clash, visited); |
| 853 |
if (error != null) { |
| 854 |
error.add(session); |
| 855 |
} |
| 856 |
} |
| 857 |
} |
| 858 |
return error; |
| 859 |
} |
| 860 |
} |
| 861 |
|
| 862 |
@Override |
| 863 |
public void checkSupportAlter() { |
| 864 |
// ok |
| 865 |
} |
| 866 |
|
| 867 |
public boolean getContainsLargeObject() { |
| 868 |
return containsLargeObject; |
| 869 |
} |
| 870 |
|
| 871 |
@Override |
| 872 |
public Column getRowIdColumn() { |
| 873 |
if (rowIdColumn == null) { |
| 874 |
rowIdColumn = new Column(Column.ROWID, TypeInfo.TYPE_BIGINT, this, SearchRow.ROWID_INDEX); |
| 875 |
rowIdColumn.setRowId(true); |
| 876 |
rowIdColumn.setNullable(false); |
| 877 |
} |
| 878 |
return rowIdColumn; |
| 879 |
} |
| 880 |
|
| 881 |
@Override |
| 882 |
public TableType getTableType() { |
| 883 |
return TableType.TABLE; |
| 884 |
} |
| 885 |
|
| 886 |
@Override |
| 887 |
public boolean isDeterministic() { |
| 888 |
return true; |
| 889 |
} |
| 890 |
|
| 891 |
@Override |
| 892 |
public boolean isLockedExclusively() { |
| 893 |
return lockExclusiveSession != null; |
| 894 |
} |
| 895 |
|
| 896 |
@Override |
| 897 |
public boolean isLockedExclusivelyBy(SessionLocal session) { |
| 898 |
return lockExclusiveSession == session; |
| 899 |
} |
| 900 |
|
| 901 |
@Override |
| 902 |
protected void invalidate() { |
| 903 |
super.invalidate(); |
| 904 |
/* |
| 905 |
* Query cache of a some sleeping session can have references to |
| 906 |
* invalidated tables. When this table was dropped by another session, |
| 907 |
* the field below still points to it and prevents its garbage |
| 908 |
* collection, so this field needs to be cleared to prevent a memory |
| 909 |
* leak. |
| 910 |
*/ |
| 911 |
lockExclusiveSession = null; |
| 912 |
} |
| 913 |
|
| 914 |
@Override |
| 915 |
public String toString() { |
| 916 |
return getTraceSQL(); |
| 917 |
} |
| 918 |
|
| 919 |
/** |
| 920 |
* Prepares columns of an index. |
| 921 |
* |
| 922 |
* @param database the database |
| 923 |
* @param cols the index columns |
| 924 |
* @param indexType the type of an index |
| 925 |
* @return the prepared columns with flags set |
| 926 |
*/ |
| 927 |
private static IndexColumn[] prepareColumns(Database database, IndexColumn[] cols, IndexType indexType) { |
| 928 |
if (indexType.isPrimaryKey()) { |
| 929 |
for (IndexColumn c : cols) { |
| 930 |
Column column = c.column; |
| 931 |
if (column.isNullable()) { |
| 932 |
throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName()); |
| 933 |
} |
| 934 |
} |
| 935 |
for (IndexColumn c : cols) { |
| 936 |
c.column.setPrimaryKey(true); |
| 937 |
} |
| 938 |
} else if (!indexType.isSpatial()) { |
| 939 |
int i = 0, l = cols.length; |
| 940 |
while (i < l && (cols[i].sortType & (SortOrder.NULLS_FIRST | SortOrder.NULLS_LAST)) != 0) { |
| 941 |
i++; |
| 942 |
} |
| 943 |
if (i != l) { |
| 944 |
cols = cols.clone(); |
| 945 |
DefaultNullOrdering defaultNullOrdering = database.getDefaultNullOrdering(); |
| 946 |
for (; i < l; i++) { |
| 947 |
IndexColumn oldColumn = cols[i]; |
| 948 |
int sortTypeOld = oldColumn.sortType; |
| 949 |
int sortTypeNew = defaultNullOrdering.addExplicitNullOrdering(sortTypeOld); |
| 950 |
if (sortTypeNew != sortTypeOld) { |
| 951 |
IndexColumn newColumn = new IndexColumn(oldColumn.columnName, sortTypeNew); |
| 952 |
newColumn.column = oldColumn.column; |
| 953 |
cols[i] = newColumn; |
| 954 |
} |
| 955 |
} |
| 956 |
} |
| 957 |
} |
| 958 |
return cols; |
| 959 |
} |
| 960 |
} |