| 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.io.IOException; |
| 9 |
import java.net.Socket; |
| 10 |
import java.sql.SQLException; |
| 11 |
import java.util.ArrayList; |
| 12 |
import org.h2.api.DatabaseEventListener; |
| 13 |
import org.h2.api.ErrorCode; |
| 14 |
import org.h2.api.JavaObjectSerializer; |
| 15 |
import org.h2.command.CommandInterface; |
| 16 |
import org.h2.command.CommandRemote; |
| 17 |
import org.h2.command.dml.SetTypes; |
| 18 |
import org.h2.engine.Mode.ModeEnum; |
| 19 |
import org.h2.expression.ParameterInterface; |
| 20 |
import org.h2.jdbc.JdbcException; |
| 21 |
import org.h2.jdbc.meta.DatabaseMeta; |
| 22 |
import org.h2.jdbc.meta.DatabaseMetaLegacy; |
| 23 |
import org.h2.jdbc.meta.DatabaseMetaRemote; |
| 24 |
import org.h2.message.DbException; |
| 25 |
import org.h2.message.Trace; |
| 26 |
import org.h2.message.TraceSystem; |
| 27 |
import org.h2.result.ResultInterface; |
| 28 |
import org.h2.store.DataHandler; |
| 29 |
import org.h2.store.FileStore; |
| 30 |
import org.h2.store.LobStorageFrontend; |
| 31 |
import org.h2.store.fs.FileUtils; |
| 32 |
import org.h2.util.DateTimeUtils; |
| 33 |
import org.h2.util.JdbcUtils; |
| 34 |
import org.h2.util.MathUtils; |
| 35 |
import org.h2.util.NetUtils; |
| 36 |
import org.h2.util.NetworkConnectionInfo; |
| 37 |
import org.h2.util.SmallLRUCache; |
| 38 |
import org.h2.util.StringUtils; |
| 39 |
import org.h2.util.TempFileDeleter; |
| 40 |
import org.h2.util.TimeZoneProvider; |
| 41 |
import org.h2.util.Utils; |
| 42 |
import org.h2.value.CompareMode; |
| 43 |
import org.h2.value.Transfer; |
| 44 |
import org.h2.value.Value; |
| 45 |
import org.h2.value.ValueInteger; |
| 46 |
import org.h2.value.ValueLob; |
| 47 |
import org.h2.value.ValueTimestampTimeZone; |
| 48 |
import org.h2.value.ValueVarchar; |
| 49 |
|
| 50 |
/** |
| 51 |
* The client side part of a session when using the server mode. This object |
| 52 |
* communicates with a Session on the server side. |
| 53 |
*/ |
| 54 |
public final class SessionRemote extends Session implements DataHandler { |
| 55 |
|
| 56 |
public static final int SESSION_PREPARE = 0; |
| 57 |
public static final int SESSION_CLOSE = 1; |
| 58 |
public static final int COMMAND_EXECUTE_QUERY = 2; |
| 59 |
public static final int COMMAND_EXECUTE_UPDATE = 3; |
| 60 |
public static final int COMMAND_CLOSE = 4; |
| 61 |
public static final int RESULT_FETCH_ROWS = 5; |
| 62 |
public static final int RESULT_RESET = 6; |
| 63 |
public static final int RESULT_CLOSE = 7; |
| 64 |
public static final int COMMAND_COMMIT = 8; |
| 65 |
public static final int CHANGE_ID = 9; |
| 66 |
public static final int COMMAND_GET_META_DATA = 10; |
| 67 |
// 11 was used for SESSION_PREPARE_READ_PARAMS |
| 68 |
public static final int SESSION_SET_ID = 12; |
| 69 |
public static final int SESSION_CANCEL_STATEMENT = 13; |
| 70 |
public static final int SESSION_CHECK_KEY = 14; |
| 71 |
public static final int SESSION_SET_AUTOCOMMIT = 15; |
| 72 |
public static final int SESSION_HAS_PENDING_TRANSACTION = 16; |
| 73 |
public static final int LOB_READ = 17; |
| 74 |
public static final int SESSION_PREPARE_READ_PARAMS2 = 18; |
| 75 |
public static final int GET_JDBC_META = 19; |
| 76 |
|
| 77 |
public static final int STATUS_ERROR = 0; |
| 78 |
public static final int STATUS_OK = 1; |
| 79 |
public static final int STATUS_CLOSED = 2; |
| 80 |
public static final int STATUS_OK_STATE_CHANGED = 3; |
| 81 |
|
| 82 |
private TraceSystem traceSystem; |
| 83 |
private Trace trace; |
| 84 |
private ArrayList<Transfer> transferList = Utils.newSmallArrayList(); |
| 85 |
private int nextId; |
| 86 |
private boolean autoCommit = true; |
| 87 |
private ConnectionInfo connectionInfo; |
| 88 |
private String databaseName; |
| 89 |
private String cipher; |
| 90 |
private byte[] fileEncryptionKey; |
| 91 |
private final Object lobSyncObject = new Object(); |
| 92 |
private String sessionId; |
| 93 |
private int clientVersion; |
| 94 |
private boolean autoReconnect; |
| 95 |
private int lastReconnect; |
| 96 |
private Session embedded; |
| 97 |
private DatabaseEventListener eventListener; |
| 98 |
private LobStorageFrontend lobStorage; |
| 99 |
private boolean cluster; |
| 100 |
private TempFileDeleter tempFileDeleter; |
| 101 |
|
| 102 |
private JavaObjectSerializer javaObjectSerializer; |
| 103 |
|
| 104 |
private final CompareMode compareMode = CompareMode.getInstance(null, 0); |
| 105 |
|
| 106 |
private final boolean oldInformationSchema; |
| 107 |
|
| 108 |
private String currentSchemaName; |
| 109 |
|
| 110 |
private volatile DynamicSettings dynamicSettings; |
| 111 |
|
| 112 |
public SessionRemote(ConnectionInfo ci) { |
| 113 |
this.connectionInfo = ci; |
| 114 |
oldInformationSchema = ci.getProperty("OLD_INFORMATION_SCHEMA", false); |
| 115 |
} |
| 116 |
|
| 117 |
@Override |
| 118 |
public ArrayList<String> getClusterServers() { |
| 119 |
ArrayList<String> serverList = new ArrayList<>(); |
| 120 |
for (Transfer transfer : transferList) { |
| 121 |
serverList.add(transfer.getSocket().getInetAddress(). |
| 122 |
getHostAddress() + ":" + |
| 123 |
transfer.getSocket().getPort()); |
| 124 |
} |
| 125 |
return serverList; |
| 126 |
} |
| 127 |
|
| 128 |
private Transfer initTransfer(ConnectionInfo ci, String db, String server) |
| 129 |
throws IOException { |
| 130 |
Socket socket = NetUtils.createSocket(server, Constants.DEFAULT_TCP_PORT, ci.isSSL(), |
| 131 |
ci.getProperty("NETWORK_TIMEOUT", 0)); |
| 132 |
Transfer trans = new Transfer(this, socket); |
| 133 |
trans.setSSL(ci.isSSL()); |
| 134 |
trans.init(); |
| 135 |
trans.writeInt(Constants.TCP_PROTOCOL_VERSION_MIN_SUPPORTED); |
| 136 |
trans.writeInt(Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED); |
| 137 |
trans.writeString(db); |
| 138 |
trans.writeString(ci.getOriginalURL()); |
| 139 |
trans.writeString(ci.getUserName()); |
| 140 |
trans.writeBytes(ci.getUserPasswordHash()); |
| 141 |
trans.writeBytes(ci.getFilePasswordHash()); |
| 142 |
String[] keys = ci.getKeys(); |
| 143 |
trans.writeInt(keys.length); |
| 144 |
for (String key : keys) { |
| 145 |
trans.writeString(key).writeString(ci.getProperty(key)); |
| 146 |
} |
| 147 |
try { |
| 148 |
done(trans); |
| 149 |
clientVersion = trans.readInt(); |
| 150 |
trans.setVersion(clientVersion); |
| 151 |
if (ci.getFileEncryptionKey() != null) { |
| 152 |
trans.writeBytes(ci.getFileEncryptionKey()); |
| 153 |
} |
| 154 |
trans.writeInt(SessionRemote.SESSION_SET_ID); |
| 155 |
trans.writeString(sessionId); |
| 156 |
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_20) { |
| 157 |
TimeZoneProvider timeZone = ci.getTimeZone(); |
| 158 |
if (timeZone == null) { |
| 159 |
timeZone = DateTimeUtils.getTimeZone(); |
| 160 |
} |
| 161 |
trans.writeString(timeZone.getId()); |
| 162 |
} |
| 163 |
done(trans); |
| 164 |
autoCommit = trans.readBoolean(); |
| 165 |
return trans; |
| 166 |
} catch (DbException e) { |
| 167 |
trans.close(); |
| 168 |
throw e; |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
@Override |
| 173 |
public boolean hasPendingTransaction() { |
| 174 |
for (int i = 0, count = 0; i < transferList.size(); i++) { |
| 175 |
Transfer transfer = transferList.get(i); |
| 176 |
try { |
| 177 |
traceOperation("SESSION_HAS_PENDING_TRANSACTION", 0); |
| 178 |
transfer.writeInt( |
| 179 |
SessionRemote.SESSION_HAS_PENDING_TRANSACTION); |
| 180 |
done(transfer); |
| 181 |
return transfer.readInt() != 0; |
| 182 |
} catch (IOException e) { |
| 183 |
removeServer(e, i--, ++count); |
| 184 |
} |
| 185 |
} |
| 186 |
return true; |
| 187 |
} |
| 188 |
|
| 189 |
@Override |
| 190 |
public void cancel() { |
| 191 |
// this method is called when closing the connection |
| 192 |
// the statement that is currently running is not canceled in this case |
| 193 |
// however Statement.cancel is supported |
| 194 |
} |
| 195 |
|
| 196 |
/** |
| 197 |
* Cancel the statement with the given id. |
| 198 |
* |
| 199 |
* @param id the statement id |
| 200 |
*/ |
| 201 |
public void cancelStatement(int id) { |
| 202 |
for (Transfer transfer : transferList) { |
| 203 |
try { |
| 204 |
Transfer trans = transfer.openNewConnection(); |
| 205 |
trans.init(); |
| 206 |
trans.writeInt(clientVersion); |
| 207 |
trans.writeInt(clientVersion); |
| 208 |
trans.writeString(null); |
| 209 |
trans.writeString(null); |
| 210 |
trans.writeString(sessionId); |
| 211 |
trans.writeInt(SessionRemote.SESSION_CANCEL_STATEMENT); |
| 212 |
trans.writeInt(id); |
| 213 |
trans.close(); |
| 214 |
} catch (IOException e) { |
| 215 |
trace.debug(e, "could not cancel statement"); |
| 216 |
} |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
private void checkClusterDisableAutoCommit(String serverList) { |
| 221 |
if (autoCommit && transferList.size() > 1) { |
| 222 |
setAutoCommitSend(false); |
| 223 |
CommandInterface c = prepareCommand( |
| 224 |
"SET CLUSTER " + serverList, Integer.MAX_VALUE); |
| 225 |
// this will set autoCommit to false |
| 226 |
c.executeUpdate(null); |
| 227 |
// so we need to switch it on |
| 228 |
autoCommit = true; |
| 229 |
cluster = true; |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
/** |
| 234 |
* Returns the TCP protocol version of remote connection. |
| 235 |
* |
| 236 |
* @return the TCP protocol version |
| 237 |
*/ |
| 238 |
public int getClientVersion() { |
| 239 |
return clientVersion; |
| 240 |
} |
| 241 |
|
| 242 |
@Override |
| 243 |
public boolean getAutoCommit() { |
| 244 |
return autoCommit; |
| 245 |
} |
| 246 |
|
| 247 |
@Override |
| 248 |
public void setAutoCommit(boolean autoCommit) { |
| 249 |
if (!cluster) { |
| 250 |
setAutoCommitSend(autoCommit); |
| 251 |
} |
| 252 |
this.autoCommit = autoCommit; |
| 253 |
} |
| 254 |
|
| 255 |
public void setAutoCommitFromServer(boolean autoCommit) { |
| 256 |
if (cluster) { |
| 257 |
if (autoCommit) { |
| 258 |
// the user executed SET AUTOCOMMIT TRUE |
| 259 |
setAutoCommitSend(false); |
| 260 |
this.autoCommit = true; |
| 261 |
} |
| 262 |
} else { |
| 263 |
this.autoCommit = autoCommit; |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
private synchronized void setAutoCommitSend(boolean autoCommit) { |
| 268 |
for (int i = 0, count = 0; i < transferList.size(); i++) { |
| 269 |
Transfer transfer = transferList.get(i); |
| 270 |
try { |
| 271 |
traceOperation("SESSION_SET_AUTOCOMMIT", autoCommit ? 1 : 0); |
| 272 |
transfer.writeInt(SessionRemote.SESSION_SET_AUTOCOMMIT). |
| 273 |
writeBoolean(autoCommit); |
| 274 |
done(transfer); |
| 275 |
} catch (IOException e) { |
| 276 |
removeServer(e, i--, ++count); |
| 277 |
} |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
/** |
| 282 |
* Calls COMMIT if the session is in cluster mode. |
| 283 |
*/ |
| 284 |
public void autoCommitIfCluster() { |
| 285 |
if (autoCommit && cluster) { |
| 286 |
// server side auto commit is off because of race conditions |
| 287 |
// (update set id=1 where id=0, but update set id=2 where id=0 is |
| 288 |
// faster) |
| 289 |
for (int i = 0, count = 0; i < transferList.size(); i++) { |
| 290 |
Transfer transfer = transferList.get(i); |
| 291 |
try { |
| 292 |
traceOperation("COMMAND_COMMIT", 0); |
| 293 |
transfer.writeInt(SessionRemote.COMMAND_COMMIT); |
| 294 |
done(transfer); |
| 295 |
} catch (IOException e) { |
| 296 |
removeServer(e, i--, ++count); |
| 297 |
} |
| 298 |
} |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
private String getFilePrefix(String dir) { |
| 303 |
StringBuilder buff = new StringBuilder(dir); |
| 304 |
buff.append('/'); |
| 305 |
for (int i = 0; i < databaseName.length(); i++) { |
| 306 |
char ch = databaseName.charAt(i); |
| 307 |
if (Character.isLetterOrDigit(ch)) { |
| 308 |
buff.append(ch); |
| 309 |
} else { |
| 310 |
buff.append('_'); |
| 311 |
} |
| 312 |
} |
| 313 |
return buff.toString(); |
| 314 |
} |
| 315 |
|
| 316 |
/** |
| 317 |
* Open a new (remote or embedded) session. |
| 318 |
* |
| 319 |
* @param openNew whether to open a new session in any case |
| 320 |
* @return the session |
| 321 |
*/ |
| 322 |
public Session connectEmbeddedOrServer(boolean openNew) { |
| 323 |
ConnectionInfo ci = connectionInfo; |
| 324 |
if (ci.isRemote()) { |
| 325 |
connectServer(ci); |
| 326 |
return this; |
| 327 |
} |
| 328 |
boolean autoServerMode = ci.getProperty("AUTO_SERVER", false); |
| 329 |
ConnectionInfo backup = null; |
| 330 |
try { |
| 331 |
if (autoServerMode) { |
| 332 |
backup = ci.clone(); |
| 333 |
connectionInfo = ci.clone(); |
| 334 |
} |
| 335 |
if (openNew) { |
| 336 |
ci.setProperty("OPEN_NEW", "true"); |
| 337 |
} |
| 338 |
return Engine.createSession(ci); |
| 339 |
} catch (Exception re) { |
| 340 |
DbException e = DbException.convert(re); |
| 341 |
if (e.getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1) { |
| 342 |
if (autoServerMode) { |
| 343 |
String serverKey = ((JdbcException) e.getSQLException()).getSQL(); |
| 344 |
if (serverKey != null) { |
| 345 |
backup.setServerKey(serverKey); |
| 346 |
// OPEN_NEW must be removed now, otherwise |
| 347 |
// opening a session with AUTO_SERVER fails |
| 348 |
// if another connection is already open |
| 349 |
backup.removeProperty("OPEN_NEW", null); |
| 350 |
connectServer(backup); |
| 351 |
return this; |
| 352 |
} |
| 353 |
} |
| 354 |
} |
| 355 |
throw e; |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
private void connectServer(ConnectionInfo ci) { |
| 360 |
String name = ci.getName(); |
| 361 |
if (name.startsWith("//")) { |
| 362 |
name = name.substring("//".length()); |
| 363 |
} |
| 364 |
int idx = name.indexOf('/'); |
| 365 |
if (idx < 0) { |
| 366 |
throw ci.getFormatException(); |
| 367 |
} |
| 368 |
databaseName = name.substring(idx + 1); |
| 369 |
String server = name.substring(0, idx); |
| 370 |
traceSystem = new TraceSystem(null); |
| 371 |
String traceLevelFile = ci.getProperty( |
| 372 |
SetTypes.TRACE_LEVEL_FILE, null); |
| 373 |
if (traceLevelFile != null) { |
| 374 |
int level = Integer.parseInt(traceLevelFile); |
| 375 |
String prefix = getFilePrefix( |
| 376 |
SysProperties.CLIENT_TRACE_DIRECTORY); |
| 377 |
try { |
| 378 |
traceSystem.setLevelFile(level); |
| 379 |
if (level > 0 && level < 4) { |
| 380 |
String file = FileUtils.createTempFile(prefix, |
| 381 |
Constants.SUFFIX_TRACE_FILE, false); |
| 382 |
traceSystem.setFileName(file); |
| 383 |
} |
| 384 |
} catch (IOException e) { |
| 385 |
throw DbException.convertIOException(e, prefix); |
| 386 |
} |
| 387 |
} |
| 388 |
String traceLevelSystemOut = ci.getProperty( |
| 389 |
SetTypes.TRACE_LEVEL_SYSTEM_OUT, null); |
| 390 |
if (traceLevelSystemOut != null) { |
| 391 |
int level = Integer.parseInt(traceLevelSystemOut); |
| 392 |
traceSystem.setLevelSystemOut(level); |
| 393 |
} |
| 394 |
trace = traceSystem.getTrace(Trace.JDBC); |
| 395 |
String serverList = null; |
| 396 |
if (server.indexOf(',') >= 0) { |
| 397 |
serverList = StringUtils.quoteStringSQL(server); |
| 398 |
ci.setProperty("CLUSTER", Constants.CLUSTERING_ENABLED); |
| 399 |
} |
| 400 |
autoReconnect = ci.getProperty("AUTO_RECONNECT", false); |
| 401 |
// AUTO_SERVER implies AUTO_RECONNECT |
| 402 |
boolean autoServer = ci.getProperty("AUTO_SERVER", false); |
| 403 |
if (autoServer && serverList != null) { |
| 404 |
throw DbException |
| 405 |
.getUnsupportedException("autoServer && serverList != null"); |
| 406 |
} |
| 407 |
autoReconnect |= autoServer; |
| 408 |
if (autoReconnect) { |
| 409 |
String className = ci.getProperty("DATABASE_EVENT_LISTENER"); |
| 410 |
if (className != null) { |
| 411 |
className = StringUtils.trim(className, true, true, '\''); |
| 412 |
try { |
| 413 |
eventListener = (DatabaseEventListener) JdbcUtils |
| 414 |
.loadUserClass(className).getDeclaredConstructor().newInstance(); |
| 415 |
} catch (Throwable e) { |
| 416 |
throw DbException.convert(e); |
| 417 |
} |
| 418 |
} |
| 419 |
} |
| 420 |
cipher = ci.getProperty("CIPHER"); |
| 421 |
if (cipher != null) { |
| 422 |
fileEncryptionKey = MathUtils.secureRandomBytes(32); |
| 423 |
} |
| 424 |
String[] servers = StringUtils.arraySplit(server, ',', true); |
| 425 |
int len = servers.length; |
| 426 |
transferList.clear(); |
| 427 |
sessionId = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32)); |
| 428 |
// TODO cluster: support more than 2 connections |
| 429 |
boolean switchOffCluster = false; |
| 430 |
try { |
| 431 |
for (String s : servers) { |
| 432 |
try { |
| 433 |
Transfer trans = initTransfer(ci, databaseName, s); |
| 434 |
transferList.add(trans); |
| 435 |
} catch (IOException e) { |
| 436 |
if (len == 1) { |
| 437 |
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, e + ": " + s); |
| 438 |
} |
| 439 |
switchOffCluster = true; |
| 440 |
} |
| 441 |
} |
| 442 |
checkClosed(); |
| 443 |
if (switchOffCluster) { |
| 444 |
switchOffCluster(); |
| 445 |
} |
| 446 |
checkClusterDisableAutoCommit(serverList); |
| 447 |
} catch (DbException e) { |
| 448 |
traceSystem.close(); |
| 449 |
throw e; |
| 450 |
} |
| 451 |
getDynamicSettings(); |
| 452 |
} |
| 453 |
|
| 454 |
private void switchOffCluster() { |
| 455 |
CommandInterface ci = prepareCommand("SET CLUSTER ''", Integer.MAX_VALUE); |
| 456 |
ci.executeUpdate(null); |
| 457 |
} |
| 458 |
|
| 459 |
/** |
| 460 |
* Remove a server from the list of cluster nodes and disables the cluster |
| 461 |
* mode. |
| 462 |
* |
| 463 |
* @param e the exception (used for debugging) |
| 464 |
* @param i the index of the server to remove |
| 465 |
* @param count the retry count index |
| 466 |
*/ |
| 467 |
public void removeServer(IOException e, int i, int count) { |
| 468 |
trace.debug(e, "removing server because of exception"); |
| 469 |
transferList.remove(i); |
| 470 |
if (transferList.isEmpty() && autoReconnect(count)) { |
| 471 |
return; |
| 472 |
} |
| 473 |
checkClosed(); |
| 474 |
switchOffCluster(); |
| 475 |
} |
| 476 |
|
| 477 |
@Override |
| 478 |
public synchronized CommandInterface prepareCommand(String sql, int fetchSize) { |
| 479 |
checkClosed(); |
| 480 |
return new CommandRemote(this, transferList, sql, fetchSize); |
| 481 |
} |
| 482 |
|
| 483 |
/** |
| 484 |
* Automatically re-connect if necessary and if configured to do so. |
| 485 |
* |
| 486 |
* @param count the retry count index |
| 487 |
* @return true if reconnected |
| 488 |
*/ |
| 489 |
private boolean autoReconnect(int count) { |
| 490 |
if (!isClosed()) { |
| 491 |
return false; |
| 492 |
} |
| 493 |
if (!autoReconnect) { |
| 494 |
return false; |
| 495 |
} |
| 496 |
if (!cluster && !autoCommit) { |
| 497 |
return false; |
| 498 |
} |
| 499 |
if (count > SysProperties.MAX_RECONNECT) { |
| 500 |
return false; |
| 501 |
} |
| 502 |
lastReconnect++; |
| 503 |
while (true) { |
| 504 |
try { |
| 505 |
embedded = connectEmbeddedOrServer(false); |
| 506 |
break; |
| 507 |
} catch (DbException e) { |
| 508 |
if (e.getErrorCode() != ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE) { |
| 509 |
throw e; |
| 510 |
} |
| 511 |
// exclusive mode: re-try endlessly |
| 512 |
try { |
| 513 |
Thread.sleep(500); |
| 514 |
} catch (Exception e2) { |
| 515 |
// ignore |
| 516 |
} |
| 517 |
} |
| 518 |
} |
| 519 |
if (embedded == this) { |
| 520 |
// connected to a server somewhere else |
| 521 |
embedded = null; |
| 522 |
} else { |
| 523 |
// opened an embedded connection now - |
| 524 |
// must connect to this database in server mode |
| 525 |
// unfortunately |
| 526 |
connectEmbeddedOrServer(true); |
| 527 |
} |
| 528 |
recreateSessionState(); |
| 529 |
if (eventListener != null) { |
| 530 |
eventListener.setProgress(DatabaseEventListener.STATE_RECONNECTED, |
| 531 |
databaseName, count, SysProperties.MAX_RECONNECT); |
| 532 |
} |
| 533 |
return true; |
| 534 |
} |
| 535 |
|
| 536 |
/** |
| 537 |
* Check if this session is closed and throws an exception if so. |
| 538 |
* |
| 539 |
* @throws DbException if the session is closed |
| 540 |
*/ |
| 541 |
public void checkClosed() { |
| 542 |
if (isClosed()) { |
| 543 |
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "session closed"); |
| 544 |
} |
| 545 |
} |
| 546 |
|
| 547 |
@Override |
| 548 |
public void close() { |
| 549 |
RuntimeException closeError = null; |
| 550 |
if (transferList != null) { |
| 551 |
synchronized (this) { |
| 552 |
for (Transfer transfer : transferList) { |
| 553 |
try { |
| 554 |
traceOperation("SESSION_CLOSE", 0); |
| 555 |
transfer.writeInt(SessionRemote.SESSION_CLOSE); |
| 556 |
done(transfer); |
| 557 |
transfer.close(); |
| 558 |
} catch (RuntimeException e) { |
| 559 |
trace.error(e, "close"); |
| 560 |
closeError = e; |
| 561 |
} catch (Exception e) { |
| 562 |
trace.error(e, "close"); |
| 563 |
} |
| 564 |
} |
| 565 |
} |
| 566 |
transferList = null; |
| 567 |
} |
| 568 |
traceSystem.close(); |
| 569 |
if (embedded != null) { |
| 570 |
embedded.close(); |
| 571 |
embedded = null; |
| 572 |
} |
| 573 |
if (closeError != null) { |
| 574 |
throw closeError; |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
@Override |
| 579 |
public Trace getTrace() { |
| 580 |
return traceSystem.getTrace(Trace.JDBC); |
| 581 |
} |
| 582 |
|
| 583 |
public int getNextId() { |
| 584 |
return nextId++; |
| 585 |
} |
| 586 |
|
| 587 |
public int getCurrentId() { |
| 588 |
return nextId; |
| 589 |
} |
| 590 |
|
| 591 |
/** |
| 592 |
* Called to flush the output after data has been sent to the server and |
| 593 |
* just before receiving data. This method also reads the status code from |
| 594 |
* the server and throws any exception the server sent. |
| 595 |
* |
| 596 |
* @param transfer the transfer object |
| 597 |
* @throws DbException if the server sent an exception |
| 598 |
* @throws IOException if there is a communication problem between client |
| 599 |
* and server |
| 600 |
*/ |
| 601 |
public void done(Transfer transfer) throws IOException { |
| 602 |
transfer.flush(); |
| 603 |
int status = transfer.readInt(); |
| 604 |
switch (status) { |
| 605 |
case STATUS_ERROR: |
| 606 |
throw readException(transfer); |
| 607 |
case STATUS_OK: |
| 608 |
break; |
| 609 |
case STATUS_CLOSED: |
| 610 |
transferList = null; |
| 611 |
break; |
| 612 |
case STATUS_OK_STATE_CHANGED: |
| 613 |
sessionStateChanged = true; |
| 614 |
currentSchemaName = null; |
| 615 |
dynamicSettings = null; |
| 616 |
break; |
| 617 |
default: |
| 618 |
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "unexpected status " + status); |
| 619 |
} |
| 620 |
} |
| 621 |
|
| 622 |
/** |
| 623 |
* Reads an exception. |
| 624 |
* |
| 625 |
* @param transfer |
| 626 |
* the transfer object |
| 627 |
* @return the exception |
| 628 |
* @throws IOException |
| 629 |
* on I/O exception |
| 630 |
*/ |
| 631 |
public static DbException readException(Transfer transfer) throws IOException { |
| 632 |
String sqlstate = transfer.readString(); |
| 633 |
String message = transfer.readString(); |
| 634 |
String sql = transfer.readString(); |
| 635 |
int errorCode = transfer.readInt(); |
| 636 |
String stackTrace = transfer.readString(); |
| 637 |
SQLException s = DbException.getJdbcSQLException(message, sql, sqlstate, errorCode, null, stackTrace); |
| 638 |
if (errorCode == ErrorCode.CONNECTION_BROKEN_1) { |
| 639 |
// allow re-connect |
| 640 |
throw new IOException(s.toString(), s); |
| 641 |
} |
| 642 |
return DbException.convert(s); |
| 643 |
} |
| 644 |
|
| 645 |
/** |
| 646 |
* Returns true if the connection was opened in cluster mode. |
| 647 |
* |
| 648 |
* @return true if it is |
| 649 |
*/ |
| 650 |
public boolean isClustered() { |
| 651 |
return cluster; |
| 652 |
} |
| 653 |
|
| 654 |
@Override |
| 655 |
public boolean isClosed() { |
| 656 |
return transferList == null || transferList.isEmpty(); |
| 657 |
} |
| 658 |
|
| 659 |
/** |
| 660 |
* Write the operation to the trace system if debug trace is enabled. |
| 661 |
* |
| 662 |
* @param operation the operation performed |
| 663 |
* @param id the id of the operation |
| 664 |
*/ |
| 665 |
public void traceOperation(String operation, int id) { |
| 666 |
if (trace.isDebugEnabled()) { |
| 667 |
trace.debug("{0} {1}", operation, id); |
| 668 |
} |
| 669 |
} |
| 670 |
|
| 671 |
@Override |
| 672 |
public void checkPowerOff() { |
| 673 |
// ok |
| 674 |
} |
| 675 |
|
| 676 |
@Override |
| 677 |
public void checkWritingAllowed() { |
| 678 |
// ok |
| 679 |
} |
| 680 |
|
| 681 |
@Override |
| 682 |
public String getDatabasePath() { |
| 683 |
return ""; |
| 684 |
} |
| 685 |
|
| 686 |
@Override |
| 687 |
public int getMaxLengthInplaceLob() { |
| 688 |
return SysProperties.LOB_CLIENT_MAX_SIZE_MEMORY; |
| 689 |
} |
| 690 |
|
| 691 |
@Override |
| 692 |
public FileStore openFile(String name, String mode, boolean mustExist) { |
| 693 |
if (mustExist && !FileUtils.exists(name)) { |
| 694 |
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name); |
| 695 |
} |
| 696 |
FileStore store; |
| 697 |
if (cipher == null) { |
| 698 |
store = FileStore.open(this, name, mode); |
| 699 |
} else { |
| 700 |
store = FileStore.open(this, name, mode, cipher, fileEncryptionKey, 0); |
| 701 |
} |
| 702 |
store.setCheckedWriting(false); |
| 703 |
try { |
| 704 |
store.init(); |
| 705 |
} catch (DbException e) { |
| 706 |
store.closeSilently(); |
| 707 |
throw e; |
| 708 |
} |
| 709 |
return store; |
| 710 |
} |
| 711 |
|
| 712 |
@Override |
| 713 |
public DataHandler getDataHandler() { |
| 714 |
return this; |
| 715 |
} |
| 716 |
|
| 717 |
@Override |
| 718 |
public Object getLobSyncObject() { |
| 719 |
return lobSyncObject; |
| 720 |
} |
| 721 |
|
| 722 |
@Override |
| 723 |
public SmallLRUCache<String, String[]> getLobFileListCache() { |
| 724 |
return null; |
| 725 |
} |
| 726 |
|
| 727 |
public int getLastReconnect() { |
| 728 |
return lastReconnect; |
| 729 |
} |
| 730 |
|
| 731 |
@Override |
| 732 |
public TempFileDeleter getTempFileDeleter() { |
| 733 |
if (tempFileDeleter == null) { |
| 734 |
tempFileDeleter = TempFileDeleter.getInstance(); |
| 735 |
} |
| 736 |
return tempFileDeleter; |
| 737 |
} |
| 738 |
|
| 739 |
@Override |
| 740 |
public LobStorageFrontend getLobStorage() { |
| 741 |
if (lobStorage == null) { |
| 742 |
lobStorage = new LobStorageFrontend(this); |
| 743 |
} |
| 744 |
return lobStorage; |
| 745 |
} |
| 746 |
|
| 747 |
@Override |
| 748 |
public synchronized int readLob(long lobId, byte[] hmac, long offset, |
| 749 |
byte[] buff, int off, int length) { |
| 750 |
checkClosed(); |
| 751 |
for (int i = 0, count = 0; i < transferList.size(); i++) { |
| 752 |
Transfer transfer = transferList.get(i); |
| 753 |
try { |
| 754 |
traceOperation("LOB_READ", (int) lobId); |
| 755 |
transfer.writeInt(SessionRemote.LOB_READ); |
| 756 |
transfer.writeLong(lobId); |
| 757 |
transfer.writeBytes(hmac); |
| 758 |
transfer.writeLong(offset); |
| 759 |
transfer.writeInt(length); |
| 760 |
done(transfer); |
| 761 |
length = transfer.readInt(); |
| 762 |
if (length <= 0) { |
| 763 |
return length; |
| 764 |
} |
| 765 |
transfer.readBytes(buff, off, length); |
| 766 |
return length; |
| 767 |
} catch (IOException e) { |
| 768 |
removeServer(e, i--, ++count); |
| 769 |
} |
| 770 |
} |
| 771 |
return 1; |
| 772 |
} |
| 773 |
|
| 774 |
@Override |
| 775 |
public JavaObjectSerializer getJavaObjectSerializer() { |
| 776 |
if (dynamicSettings == null) { |
| 777 |
getDynamicSettings(); |
| 778 |
} |
| 779 |
return javaObjectSerializer; |
| 780 |
} |
| 781 |
|
| 782 |
@Override |
| 783 |
public ValueLob addTemporaryLob(ValueLob v) { |
| 784 |
// do nothing |
| 785 |
return v; |
| 786 |
} |
| 787 |
|
| 788 |
@Override |
| 789 |
public CompareMode getCompareMode() { |
| 790 |
return compareMode; |
| 791 |
} |
| 792 |
|
| 793 |
@Override |
| 794 |
public boolean isRemote() { |
| 795 |
return true; |
| 796 |
} |
| 797 |
|
| 798 |
@Override |
| 799 |
public String getCurrentSchemaName() { |
| 800 |
String schema = currentSchemaName; |
| 801 |
if (schema == null) { |
| 802 |
synchronized (this) { |
| 803 |
try (CommandInterface command = prepareCommand("CALL SCHEMA()", 1); |
| 804 |
ResultInterface result = command.executeQuery(1, false)) { |
| 805 |
result.next(); |
| 806 |
currentSchemaName = schema = result.currentRow()[0].getString(); |
| 807 |
} |
| 808 |
} |
| 809 |
} |
| 810 |
return schema; |
| 811 |
} |
| 812 |
|
| 813 |
@Override |
| 814 |
public synchronized void setCurrentSchemaName(String schema) { |
| 815 |
currentSchemaName = null; |
| 816 |
try (CommandInterface command = prepareCommand( |
| 817 |
StringUtils.quoteIdentifier(new StringBuilder("SET SCHEMA "), schema).toString(), 0)) { |
| 818 |
command.executeUpdate(null); |
| 819 |
currentSchemaName = schema; |
| 820 |
} |
| 821 |
} |
| 822 |
|
| 823 |
@Override |
| 824 |
public void setNetworkConnectionInfo(NetworkConnectionInfo networkConnectionInfo) { |
| 825 |
// Not supported |
| 826 |
} |
| 827 |
|
| 828 |
@Override |
| 829 |
public IsolationLevel getIsolationLevel() { |
| 830 |
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_19) { |
| 831 |
try (CommandInterface command = prepareCommand(!isOldInformationSchema() |
| 832 |
? "SELECT ISOLATION_LEVEL FROM INFORMATION_SCHEMA.SESSIONS WHERE SESSION_ID = SESSION_ID()" |
| 833 |
: "SELECT ISOLATION_LEVEL FROM INFORMATION_SCHEMA.SESSIONS WHERE ID = SESSION_ID()", 1); |
| 834 |
ResultInterface result = command.executeQuery(1, false)) { |
| 835 |
result.next(); |
| 836 |
return IsolationLevel.fromSql(result.currentRow()[0].getString()); |
| 837 |
} |
| 838 |
} else { |
| 839 |
try (CommandInterface command = prepareCommand("CALL LOCK_MODE()", 1); |
| 840 |
ResultInterface result = command.executeQuery(1, false)) { |
| 841 |
result.next(); |
| 842 |
return IsolationLevel.fromLockMode(result.currentRow()[0].getInt()); |
| 843 |
} |
| 844 |
} |
| 845 |
} |
| 846 |
|
| 847 |
@Override |
| 848 |
public void setIsolationLevel(IsolationLevel isolationLevel) { |
| 849 |
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_19) { |
| 850 |
try (CommandInterface command = prepareCommand( |
| 851 |
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevel.getSQL(), 0)) { |
| 852 |
command.executeUpdate(null); |
| 853 |
} |
| 854 |
} else { |
| 855 |
try (CommandInterface command = prepareCommand("SET LOCK_MODE ?", 0)) { |
| 856 |
command.getParameters().get(0).setValue(ValueInteger.get(isolationLevel.getLockMode()), false); |
| 857 |
command.executeUpdate(null); |
| 858 |
} |
| 859 |
} |
| 860 |
} |
| 861 |
|
| 862 |
@Override |
| 863 |
public StaticSettings getStaticSettings() { |
| 864 |
StaticSettings settings = staticSettings; |
| 865 |
if (settings == null) { |
| 866 |
boolean databaseToUpper = true, databaseToLower = false, caseInsensitiveIdentifiers = false; |
| 867 |
try (CommandInterface command = getSettingsCommand(" IN (?, ?, ?)")) { |
| 868 |
ArrayList<? extends ParameterInterface> parameters = command.getParameters(); |
| 869 |
parameters.get(0).setValue(ValueVarchar.get("DATABASE_TO_UPPER"), false); |
| 870 |
parameters.get(1).setValue(ValueVarchar.get("DATABASE_TO_LOWER"), false); |
| 871 |
parameters.get(2).setValue(ValueVarchar.get("CASE_INSENSITIVE_IDENTIFIERS"), false); |
| 872 |
try (ResultInterface result = command.executeQuery(0, false)) { |
| 873 |
while (result.next()) { |
| 874 |
Value[] row = result.currentRow(); |
| 875 |
String value = row[1].getString(); |
| 876 |
switch (row[0].getString()) { |
| 877 |
case "DATABASE_TO_UPPER": |
| 878 |
databaseToUpper = Boolean.valueOf(value); |
| 879 |
break; |
| 880 |
case "DATABASE_TO_LOWER": |
| 881 |
databaseToLower = Boolean.valueOf(value); |
| 882 |
break; |
| 883 |
case "CASE_INSENSITIVE_IDENTIFIERS": |
| 884 |
caseInsensitiveIdentifiers = Boolean.valueOf(value); |
| 885 |
} |
| 886 |
} |
| 887 |
} |
| 888 |
} |
| 889 |
if (clientVersion < Constants.TCP_PROTOCOL_VERSION_18) { |
| 890 |
caseInsensitiveIdentifiers = !databaseToUpper; |
| 891 |
} |
| 892 |
staticSettings = settings = new StaticSettings(databaseToUpper, databaseToLower, |
| 893 |
caseInsensitiveIdentifiers); |
| 894 |
} |
| 895 |
return settings; |
| 896 |
} |
| 897 |
|
| 898 |
@Override |
| 899 |
public DynamicSettings getDynamicSettings() { |
| 900 |
DynamicSettings settings = dynamicSettings; |
| 901 |
if (settings == null) { |
| 902 |
String modeName = ModeEnum.REGULAR.name(); |
| 903 |
TimeZoneProvider timeZone = DateTimeUtils.getTimeZone(); |
| 904 |
String javaObjectSerializerName = null; |
| 905 |
try (CommandInterface command = getSettingsCommand(" IN (?, ?, ?)")) { |
| 906 |
ArrayList<? extends ParameterInterface> parameters = command.getParameters(); |
| 907 |
parameters.get(0).setValue(ValueVarchar.get("MODE"), false); |
| 908 |
parameters.get(1).setValue(ValueVarchar.get("TIME ZONE"), false); |
| 909 |
parameters.get(2).setValue(ValueVarchar.get("JAVA_OBJECT_SERIALIZER"), false); |
| 910 |
try (ResultInterface result = command.executeQuery(0, false)) { |
| 911 |
while (result.next()) { |
| 912 |
Value[] row = result.currentRow(); |
| 913 |
String value = row[1].getString(); |
| 914 |
switch (row[0].getString()) { |
| 915 |
case "MODE": |
| 916 |
modeName = value; |
| 917 |
break; |
| 918 |
case "TIME ZONE": |
| 919 |
timeZone = TimeZoneProvider.ofId(value); |
| 920 |
break; |
| 921 |
case "JAVA_OBJECT_SERIALIZER": |
| 922 |
javaObjectSerializerName = value; |
| 923 |
} |
| 924 |
} |
| 925 |
} |
| 926 |
} |
| 927 |
Mode mode = Mode.getInstance(modeName); |
| 928 |
if (mode == null) { |
| 929 |
mode = Mode.getRegular(); |
| 930 |
} |
| 931 |
dynamicSettings = settings = new DynamicSettings(mode, timeZone); |
| 932 |
if (javaObjectSerializerName != null |
| 933 |
&& !(javaObjectSerializerName = javaObjectSerializerName.trim()).isEmpty() |
| 934 |
&& !javaObjectSerializerName.equals("null")) { |
| 935 |
try { |
| 936 |
javaObjectSerializer = (JavaObjectSerializer) JdbcUtils |
| 937 |
.loadUserClass(javaObjectSerializerName).getDeclaredConstructor().newInstance(); |
| 938 |
} catch (Exception e) { |
| 939 |
throw DbException.convert(e); |
| 940 |
} |
| 941 |
} else { |
| 942 |
javaObjectSerializer = null; |
| 943 |
} |
| 944 |
} |
| 945 |
return settings; |
| 946 |
} |
| 947 |
|
| 948 |
private CommandInterface getSettingsCommand(String args) { |
| 949 |
return prepareCommand( |
| 950 |
(!isOldInformationSchema() |
| 951 |
? "SELECT SETTING_NAME, SETTING_VALUE FROM INFORMATION_SCHEMA.SETTINGS WHERE SETTING_NAME" |
| 952 |
: "SELECT NAME, `VALUE` FROM INFORMATION_SCHEMA.SETTINGS WHERE NAME") + args, |
| 953 |
Integer.MAX_VALUE); |
| 954 |
} |
| 955 |
|
| 956 |
@Override |
| 957 |
public ValueTimestampTimeZone currentTimestamp() { |
| 958 |
return DateTimeUtils.currentTimestamp(getDynamicSettings().timeZone); |
| 959 |
} |
| 960 |
|
| 961 |
@Override |
| 962 |
public TimeZoneProvider currentTimeZone() { |
| 963 |
return getDynamicSettings().timeZone; |
| 964 |
} |
| 965 |
|
| 966 |
@Override |
| 967 |
public Mode getMode() { |
| 968 |
return getDynamicSettings().mode; |
| 969 |
} |
| 970 |
|
| 971 |
@Override |
| 972 |
public DatabaseMeta getDatabaseMeta() { |
| 973 |
return clientVersion >= Constants.TCP_PROTOCOL_VERSION_20 ? new DatabaseMetaRemote(this, transferList) |
| 974 |
: new DatabaseMetaLegacy(this); |
| 975 |
} |
| 976 |
|
| 977 |
@Override |
| 978 |
public boolean isOldInformationSchema() { |
| 979 |
return oldInformationSchema || clientVersion < Constants.TCP_PROTOCOL_VERSION_20; |
| 980 |
} |
| 981 |
|
| 982 |
@Override |
| 983 |
public boolean zeroBasedEnums() { |
| 984 |
return false; |
| 985 |
} |
| 986 |
|
| 987 |
} |