| 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.engine; |
| 7 |
|
| 8 |
import java.sql.SQLException; |
| 9 |
import java.util.ArrayList; |
| 10 |
import java.util.BitSet; |
| 11 |
import java.util.Collection; |
| 12 |
import java.util.Collections; |
| 13 |
import java.util.HashMap; |
| 14 |
import java.util.HashSet; |
| 15 |
import java.util.Map; |
| 16 |
import java.util.Objects; |
| 17 |
import java.util.Set; |
| 18 |
import java.util.concurrent.ConcurrentHashMap; |
| 19 |
import java.util.concurrent.atomic.AtomicLong; |
| 20 |
import java.util.concurrent.atomic.AtomicReference; |
| 21 |
import org.h2.api.DatabaseEventListener; |
| 22 |
import org.h2.api.ErrorCode; |
| 23 |
import org.h2.api.JavaObjectSerializer; |
| 24 |
import org.h2.api.TableEngine; |
| 25 |
import org.h2.command.CommandInterface; |
| 26 |
import org.h2.command.Prepared; |
| 27 |
import org.h2.command.ddl.CreateTableData; |
| 28 |
import org.h2.command.dml.SetTypes; |
| 29 |
import org.h2.constraint.Constraint; |
| 30 |
import org.h2.constraint.Constraint.Type; |
| 31 |
import org.h2.engine.Mode.ModeEnum; |
| 32 |
import org.h2.index.Cursor; |
| 33 |
import org.h2.index.Index; |
| 34 |
import org.h2.index.IndexType; |
| 35 |
import org.h2.message.DbException; |
| 36 |
import org.h2.message.Trace; |
| 37 |
import org.h2.message.TraceSystem; |
| 38 |
import org.h2.mode.DefaultNullOrdering; |
| 39 |
import org.h2.mode.PgCatalogSchema; |
| 40 |
import org.h2.mvstore.MVStoreException; |
| 41 |
import org.h2.mvstore.db.LobStorageMap; |
| 42 |
import org.h2.mvstore.db.Store; |
| 43 |
import org.h2.result.Row; |
| 44 |
import org.h2.result.RowFactory; |
| 45 |
import org.h2.result.SearchRow; |
| 46 |
import org.h2.schema.InformationSchema; |
| 47 |
import org.h2.schema.Schema; |
| 48 |
import org.h2.schema.SchemaObject; |
| 49 |
import org.h2.schema.Sequence; |
| 50 |
import org.h2.schema.TriggerObject; |
| 51 |
import org.h2.security.auth.Authenticator; |
| 52 |
import org.h2.store.DataHandler; |
| 53 |
import org.h2.store.FileLock; |
| 54 |
import org.h2.store.FileLockMethod; |
| 55 |
import org.h2.store.FileStore; |
| 56 |
import org.h2.store.InDoubtTransaction; |
| 57 |
import org.h2.store.LobStorageInterface; |
| 58 |
import org.h2.store.fs.FileUtils; |
| 59 |
import org.h2.store.fs.encrypt.FileEncrypt; |
| 60 |
import org.h2.table.Column; |
| 61 |
import org.h2.table.IndexColumn; |
| 62 |
import org.h2.table.Table; |
| 63 |
import org.h2.table.TableLinkConnection; |
| 64 |
import org.h2.table.TableSynonym; |
| 65 |
import org.h2.table.TableType; |
| 66 |
import org.h2.table.TableView; |
| 67 |
import org.h2.tools.DeleteDbFiles; |
| 68 |
import org.h2.tools.Server; |
| 69 |
import org.h2.util.JdbcUtils; |
| 70 |
import org.h2.util.MathUtils; |
| 71 |
import org.h2.util.NetUtils; |
| 72 |
import org.h2.util.NetworkConnectionInfo; |
| 73 |
import org.h2.util.SmallLRUCache; |
| 74 |
import org.h2.util.SourceCompiler; |
| 75 |
import org.h2.util.StringUtils; |
| 76 |
import org.h2.util.TempFileDeleter; |
| 77 |
import org.h2.util.TimeZoneProvider; |
| 78 |
import org.h2.util.Utils; |
| 79 |
import org.h2.value.CaseInsensitiveConcurrentMap; |
| 80 |
import org.h2.value.CaseInsensitiveMap; |
| 81 |
import org.h2.value.CompareMode; |
| 82 |
import org.h2.value.TypeInfo; |
| 83 |
import org.h2.value.ValueInteger; |
| 84 |
import org.h2.value.ValueTimestampTimeZone; |
| 85 |
|
| 86 |
/** |
| 87 |
* There is one database object per open database. |
| 88 |
* |
| 89 |
* The format of the meta data table is: |
| 90 |
* id int, 0, objectType int, sql varchar |
| 91 |
* |
| 92 |
* @since 2004-04-15 22:49 |
| 93 |
*/ |
| 94 |
public final class Database implements DataHandler, CastDataProvider { |
| 95 |
|
| 96 |
private static int initialPowerOffCount; |
| 97 |
|
| 98 |
private static final boolean ASSERT; |
| 99 |
|
| 100 |
private static final ThreadLocal<SessionLocal> META_LOCK_DEBUGGING; |
| 101 |
private static final ThreadLocal<Database> META_LOCK_DEBUGGING_DB; |
| 102 |
private static final ThreadLocal<Throwable> META_LOCK_DEBUGGING_STACK; |
| 103 |
private static final SessionLocal[] EMPTY_SESSION_ARRAY = new SessionLocal[0]; |
| 104 |
|
| 105 |
static { |
| 106 |
boolean a = false; |
| 107 |
// Intentional side-effect |
| 108 |
assert a = true; |
| 109 |
ASSERT = a; |
| 110 |
if (a) { |
| 111 |
META_LOCK_DEBUGGING = new ThreadLocal<>(); |
| 112 |
META_LOCK_DEBUGGING_DB = new ThreadLocal<>(); |
| 113 |
META_LOCK_DEBUGGING_STACK = new ThreadLocal<>(); |
| 114 |
} else { |
| 115 |
META_LOCK_DEBUGGING = null; |
| 116 |
META_LOCK_DEBUGGING_DB = null; |
| 117 |
META_LOCK_DEBUGGING_STACK = null; |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
/** |
| 122 |
* The default name of the system user. This name is only used as long as |
| 123 |
* there is no administrator user registered. |
| 124 |
*/ |
| 125 |
private static final String SYSTEM_USER_NAME = "DBA"; |
| 126 |
|
| 127 |
private final boolean persistent; |
| 128 |
private final String databaseName; |
| 129 |
private final String databaseShortName; |
| 130 |
private final String databaseURL; |
| 131 |
private final String cipher; |
| 132 |
private final byte[] filePasswordHash; |
| 133 |
|
| 134 |
private final ConcurrentHashMap<String, RightOwner> usersAndRoles = new ConcurrentHashMap<>(); |
| 135 |
private final ConcurrentHashMap<String, Setting> settings = new ConcurrentHashMap<>(); |
| 136 |
private final ConcurrentHashMap<String, Schema> schemas = new ConcurrentHashMap<>(); |
| 137 |
private final ConcurrentHashMap<String, Right> rights = new ConcurrentHashMap<>(); |
| 138 |
private final ConcurrentHashMap<String, Comment> comments = new ConcurrentHashMap<>(); |
| 139 |
|
| 140 |
private final HashMap<String, TableEngine> tableEngines = new HashMap<>(); |
| 141 |
|
| 142 |
private final Set<SessionLocal> userSessions = Collections.synchronizedSet(new HashSet<>()); |
| 143 |
private final AtomicReference<SessionLocal> exclusiveSession = new AtomicReference<>(); |
| 144 |
private final BitSet objectIds = new BitSet(); |
| 145 |
private final Object lobSyncObject = new Object(); |
| 146 |
|
| 147 |
private final Schema mainSchema; |
| 148 |
private final Schema infoSchema; |
| 149 |
private final Schema pgCatalogSchema; |
| 150 |
private int nextSessionId; |
| 151 |
private int nextTempTableId; |
| 152 |
private final User systemUser; |
| 153 |
private SessionLocal systemSession; |
| 154 |
private SessionLocal lobSession; |
| 155 |
private final Table meta; |
| 156 |
private final Index metaIdIndex; |
| 157 |
private FileLock lock; |
| 158 |
private volatile boolean starting; |
| 159 |
private final TraceSystem traceSystem; |
| 160 |
private final Trace trace; |
| 161 |
private final FileLockMethod fileLockMethod; |
| 162 |
private final Role publicRole; |
| 163 |
private final AtomicLong modificationDataId = new AtomicLong(); |
| 164 |
private final AtomicLong modificationMetaId = new AtomicLong(); |
| 165 |
/** |
| 166 |
* Used to trigger the client side to reload some of the settings. |
| 167 |
*/ |
| 168 |
private final AtomicLong remoteSettingsId = new AtomicLong(); |
| 169 |
private CompareMode compareMode; |
| 170 |
private String cluster = Constants.CLUSTERING_DISABLED; |
| 171 |
private boolean readOnly; |
| 172 |
private DatabaseEventListener eventListener; |
| 173 |
private int maxMemoryRows = SysProperties.MAX_MEMORY_ROWS; |
| 174 |
private int lockMode; |
| 175 |
private int maxLengthInplaceLob; |
| 176 |
private int allowLiterals = Constants.ALLOW_LITERALS_ALL; |
| 177 |
|
| 178 |
private int powerOffCount = initialPowerOffCount; |
| 179 |
private volatile int closeDelay; |
| 180 |
private DelayedDatabaseCloser delayedCloser; |
| 181 |
private volatile boolean closing; |
| 182 |
private boolean ignoreCase; |
| 183 |
private boolean deleteFilesOnDisconnect; |
| 184 |
private boolean optimizeReuseResults = true; |
| 185 |
private final String cacheType; |
| 186 |
private boolean referentialIntegrity = true; |
| 187 |
private Mode mode = Mode.getRegular(); |
| 188 |
private DefaultNullOrdering defaultNullOrdering = DefaultNullOrdering.LOW; |
| 189 |
private int maxOperationMemory = |
| 190 |
Constants.DEFAULT_MAX_OPERATION_MEMORY; |
| 191 |
private SmallLRUCache<String, String[]> lobFileListCache; |
| 192 |
private final boolean autoServerMode; |
| 193 |
private final int autoServerPort; |
| 194 |
private Server server; |
| 195 |
private HashMap<TableLinkConnection, TableLinkConnection> linkConnections; |
| 196 |
private final TempFileDeleter tempFileDeleter = TempFileDeleter.getInstance(); |
| 197 |
private int compactMode; |
| 198 |
private SourceCompiler compiler; |
| 199 |
private final LobStorageInterface lobStorage; |
| 200 |
private final int pageSize; |
| 201 |
private int defaultTableType = Table.TYPE_CACHED; |
| 202 |
private final DbSettings dbSettings; |
| 203 |
private final Store store; |
| 204 |
private boolean allowBuiltinAliasOverride; |
| 205 |
private final AtomicReference<DbException> backgroundException = new AtomicReference<>(); |
| 206 |
private JavaObjectSerializer javaObjectSerializer; |
| 207 |
private String javaObjectSerializerName; |
| 208 |
private volatile boolean javaObjectSerializerInitialized; |
| 209 |
private volatile boolean queryStatistics; |
| 210 |
private int queryStatisticsMaxEntries = Constants.QUERY_STATISTICS_MAX_ENTRIES; |
| 211 |
private QueryStatisticsData queryStatisticsData; |
| 212 |
private RowFactory rowFactory = RowFactory.getRowFactory(); |
| 213 |
private boolean ignoreCatalogs; |
| 214 |
|
| 215 |
private Authenticator authenticator; |
| 216 |
|
| 217 |
public Database(ConnectionInfo ci, String cipher) { |
| 218 |
if (ASSERT) { |
| 219 |
META_LOCK_DEBUGGING.set(null); |
| 220 |
META_LOCK_DEBUGGING_DB.set(null); |
| 221 |
META_LOCK_DEBUGGING_STACK.set(null); |
| 222 |
} |
| 223 |
String databaseName = ci.getName(); |
| 224 |
this.dbSettings = ci.getDbSettings(); |
| 225 |
this.compareMode = CompareMode.getInstance(null, 0); |
| 226 |
this.persistent = ci.isPersistent(); |
| 227 |
this.filePasswordHash = ci.getFilePasswordHash(); |
| 228 |
this.databaseName = databaseName; |
| 229 |
this.databaseShortName = parseDatabaseShortName(); |
| 230 |
this.maxLengthInplaceLob = persistent ? Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB : Integer.MAX_VALUE - 8; |
| 231 |
this.cipher = cipher; |
| 232 |
this.autoServerMode = ci.getProperty("AUTO_SERVER", false); |
| 233 |
this.autoServerPort = ci.getProperty("AUTO_SERVER_PORT", 0); |
| 234 |
pageSize = ci.getProperty("PAGE_SIZE", Constants.DEFAULT_PAGE_SIZE); |
| 235 |
if (cipher != null && pageSize % FileEncrypt.BLOCK_SIZE != 0) { |
| 236 |
throw DbException.getUnsupportedException("CIPHER && PAGE_SIZE=" + pageSize); |
| 237 |
} |
| 238 |
String accessModeData = StringUtils.toLowerEnglish(ci.getProperty("ACCESS_MODE_DATA", "rw")); |
| 239 |
if ("r".equals(accessModeData)) { |
| 240 |
readOnly = true; |
| 241 |
} |
| 242 |
String lockMethodName = ci.getProperty("FILE_LOCK", null); |
| 243 |
fileLockMethod = lockMethodName != null ? FileLock.getFileLockMethod(lockMethodName) : |
| 244 |
autoServerMode ? FileLockMethod.FILE : FileLockMethod.FS; |
| 245 |
this.databaseURL = ci.getURL(); |
| 246 |
String s = ci.removeProperty("DATABASE_EVENT_LISTENER", null); |
| 247 |
if (s != null) { |
| 248 |
setEventListenerClass(StringUtils.trim(s, true, true, '\'')); |
| 249 |
} |
| 250 |
s = ci.removeProperty("MODE", null); |
| 251 |
if (s != null) { |
| 252 |
mode = Mode.getInstance(s); |
| 253 |
if (mode == null) { |
| 254 |
throw DbException.get(ErrorCode.UNKNOWN_MODE_1, s); |
| 255 |
} |
| 256 |
} |
| 257 |
s = ci.removeProperty("DEFAULT_NULL_ORDERING", null); |
| 258 |
if (s != null) { |
| 259 |
try { |
| 260 |
defaultNullOrdering = DefaultNullOrdering.valueOf(StringUtils.toUpperEnglish(s)); |
| 261 |
} catch (RuntimeException e) { |
| 262 |
throw DbException.getInvalidValueException("DEFAULT_NULL_ORDERING", s); |
| 263 |
} |
| 264 |
} |
| 265 |
s = ci.getProperty("JAVA_OBJECT_SERIALIZER", null); |
| 266 |
if (s != null) { |
| 267 |
s = StringUtils.trim(s, true, true, '\''); |
| 268 |
javaObjectSerializerName = s; |
| 269 |
} |
| 270 |
this.allowBuiltinAliasOverride = ci.getProperty("BUILTIN_ALIAS_OVERRIDE", false); |
| 271 |
boolean closeAtVmShutdown = dbSettings.dbCloseOnExit; |
| 272 |
if (autoServerMode && !closeAtVmShutdown) { |
| 273 |
throw DbException.getUnsupportedException("AUTO_SERVER=TRUE && DB_CLOSE_ON_EXIT=FALSE"); |
| 274 |
} |
| 275 |
int traceLevelFile = ci.getIntProperty(SetTypes.TRACE_LEVEL_FILE, TraceSystem.DEFAULT_TRACE_LEVEL_FILE); |
| 276 |
int traceLevelSystemOut = ci.getIntProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT, |
| 277 |
TraceSystem.DEFAULT_TRACE_LEVEL_SYSTEM_OUT); |
| 278 |
this.cacheType = StringUtils.toUpperEnglish(ci.removeProperty("CACHE_TYPE", Constants.CACHE_TYPE_DEFAULT)); |
| 279 |
this.ignoreCatalogs = ci.getProperty("IGNORE_CATALOGS", dbSettings.ignoreCatalogs); |
| 280 |
this.lockMode = ci.getProperty("LOCK_MODE", Constants.DEFAULT_LOCK_MODE); |
| 281 |
String traceFile; |
| 282 |
if (persistent) { |
| 283 |
if (readOnly) { |
| 284 |
if (traceLevelFile >= TraceSystem.DEBUG) { |
| 285 |
traceFile = Utils.getProperty("java.io.tmpdir", ".") + "/h2_" + System.currentTimeMillis() |
| 286 |
+ Constants.SUFFIX_TRACE_FILE; |
| 287 |
} else { |
| 288 |
traceFile = null; |
| 289 |
} |
| 290 |
} else { |
| 291 |
traceFile = databaseName + Constants.SUFFIX_TRACE_FILE; |
| 292 |
} |
| 293 |
} else { |
| 294 |
traceFile = null; |
| 295 |
} |
| 296 |
traceSystem = new TraceSystem(traceFile); |
| 297 |
traceSystem.setLevelFile(traceLevelFile); |
| 298 |
traceSystem.setLevelSystemOut(traceLevelSystemOut); |
| 299 |
trace = traceSystem.getTrace(Trace.DATABASE); |
| 300 |
trace.info("opening {0} (build {1})", databaseName, Constants.BUILD_ID); |
| 301 |
try { |
| 302 |
if (autoServerMode && (readOnly || !persistent || fileLockMethod == FileLockMethod.NO |
| 303 |
|| fileLockMethod == FileLockMethod.FS)) { |
| 304 |
throw DbException.getUnsupportedException( |
| 305 |
"AUTO_SERVER=TRUE && (readOnly || inMemory || FILE_LOCK=NO || FILE_LOCK=FS)"); |
| 306 |
} |
| 307 |
if (persistent) { |
| 308 |
String lockFileName = databaseName + Constants.SUFFIX_LOCK_FILE; |
| 309 |
if (readOnly) { |
| 310 |
if (FileUtils.exists(lockFileName)) { |
| 311 |
throw DbException.get(ErrorCode.DATABASE_ALREADY_OPEN_1, "Lock file exists: " + lockFileName); |
| 312 |
} |
| 313 |
} else if (fileLockMethod != FileLockMethod.NO && fileLockMethod != FileLockMethod.FS) { |
| 314 |
lock = new FileLock(traceSystem, lockFileName, Constants.LOCK_SLEEP); |
| 315 |
lock.lock(fileLockMethod); |
| 316 |
if (autoServerMode) { |
| 317 |
startServer(lock.getUniqueId()); |
| 318 |
} |
| 319 |
} |
| 320 |
deleteOldTempFiles(); |
| 321 |
} |
| 322 |
starting = true; |
| 323 |
if (dbSettings.mvStore) { |
| 324 |
store = new Store(this, ci.getFileEncryptionKey()); |
| 325 |
} else { |
| 326 |
throw new UnsupportedOperationException(); |
| 327 |
} |
| 328 |
starting = false; |
| 329 |
systemUser = new User(this, 0, SYSTEM_USER_NAME, true); |
| 330 |
systemUser.setAdmin(true); |
| 331 |
mainSchema = new Schema(this, Constants.MAIN_SCHEMA_ID, sysIdentifier(Constants.SCHEMA_MAIN), systemUser, |
| 332 |
true); |
| 333 |
infoSchema = new InformationSchema(this, systemUser); |
| 334 |
schemas.put(mainSchema.getName(), mainSchema); |
| 335 |
schemas.put(infoSchema.getName(), infoSchema); |
| 336 |
if (mode.getEnum() == ModeEnum.PostgreSQL) { |
| 337 |
pgCatalogSchema = new PgCatalogSchema(this, systemUser); |
| 338 |
schemas.put(pgCatalogSchema.getName(), pgCatalogSchema); |
| 339 |
} else { |
| 340 |
pgCatalogSchema = null; |
| 341 |
} |
| 342 |
publicRole = new Role(this, 0, sysIdentifier(Constants.PUBLIC_ROLE_NAME), true); |
| 343 |
usersAndRoles.put(publicRole.getName(), publicRole); |
| 344 |
systemSession = createSession(systemUser); |
| 345 |
lobSession = createSession(systemUser); |
| 346 |
Set<String> settingKeys = dbSettings.getSettings().keySet(); |
| 347 |
store.getTransactionStore().init(lobSession); |
| 348 |
settingKeys.removeIf(name -> name.startsWith("PAGE_STORE_")); |
| 349 |
CreateTableData data = createSysTableData(); |
| 350 |
starting = true; |
| 351 |
meta = mainSchema.createTable(data); |
| 352 |
IndexColumn[] pkCols = IndexColumn.wrap(new Column[] { data.columns.get(0) }); |
| 353 |
metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, 1, |
| 354 |
IndexType.createPrimaryKey(false, false), true, null); |
| 355 |
systemSession.commit(true); |
| 356 |
objectIds.set(0); |
| 357 |
executeMeta(); |
| 358 |
systemSession.commit(true); |
| 359 |
store.getTransactionStore().endLeftoverTransactions(); |
| 360 |
store.removeTemporaryMaps(objectIds); |
| 361 |
recompileInvalidViews(); |
| 362 |
starting = false; |
| 363 |
if (!readOnly) { |
| 364 |
// set CREATE_BUILD in a new database |
| 365 |
String settingName = SetTypes.getTypeName(SetTypes.CREATE_BUILD); |
| 366 |
Setting setting = settings.get(settingName); |
| 367 |
if (setting == null) { |
| 368 |
setting = new Setting(this, allocateObjectId(), settingName); |
| 369 |
setting.setIntValue(Constants.BUILD_ID); |
| 370 |
lockMeta(systemSession); |
| 371 |
addDatabaseObject(systemSession, setting); |
| 372 |
} |
| 373 |
} |
| 374 |
lobStorage = new LobStorageMap(this); |
| 375 |
lobSession.commit(true); |
| 376 |
systemSession.commit(true); |
| 377 |
trace.info("opened {0}", databaseName); |
| 378 |
if (persistent) { |
| 379 |
int writeDelay = ci.getProperty("WRITE_DELAY", Constants.DEFAULT_WRITE_DELAY); |
| 380 |
setWriteDelay(writeDelay); |
| 381 |
} |
| 382 |
if (closeAtVmShutdown) { |
| 383 |
OnExitDatabaseCloser.register(this); |
| 384 |
} |
| 385 |
} catch (Throwable e) { |
| 386 |
try { |
| 387 |
if (e instanceof OutOfMemoryError) { |
| 388 |
e.fillInStackTrace(); |
| 389 |
} |
| 390 |
if (e instanceof DbException) { |
| 391 |
if (((DbException) e).getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1) { |
| 392 |
stopServer(); |
| 393 |
} else { |
| 394 |
// only write if the database is not already in use |
| 395 |
trace.error(e, "opening {0}", databaseName); |
| 396 |
} |
| 397 |
} |
| 398 |
traceSystem.close(); |
| 399 |
closeOpenFilesAndUnlock(); |
| 400 |
} catch (Throwable ex) { |
| 401 |
e.addSuppressed(ex); |
| 402 |
} |
| 403 |
throw DbException.convert(e); |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
public int getLockTimeout() { |
| 408 |
Setting setting = findSetting(SetTypes.getTypeName(SetTypes.DEFAULT_LOCK_TIMEOUT)); |
| 409 |
return setting == null ? Constants.INITIAL_LOCK_TIMEOUT : setting.getIntValue(); |
| 410 |
} |
| 411 |
|
| 412 |
public RowFactory getRowFactory() { |
| 413 |
return rowFactory; |
| 414 |
} |
| 415 |
|
| 416 |
public void setRowFactory(RowFactory rowFactory) { |
| 417 |
this.rowFactory = rowFactory; |
| 418 |
} |
| 419 |
|
| 420 |
public static void setInitialPowerOffCount(int count) { |
| 421 |
initialPowerOffCount = count; |
| 422 |
} |
| 423 |
|
| 424 |
public void setPowerOffCount(int count) { |
| 425 |
if (powerOffCount == -1) { |
| 426 |
return; |
| 427 |
} |
| 428 |
powerOffCount = count; |
| 429 |
} |
| 430 |
|
| 431 |
public Store getStore() { |
| 432 |
return store; |
| 433 |
} |
| 434 |
|
| 435 |
public long getModificationDataId() { |
| 436 |
return modificationDataId.get(); |
| 437 |
} |
| 438 |
|
| 439 |
public long getNextModificationDataId() { |
| 440 |
return modificationDataId.incrementAndGet(); |
| 441 |
} |
| 442 |
|
| 443 |
public long getModificationMetaId() { |
| 444 |
return modificationMetaId.get(); |
| 445 |
} |
| 446 |
|
| 447 |
public long getNextModificationMetaId() { |
| 448 |
// if the meta data has been modified, the data is modified as well |
| 449 |
// (because MetaTable returns modificationDataId) |
| 450 |
modificationDataId.incrementAndGet(); |
| 451 |
return modificationMetaId.incrementAndGet() - 1; |
| 452 |
} |
| 453 |
|
| 454 |
public long getRemoteSettingsId() { |
| 455 |
return remoteSettingsId.get(); |
| 456 |
} |
| 457 |
|
| 458 |
public long getNextRemoteSettingsId() { |
| 459 |
return remoteSettingsId.incrementAndGet(); |
| 460 |
} |
| 461 |
|
| 462 |
public int getPowerOffCount() { |
| 463 |
return powerOffCount; |
| 464 |
} |
| 465 |
|
| 466 |
@Override |
| 467 |
public void checkPowerOff() { |
| 468 |
if (powerOffCount != 0) { |
| 469 |
checkPowerOff2(); |
| 470 |
} |
| 471 |
} |
| 472 |
|
| 473 |
private void checkPowerOff2() { |
| 474 |
if (powerOffCount > 1) { |
| 475 |
powerOffCount--; |
| 476 |
return; |
| 477 |
} |
| 478 |
if (powerOffCount != -1) { |
| 479 |
try { |
| 480 |
powerOffCount = -1; |
| 481 |
store.closeImmediately(); |
| 482 |
if (lock != null) { |
| 483 |
stopServer(); |
| 484 |
// allow testing shutdown |
| 485 |
lock.unlock(); |
| 486 |
lock = null; |
| 487 |
} |
| 488 |
if (traceSystem != null) { |
| 489 |
traceSystem.close(); |
| 490 |
} |
| 491 |
} catch (DbException e) { |
| 492 |
DbException.traceThrowable(e); |
| 493 |
} |
| 494 |
} |
| 495 |
Engine.close(databaseName); |
| 496 |
throw DbException.get(ErrorCode.DATABASE_IS_CLOSED); |
| 497 |
} |
| 498 |
|
| 499 |
/** |
| 500 |
* Get the trace object for the given module id. |
| 501 |
* |
| 502 |
* @param moduleId the module id |
| 503 |
* @return the trace object |
| 504 |
*/ |
| 505 |
public Trace getTrace(int moduleId) { |
| 506 |
return traceSystem.getTrace(moduleId); |
| 507 |
} |
| 508 |
|
| 509 |
@Override |
| 510 |
public FileStore openFile(String name, String openMode, boolean mustExist) { |
| 511 |
if (mustExist && !FileUtils.exists(name)) { |
| 512 |
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name); |
| 513 |
} |
| 514 |
FileStore store = FileStore.open(this, name, openMode, cipher, |
| 515 |
filePasswordHash); |
| 516 |
try { |
| 517 |
store.init(); |
| 518 |
} catch (DbException e) { |
| 519 |
store.closeSilently(); |
| 520 |
throw e; |
| 521 |
} |
| 522 |
return store; |
| 523 |
} |
| 524 |
|
| 525 |
/** |
| 526 |
* Check if the file password hash is correct. |
| 527 |
* |
| 528 |
* @param testCipher the cipher algorithm |
| 529 |
* @param testHash the hash code |
| 530 |
* @return true if the cipher algorithm and the password match |
| 531 |
*/ |
| 532 |
boolean validateFilePasswordHash(String testCipher, byte[] testHash) { |
| 533 |
if (!Objects.equals(testCipher, this.cipher)) { |
| 534 |
return false; |
| 535 |
} |
| 536 |
return Utils.compareSecure(testHash, filePasswordHash); |
| 537 |
} |
| 538 |
|
| 539 |
private String parseDatabaseShortName() { |
| 540 |
String n = databaseName; |
| 541 |
int l = n.length(), i = l; |
| 542 |
loop: while (--i >= 0) { |
| 543 |
char ch = n.charAt(i); |
| 544 |
switch (ch) { |
| 545 |
case '/': |
| 546 |
case ':': |
| 547 |
case '\\': |
| 548 |
break loop; |
| 549 |
} |
| 550 |
} |
| 551 |
n = ++i == l ? "UNNAMED" : n.substring(i); |
| 552 |
return StringUtils.truncateString( |
| 553 |
dbSettings.databaseToUpper ? StringUtils.toUpperEnglish(n) |
| 554 |
: dbSettings.databaseToLower ? StringUtils.toLowerEnglish(n) : n, |
| 555 |
Constants.MAX_IDENTIFIER_LENGTH); |
| 556 |
} |
| 557 |
|
| 558 |
private CreateTableData createSysTableData() { |
| 559 |
CreateTableData data = new CreateTableData(); |
| 560 |
ArrayList<Column> cols = data.columns; |
| 561 |
Column columnId = new Column("ID", TypeInfo.TYPE_INTEGER); |
| 562 |
columnId.setNullable(false); |
| 563 |
cols.add(columnId); |
| 564 |
cols.add(new Column("HEAD", TypeInfo.TYPE_INTEGER)); |
| 565 |
cols.add(new Column("TYPE", TypeInfo.TYPE_INTEGER)); |
| 566 |
cols.add(new Column("SQL", TypeInfo.TYPE_VARCHAR)); |
| 567 |
data.tableName = "SYS"; |
| 568 |
data.id = 0; |
| 569 |
data.temporary = false; |
| 570 |
data.persistData = persistent; |
| 571 |
data.persistIndexes = persistent; |
| 572 |
data.isHidden = true; |
| 573 |
data.session = systemSession; |
| 574 |
return data; |
| 575 |
} |
| 576 |
|
| 577 |
private void executeMeta() { |
| 578 |
Cursor cursor = metaIdIndex.find(systemSession, null, null); |
| 579 |
ArrayList<MetaRecord> firstRecords = new ArrayList<>(), domainRecords = new ArrayList<>(), |
| 580 |
middleRecords = new ArrayList<>(), constraintRecords = new ArrayList<>(), |
| 581 |
lastRecords = new ArrayList<>(); |
| 582 |
while (cursor.next()) { |
| 583 |
MetaRecord rec = new MetaRecord(cursor.get()); |
| 584 |
objectIds.set(rec.getId()); |
| 585 |
switch (rec.getObjectType()) { |
| 586 |
case DbObject.SETTING: |
| 587 |
case DbObject.USER: |
| 588 |
case DbObject.SCHEMA: |
| 589 |
case DbObject.FUNCTION_ALIAS: |
| 590 |
firstRecords.add(rec); |
| 591 |
break; |
| 592 |
case DbObject.DOMAIN: |
| 593 |
domainRecords.add(rec); |
| 594 |
break; |
| 595 |
case DbObject.SEQUENCE: |
| 596 |
case DbObject.CONSTANT: |
| 597 |
case DbObject.TABLE_OR_VIEW: |
| 598 |
case DbObject.INDEX: |
| 599 |
middleRecords.add(rec); |
| 600 |
break; |
| 601 |
case DbObject.CONSTRAINT: |
| 602 |
constraintRecords.add(rec); |
| 603 |
break; |
| 604 |
default: |
| 605 |
lastRecords.add(rec); |
| 606 |
} |
| 607 |
} |
| 608 |
synchronized (systemSession) { |
| 609 |
executeMeta(firstRecords); |
| 610 |
// Domains may depend on other domains |
| 611 |
int count = domainRecords.size(); |
| 612 |
if (count > 0) { |
| 613 |
for (int j = 0;; count = j) { |
| 614 |
DbException exception = null; |
| 615 |
for (int i = 0; i < count; i++) { |
| 616 |
MetaRecord rec = domainRecords.get(i); |
| 617 |
try { |
| 618 |
rec.prepareAndExecute(this, systemSession, eventListener); |
| 619 |
} catch (DbException ex) { |
| 620 |
if (exception == null) { |
| 621 |
exception = ex; |
| 622 |
} |
| 623 |
domainRecords.set(j++, rec); |
| 624 |
} |
| 625 |
} |
| 626 |
if (exception == null) { |
| 627 |
break; |
| 628 |
} |
| 629 |
if (count == j) { |
| 630 |
throw exception; |
| 631 |
} |
| 632 |
} |
| 633 |
} |
| 634 |
executeMeta(middleRecords); |
| 635 |
// Prepare, but don't create all constraints and sort them |
| 636 |
count = constraintRecords.size(); |
| 637 |
if (count > 0) { |
| 638 |
ArrayList<Prepared> constraints = new ArrayList<>(count); |
| 639 |
for (int i = 0; i < count; i++) { |
| 640 |
Prepared prepared = constraintRecords.get(i).prepare(this, systemSession, eventListener); |
| 641 |
if (prepared != null) { |
| 642 |
constraints.add(prepared); |
| 643 |
} |
| 644 |
} |
| 645 |
constraints.sort(MetaRecord.CONSTRAINTS_COMPARATOR); |
| 646 |
// Create constraints in order (unique and primary key before |
| 647 |
// all others) |
| 648 |
for (Prepared constraint : constraints) { |
| 649 |
MetaRecord.execute(this, constraint, eventListener, constraint.getSQL()); |
| 650 |
} |
| 651 |
} |
| 652 |
executeMeta(lastRecords); |
| 653 |
} |
| 654 |
} |
| 655 |
|
| 656 |
private void executeMeta(ArrayList<MetaRecord> records) { |
| 657 |
if (!records.isEmpty()) { |
| 658 |
records.sort(null); |
| 659 |
for (MetaRecord rec : records) { |
| 660 |
rec.prepareAndExecute(this, systemSession, eventListener); |
| 661 |
} |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
private void startServer(String key) { |
| 666 |
try { |
| 667 |
server = Server.createTcpServer( |
| 668 |
"-tcpPort", Integer.toString(autoServerPort), |
| 669 |
"-tcpAllowOthers", |
| 670 |
"-tcpDaemon", |
| 671 |
"-key", key, databaseName); |
| 672 |
server.start(); |
| 673 |
} catch (SQLException e) { |
| 674 |
throw DbException.convert(e); |
| 675 |
} |
| 676 |
String localAddress = NetUtils.getLocalAddress(); |
| 677 |
String address = localAddress + ":" + server.getPort(); |
| 678 |
lock.setProperty("server", address); |
| 679 |
String hostName = NetUtils.getHostName(localAddress); |
| 680 |
lock.setProperty("hostName", hostName); |
| 681 |
lock.save(); |
| 682 |
} |
| 683 |
|
| 684 |
private void stopServer() { |
| 685 |
if (server != null) { |
| 686 |
Server s = server; |
| 687 |
// avoid calling stop recursively |
| 688 |
// because stopping the server will |
| 689 |
// try to close the database as well |
| 690 |
server = null; |
| 691 |
s.stop(); |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
private void recompileInvalidViews() { |
| 696 |
boolean atLeastOneRecompiledSuccessfully; |
| 697 |
do { |
| 698 |
atLeastOneRecompiledSuccessfully = false; |
| 699 |
for (Schema schema : schemas.values()) { |
| 700 |
for (Table obj : schema.getAllTablesAndViews(null)) { |
| 701 |
if (obj instanceof TableView) { |
| 702 |
TableView view = (TableView) obj; |
| 703 |
if (view.isInvalid()) { |
| 704 |
view.recompile(systemSession, true, false); |
| 705 |
if (!view.isInvalid()) { |
| 706 |
atLeastOneRecompiledSuccessfully = true; |
| 707 |
} |
| 708 |
} |
| 709 |
} |
| 710 |
} |
| 711 |
} |
| 712 |
} while (atLeastOneRecompiledSuccessfully); |
| 713 |
TableView.clearIndexCaches(this); |
| 714 |
} |
| 715 |
|
| 716 |
private void addMeta(SessionLocal session, DbObject obj) { |
| 717 |
assert Thread.holdsLock(this); |
| 718 |
int id = obj.getId(); |
| 719 |
if (id > 0 && !obj.isTemporary()) { |
| 720 |
if (!isReadOnly()) { |
| 721 |
Row r = meta.getTemplateRow(); |
| 722 |
MetaRecord.populateRowFromDBObject(obj, r); |
| 723 |
assert objectIds.get(id); |
| 724 |
if (SysProperties.CHECK) { |
| 725 |
verifyMetaLocked(session); |
| 726 |
} |
| 727 |
Cursor cursor = metaIdIndex.find(session, r, r); |
| 728 |
if (!cursor.next()) { |
| 729 |
meta.addRow(session, r); |
| 730 |
} else { |
| 731 |
assert starting; |
| 732 |
Row oldRow = cursor.get(); |
| 733 |
MetaRecord rec = new MetaRecord(oldRow); |
| 734 |
assert rec.getId() == obj.getId(); |
| 735 |
assert rec.getObjectType() == obj.getType(); |
| 736 |
if (!rec.getSQL().equals(obj.getCreateSQLForMeta())) { |
| 737 |
meta.updateRow(session, oldRow, r); |
| 738 |
} |
| 739 |
} |
| 740 |
} |
| 741 |
} |
| 742 |
} |
| 743 |
|
| 744 |
/** |
| 745 |
* Verify the meta table is locked. |
| 746 |
* |
| 747 |
* @param session the session |
| 748 |
*/ |
| 749 |
public void verifyMetaLocked(SessionLocal session) { |
| 750 |
if (lockMode != Constants.LOCK_MODE_OFF && meta != null && !meta.isLockedExclusivelyBy(session)) { |
| 751 |
throw DbException.getInternalError(); |
| 752 |
} |
| 753 |
} |
| 754 |
|
| 755 |
/** |
| 756 |
* Lock the metadata table for updates. |
| 757 |
* |
| 758 |
* @param session the session |
| 759 |
* @return whether it was already locked before by this session |
| 760 |
*/ |
| 761 |
public boolean lockMeta(SessionLocal session) { |
| 762 |
// this method can not be synchronized on the database object, |
| 763 |
// as unlocking is also synchronized on the database object - |
| 764 |
// so if locking starts just before unlocking, locking could |
| 765 |
// never be successful |
| 766 |
if (meta == null) { |
| 767 |
return true; |
| 768 |
} |
| 769 |
if (ASSERT) { |
| 770 |
lockMetaAssertion(session); |
| 771 |
} |
| 772 |
return meta.lock(session, Table.EXCLUSIVE_LOCK); |
| 773 |
} |
| 774 |
|
| 775 |
private void lockMetaAssertion(SessionLocal session) { |
| 776 |
// If we are locking two different databases in the same stack, just ignore it. |
| 777 |
// This only happens in TestLinkedTable where we connect to another h2 DB in the |
| 778 |
// same process. |
| 779 |
if (META_LOCK_DEBUGGING_DB.get() != null && META_LOCK_DEBUGGING_DB.get() != this) { |
| 780 |
final SessionLocal prev = META_LOCK_DEBUGGING.get(); |
| 781 |
if (prev == null) { |
| 782 |
META_LOCK_DEBUGGING.set(session); |
| 783 |
META_LOCK_DEBUGGING_DB.set(this); |
| 784 |
META_LOCK_DEBUGGING_STACK.set(new Throwable("Last meta lock granted in this stack trace, " |
| 785 |
+ "this is debug information for following IllegalStateException")); |
| 786 |
} else if (prev != session) { |
| 787 |
META_LOCK_DEBUGGING_STACK.get().printStackTrace(); |
| 788 |
throw new IllegalStateException("meta currently locked by " + prev + ", sessionid=" + prev.getId() |
| 789 |
+ " and trying to be locked by different session, " + session + ", sessionid=" // |
| 790 |
+ session.getId() + " on same thread"); |
| 791 |
} |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
/** |
| 796 |
* Unlock the metadata table. |
| 797 |
* |
| 798 |
* @param session the session |
| 799 |
*/ |
| 800 |
public void unlockMeta(SessionLocal session) { |
| 801 |
if (meta != null) { |
| 802 |
unlockMetaDebug(session); |
| 803 |
meta.unlock(session); |
| 804 |
session.unlock(meta); |
| 805 |
} |
| 806 |
} |
| 807 |
|
| 808 |
/** |
| 809 |
* This method doesn't actually unlock the metadata table, all it does it |
| 810 |
* reset the debugging flags. |
| 811 |
* |
| 812 |
* @param session the session |
| 813 |
*/ |
| 814 |
static void unlockMetaDebug(SessionLocal session) { |
| 815 |
if (ASSERT) { |
| 816 |
if (META_LOCK_DEBUGGING.get() == session) { |
| 817 |
META_LOCK_DEBUGGING.set(null); |
| 818 |
META_LOCK_DEBUGGING_DB.set(null); |
| 819 |
META_LOCK_DEBUGGING_STACK.set(null); |
| 820 |
} |
| 821 |
} |
| 822 |
} |
| 823 |
|
| 824 |
/** |
| 825 |
* Remove the given object from the meta data. |
| 826 |
* |
| 827 |
* @param session the session |
| 828 |
* @param id the id of the object to remove |
| 829 |
*/ |
| 830 |
public void removeMeta(SessionLocal session, int id) { |
| 831 |
if (id > 0 && !starting) { |
| 832 |
SearchRow r = meta.getRowFactory().createRow(); |
| 833 |
r.setValue(0, ValueInteger.get(id)); |
| 834 |
boolean wasLocked = lockMeta(session); |
| 835 |
try { |
| 836 |
Cursor cursor = metaIdIndex.find(session, r, r); |
| 837 |
if (cursor.next()) { |
| 838 |
Row found = cursor.get(); |
| 839 |
meta.removeRow(session, found); |
| 840 |
if (SysProperties.CHECK) { |
| 841 |
checkMetaFree(session, id); |
| 842 |
} |
| 843 |
} |
| 844 |
} finally { |
| 845 |
if (!wasLocked) { |
| 846 |
// must not keep the lock if it was not locked |
| 847 |
// otherwise updating sequences may cause a deadlock |
| 848 |
unlockMeta(session); |
| 849 |
} |
| 850 |
} |
| 851 |
// release of the object id has to be postponed until the end of the transaction, |
| 852 |
// otherwise it might be re-used prematurely, and it would make |
| 853 |
// rollback impossible or lead to MVMaps name collision, |
| 854 |
// so until then ids are accumulated within session |
| 855 |
session.scheduleDatabaseObjectIdForRelease(id); |
| 856 |
} |
| 857 |
} |
| 858 |
|
| 859 |
/** |
| 860 |
* Mark some database ids as unused. |
| 861 |
* @param idsToRelease the ids to release |
| 862 |
*/ |
| 863 |
public void releaseDatabaseObjectIds(BitSet idsToRelease) { |
| 864 |
synchronized (objectIds) { |
| 865 |
objectIds.andNot(idsToRelease); |
| 866 |
} |
| 867 |
} |
| 868 |
|
| 869 |
@SuppressWarnings("unchecked") |
| 870 |
private Map<String, DbObject> getMap(int type) { |
| 871 |
Map<String, ? extends DbObject> result; |
| 872 |
switch (type) { |
| 873 |
case DbObject.USER: |
| 874 |
case DbObject.ROLE: |
| 875 |
result = usersAndRoles; |
| 876 |
break; |
| 877 |
case DbObject.SETTING: |
| 878 |
result = settings; |
| 879 |
break; |
| 880 |
case DbObject.RIGHT: |
| 881 |
result = rights; |
| 882 |
break; |
| 883 |
case DbObject.SCHEMA: |
| 884 |
result = schemas; |
| 885 |
break; |
| 886 |
case DbObject.COMMENT: |
| 887 |
result = comments; |
| 888 |
break; |
| 889 |
default: |
| 890 |
throw DbException.getInternalError("type=" + type); |
| 891 |
} |
| 892 |
return (Map<String, DbObject>) result; |
| 893 |
} |
| 894 |
|
| 895 |
/** |
| 896 |
* Add a schema object to the database. |
| 897 |
* |
| 898 |
* @param session the session |
| 899 |
* @param obj the object to add |
| 900 |
*/ |
| 901 |
public void addSchemaObject(SessionLocal session, SchemaObject obj) { |
| 902 |
int id = obj.getId(); |
| 903 |
if (id > 0 && !starting) { |
| 904 |
checkWritingAllowed(); |
| 905 |
} |
| 906 |
lockMeta(session); |
| 907 |
synchronized (this) { |
| 908 |
obj.getSchema().add(obj); |
| 909 |
addMeta(session, obj); |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
/** |
| 914 |
* Add an object to the database. |
| 915 |
* |
| 916 |
* @param session the session |
| 917 |
* @param obj the object to add |
| 918 |
*/ |
| 919 |
public synchronized void addDatabaseObject(SessionLocal session, DbObject obj) { |
| 920 |
int id = obj.getId(); |
| 921 |
if (id > 0 && !starting) { |
| 922 |
checkWritingAllowed(); |
| 923 |
} |
| 924 |
Map<String, DbObject> map = getMap(obj.getType()); |
| 925 |
if (obj.getType() == DbObject.USER) { |
| 926 |
User user = (User) obj; |
| 927 |
if (user.isAdmin() && systemUser.getName().equals(SYSTEM_USER_NAME)) { |
| 928 |
systemUser.rename(user.getName()); |
| 929 |
} |
| 930 |
} |
| 931 |
String name = obj.getName(); |
| 932 |
if (SysProperties.CHECK && map.get(name) != null) { |
| 933 |
throw DbException.getInternalError("object already exists"); |
| 934 |
} |
| 935 |
lockMeta(session); |
| 936 |
addMeta(session, obj); |
| 937 |
map.put(name, obj); |
| 938 |
} |
| 939 |
|
| 940 |
/** |
| 941 |
* Get the comment for the given database object if one exists, or null if |
| 942 |
* not. |
| 943 |
* |
| 944 |
* @param object the database object |
| 945 |
* @return the comment or null |
| 946 |
*/ |
| 947 |
public Comment findComment(DbObject object) { |
| 948 |
if (object.getType() == DbObject.COMMENT) { |
| 949 |
return null; |
| 950 |
} |
| 951 |
String key = Comment.getKey(object); |
| 952 |
return comments.get(key); |
| 953 |
} |
| 954 |
|
| 955 |
/** |
| 956 |
* Get the role if it exists, or null if not. |
| 957 |
* |
| 958 |
* @param roleName the name of the role |
| 959 |
* @return the role or null |
| 960 |
*/ |
| 961 |
public Role findRole(String roleName) { |
| 962 |
RightOwner rightOwner = findUserOrRole(roleName); |
| 963 |
return rightOwner instanceof Role ? (Role) rightOwner : null; |
| 964 |
} |
| 965 |
|
| 966 |
/** |
| 967 |
* Get the schema if it exists, or null if not. |
| 968 |
* |
| 969 |
* @param schemaName the name of the schema |
| 970 |
* @return the schema or null |
| 971 |
*/ |
| 972 |
public Schema findSchema(String schemaName) { |
| 973 |
if (schemaName == null) { |
| 974 |
return null; |
| 975 |
} |
| 976 |
return schemas.get(schemaName); |
| 977 |
} |
| 978 |
|
| 979 |
/** |
| 980 |
* Get the setting if it exists, or null if not. |
| 981 |
* |
| 982 |
* @param name the name of the setting |
| 983 |
* @return the setting or null |
| 984 |
*/ |
| 985 |
public Setting findSetting(String name) { |
| 986 |
return settings.get(name); |
| 987 |
} |
| 988 |
|
| 989 |
/** |
| 990 |
* Get the user if it exists, or null if not. |
| 991 |
* |
| 992 |
* @param name the name of the user |
| 993 |
* @return the user or null |
| 994 |
*/ |
| 995 |
public User findUser(String name) { |
| 996 |
RightOwner rightOwner = findUserOrRole(name); |
| 997 |
return rightOwner instanceof User ? (User) rightOwner : null; |
| 998 |
} |
| 999 |
|
| 1000 |
/** |
| 1001 |
* Get user with the given name. This method throws an exception if the user |
| 1002 |
* does not exist. |
| 1003 |
* |
| 1004 |
* @param name the user name |
| 1005 |
* @return the user |
| 1006 |
* @throws DbException if the user does not exist |
| 1007 |
*/ |
| 1008 |
public User getUser(String name) { |
| 1009 |
User user = findUser(name); |
| 1010 |
if (user == null) { |
| 1011 |
throw DbException.get(ErrorCode.USER_NOT_FOUND_1, name); |
| 1012 |
} |
| 1013 |
return user; |
| 1014 |
} |
| 1015 |
|
| 1016 |
/** |
| 1017 |
* Get the user or role if it exists, or {@code null} if not. |
| 1018 |
* |
| 1019 |
* @param name the name of the user or role |
| 1020 |
* @return the user, the role, or {@code null} |
| 1021 |
*/ |
| 1022 |
public RightOwner findUserOrRole(String name) { |
| 1023 |
return usersAndRoles.get(StringUtils.toUpperEnglish(name)); |
| 1024 |
} |
| 1025 |
|
| 1026 |
/** |
| 1027 |
* Create a session for the given user. |
| 1028 |
* |
| 1029 |
* @param user the user |
| 1030 |
* @param networkConnectionInfo the network connection information, or {@code null} |
| 1031 |
* @return the session, or null if the database is currently closing |
| 1032 |
* @throws DbException if the database is in exclusive mode |
| 1033 |
*/ |
| 1034 |
synchronized SessionLocal createSession(User user, NetworkConnectionInfo networkConnectionInfo) { |
| 1035 |
if (closing) { |
| 1036 |
return null; |
| 1037 |
} |
| 1038 |
if (exclusiveSession.get() != null) { |
| 1039 |
throw DbException.get(ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE); |
| 1040 |
} |
| 1041 |
SessionLocal session = createSession(user); |
| 1042 |
session.setNetworkConnectionInfo(networkConnectionInfo); |
| 1043 |
userSessions.add(session); |
| 1044 |
trace.info("connecting session #{0} to {1}", session.getId(), databaseName); |
| 1045 |
if (delayedCloser != null) { |
| 1046 |
delayedCloser.reset(); |
| 1047 |
delayedCloser = null; |
| 1048 |
} |
| 1049 |
return session; |
| 1050 |
} |
| 1051 |
|
| 1052 |
private SessionLocal createSession(User user) { |
| 1053 |
int id = ++nextSessionId; |
| 1054 |
return new SessionLocal(this, user, id); |
| 1055 |
} |
| 1056 |
|
| 1057 |
/** |
| 1058 |
* Remove a session. This method is called after the user has disconnected. |
| 1059 |
* |
| 1060 |
* @param session the session |
| 1061 |
*/ |
| 1062 |
public synchronized void removeSession(SessionLocal session) { |
| 1063 |
if (session != null) { |
| 1064 |
exclusiveSession.compareAndSet(session, null); |
| 1065 |
if (userSessions.remove(session)) { |
| 1066 |
trace.info("disconnecting session #{0}", session.getId()); |
| 1067 |
} |
| 1068 |
} |
| 1069 |
if (isUserSession(session)) { |
| 1070 |
if (userSessions.isEmpty()) { |
| 1071 |
if (closeDelay == 0) { |
| 1072 |
close(false); |
| 1073 |
} else if (closeDelay < 0) { |
| 1074 |
return; |
| 1075 |
} else { |
| 1076 |
delayedCloser = new DelayedDatabaseCloser(this, closeDelay * 1000); |
| 1077 |
} |
| 1078 |
} |
| 1079 |
if (session != null) { |
| 1080 |
trace.info("disconnected session #{0}", session.getId()); |
| 1081 |
} |
| 1082 |
} |
| 1083 |
} |
| 1084 |
|
| 1085 |
boolean isUserSession(SessionLocal session) { |
| 1086 |
return session != systemSession && session != lobSession; |
| 1087 |
} |
| 1088 |
|
| 1089 |
private synchronized void closeAllSessionsExcept(SessionLocal except) { |
| 1090 |
SessionLocal[] all = userSessions.toArray(EMPTY_SESSION_ARRAY); |
| 1091 |
for (SessionLocal s : all) { |
| 1092 |
if (s != except) { |
| 1093 |
// indicate that session need to be closed ASAP |
| 1094 |
s.suspend(); |
| 1095 |
} |
| 1096 |
} |
| 1097 |
|
| 1098 |
int timeout = 2 * getLockTimeout(); |
| 1099 |
long start = System.currentTimeMillis(); |
| 1100 |
// 'sleep' should be strictly greater than zero, otherwise real time is not taken into consideration |
| 1101 |
// and the thread simply waits until notified |
| 1102 |
long sleep = Math.max(timeout / 20, 1); |
| 1103 |
boolean done = false; |
| 1104 |
while (!done) { |
| 1105 |
try { |
| 1106 |
// although nobody going to notify us |
| 1107 |
// it is vital to give up lock on a database |
| 1108 |
wait(sleep); |
| 1109 |
} catch (InterruptedException e1) { |
| 1110 |
// ignore |
| 1111 |
} |
| 1112 |
if (System.currentTimeMillis() - start > timeout) { |
| 1113 |
for (SessionLocal s : all) { |
| 1114 |
if (s != except && !s.isClosed()) { |
| 1115 |
try { |
| 1116 |
// this will rollback outstanding transaction |
| 1117 |
s.close(); |
| 1118 |
} catch (Throwable e) { |
| 1119 |
trace.error(e, "disconnecting session #{0}", s.getId()); |
| 1120 |
} |
| 1121 |
} |
| 1122 |
} |
| 1123 |
break; |
| 1124 |
} |
| 1125 |
done = true; |
| 1126 |
for (SessionLocal s : all) { |
| 1127 |
if (s != except && !s.isClosed()) { |
| 1128 |
done = false; |
| 1129 |
break; |
| 1130 |
} |
| 1131 |
} |
| 1132 |
} |
| 1133 |
} |
| 1134 |
|
| 1135 |
/** |
| 1136 |
* Close the database. |
| 1137 |
* |
| 1138 |
* @param fromShutdownHook true if this method is called from the shutdown |
| 1139 |
* hook |
| 1140 |
*/ |
| 1141 |
void close(boolean fromShutdownHook) { |
| 1142 |
DbException b = backgroundException.getAndSet(null); |
| 1143 |
try { |
| 1144 |
closeImpl(fromShutdownHook); |
| 1145 |
} catch (Throwable t) { |
| 1146 |
if (b != null) { |
| 1147 |
t.addSuppressed(b); |
| 1148 |
} |
| 1149 |
throw t; |
| 1150 |
} |
| 1151 |
if (b != null) { |
| 1152 |
// wrap the exception, so we see it was thrown here |
| 1153 |
throw DbException.get(b.getErrorCode(), b, b.getMessage()); |
| 1154 |
} |
| 1155 |
} |
| 1156 |
|
| 1157 |
private void closeImpl(boolean fromShutdownHook) { |
| 1158 |
synchronized (this) { |
| 1159 |
if (closing || !fromShutdownHook && !userSessions.isEmpty()) { |
| 1160 |
return; |
| 1161 |
} |
| 1162 |
closing = true; |
| 1163 |
stopServer(); |
| 1164 |
if (!userSessions.isEmpty()) { |
| 1165 |
assert fromShutdownHook; |
| 1166 |
trace.info("closing {0} from shutdown hook", databaseName); |
| 1167 |
closeAllSessionsExcept(null); |
| 1168 |
} |
| 1169 |
trace.info("closing {0}", databaseName); |
| 1170 |
if (eventListener != null) { |
| 1171 |
// allow the event listener to connect to the database |
| 1172 |
closing = false; |
| 1173 |
DatabaseEventListener e = eventListener; |
| 1174 |
// set it to null, to make sure it's called only once |
| 1175 |
eventListener = null; |
| 1176 |
e.closingDatabase(); |
| 1177 |
closing = true; |
| 1178 |
if (!userSessions.isEmpty()) { |
| 1179 |
trace.info("event listener {0} left connection open", e.getClass().getName()); |
| 1180 |
// if listener left an open connection |
| 1181 |
closeAllSessionsExcept(null); |
| 1182 |
} |
| 1183 |
} |
| 1184 |
} |
| 1185 |
try { |
| 1186 |
try { |
| 1187 |
if (systemSession != null) { |
| 1188 |
if (powerOffCount != -1) { |
| 1189 |
for (Schema schema : schemas.values()) { |
| 1190 |
for (Table table : schema.getAllTablesAndViews(null)) { |
| 1191 |
if (table.isGlobalTemporary()) { |
| 1192 |
removeSchemaObject(systemSession, table); |
| 1193 |
} else { |
| 1194 |
table.close(systemSession); |
| 1195 |
} |
| 1196 |
} |
| 1197 |
} |
| 1198 |
for (Schema schema : schemas.values()) { |
| 1199 |
for (Sequence sequence : schema.getAllSequences()) { |
| 1200 |
sequence.close(); |
| 1201 |
} |
| 1202 |
} |
| 1203 |
} |
| 1204 |
for (Schema schema : schemas.values()) { |
| 1205 |
for (TriggerObject trigger : schema.getAllTriggers()) { |
| 1206 |
try { |
| 1207 |
trigger.close(); |
| 1208 |
} catch (SQLException e) { |
| 1209 |
trace.error(e, "close"); |
| 1210 |
} |
| 1211 |
} |
| 1212 |
} |
| 1213 |
if (powerOffCount != -1) { |
| 1214 |
meta.close(systemSession); |
| 1215 |
systemSession.commit(true); |
| 1216 |
} |
| 1217 |
if (lobSession != null) { |
| 1218 |
lobSession.close(); |
| 1219 |
lobSession = null; |
| 1220 |
} |
| 1221 |
systemSession.close(); |
| 1222 |
systemSession = null; |
| 1223 |
} |
| 1224 |
tempFileDeleter.deleteAll(); |
| 1225 |
closeOpenFilesAndUnlock(); |
| 1226 |
} catch (DbException | MVStoreException e) { |
| 1227 |
trace.error(e, "close"); |
| 1228 |
} |
| 1229 |
trace.info("closed"); |
| 1230 |
traceSystem.close(); |
| 1231 |
OnExitDatabaseCloser.unregister(this); |
| 1232 |
if (deleteFilesOnDisconnect && persistent) { |
| 1233 |
deleteFilesOnDisconnect = false; |
| 1234 |
try { |
| 1235 |
String directory = FileUtils.getParent(databaseName); |
| 1236 |
String name = FileUtils.getName(databaseName); |
| 1237 |
DeleteDbFiles.execute(directory, name, true); |
| 1238 |
} catch (Exception e) { |
| 1239 |
// ignore (the trace is closed already) |
| 1240 |
} |
| 1241 |
} |
| 1242 |
} finally { |
| 1243 |
Engine.close(databaseName); |
| 1244 |
} |
| 1245 |
} |
| 1246 |
|
| 1247 |
/** |
| 1248 |
* Close all open files and unlock the database. |
| 1249 |
*/ |
| 1250 |
private synchronized void closeOpenFilesAndUnlock() { |
| 1251 |
try { |
| 1252 |
if (lobStorage != null) { |
| 1253 |
lobStorage.close(); |
| 1254 |
} |
| 1255 |
if (store != null && !store.getMvStore().isClosed()) { |
| 1256 |
if (compactMode == CommandInterface.SHUTDOWN_IMMEDIATELY) { |
| 1257 |
store.closeImmediately(); |
| 1258 |
} else { |
| 1259 |
int allowedCompactionTime = |
| 1260 |
compactMode == CommandInterface.SHUTDOWN_COMPACT || |
| 1261 |
compactMode == CommandInterface.SHUTDOWN_DEFRAG || |
| 1262 |
dbSettings.defragAlways ? -1 : dbSettings.maxCompactTime; |
| 1263 |
store.close(allowedCompactionTime); |
| 1264 |
} |
| 1265 |
if (persistent) { |
| 1266 |
// Don't delete temp files if everything is already closed |
| 1267 |
// (maybe in checkPowerOff), the database could be open now |
| 1268 |
// (even from within another process). |
| 1269 |
if (lock != null || fileLockMethod == FileLockMethod.NO || fileLockMethod == FileLockMethod.FS) { |
| 1270 |
deleteOldTempFiles(); |
| 1271 |
} |
| 1272 |
} |
| 1273 |
} |
| 1274 |
} finally { |
| 1275 |
if (lock != null) { |
| 1276 |
lock.unlock(); |
| 1277 |
lock = null; |
| 1278 |
} |
| 1279 |
} |
| 1280 |
} |
| 1281 |
|
| 1282 |
private synchronized void closeFiles() { |
| 1283 |
try { |
| 1284 |
store.closeImmediately(); |
| 1285 |
} catch (DbException e) { |
| 1286 |
trace.error(e, "close"); |
| 1287 |
} |
| 1288 |
} |
| 1289 |
|
| 1290 |
private void checkMetaFree(SessionLocal session, int id) { |
| 1291 |
SearchRow r = meta.getRowFactory().createRow(); |
| 1292 |
r.setValue(0, ValueInteger.get(id)); |
| 1293 |
Cursor cursor = metaIdIndex.find(session, r, r); |
| 1294 |
if (cursor.next()) { |
| 1295 |
throw DbException.getInternalError(); |
| 1296 |
} |
| 1297 |
} |
| 1298 |
|
| 1299 |
/** |
| 1300 |
* Allocate a new object id. |
| 1301 |
* |
| 1302 |
* @return the id |
| 1303 |
*/ |
| 1304 |
public int allocateObjectId() { |
| 1305 |
int i; |
| 1306 |
synchronized (objectIds) { |
| 1307 |
i = objectIds.nextClearBit(0); |
| 1308 |
objectIds.set(i); |
| 1309 |
} |
| 1310 |
return i; |
| 1311 |
} |
| 1312 |
|
| 1313 |
/** |
| 1314 |
* Returns system user. |
| 1315 |
* |
| 1316 |
* @return system user |
| 1317 |
*/ |
| 1318 |
public User getSystemUser() { |
| 1319 |
return systemUser; |
| 1320 |
} |
| 1321 |
|
| 1322 |
/** |
| 1323 |
* Returns main schema (usually PUBLIC). |
| 1324 |
* |
| 1325 |
* @return main schema (usually PUBLIC) |
| 1326 |
*/ |
| 1327 |
public Schema getMainSchema() { |
| 1328 |
return mainSchema; |
| 1329 |
} |
| 1330 |
|
| 1331 |
public ArrayList<Comment> getAllComments() { |
| 1332 |
return new ArrayList<>(comments.values()); |
| 1333 |
} |
| 1334 |
|
| 1335 |
public int getAllowLiterals() { |
| 1336 |
if (starting) { |
| 1337 |
return Constants.ALLOW_LITERALS_ALL; |
| 1338 |
} |
| 1339 |
return allowLiterals; |
| 1340 |
} |
| 1341 |
|
| 1342 |
public ArrayList<Right> getAllRights() { |
| 1343 |
return new ArrayList<>(rights.values()); |
| 1344 |
} |
| 1345 |
|
| 1346 |
/** |
| 1347 |
* Get all tables and views. Meta data tables may be excluded. |
| 1348 |
* |
| 1349 |
* @return all objects of that type |
| 1350 |
*/ |
| 1351 |
public ArrayList<Table> getAllTablesAndViews() { |
| 1352 |
ArrayList<Table> list = new ArrayList<>(); |
| 1353 |
for (Schema schema : schemas.values()) { |
| 1354 |
list.addAll(schema.getAllTablesAndViews(null)); |
| 1355 |
} |
| 1356 |
return list; |
| 1357 |
} |
| 1358 |
|
| 1359 |
/** |
| 1360 |
* Get all synonyms. |
| 1361 |
* |
| 1362 |
* @return all objects of that type |
| 1363 |
*/ |
| 1364 |
public ArrayList<TableSynonym> getAllSynonyms() { |
| 1365 |
ArrayList<TableSynonym> list = new ArrayList<>(); |
| 1366 |
for (Schema schema : schemas.values()) { |
| 1367 |
list.addAll(schema.getAllSynonyms()); |
| 1368 |
} |
| 1369 |
return list; |
| 1370 |
} |
| 1371 |
|
| 1372 |
public Collection<Schema> getAllSchemas() { |
| 1373 |
return schemas.values(); |
| 1374 |
} |
| 1375 |
|
| 1376 |
public Collection<Schema> getAllSchemasNoMeta() { |
| 1377 |
return schemas.values(); |
| 1378 |
} |
| 1379 |
|
| 1380 |
public Collection<Setting> getAllSettings() { |
| 1381 |
return settings.values(); |
| 1382 |
} |
| 1383 |
|
| 1384 |
public Collection<RightOwner> getAllUsersAndRoles() { |
| 1385 |
return usersAndRoles.values(); |
| 1386 |
} |
| 1387 |
|
| 1388 |
public String getCacheType() { |
| 1389 |
return cacheType; |
| 1390 |
} |
| 1391 |
|
| 1392 |
public String getCluster() { |
| 1393 |
return cluster; |
| 1394 |
} |
| 1395 |
|
| 1396 |
@Override |
| 1397 |
public CompareMode getCompareMode() { |
| 1398 |
return compareMode; |
| 1399 |
} |
| 1400 |
|
| 1401 |
@Override |
| 1402 |
public String getDatabasePath() { |
| 1403 |
if (persistent) { |
| 1404 |
return FileUtils.toRealPath(databaseName); |
| 1405 |
} |
| 1406 |
return null; |
| 1407 |
} |
| 1408 |
|
| 1409 |
public String getShortName() { |
| 1410 |
return databaseShortName; |
| 1411 |
} |
| 1412 |
|
| 1413 |
public String getName() { |
| 1414 |
return databaseName; |
| 1415 |
} |
| 1416 |
|
| 1417 |
/** |
| 1418 |
* Get all sessions that are currently connected to the database. |
| 1419 |
* |
| 1420 |
* @param includingSystemSession if the system session should also be |
| 1421 |
* included |
| 1422 |
* @return the list of sessions |
| 1423 |
*/ |
| 1424 |
public SessionLocal[] getSessions(boolean includingSystemSession) { |
| 1425 |
ArrayList<SessionLocal> list; |
| 1426 |
// need to synchronized on this database, |
| 1427 |
// otherwise the list may contain null elements |
| 1428 |
synchronized (this) { |
| 1429 |
list = new ArrayList<>(userSessions); |
| 1430 |
} |
| 1431 |
if (includingSystemSession) { |
| 1432 |
// copy, to ensure the reference is stable |
| 1433 |
SessionLocal s = systemSession; |
| 1434 |
if (s != null) { |
| 1435 |
list.add(s); |
| 1436 |
} |
| 1437 |
s = lobSession; |
| 1438 |
if (s != null) { |
| 1439 |
list.add(s); |
| 1440 |
} |
| 1441 |
} |
| 1442 |
return list.toArray(new SessionLocal[0]); |
| 1443 |
} |
| 1444 |
|
| 1445 |
/** |
| 1446 |
* Update an object in the system table. |
| 1447 |
* |
| 1448 |
* @param session the session |
| 1449 |
* @param obj the database object |
| 1450 |
*/ |
| 1451 |
public void updateMeta(SessionLocal session, DbObject obj) { |
| 1452 |
int id = obj.getId(); |
| 1453 |
if (id > 0) { |
| 1454 |
if (!starting && !obj.isTemporary()) { |
| 1455 |
Row newRow = meta.getTemplateRow(); |
| 1456 |
MetaRecord.populateRowFromDBObject(obj, newRow); |
| 1457 |
Row oldRow = metaIdIndex.getRow(session, id); |
| 1458 |
if (oldRow != null) { |
| 1459 |
meta.updateRow(session, oldRow, newRow); |
| 1460 |
} |
| 1461 |
} |
| 1462 |
// for temporary objects |
| 1463 |
synchronized (objectIds) { |
| 1464 |
objectIds.set(id); |
| 1465 |
} |
| 1466 |
} |
| 1467 |
} |
| 1468 |
|
| 1469 |
/** |
| 1470 |
* Rename a schema object. |
| 1471 |
* |
| 1472 |
* @param session the session |
| 1473 |
* @param obj the object |
| 1474 |
* @param newName the new name |
| 1475 |
*/ |
| 1476 |
public synchronized void renameSchemaObject(SessionLocal session, |
| 1477 |
SchemaObject obj, String newName) { |
| 1478 |
checkWritingAllowed(); |
| 1479 |
obj.getSchema().rename(obj, newName); |
| 1480 |
updateMetaAndFirstLevelChildren(session, obj); |
| 1481 |
} |
| 1482 |
|
| 1483 |
private synchronized void updateMetaAndFirstLevelChildren(SessionLocal session, DbObject obj) { |
| 1484 |
ArrayList<DbObject> list = obj.getChildren(); |
| 1485 |
Comment comment = findComment(obj); |
| 1486 |
if (comment != null) { |
| 1487 |
throw DbException.getInternalError(comment.toString()); |
| 1488 |
} |
| 1489 |
updateMeta(session, obj); |
| 1490 |
// remember that this scans only one level deep! |
| 1491 |
if (list != null) { |
| 1492 |
for (DbObject o : list) { |
| 1493 |
if (o.getCreateSQL() != null) { |
| 1494 |
updateMeta(session, o); |
| 1495 |
} |
| 1496 |
} |
| 1497 |
} |
| 1498 |
} |
| 1499 |
|
| 1500 |
/** |
| 1501 |
* Rename a database object. |
| 1502 |
* |
| 1503 |
* @param session the session |
| 1504 |
* @param obj the object |
| 1505 |
* @param newName the new name |
| 1506 |
*/ |
| 1507 |
public synchronized void renameDatabaseObject(SessionLocal session, |
| 1508 |
DbObject obj, String newName) { |
| 1509 |
checkWritingAllowed(); |
| 1510 |
int type = obj.getType(); |
| 1511 |
Map<String, DbObject> map = getMap(type); |
| 1512 |
if (SysProperties.CHECK) { |
| 1513 |
if (!map.containsKey(obj.getName())) { |
| 1514 |
throw DbException.getInternalError("not found: " + obj.getName()); |
| 1515 |
} |
| 1516 |
if (obj.getName().equals(newName) || map.containsKey(newName)) { |
| 1517 |
throw DbException.getInternalError("object already exists: " + newName); |
| 1518 |
} |
| 1519 |
} |
| 1520 |
obj.checkRename(); |
| 1521 |
map.remove(obj.getName()); |
| 1522 |
obj.rename(newName); |
| 1523 |
map.put(newName, obj); |
| 1524 |
updateMetaAndFirstLevelChildren(session, obj); |
| 1525 |
} |
| 1526 |
|
| 1527 |
private void deleteOldTempFiles() { |
| 1528 |
String path = FileUtils.getParent(databaseName); |
| 1529 |
for (String name : FileUtils.newDirectoryStream(path)) { |
| 1530 |
if (name.endsWith(Constants.SUFFIX_TEMP_FILE) && |
| 1531 |
name.startsWith(databaseName)) { |
| 1532 |
// can't always delete the files, they may still be open |
| 1533 |
FileUtils.tryDelete(name); |
| 1534 |
} |
| 1535 |
} |
| 1536 |
} |
| 1537 |
|
| 1538 |
/** |
| 1539 |
* Get the schema. If the schema does not exist, an exception is thrown. |
| 1540 |
* |
| 1541 |
* @param schemaName the name of the schema |
| 1542 |
* @return the schema |
| 1543 |
* @throws DbException no schema with that name exists |
| 1544 |
*/ |
| 1545 |
public Schema getSchema(String schemaName) { |
| 1546 |
Schema schema = findSchema(schemaName); |
| 1547 |
if (schema == null) { |
| 1548 |
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName); |
| 1549 |
} |
| 1550 |
return schema; |
| 1551 |
} |
| 1552 |
|
| 1553 |
/** |
| 1554 |
* Remove the object from the database. |
| 1555 |
* |
| 1556 |
* @param session the session |
| 1557 |
* @param obj the object to remove |
| 1558 |
*/ |
| 1559 |
public synchronized void removeDatabaseObject(SessionLocal session, DbObject obj) { |
| 1560 |
checkWritingAllowed(); |
| 1561 |
String objName = obj.getName(); |
| 1562 |
int type = obj.getType(); |
| 1563 |
Map<String, DbObject> map = getMap(type); |
| 1564 |
if (SysProperties.CHECK && !map.containsKey(objName)) { |
| 1565 |
throw DbException.getInternalError("not found: " + objName); |
| 1566 |
} |
| 1567 |
Comment comment = findComment(obj); |
| 1568 |
lockMeta(session); |
| 1569 |
if (comment != null) { |
| 1570 |
removeDatabaseObject(session, comment); |
| 1571 |
} |
| 1572 |
int id = obj.getId(); |
| 1573 |
obj.removeChildrenAndResources(session); |
| 1574 |
map.remove(objName); |
| 1575 |
removeMeta(session, id); |
| 1576 |
} |
| 1577 |
|
| 1578 |
/** |
| 1579 |
* Get the first table that depends on this object. |
| 1580 |
* |
| 1581 |
* @param obj the object to find |
| 1582 |
* @param except the table to exclude (or null) |
| 1583 |
* @return the first dependent table, or null |
| 1584 |
*/ |
| 1585 |
public Table getDependentTable(SchemaObject obj, Table except) { |
| 1586 |
switch (obj.getType()) { |
| 1587 |
case DbObject.COMMENT: |
| 1588 |
case DbObject.CONSTRAINT: |
| 1589 |
case DbObject.INDEX: |
| 1590 |
case DbObject.RIGHT: |
| 1591 |
case DbObject.TRIGGER: |
| 1592 |
case DbObject.USER: |
| 1593 |
return null; |
| 1594 |
default: |
| 1595 |
} |
| 1596 |
HashSet<DbObject> set = new HashSet<>(); |
| 1597 |
for (Schema schema : schemas.values()) { |
| 1598 |
for (Table t : schema.getAllTablesAndViews(null)) { |
| 1599 |
if (except == t || TableType.VIEW == t.getTableType()) { |
| 1600 |
continue; |
| 1601 |
} |
| 1602 |
set.clear(); |
| 1603 |
t.addDependencies(set); |
| 1604 |
if (set.contains(obj)) { |
| 1605 |
return t; |
| 1606 |
} |
| 1607 |
} |
| 1608 |
} |
| 1609 |
return null; |
| 1610 |
} |
| 1611 |
|
| 1612 |
/** |
| 1613 |
* Remove an object from the system table. |
| 1614 |
* |
| 1615 |
* @param session the session |
| 1616 |
* @param obj the object to be removed |
| 1617 |
*/ |
| 1618 |
public void removeSchemaObject(SessionLocal session, |
| 1619 |
SchemaObject obj) { |
| 1620 |
int type = obj.getType(); |
| 1621 |
if (type == DbObject.TABLE_OR_VIEW) { |
| 1622 |
Table table = (Table) obj; |
| 1623 |
if (table.isTemporary() && !table.isGlobalTemporary()) { |
| 1624 |
session.removeLocalTempTable(table); |
| 1625 |
return; |
| 1626 |
} |
| 1627 |
} else if (type == DbObject.INDEX) { |
| 1628 |
Index index = (Index) obj; |
| 1629 |
Table table = index.getTable(); |
| 1630 |
if (table.isTemporary() && !table.isGlobalTemporary()) { |
| 1631 |
session.removeLocalTempTableIndex(index); |
| 1632 |
return; |
| 1633 |
} |
| 1634 |
} else if (type == DbObject.CONSTRAINT) { |
| 1635 |
Constraint constraint = (Constraint) obj; |
| 1636 |
if (constraint.getConstraintType() != Type.DOMAIN) { |
| 1637 |
Table table = constraint.getTable(); |
| 1638 |
if (table.isTemporary() && !table.isGlobalTemporary()) { |
| 1639 |
session.removeLocalTempTableConstraint(constraint); |
| 1640 |
return; |
| 1641 |
} |
| 1642 |
} |
| 1643 |
} |
| 1644 |
checkWritingAllowed(); |
| 1645 |
lockMeta(session); |
| 1646 |
synchronized (this) { |
| 1647 |
Comment comment = findComment(obj); |
| 1648 |
if (comment != null) { |
| 1649 |
removeDatabaseObject(session, comment); |
| 1650 |
} |
| 1651 |
obj.getSchema().remove(obj); |
| 1652 |
int id = obj.getId(); |
| 1653 |
if (!starting) { |
| 1654 |
Table t = getDependentTable(obj, null); |
| 1655 |
if (t != null) { |
| 1656 |
obj.getSchema().add(obj); |
| 1657 |
throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getTraceSQL(), t.getTraceSQL()); |
| 1658 |
} |
| 1659 |
obj.removeChildrenAndResources(session); |
| 1660 |
} |
| 1661 |
removeMeta(session, id); |
| 1662 |
} |
| 1663 |
} |
| 1664 |
|
| 1665 |
/** |
| 1666 |
* Check if this database is disk-based. |
| 1667 |
* |
| 1668 |
* @return true if it is disk-based, false if it is in-memory only. |
| 1669 |
*/ |
| 1670 |
public boolean isPersistent() { |
| 1671 |
return persistent; |
| 1672 |
} |
| 1673 |
|
| 1674 |
public TraceSystem getTraceSystem() { |
| 1675 |
return traceSystem; |
| 1676 |
} |
| 1677 |
|
| 1678 |
public synchronized void setCacheSize(int kb) { |
| 1679 |
if (starting) { |
| 1680 |
int max = MathUtils.convertLongToInt(Utils.getMemoryMax()) / 2; |
| 1681 |
kb = Math.min(kb, max); |
| 1682 |
} |
| 1683 |
store.setCacheSize(Math.max(1, kb)); |
| 1684 |
} |
| 1685 |
|
| 1686 |
public synchronized void setMasterUser(User user) { |
| 1687 |
lockMeta(systemSession); |
| 1688 |
addDatabaseObject(systemSession, user); |
| 1689 |
systemSession.commit(true); |
| 1690 |
} |
| 1691 |
|
| 1692 |
public Role getPublicRole() { |
| 1693 |
return publicRole; |
| 1694 |
} |
| 1695 |
|
| 1696 |
/** |
| 1697 |
* Get a unique temporary table name. |
| 1698 |
* |
| 1699 |
* @param baseName the prefix of the returned name |
| 1700 |
* @param session the session |
| 1701 |
* @return a unique name |
| 1702 |
*/ |
| 1703 |
public synchronized String getTempTableName(String baseName, SessionLocal session) { |
| 1704 |
int maxBaseLength = Constants.MAX_IDENTIFIER_LENGTH - (7 + ValueInteger.DISPLAY_SIZE * 2); |
| 1705 |
if (baseName.length() > maxBaseLength) { |
| 1706 |
baseName = baseName.substring(0, maxBaseLength); |
| 1707 |
} |
| 1708 |
String tempName; |
| 1709 |
do { |
| 1710 |
tempName = baseName + "_COPY_" + session.getId() + '_' + nextTempTableId++; |
| 1711 |
} while (mainSchema.findTableOrView(session, tempName) != null); |
| 1712 |
return tempName; |
| 1713 |
} |
| 1714 |
|
| 1715 |
public void setCompareMode(CompareMode compareMode) { |
| 1716 |
this.compareMode = compareMode; |
| 1717 |
} |
| 1718 |
|
| 1719 |
public void setCluster(String cluster) { |
| 1720 |
this.cluster = cluster; |
| 1721 |
} |
| 1722 |
|
| 1723 |
@Override |
| 1724 |
public void checkWritingAllowed() { |
| 1725 |
if (readOnly) { |
| 1726 |
throw DbException.get(ErrorCode.DATABASE_IS_READ_ONLY); |
| 1727 |
} |
| 1728 |
} |
| 1729 |
|
| 1730 |
public boolean isReadOnly() { |
| 1731 |
return readOnly; |
| 1732 |
} |
| 1733 |
|
| 1734 |
public void setWriteDelay(int value) { |
| 1735 |
store.getMvStore().setAutoCommitDelay(value < 0 ? 0 : value); |
| 1736 |
} |
| 1737 |
|
| 1738 |
public int getRetentionTime() { |
| 1739 |
return store.getMvStore().getRetentionTime(); |
| 1740 |
} |
| 1741 |
|
| 1742 |
public void setRetentionTime(int value) { |
| 1743 |
store.getMvStore().setRetentionTime(value); |
| 1744 |
} |
| 1745 |
|
| 1746 |
public void setAllowBuiltinAliasOverride(boolean b) { |
| 1747 |
allowBuiltinAliasOverride = b; |
| 1748 |
} |
| 1749 |
|
| 1750 |
public boolean isAllowBuiltinAliasOverride() { |
| 1751 |
return allowBuiltinAliasOverride; |
| 1752 |
} |
| 1753 |
|
| 1754 |
/** |
| 1755 |
* Get the list of in-doubt transactions. |
| 1756 |
* |
| 1757 |
* @return the list |
| 1758 |
*/ |
| 1759 |
public ArrayList<InDoubtTransaction> getInDoubtTransactions() { |
| 1760 |
return store.getInDoubtTransactions(); |
| 1761 |
} |
| 1762 |
|
| 1763 |
/** |
| 1764 |
* Prepare a transaction. |
| 1765 |
* |
| 1766 |
* @param session the session |
| 1767 |
* @param transaction the name of the transaction |
| 1768 |
*/ |
| 1769 |
synchronized void prepareCommit(SessionLocal session, String transaction) { |
| 1770 |
if (!readOnly) { |
| 1771 |
store.prepareCommit(session, transaction); |
| 1772 |
} |
| 1773 |
} |
| 1774 |
|
| 1775 |
/** |
| 1776 |
* If there is a background store thread, and if there wasn an exception in |
| 1777 |
* that thread, throw it now. |
| 1778 |
*/ |
| 1779 |
void throwLastBackgroundException() { |
| 1780 |
DbException b = backgroundException.getAndSet(null); |
| 1781 |
if (b != null) { |
| 1782 |
// wrap the exception, so we see it was thrown here |
| 1783 |
throw DbException.get(b.getErrorCode(), b, b.getMessage()); |
| 1784 |
} |
| 1785 |
} |
| 1786 |
|
| 1787 |
public void setBackgroundException(DbException e) { |
| 1788 |
if (backgroundException.compareAndSet(null, e)) { |
| 1789 |
TraceSystem t = getTraceSystem(); |
| 1790 |
if (t != null) { |
| 1791 |
t.getTrace(Trace.DATABASE).error(e, "flush"); |
| 1792 |
} |
| 1793 |
} |
| 1794 |
} |
| 1795 |
|
| 1796 |
public Throwable getBackgroundException() { |
| 1797 |
MVStoreException exception = store.getMvStore().getPanicException(); |
| 1798 |
if(exception != null) { |
| 1799 |
return exception; |
| 1800 |
} |
| 1801 |
return backgroundException.getAndSet(null); |
| 1802 |
} |
| 1803 |
|
| 1804 |
|
| 1805 |
/** |
| 1806 |
* Flush all pending changes to the transaction log. |
| 1807 |
*/ |
| 1808 |
public synchronized void flush() { |
| 1809 |
if (!readOnly) { |
| 1810 |
try { |
| 1811 |
store.flush(); |
| 1812 |
} catch (RuntimeException e) { |
| 1813 |
backgroundException.compareAndSet(null, DbException.convert(e)); |
| 1814 |
throw e; |
| 1815 |
} |
| 1816 |
} |
| 1817 |
} |
| 1818 |
|
| 1819 |
public void setEventListener(DatabaseEventListener eventListener) { |
| 1820 |
this.eventListener = eventListener; |
| 1821 |
} |
| 1822 |
|
| 1823 |
public void setEventListenerClass(String className) { |
| 1824 |
if (className == null || className.isEmpty()) { |
| 1825 |
eventListener = null; |
| 1826 |
} else { |
| 1827 |
try { |
| 1828 |
eventListener = (DatabaseEventListener) |
| 1829 |
JdbcUtils.loadUserClass(className).getDeclaredConstructor().newInstance(); |
| 1830 |
String url = databaseURL; |
| 1831 |
if (cipher != null) { |
| 1832 |
url += ";CIPHER=" + cipher; |
| 1833 |
} |
| 1834 |
eventListener.init(url); |
| 1835 |
} catch (Throwable e) { |
| 1836 |
throw DbException.get( |
| 1837 |
ErrorCode.ERROR_SETTING_DATABASE_EVENT_LISTENER_2, e, |
| 1838 |
className, e.toString()); |
| 1839 |
} |
| 1840 |
} |
| 1841 |
} |
| 1842 |
|
| 1843 |
/** |
| 1844 |
* Set the progress of a long running operation. |
| 1845 |
* This method calls the {@link DatabaseEventListener} if one is registered. |
| 1846 |
* |
| 1847 |
* @param state the {@link DatabaseEventListener} state |
| 1848 |
* @param name the object name |
| 1849 |
* @param x the current position |
| 1850 |
* @param max the highest value or 0 if unknown |
| 1851 |
*/ |
| 1852 |
public void setProgress(int state, String name, long x, long max) { |
| 1853 |
if (eventListener != null) { |
| 1854 |
try { |
| 1855 |
eventListener.setProgress(state, name, x, max); |
| 1856 |
} catch (Exception e2) { |
| 1857 |
// ignore this (user made) exception |
| 1858 |
} |
| 1859 |
} |
| 1860 |
} |
| 1861 |
|
| 1862 |
/** |
| 1863 |
* This method is called after an exception occurred, to inform the database |
| 1864 |
* event listener (if one is set). |
| 1865 |
* |
| 1866 |
* @param e the exception |
| 1867 |
* @param sql the SQL statement |
| 1868 |
*/ |
| 1869 |
public void exceptionThrown(SQLException e, String sql) { |
| 1870 |
if (eventListener != null) { |
| 1871 |
try { |
| 1872 |
eventListener.exceptionThrown(e, sql); |
| 1873 |
} catch (Exception e2) { |
| 1874 |
// ignore this (user made) exception |
| 1875 |
} |
| 1876 |
} |
| 1877 |
} |
| 1878 |
|
| 1879 |
/** |
| 1880 |
* Synchronize the files with the file system. This method is called when |
| 1881 |
* executing the SQL statement CHECKPOINT SYNC. |
| 1882 |
*/ |
| 1883 |
public synchronized void sync() { |
| 1884 |
if (readOnly) { |
| 1885 |
return; |
| 1886 |
} |
| 1887 |
store.sync(); |
| 1888 |
} |
| 1889 |
|
| 1890 |
public int getMaxMemoryRows() { |
| 1891 |
return maxMemoryRows; |
| 1892 |
} |
| 1893 |
|
| 1894 |
public void setMaxMemoryRows(int value) { |
| 1895 |
this.maxMemoryRows = value; |
| 1896 |
} |
| 1897 |
|
| 1898 |
public void setLockMode(int lockMode) { |
| 1899 |
switch (lockMode) { |
| 1900 |
case Constants.LOCK_MODE_OFF: |
| 1901 |
case Constants.LOCK_MODE_READ_COMMITTED: |
| 1902 |
break; |
| 1903 |
case Constants.LOCK_MODE_TABLE: |
| 1904 |
case Constants.LOCK_MODE_TABLE_GC: |
| 1905 |
lockMode = Constants.LOCK_MODE_READ_COMMITTED; |
| 1906 |
break; |
| 1907 |
default: |
| 1908 |
throw DbException.getInvalidValueException("lock mode", lockMode); |
| 1909 |
} |
| 1910 |
this.lockMode = lockMode; |
| 1911 |
} |
| 1912 |
|
| 1913 |
public int getLockMode() { |
| 1914 |
return lockMode; |
| 1915 |
} |
| 1916 |
|
| 1917 |
public void setCloseDelay(int value) { |
| 1918 |
this.closeDelay = value; |
| 1919 |
} |
| 1920 |
|
| 1921 |
public SessionLocal getSystemSession() { |
| 1922 |
return systemSession; |
| 1923 |
} |
| 1924 |
|
| 1925 |
/** |
| 1926 |
* Check if the database is in the process of closing. |
| 1927 |
* |
| 1928 |
* @return true if the database is closing |
| 1929 |
*/ |
| 1930 |
public boolean isClosing() { |
| 1931 |
return closing; |
| 1932 |
} |
| 1933 |
|
| 1934 |
public void setMaxLengthInplaceLob(int value) { |
| 1935 |
this.maxLengthInplaceLob = value; |
| 1936 |
} |
| 1937 |
|
| 1938 |
@Override |
| 1939 |
public int getMaxLengthInplaceLob() { |
| 1940 |
return maxLengthInplaceLob; |
| 1941 |
} |
| 1942 |
|
| 1943 |
public void setIgnoreCase(boolean b) { |
| 1944 |
ignoreCase = b; |
| 1945 |
} |
| 1946 |
|
| 1947 |
public boolean getIgnoreCase() { |
| 1948 |
if (starting) { |
| 1949 |
// tables created at startup must not be converted to ignorecase |
| 1950 |
return false; |
| 1951 |
} |
| 1952 |
return ignoreCase; |
| 1953 |
} |
| 1954 |
|
| 1955 |
public void setIgnoreCatalogs(boolean b) { |
| 1956 |
ignoreCatalogs = b; |
| 1957 |
} |
| 1958 |
|
| 1959 |
public boolean getIgnoreCatalogs() { |
| 1960 |
return ignoreCatalogs; |
| 1961 |
} |
| 1962 |
|
| 1963 |
|
| 1964 |
public synchronized void setDeleteFilesOnDisconnect(boolean b) { |
| 1965 |
this.deleteFilesOnDisconnect = b; |
| 1966 |
} |
| 1967 |
|
| 1968 |
public void setAllowLiterals(int value) { |
| 1969 |
this.allowLiterals = value; |
| 1970 |
} |
| 1971 |
|
| 1972 |
public boolean getOptimizeReuseResults() { |
| 1973 |
return optimizeReuseResults; |
| 1974 |
} |
| 1975 |
|
| 1976 |
public void setOptimizeReuseResults(boolean b) { |
| 1977 |
optimizeReuseResults = b; |
| 1978 |
} |
| 1979 |
|
| 1980 |
@Override |
| 1981 |
public Object getLobSyncObject() { |
| 1982 |
return lobSyncObject; |
| 1983 |
} |
| 1984 |
|
| 1985 |
public int getSessionCount() { |
| 1986 |
return userSessions.size(); |
| 1987 |
} |
| 1988 |
|
| 1989 |
public void setReferentialIntegrity(boolean b) { |
| 1990 |
referentialIntegrity = b; |
| 1991 |
} |
| 1992 |
|
| 1993 |
public boolean getReferentialIntegrity() { |
| 1994 |
return referentialIntegrity; |
| 1995 |
} |
| 1996 |
|
| 1997 |
public void setQueryStatistics(boolean b) { |
| 1998 |
queryStatistics = b; |
| 1999 |
synchronized (this) { |
| 2000 |
if (!b) { |
| 2001 |
queryStatisticsData = null; |
| 2002 |
} |
| 2003 |
} |
| 2004 |
} |
| 2005 |
|
| 2006 |
public boolean getQueryStatistics() { |
| 2007 |
return queryStatistics; |
| 2008 |
} |
| 2009 |
|
| 2010 |
public void setQueryStatisticsMaxEntries(int n) { |
| 2011 |
queryStatisticsMaxEntries = n; |
| 2012 |
if (queryStatisticsData != null) { |
| 2013 |
synchronized (this) { |
| 2014 |
if (queryStatisticsData != null) { |
| 2015 |
queryStatisticsData.setMaxQueryEntries(queryStatisticsMaxEntries); |
| 2016 |
} |
| 2017 |
} |
| 2018 |
} |
| 2019 |
} |
| 2020 |
|
| 2021 |
public QueryStatisticsData getQueryStatisticsData() { |
| 2022 |
if (!queryStatistics) { |
| 2023 |
return null; |
| 2024 |
} |
| 2025 |
if (queryStatisticsData == null) { |
| 2026 |
synchronized (this) { |
| 2027 |
if (queryStatisticsData == null) { |
| 2028 |
queryStatisticsData = new QueryStatisticsData(queryStatisticsMaxEntries); |
| 2029 |
} |
| 2030 |
} |
| 2031 |
} |
| 2032 |
return queryStatisticsData; |
| 2033 |
} |
| 2034 |
|
| 2035 |
/** |
| 2036 |
* Check if the database is currently opening. This is true until all stored |
| 2037 |
* SQL statements have been executed. |
| 2038 |
* |
| 2039 |
* @return true if the database is still starting |
| 2040 |
*/ |
| 2041 |
public boolean isStarting() { |
| 2042 |
return starting; |
| 2043 |
} |
| 2044 |
|
| 2045 |
/** |
| 2046 |
* Called after the database has been opened and initialized. This method |
| 2047 |
* notifies the event listener if one has been set. |
| 2048 |
*/ |
| 2049 |
void opened() { |
| 2050 |
if (eventListener != null) { |
| 2051 |
eventListener.opened(); |
| 2052 |
} |
| 2053 |
} |
| 2054 |
|
| 2055 |
public void setMode(Mode mode) { |
| 2056 |
this.mode = mode; |
| 2057 |
getNextRemoteSettingsId(); |
| 2058 |
} |
| 2059 |
|
| 2060 |
@Override |
| 2061 |
public Mode getMode() { |
| 2062 |
return mode; |
| 2063 |
} |
| 2064 |
|
| 2065 |
public void setDefaultNullOrdering(DefaultNullOrdering defaultNullOrdering) { |
| 2066 |
this.defaultNullOrdering = defaultNullOrdering; |
| 2067 |
} |
| 2068 |
|
| 2069 |
public DefaultNullOrdering getDefaultNullOrdering() { |
| 2070 |
return defaultNullOrdering; |
| 2071 |
} |
| 2072 |
|
| 2073 |
public void setMaxOperationMemory(int maxOperationMemory) { |
| 2074 |
this.maxOperationMemory = maxOperationMemory; |
| 2075 |
} |
| 2076 |
|
| 2077 |
public int getMaxOperationMemory() { |
| 2078 |
return maxOperationMemory; |
| 2079 |
} |
| 2080 |
|
| 2081 |
public SessionLocal getExclusiveSession() { |
| 2082 |
return exclusiveSession.get(); |
| 2083 |
} |
| 2084 |
|
| 2085 |
/** |
| 2086 |
* Set the session that can exclusively access the database. |
| 2087 |
* |
| 2088 |
* @param session the session |
| 2089 |
* @param closeOthers whether other sessions are closed |
| 2090 |
* @return true if success or if database is in exclusive mode |
| 2091 |
* set by this session already, false otherwise |
| 2092 |
*/ |
| 2093 |
public boolean setExclusiveSession(SessionLocal session, boolean closeOthers) { |
| 2094 |
if (exclusiveSession.get() != session && |
| 2095 |
!exclusiveSession.compareAndSet(null, session)) { |
| 2096 |
return false; |
| 2097 |
} |
| 2098 |
if (closeOthers) { |
| 2099 |
closeAllSessionsExcept(session); |
| 2100 |
} |
| 2101 |
return true; |
| 2102 |
} |
| 2103 |
|
| 2104 |
/** |
| 2105 |
* Stop exclusive access the database by provided session. |
| 2106 |
* |
| 2107 |
* @param session the session |
| 2108 |
* @return true if success or if database is in non-exclusive mode already, |
| 2109 |
* false otherwise |
| 2110 |
*/ |
| 2111 |
public boolean unsetExclusiveSession(SessionLocal session) { |
| 2112 |
return exclusiveSession.get() == null |
| 2113 |
|| exclusiveSession.compareAndSet(session, null); |
| 2114 |
} |
| 2115 |
|
| 2116 |
@Override |
| 2117 |
public SmallLRUCache<String, String[]> getLobFileListCache() { |
| 2118 |
if (lobFileListCache == null) { |
| 2119 |
lobFileListCache = SmallLRUCache.newInstance(128); |
| 2120 |
} |
| 2121 |
return lobFileListCache; |
| 2122 |
} |
| 2123 |
|
| 2124 |
/** |
| 2125 |
* Checks if the system table (containing the catalog) is locked. |
| 2126 |
* |
| 2127 |
* @return true if it is currently locked |
| 2128 |
*/ |
| 2129 |
public boolean isSysTableLocked() { |
| 2130 |
return meta == null || meta.isLockedExclusively(); |
| 2131 |
} |
| 2132 |
|
| 2133 |
/** |
| 2134 |
* Checks if the system table (containing the catalog) is locked by the |
| 2135 |
* given session. |
| 2136 |
* |
| 2137 |
* @param session the session |
| 2138 |
* @return true if it is currently locked |
| 2139 |
*/ |
| 2140 |
public boolean isSysTableLockedBy(SessionLocal session) { |
| 2141 |
return meta == null || meta.isLockedExclusivelyBy(session); |
| 2142 |
} |
| 2143 |
|
| 2144 |
/** |
| 2145 |
* Open a new connection or get an existing connection to another database. |
| 2146 |
* |
| 2147 |
* @param driver the database driver or null |
| 2148 |
* @param url the database URL |
| 2149 |
* @param user the user name |
| 2150 |
* @param password the password |
| 2151 |
* @return the connection |
| 2152 |
*/ |
| 2153 |
public TableLinkConnection getLinkConnection(String driver, String url, |
| 2154 |
String user, String password) { |
| 2155 |
if (linkConnections == null) { |
| 2156 |
linkConnections = new HashMap<>(); |
| 2157 |
} |
| 2158 |
return TableLinkConnection.open(linkConnections, driver, url, user, |
| 2159 |
password, dbSettings.shareLinkedConnections); |
| 2160 |
} |
| 2161 |
|
| 2162 |
@Override |
| 2163 |
public String toString() { |
| 2164 |
return databaseShortName + ":" + super.toString(); |
| 2165 |
} |
| 2166 |
|
| 2167 |
/** |
| 2168 |
* Immediately close the database. |
| 2169 |
*/ |
| 2170 |
public void shutdownImmediately() { |
| 2171 |
closing = true; |
| 2172 |
setPowerOffCount(1); |
| 2173 |
try { |
| 2174 |
checkPowerOff(); |
| 2175 |
} catch (DbException e) { |
| 2176 |
// ignore |
| 2177 |
} |
| 2178 |
closeFiles(); |
| 2179 |
powerOffCount = 0; |
| 2180 |
} |
| 2181 |
|
| 2182 |
@Override |
| 2183 |
public TempFileDeleter getTempFileDeleter() { |
| 2184 |
return tempFileDeleter; |
| 2185 |
} |
| 2186 |
|
| 2187 |
/** |
| 2188 |
* Get the first user defined table, excluding the LOB_BLOCKS table that the |
| 2189 |
* Recover tool creates. |
| 2190 |
* |
| 2191 |
* @return the table or null if no table is defined |
| 2192 |
*/ |
| 2193 |
public Table getFirstUserTable() { |
| 2194 |
for (Schema schema : schemas.values()) { |
| 2195 |
for (Table table : schema.getAllTablesAndViews(null)) { |
| 2196 |
if (table.getCreateSQL() == null || table.isHidden()) { |
| 2197 |
continue; |
| 2198 |
} |
| 2199 |
// exclude the LOB_MAP that the Recover tool creates |
| 2200 |
if (schema.getId() == Constants.INFORMATION_SCHEMA_ID |
| 2201 |
&& table.getName().equalsIgnoreCase("LOB_BLOCKS")) { |
| 2202 |
continue; |
| 2203 |
} |
| 2204 |
return table; |
| 2205 |
} |
| 2206 |
} |
| 2207 |
return null; |
| 2208 |
} |
| 2209 |
|
| 2210 |
/** |
| 2211 |
* Flush all changes and open a new transaction log. |
| 2212 |
*/ |
| 2213 |
public void checkpoint() { |
| 2214 |
if (persistent) { |
| 2215 |
store.flush(); |
| 2216 |
} |
| 2217 |
getTempFileDeleter().deleteUnused(); |
| 2218 |
} |
| 2219 |
|
| 2220 |
/** |
| 2221 |
* Switch the database to read-only mode. |
| 2222 |
* |
| 2223 |
* @param readOnly the new value |
| 2224 |
*/ |
| 2225 |
public void setReadOnly(boolean readOnly) { |
| 2226 |
this.readOnly = readOnly; |
| 2227 |
} |
| 2228 |
|
| 2229 |
public void setCompactMode(int compactMode) { |
| 2230 |
this.compactMode = compactMode; |
| 2231 |
} |
| 2232 |
|
| 2233 |
public SourceCompiler getCompiler() { |
| 2234 |
if (compiler == null) { |
| 2235 |
compiler = new SourceCompiler(); |
| 2236 |
} |
| 2237 |
return compiler; |
| 2238 |
} |
| 2239 |
|
| 2240 |
@Override |
| 2241 |
public LobStorageInterface getLobStorage() { |
| 2242 |
return lobStorage; |
| 2243 |
} |
| 2244 |
|
| 2245 |
public SessionLocal getLobSession() { |
| 2246 |
return lobSession; |
| 2247 |
} |
| 2248 |
|
| 2249 |
public int getDefaultTableType() { |
| 2250 |
return defaultTableType; |
| 2251 |
} |
| 2252 |
|
| 2253 |
public void setDefaultTableType(int defaultTableType) { |
| 2254 |
this.defaultTableType = defaultTableType; |
| 2255 |
} |
| 2256 |
|
| 2257 |
public DbSettings getSettings() { |
| 2258 |
return dbSettings; |
| 2259 |
} |
| 2260 |
|
| 2261 |
/** |
| 2262 |
* Create a new hash map. Depending on the configuration, the key is case |
| 2263 |
* sensitive or case insensitive. |
| 2264 |
* |
| 2265 |
* @param <V> the value type |
| 2266 |
* @return the hash map |
| 2267 |
*/ |
| 2268 |
public <V> HashMap<String, V> newStringMap() { |
| 2269 |
return dbSettings.caseInsensitiveIdentifiers ? new CaseInsensitiveMap<>() : new HashMap<>(); |
| 2270 |
} |
| 2271 |
|
| 2272 |
/** |
| 2273 |
* Create a new hash map. Depending on the configuration, the key is case |
| 2274 |
* sensitive or case insensitive. |
| 2275 |
* |
| 2276 |
* @param <V> the value type |
| 2277 |
* @param initialCapacity the initial capacity |
| 2278 |
* @return the hash map |
| 2279 |
*/ |
| 2280 |
public <V> HashMap<String, V> newStringMap(int initialCapacity) { |
| 2281 |
return dbSettings.caseInsensitiveIdentifiers ? new CaseInsensitiveMap<>(initialCapacity) |
| 2282 |
: new HashMap<>(initialCapacity); |
| 2283 |
} |
| 2284 |
|
| 2285 |
/** |
| 2286 |
* Create a new hash map. Depending on the configuration, the key is case |
| 2287 |
* sensitive or case insensitive. |
| 2288 |
* |
| 2289 |
* @param <V> the value type |
| 2290 |
* @return the hash map |
| 2291 |
*/ |
| 2292 |
public <V> ConcurrentHashMap<String, V> newConcurrentStringMap() { |
| 2293 |
return dbSettings.caseInsensitiveIdentifiers ? new CaseInsensitiveConcurrentMap<>() |
| 2294 |
: new ConcurrentHashMap<>(); |
| 2295 |
} |
| 2296 |
|
| 2297 |
/** |
| 2298 |
* Compare two identifiers (table names, column names,...) and verify they |
| 2299 |
* are equal. Case sensitivity depends on the configuration. |
| 2300 |
* |
| 2301 |
* @param a the first identifier |
| 2302 |
* @param b the second identifier |
| 2303 |
* @return true if they match |
| 2304 |
*/ |
| 2305 |
public boolean equalsIdentifiers(String a, String b) { |
| 2306 |
return a.equals(b) || dbSettings.caseInsensitiveIdentifiers && a.equalsIgnoreCase(b); |
| 2307 |
} |
| 2308 |
|
| 2309 |
/** |
| 2310 |
* Returns identifier in upper or lower case depending on database settings. |
| 2311 |
* |
| 2312 |
* @param upperName |
| 2313 |
* identifier in the upper case |
| 2314 |
* @return identifier in upper or lower case |
| 2315 |
*/ |
| 2316 |
public String sysIdentifier(String upperName) { |
| 2317 |
assert isUpperSysIdentifier(upperName); |
| 2318 |
return dbSettings.databaseToLower ? StringUtils.toLowerEnglish(upperName) : upperName; |
| 2319 |
} |
| 2320 |
|
| 2321 |
private static boolean isUpperSysIdentifier(String upperName) { |
| 2322 |
int l = upperName.length(); |
| 2323 |
if (l == 0) { |
| 2324 |
return false; |
| 2325 |
} |
| 2326 |
char c = upperName.charAt(0); |
| 2327 |
if (c < 'A' || c > 'Z') { |
| 2328 |
return false; |
| 2329 |
} |
| 2330 |
l--; |
| 2331 |
for (int i = 1; i < l; i++) { |
| 2332 |
c = upperName.charAt(i); |
| 2333 |
if ((c < 'A' || c > 'Z') && c != '_') { |
| 2334 |
return false; |
| 2335 |
} |
| 2336 |
} |
| 2337 |
if (l > 0) { |
| 2338 |
c = upperName.charAt(l); |
| 2339 |
if (c < 'A' || c > 'Z') { |
| 2340 |
return false; |
| 2341 |
} |
| 2342 |
} |
| 2343 |
return true; |
| 2344 |
} |
| 2345 |
|
| 2346 |
@Override |
| 2347 |
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff, int off, int length) { |
| 2348 |
throw DbException.getInternalError(); |
| 2349 |
} |
| 2350 |
|
| 2351 |
public int getPageSize() { |
| 2352 |
return pageSize; |
| 2353 |
} |
| 2354 |
|
| 2355 |
@Override |
| 2356 |
public JavaObjectSerializer getJavaObjectSerializer() { |
| 2357 |
initJavaObjectSerializer(); |
| 2358 |
return javaObjectSerializer; |
| 2359 |
} |
| 2360 |
|
| 2361 |
private void initJavaObjectSerializer() { |
| 2362 |
if (javaObjectSerializerInitialized) { |
| 2363 |
return; |
| 2364 |
} |
| 2365 |
synchronized (this) { |
| 2366 |
if (javaObjectSerializerInitialized) { |
| 2367 |
return; |
| 2368 |
} |
| 2369 |
String serializerName = javaObjectSerializerName; |
| 2370 |
if (serializerName != null) { |
| 2371 |
serializerName = serializerName.trim(); |
| 2372 |
if (!serializerName.isEmpty() && |
| 2373 |
!serializerName.equals("null")) { |
| 2374 |
try { |
| 2375 |
javaObjectSerializer = (JavaObjectSerializer) |
| 2376 |
JdbcUtils.loadUserClass(serializerName).getDeclaredConstructor().newInstance(); |
| 2377 |
} catch (Exception e) { |
| 2378 |
throw DbException.convert(e); |
| 2379 |
} |
| 2380 |
} |
| 2381 |
} |
| 2382 |
javaObjectSerializerInitialized = true; |
| 2383 |
} |
| 2384 |
} |
| 2385 |
|
| 2386 |
public void setJavaObjectSerializerName(String serializerName) { |
| 2387 |
synchronized (this) { |
| 2388 |
javaObjectSerializerInitialized = false; |
| 2389 |
javaObjectSerializerName = serializerName; |
| 2390 |
getNextRemoteSettingsId(); |
| 2391 |
} |
| 2392 |
} |
| 2393 |
|
| 2394 |
/** |
| 2395 |
* Get the table engine class, loading it if needed. |
| 2396 |
* |
| 2397 |
* @param tableEngine the table engine name |
| 2398 |
* @return the class |
| 2399 |
*/ |
| 2400 |
public TableEngine getTableEngine(String tableEngine) { |
| 2401 |
assert Thread.holdsLock(this); |
| 2402 |
|
| 2403 |
TableEngine engine = tableEngines.get(tableEngine); |
| 2404 |
if (engine == null) { |
| 2405 |
try { |
| 2406 |
engine = (TableEngine) JdbcUtils.loadUserClass(tableEngine).getDeclaredConstructor().newInstance(); |
| 2407 |
} catch (Exception e) { |
| 2408 |
throw DbException.convert(e); |
| 2409 |
} |
| 2410 |
tableEngines.put(tableEngine, engine); |
| 2411 |
} |
| 2412 |
return engine; |
| 2413 |
} |
| 2414 |
|
| 2415 |
/** |
| 2416 |
* get authenticator for database users |
| 2417 |
* @return authenticator set for database |
| 2418 |
*/ |
| 2419 |
public Authenticator getAuthenticator() { |
| 2420 |
return authenticator; |
| 2421 |
} |
| 2422 |
|
| 2423 |
/** |
| 2424 |
* Set current database authenticator |
| 2425 |
* |
| 2426 |
* @param authenticator = authenticator to set, null to revert to the Internal authenticator |
| 2427 |
*/ |
| 2428 |
public void setAuthenticator(Authenticator authenticator) { |
| 2429 |
if (authenticator!=null) { |
| 2430 |
authenticator.init(this); |
| 2431 |
} |
| 2432 |
this.authenticator=authenticator; |
| 2433 |
} |
| 2434 |
|
| 2435 |
@Override |
| 2436 |
public ValueTimestampTimeZone currentTimestamp() { |
| 2437 |
Session session = SessionLocal.getThreadLocalSession(); |
| 2438 |
if (session != null) { |
| 2439 |
return session.currentTimestamp(); |
| 2440 |
} |
| 2441 |
throw DbException.getUnsupportedException("Unsafe comparison or cast"); |
| 2442 |
} |
| 2443 |
|
| 2444 |
@Override |
| 2445 |
public TimeZoneProvider currentTimeZone() { |
| 2446 |
Session session = SessionLocal.getThreadLocalSession(); |
| 2447 |
if (session != null) { |
| 2448 |
return session.currentTimeZone(); |
| 2449 |
} |
| 2450 |
throw DbException.getUnsupportedException("Unsafe comparison or cast"); |
| 2451 |
} |
| 2452 |
|
| 2453 |
@Override |
| 2454 |
public boolean zeroBasedEnums() { |
| 2455 |
return dbSettings.zeroBasedEnums; |
| 2456 |
} |
| 2457 |
|
| 2458 |
} |