idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
29,400
@ Deprecated public static String unquoteIdentifier ( String string ) { if ( string != null && string . startsWith ( "`" ) && string . endsWith ( "`" ) && string . length ( ) >= 2 ) { return string . substring ( 1 , string . length ( ) - 1 ) . replace ( "``" , "`" ) ; } return string ; }
UnQuote string .
83
4
29,401
public ClientSidePreparedStatement clientPrepareStatement ( final String sql ) throws SQLException { return new ClientSidePreparedStatement ( this , sql , ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY , Statement . RETURN_GENERATED_KEYS ) ; }
Create a new client prepared statement .
69
7
29,402
public ServerSidePreparedStatement serverPrepareStatement ( final String sql ) throws SQLException { return new ServerSidePreparedStatement ( this , sql , ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY , Statement . RETURN_GENERATED_KEYS ) ; }
Create a new server prepared statement .
69
7
29,403
public PreparedStatement prepareStatement ( final String sql ) throws SQLException { return internalPrepareStatement ( sql , ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY , Statement . NO_GENERATED_KEYS ) ; }
creates a new prepared statement .
60
7
29,404
private PreparedStatement internalPrepareStatement ( final String sql , final int resultSetScrollType , final int resultSetConcurrency , final int autoGeneratedKeys ) throws SQLException { if ( sql != null ) { String sqlQuery = Utils . nativeSql ( sql , protocol . noBackslashEscapes ( ) ) ; if ( options . useServerPrepStmts && PREPARABLE_STATEMENT_PATTERN . matcher ( sqlQuery ) . find ( ) ) { //prepare isn't delayed -> if prepare fail, fallback to client preparedStatement? checkConnection ( ) ; try { return new ServerSidePreparedStatement ( this , sqlQuery , resultSetScrollType , resultSetConcurrency , autoGeneratedKeys ) ; } catch ( SQLNonTransientConnectionException e ) { throw e ; } catch ( SQLException e ) { //on some specific case, server cannot prepared data (CONJ-238) //will use clientPreparedStatement } } return new ClientSidePreparedStatement ( this , sqlQuery , resultSetScrollType , resultSetConcurrency , autoGeneratedKeys ) ; } else { throw new SQLException ( "SQL value can not be NULL" ) ; } }
Send ServerPrepareStatement or ClientPrepareStatement depending on SQL query and options If server side and PREPARE can be delayed a facade will be return to have a fallback on client prepareStatement .
261
41
29,405
public void commit ( ) throws SQLException { lock . lock ( ) ; try { if ( protocol . inTransaction ( ) ) { try ( Statement st = createStatement ( ) ) { st . execute ( "COMMIT" ) ; } } } finally { lock . unlock ( ) ; } }
Sends commit to the server .
63
7
29,406
public void setReadOnly ( final boolean readOnly ) throws SQLException { try { logger . debug ( "conn={}({}) - set read-only to value {} {}" , protocol . getServerThreadId ( ) , protocol . isMasterConnection ( ) ? "M" : "S" , readOnly ) ; stateFlag |= ConnectionState . STATE_READ_ONLY ; protocol . setReadonly ( readOnly ) ; } catch ( SQLException e ) { throw ExceptionMapper . getException ( e , this , null , false ) ; } }
Sets whether this connection is read only .
122
9
29,407
public Properties getClientInfo ( ) throws SQLException { checkConnection ( ) ; Properties properties = new Properties ( ) ; try ( Statement statement = createStatement ( ) ) { try ( ResultSet rs = statement . executeQuery ( "SELECT @ApplicationName, @ClientUser, @ClientHostname" ) ) { if ( rs . next ( ) ) { if ( rs . getString ( 1 ) != null ) { properties . setProperty ( "ApplicationName" , rs . getString ( 1 ) ) ; } if ( rs . getString ( 2 ) != null ) { properties . setProperty ( "ClientUser" , rs . getString ( 2 ) ) ; } if ( rs . getString ( 3 ) != null ) { properties . setProperty ( "ClientHostname" , rs . getString ( 3 ) ) ; } return properties ; } } } properties . setProperty ( "ApplicationName" , null ) ; properties . setProperty ( "ClientUser" , null ) ; properties . setProperty ( "ClientHostname" , null ) ; return properties ; }
Returns a list containing the name and current value of each client info property supported by the driver . The value of a client info property may be null if the property has not been set and does not have a default value .
225
44
29,408
public void setNetworkTimeout ( Executor executor , final int milliseconds ) throws SQLException { if ( this . isClosed ( ) ) { throw ExceptionMapper . getSqlException ( "Connection.setNetworkTimeout cannot be called on a closed connection" ) ; } if ( milliseconds < 0 ) { throw ExceptionMapper . getSqlException ( "Connection.setNetworkTimeout cannot be called with a negative timeout" ) ; } SQLPermission sqlPermission = new SQLPermission ( "setNetworkTimeout" ) ; SecurityManager securityManager = System . getSecurityManager ( ) ; if ( securityManager != null ) { securityManager . checkPermission ( sqlPermission ) ; } try { stateFlag |= ConnectionState . STATE_NETWORK_TIMEOUT ; protocol . setTimeout ( milliseconds ) ; } catch ( SocketException se ) { throw ExceptionMapper . getSqlException ( "Cannot set the network timeout" , se ) ; } }
Change network timeout .
203
4
29,409
public void reset ( ) throws SQLException { boolean useComReset = options . useResetConnection && ( ( protocol . isServerMariaDb ( ) && protocol . versionGreaterOrEqual ( 10 , 2 , 4 ) ) || ( ! protocol . isServerMariaDb ( ) && protocol . versionGreaterOrEqual ( 5 , 7 , 3 ) ) ) ; if ( useComReset ) { protocol . reset ( ) ; } if ( stateFlag != 0 ) { try { if ( ( stateFlag & ConnectionState . STATE_NETWORK_TIMEOUT ) != 0 ) { setNetworkTimeout ( null , options . socketTimeout ) ; } if ( ( stateFlag & ConnectionState . STATE_AUTOCOMMIT ) != 0 ) { setAutoCommit ( options . autocommit ) ; } if ( ( stateFlag & ConnectionState . STATE_DATABASE ) != 0 ) { protocol . resetDatabase ( ) ; } if ( ( stateFlag & ConnectionState . STATE_READ_ONLY ) != 0 ) { setReadOnly ( false ) ; //default to master connection } //COM_RESET_CONNECTION reset transaction isolation if ( ! useComReset && ( stateFlag & ConnectionState . STATE_TRANSACTION_ISOLATION ) != 0 ) { setTransactionIsolation ( defaultTransactionIsolation ) ; } stateFlag = 0 ; } catch ( SQLException sqle ) { throw ExceptionMapper . getSqlException ( "error resetting connection" ) ; } } warningsCleared = true ; }
Reset connection set has it was after creating a fresh new connection . defaultTransactionIsolation must have been initialized .
331
23
29,410
public int getIndex ( String name ) throws SQLException { if ( name == null ) { throw new SQLException ( "Column name cannot be null" ) ; } String lowerName = name . toLowerCase ( Locale . ROOT ) ; // The specs in JDBC 4.0 specify that ResultSet.findColumn and // ResultSet.getXXX(String name) should use column alias (AS in the query). If label is not found, we use // original table name. if ( aliasMap == null ) { aliasMap = new HashMap <> ( ) ; int counter = 0 ; for ( ColumnInformation ci : columnInfo ) { String columnAlias = ci . getName ( ) ; if ( columnAlias != null ) { columnAlias = columnAlias . toLowerCase ( Locale . ROOT ) ; aliasMap . putIfAbsent ( columnAlias , counter ) ; String tableName = ci . getTable ( ) ; if ( tableName != null ) { aliasMap . putIfAbsent ( tableName . toLowerCase ( Locale . ROOT ) + "." + columnAlias , counter ) ; } } counter ++ ; } } Integer res = aliasMap . get ( lowerName ) ; if ( res != null ) { return res ; } if ( originalMap == null ) { originalMap = new HashMap <> ( ) ; int counter = 0 ; for ( ColumnInformation ci : columnInfo ) { String columnRealName = ci . getOriginalName ( ) ; if ( columnRealName != null ) { columnRealName = columnRealName . toLowerCase ( Locale . ROOT ) ; originalMap . putIfAbsent ( columnRealName , counter ) ; String tableName = ci . getOriginalTable ( ) ; if ( tableName != null ) { originalMap . putIfAbsent ( tableName . toLowerCase ( Locale . ROOT ) + "." + columnRealName , counter ) ; } } counter ++ ; } } res = originalMap . get ( lowerName ) ; if ( res == null ) { throw ExceptionMapper . get ( "No such column: " + name , "42S22" , 1054 , null , false ) ; } return res ; }
Get column index by name .
477
6
29,411
public long getPrecision ( ) { switch ( type ) { case OLDDECIMAL : case DECIMAL : //DECIMAL and OLDDECIMAL are "exact" fixed-point number. //so : // - if can be signed, 1 byte is saved for sign // - if decimal > 0, one byte more for dot if ( isSigned ( ) ) { return length - ( ( decimals > 0 ) ? 2 : 1 ) ; } else { return length - ( ( decimals > 0 ) ? 1 : 0 ) ; } default : return length ; } }
Return metadata precision .
127
4
29,412
public int getDisplaySize ( ) { int vtype = type . getSqlType ( ) ; if ( vtype == Types . VARCHAR || vtype == Types . CHAR ) { int maxWidth = maxCharlen [ charsetNumber & 0xff ] ; if ( maxWidth == 0 ) { maxWidth = 1 ; } return ( int ) length / maxWidth ; } return ( int ) length ; }
Get column size .
87
4
29,413
public void addStats ( long updateCount , long insertId , boolean moreResultAvailable ) { if ( cmdInformation == null ) { if ( batch ) { cmdInformation = new CmdInformationBatch ( expectedSize , autoIncrement ) ; } else if ( moreResultAvailable ) { cmdInformation = new CmdInformationMultiple ( expectedSize , autoIncrement ) ; } else { cmdInformation = new CmdInformationSingle ( insertId , updateCount , autoIncrement ) ; return ; } } cmdInformation . addSuccessStat ( updateCount , insertId ) ; }
Add execution statistics .
118
4
29,414
public void addStatsError ( boolean moreResultAvailable ) { if ( cmdInformation == null ) { if ( batch ) { cmdInformation = new CmdInformationBatch ( expectedSize , autoIncrement ) ; } else if ( moreResultAvailable ) { cmdInformation = new CmdInformationMultiple ( expectedSize , autoIncrement ) ; } else { cmdInformation = new CmdInformationSingle ( 0 , Statement . EXECUTE_FAILED , autoIncrement ) ; return ; } } cmdInformation . addErrorStat ( ) ; }
Indicate that result is an Error to set appropriate results .
112
12
29,415
public void addResultSet ( SelectResultSet resultSet , boolean moreResultAvailable ) { if ( resultSet . isCallableResult ( ) ) { callableResultSet = resultSet ; return ; } if ( executionResults == null ) { executionResults = new ArrayDeque <> ( ) ; } executionResults . add ( resultSet ) ; if ( cmdInformation == null ) { if ( batch ) { cmdInformation = new CmdInformationBatch ( expectedSize , autoIncrement ) ; } else if ( moreResultAvailable ) { cmdInformation = new CmdInformationMultiple ( expectedSize , autoIncrement ) ; } else { cmdInformation = new CmdInformationSingle ( 0 , - 1 , autoIncrement ) ; return ; } } cmdInformation . addResultSetStat ( ) ; }
Add resultSet to results .
166
6
29,416
public boolean isFullyLoaded ( Protocol protocol ) { if ( fetchSize == 0 || resultSet == null ) { return true ; } return resultSet . isFullyLoaded ( ) && executionResults . isEmpty ( ) && ! protocol . hasMoreResults ( ) ; }
Indicate if result contain result - set that is still streaming from server .
59
15
29,417
public boolean getMoreResults ( final int current , Protocol protocol ) throws SQLException { if ( fetchSize != 0 && resultSet != null ) { protocol . getLock ( ) . lock ( ) ; try { //load current resultSet if ( current == Statement . CLOSE_CURRENT_RESULT && resultSet != null ) { resultSet . close ( ) ; } else { resultSet . fetchRemaining ( ) ; } //load next data if there is if ( protocol . hasMoreResults ( ) ) { protocol . getResult ( this ) ; } } catch ( SQLException e ) { ExceptionMapper . throwException ( e , null , statement ) ; } finally { protocol . getLock ( ) . unlock ( ) ; } } if ( cmdInformation . moreResults ( ) && ! batch ) { if ( current == Statement . CLOSE_CURRENT_RESULT && resultSet != null ) { resultSet . close ( ) ; } if ( executionResults != null ) { resultSet = executionResults . poll ( ) ; } return resultSet != null ; } else { if ( current == Statement . CLOSE_CURRENT_RESULT && resultSet != null ) { resultSet . close ( ) ; } resultSet = null ; return false ; } }
Position to next resultSet .
268
6
29,418
public String getDatabaseName ( ) { if ( database != null ) { return database ; } return ( urlParser != null && urlParser . getDatabase ( ) != null ) ? urlParser . getDatabase ( ) : "" ; }
Gets the name of the database .
48
8
29,419
public String getUser ( ) { if ( user != null ) { return user ; } return urlParser != null ? urlParser . getUsername ( ) : null ; }
Gets the username .
36
5
29,420
public int getPort ( ) { if ( port != null && port != 0 ) { return port ; } return urlParser != null ? urlParser . getHostAddresses ( ) . get ( 0 ) . port : 3306 ; }
Returns the port number .
49
5
29,421
public String getServerName ( ) { if ( hostname != null ) { return hostname ; } boolean hasHost = urlParser != null && this . urlParser . getHostAddresses ( ) . get ( 0 ) . host != null ; return ( hasHost ) ? this . urlParser . getHostAddresses ( ) . get ( 0 ) . host : "localhost" ; }
Returns the name of the database server .
81
8
29,422
public static void send ( final PacketOutputStream pos , final String database ) throws IOException { pos . startPacket ( 0 ) ; pos . write ( Packet . COM_INIT_DB ) ; pos . write ( database . getBytes ( "UTF-8" ) ) ; pos . flush ( ) ; }
Send a COM_INIT_DB request to specify the default schema for the connection .
68
18
29,423
public static GssapiAuth getAuthenticationMethod ( ) { try { //Waffle-jna has jna as dependency, so if not available on classpath, just use standard authentication if ( Platform . isWindows ( ) ) { try { Class . forName ( "waffle.windows.auth.impl.WindowsAuthProviderImpl" ) ; return new WindowsNativeSspiAuthentication ( ) ; } catch ( ClassNotFoundException cle ) { //waffle not in the classpath } } } catch ( Throwable cle ) { //jna jar's are not in classpath } return new StandardGssapiAuthentication ( ) ; }
Get authentication method according to classpath . Windows native authentication is using Waffle - jna .
136
19
29,424
public void writeTo ( final PacketOutputStream pos ) throws IOException { pos . write ( BINARY_INTRODUCER ) ; if ( length == Long . MAX_VALUE ) { pos . write ( is , true , noBackslashEscapes ) ; } else { pos . write ( is , length , true , noBackslashEscapes ) ; } pos . write ( QUOTE ) ; }
Write stream in text format .
89
6
29,425
public void writeTo ( final PacketOutputStream pos ) throws IOException { pos . write ( BINARY_INTRODUCER ) ; pos . writeBytesEscaped ( bytes , bytes . length , noBackslashEscapes ) ; pos . write ( QUOTE ) ; }
Write data to socket in text format .
61
8
29,426
@ SuppressWarnings ( "unchecked" ) public static void init ( boolean mustLog ) { if ( ( hasToLog == null || hasToLog != mustLog ) && mustLog ) { synchronized ( LoggerFactory . class ) { if ( hasToLog == null || hasToLog != mustLog ) { try { Class . forName ( "org.slf4j.LoggerFactory" ) ; hasToLog = Boolean . TRUE ; } catch ( ClassNotFoundException classNotFound ) { System . out . println ( "Logging cannot be activated, missing slf4j dependency" ) ; hasToLog = Boolean . FALSE ; } } } } }
Initialize factory .
144
4
29,427
public static Logger getLogger ( Class < ? > clazz ) { if ( hasToLog != null && hasToLog ) { return new Slf4JLogger ( org . slf4j . LoggerFactory . getLogger ( clazz ) ) ; } else { return NO_LOGGER ; } }
Initialize logger .
69
4
29,428
public static Socket standardSocket ( UrlParser urlParser , String host ) throws IOException { SocketFactory socketFactory ; String socketFactoryName = urlParser . getOptions ( ) . socketFactory ; if ( socketFactoryName != null ) { try { @ SuppressWarnings ( "unchecked" ) Class < ? extends SocketFactory > socketFactoryClass = ( Class < ? extends SocketFactory > ) Class . forName ( socketFactoryName ) ; if ( socketFactoryClass != null ) { Constructor < ? extends SocketFactory > constructor = socketFactoryClass . getConstructor ( ) ; socketFactory = constructor . newInstance ( ) ; return socketFactory . createSocket ( ) ; } } catch ( Exception exp ) { throw new IOException ( "Socket factory failed to initialized with option \"socketFactory\" set to \"" + urlParser . getOptions ( ) . socketFactory + "\"" , exp ) ; } } socketFactory = SocketFactory . getDefault ( ) ; return socketFactory . createSocket ( ) ; }
Use standard socket implementation .
212
5
29,429
public static String escapeString ( String value , boolean noBackslashEscapes ) { if ( ! value . contains ( "'" ) ) { if ( noBackslashEscapes ) { return value ; } if ( ! value . contains ( "\\" ) ) { return value ; } } String escaped = value . replace ( "'" , "''" ) ; if ( noBackslashEscapes ) { return escaped ; } return escaped . replace ( "\\" , "\\\\" ) ; }
Escape String .
106
4
29,430
public static byte [ ] encryptPassword ( final String password , final byte [ ] seed , String passwordCharacterEncoding ) throws NoSuchAlgorithmException , UnsupportedEncodingException { if ( password == null || password . isEmpty ( ) ) { return new byte [ 0 ] ; } final MessageDigest messageDigest = MessageDigest . getInstance ( "SHA-1" ) ; byte [ ] bytePwd ; if ( passwordCharacterEncoding != null && ! passwordCharacterEncoding . isEmpty ( ) ) { bytePwd = password . getBytes ( passwordCharacterEncoding ) ; } else { bytePwd = password . getBytes ( ) ; } final byte [ ] stage1 = messageDigest . digest ( bytePwd ) ; messageDigest . reset ( ) ; final byte [ ] stage2 = messageDigest . digest ( stage1 ) ; messageDigest . reset ( ) ; messageDigest . update ( seed ) ; messageDigest . update ( stage2 ) ; final byte [ ] digest = messageDigest . digest ( ) ; final byte [ ] returnBytes = new byte [ digest . length ] ; for ( int i = 0 ; i < digest . length ; i ++ ) { returnBytes [ i ] = ( byte ) ( stage1 [ i ] ^ digest [ i ] ) ; } return returnBytes ; }
Encrypts a password .
283
6
29,431
public static byte [ ] copyWithLength ( byte [ ] orig , int length ) { // No need to initialize with zero bytes, because the bytes are already initialized with that byte [ ] result = new byte [ length ] ; int howMuchToCopy = length < orig . length ? length : orig . length ; System . arraycopy ( orig , 0 , result , 0 , howMuchToCopy ) ; return result ; }
Copies the original byte array content to a new byte array . The resulting byte array is always length size . If length is smaller than the original byte array the resulting byte array is truncated . If length is bigger than the original byte array the resulting byte array is filled with zero bytes .
87
58
29,432
public static byte [ ] copyRange ( byte [ ] orig , int from , int to ) { int length = to - from ; byte [ ] result = new byte [ length ] ; int howMuchToCopy = orig . length - from < length ? orig . length - from : length ; System . arraycopy ( orig , from , result , 0 , howMuchToCopy ) ; return result ; }
Copies from original byte array to a new byte array . The resulting byte array is always to - from size .
83
23
29,433
public static Protocol retrieveProxy ( final UrlParser urlParser , final GlobalStateInfo globalInfo ) throws SQLException { final ReentrantLock lock = new ReentrantLock ( ) ; Protocol protocol ; switch ( urlParser . getHaMode ( ) ) { case AURORA : return getProxyLoggingIfNeeded ( urlParser , ( Protocol ) Proxy . newProxyInstance ( AuroraProtocol . class . getClassLoader ( ) , new Class [ ] { Protocol . class } , new FailoverProxy ( new AuroraListener ( urlParser , globalInfo ) , lock ) ) ) ; case REPLICATION : return getProxyLoggingIfNeeded ( urlParser , ( Protocol ) Proxy . newProxyInstance ( MastersSlavesProtocol . class . getClassLoader ( ) , new Class [ ] { Protocol . class } , new FailoverProxy ( new MastersSlavesListener ( urlParser , globalInfo ) , lock ) ) ) ; case FAILOVER : case SEQUENTIAL : return getProxyLoggingIfNeeded ( urlParser , ( Protocol ) Proxy . newProxyInstance ( MasterProtocol . class . getClassLoader ( ) , new Class [ ] { Protocol . class } , new FailoverProxy ( new MastersFailoverListener ( urlParser , globalInfo ) , lock ) ) ) ; default : protocol = getProxyLoggingIfNeeded ( urlParser , new MasterProtocol ( urlParser , globalInfo , lock ) ) ; protocol . connectWithoutProxy ( ) ; return protocol ; } }
Retrieve protocol corresponding to the failover options . if no failover option protocol will not be proxied . if a failover option is precised protocol will be proxied so that any connection error will be handle directly .
319
45
29,434
public static Socket createSocket ( UrlParser urlParser , String host ) throws IOException { return socketHandler . apply ( urlParser , host ) ; }
Create socket accordingly to options .
32
6
29,435
public static String parseSessionVariables ( String sessionVariable ) { StringBuilder out = new StringBuilder ( ) ; StringBuilder sb = new StringBuilder ( ) ; Parse state = Parse . Normal ; boolean iskey = true ; boolean singleQuotes = true ; boolean first = true ; String key = null ; char [ ] chars = sessionVariable . toCharArray ( ) ; for ( char car : chars ) { if ( state == Parse . Escape ) { sb . append ( car ) ; state = singleQuotes ? Parse . Quote : Parse . String ; continue ; } switch ( car ) { case ' ' : if ( state == Parse . Normal ) { state = Parse . String ; singleQuotes = false ; } else if ( state == Parse . String && ! singleQuotes ) { state = Parse . Normal ; } break ; case ' ' : if ( state == Parse . Normal ) { state = Parse . String ; singleQuotes = true ; } else if ( state == Parse . String && singleQuotes ) { state = Parse . Normal ; } break ; case ' ' : if ( state == Parse . String ) { state = Parse . Escape ; } break ; case ' ' : case ' ' : if ( state == Parse . Normal ) { if ( ! iskey ) { if ( ! first ) { out . append ( "," ) ; } out . append ( key ) ; out . append ( sb . toString ( ) ) ; first = false ; } else { key = sb . toString ( ) . trim ( ) ; if ( ! key . isEmpty ( ) ) { if ( ! first ) { out . append ( "," ) ; } out . append ( key ) ; first = false ; } } iskey = true ; key = null ; sb = new StringBuilder ( ) ; continue ; } break ; case ' ' : if ( state == Parse . Normal && iskey ) { key = sb . toString ( ) . trim ( ) ; iskey = false ; sb = new StringBuilder ( ) ; } break ; default : //nothing } sb . append ( car ) ; } if ( ! iskey ) { if ( ! first ) { out . append ( "," ) ; } out . append ( key ) ; out . append ( sb . toString ( ) ) ; } else { String tmpkey = sb . toString ( ) . trim ( ) ; if ( ! tmpkey . isEmpty ( ) && ! first ) { out . append ( "," ) ; } out . append ( tmpkey ) ; } return out . toString ( ) ; }
Parse the option sessionVariable to ensure having no injection . semi - column not in string will be replaced by comma .
563
24
29,436
public static int transactionFromString ( String txIsolation ) throws SQLException { switch ( txIsolation ) { //tx_isolation case "READ-UNCOMMITTED" : return Connection . TRANSACTION_READ_UNCOMMITTED ; case "READ-COMMITTED" : return Connection . TRANSACTION_READ_COMMITTED ; case "REPEATABLE-READ" : return Connection . TRANSACTION_REPEATABLE_READ ; case "SERIALIZABLE" : return Connection . TRANSACTION_SERIALIZABLE ; default : throw new SQLException ( "unknown transaction isolation level" ) ; } }
Traduce a String value of transaction isolation to corresponding java value .
139
14
29,437
private void validAllParameters ( ) throws SQLException { setInputOutputParameterMap ( ) ; //Set value for OUT parameters for ( int index = 0 ; index < params . size ( ) ; index ++ ) { if ( ! params . get ( index ) . isInput ( ) ) { super . setParameter ( index + 1 , new NullParameter ( ) ) ; } } validParameters ( ) ; }
Valid that all parameters are set .
86
7
29,438
public static int equal ( int b , int c ) { int result = 0 ; int xor = b ^ c ; for ( int i = 0 ; i < 8 ; i ++ ) { result |= xor >> i ; } return ( result ^ 0x01 ) & 0x01 ; }
Constant - time byte comparison .
63
7
29,439
public static String bytesToHex ( byte [ ] raw ) { if ( raw == null ) { return null ; } final StringBuilder hex = new StringBuilder ( 2 * raw . length ) ; for ( final byte b : raw ) { hex . append ( Character . forDigit ( ( b & 0xF0 ) >> 4 , 16 ) ) . append ( Character . forDigit ( ( b & 0x0F ) , 16 ) ) ; } return hex . toString ( ) ; }
Converts bytes to a hex string .
106
8
29,440
private HostAddress findClusterHostAddress ( UrlParser urlParser ) throws SQLException { List < HostAddress > hostAddresses = urlParser . getHostAddresses ( ) ; Matcher matcher ; for ( HostAddress hostAddress : hostAddresses ) { matcher = auroraDnsPattern . matcher ( hostAddress . host ) ; if ( matcher . find ( ) ) { if ( clusterDnsSuffix != null ) { //ensure there is only one cluster if ( ! clusterDnsSuffix . equalsIgnoreCase ( matcher . group ( 3 ) ) ) { throw new SQLException ( "Connection string must contain only one aurora cluster. " + "'" + hostAddress . host + "' doesn't correspond to DNS prefix '" + clusterDnsSuffix + "'" ) ; } } else { clusterDnsSuffix = matcher . group ( 3 ) ; } if ( matcher . group ( 2 ) != null && ! matcher . group ( 2 ) . isEmpty ( ) ) { //not just an instance entry-point, but cluster entrypoint. return hostAddress ; } } else { if ( clusterDnsSuffix == null && hostAddress . host . contains ( "." ) && ! Utils . isIPv4 ( hostAddress . host ) && ! Utils . isIPv6 ( hostAddress . host ) ) { clusterDnsSuffix = hostAddress . host . substring ( hostAddress . host . indexOf ( "." ) + 1 ) ; } } } return null ; }
Retrieves the cluster host address from the UrlParser instance .
338
14
29,441
public void retrieveAllEndpointsAndSet ( Protocol protocol ) throws SQLException { // For a given cluster, same port for all endpoints and same end host address if ( clusterDnsSuffix != null ) { List < String > endpoints = getCurrentEndpointIdentifiers ( protocol ) ; setUrlParserFromEndpoints ( endpoints , protocol . getPort ( ) ) ; } }
Retrieves the information necessary to add a new endpoint . Calls the methods that retrieves the instance identifiers and sets urlParser accordingly .
84
27
29,442
private List < String > getCurrentEndpointIdentifiers ( Protocol protocol ) throws SQLException { List < String > endpoints = new ArrayList <> ( ) ; try { proxy . lock . lock ( ) ; try { // Deleted instance may remain in db for 24 hours so ignoring instances that have had no change // for 3 minutes Results results = new Results ( ) ; protocol . executeQuery ( false , results , "select server_id, session_id from information_schema.replica_host_status " + "where last_update_timestamp > now() - INTERVAL 3 MINUTE" ) ; results . commandEnd ( ) ; ResultSet resultSet = results . getResultSet ( ) ; while ( resultSet . next ( ) ) { endpoints . add ( resultSet . getString ( 1 ) + "." + clusterDnsSuffix ) ; } //randomize order for distributed load-balancing Collections . shuffle ( endpoints ) ; } finally { proxy . lock . unlock ( ) ; } } catch ( SQLException qe ) { logger . warning ( "SQL exception occurred: " + qe . getMessage ( ) ) ; if ( protocol . getProxy ( ) . hasToHandleFailover ( qe ) ) { if ( masterProtocol == null || masterProtocol . equals ( protocol ) ) { setMasterHostFail ( ) ; } else if ( secondaryProtocol . equals ( protocol ) ) { setSecondaryHostFail ( ) ; } addToBlacklist ( protocol . getHostAddress ( ) ) ; reconnectFailedConnection ( new SearchFilter ( isMasterHostFail ( ) , isSecondaryHostFail ( ) ) ) ; } } return endpoints ; }
Retrieves all endpoints of a cluster from the appropriate database table .
363
15
29,443
private void setUrlParserFromEndpoints ( List < String > endpoints , int port ) { List < HostAddress > addresses = new ArrayList <> ( ) ; for ( String endpoint : endpoints ) { HostAddress newHostAddress = new HostAddress ( endpoint , port , null ) ; addresses . add ( newHostAddress ) ; } synchronized ( urlParser ) { urlParser . setHostAddresses ( addresses ) ; } }
Sets urlParser accordingly to discovered hosts .
90
9
29,444
public static org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement p2 ( final Curve curve , final FieldElement X , final FieldElement Y , final FieldElement Z ) { return new org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement ( curve , Representation . P2 , X , Y , Z , null ) ; }
Creates a new group element in P2 representation .
100
11
29,445
public static org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement p1p1 ( final Curve curve , final FieldElement X , final FieldElement Y , final FieldElement Z , final FieldElement T ) { return new org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement ( curve , Representation . P1P1 , X , Y , Z , T ) ; }
Creates a new group element in P1P1 representation .
109
13
29,446
public static org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement precomp ( final Curve curve , final FieldElement ypx , final FieldElement ymx , final FieldElement xy2d ) { return new org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement ( curve , Representation . PRECOMP , ypx , ymx , xy2d , null ) ; }
Creates a new group element in PRECOMP representation .
111
12
29,447
public static org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement cached ( final Curve curve , final FieldElement YpX , final FieldElement YmX , final FieldElement Z , final FieldElement T2d ) { return new org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement ( curve , Representation . CACHED , YpX , YmX , Z , T2d ) ; }
Creates a new group element in CACHED representation .
117
12
29,448
public byte [ ] toByteArray ( ) { switch ( this . repr ) { case P2 : case P3 : FieldElement recip = Z . invert ( ) ; FieldElement x = X . multiply ( recip ) ; FieldElement y = Y . multiply ( recip ) ; byte [ ] s = y . toByteArray ( ) ; s [ s . length - 1 ] |= ( x . isNegative ( ) ? ( byte ) 0x80 : 0 ) ; return s ; default : return toP2 ( ) . toByteArray ( ) ; } }
Converts the group element to an encoded point on the curve .
120
13
29,449
public org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement toP2 ( ) { return toRep ( Representation . P2 ) ; }
Converts the group element to the P2 representation .
46
11
29,450
public org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement toP3 ( ) { return toRep ( Representation . P3 ) ; }
Converts the group element to the P3 representation .
46
11
29,451
public org . mariadb . jdbc . internal . com . send . authentication . ed25519 . math . GroupElement toCached ( ) { return toRep ( Representation . CACHED ) ; }
Converts the group element to the CACHED representation .
47
12
29,452
public boolean isOnCurve ( Curve curve ) { switch ( repr ) { case P2 : case P3 : FieldElement recip = Z . invert ( ) ; FieldElement x = X . multiply ( recip ) ; FieldElement y = Y . multiply ( recip ) ; FieldElement xx = x . square ( ) ; FieldElement yy = y . square ( ) ; FieldElement dxxyy = curve . getD ( ) . multiply ( xx ) . multiply ( yy ) ; return curve . getField ( ) . ONE . add ( dxxyy ) . add ( xx ) . equals ( yy ) ; default : return toP2 ( ) . isOnCurve ( curve ) ; } }
Verify that a point is on the curve .
149
10
29,453
public String getSubString ( long pos , int length ) throws SQLException { if ( pos < 1 ) { throw ExceptionMapper . getSqlException ( "position must be >= 1" ) ; } if ( length < 0 ) { throw ExceptionMapper . getSqlException ( "length must be > 0" ) ; } try { String val = toString ( ) ; return val . substring ( ( int ) pos - 1 , Math . min ( ( int ) pos - 1 + length , val . length ( ) ) ) ; } catch ( Exception e ) { throw new SQLException ( e ) ; } }
Get sub string .
135
4
29,454
public Reader getCharacterStream ( long pos , long length ) throws SQLException { String val = toString ( ) ; if ( val . length ( ) < ( int ) pos - 1 + length ) { throw ExceptionMapper . getSqlException ( "pos + length is greater than the number of characters in the Clob" ) ; } String sub = val . substring ( ( int ) pos - 1 , ( int ) pos - 1 + ( int ) length ) ; return new StringReader ( sub ) ; }
Returns a Reader object that contains a partial Clob value starting with the character specified by pos which is length characters in length .
110
25
29,455
public Writer setCharacterStream ( long pos ) throws SQLException { int bytePosition = utf8Position ( ( int ) pos - 1 ) ; OutputStream stream = setBinaryStream ( bytePosition + 1 ) ; return new OutputStreamWriter ( stream , StandardCharsets . UTF_8 ) ; }
Set character stream .
66
4
29,456
private int utf8Position ( int charPosition ) { int pos = offset ; for ( int i = 0 ; i < charPosition ; i ++ ) { int byteValue = data [ pos ] & 0xff ; if ( byteValue < 0x80 ) { pos += 1 ; } else if ( byteValue < 0xC2 ) { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } else if ( byteValue < 0xE0 ) { pos += 2 ; } else if ( byteValue < 0xF0 ) { pos += 3 ; } else if ( byteValue < 0xF8 ) { pos += 4 ; } else { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } } return pos ; }
Convert character position into byte position in UTF8 byte array .
178
13
29,457
public int setString ( long pos , String str ) throws SQLException { int bytePosition = utf8Position ( ( int ) pos - 1 ) ; super . setBytes ( bytePosition + 1 - offset , str . getBytes ( StandardCharsets . UTF_8 ) ) ; return str . length ( ) ; }
Set String .
70
3
29,458
@ Override public long length ( ) { //The length of a character string is the number of UTF-16 units (not the number of characters) long len = 0 ; int pos = offset ; //set ASCII (<= 127 chars) for ( ; len < length && data [ pos ] >= 0 ; ) { len ++ ; pos ++ ; } //multi-bytes UTF-8 while ( pos < offset + length ) { byte firstByte = data [ pos ++ ] ; if ( firstByte < 0 ) { if ( firstByte >> 5 != - 2 || ( firstByte & 30 ) == 0 ) { if ( firstByte >> 4 == - 2 ) { if ( pos + 1 < offset + length ) { pos += 2 ; len ++ ; } else { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } } else if ( firstByte >> 3 != - 2 ) { throw new UncheckedIOException ( "invalid UTF8" , new CharacterCodingException ( ) ) ; } else if ( pos + 2 < offset + length ) { pos += 3 ; len += 2 ; } else { //bad truncated UTF8 pos += offset + length ; len += 1 ; } } else { pos ++ ; len ++ ; } } else { len ++ ; } } return len ; }
Return character length of the Clob . Assume UTF8 encoding .
281
14
29,459
private ArrayList < String > searchAccurateAliases ( String [ ] keyTypes , Principal [ ] issuers ) { if ( keyTypes == null || keyTypes . length == 0 ) { return null ; } ArrayList < String > accurateAliases = new ArrayList <> ( ) ; for ( Map . Entry < String , KeyStore . PrivateKeyEntry > mapEntry : privateKeyHash . entrySet ( ) ) { Certificate [ ] certs = mapEntry . getValue ( ) . getCertificateChain ( ) ; String alg = certs [ 0 ] . getPublicKey ( ) . getAlgorithm ( ) ; for ( String keyType : keyTypes ) { if ( alg . equals ( keyType ) ) { if ( issuers != null && issuers . length != 0 ) { checkLoop : for ( Certificate cert : certs ) { if ( cert instanceof X509Certificate ) { X500Principal certificateIssuer = ( ( X509Certificate ) cert ) . getIssuerX500Principal ( ) ; for ( Principal issuer : issuers ) { if ( certificateIssuer . equals ( issuer ) ) { accurateAliases . add ( mapEntry . getKey ( ) ) ; break checkLoop ; } } } } } else { accurateAliases . add ( mapEntry . getKey ( ) ) ; } } } } return accurateAliases ; }
Search aliases corresponding to algorithms and issuers .
289
9
29,460
@ SuppressWarnings ( "unchecked" ) public static SocketHandlerFunction getSocketHandler ( ) { try { //forcing use of JNA to ensure AOT compilation Platform . getOSType ( ) ; return ( urlParser , host ) -> { if ( urlParser . getOptions ( ) . pipe != null ) { return new NamedPipeSocket ( host , urlParser . getOptions ( ) . pipe ) ; } else if ( urlParser . getOptions ( ) . localSocket != null ) { try { return new UnixDomainSocket ( urlParser . getOptions ( ) . localSocket ) ; } catch ( RuntimeException re ) { throw new IOException ( re . getMessage ( ) , re . getCause ( ) ) ; } } else if ( urlParser . getOptions ( ) . sharedMemory != null ) { try { return new SharedMemorySocket ( urlParser . getOptions ( ) . sharedMemory ) ; } catch ( RuntimeException re ) { throw new IOException ( re . getMessage ( ) , re . getCause ( ) ) ; } } else { return Utils . standardSocket ( urlParser , host ) ; } } ; } catch ( Throwable cle ) { //jna jar's are not in classpath } return ( urlParser , host ) -> Utils . standardSocket ( urlParser , host ) ; }
Create socket according to options . In case of compilation ahead of time will throw an error if dependencies found then use default socket implementation .
281
26
29,461
public void blockTillTerminated ( ) { while ( ! runState . compareAndSet ( State . IDLE , State . REMOVED ) ) { // wait and retry LockSupport . parkNanos ( TimeUnit . MILLISECONDS . toNanos ( 10 ) ) ; if ( Thread . currentThread ( ) . isInterrupted ( ) ) { runState . set ( State . REMOVED ) ; return ; } } }
Unschedule next launched and wait for the current task to complete before closing it .
95
17
29,462
public void unscheduleTask ( ) { if ( unschedule . compareAndSet ( false , true ) ) { scheduledFuture . cancel ( false ) ; scheduledFuture = null ; } }
Unschedule task if active and cancel thread to inform it must be interrupted in a proper way .
40
20
29,463
public ResultSet getGeneratedKeys ( Protocol protocol ) { if ( insertId == 0 ) { return SelectResultSet . createEmptyResultSet ( ) ; } if ( updateCount > 1 ) { long [ ] insertIds = new long [ ( int ) updateCount ] ; for ( int i = 0 ; i < updateCount ; i ++ ) { insertIds [ i ] = insertId + i * autoIncrement ; } return SelectResultSet . createGeneratedData ( insertIds , protocol , true ) ; } return SelectResultSet . createGeneratedData ( new long [ ] { insertId } , protocol , true ) ; }
Get generated Keys .
136
4
29,464
public BigDecimal getInternalBigDecimal ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return BigDecimal . valueOf ( parseBit ( ) ) ; case TINYINT : return BigDecimal . valueOf ( ( long ) getInternalTinyInt ( columnInfo ) ) ; case SMALLINT : case YEAR : return BigDecimal . valueOf ( ( long ) getInternalSmallInt ( columnInfo ) ) ; case INTEGER : case MEDIUMINT : return BigDecimal . valueOf ( getInternalMediumInt ( columnInfo ) ) ; case BIGINT : long value = ( ( buf [ pos ] & 0xff ) + ( ( long ) ( buf [ pos + 1 ] & 0xff ) << 8 ) + ( ( long ) ( buf [ pos + 2 ] & 0xff ) << 16 ) + ( ( long ) ( buf [ pos + 3 ] & 0xff ) << 24 ) + ( ( long ) ( buf [ pos + 4 ] & 0xff ) << 32 ) + ( ( long ) ( buf [ pos + 5 ] & 0xff ) << 40 ) + ( ( long ) ( buf [ pos + 6 ] & 0xff ) << 48 ) + ( ( long ) ( buf [ pos + 7 ] & 0xff ) << 56 ) ) ; if ( columnInfo . isSigned ( ) ) { return new BigDecimal ( String . valueOf ( BigInteger . valueOf ( value ) ) ) . setScale ( columnInfo . getDecimals ( ) ) ; } else { return new BigDecimal ( String . valueOf ( new BigInteger ( 1 , new byte [ ] { ( byte ) ( value >> 56 ) , ( byte ) ( value >> 48 ) , ( byte ) ( value >> 40 ) , ( byte ) ( value >> 32 ) , ( byte ) ( value >> 24 ) , ( byte ) ( value >> 16 ) , ( byte ) ( value >> 8 ) , ( byte ) value } ) ) ) . setScale ( columnInfo . getDecimals ( ) ) ; } case FLOAT : return BigDecimal . valueOf ( getInternalFloat ( columnInfo ) ) ; case DOUBLE : return BigDecimal . valueOf ( getInternalDouble ( columnInfo ) ) ; case DECIMAL : case VARSTRING : case VARCHAR : case STRING : case OLDDECIMAL : return new BigDecimal ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; default : throw new SQLException ( "getBigDecimal not available for data field type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) ) ; } }
Get BigDecimal from raw binary format .
599
9
29,465
@ SuppressWarnings ( "deprecation" ) public Date getInternalDate ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case TIMESTAMP : case DATETIME : Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; return ( timestamp == null ) ? null : new Date ( timestamp . getTime ( ) ) ; case TIME : throw new SQLException ( "Cannot read Date using a Types.TIME field" ) ; case STRING : String rawValue = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( "0000-00-00" . equals ( rawValue ) ) { lastValueNull |= BIT_LAST_ZERO_DATE ; return null ; } return new Date ( Integer . parseInt ( rawValue . substring ( 0 , 4 ) ) - 1900 , Integer . parseInt ( rawValue . substring ( 5 , 7 ) ) - 1 , Integer . parseInt ( rawValue . substring ( 8 , 10 ) ) ) ; default : if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } int year = ( ( buf [ pos ] & 0xff ) | ( buf [ pos + 1 ] & 0xff ) << 8 ) ; if ( length == 2 && columnInfo . getLength ( ) == 2 ) { //YEAR(2) - deprecated if ( year <= 69 ) { year += 2000 ; } else { year += 1900 ; } } int month = 1 ; int day = 1 ; if ( length >= 4 ) { month = buf [ pos + 2 ] ; day = buf [ pos + 3 ] ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; calendar . set ( Calendar . YEAR , year ) ; calendar . set ( Calendar . MONTH , month - 1 ) ; calendar . set ( Calendar . DAY_OF_MONTH , day ) ; calendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; calendar . set ( Calendar . MINUTE , 0 ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; Date dt = new Date ( calendar . getTimeInMillis ( ) ) ; return dt ; } }
Get date from raw binary format .
533
7
29,466
public Time getInternalTime ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case TIMESTAMP : case DATETIME : Timestamp ts = getInternalTimestamp ( columnInfo , cal , timeZone ) ; return ( ts == null ) ? null : new Time ( ts . getTime ( ) ) ; case DATE : throw new SQLException ( "Cannot read Time using a Types.DATE field" ) ; default : Calendar calendar = Calendar . getInstance ( ) ; calendar . clear ( ) ; int day = 0 ; int hour = 0 ; int minutes = 0 ; int seconds = 0 ; boolean negate = false ; if ( length > 0 ) { negate = ( buf [ pos ] & 0xff ) == 0x01 ; } if ( length > 4 ) { day = ( ( buf [ pos + 1 ] & 0xff ) + ( ( buf [ pos + 2 ] & 0xff ) << 8 ) + ( ( buf [ pos + 3 ] & 0xff ) << 16 ) + ( ( buf [ pos + 4 ] & 0xff ) << 24 ) ) ; } if ( length > 7 ) { hour = buf [ pos + 5 ] ; minutes = buf [ pos + 6 ] ; seconds = buf [ pos + 7 ] ; } calendar . set ( 1970 , Calendar . JANUARY , ( ( negate ? - 1 : 1 ) * day ) + 1 , ( negate ? - 1 : 1 ) * hour , minutes , seconds ) ; int nanoseconds = 0 ; if ( length > 8 ) { nanoseconds = ( ( buf [ pos + 8 ] & 0xff ) + ( ( buf [ pos + 9 ] & 0xff ) << 8 ) + ( ( buf [ pos + 10 ] & 0xff ) << 16 ) + ( ( buf [ pos + 11 ] & 0xff ) << 24 ) ) ; } calendar . set ( Calendar . MILLISECOND , nanoseconds / 1000 ) ; return new Time ( calendar . getTimeInMillis ( ) ) ; } }
Get time from raw binary format .
463
7
29,467
public Object getInternalObject ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : if ( columnInfo . getLength ( ) == 1 ) { return buf [ pos ] != 0 ; } byte [ ] dataBit = new byte [ length ] ; System . arraycopy ( buf , pos , dataBit , 0 , length ) ; return dataBit ; case TINYINT : if ( options . tinyInt1isBit && columnInfo . getLength ( ) == 1 ) { return buf [ pos ] != 0 ; } return getInternalInt ( columnInfo ) ; case INTEGER : if ( ! columnInfo . isSigned ( ) ) { return getInternalLong ( columnInfo ) ; } return getInternalInt ( columnInfo ) ; case BIGINT : if ( ! columnInfo . isSigned ( ) ) { return getInternalBigInteger ( columnInfo ) ; } return getInternalLong ( columnInfo ) ; case DOUBLE : return getInternalDouble ( columnInfo ) ; case VARCHAR : case VARSTRING : case STRING : if ( columnInfo . isBinary ( ) ) { byte [ ] data = new byte [ getLengthMaxFieldSize ( ) ] ; System . arraycopy ( buf , pos , data , 0 , getLengthMaxFieldSize ( ) ) ; return data ; } return getInternalString ( columnInfo , null , timeZone ) ; case TIMESTAMP : case DATETIME : return getInternalTimestamp ( columnInfo , null , timeZone ) ; case DATE : return getInternalDate ( columnInfo , null , timeZone ) ; case DECIMAL : return getInternalBigDecimal ( columnInfo ) ; case BLOB : case LONGBLOB : case MEDIUMBLOB : case TINYBLOB : byte [ ] dataBlob = new byte [ getLengthMaxFieldSize ( ) ] ; System . arraycopy ( buf , pos , dataBlob , 0 , getLengthMaxFieldSize ( ) ) ; return dataBlob ; case NULL : return null ; case YEAR : if ( options . yearIsDateType ) { return getInternalDate ( columnInfo , null , timeZone ) ; } return getInternalShort ( columnInfo ) ; case SMALLINT : case MEDIUMINT : return getInternalInt ( columnInfo ) ; case FLOAT : return getInternalFloat ( columnInfo ) ; case TIME : return getInternalTime ( columnInfo , null , timeZone ) ; case OLDDECIMAL : case JSON : return getInternalString ( columnInfo , null , timeZone ) ; case GEOMETRY : byte [ ] data = new byte [ length ] ; System . arraycopy ( buf , pos , data , 0 , length ) ; return data ; case ENUM : break ; case NEWDATE : break ; case SET : break ; default : break ; } throw ExceptionMapper . getFeatureNotSupportedException ( "Type '" + columnInfo . getColumnType ( ) . getTypeName ( ) + "' is not supported" ) ; }
Get Object from raw binary format .
670
7
29,468
public boolean getInternalBoolean ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return false ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return parseBit ( ) != 0 ; case TINYINT : return getInternalTinyInt ( columnInfo ) != 0 ; case SMALLINT : case YEAR : return getInternalSmallInt ( columnInfo ) != 0 ; case INTEGER : case MEDIUMINT : return getInternalMediumInt ( columnInfo ) != 0 ; case BIGINT : return getInternalLong ( columnInfo ) != 0 ; case FLOAT : return getInternalFloat ( columnInfo ) != 0 ; case DOUBLE : return getInternalDouble ( columnInfo ) != 0 ; case DECIMAL : case OLDDECIMAL : return getInternalBigDecimal ( columnInfo ) . longValue ( ) != 0 ; default : final String rawVal = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; return ! ( "false" . equals ( rawVal ) || "0" . equals ( rawVal ) ) ; } }
Get boolean from raw binary format .
245
7
29,469
public byte getInternalByte ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value ; switch ( columnInfo . getColumnType ( ) ) { case BIT : value = parseBit ( ) ; break ; case TINYINT : value = getInternalTinyInt ( columnInfo ) ; break ; case SMALLINT : case YEAR : value = getInternalSmallInt ( columnInfo ) ; break ; case INTEGER : case MEDIUMINT : value = getInternalMediumInt ( columnInfo ) ; break ; case BIGINT : value = getInternalLong ( columnInfo ) ; break ; case FLOAT : value = ( long ) getInternalFloat ( columnInfo ) ; break ; case DOUBLE : value = ( long ) getInternalDouble ( columnInfo ) ; break ; case DECIMAL : case OLDDECIMAL : BigDecimal bigDecimal = getInternalBigDecimal ( columnInfo ) ; rangeCheck ( Byte . class , Byte . MIN_VALUE , Byte . MAX_VALUE , bigDecimal , columnInfo ) ; return bigDecimal . byteValue ( ) ; case VARSTRING : case VARCHAR : case STRING : value = Long . parseLong ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; break ; default : throw new SQLException ( "getByte not available for data field type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) ) ; } rangeCheck ( Byte . class , Byte . MIN_VALUE , Byte . MAX_VALUE , value , columnInfo ) ; return ( byte ) value ; }
Get byte from raw binary format .
358
7
29,470
public String getInternalTimeString ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { // binary send 00:00:00 as 0. if ( columnInfo . getDecimals ( ) == 0 ) { return "00:00:00" ; } else { StringBuilder value = new StringBuilder ( "00:00:00." ) ; int decimal = columnInfo . getDecimals ( ) ; while ( decimal -- > 0 ) { value . append ( "0" ) ; } return value . toString ( ) ; } } String rawValue = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( "0000-00-00" . equals ( rawValue ) ) { return null ; } int day = ( ( buf [ pos + 1 ] & 0xff ) | ( ( buf [ pos + 2 ] & 0xff ) << 8 ) | ( ( buf [ pos + 3 ] & 0xff ) << 16 ) | ( ( buf [ pos + 4 ] & 0xff ) << 24 ) ) ; int hour = buf [ pos + 5 ] ; int timeHour = hour + day * 24 ; String hourString ; if ( timeHour < 10 ) { hourString = "0" + timeHour ; } else { hourString = Integer . toString ( timeHour ) ; } String minuteString ; int minutes = buf [ pos + 6 ] ; if ( minutes < 10 ) { minuteString = "0" + minutes ; } else { minuteString = Integer . toString ( minutes ) ; } String secondString ; int seconds = buf [ pos + 7 ] ; if ( seconds < 10 ) { secondString = "0" + seconds ; } else { secondString = Integer . toString ( seconds ) ; } int microseconds = 0 ; if ( length > 8 ) { microseconds = ( ( buf [ pos + 8 ] & 0xff ) | ( buf [ pos + 9 ] & 0xff ) << 8 | ( buf [ pos + 10 ] & 0xff ) << 16 | ( buf [ pos + 11 ] & 0xff ) << 24 ) ; } StringBuilder microsecondString = new StringBuilder ( Integer . toString ( microseconds ) ) ; while ( microsecondString . length ( ) < 6 ) { microsecondString . insert ( 0 , "0" ) ; } boolean negative = ( buf [ pos ] == 0x01 ) ; return ( negative ? "-" : "" ) + ( hourString + ":" + minuteString + ":" + secondString + "." + microsecondString ) ; }
Get Time in string format from raw binary format .
556
10
29,471
public ZonedDateTime getInternalZonedDateTime ( ColumnInformation columnInfo , Class clazz , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIMESTAMP : int year = ( ( buf [ pos ] & 0xff ) | ( buf [ pos + 1 ] & 0xff ) << 8 ) ; int month = buf [ pos + 2 ] ; int day = buf [ pos + 3 ] ; int hour = 0 ; int minutes = 0 ; int seconds = 0 ; int microseconds = 0 ; if ( length > 4 ) { hour = buf [ pos + 4 ] ; minutes = buf [ pos + 5 ] ; seconds = buf [ pos + 6 ] ; if ( length > 7 ) { microseconds = ( ( buf [ pos + 7 ] & 0xff ) + ( ( buf [ pos + 8 ] & 0xff ) << 8 ) + ( ( buf [ pos + 9 ] & 0xff ) << 16 ) + ( ( buf [ pos + 10 ] & 0xff ) << 24 ) ) ; } } return ZonedDateTime . of ( year , month , day , hour , minutes , seconds , microseconds * 1000 , timeZone . toZoneId ( ) ) ; case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : //string conversion String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { return ZonedDateTime . parse ( raw , TEXT_ZONED_DATE_TIME ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as ZonedDateTime. time must have \"yyyy-MM-dd[T/ ]HH:mm:ss[.S]\" " + "with offset and timezone format (example : '2011-12-03 10:15:30+01:00[Europe/Paris]')" ) ; } default : throw new SQLException ( "Cannot read " + clazz . getName ( ) + " using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } }
Get ZonedDateTime from raw binary format .
549
10
29,472
public LocalTime getInternalLocalTime ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIME : int day = 0 ; int hour = 0 ; int minutes = 0 ; int seconds = 0 ; int microseconds = 0 ; final boolean negate = ( buf [ pos ] & 0xff ) == 0x01 ; if ( length > 4 ) { day = ( ( buf [ pos + 1 ] & 0xff ) + ( ( buf [ pos + 2 ] & 0xff ) << 8 ) + ( ( buf [ pos + 3 ] & 0xff ) << 16 ) + ( ( buf [ pos + 4 ] & 0xff ) << 24 ) ) ; } if ( length > 7 ) { hour = buf [ pos + 5 ] ; minutes = buf [ pos + 6 ] ; seconds = buf [ pos + 7 ] ; } if ( length > 8 ) { microseconds = ( ( buf [ pos + 8 ] & 0xff ) + ( ( buf [ pos + 9 ] & 0xff ) << 8 ) + ( ( buf [ pos + 10 ] & 0xff ) << 16 ) + ( ( buf [ pos + 11 ] & 0xff ) << 24 ) ) ; } return LocalTime . of ( ( negate ? - 1 : 1 ) * ( day * 24 + hour ) , minutes , seconds , microseconds * 1000 ) ; case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : //string conversion String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; try { return LocalTime . parse ( raw , DateTimeFormatter . ISO_LOCAL_TIME . withZone ( timeZone . toZoneId ( ) ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . TIMESTAMP : ZonedDateTime zonedDateTime = getInternalZonedDateTime ( columnInfo , LocalTime . class , timeZone ) ; return zonedDateTime == null ? null : zonedDateTime . withZoneSameInstant ( ZoneId . systemDefault ( ) ) . toLocalTime ( ) ; default : throw new SQLException ( "Cannot read LocalTime using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } }
Get LocalTime from raw binary format .
601
8
29,473
public static Pool retrievePool ( UrlParser urlParser ) { if ( ! poolMap . containsKey ( urlParser ) ) { synchronized ( poolMap ) { if ( ! poolMap . containsKey ( urlParser ) ) { if ( poolExecutor == null ) { poolExecutor = new ScheduledThreadPoolExecutor ( 1 , new MariaDbThreadFactory ( "MariaDbPool-maxTimeoutIdle-checker" ) ) ; } Pool pool = new Pool ( urlParser , poolIndex . incrementAndGet ( ) , poolExecutor ) ; poolMap . put ( urlParser , pool ) ; return pool ; } } } return poolMap . get ( urlParser ) ; }
Get existing pool for a configuration . Create it if doesn t exists .
144
14
29,474
public static void remove ( Pool pool ) { if ( poolMap . containsKey ( pool . getUrlParser ( ) ) ) { synchronized ( poolMap ) { if ( poolMap . containsKey ( pool . getUrlParser ( ) ) ) { poolMap . remove ( pool . getUrlParser ( ) ) ; shutdownExecutor ( ) ; } } } }
Remove pool .
75
3
29,475
public static void close ( ) { synchronized ( poolMap ) { for ( Pool pool : poolMap . values ( ) ) { try { pool . close ( ) ; } catch ( InterruptedException exception ) { //eat } } shutdownExecutor ( ) ; poolMap . clear ( ) ; } }
Close all pools .
62
4
29,476
public static void close ( String poolName ) { if ( poolName == null ) { return ; } synchronized ( poolMap ) { for ( Pool pool : poolMap . values ( ) ) { if ( poolName . equals ( pool . getUrlParser ( ) . getOptions ( ) . poolName ) ) { try { pool . close ( ) ; } catch ( InterruptedException exception ) { //eat } poolMap . remove ( pool . getUrlParser ( ) ) ; return ; } } if ( poolMap . isEmpty ( ) ) { shutdownExecutor ( ) ; } } }
Closing a pool with name defined in url .
123
10
29,477
public synchronized int read ( byte [ ] externalBuf , int off , int len ) throws IOException { if ( len == 0 ) { return 0 ; } int totalReads = 0 ; while ( true ) { //read if ( end - pos <= 0 ) { if ( len - totalReads >= buf . length ) { //buffer length is less than asked byte and buffer is empty // => filling directly into external buffer int reads = super . read ( externalBuf , off + totalReads , len - totalReads ) ; if ( reads <= 0 ) { return ( totalReads == 0 ) ? - 1 : totalReads ; } return totalReads + reads ; } else { //filling internal buffer fillBuffer ( len - totalReads ) ; if ( end <= 0 ) { return ( totalReads == 0 ) ? - 1 : totalReads ; } } } //copy internal value to buffer. int copyLength = Math . min ( len - totalReads , end - pos ) ; System . arraycopy ( buf , pos , externalBuf , off + totalReads , copyLength ) ; pos += copyLength ; totalReads += copyLength ; if ( totalReads >= len || super . available ( ) <= 0 ) { return totalReads ; } } }
Returing byte array from cache of reading socket if needed .
273
12
29,478
private void fillBuffer ( int minNeededBytes ) throws IOException { int lengthToReallyRead = Math . min ( BUF_SIZE , Math . max ( super . available ( ) , minNeededBytes ) ) ; end = super . read ( buf , 0 , lengthToReallyRead ) ; pos = 0 ; }
Fill buffer with required length or available bytes .
68
9
29,479
@ Override public void checkClientTrusted ( X509Certificate [ ] x509Certificates , String string ) throws CertificateException { if ( trustManager == null ) { return ; } trustManager . checkClientTrusted ( x509Certificates , string ) ; }
Check client trusted .
58
4
29,480
private void addConnectionRequest ( ) { if ( totalConnection . get ( ) < options . maxPoolSize && poolState . get ( ) == POOL_STATE_OK ) { //ensure to have one worker if was timeout connectionAppender . prestartCoreThread ( ) ; connectionAppenderQueue . offer ( ( ) -> { if ( ( totalConnection . get ( ) < options . minPoolSize || pendingRequestNumber . get ( ) > 0 ) && totalConnection . get ( ) < options . maxPoolSize ) { try { addConnection ( ) ; } catch ( SQLException sqle ) { //eat } } } ) ; } }
Add new connection if needed . Only one thread create new connection so new connection request will wait to newly created connection or for a released connection .
138
28
29,481
private void removeIdleTimeoutConnection ( ) { //descending iterator since first from queue are the first to be used Iterator < MariaDbPooledConnection > iterator = idleConnections . descendingIterator ( ) ; MariaDbPooledConnection item ; while ( iterator . hasNext ( ) ) { item = iterator . next ( ) ; long idleTime = System . nanoTime ( ) - item . getLastUsed ( ) . get ( ) ; boolean timedOut = idleTime > TimeUnit . SECONDS . toNanos ( maxIdleTime ) ; boolean shouldBeReleased = false ; if ( globalInfo != null ) { // idle time is reaching server @@wait_timeout if ( idleTime > TimeUnit . SECONDS . toNanos ( globalInfo . getWaitTimeout ( ) - 45 ) ) { shouldBeReleased = true ; } // idle has reach option maxIdleTime value and pool has more connections than minPoolSiz if ( timedOut && totalConnection . get ( ) > options . minPoolSize ) { shouldBeReleased = true ; } } else if ( timedOut ) { shouldBeReleased = true ; } if ( shouldBeReleased && idleConnections . remove ( item ) ) { totalConnection . decrementAndGet ( ) ; silentCloseConnection ( item ) ; addConnectionRequest ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "pool {} connection removed due to inactivity (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } } } }
Removing idle connection . Close them and recreate connection to reach minimal number of connection .
343
17
29,482
private void addConnection ( ) throws SQLException { //create new connection Protocol protocol = Utils . retrieveProxy ( urlParser , globalInfo ) ; MariaDbConnection connection = new MariaDbConnection ( protocol ) ; MariaDbPooledConnection pooledConnection = createPoolConnection ( connection ) ; if ( options . staticGlobal ) { //on first connection load initial state if ( globalInfo == null ) { initializePoolGlobalState ( connection ) ; } //set default transaction isolation level to permit resetting to initial state connection . setDefaultTransactionIsolation ( globalInfo . getDefaultTransactionIsolation ( ) ) ; } else { //set default transaction isolation level to permit resetting to initial state connection . setDefaultTransactionIsolation ( connection . getTransactionIsolation ( ) ) ; } if ( poolState . get ( ) == POOL_STATE_OK && totalConnection . incrementAndGet ( ) <= options . maxPoolSize ) { idleConnections . addFirst ( pooledConnection ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "pool {} new physical connection created (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } return ; } silentCloseConnection ( pooledConnection ) ; }
Create new connection .
276
4
29,483
private MariaDbPooledConnection getIdleConnection ( long timeout , TimeUnit timeUnit ) throws InterruptedException { while ( true ) { MariaDbPooledConnection item = ( timeout == 0 ) ? idleConnections . pollFirst ( ) : idleConnections . pollFirst ( timeout , timeUnit ) ; if ( item != null ) { MariaDbConnection connection = item . getConnection ( ) ; try { if ( TimeUnit . NANOSECONDS . toMillis ( System . nanoTime ( ) - item . getLastUsed ( ) . get ( ) ) > options . poolValidMinDelay ) { //validate connection if ( connection . isValid ( 10 ) ) { //10 seconds timeout item . lastUsedToNow ( ) ; return item ; } } else { // connection has been retrieved recently -> skip connection validation item . lastUsedToNow ( ) ; return item ; } } catch ( SQLException sqle ) { //eat } totalConnection . decrementAndGet ( ) ; // validation failed silentAbortConnection ( item ) ; addConnectionRequest ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "pool {} connection removed from pool due to failed validation (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } continue ; } return null ; } }
Get an existing idle connection in pool .
302
8
29,484
public MariaDbConnection getConnection ( String username , String password ) throws SQLException { try { if ( ( urlParser . getUsername ( ) != null ? urlParser . getUsername ( ) . equals ( username ) : username == null ) && ( urlParser . getPassword ( ) != null ? urlParser . getPassword ( ) . equals ( password ) : password == null ) ) { return getConnection ( ) ; } UrlParser tmpUrlParser = ( UrlParser ) urlParser . clone ( ) ; tmpUrlParser . setUsername ( username ) ; tmpUrlParser . setPassword ( password ) ; Protocol protocol = Utils . retrieveProxy ( tmpUrlParser , globalInfo ) ; return new MariaDbConnection ( protocol ) ; } catch ( CloneNotSupportedException cloneException ) { //cannot occur throw new SQLException ( "Error getting connection, parameters cannot be cloned" , cloneException ) ; } }
Get new connection from pool if user and password correspond to pool . If username and password are different from pool will return a dedicated connection .
197
27
29,485
public void close ( ) throws InterruptedException { synchronized ( this ) { Pools . remove ( this ) ; poolState . set ( POOL_STATE_CLOSING ) ; pendingRequestNumber . set ( 0 ) ; scheduledFuture . cancel ( false ) ; connectionAppender . shutdown ( ) ; try { connectionAppender . awaitTermination ( 10 , TimeUnit . SECONDS ) ; } catch ( InterruptedException i ) { //eat } if ( logger . isInfoEnabled ( ) ) { logger . info ( "closing pool {} (total:{}, active:{}, pending:{})" , poolTag , totalConnection . get ( ) , getActiveConnections ( ) , pendingRequestNumber . get ( ) ) ; } ExecutorService connectionRemover = new ThreadPoolExecutor ( totalConnection . get ( ) , options . maxPoolSize , 10 , TimeUnit . SECONDS , new LinkedBlockingQueue <> ( options . maxPoolSize ) , new MariaDbThreadFactory ( poolTag + "-destroyer" ) ) ; //loop for up to 10 seconds to close not used connection long start = System . nanoTime ( ) ; do { closeAll ( connectionRemover , idleConnections ) ; if ( totalConnection . get ( ) > 0 ) { Thread . sleep ( 0 , 10_00 ) ; } } while ( totalConnection . get ( ) > 0 && TimeUnit . NANOSECONDS . toSeconds ( System . nanoTime ( ) - start ) < 10 ) ; //after having wait for 10 seconds, force removal, even if used connections if ( totalConnection . get ( ) > 0 || idleConnections . isEmpty ( ) ) { closeAll ( connectionRemover , idleConnections ) ; } connectionRemover . shutdown ( ) ; try { unRegisterJmx ( ) ; } catch ( Exception exception ) { //eat } connectionRemover . awaitTermination ( 10 , TimeUnit . SECONDS ) ; } }
Close pool and underlying connections .
416
6
29,486
public void addToBlacklist ( HostAddress hostAddress ) { if ( hostAddress != null && ! isExplicitClosed ( ) ) { blacklist . putIfAbsent ( hostAddress , System . nanoTime ( ) ) ; } }
After a failover put the hostAddress in a static list so the other connection will not take this host in account for a time .
50
27
29,487
public void resetOldsBlackListHosts ( ) { long currentTimeNanos = System . nanoTime ( ) ; Set < Map . Entry < HostAddress , Long > > entries = blacklist . entrySet ( ) ; for ( Map . Entry < HostAddress , Long > blEntry : entries ) { long entryNanos = blEntry . getValue ( ) ; long durationSeconds = TimeUnit . NANOSECONDS . toSeconds ( currentTimeNanos - entryNanos ) ; if ( durationSeconds >= urlParser . getOptions ( ) . loadBalanceBlacklistTimeout ) { blacklist . remove ( blEntry . getKey ( ) , entryNanos ) ; } } }
Permit to remove Host to blacklist after loadBalanceBlacklistTimeout seconds .
146
15
29,488
public boolean setMasterHostFail ( ) { if ( masterHostFail . compareAndSet ( false , true ) ) { masterHostFailNanos = System . nanoTime ( ) ; currentConnectionAttempts . set ( 0 ) ; return true ; } return false ; }
Set master fail variables .
55
5
29,489
public HandleErrorResult relaunchOperation ( Method method , Object [ ] args ) throws IllegalAccessException , InvocationTargetException { HandleErrorResult handleErrorResult = new HandleErrorResult ( true ) ; if ( method != null ) { switch ( method . getName ( ) ) { case "executeQuery" : if ( args [ 2 ] instanceof String ) { String query = ( ( String ) args [ 2 ] ) . toUpperCase ( Locale . ROOT ) ; if ( ! "ALTER SYSTEM CRASH" . equals ( query ) && ! query . startsWith ( "KILL" ) ) { logger . debug ( "relaunch query to new connection {}" , ( ( currentProtocol != null ) ? "(conn=" + currentProtocol . getServerThreadId ( ) + ")" : "" ) ) ; handleErrorResult . resultObject = method . invoke ( currentProtocol , args ) ; handleErrorResult . mustThrowError = false ; } } break ; case "executePreparedQuery" : //the statementId has been discarded with previous session try { boolean mustBeOnMaster = ( Boolean ) args [ 0 ] ; ServerPrepareResult oldServerPrepareResult = ( ServerPrepareResult ) args [ 1 ] ; ServerPrepareResult serverPrepareResult = currentProtocol . prepare ( oldServerPrepareResult . getSql ( ) , mustBeOnMaster ) ; oldServerPrepareResult . failover ( serverPrepareResult . getStatementId ( ) , currentProtocol ) ; logger . debug ( "relaunch query to new connection " + ( ( currentProtocol != null ) ? "server thread id " + currentProtocol . getServerThreadId ( ) : "" ) ) ; handleErrorResult . resultObject = method . invoke ( currentProtocol , args ) ; handleErrorResult . mustThrowError = false ; } catch ( Exception e ) { //if retry prepare fail, discard error. execution error will indicate the error. } break ; default : handleErrorResult . resultObject = method . invoke ( currentProtocol , args ) ; handleErrorResult . mustThrowError = false ; break ; } } return handleErrorResult ; }
After a failover that has bean done relaunch the operation that was in progress . In case of special operation that crash server doesn t relaunched it ;
457
32
29,490
public boolean isQueryRelaunchable ( Method method , Object [ ] args ) { if ( method != null ) { switch ( method . getName ( ) ) { case "executeQuery" : if ( ! ( ( Boolean ) args [ 0 ] ) ) { return true ; //launched on slave connection } if ( args [ 2 ] instanceof String ) { return ( ( String ) args [ 2 ] ) . toUpperCase ( Locale . ROOT ) . startsWith ( "SELECT" ) ; } else if ( args [ 2 ] instanceof ClientPrepareResult ) { @ SuppressWarnings ( "unchecked" ) String query = new String ( ( ( ClientPrepareResult ) args [ 2 ] ) . getQueryParts ( ) . get ( 0 ) ) . toUpperCase ( Locale . ROOT ) ; return query . startsWith ( "SELECT" ) ; } break ; case "executePreparedQuery" : if ( ! ( ( Boolean ) args [ 0 ] ) ) { return true ; //launched on slave connection } ServerPrepareResult serverPrepareResult = ( ServerPrepareResult ) args [ 1 ] ; return ( serverPrepareResult . getSql ( ) ) . toUpperCase ( Locale . ROOT ) . startsWith ( "SELECT" ) ; case "executeBatchStmt" : case "executeBatchClient" : case "executeBatchServer" : return ! ( ( Boolean ) args [ 0 ] ) ; default : return false ; } } return false ; }
Check if query can be re - executed .
325
9
29,491
public void syncConnection ( Protocol from , Protocol to ) throws SQLException { if ( from != null ) { proxy . lock . lock ( ) ; try { to . resetStateAfterFailover ( from . getMaxRows ( ) , from . getTransactionIsolationLevel ( ) , from . getDatabase ( ) , from . getAutocommit ( ) ) ; } finally { proxy . lock . unlock ( ) ; } } }
When switching between 2 connections report existing connection parameter to the new used connection .
93
15
29,492
@ Override public void throwFailoverMessage ( HostAddress failHostAddress , boolean wasMaster , SQLException queryException , boolean reconnected ) throws SQLException { String firstPart = "Communications link failure with " + ( wasMaster ? "primary" : "secondary" ) + ( ( failHostAddress != null ) ? " host " + failHostAddress . host + ":" + failHostAddress . port : "" ) + ". " ; String error = "" ; if ( reconnected ) { error += " Driver has reconnect connection" ; } else { if ( currentConnectionAttempts . get ( ) > urlParser . getOptions ( ) . retriesAllDown ) { error += " Driver will not try to reconnect (too much failure > " + urlParser . getOptions ( ) . retriesAllDown + ")" ; } } String message ; String sqlState ; int vendorCode = 0 ; Throwable cause = null ; if ( queryException == null ) { message = firstPart + error ; sqlState = CONNECTION_EXCEPTION . getSqlState ( ) ; } else { message = firstPart + queryException . getMessage ( ) + ". " + error ; sqlState = queryException . getSQLState ( ) ; vendorCode = queryException . getErrorCode ( ) ; cause = queryException . getCause ( ) ; } if ( sqlState != null && sqlState . startsWith ( "08" ) ) { if ( reconnected ) { //change sqlState to "Transaction has been rolled back", to transaction exception, since reconnection has succeed sqlState = "25S03" ; } else { throw new SQLNonTransientConnectionException ( message , sqlState , vendorCode , cause ) ; } } throw new SQLException ( message , sqlState , vendorCode , cause ) ; }
Throw a human readable message after a failoverException .
384
11
29,493
public String getInternalString ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return String . valueOf ( parseBit ( ) ) ; case DOUBLE : case FLOAT : return zeroFillingIfNeeded ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) , columnInfo ) ; case TIME : return getInternalTimeString ( columnInfo ) ; case DATE : Date date = getInternalDate ( columnInfo , cal , timeZone ) ; if ( date == null ) { if ( ( lastValueNull & BIT_LAST_ZERO_DATE ) != 0 ) { lastValueNull ^= BIT_LAST_ZERO_DATE ; return new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; } return null ; } return date . toString ( ) ; case YEAR : if ( options . yearIsDateType ) { Date date1 = getInternalDate ( columnInfo , cal , timeZone ) ; return ( date1 == null ) ? null : date1 . toString ( ) ; } break ; case TIMESTAMP : case DATETIME : Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; if ( timestamp == null ) { if ( ( lastValueNull & BIT_LAST_ZERO_DATE ) != 0 ) { lastValueNull ^= BIT_LAST_ZERO_DATE ; return new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; } return null ; } return timestamp . toString ( ) ; case DECIMAL : case OLDDECIMAL : BigDecimal bigDecimal = getInternalBigDecimal ( columnInfo ) ; return ( bigDecimal == null ) ? null : zeroFillingIfNeeded ( bigDecimal . toString ( ) , columnInfo ) ; case NULL : return null ; default : break ; } if ( maxFieldSize > 0 ) { return new String ( buf , pos , Math . min ( maxFieldSize * 3 , length ) , StandardCharsets . UTF_8 ) . substring ( 0 , Math . min ( maxFieldSize , length ) ) ; } return new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; }
Get String from raw text format .
526
7
29,494
public int getInternalInt ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value = getInternalLong ( columnInfo ) ; rangeCheck ( Integer . class , Integer . MIN_VALUE , Integer . MAX_VALUE , value , columnInfo ) ; return ( int ) value ; }
Get int from raw text format .
74
7
29,495
public float getInternalFloat ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } switch ( columnInfo . getColumnType ( ) ) { case BIT : return parseBit ( ) ; case TINYINT : case SMALLINT : case YEAR : case INTEGER : case MEDIUMINT : case FLOAT : case DOUBLE : case DECIMAL : case VARSTRING : case VARCHAR : case STRING : case OLDDECIMAL : case BIGINT : try { return Float . valueOf ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; } catch ( NumberFormatException nfe ) { SQLException sqlException = new SQLException ( "Incorrect format \"" + new String ( buf , pos , length , StandardCharsets . UTF_8 ) + "\" for getFloat for data field with type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) , "22003" , 1264 ) ; //noinspection UnnecessaryInitCause sqlException . initCause ( nfe ) ; throw sqlException ; } default : throw new SQLException ( "getFloat not available for data field type " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) ) ; } }
Get float from raw text format .
293
7
29,496
public BigDecimal getInternalBigDecimal ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } if ( columnInfo . getColumnType ( ) == ColumnType . BIT ) { return BigDecimal . valueOf ( parseBit ( ) ) ; } return new BigDecimal ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; }
Get BigDecimal from raw text format .
89
9
29,497
@ SuppressWarnings ( "deprecation" ) public Date getInternalDate ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } switch ( columnInfo . getColumnType ( ) ) { case DATE : int [ ] datePart = new int [ ] { 0 , 0 , 0 } ; int partIdx = 0 ; for ( int begin = pos ; begin < pos + length ; begin ++ ) { byte b = buf [ begin ] ; if ( b == ' ' ) { partIdx ++ ; continue ; } if ( b < ' ' || b > ' ' ) { throw new SQLException ( "cannot parse data in date string '" + new String ( buf , pos , length , StandardCharsets . UTF_8 ) + "'" ) ; } datePart [ partIdx ] = datePart [ partIdx ] * 10 + b - 48 ; } if ( datePart [ 0 ] == 0 && datePart [ 1 ] == 0 && datePart [ 2 ] == 0 ) { lastValueNull |= BIT_LAST_ZERO_DATE ; return null ; } return new Date ( datePart [ 0 ] - 1900 , datePart [ 1 ] - 1 , datePart [ 2 ] ) ; case TIMESTAMP : case DATETIME : Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; if ( timestamp == null ) { return null ; } return new Date ( timestamp . getTime ( ) ) ; case TIME : throw new SQLException ( "Cannot read DATE using a Types.TIME field" ) ; case YEAR : int year = 0 ; for ( int begin = pos ; begin < pos + length ; begin ++ ) { year = year * 10 + buf [ begin ] - 48 ; } if ( length == 2 && columnInfo . getLength ( ) == 2 ) { if ( year <= 69 ) { year += 2000 ; } else { year += 1900 ; } } return new Date ( year - 1900 , 0 , 1 ) ; default : try { DateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd" ) ; sdf . setTimeZone ( timeZone ) ; java . util . Date utilDate = sdf . parse ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; return new Date ( utilDate . getTime ( ) ) ; } catch ( ParseException e ) { throw ExceptionMapper . getSqlException ( "Could not get object as Date : " + e . getMessage ( ) , "S1009" , e ) ; } } }
Get date from raw text format .
581
7
29,498
public Time getInternalTime ( ColumnInformation columnInfo , Calendar cal , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( columnInfo . getColumnType ( ) == ColumnType . TIMESTAMP || columnInfo . getColumnType ( ) == ColumnType . DATETIME ) { Timestamp timestamp = getInternalTimestamp ( columnInfo , cal , timeZone ) ; return ( timestamp == null ) ? null : new Time ( timestamp . getTime ( ) ) ; } else if ( columnInfo . getColumnType ( ) == ColumnType . DATE ) { throw new SQLException ( "Cannot read Time using a Types.DATE field" ) ; } else { String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( ! options . useLegacyDatetimeCode && ( raw . startsWith ( "-" ) || raw . split ( ":" ) . length != 3 || raw . indexOf ( ":" ) > 3 ) ) { throw new SQLException ( "Time format \"" + raw + "\" incorrect, must be HH:mm:ss" ) ; } boolean negate = raw . startsWith ( "-" ) ; if ( negate ) { raw = raw . substring ( 1 ) ; } String [ ] rawPart = raw . split ( ":" ) ; if ( rawPart . length == 3 ) { int hour = Integer . parseInt ( rawPart [ 0 ] ) ; int minutes = Integer . parseInt ( rawPart [ 1 ] ) ; int seconds = Integer . parseInt ( rawPart [ 2 ] . substring ( 0 , 2 ) ) ; Calendar calendar = Calendar . getInstance ( ) ; if ( options . useLegacyDatetimeCode ) { calendar . setLenient ( true ) ; } calendar . clear ( ) ; calendar . set ( 1970 , Calendar . JANUARY , 1 , ( negate ? - 1 : 1 ) * hour , minutes , seconds ) ; int nanoseconds = extractNanos ( raw ) ; calendar . set ( Calendar . MILLISECOND , nanoseconds / 1000000 ) ; return new Time ( calendar . getTimeInMillis ( ) ) ; } else { throw new SQLException ( raw + " cannot be parse as time. time must have \"99:99:99\" format" ) ; } } }
Get time from raw text format .
515
7
29,499
public boolean getInternalBoolean ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return false ; } if ( columnInfo . getColumnType ( ) == ColumnType . BIT ) { return parseBit ( ) != 0 ; } final String rawVal = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; return ! ( "false" . equals ( rawVal ) || "0" . equals ( rawVal ) ) ; }
Get boolean from raw text format .
102
7