org.mariadb.jdbc.internal.protocol
Class AbstractQueryProtocol

java.lang.Object
  extended by org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol
      extended by org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol
All Implemented Interfaces:
Protocol
Direct Known Subclasses:
MasterProtocol

public class AbstractQueryProtocol
extends AbstractConnectProtocol
implements Protocol


Field Summary
static ThreadPoolExecutor readScheduler
           
 
Fields inherited from class org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol
activeStreamingResult, autoIncrementIncrement, connected, currentHost, database, dataTypeMappingFlags, eofDeprecated, explicitClosed, hasWarnings, IS_MASTER_QUERY, lock, options, proxy, reader, readOnly, serverCapabilities, serverPrepareStatementCache, serverStatus, serverThreadId, SESSION_QUERY, socket, urlParser, writer
 
Constructor Summary
AbstractQueryProtocol(UrlParser urlParser, ReentrantLock lock)
          Get a protocol instance.
 
Method Summary
 ServerPrepareResult addPrepareInCache(String key, ServerPrepareResult serverPrepareResult)
           
 void cancelCurrentQuery()
          Cancels the current query - clones the current protocol and executes a query using the new connection.
 void closeExplicit()
           
 void executeBatch(boolean mustExecuteOnMaster, Results results, List<String> queries)
          Execute list of queries not rewritable.
 void executeBatchMulti(boolean mustExecuteOnMaster, Results results, ClientPrepareResult clientPrepareResult, List<ParameterHolder[]> parametersList)
          Execute clientPrepareQuery batch.
 void executeBatchMultiple(boolean mustExecuteOnMaster, Results results, List<String> queries)
          Execute list of queries.
 void executeBatchRewrite(boolean mustExecuteOnMaster, Results results, ClientPrepareResult prepareResult, List<ParameterHolder[]> parameterList, boolean rewriteValues)
          Specific execution for batch rewrite that has specific query for memory.
 void executePreparedQuery(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, ParameterHolder[] parameters)
          Execute a query that is already prepared.
 void executeQuery(boolean mustExecuteOnMaster, Results results, ClientPrepareResult clientPrepareResult, ParameterHolder[] parameters)
          Execute a unique clientPrepareQuery.
 void executeQuery(boolean mustExecuteOnMaster, Results results, ClientPrepareResult clientPrepareResult, ParameterHolder[] parameters, int queryTimeout)
          Execute a unique clientPrepareQuery.
 void executeQuery(boolean mustExecuteOnMaster, Results results, String sql)
          Execute query directly to outputStream.
 void executeQuery(boolean mustExecuteOnMaster, Results results, String sql, Charset charset)
           
 void executeQuery(String sql)
          Execute internal query.
 boolean forceReleasePrepareStatement(int statementId)
          Force release of prepare statement that are not used.
 void forceReleaseWaitingPrepareStatement()
          Force release of prepare statement that are not used.
 boolean getAutocommit()
          Get current autocommit status.
 int getAutoIncrementIncrement()
          Get current auto increment increment.
 long getMaxRows()
           
 void getResult(Results results)
           
 int getTimeout()
          Returns the connection timeout in milliseconds.
 int getTransactionIsolationLevel()
           
 SQLException handleIoException(IOException initialException)
          Handle IoException (reconnect if Exception is due to having send too much data, making server close the connection.
 boolean inTransaction()
           
 boolean isInterrupted()
           
 boolean isValid()
           
 boolean ping()
           
 ServerPrepareResult prepare(String sql, boolean executeOnMaster)
          Prepare query on server side.
 ServerPrepareResult prepareAndExecute(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, String sql, ParameterHolder[] parameters)
          Execute Prepare if needed, and execute COM_STMT_EXECUTE queries in batch.
 ServerPrepareResult prepareAndExecutes(boolean mustExecuteOnMaster, ServerPrepareResult serverPrepareResult, Results results, String sql, List<ParameterHolder[]> parametersList)
          Execute Prepare if needed, and execute COM_STMT_EXECUTE queries in batch.
 void prolog(long maxRows, boolean hasProxy, MariaDbConnection connection, MariaDbStatement statement)
          Preparation before command.
 void prologProxy(ServerPrepareResult serverPrepareResult, long maxRows, boolean hasProxy, MariaDbConnection connection, MariaDbStatement statement)
           
 SQLException readErrorPacket(Buffer buffer, Results results)
          Read ERR_Packet.
 void readLocalInfilePacket(Buffer buffer, Results results)
          Read Local_infile Packet.
 void readOkPacket(Buffer buffer, Results results)
          Read OK_Packet.
 void readPacket(Results results)
          Read server response packet.
 void readResultSet(Buffer buffer, Results results)
          Read ResultSet Packet.
 void releasePrepareStatement(ServerPrepareResult serverPrepareResult)
          Deallocate prepare statement if not used anymore.
 void resetStateAfterFailover(long maxRows, int transactionIsolationLevel, String database, boolean autocommit)
          Set current state after a failover.
 void rollback()
          Rollback transaction.
 void setActiveFutureTask(FutureTask activeFutureTask)
           
 void setCatalog(String database)
           
 void setInternalMaxRows(long max)
          Set max row retuen by a statement.
 void setLocalInfileInputStream(InputStream inputStream)
           
 void setMaxRows(long max)
           
 void setTimeout(int timeout)
          Sets the connection timeout.
 void setTransactionIsolation(int level)
          Set transaction isolation.
 void stopIfInterrupted()
          Throw TimeoutException if timeout has been reached.
 
Methods inherited from class org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol
changeSocketSoTimeout, changeSocketTcpNoDelay, checkIfMaster, close, close, connect, connectWithoutProxy, enabledSslCipherSuites, enabledSslProtocolSuites, getActiveStreamingResult, getDatabase, getDataTypeMappingFlags, getHost, getHostAddress, getLock, getMajorServerVersion, getMinorServerVersion, getOptions, getPassword, getPinGlobalTxToPhysicalConnection, getPort, getProxy, getReader, getReadonly, getServerData, getServerThreadId, getServerVersion, getTimeZone, getTraces, getUrlParser, getUsername, getWriter, hasMoreResults, hasWarnings, isClosed, isConnected, isEofDeprecated, isExplicitClosed, isMasterConnection, isServerMariaDb, mustBeMasterConnection, noBackslashEscapes, prepareStatementCache, readEofPacket, readPipelineCheckMaster, removeActiveStreamingResult, removeHasMoreResults, sendPipelineCheckMaster, sessionStateAware, setActiveStreamingResult, setHasWarnings, setHostAddress, setHostFailedWithoutProxy, setProxy, setReadonly, setServerStatus, shouldReconnectWithoutProxy, skip, skipEofPacket, versionGreaterOrEqual
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.mariadb.jdbc.internal.protocol.Protocol
changeSocketSoTimeout, changeSocketTcpNoDelay, checkIfMaster, close, connect, connectWithoutProxy, getActiveStreamingResult, getDatabase, getDataTypeMappingFlags, getHost, getHostAddress, getLock, getMajorServerVersion, getMinorServerVersion, getOptions, getPassword, getPinGlobalTxToPhysicalConnection, getPort, getProxy, getReader, getReadonly, getServerThreadId, getServerVersion, getTimeZone, getTraces, getUrlParser, getUsername, getWriter, hasMoreResults, hasWarnings, isClosed, isConnected, isEofDeprecated, isExplicitClosed, isMasterConnection, isServerMariaDb, mustBeMasterConnection, noBackslashEscapes, prepareStatementCache, readEofPacket, removeActiveStreamingResult, removeHasMoreResults, sessionStateAware, setActiveStreamingResult, setHasWarnings, setHostAddress, setHostFailedWithoutProxy, setProxy, setReadonly, setServerStatus, shouldReconnectWithoutProxy, skip, skipEofPacket, versionGreaterOrEqual
 

Field Detail

readScheduler

public static ThreadPoolExecutor readScheduler
Constructor Detail

AbstractQueryProtocol

public AbstractQueryProtocol(UrlParser urlParser,
                             ReentrantLock lock)
Get a protocol instance.

Parameters:
urlParser - connection URL infos
lock - the lock for thread synchronisation
Method Detail

executeQuery

public void executeQuery(String sql)
                  throws SQLException
Execute internal query.

!! will not support multi values queries !!

Specified by:
executeQuery in interface Protocol
Specified by:
executeQuery in class AbstractConnectProtocol
Parameters:
sql - sql
Throws:
SQLException - in any exception occur

executeQuery

public void executeQuery(boolean mustExecuteOnMaster,
                         Results results,
                         String sql)
                  throws SQLException
Execute query directly to outputStream.

Specified by:
executeQuery in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - result
sql - the query to executeInternal
Throws:
SQLException - exception

executeQuery

public void executeQuery(boolean mustExecuteOnMaster,
                         Results results,
                         String sql,
                         Charset charset)
                  throws SQLException
Specified by:
executeQuery in interface Protocol
Throws:
SQLException

executeQuery

public void executeQuery(boolean mustExecuteOnMaster,
                         Results results,
                         ClientPrepareResult clientPrepareResult,
                         ParameterHolder[] parameters)
                  throws SQLException
Execute a unique clientPrepareQuery.

Specified by:
executeQuery in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - results
clientPrepareResult - clientPrepareResult
parameters - parameters
Throws:
SQLException - exception

executeQuery

public void executeQuery(boolean mustExecuteOnMaster,
                         Results results,
                         ClientPrepareResult clientPrepareResult,
                         ParameterHolder[] parameters,
                         int queryTimeout)
                  throws SQLException
Execute a unique clientPrepareQuery.

Specified by:
executeQuery in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - results
clientPrepareResult - clientPrepareResult
parameters - parameters
queryTimeout - if timeout is set and must use max_statement_time
Throws:
SQLException - exception

executeBatchMulti

public void executeBatchMulti(boolean mustExecuteOnMaster,
                              Results results,
                              ClientPrepareResult clientPrepareResult,
                              List<ParameterHolder[]> parametersList)
                       throws SQLException
Execute clientPrepareQuery batch.

Specified by:
executeBatchMulti in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - results
clientPrepareResult - ClientPrepareResult
parametersList - List of parameters
Throws:
SQLException - exception

executeBatch

public void executeBatch(boolean mustExecuteOnMaster,
                         Results results,
                         List<String> queries)
                  throws SQLException
Execute list of queries not rewritable.

Specified by:
executeBatch in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - result object
queries - list of queries
Throws:
SQLException - exception

prepare

public ServerPrepareResult prepare(String sql,
                                   boolean executeOnMaster)
                            throws SQLException
Prepare query on server side. Will permit to know the parameter number of the query, and permit to send only the data on next results.

For failover, two additional information are in the resultset object : - current connection : Since server maintain a state of this prepare statement, all query will be executed on this particular connection. - executeOnMaster : state of current connection when creating this prepareStatement (if was on master, will only be executed on master. If was on a slave, can be execute temporary on master, but we keep this flag, so when a slave is connected back to relaunch this query on slave)

Specified by:
prepare in interface Protocol
Parameters:
sql - the query
executeOnMaster - state of current connection when creating this prepareStatement
Returns:
a ServerPrepareResult object that contain prepare result information.
Throws:
SQLException - if any error occur on connection.

executeBatchMultiple

public void executeBatchMultiple(boolean mustExecuteOnMaster,
                                 Results results,
                                 List<String> queries)
                          throws SQLException
Execute list of queries. This method is used when using text batch statement and using rewriting (allowMultiQueries || rewriteBatchedStatements). queries will be send to server according to max_allowed_packet size.

Specified by:
executeBatchMultiple in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - result object
queries - list of queries
Throws:
SQLException - exception

executeBatchRewrite

public void executeBatchRewrite(boolean mustExecuteOnMaster,
                                Results results,
                                ClientPrepareResult prepareResult,
                                List<ParameterHolder[]> parameterList,
                                boolean rewriteValues)
                         throws SQLException
Specific execution for batch rewrite that has specific query for memory.

Specified by:
executeBatchRewrite in interface Protocol
Parameters:
mustExecuteOnMaster - was intended to be launched on master connection
results - result
prepareResult - prepareResult
parameterList - parameters
rewriteValues - is rewritable flag
Throws:
SQLException - exception

prepareAndExecutes

public ServerPrepareResult prepareAndExecutes(boolean mustExecuteOnMaster,
                                              ServerPrepareResult serverPrepareResult,
                                              Results results,
                                              String sql,
                                              List<ParameterHolder[]> parametersList)
                                       throws SQLException
Execute Prepare if needed, and execute COM_STMT_EXECUTE queries in batch.

Specified by:
prepareAndExecutes in interface Protocol
Parameters:
mustExecuteOnMaster - must normally be executed on master connection
serverPrepareResult - prepare result. can be null if not prepared.
results - execution results
sql - sql query if needed to be prepared
parametersList - parameter list
Returns:
Prepare result
Throws:
SQLException - if parameter error or connection error occur.

prepareAndExecute

public ServerPrepareResult prepareAndExecute(boolean mustExecuteOnMaster,
                                             ServerPrepareResult serverPrepareResult,
                                             Results results,
                                             String sql,
                                             ParameterHolder[] parameters)
                                      throws SQLException
Execute Prepare if needed, and execute COM_STMT_EXECUTE queries in batch.

Specified by:
prepareAndExecute in interface Protocol
Parameters:
mustExecuteOnMaster - must normally be executed on master connection
serverPrepareResult - prepare result. can be null if not prepared.
results - execution results
sql - sql query if needed to be prepared
parameters - parameters
Returns:
Prepare result
Throws:
SQLException - if parameter error or connection error occur.

executePreparedQuery

public void executePreparedQuery(boolean mustExecuteOnMaster,
                                 ServerPrepareResult serverPrepareResult,
                                 Results results,
                                 ParameterHolder[] parameters)
                          throws SQLException
Execute a query that is already prepared.

Specified by:
executePreparedQuery in interface Protocol
Parameters:
mustExecuteOnMaster - must execute on master
serverPrepareResult - prepare result
results - execution result
parameters - parameters
Throws:
SQLException - exception

rollback

public void rollback()
              throws SQLException
Rollback transaction.

Specified by:
rollback in interface Protocol
Throws:
SQLException

forceReleasePrepareStatement

public boolean forceReleasePrepareStatement(int statementId)
                                     throws SQLException
Force release of prepare statement that are not used. This method will be call when adding a new preparestatement in cache, so the packet can be send to server without problem.

Specified by:
forceReleasePrepareStatement in interface Protocol
Parameters:
statementId - prepared statement Id to remove.
Returns:
true if successfully released
Throws:
SQLException - if connection exception.

forceReleaseWaitingPrepareStatement

public void forceReleaseWaitingPrepareStatement()
                                         throws SQLException
Force release of prepare statement that are not used. This permit to deallocate a statement that cannot be release due to multi-thread use.

Specified by:
forceReleaseWaitingPrepareStatement in interface Protocol
Throws:
SQLException - if connection occur

ping

public boolean ping()
             throws SQLException
Specified by:
ping in interface Protocol
Throws:
SQLException

isValid

public boolean isValid()
                throws SQLException
Specified by:
isValid in interface Protocol
Throws:
SQLException

setCatalog

public void setCatalog(String database)
                throws SQLException
Specified by:
setCatalog in interface Protocol
Throws:
SQLException

cancelCurrentQuery

public void cancelCurrentQuery()
                        throws SQLException,
                               IOException
Cancels the current query - clones the current protocol and executes a query using the new connection.

Specified by:
cancelCurrentQuery in interface Protocol
Throws:
SQLException - never thrown
IOException - if Host is not responding

getAutocommit

public boolean getAutocommit()
Get current autocommit status.

Specified by:
getAutocommit in interface Protocol
Returns:
autocommit status

inTransaction

public boolean inTransaction()
Specified by:
inTransaction in interface Protocol

closeExplicit

public void closeExplicit()
Specified by:
closeExplicit in interface Protocol

releasePrepareStatement

public void releasePrepareStatement(ServerPrepareResult serverPrepareResult)
                             throws SQLException
Deallocate prepare statement if not used anymore.

Specified by:
releasePrepareStatement in interface Protocol
Parameters:
serverPrepareResult - allocation result
Throws:
SQLException - if deallocation failed.

setInternalMaxRows

public void setInternalMaxRows(long max)
Set max row retuen by a statement.

Specified by:
setInternalMaxRows in interface Protocol
Parameters:
max - row number max value

getMaxRows

public long getMaxRows()
Specified by:
getMaxRows in interface Protocol

setMaxRows

public void setMaxRows(long max)
                throws SQLException
Specified by:
setMaxRows in interface Protocol
Throws:
SQLException

setLocalInfileInputStream

public void setLocalInfileInputStream(InputStream inputStream)
Specified by:
setLocalInfileInputStream in interface Protocol

getTimeout

public int getTimeout()
               throws SocketException
Returns the connection timeout in milliseconds.

Specified by:
getTimeout in interface Protocol
Returns:
the connection timeout in milliseconds.
Throws:
SocketException - if there is an error in the underlying protocol, such as a TCP error.

setTimeout

public void setTimeout(int timeout)
                throws SocketException
Sets the connection timeout.

Specified by:
setTimeout in interface Protocol
Parameters:
timeout - the timeout, in milliseconds
Throws:
SocketException - if there is an error in the underlying protocol, such as a TCP error.

setTransactionIsolation

public void setTransactionIsolation(int level)
                             throws SQLException
Set transaction isolation.

Specified by:
setTransactionIsolation in interface Protocol
Parameters:
level - transaction level.
Throws:
SQLException - if transaction level is unknown

getTransactionIsolationLevel

public int getTransactionIsolationLevel()
Specified by:
getTransactionIsolationLevel in interface Protocol

getResult

public void getResult(Results results)
               throws SQLException
Specified by:
getResult in interface Protocol
Throws:
SQLException

readPacket

public void readPacket(Results results)
                throws SQLException
Read server response packet.

Parameters:
results - result object
Throws:
SQLException - if sub-result connection fail
See Also:
server response packets

readOkPacket

public void readOkPacket(Buffer buffer,
                         Results results)
                  throws SQLException
Read OK_Packet.

Parameters:
buffer - current buffer
results - result object
Throws:
SQLException - if sub-result connection fail
See Also:
OK_Packet

getAutoIncrementIncrement

public int getAutoIncrementIncrement()
Get current auto increment increment.

Specified by:
getAutoIncrementIncrement in interface Protocol
Returns:
auto increment increment.

readErrorPacket

public SQLException readErrorPacket(Buffer buffer,
                                    Results results)
Read ERR_Packet.

Parameters:
buffer - current buffer
results - result object
Returns:
SQLException if sub-result connection fail
See Also:
ERR_Packet

readLocalInfilePacket

public void readLocalInfilePacket(Buffer buffer,
                                  Results results)
                           throws SQLException
Read Local_infile Packet.

Parameters:
buffer - current buffer
results - result object
Throws:
SQLException - if sub-result connection fail
See Also:
local_infile packet

readResultSet

public void readResultSet(Buffer buffer,
                          Results results)
                   throws SQLException
Read ResultSet Packet.

Parameters:
buffer - current buffer
results - result object
Throws:
SQLException - if sub-result connection fail
See Also:
resultSet packets

prologProxy

public void prologProxy(ServerPrepareResult serverPrepareResult,
                        long maxRows,
                        boolean hasProxy,
                        MariaDbConnection connection,
                        MariaDbStatement statement)
                 throws SQLException
Specified by:
prologProxy in interface Protocol
Throws:
SQLException

prolog

public void prolog(long maxRows,
                   boolean hasProxy,
                   MariaDbConnection connection,
                   MariaDbStatement statement)
            throws SQLException
Preparation before command.

Specified by:
prolog in interface Protocol
Parameters:
maxRows - query max rows
hasProxy - has proxy
connection - current connection
statement - current statement
Throws:
SQLException - if any error occur.

addPrepareInCache

public ServerPrepareResult addPrepareInCache(String key,
                                             ServerPrepareResult serverPrepareResult)
Specified by:
addPrepareInCache in interface Protocol

resetStateAfterFailover

public void resetStateAfterFailover(long maxRows,
                                    int transactionIsolationLevel,
                                    String database,
                                    boolean autocommit)
                             throws SQLException
Set current state after a failover.

Specified by:
resetStateAfterFailover in interface Protocol
Parameters:
maxRows - current Max rows
transactionIsolationLevel - current transactionIsolationLevel
database - current database
autocommit - current autocommit state
Throws:
SQLException - if any error occur.

handleIoException

public SQLException handleIoException(IOException initialException)
Handle IoException (reconnect if Exception is due to having send too much data, making server close the connection.

There is 3 kind of IOException :

  1. MaxAllowedPacketException : without need of reconnect : thrown when driver don't send packet that would have been too big then error is not a CONNECTION_EXCEPTION
  2. packets size is greater than max_allowed_packet (can be checked with writer.isAllowedCmdLength()). Need to reconnect
  3. unknown IO error throw a CONNECTION_EXCEPTION

Specified by:
handleIoException in interface Protocol
Parameters:
initialException - initial Io error
Returns:
the resulting error to return to client.

setActiveFutureTask

public void setActiveFutureTask(FutureTask activeFutureTask)
Specified by:
setActiveFutureTask in interface Protocol

isInterrupted

public boolean isInterrupted()
Specified by:
isInterrupted in interface Protocol

stopIfInterrupted

public void stopIfInterrupted()
                       throws SQLTimeoutException
Throw TimeoutException if timeout has been reached.

Specified by:
stopIfInterrupted in interface Protocol
Throws:
SQLTimeoutException - to indicate timeout exception.


Copyright © 2017. All rights reserved.