idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
29,500 | public byte getInternalByte ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value = getInternalLong ( columnInfo ) ; rangeCheck ( Byte . class , Byte . MIN_VALUE , Byte . MAX_VALUE , value , columnInfo ) ; return ( byte ) value ; } | Get byte from raw text format . | 74 | 7 |
29,501 | public short getInternalShort ( ColumnInformation columnInfo ) throws SQLException { if ( lastValueWasNull ( ) ) { return 0 ; } long value = getInternalLong ( columnInfo ) ; rangeCheck ( Short . class , Short . MIN_VALUE , Short . MAX_VALUE , value , columnInfo ) ; return ( short ) value ; } | Get short from raw text format . | 74 | 7 |
29,502 | public String getInternalTimeString ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } String rawValue = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; if ( "0000-00-00" . equals ( rawValue ) ) { return null ; } if ( options . maximizeMysqlCompatibility && options . useLegacyDatetimeCode && rawValue . indexOf ( "." ) > 0 ) { return rawValue . substring ( 0 , rawValue . indexOf ( "." ) ) ; } return rawValue ; } | Get Time in string format from raw text format . | 130 | 10 |
29,503 | public BigInteger getInternalBigInteger ( ColumnInformation columnInfo ) { if ( lastValueWasNull ( ) ) { return null ; } return new BigInteger ( new String ( buf , pos , length , StandardCharsets . UTF_8 ) ) ; } | Get BigInteger format from raw text format . | 54 | 9 |
29,504 | 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 ; } String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIMESTAMP : if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { LocalDateTime localDateTime = LocalDateTime . parse ( raw , TEXT_LOCAL_DATE_TIME . withZone ( timeZone . toZoneId ( ) ) ) ; return ZonedDateTime . of ( localDateTime , timeZone . toZoneId ( ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalDateTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format" ) ; } case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : 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 format from raw text format . | 478 | 11 |
29,505 | public OffsetTime getInternalOffsetTime ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } ZoneId zoneId = timeZone . toZoneId ( ) . normalized ( ) ; if ( zoneId instanceof ZoneOffset ) { ZoneOffset zoneOffset = ( ZoneOffset ) zoneId ; String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIMESTAMP : if ( raw . startsWith ( "0000-00-00 00:00:00" ) ) { return null ; } try { return ZonedDateTime . parse ( raw , TEXT_LOCAL_DATE_TIME . withZone ( zoneOffset ) ) . toOffsetDateTime ( ) . toOffsetTime ( ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as OffsetTime. time must have \"yyyy-MM-dd HH:mm:ss[.S]\" format" ) ; } case Types . TIME : try { LocalTime localTime = LocalTime . parse ( raw , DateTimeFormatter . ISO_LOCAL_TIME . withZone ( zoneOffset ) ) ; return OffsetTime . of ( localTime , zoneOffset ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : try { return OffsetTime . parse ( raw , DateTimeFormatter . ISO_OFFSET_TIME ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as OffsetTime (format is \"HH:mm:ss[.S]\" with offset for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } default : throw new SQLException ( "Cannot read " + OffsetTime . class . getName ( ) + " using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } if ( options . useLegacyDatetimeCode ) { //system timezone is not an offset throw new SQLException ( "Cannot return an OffsetTime for a TIME field when default timezone is '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)" ) ; } //server timezone is not an offset throw new SQLException ( "Cannot return an OffsetTime for a TIME field when server timezone '" + zoneId + "' (only possible for time-zone offset from Greenwich/UTC, such as +02:00)" ) ; } | Get OffsetTime format from raw text format . | 695 | 10 |
29,506 | public LocalTime getInternalLocalTime ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . TIME : case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : 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 format from raw text format . | 341 | 9 |
29,507 | public LocalDate getInternalLocalDate ( ColumnInformation columnInfo , TimeZone timeZone ) throws SQLException { if ( lastValueWasNull ( ) ) { return null ; } if ( length == 0 ) { lastValueNull |= BIT_LAST_FIELD_NULL ; return null ; } String raw = new String ( buf , pos , length , StandardCharsets . UTF_8 ) ; switch ( columnInfo . getColumnType ( ) . getSqlType ( ) ) { case Types . DATE : case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : if ( raw . startsWith ( "0000-00-00" ) ) { return null ; } try { return LocalDate . parse ( raw , DateTimeFormatter . ISO_LOCAL_DATE . withZone ( timeZone . toZoneId ( ) ) ) ; } catch ( DateTimeParseException dateParserEx ) { throw new SQLException ( raw + " cannot be parse as LocalDate (format is \"yyyy-MM-dd\" for data type \"" + columnInfo . getColumnType ( ) + "\")" ) ; } case Types . TIMESTAMP : ZonedDateTime zonedDateTime = getInternalZonedDateTime ( columnInfo , LocalDate . class , timeZone ) ; return zonedDateTime == null ? null : zonedDateTime . withZoneSameInstant ( ZoneId . systemDefault ( ) ) . toLocalDate ( ) ; default : throw new SQLException ( "Cannot read LocalDate using a " + columnInfo . getColumnType ( ) . getJavaTypeName ( ) + " field" ) ; } } | Get LocalDate format from raw text format . | 361 | 9 |
29,508 | public void connect ( ) throws SQLException { if ( ! isClosed ( ) ) { close ( ) ; } try { connect ( ( currentHost != null ) ? currentHost . host : null , ( currentHost != null ) ? currentHost . port : 3306 ) ; } catch ( IOException ioException ) { throw ExceptionMapper . connException ( "Could not connect to " + currentHost + ". " + ioException . getMessage ( ) + getTraces ( ) , ioException ) ; } } | Connect to currentHost . | 110 | 5 |
29,509 | private void connect ( String host , int port ) throws SQLException , IOException { try { socket = Utils . createSocket ( urlParser , host ) ; if ( options . socketTimeout != null ) { socket . setSoTimeout ( options . socketTimeout ) ; } initializeSocketOption ( ) ; // Bind the socket to a particular interface if the connection property // localSocketAddress has been defined. if ( options . localSocketAddress != null ) { InetSocketAddress localAddress = new InetSocketAddress ( options . localSocketAddress , 0 ) ; socket . bind ( localAddress ) ; } if ( ! socket . isConnected ( ) ) { InetSocketAddress sockAddr = urlParser . getOptions ( ) . pipe == null ? new InetSocketAddress ( host , port ) : null ; if ( options . connectTimeout != 0 ) { socket . connect ( sockAddr , options . connectTimeout ) ; } else { socket . connect ( sockAddr ) ; } } handleConnectionPhases ( host ) ; connected = true ; if ( options . useCompression ) { writer = new CompressPacketOutputStream ( writer . getOutputStream ( ) , options . maxQuerySizeToLog ) ; reader = new DecompressPacketInputStream ( ( ( StandardPacketInputStream ) reader ) . getInputStream ( ) , options . maxQuerySizeToLog ) ; if ( options . enablePacketDebug ) { writer . setTraceCache ( traceCache ) ; reader . setTraceCache ( traceCache ) ; } } boolean mustLoadAdditionalInfo = true ; if ( globalInfo != null ) { if ( globalInfo . isAutocommit ( ) == options . autocommit ) { mustLoadAdditionalInfo = false ; } } if ( mustLoadAdditionalInfo ) { Map < String , String > serverData = new TreeMap <> ( ) ; if ( options . usePipelineAuth && ! options . createDatabaseIfNotExist ) { try { sendPipelineAdditionalData ( ) ; readPipelineAdditionalData ( serverData ) ; } catch ( SQLException sqle ) { if ( "08" . equals ( sqle . getSQLState ( ) ) ) { throw sqle ; } //in case pipeline is not supported //(proxy flush socket after reading first packet) additionalData ( serverData ) ; } } else { additionalData ( serverData ) ; } writer . setMaxAllowedPacket ( Integer . parseInt ( serverData . get ( "max_allowed_packet" ) ) ) ; autoIncrementIncrement = Integer . parseInt ( serverData . get ( "auto_increment_increment" ) ) ; loadCalendar ( serverData . get ( "time_zone" ) , serverData . get ( "system_time_zone" ) ) ; } else { writer . setMaxAllowedPacket ( ( int ) globalInfo . getMaxAllowedPacket ( ) ) ; autoIncrementIncrement = globalInfo . getAutoIncrementIncrement ( ) ; loadCalendar ( globalInfo . getTimeZone ( ) , globalInfo . getSystemTimeZone ( ) ) ; } reader . setServerThreadId ( this . serverThreadId , isMasterConnection ( ) ) ; writer . setServerThreadId ( this . serverThreadId , isMasterConnection ( ) ) ; activeStreamingResult = null ; hostFailed = false ; } catch ( IOException | SQLException ioException ) { ensureClosingSocketOnException ( ) ; throw ioException ; } } | Connect the client and perform handshake . | 756 | 7 |
29,510 | private void sendPipelineCheckMaster ( ) throws IOException { if ( urlParser . getHaMode ( ) == HaMode . AURORA ) { writer . startPacket ( 0 ) ; writer . write ( COM_QUERY ) ; writer . write ( IS_MASTER_QUERY ) ; writer . flush ( ) ; } } | Send query to identify if server is master . | 74 | 9 |
29,511 | private void enabledSslCipherSuites ( SSLSocket sslSocket ) throws SQLException { if ( options . enabledSslCipherSuites != null ) { List < String > possibleCiphers = Arrays . asList ( sslSocket . getSupportedCipherSuites ( ) ) ; String [ ] ciphers = options . enabledSslCipherSuites . split ( "[,;\\s]+" ) ; for ( String cipher : ciphers ) { if ( ! possibleCiphers . contains ( cipher ) ) { throw new SQLException ( "Unsupported SSL cipher '" + cipher + "'. Supported ciphers : " + possibleCiphers . toString ( ) . replace ( "[" , "" ) . replace ( "]" , "" ) ) ; } } sslSocket . setEnabledCipherSuites ( ciphers ) ; } } | Set ssl socket cipher according to options . | 192 | 9 |
29,512 | public boolean versionGreaterOrEqual ( int major , int minor , int patch ) { if ( this . majorVersion > major ) { return true ; } if ( this . majorVersion < major ) { return false ; } /* * Major versions are equal, compare minor versions */ if ( this . minorVersion > minor ) { return true ; } if ( this . minorVersion < minor ) { return false ; } //Minor versions are equal, compare patch version. return this . patchVersion >= patch ; } | Utility method to check if database version is greater than parameters . | 105 | 13 |
29,513 | public Buffer process ( PacketOutputStream out , PacketInputStream in , AtomicInteger sequence ) throws IOException { if ( password == null || password . isEmpty ( ) ) { out . writeEmptyPacket ( sequence . incrementAndGet ( ) ) ; } else { out . startPacket ( sequence . incrementAndGet ( ) ) ; byte [ ] bytePwd ; if ( passwordCharacterEncoding != null && ! passwordCharacterEncoding . isEmpty ( ) ) { bytePwd = password . getBytes ( passwordCharacterEncoding ) ; } else { bytePwd = password . getBytes ( ) ; } out . write ( bytePwd ) ; out . write ( 0 ) ; out . flush ( ) ; } Buffer buffer = in . getPacket ( true ) ; sequence . set ( in . getLastPacketSeq ( ) ) ; return buffer ; } | Send password in clear text to server . | 185 | 8 |
29,514 | public static byte [ ] create ( byte [ ] [ ] rowDatas , ColumnType [ ] columnTypes ) { int totalLength = 0 ; for ( byte [ ] rowData : rowDatas ) { if ( rowData == null ) { totalLength ++ ; } else { int length = rowData . length ; if ( length < 251 ) { totalLength += length + 1 ; } else if ( length < 65536 ) { totalLength += length + 3 ; } else if ( length < 16777216 ) { totalLength += length + 4 ; } else { totalLength += length + 9 ; } } } byte [ ] buf = new byte [ totalLength ] ; int pos = 0 ; for ( byte [ ] arr : rowDatas ) { if ( arr == null ) { buf [ pos ++ ] = ( byte ) 251 ; } else { int length = arr . length ; if ( length < 251 ) { buf [ pos ++ ] = ( byte ) length ; } else if ( length < 65536 ) { buf [ pos ++ ] = ( byte ) 0xfc ; buf [ pos ++ ] = ( byte ) length ; buf [ pos ++ ] = ( byte ) ( length >>> 8 ) ; } else if ( length < 16777216 ) { buf [ pos ++ ] = ( byte ) 0xfd ; buf [ pos ++ ] = ( byte ) length ; buf [ pos ++ ] = ( byte ) ( length >>> 8 ) ; buf [ pos ++ ] = ( byte ) ( length >>> 16 ) ; } else { buf [ pos ++ ] = ( byte ) 0xfe ; buf [ pos ++ ] = ( byte ) length ; buf [ pos ++ ] = ( byte ) ( length >>> 8 ) ; buf [ pos ++ ] = ( byte ) ( length >>> 16 ) ; buf [ pos ++ ] = ( byte ) ( length >>> 24 ) ; //byte[] cannot have more than 4 byte length size, so buf[pos+5] -> buf[pos+8] = 0x00; pos += 4 ; } System . arraycopy ( arr , 0 , buf , pos , length ) ; pos += length ; } } return buf ; } | Create Buffer with Text protocol values . | 453 | 7 |
29,515 | public static UrlParser parse ( final String url , Properties prop ) throws SQLException { if ( url != null && ( url . startsWith ( "jdbc:mariadb:" ) || url . startsWith ( "jdbc:mysql:" ) && ! url . contains ( DISABLE_MYSQL_URL ) ) ) { UrlParser urlParser = new UrlParser ( ) ; parseInternal ( urlParser , url , ( prop == null ) ? new Properties ( ) : prop ) ; return urlParser ; } return null ; } | Parse url connection string with additional properties . | 120 | 9 |
29,516 | private static void parseInternal ( UrlParser urlParser , String url , Properties properties ) throws SQLException { try { urlParser . initialUrl = url ; int separator = url . indexOf ( "//" ) ; if ( separator == - 1 ) { throw new IllegalArgumentException ( "url parsing error : '//' is not present in the url " + url ) ; } urlParser . haMode = parseHaMode ( url , separator ) ; String urlSecondPart = url . substring ( separator + 2 ) ; int dbIndex = urlSecondPart . indexOf ( "/" ) ; int paramIndex = urlSecondPart . indexOf ( "?" ) ; String hostAddressesString ; String additionalParameters ; if ( ( dbIndex < paramIndex && dbIndex < 0 ) || ( dbIndex > paramIndex && paramIndex > - 1 ) ) { hostAddressesString = urlSecondPart . substring ( 0 , paramIndex ) ; additionalParameters = urlSecondPart . substring ( paramIndex ) ; } else if ( ( dbIndex < paramIndex && dbIndex > - 1 ) || ( dbIndex > paramIndex && paramIndex < 0 ) ) { hostAddressesString = urlSecondPart . substring ( 0 , dbIndex ) ; additionalParameters = urlSecondPart . substring ( dbIndex ) ; } else { hostAddressesString = urlSecondPart ; additionalParameters = null ; } defineUrlParserParameters ( urlParser , properties , hostAddressesString , additionalParameters ) ; setDefaultHostAddressType ( urlParser ) ; urlParser . loadMultiMasterValue ( ) ; } catch ( IllegalArgumentException i ) { throw new SQLException ( "error parsing url : " + i . getMessage ( ) , i ) ; } } | Parses the connection URL in order to set the UrlParser instance with all the information provided through the URL . | 375 | 24 |
29,517 | public UrlParser auroraPipelineQuirks ( ) { //Aurora has issue with pipelining, depending on network speed. //Driver must rely on information provided by user : hostname if dns, and HA mode.</p> boolean disablePipeline = isAurora ( ) ; if ( options . useBatchMultiSend == null ) { options . useBatchMultiSend = disablePipeline ? Boolean . FALSE : Boolean . TRUE ; } if ( options . usePipelineAuth == null ) { options . usePipelineAuth = disablePipeline ? Boolean . FALSE : Boolean . TRUE ; } return this ; } | Permit to set parameters not forced . if options useBatchMultiSend and usePipelineAuth are not explicitly set in connection string value will default to true or false according if aurora detection . | 140 | 41 |
29,518 | @ Override public boolean removeEldestEntry ( Map . Entry eldest ) { boolean mustBeRemoved = this . size ( ) > maxSize ; if ( mustBeRemoved ) { ServerPrepareResult serverPrepareResult = ( ( ServerPrepareResult ) eldest . getValue ( ) ) ; serverPrepareResult . setRemoveFromCache ( ) ; if ( serverPrepareResult . canBeDeallocate ( ) ) { try { protocol . forceReleasePrepareStatement ( serverPrepareResult . getStatementId ( ) ) ; } catch ( SQLException e ) { //eat exception } } } return mustBeRemoved ; } | Remove eldestEntry . | 134 | 4 |
29,519 | public synchronized ServerPrepareResult put ( String key , ServerPrepareResult result ) { ServerPrepareResult cachedServerPrepareResult = super . get ( key ) ; //if there is already some cached data (and not been deallocate), return existing cached data if ( cachedServerPrepareResult != null && cachedServerPrepareResult . incrementShareCounter ( ) ) { return cachedServerPrepareResult ; } //if no cache data, or been deallocate, put new result in cache result . setAddToCache ( ) ; super . put ( key , result ) ; return null ; } | Associates the specified value with the specified key in this map . If the map previously contained a mapping for the key the existing cached prepared result shared counter will be incremented . | 125 | 36 |
29,520 | public void authenticate ( final PacketOutputStream out , final PacketInputStream in , final AtomicInteger sequence , final String servicePrincipalName , final String mechanisms ) throws IOException { // initialize a security context on the client IWindowsSecurityContext clientContext = WindowsSecurityContextImpl . getCurrent ( mechanisms , servicePrincipalName ) ; do { // Step 1: send token to server byte [ ] tokenForTheServerOnTheClient = clientContext . getToken ( ) ; out . startPacket ( sequence . incrementAndGet ( ) ) ; out . write ( tokenForTheServerOnTheClient ) ; out . flush ( ) ; // Step 2: read server response token if ( clientContext . isContinue ( ) ) { Buffer buffer = in . getPacket ( true ) ; sequence . set ( in . getLastPacketSeq ( ) ) ; byte [ ] tokenForTheClientOnTheServer = buffer . readRawBytes ( buffer . remaining ( ) ) ; Sspi . SecBufferDesc continueToken = new Sspi . SecBufferDesc ( Sspi . SECBUFFER_TOKEN , tokenForTheClientOnTheServer ) ; clientContext . initialize ( clientContext . getHandle ( ) , continueToken , servicePrincipalName ) ; } } while ( clientContext . isContinue ( ) ) ; clientContext . dispose ( ) ; } | Process native windows GSS plugin authentication . | 286 | 8 |
29,521 | public static void send ( final PacketOutputStream pos ) { try { pos . startPacket ( 0 ) ; pos . write ( Packet . COM_QUIT ) ; pos . flush ( ) ; } catch ( IOException ioe ) { //eat } } | Send close stream to server . | 56 | 6 |
29,522 | public void flush ( ) throws IOException { flushBuffer ( true ) ; out . flush ( ) ; // if buffer is big, and last query doesn't use at least half of it, resize buffer to default value if ( buf . length > SMALL_BUFFER_SIZE && cmdLength * 2 < buf . length ) { buf = new byte [ SMALL_BUFFER_SIZE ] ; } if ( cmdLength >= maxAllowedPacket ) { throw new MaxAllowedPacketException ( "query size (" + cmdLength + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")" , true ) ; } } | Send packet to socket . | 139 | 5 |
29,523 | public void checkMaxAllowedLength ( int length ) throws MaxAllowedPacketException { if ( cmdLength + length >= maxAllowedPacket && cmdLength == 0 ) { //launch exception only if no packet has been send. throw new MaxAllowedPacketException ( "query size (" + ( cmdLength + length ) + ") is >= to max_allowed_packet (" + maxAllowedPacket + ")" , false ) ; } } | Count query size . If query size is greater than max_allowed_packet and nothing has been already send throw an exception to avoid having the connection closed . | 97 | 32 |
29,524 | public void writeShort ( short value ) throws IOException { if ( 2 > buf . length - pos ) { //not enough space remaining byte [ ] arr = new byte [ 2 ] ; arr [ 0 ] = ( byte ) value ; arr [ 1 ] = ( byte ) ( value >> 8 ) ; write ( arr , 0 , 2 ) ; return ; } buf [ pos ] = ( byte ) value ; buf [ pos + 1 ] = ( byte ) ( value >> 8 ) ; pos += 2 ; } | Write short value into buffer . flush buffer if too small . | 106 | 12 |
29,525 | public void writeInt ( int value ) throws IOException { if ( 4 > buf . length - pos ) { //not enough space remaining byte [ ] arr = new byte [ 4 ] ; arr [ 0 ] = ( byte ) value ; arr [ 1 ] = ( byte ) ( value >> 8 ) ; arr [ 2 ] = ( byte ) ( value >> 16 ) ; arr [ 3 ] = ( byte ) ( value >> 24 ) ; write ( arr , 0 , 4 ) ; return ; } buf [ pos ] = ( byte ) value ; buf [ pos + 1 ] = ( byte ) ( value >> 8 ) ; buf [ pos + 2 ] = ( byte ) ( value >> 16 ) ; buf [ pos + 3 ] = ( byte ) ( value >> 24 ) ; pos += 4 ; } | Write int value into buffer . flush buffer if too small . | 166 | 12 |
29,526 | public void writeLong ( long value ) throws IOException { if ( 8 > buf . length - pos ) { //not enough space remaining byte [ ] arr = new byte [ 8 ] ; arr [ 0 ] = ( byte ) value ; arr [ 1 ] = ( byte ) ( value >> 8 ) ; arr [ 2 ] = ( byte ) ( value >> 16 ) ; arr [ 3 ] = ( byte ) ( value >> 24 ) ; arr [ 4 ] = ( byte ) ( value >> 32 ) ; arr [ 5 ] = ( byte ) ( value >> 40 ) ; arr [ 6 ] = ( byte ) ( value >> 48 ) ; arr [ 7 ] = ( byte ) ( value >> 56 ) ; write ( arr , 0 , 8 ) ; return ; } buf [ pos ] = ( byte ) value ; buf [ pos + 1 ] = ( byte ) ( value >> 8 ) ; buf [ pos + 2 ] = ( byte ) ( value >> 16 ) ; buf [ pos + 3 ] = ( byte ) ( value >> 24 ) ; buf [ pos + 4 ] = ( byte ) ( value >> 32 ) ; buf [ pos + 5 ] = ( byte ) ( value >> 40 ) ; buf [ pos + 6 ] = ( byte ) ( value >> 48 ) ; buf [ pos + 7 ] = ( byte ) ( value >> 56 ) ; pos += 8 ; } | Write long value into buffer . flush buffer if too small . | 286 | 12 |
29,527 | public void writeBytes ( byte value , int len ) throws IOException { if ( len > buf . length - pos ) { //not enough space remaining byte [ ] arr = new byte [ len ] ; Arrays . fill ( arr , value ) ; write ( arr , 0 , len ) ; return ; } for ( int i = pos ; i < pos + len ; i ++ ) { buf [ i ] = value ; } pos += len ; } | Write byte value len times into buffer . flush buffer if too small . | 94 | 14 |
29,528 | public void write ( int value ) throws IOException { if ( pos >= buf . length ) { if ( pos >= getMaxPacketLength ( ) && ! bufferContainDataAfterMark ) { //buffer is more than a Packet, must flushBuffer() flushBuffer ( false ) ; } else { growBuffer ( 1 ) ; } } buf [ pos ++ ] = ( byte ) value ; } | Write byte into buffer flush buffer to socket if needed . | 83 | 11 |
29,529 | public void write ( byte [ ] arr , int off , int len ) throws IOException { if ( len > buf . length - pos ) { if ( buf . length != getMaxPacketLength ( ) ) { growBuffer ( len ) ; } //max buffer size if ( len > buf . length - pos ) { if ( mark != - 1 ) { growBuffer ( len ) ; if ( mark != - 1 ) { flushBufferStopAtMark ( ) ; } } else { //not enough space in buffer, will stream : // fill buffer and flush until all data are snd int remainingLen = len ; do { int lenToFillBuffer = Math . min ( getMaxPacketLength ( ) - pos , remainingLen ) ; System . arraycopy ( arr , off , buf , pos , lenToFillBuffer ) ; remainingLen -= lenToFillBuffer ; off += lenToFillBuffer ; pos += lenToFillBuffer ; if ( remainingLen > 0 ) { flushBuffer ( false ) ; } else { break ; } } while ( true ) ; return ; } } } System . arraycopy ( arr , off , buf , pos , len ) ; pos += len ; } | Write byte array to buffer . If buffer is full flush socket . | 247 | 13 |
29,530 | public void write ( Reader reader , boolean escape , boolean noBackslashEscapes ) throws IOException { char [ ] buffer = new char [ 4096 ] ; int len ; while ( ( len = reader . read ( buffer ) ) >= 0 ) { byte [ ] data = new String ( buffer , 0 , len ) . getBytes ( "UTF-8" ) ; if ( escape ) { writeBytesEscaped ( data , data . length , noBackslashEscapes ) ; } else { write ( data ) ; } } } | Write reader into socket . | 112 | 5 |
29,531 | public void writeBytesEscaped ( byte [ ] bytes , int len , boolean noBackslashEscapes ) throws IOException { if ( len * 2 > buf . length - pos ) { //makes buffer bigger (up to 16M) if ( buf . length != getMaxPacketLength ( ) ) { growBuffer ( len * 2 ) ; } //data may be bigger than buffer. //must flush buffer when full (and reset position to 0) if ( len * 2 > buf . length - pos ) { if ( mark != - 1 ) { growBuffer ( len * 2 ) ; if ( mark != - 1 ) { flushBufferStopAtMark ( ) ; } } else { //not enough space in buffer, will fill buffer if ( noBackslashEscapes ) { for ( int i = 0 ; i < len ; i ++ ) { if ( QUOTE == bytes [ i ] ) { buf [ pos ++ ] = QUOTE ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } buf [ pos ++ ] = bytes [ i ] ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } } else { for ( int i = 0 ; i < len ; i ++ ) { if ( bytes [ i ] == QUOTE || bytes [ i ] == BACKSLASH || bytes [ i ] == DBL_QUOTE || bytes [ i ] == ZERO_BYTE ) { buf [ pos ++ ] = ' ' ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } buf [ pos ++ ] = bytes [ i ] ; if ( buf . length <= pos ) { flushBuffer ( false ) ; } } } return ; } } } //sure to have enough place filling buffer directly if ( noBackslashEscapes ) { for ( int i = 0 ; i < len ; i ++ ) { if ( QUOTE == bytes [ i ] ) { buf [ pos ++ ] = QUOTE ; } buf [ pos ++ ] = bytes [ i ] ; } } else { for ( int i = 0 ; i < len ; i ++ ) { if ( bytes [ i ] == QUOTE || bytes [ i ] == BACKSLASH || bytes [ i ] == ' ' || bytes [ i ] == ZERO_BYTE ) { buf [ pos ++ ] = BACKSLASH ; //add escape slash } buf [ pos ++ ] = bytes [ i ] ; } } } | Write escape bytes to socket . | 517 | 6 |
29,532 | @ Override public void flushBufferStopAtMark ( ) throws IOException { final int end = pos ; pos = mark ; flushBuffer ( true ) ; out . flush ( ) ; startPacket ( 0 ) ; System . arraycopy ( buf , mark , buf , pos , end - mark ) ; pos += end - mark ; mark = - 1 ; bufferContainDataAfterMark = true ; } | Flush to last mark . | 84 | 6 |
29,533 | public byte [ ] resetMark ( ) { mark = - 1 ; if ( bufferContainDataAfterMark ) { byte [ ] data = Arrays . copyOfRange ( buf , initialPacketPos ( ) , pos ) ; startPacket ( 0 ) ; bufferContainDataAfterMark = false ; return data ; } return null ; } | Reset mark flag and send bytes after mark flag . | 72 | 11 |
29,534 | public static DynamicSizedSchedulerInterface getScheduler ( int initialThreadCount , String poolName , int maximumPoolSize ) { return getSchedulerProvider ( ) . getScheduler ( initialThreadCount , poolName , maximumPoolSize ) ; } | Get a Dynamic sized scheduler directly with the current set provider . | 56 | 13 |
29,535 | public void connect ( SocketAddress endpoint , int timeout ) throws IOException { String filename ; if ( host == null || host . equals ( "localhost" ) ) { filename = "\\\\.\\pipe\\" + name ; } else { filename = "\\\\" + host + "\\pipe\\" + name ; } //use a default timeout of 100ms if no timeout set. int usedTimeout = timeout == 0 ? 100 : timeout ; long initialNano = System . nanoTime ( ) ; do { try { file = new RandomAccessFile ( filename , "rw" ) ; break ; } catch ( FileNotFoundException fileNotFoundException ) { try { //using JNA if available Kernel32 . INSTANCE . WaitNamedPipe ( filename , timeout ) ; //then retry connection file = new RandomAccessFile ( filename , "rw" ) ; } catch ( Throwable cle ) { // in case JNA not on classpath, then wait 10ms before next try. if ( System . nanoTime ( ) - initialNano > TimeUnit . MILLISECONDS . toNanos ( usedTimeout ) ) { if ( timeout == 0 ) { throw new FileNotFoundException ( fileNotFoundException . getMessage ( ) + "\nplease consider set connectTimeout option, so connection can retry having access to named pipe. " + "\n(Named pipe can throw ERROR_PIPE_BUSY error)" ) ; } throw fileNotFoundException ; } try { TimeUnit . MILLISECONDS . sleep ( 5 ) ; } catch ( InterruptedException interrupted ) { IOException ioException = new IOException ( "Interruption during connection to named pipe" ) ; ioException . initCause ( interrupted ) ; throw ioException ; } } } } while ( true ) ; is = new InputStream ( ) { @ Override public int read ( byte [ ] bytes , int off , int len ) throws IOException { return file . read ( bytes , off , len ) ; } @ Override public int read ( ) throws IOException { return file . read ( ) ; } @ Override public int read ( byte [ ] bytes ) throws IOException { return file . read ( bytes ) ; } } ; os = new OutputStream ( ) { @ Override public void write ( byte [ ] bytes , int off , int len ) throws IOException { file . write ( bytes , off , len ) ; } @ Override public void write ( int value ) throws IOException { file . write ( value ) ; } @ Override public void write ( byte [ ] bytes ) throws IOException { file . write ( bytes ) ; } } ; } | Name pipe connection . | 559 | 4 |
29,536 | public void writeTo ( final PacketOutputStream pos ) throws IOException { if ( loadedStream == null ) { writeObjectToBytes ( ) ; } pos . write ( BINARY_INTRODUCER ) ; pos . writeBytesEscaped ( loadedStream , loadedStream . length , noBackSlashEscapes ) ; pos . write ( QUOTE ) ; } | Write object to buffer for text protocol . | 79 | 8 |
29,537 | public void failover ( int statementId , Protocol unProxiedProtocol ) { this . statementId = statementId ; this . unProxiedProtocol = unProxiedProtocol ; this . parameterTypeHeader = new ColumnType [ parameters . length ] ; this . shareCounter = 1 ; this . isBeingDeallocate = false ; } | Update information after a failover . | 75 | 7 |
29,538 | public int isNullable ( final int column ) throws SQLException { if ( ( getColumnInformation ( column ) . getFlags ( ) & ColumnFlags . NOT_NULL ) == 0 ) { return ResultSetMetaData . columnNullable ; } else { return ResultSetMetaData . columnNoNulls ; } } | Indicates the nullability of values in the designated column . | 68 | 12 |
29,539 | public String getTableName ( final int column ) throws SQLException { if ( returnTableAlias ) { return getColumnInformation ( column ) . getTable ( ) ; } else { return getColumnInformation ( column ) . getOriginalTable ( ) ; } } | Gets the designated column s table name . | 55 | 9 |
29,540 | public int getColumnType ( final int column ) throws SQLException { ColumnInformation ci = getColumnInformation ( column ) ; switch ( ci . getColumnType ( ) ) { case BIT : if ( ci . getLength ( ) == 1 ) { return Types . BIT ; } return Types . VARBINARY ; case TINYINT : if ( ci . getLength ( ) == 1 && options . tinyInt1isBit ) { return Types . BIT ; } return Types . TINYINT ; case YEAR : if ( options . yearIsDateType ) { return Types . DATE ; } return Types . SMALLINT ; case BLOB : if ( ci . getLength ( ) < 0 || ci . getLength ( ) > 16777215 ) { return Types . LONGVARBINARY ; } return Types . VARBINARY ; case VARCHAR : case VARSTRING : if ( ci . isBinary ( ) ) { return Types . VARBINARY ; } if ( ci . getLength ( ) < 0 ) { return Types . LONGVARCHAR ; } return Types . VARCHAR ; case STRING : if ( ci . isBinary ( ) ) { return Types . BINARY ; } return Types . CHAR ; default : return ci . getColumnType ( ) . getSqlType ( ) ; } } | Retrieves the designated column s SQL type . | 297 | 10 |
29,541 | private static int skipWhite ( char [ ] part , int startPos ) { for ( int i = startPos ; i < part . length ; i ++ ) { if ( ! Character . isWhitespace ( part [ i ] ) ) { return i ; } } return part . length ; } | Return new position or - 1 on error | 62 | 8 |
29,542 | private String catalogCond ( String columnName , String catalog ) { if ( catalog == null ) { /* Treat null catalog as current */ if ( connection . nullCatalogMeansCurrent ) { return "(ISNULL(database()) OR (" + columnName + " = database()))" ; } return "(1 = 1)" ; } if ( catalog . isEmpty ( ) ) { return "(ISNULL(database()) OR (" + columnName + " = database()))" ; } return "(" + columnName + " = " + escapeQuote ( catalog ) + ")" ; } | Generate part of the information schema query that restricts catalog names In the driver catalogs is the equivalent to MariaDB schemas . | 119 | 26 |
29,543 | public ResultSet getPseudoColumns ( String catalog , String schemaPattern , String tableNamePattern , String columnNamePattern ) throws SQLException { return connection . createStatement ( ) . executeQuery ( "SELECT ' ' TABLE_CAT, ' ' TABLE_SCHEM," + "' ' TABLE_NAME, ' ' COLUMN_NAME, 0 DATA_TYPE, 0 COLUMN_SIZE, 0 DECIMAL_DIGITS," + "10 NUM_PREC_RADIX, ' ' COLUMN_USAGE, ' ' REMARKS, 0 CHAR_OCTET_LENGTH, 'YES' IS_NULLABLE FROM DUAL " + "WHERE 1=0" ) ; } | Retrieves a description of the pseudo or hidden columns available in a given table within the specified catalog and schema . Pseudo or hidden columns may not always be stored within a table and are not visible in a ResultSet unless they are specified in the query s outermost SELECT list . Pseudo or hidden columns may not necessarily be able to be modified . If there are no pseudo or hidden columns an empty ResultSet is returned . | 155 | 86 |
29,544 | public String getDatabaseProductName ( ) throws SQLException { if ( urlParser . getOptions ( ) . useMysqlMetadata ) { return "MySQL" ; } if ( connection . getProtocol ( ) . isServerMariaDb ( ) && connection . getProtocol ( ) . getServerVersion ( ) . toLowerCase ( Locale . ROOT ) . contains ( "mariadb" ) ) { return "MariaDB" ; } return "MySQL" ; } | Return Server type . MySQL or MariaDB . MySQL can be forced for compatibility with option useMysqlMetadata | 106 | 23 |
29,545 | public ResultSet getVersionColumns ( String catalog , String schema , String table ) throws SQLException { String sql = "SELECT 0 SCOPE, ' ' COLUMN_NAME, 0 DATA_TYPE," + " ' ' TYPE_NAME, 0 COLUMN_SIZE, 0 BUFFER_LENGTH," + " 0 DECIMAL_DIGITS, 0 PSEUDO_COLUMN " + " FROM DUAL WHERE 1 = 0" ; return executeQuery ( sql ) ; } | Retrieves a description of a table s columns that are automatically updated when any value in a row is updated . They are unordered . | 107 | 28 |
29,546 | public static SSLSocketFactory getSslSocketFactory ( Options options ) throws SQLException { TrustManager [ ] trustManager = null ; KeyManager [ ] keyManager = null ; if ( options . trustServerCertificate || options . serverSslCert != null || options . trustStore != null ) { trustManager = new X509TrustManager [ ] { new MariaDbX509TrustManager ( options ) } ; } if ( options . keyStore != null ) { keyManager = new KeyManager [ ] { loadClientCerts ( options . keyStore , options . keyStorePassword , options . keyPassword , options . keyStoreType ) } ; } else { String keyStore = System . getProperty ( "javax.net.ssl.keyStore" ) ; String keyStorePassword = System . getProperty ( "javax.net.ssl.keyStorePassword" ) ; if ( keyStore != null ) { try { keyManager = new KeyManager [ ] { loadClientCerts ( keyStore , keyStorePassword , keyStorePassword , options . keyStoreType ) } ; } catch ( SQLException queryException ) { keyManager = null ; logger . error ( "Error loading keymanager from system properties" , queryException ) ; } } } try { SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( keyManager , trustManager , null ) ; return sslContext . getSocketFactory ( ) ; } catch ( KeyManagementException keyManagementEx ) { throw ExceptionMapper . connException ( "Could not initialize SSL context" , keyManagementEx ) ; } catch ( NoSuchAlgorithmException noSuchAlgorithmEx ) { throw ExceptionMapper . connException ( "SSLContext TLS Algorithm not unknown" , noSuchAlgorithmEx ) ; } } | Create an SSL factory according to connection string options . | 388 | 10 |
29,547 | @ Override public void clearBatch ( ) { parameterList . clear ( ) ; hasLongData = false ; this . parameters = new ParameterHolder [ prepareResult . getParamCount ( ) ] ; } | Clear batch . | 45 | 3 |
29,548 | private void executeInternalBatch ( int size ) throws SQLException { executeQueryPrologue ( true ) ; results = new Results ( this , 0 , true , size , false , resultSetScrollType , resultSetConcurrency , autoGeneratedKeys , protocol . getAutoIncrementIncrement ( ) ) ; if ( protocol . executeBatchClient ( protocol . isMasterConnection ( ) , results , prepareResult , parameterList , hasLongData ) ) { return ; } //send query one by one, reading results for each query before sending another one SQLException exception = null ; if ( queryTimeout > 0 ) { for ( int batchQueriesCount = 0 ; batchQueriesCount < size ; batchQueriesCount ++ ) { protocol . stopIfInterrupted ( ) ; try { protocol . executeQuery ( protocol . isMasterConnection ( ) , results , prepareResult , parameterList . get ( batchQueriesCount ) ) ; } catch ( SQLException e ) { if ( options . continueBatchOnError ) { exception = e ; } else { throw e ; } } } } else { for ( int batchQueriesCount = 0 ; batchQueriesCount < size ; batchQueriesCount ++ ) { try { protocol . executeQuery ( protocol . isMasterConnection ( ) , results , prepareResult , parameterList . get ( batchQueriesCount ) ) ; } catch ( SQLException e ) { if ( options . continueBatchOnError ) { exception = e ; } else { throw e ; } } } } if ( exception != null ) { throw exception ; } } | Choose better way to execute queries according to query and options . | 338 | 12 |
29,549 | public void setParameter ( final int parameterIndex , final ParameterHolder holder ) throws SQLException { if ( parameterIndex >= 1 && parameterIndex < prepareResult . getParamCount ( ) + 1 ) { parameters [ parameterIndex - 1 ] = holder ; } else { String error = "Could not set parameter at position " + parameterIndex + " (values was " + holder . toString ( ) + ")\n" + "Query - conn:" + protocol . getServerThreadId ( ) + "(" + ( protocol . isMasterConnection ( ) ? "M" : "S" ) + ") " ; if ( options . maxQuerySizeToLog > 0 ) { error += " - \"" ; if ( sqlQuery . length ( ) < options . maxQuerySizeToLog ) { error += sqlQuery ; } else { error += sqlQuery . substring ( 0 , options . maxQuerySizeToLog ) + "..." ; } error += "\"" ; } else { error += " - \"" + sqlQuery + "\"" ; } logger . error ( error ) ; throw ExceptionMapper . getSqlException ( error ) ; } } | Set parameter . | 246 | 3 |
29,550 | @ Override public void close ( ) throws SQLException { super . close ( ) ; if ( connection == null || connection . pooledConnection == null || connection . pooledConnection . noStmtEventListeners ( ) ) { return ; } connection . pooledConnection . fireStatementClosed ( this ) ; connection = null ; } | Close prepared statement maybe fire closed - statement events | 69 | 9 |
29,551 | public void writeEmptyPacket ( ) throws IOException { buf [ 0 ] = ( byte ) 4 ; buf [ 1 ] = ( byte ) 0x00 ; buf [ 2 ] = ( byte ) 0x00 ; buf [ 3 ] = ( byte ) this . compressSeqNo ++ ; buf [ 4 ] = ( byte ) 0x00 ; buf [ 5 ] = ( byte ) 0x00 ; buf [ 6 ] = ( byte ) 0x00 ; buf [ 7 ] = ( byte ) 0x00 ; buf [ 8 ] = ( byte ) 0x00 ; buf [ 9 ] = ( byte ) 0x00 ; buf [ 10 ] = ( byte ) this . seqNo ++ ; out . write ( buf , 0 , 11 ) ; if ( traceCache != null ) { traceCache . put ( new TraceObject ( true , COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET , Arrays . copyOfRange ( buf , 0 , 11 ) ) ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "send uncompress:{}{}" , serverThreadLog , Utils . hexdump ( maxQuerySizeToLog , 0 , 11 , buf ) ) ; } } | Write an empty packet . | 264 | 5 |
29,552 | public static AuthenticationPlugin processAuthPlugin ( String plugin , String password , byte [ ] authData , Options options ) throws SQLException { switch ( plugin ) { case MYSQL_NATIVE_PASSWORD : return new NativePasswordPlugin ( password , authData , options . passwordCharacterEncoding ) ; case MYSQL_OLD_PASSWORD : return new OldPasswordPlugin ( password , authData ) ; case MYSQL_CLEAR_PASSWORD : return new ClearPasswordPlugin ( password , options . passwordCharacterEncoding ) ; case DIALOG : return new SendPamAuthPacket ( password , authData , options . passwordCharacterEncoding ) ; case GSSAPI_CLIENT : return new SendGssApiAuthPacket ( authData , options . servicePrincipalName ) ; case MYSQL_ED25519_PASSWORD : return new Ed25519PasswordPlugin ( password , authData , options . passwordCharacterEncoding ) ; default : throw new SQLException ( "Client does not support authentication protocol requested by server. " + "Consider upgrading MariaDB client. plugin was = " + plugin , "08004" , 1251 ) ; } } | Process AuthenticationSwitch . | 254 | 4 |
29,553 | private static void searchProbableMaster ( AuroraListener listener , final GlobalStateInfo globalInfo , HostAddress probableMaster ) { AuroraProtocol protocol = getNewProtocol ( listener . getProxy ( ) , globalInfo , listener . getUrlParser ( ) ) ; try { protocol . setHostAddress ( probableMaster ) ; protocol . connect ( ) ; listener . removeFromBlacklist ( protocol . getHostAddress ( ) ) ; if ( listener . isMasterHostFailReconnect ( ) && protocol . isMasterConnection ( ) ) { protocol . setMustBeMasterConnection ( true ) ; listener . foundActiveMaster ( protocol ) ; } else if ( listener . isSecondaryHostFailReconnect ( ) && ! protocol . isMasterConnection ( ) ) { protocol . setMustBeMasterConnection ( false ) ; listener . foundActiveSecondary ( protocol ) ; } else { protocol . close ( ) ; protocol = getNewProtocol ( listener . getProxy ( ) , globalInfo , listener . getUrlParser ( ) ) ; } } catch ( SQLException e ) { listener . addToBlacklist ( protocol . getHostAddress ( ) ) ; } } | Connect aurora probable master . Aurora master change in time . The only way to check that a server is a master is to asked him . | 243 | 28 |
29,554 | public static AuroraProtocol getNewProtocol ( FailoverProxy proxy , final GlobalStateInfo globalInfo , UrlParser urlParser ) { AuroraProtocol newProtocol = new AuroraProtocol ( urlParser , globalInfo , proxy . lock ) ; newProtocol . setProxy ( proxy ) ; return newProtocol ; } | Initialize new protocol instance . | 68 | 6 |
29,555 | @ Override public void reset ( ) { insertIds . clear ( ) ; updateCounts . clear ( ) ; insertIdNumber = 0 ; hasException = false ; rewritten = false ; } | Clear error state used for clear exception after first batch query when fall back to per - query execution . | 41 | 20 |
29,556 | private boolean readNextValue ( ) throws IOException , SQLException { byte [ ] buf = reader . getPacketArray ( false ) ; //is error Packet if ( buf [ 0 ] == ERROR ) { protocol . removeActiveStreamingResult ( ) ; protocol . removeHasMoreResults ( ) ; protocol . setHasWarnings ( false ) ; ErrorPacket errorPacket = new ErrorPacket ( new Buffer ( buf ) ) ; resetVariables ( ) ; throw ExceptionMapper . get ( errorPacket . getMessage ( ) , errorPacket . getSqlState ( ) , errorPacket . getErrorNumber ( ) , null , false ) ; } //is end of stream if ( buf [ 0 ] == EOF && ( ( eofDeprecated && buf . length < 0xffffff ) || ( ! eofDeprecated && buf . length < 8 ) ) ) { int serverStatus ; int warnings ; if ( ! eofDeprecated ) { //EOF_Packet warnings = ( buf [ 1 ] & 0xff ) + ( ( buf [ 2 ] & 0xff ) << 8 ) ; serverStatus = ( ( buf [ 3 ] & 0xff ) + ( ( buf [ 4 ] & 0xff ) << 8 ) ) ; //CallableResult has been read from intermediate EOF server_status //and is mandatory because : // // - Call query will have an callable resultSet for OUT parameters // this resultSet must be identified and not listed in JDBC statement.getResultSet() // // - after a callable resultSet, a OK packet is send, // but mysql before 5.7.4 doesn't send MORE_RESULTS_EXISTS flag if ( callableResult ) { serverStatus |= MORE_RESULTS_EXISTS ; } } else { //OK_Packet with a 0xFE header int pos = skipLengthEncodedValue ( buf , 1 ) ; //skip update count pos = skipLengthEncodedValue ( buf , pos ) ; //skip insert id serverStatus = ( ( buf [ pos ++ ] & 0xff ) + ( ( buf [ pos ++ ] & 0xff ) << 8 ) ) ; warnings = ( buf [ pos ++ ] & 0xff ) + ( ( buf [ pos ] & 0xff ) << 8 ) ; callableResult = ( serverStatus & PS_OUT_PARAMETERS ) != 0 ; } protocol . setServerStatus ( ( short ) serverStatus ) ; protocol . setHasWarnings ( warnings > 0 ) ; if ( ( serverStatus & MORE_RESULTS_EXISTS ) == 0 ) { protocol . removeActiveStreamingResult ( ) ; } resetVariables ( ) ; return false ; } //this is a result-set row, save it if ( dataSize + 1 >= data . length ) { growDataArray ( ) ; } data [ dataSize ++ ] = buf ; return true ; } | Read next value . | 615 | 4 |
29,557 | protected void deleteCurrentRowData ( ) throws SQLException { //move data System . arraycopy ( data , rowPointer + 1 , data , rowPointer , dataSize - 1 - rowPointer ) ; data [ dataSize - 1 ] = null ; dataSize -- ; lastRowPointer = - 1 ; previous ( ) ; } | Delete current data . Position cursor to the previous row . | 73 | 11 |
29,558 | public void close ( ) throws SQLException { isClosed = true ; if ( ! isEof ) { lock . lock ( ) ; try { while ( ! isEof ) { dataSize = 0 ; //to avoid storing data readNextValue ( ) ; } } catch ( SQLException queryException ) { throw ExceptionMapper . getException ( queryException , null , this . statement , false ) ; } catch ( IOException ioe ) { throw handleIoException ( ioe ) ; } finally { resetVariables ( ) ; lock . unlock ( ) ; } } resetVariables ( ) ; //keep garbage easy for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = null ; } if ( statement != null ) { statement . checkCloseOnCompletion ( this ) ; statement = null ; } } | Close resultSet . | 184 | 4 |
29,559 | private int nameToIndex ( String parameterName ) throws SQLException { parameterMetadata . readMetadataFromDbIfRequired ( ) ; for ( int i = 1 ; i <= parameterMetadata . getParameterCount ( ) ; i ++ ) { String name = parameterMetadata . getName ( i ) ; if ( name != null && name . equalsIgnoreCase ( parameterName ) ) { return i ; } } throw new SQLException ( "there is no parameter with the name " + parameterName ) ; } | Convert parameter name to parameter index in the query . | 111 | 11 |
29,560 | private int nameToOutputIndex ( String parameterName ) throws SQLException { parameterMetadata . readMetadataFromDbIfRequired ( ) ; for ( int i = 0 ; i < parameterMetadata . getParameterCount ( ) ; i ++ ) { String name = parameterMetadata . getName ( i + 1 ) ; if ( name != null && name . equalsIgnoreCase ( parameterName ) ) { if ( outputParameterMapper [ i ] == - 1 ) { //this is not an outputParameter throw new SQLException ( "Parameter '" + parameterName + "' is not declared as output parameter with method registerOutParameter" ) ; } return outputParameterMapper [ i ] ; } } throw new SQLException ( "there is no parameter with the name " + parameterName ) ; } | Convert parameter name to output parameter index in the query . | 172 | 12 |
29,561 | private int indexToOutputIndex ( int parameterIndex ) throws SQLException { try { if ( outputParameterMapper [ parameterIndex - 1 ] == - 1 ) { //this is not an outputParameter throw new SQLException ( "Parameter in index '" + parameterIndex + "' is not declared as output parameter with method registerOutParameter" ) ; } return outputParameterMapper [ parameterIndex - 1 ] ; } catch ( ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException ) { if ( parameterIndex < 1 ) { throw new SQLException ( "Index " + parameterIndex + " must at minimum be 1" ) ; } throw new SQLException ( "Index value '" + parameterIndex + "' is incorrect. Maximum value is " + params . size ( ) ) ; } } | Convert parameter index to corresponding outputIndex . | 173 | 9 |
29,562 | public void writeTo ( PacketOutputStream pos ) throws IOException { pos . write ( QUOTE ) ; if ( length == Long . MAX_VALUE ) { pos . write ( reader , true , noBackslashEscapes ) ; } else { pos . write ( reader , length , true , noBackslashEscapes ) ; } pos . write ( QUOTE ) ; } | Write reader to database in text format . | 81 | 8 |
29,563 | @ Override public void reset ( ) throws SQLException { cmdPrologue ( ) ; try { writer . startPacket ( 0 ) ; writer . write ( COM_RESET_CONNECTION ) ; writer . flush ( ) ; getResult ( new Results ( ) ) ; //clear prepare statement cache if ( options . cachePrepStmts && options . useServerPrepStmts ) { serverPrepareStatementCache . clear ( ) ; } } catch ( SQLException sqlException ) { throw logQuery . exceptionWithQuery ( "COM_RESET_CONNECTION failed." , sqlException , explicitClosed ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } } | Reset connection state . | 155 | 5 |
29,564 | @ Override public void executeQuery ( boolean mustExecuteOnMaster , Results results , final String sql ) throws SQLException { cmdPrologue ( ) ; try { writer . startPacket ( 0 ) ; writer . write ( COM_QUERY ) ; writer . write ( sql ) ; writer . flush ( ) ; getResult ( results ) ; } catch ( SQLException sqlException ) { if ( "70100" . equals ( sqlException . getSQLState ( ) ) && 1927 == sqlException . getErrorCode ( ) ) { throw handleIoException ( sqlException ) ; } throw logQuery . exceptionWithQuery ( sql , sqlException , explicitClosed ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } } | Execute query directly to outputStream . | 165 | 8 |
29,565 | public void executeQuery ( boolean mustExecuteOnMaster , Results results , final ClientPrepareResult clientPrepareResult , ParameterHolder [ ] parameters ) throws SQLException { cmdPrologue ( ) ; try { if ( clientPrepareResult . getParamCount ( ) == 0 && ! clientPrepareResult . isQueryMultiValuesRewritable ( ) ) { if ( clientPrepareResult . getQueryParts ( ) . size ( ) == 1 ) { ComQuery . sendDirect ( writer , clientPrepareResult . getQueryParts ( ) . get ( 0 ) ) ; } else { ComQuery . sendMultiDirect ( writer , clientPrepareResult . getQueryParts ( ) ) ; } } else { writer . startPacket ( 0 ) ; ComQuery . sendSubCmd ( writer , clientPrepareResult , parameters , - 1 ) ; writer . flush ( ) ; } getResult ( results ) ; } catch ( SQLException queryException ) { throw logQuery . exceptionWithQuery ( parameters , queryException , clientPrepareResult ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } } | Execute a unique clientPrepareQuery . | 244 | 9 |
29,566 | private void executeBatch ( Results results , final List < String > queries ) throws SQLException { if ( ! options . useBatchMultiSend ) { String sql = null ; SQLException exception = null ; for ( int i = 0 ; i < queries . size ( ) && ! isInterrupted ( ) ; i ++ ) { try { sql = queries . get ( i ) ; writer . startPacket ( 0 ) ; writer . write ( COM_QUERY ) ; writer . write ( sql ) ; writer . flush ( ) ; getResult ( results ) ; } catch ( SQLException sqlException ) { if ( exception == null ) { exception = logQuery . exceptionWithQuery ( sql , sqlException , explicitClosed ) ; if ( ! options . continueBatchOnError ) { throw exception ; } } } catch ( IOException e ) { if ( exception == null ) { exception = handleIoException ( e ) ; if ( ! options . continueBatchOnError ) { throw exception ; } } } } stopIfInterrupted ( ) ; if ( exception != null ) { throw exception ; } return ; } initializeBatchReader ( ) ; new AbstractMultiSend ( this , writer , results , queries ) { @ Override public void sendCmd ( PacketOutputStream pos , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int paramCount , BulkStatus status , PrepareResult prepareResult ) throws IOException { String sql = queries . get ( status . sendCmdCounter ) ; pos . startPacket ( 0 ) ; pos . write ( COM_QUERY ) ; pos . write ( sql ) ; pos . flush ( ) ; } @ Override public SQLException handleResultException ( SQLException qex , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int currentCounter , int sendCmdCounter , int paramCount , PrepareResult prepareResult ) { String sql = queries . get ( currentCounter + sendCmdCounter ) ; return logQuery . exceptionWithQuery ( sql , qex , explicitClosed ) ; } @ Override public int getParamCount ( ) { return - 1 ; } @ Override public int getTotalExecutionNumber ( ) { return queries . size ( ) ; } } . executeBatch ( ) ; } | Execute list of queries not rewritable . | 500 | 10 |
29,567 | @ Override public ServerPrepareResult prepare ( String sql , boolean executeOnMaster ) throws SQLException { cmdPrologue ( ) ; lock . lock ( ) ; try { if ( options . cachePrepStmts && options . useServerPrepStmts ) { ServerPrepareResult pr = serverPrepareStatementCache . get ( database + "-" + sql ) ; if ( pr != null && pr . incrementShareCounter ( ) ) { return pr ; } } writer . startPacket ( 0 ) ; writer . write ( COM_STMT_PREPARE ) ; writer . write ( sql ) ; writer . flush ( ) ; ComStmtPrepare comStmtPrepare = new ComStmtPrepare ( this , sql ) ; return comStmtPrepare . read ( reader , eofDeprecated ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } finally { lock . unlock ( ) ; } } | 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 . | 205 | 28 |
29,568 | private void executeBatchRewrite ( Results results , final ClientPrepareResult prepareResult , List < ParameterHolder [ ] > parameterList , boolean rewriteValues ) throws SQLException { cmdPrologue ( ) ; ParameterHolder [ ] parameters ; int currentIndex = 0 ; int totalParameterList = parameterList . size ( ) ; try { do { currentIndex = ComQuery . sendRewriteCmd ( writer , prepareResult . getQueryParts ( ) , currentIndex , prepareResult . getParamCount ( ) , parameterList , rewriteValues ) ; getResult ( results ) ; if ( Thread . currentThread ( ) . isInterrupted ( ) ) { throw new SQLException ( "Interrupted during batch" , INTERRUPTED_EXCEPTION . getSqlState ( ) , - 1 ) ; } } while ( currentIndex < totalParameterList ) ; } catch ( SQLException sqlEx ) { throw logQuery . exceptionWithQuery ( sqlEx , prepareResult ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } finally { results . setRewritten ( rewriteValues ) ; } } | Specific execution for batch rewrite that has specific query for memory . | 245 | 12 |
29,569 | public boolean executeBatchServer ( boolean mustExecuteOnMaster , ServerPrepareResult serverPrepareResult , Results results , String sql , final List < ParameterHolder [ ] > parametersList , boolean hasLongData ) throws SQLException { cmdPrologue ( ) ; if ( options . useBulkStmts && ! hasLongData && results . getAutoGeneratedKeys ( ) == Statement . NO_GENERATED_KEYS && versionGreaterOrEqual ( 10 , 2 , 7 ) && executeBulkBatch ( results , sql , serverPrepareResult , parametersList ) ) { return true ; } if ( ! options . useBatchMultiSend ) { return false ; } initializeBatchReader ( ) ; new AbstractMultiSend ( this , writer , results , serverPrepareResult , parametersList , true , sql ) { @ Override public void sendCmd ( PacketOutputStream writer , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int paramCount , BulkStatus status , PrepareResult prepareResult ) throws SQLException , IOException { ParameterHolder [ ] parameters = parametersList . get ( status . sendCmdCounter ) ; //validate parameter set if ( parameters . length < paramCount ) { throw new SQLException ( "Parameter at position " + ( paramCount - 1 ) + " is not set" , "07004" ) ; } //send binary data in a separate stream for ( int i = 0 ; i < paramCount ; i ++ ) { if ( parameters [ i ] . isLongData ( ) ) { writer . startPacket ( 0 ) ; writer . write ( COM_STMT_SEND_LONG_DATA ) ; writer . writeInt ( statementId ) ; writer . writeShort ( ( short ) i ) ; parameters [ i ] . writeBinary ( writer ) ; writer . flush ( ) ; } } writer . startPacket ( 0 ) ; ComStmtExecute . writeCmd ( statementId , parameters , paramCount , parameterTypeHeader , writer , CURSOR_TYPE_NO_CURSOR ) ; writer . flush ( ) ; } @ Override public SQLException handleResultException ( SQLException qex , Results results , List < ParameterHolder [ ] > parametersList , List < String > queries , int currentCounter , int sendCmdCounter , int paramCount , PrepareResult prepareResult ) { return logQuery . exceptionWithQuery ( qex , prepareResult ) ; } @ Override public int getParamCount ( ) { return getPrepareResult ( ) == null ? parametersList . get ( 0 ) . length : ( ( ServerPrepareResult ) getPrepareResult ( ) ) . getParameters ( ) . length ; } @ Override public int getTotalExecutionNumber ( ) { return parametersList . size ( ) ; } } . executeBatch ( ) ; return true ; } | Execute Prepare if needed and execute COM_STMT_EXECUTE queries in batch . | 629 | 19 |
29,570 | @ Override public void executePreparedQuery ( boolean mustExecuteOnMaster , ServerPrepareResult serverPrepareResult , Results results , ParameterHolder [ ] parameters ) throws SQLException { cmdPrologue ( ) ; try { int parameterCount = serverPrepareResult . getParameters ( ) . length ; //send binary data in a separate stream for ( int i = 0 ; i < parameterCount ; i ++ ) { if ( parameters [ i ] . isLongData ( ) ) { writer . startPacket ( 0 ) ; writer . write ( COM_STMT_SEND_LONG_DATA ) ; writer . writeInt ( serverPrepareResult . getStatementId ( ) ) ; writer . writeShort ( ( short ) i ) ; parameters [ i ] . writeBinary ( writer ) ; writer . flush ( ) ; } } //send execute query ComStmtExecute . send ( writer , serverPrepareResult . getStatementId ( ) , parameters , parameterCount , serverPrepareResult . getParameterTypeHeader ( ) , CURSOR_TYPE_NO_CURSOR ) ; getResult ( results ) ; } catch ( SQLException qex ) { throw logQuery . exceptionWithQuery ( parameters , qex , serverPrepareResult ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } } | Execute a query that is already prepared . | 293 | 9 |
29,571 | public void rollback ( ) throws SQLException { cmdPrologue ( ) ; lock . lock ( ) ; try { if ( inTransaction ( ) ) { executeQuery ( "ROLLBACK" ) ; } } catch ( Exception e ) { /* eat exception */ } finally { lock . unlock ( ) ; } } | Rollback transaction . | 68 | 4 |
29,572 | public boolean forceReleasePrepareStatement ( int statementId ) throws SQLException { if ( lock . tryLock ( ) ) { try { checkClose ( ) ; try { writer . startPacket ( 0 ) ; writer . write ( COM_STMT_CLOSE ) ; writer . writeInt ( statementId ) ; writer . flush ( ) ; return true ; } catch ( IOException e ) { connected = false ; throw new SQLException ( "Could not deallocate query: " + e . getMessage ( ) , CONNECTION_EXCEPTION . getSqlState ( ) , e ) ; } } finally { lock . unlock ( ) ; } } else { //lock is used by another thread (bulk reading) statementIdToRelease = statementId ; } return false ; } | Force release of prepare statement that are not used . This method will be call when adding a new prepare statement in cache so the packet can be send to server without problem . | 169 | 34 |
29,573 | @ Override public void cancelCurrentQuery ( ) throws SQLException { try ( MasterProtocol copiedProtocol = new MasterProtocol ( urlParser , new GlobalStateInfo ( ) , new ReentrantLock ( ) ) ) { copiedProtocol . setHostAddress ( getHostAddress ( ) ) ; copiedProtocol . connect ( ) ; //no lock, because there is already a query running that possessed the lock. copiedProtocol . executeQuery ( "KILL QUERY " + serverThreadId ) ; } interrupted = true ; } | Cancels the current query - clones the current protocol and executes a query using the new connection . | 114 | 20 |
29,574 | @ Override public void releasePrepareStatement ( ServerPrepareResult serverPrepareResult ) throws SQLException { //If prepared cache is enable, the ServerPrepareResult can be shared in many PrepStatement, //so synchronised use count indicator will be decrement. serverPrepareResult . decrementShareCounter ( ) ; //deallocate from server if not cached if ( serverPrepareResult . canBeDeallocate ( ) ) { forceReleasePrepareStatement ( serverPrepareResult . getStatementId ( ) ) ; } } | Deallocate prepare statement if not used anymore . | 114 | 10 |
29,575 | @ Override public void setTimeout ( int timeout ) throws SocketException { lock . lock ( ) ; try { this . socket . setSoTimeout ( timeout ) ; } finally { lock . unlock ( ) ; } } | Sets the connection timeout . | 45 | 6 |
29,576 | public void setTransactionIsolation ( final int level ) throws SQLException { cmdPrologue ( ) ; lock . lock ( ) ; try { String query = "SET SESSION TRANSACTION ISOLATION LEVEL" ; switch ( level ) { case Connection . TRANSACTION_READ_UNCOMMITTED : query += " READ UNCOMMITTED" ; break ; case Connection . TRANSACTION_READ_COMMITTED : query += " READ COMMITTED" ; break ; case Connection . TRANSACTION_REPEATABLE_READ : query += " REPEATABLE READ" ; break ; case Connection . TRANSACTION_SERIALIZABLE : query += " SERIALIZABLE" ; break ; default : throw new SQLException ( "Unsupported transaction isolation level" ) ; } executeQuery ( query ) ; transactionIsolationLevel = level ; } finally { lock . unlock ( ) ; } } | Set transaction isolation . | 193 | 4 |
29,577 | private void readPacket ( Results results ) throws SQLException { Buffer buffer ; try { buffer = reader . getPacket ( true ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } switch ( buffer . getByteAt ( 0 ) ) { //********************************************************************************************************* //* OK response //********************************************************************************************************* case OK : readOkPacket ( buffer , results ) ; break ; //********************************************************************************************************* //* ERROR response //********************************************************************************************************* case ERROR : throw readErrorPacket ( buffer , results ) ; //********************************************************************************************************* //* LOCAL INFILE response //********************************************************************************************************* case LOCAL_INFILE : readLocalInfilePacket ( buffer , results ) ; break ; //********************************************************************************************************* //* ResultSet //********************************************************************************************************* default : readResultSet ( buffer , results ) ; break ; } } | Read server response packet . | 193 | 5 |
29,578 | private void readOkPacket ( Buffer buffer , Results results ) { buffer . skipByte ( ) ; //fieldCount final long updateCount = buffer . getLengthEncodedNumeric ( ) ; final long insertId = buffer . getLengthEncodedNumeric ( ) ; serverStatus = buffer . readShort ( ) ; hasWarnings = ( buffer . readShort ( ) > 0 ) ; if ( ( serverStatus & ServerStatus . SERVER_SESSION_STATE_CHANGED ) != 0 ) { handleStateChange ( buffer , results ) ; } results . addStats ( updateCount , insertId , hasMoreResults ( ) ) ; } | Read OK_Packet . | 136 | 6 |
29,579 | private SQLException readErrorPacket ( Buffer buffer , Results results ) { removeHasMoreResults ( ) ; this . hasWarnings = false ; buffer . skipByte ( ) ; final int errorNumber = buffer . readShort ( ) ; String message ; String sqlState ; if ( buffer . readByte ( ) == ' ' ) { sqlState = new String ( buffer . readRawBytes ( 5 ) ) ; message = buffer . readStringNullEnd ( StandardCharsets . UTF_8 ) ; } else { // Pre-4.1 message, still can be output in newer versions (e.g with 'Too many connections') buffer . position -= 1 ; message = new String ( buffer . buf , buffer . position , buffer . limit - buffer . position , StandardCharsets . UTF_8 ) ; sqlState = "HY000" ; } results . addStatsError ( false ) ; //force current status to in transaction to ensure rollback/commit, since command may have issue a transaction serverStatus |= ServerStatus . IN_TRANSACTION ; removeActiveStreamingResult ( ) ; return new SQLException ( message , sqlState , errorNumber ) ; } | Read ERR_Packet . | 249 | 7 |
29,580 | private void readLocalInfilePacket ( Buffer buffer , Results results ) throws SQLException { int seq = 2 ; buffer . getLengthEncodedNumeric ( ) ; //field pos String fileName = buffer . readStringNullEnd ( StandardCharsets . UTF_8 ) ; try { // Server request the local file (LOCAL DATA LOCAL INFILE) // We do accept general URLs, too. If the localInfileStream is // set, use that. InputStream is ; writer . startPacket ( seq ) ; if ( localInfileInputStream == null ) { if ( ! getUrlParser ( ) . getOptions ( ) . allowLocalInfile ) { writer . writeEmptyPacket ( ) ; reader . getPacket ( true ) ; throw new SQLException ( "Usage of LOCAL INFILE is disabled. To use it enable it via the connection property allowLocalInfile=true" , FEATURE_NOT_SUPPORTED . getSqlState ( ) , - 1 ) ; } //validate all defined interceptors ServiceLoader < LocalInfileInterceptor > loader = ServiceLoader . load ( LocalInfileInterceptor . class ) ; for ( LocalInfileInterceptor interceptor : loader ) { if ( ! interceptor . validate ( fileName ) ) { writer . writeEmptyPacket ( ) ; reader . getPacket ( true ) ; throw new SQLException ( "LOCAL DATA LOCAL INFILE request to send local file named \"" + fileName + "\" not validated by interceptor \"" + interceptor . getClass ( ) . getName ( ) + "\"" ) ; } } try { URL url = new URL ( fileName ) ; is = url . openStream ( ) ; } catch ( IOException ioe ) { try { is = new FileInputStream ( fileName ) ; } catch ( FileNotFoundException f ) { writer . writeEmptyPacket ( ) ; reader . getPacket ( true ) ; throw new SQLException ( "Could not send file : " + f . getMessage ( ) , "22000" , - 1 , f ) ; } } } else { is = localInfileInputStream ; localInfileInputStream = null ; } try { byte [ ] buf = new byte [ 8192 ] ; int len ; while ( ( len = is . read ( buf ) ) > 0 ) { writer . startPacket ( seq ++ ) ; writer . write ( buf , 0 , len ) ; writer . flush ( ) ; } writer . writeEmptyPacket ( ) ; } catch ( IOException ioe ) { throw handleIoException ( ioe ) ; } finally { is . close ( ) ; } getResult ( results ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } } | Read Local_infile Packet . | 600 | 8 |
29,581 | private void readResultSet ( Buffer buffer , Results results ) throws SQLException { long fieldCount = buffer . getLengthEncodedNumeric ( ) ; try { //read columns information's ColumnInformation [ ] ci = new ColumnInformation [ ( int ) fieldCount ] ; for ( int i = 0 ; i < fieldCount ; i ++ ) { ci [ i ] = new ColumnInformation ( reader . getPacket ( false ) ) ; } boolean callableResult = false ; if ( ! eofDeprecated ) { //read EOF packet //EOF status is mandatory because : // - Call query will have an callable resultSet for OUT parameters // -> this resultSet must be identified and not listed in JDBC statement.getResultSet() // - after a callable resultSet, a OK packet is send, but mysql does send the a bad "more result flag" Buffer bufferEof = reader . getPacket ( true ) ; if ( bufferEof . readByte ( ) != EOF ) { //using IOException to close connection, throw new IOException ( "Packets out of order when reading field packets, expected was EOF stream." + ( ( options . enablePacketDebug ) ? getTraces ( ) : "Packet contents (hex) = " + Utils . hexdump ( options . maxQuerySizeToLog , 0 , bufferEof . limit , bufferEof . buf ) ) ) ; } bufferEof . skipBytes ( 2 ) ; //Skip warningCount callableResult = ( bufferEof . readShort ( ) & ServerStatus . PS_OUT_PARAMETERS ) != 0 ; } //read resultSet SelectResultSet selectResultSet ; if ( results . getResultSetConcurrency ( ) == ResultSet . CONCUR_READ_ONLY ) { selectResultSet = new SelectResultSet ( ci , results , this , reader , callableResult , eofDeprecated ) ; } else { //remove fetch size to permit updating results without creating new connection results . removeFetchSize ( ) ; selectResultSet = new UpdatableResultSet ( ci , results , this , reader , callableResult , eofDeprecated ) ; } results . addResultSet ( selectResultSet , hasMoreResults ( ) || results . getFetchSize ( ) > 0 ) ; } catch ( IOException e ) { throw handleIoException ( e ) ; } } | Read ResultSet Packet . | 512 | 6 |
29,582 | public void prolog ( long maxRows , boolean hasProxy , MariaDbConnection connection , MariaDbStatement statement ) throws SQLException { if ( explicitClosed ) { throw new SQLException ( "execute() is called on closed connection" ) ; } //old failover handling if ( ! hasProxy && shouldReconnectWithoutProxy ( ) ) { try { connectWithoutProxy ( ) ; } catch ( SQLException qe ) { ExceptionMapper . throwException ( qe , connection , statement ) ; } } try { setMaxRows ( maxRows ) ; } catch ( SQLException qe ) { ExceptionMapper . throwException ( qe , connection , statement ) ; } connection . reenableWarnings ( ) ; } | Preparation before command . | 163 | 6 |
29,583 | public SQLException handleIoException ( Exception initialException ) { boolean mustReconnect ; boolean driverPreventError = false ; if ( initialException instanceof MaxAllowedPacketException ) { mustReconnect = ( ( MaxAllowedPacketException ) initialException ) . isMustReconnect ( ) ; driverPreventError = ! mustReconnect ; } else { mustReconnect = writer . exceedMaxLength ( ) ; } if ( mustReconnect ) { try { connect ( ) ; } catch ( SQLException queryException ) { connected = false ; return new SQLNonTransientConnectionException ( initialException . getMessage ( ) + "\nError during reconnection" + getTraces ( ) , CONNECTION_EXCEPTION . getSqlState ( ) , initialException ) ; } try { resetStateAfterFailover ( getMaxRows ( ) , getTransactionIsolationLevel ( ) , getDatabase ( ) , getAutocommit ( ) ) ; } catch ( SQLException queryException ) { return new SQLException ( "reconnection succeed, but resetting previous state failed" , UNDEFINED_SQLSTATE . getSqlState ( ) + getTraces ( ) , initialException ) ; } return new SQLTransientConnectionException ( "Could not send query: query size is >= to max_allowed_packet (" + writer . getMaxAllowedPacket ( ) + ")" + getTraces ( ) , UNDEFINED_SQLSTATE . getSqlState ( ) , initialException ) ; } if ( ! driverPreventError ) { connected = false ; } return new SQLNonTransientConnectionException ( initialException . getMessage ( ) + getTraces ( ) , driverPreventError ? UNDEFINED_SQLSTATE . getSqlState ( ) : CONNECTION_EXCEPTION . getSqlState ( ) , initialException ) ; } | Handle IoException ( reconnect if Exception is due to having send too much data making server close the connection . | 415 | 21 |
29,584 | public void writeTo ( final PacketOutputStream pos ) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat ( "HH:mm:ss" ) ; sdf . setTimeZone ( timeZone ) ; String dateString = sdf . format ( time ) ; pos . write ( QUOTE ) ; pos . write ( dateString . getBytes ( ) ) ; int microseconds = ( int ) ( time . getTime ( ) % 1000 ) * 1000 ; if ( microseconds > 0 && fractionalSeconds ) { pos . write ( ' ' ) ; int factor = 100000 ; while ( microseconds > 0 ) { int dig = microseconds / factor ; pos . write ( ' ' + dig ) ; microseconds -= dig * factor ; factor /= 10 ; } } pos . write ( QUOTE ) ; } | Write Time parameter to outputStream . | 176 | 7 |
29,585 | public Connection connect ( final String url , final Properties props ) throws SQLException { UrlParser urlParser = UrlParser . parse ( url , props ) ; if ( urlParser == null || urlParser . getHostAddresses ( ) == null ) { return null ; } else { return MariaDbConnection . newConnection ( urlParser , null ) ; } } | Connect to the given connection string . | 77 | 7 |
29,586 | public DriverPropertyInfo [ ] getPropertyInfo ( String url , Properties info ) throws SQLException { if ( url != null ) { UrlParser urlParser = UrlParser . parse ( url , info ) ; if ( urlParser == null || urlParser . getOptions ( ) == null ) { return new DriverPropertyInfo [ 0 ] ; } List < DriverPropertyInfo > props = new ArrayList <> ( ) ; for ( DefaultOptions o : DefaultOptions . values ( ) ) { try { Field field = Options . class . getField ( o . getOptionName ( ) ) ; Object value = field . get ( urlParser . getOptions ( ) ) ; DriverPropertyInfo propertyInfo = new DriverPropertyInfo ( field . getName ( ) , value == null ? null : value . toString ( ) ) ; propertyInfo . description = o . getDescription ( ) ; propertyInfo . required = o . isRequired ( ) ; props . add ( propertyInfo ) ; } catch ( NoSuchFieldException | IllegalAccessException e ) { //eat error } } return props . toArray ( new DriverPropertyInfo [ props . size ( ) ] ) ; } return new DriverPropertyInfo [ 0 ] ; } | Get the property info . | 254 | 5 |
29,587 | @ Override public void initializeConnection ( ) throws SQLException { super . initializeConnection ( ) ; try { reconnectFailedConnection ( new SearchFilter ( true ) ) ; } catch ( SQLException e ) { //initializeConnection failed checkInitialConnection ( e ) ; } } | Initialize connections . | 61 | 4 |
29,588 | public void checkWaitingConnection ( ) throws SQLException { if ( isSecondaryHostFail ( ) ) { proxy . lock . lock ( ) ; try { Protocol waitingProtocol = waitNewSecondaryProtocol . getAndSet ( null ) ; if ( waitingProtocol != null && pingSecondaryProtocol ( waitingProtocol ) ) { lockAndSwitchSecondary ( waitingProtocol ) ; } } finally { proxy . lock . unlock ( ) ; } } if ( isMasterHostFail ( ) ) { proxy . lock . lock ( ) ; try { Protocol waitingProtocol = waitNewMasterProtocol . getAndSet ( null ) ; if ( waitingProtocol != null && pingMasterProtocol ( waitingProtocol ) ) { lockAndSwitchMaster ( waitingProtocol ) ; } } finally { proxy . lock . unlock ( ) ; } } } | Verify that there is waiting connection that have to replace failing one . If there is replace failed connection with new one . | 181 | 24 |
29,589 | public void reconnectFailedConnection ( SearchFilter searchFilter ) throws SQLException { if ( ! searchFilter . isInitialConnection ( ) && ( isExplicitClosed ( ) || ( searchFilter . isFineIfFoundOnlyMaster ( ) && ! isMasterHostFail ( ) ) || searchFilter . isFineIfFoundOnlySlave ( ) && ! isSecondaryHostFail ( ) ) ) { return ; } //check if a connection has been retrieved by failoverLoop during lock if ( ! searchFilter . isFailoverLoop ( ) ) { try { checkWaitingConnection ( ) ; if ( ( searchFilter . isFineIfFoundOnlyMaster ( ) && ! isMasterHostFail ( ) ) || searchFilter . isFineIfFoundOnlySlave ( ) && ! isSecondaryHostFail ( ) ) { return ; } } catch ( ReconnectDuringTransactionException e ) { //don't throw an exception for this specific exception return ; } } currentConnectionAttempts . incrementAndGet ( ) ; resetOldsBlackListHosts ( ) ; //put the list in the following order // - random order not blacklist and not connected host // - random order blacklist host // - connected host List < HostAddress > loopAddress = new LinkedList <> ( urlParser . getHostAddresses ( ) ) ; loopAddress . removeAll ( getBlacklistKeys ( ) ) ; Collections . shuffle ( loopAddress ) ; List < HostAddress > blacklistShuffle = new LinkedList <> ( getBlacklistKeys ( ) ) ; blacklistShuffle . retainAll ( urlParser . getHostAddresses ( ) ) ; Collections . shuffle ( blacklistShuffle ) ; loopAddress . addAll ( blacklistShuffle ) ; //put connected at end if ( masterProtocol != null && ! isMasterHostFail ( ) ) { loopAddress . remove ( masterProtocol . getHostAddress ( ) ) ; loopAddress . add ( masterProtocol . getHostAddress ( ) ) ; } if ( secondaryProtocol != null && ! isSecondaryHostFail ( ) ) { loopAddress . remove ( secondaryProtocol . getHostAddress ( ) ) ; loopAddress . add ( secondaryProtocol . getHostAddress ( ) ) ; } if ( ( isMasterHostFail ( ) || isSecondaryHostFail ( ) ) || searchFilter . isInitialConnection ( ) ) { //while permit to avoid case when succeeded creating a new Master connection //and ping master connection fail a few millissecond after, //resulting a masterConnection not initialized. do { MastersSlavesProtocol . loop ( this , globalInfo , loopAddress , searchFilter ) ; //close loop if all connection are retrieved if ( ! searchFilter . isFailoverLoop ( ) ) { try { checkWaitingConnection ( ) ; } catch ( ReconnectDuringTransactionException e ) { //don't throw an exception for this specific exception } } } while ( searchFilter . isInitialConnection ( ) && ! ( masterProtocol != null || ( urlParser . getOptions ( ) . allowMasterDownConnection && secondaryProtocol != null ) ) ) ; if ( searchFilter . isInitialConnection ( ) && masterProtocol == null && currentReadOnlyAsked ) { currentProtocol = this . secondaryProtocol ; currentReadOnlyAsked = true ; } } } | Loop to connect . | 690 | 4 |
29,590 | public void foundActiveMaster ( Protocol newMasterProtocol ) { if ( isMasterHostFail ( ) ) { if ( isExplicitClosed ( ) ) { newMasterProtocol . close ( ) ; return ; } if ( ! waitNewMasterProtocol . compareAndSet ( null , newMasterProtocol ) ) { newMasterProtocol . close ( ) ; } } else { newMasterProtocol . close ( ) ; } } | Method called when a new Master connection is found after a fallback . | 92 | 14 |
29,591 | public void lockAndSwitchMaster ( Protocol newMasterProtocol ) throws ReconnectDuringTransactionException { if ( masterProtocol != null && ! masterProtocol . isClosed ( ) ) { masterProtocol . close ( ) ; } if ( ! currentReadOnlyAsked || isSecondaryHostFail ( ) ) { //actually on a secondary read-only because master was unknown. //So select master as currentConnection if ( currentProtocol != null ) { try { syncConnection ( currentProtocol , newMasterProtocol ) ; } catch ( Exception e ) { //Some error append during connection parameter synchronisation } } //switching current connection to master connection currentProtocol = newMasterProtocol ; } boolean inTransaction = this . masterProtocol != null && this . masterProtocol . inTransaction ( ) ; this . masterProtocol = newMasterProtocol ; resetMasterFailoverData ( ) ; if ( inTransaction ) { //master connection was down, so has been change for a new active connection //problem was there was an active connection -> must throw exception so client known it throw new ReconnectDuringTransactionException ( "Connection reconnect automatically during an active transaction" , 1401 , "25S03" ) ; } } | Use the parameter newMasterProtocol as new current master connection . | 255 | 13 |
29,592 | public void foundActiveSecondary ( Protocol newSecondaryProtocol ) throws SQLException { if ( isSecondaryHostFail ( ) ) { if ( isExplicitClosed ( ) ) { newSecondaryProtocol . close ( ) ; return ; } if ( proxy . lock . tryLock ( ) ) { try { lockAndSwitchSecondary ( newSecondaryProtocol ) ; } finally { proxy . lock . unlock ( ) ; } } else { if ( ! waitNewSecondaryProtocol . compareAndSet ( null , newSecondaryProtocol ) ) { newSecondaryProtocol . close ( ) ; } } } else { newSecondaryProtocol . close ( ) ; } } | Method called when a new secondary connection is found after a fallback . | 148 | 14 |
29,593 | public void lockAndSwitchSecondary ( Protocol newSecondaryProtocol ) throws SQLException { if ( secondaryProtocol != null && ! secondaryProtocol . isClosed ( ) ) { secondaryProtocol . close ( ) ; } //if asked to be on read only connection, switching to this new connection if ( currentReadOnlyAsked || ( urlParser . getOptions ( ) . failOnReadOnly && ! currentReadOnlyAsked && isMasterHostFail ( ) ) ) { if ( currentProtocol == null ) { try { syncConnection ( currentProtocol , newSecondaryProtocol ) ; } catch ( Exception e ) { //Some error append during connection parameter synchronisation } } currentProtocol = newSecondaryProtocol ; } //set new found connection as slave connection. this . secondaryProtocol = newSecondaryProtocol ; if ( urlParser . getOptions ( ) . assureReadOnly ) { setSessionReadOnly ( true , this . secondaryProtocol ) ; } resetSecondaryFailoverData ( ) ; } | Use the parameter newSecondaryProtocol as new current secondary connection . | 216 | 14 |
29,594 | public HandleErrorResult primaryFail ( Method method , Object [ ] args , boolean killCmd ) { boolean alreadyClosed = masterProtocol == null || ! masterProtocol . isConnected ( ) ; boolean inTransaction = masterProtocol != null && masterProtocol . inTransaction ( ) ; //in case of SocketTimeoutException due to having set socketTimeout, must force connection close if ( masterProtocol != null && masterProtocol . isConnected ( ) ) { masterProtocol . close ( ) ; } //fail on slave if parameter permit so if ( urlParser . getOptions ( ) . failOnReadOnly && ! isSecondaryHostFail ( ) ) { try { if ( this . secondaryProtocol != null && this . secondaryProtocol . ping ( ) ) { //switching to secondary connection proxy . lock . lock ( ) ; try { if ( masterProtocol != null ) { syncConnection ( masterProtocol , this . secondaryProtocol ) ; } currentProtocol = this . secondaryProtocol ; } finally { proxy . lock . unlock ( ) ; } FailoverLoop . addListener ( this ) ; try { return relaunchOperation ( method , args ) ; } catch ( Exception e ) { //relaunchOperation failed } return new HandleErrorResult ( ) ; } } catch ( Exception e ) { if ( setSecondaryHostFail ( ) ) { blackListAndCloseConnection ( this . secondaryProtocol ) ; } } } try { reconnectFailedConnection ( new SearchFilter ( true , urlParser . getOptions ( ) . failOnReadOnly ) ) ; handleFailLoop ( ) ; if ( currentProtocol != null ) { if ( killCmd ) { return new HandleErrorResult ( true , false ) ; } if ( currentReadOnlyAsked || alreadyClosed || ! inTransaction && isQueryRelaunchable ( method , args ) ) { //connection was not in transaction //can relaunch query logger . info ( "Connection to master lost, new master {}, conn={} found" + ", query type permit to be re-execute on new server without throwing exception" , currentProtocol . getHostAddress ( ) , currentProtocol . getServerThreadId ( ) ) ; return relaunchOperation ( method , args ) ; } //throw Exception because must inform client, even if connection is reconnected return new HandleErrorResult ( true ) ; } else { setMasterHostFail ( ) ; FailoverLoop . removeListener ( this ) ; return new HandleErrorResult ( ) ; } } catch ( Exception e ) { //we will throw a Connection exception that will close connection if ( e . getCause ( ) != null && proxy . hasToHandleFailover ( ( SQLException ) e . getCause ( ) ) && currentProtocol != null && currentProtocol . isConnected ( ) ) { currentProtocol . close ( ) ; } setMasterHostFail ( ) ; FailoverLoop . removeListener ( this ) ; return new HandleErrorResult ( ) ; } } | To handle the newly detected failover on the master connection . | 628 | 12 |
29,595 | public void reconnect ( ) throws SQLException { SearchFilter filter ; boolean inTransaction = false ; if ( currentReadOnlyAsked ) { filter = new SearchFilter ( true , true ) ; } else { inTransaction = masterProtocol != null && masterProtocol . inTransaction ( ) ; filter = new SearchFilter ( true , urlParser . getOptions ( ) . failOnReadOnly ) ; } reconnectFailedConnection ( filter ) ; handleFailLoop ( ) ; if ( inTransaction ) { throw new ReconnectDuringTransactionException ( "Connection reconnect automatically during an active transaction" , 1401 , "25S03" ) ; } } | Reconnect failed connection . | 134 | 6 |
29,596 | private boolean pingSecondaryProtocol ( Protocol protocol ) { try { if ( protocol != null && protocol . isConnected ( ) && protocol . ping ( ) ) { return true ; } } catch ( Exception e ) { protocol . close ( ) ; if ( setSecondaryHostFail ( ) ) { addToBlacklist ( protocol . getHostAddress ( ) ) ; } } return false ; } | Ping secondary protocol . ! lock must be set ! | 83 | 10 |
29,597 | public HandleErrorResult secondaryFail ( Method method , Object [ ] args , boolean killCmd ) throws Throwable { proxy . lock . lock ( ) ; try { if ( pingSecondaryProtocol ( this . secondaryProtocol ) ) { return relaunchOperation ( method , args ) ; } } finally { proxy . lock . unlock ( ) ; } if ( ! isMasterHostFail ( ) ) { try { //check that master is on before switching to him if ( masterProtocol != null && masterProtocol . isValid ( 1000 ) ) { //switching to master connection syncConnection ( secondaryProtocol , masterProtocol ) ; proxy . lock . lock ( ) ; try { currentProtocol = masterProtocol ; } finally { proxy . lock . unlock ( ) ; } FailoverLoop . addListener ( this ) ; logger . info ( "Connection to slave lost, using master connection" + ", query is re-execute on master server without throwing exception" ) ; return relaunchOperation ( method , args ) ; //now that we are on master, relaunched result if the result was not crashing the master } } catch ( Exception e ) { //ping fail on master if ( setMasterHostFail ( ) ) { blackListAndCloseConnection ( masterProtocol ) ; } } } try { reconnectFailedConnection ( new SearchFilter ( true , true ) ) ; handleFailLoop ( ) ; if ( isSecondaryHostFail ( ) ) { syncConnection ( this . secondaryProtocol , this . masterProtocol ) ; proxy . lock . lock ( ) ; try { currentProtocol = this . masterProtocol ; } finally { proxy . lock . unlock ( ) ; } } if ( killCmd ) { return new HandleErrorResult ( true , false ) ; } logger . info ( "Connection to slave lost, new slave {}, conn={} found" + ", query is re-execute on new server without throwing exception" , currentProtocol . getHostAddress ( ) , currentProtocol . getServerThreadId ( ) ) ; return relaunchOperation ( method , args ) ; //now that we are reconnect, relaunched result if the result was not crashing the node } catch ( Exception ee ) { //we will throw a Connection exception that will close connection FailoverLoop . removeListener ( this ) ; return new HandleErrorResult ( ) ; } } | To handle the newly detected failover on the secondary connection . | 494 | 12 |
29,598 | public List < HostAddress > connectedHosts ( ) { List < HostAddress > usedHost = new ArrayList <> ( ) ; if ( isMasterHostFail ( ) ) { Protocol masterProtocol = waitNewMasterProtocol . get ( ) ; if ( masterProtocol != null ) { usedHost . add ( masterProtocol . getHostAddress ( ) ) ; } } else { usedHost . add ( masterProtocol . getHostAddress ( ) ) ; } if ( isSecondaryHostFail ( ) ) { Protocol secondProtocol = waitNewSecondaryProtocol . get ( ) ; if ( secondProtocol != null ) { usedHost . add ( secondProtocol . getHostAddress ( ) ) ; } } else { usedHost . add ( secondaryProtocol . getHostAddress ( ) ) ; } return usedHost ; } | List current connected HostAddress . | 177 | 6 |
29,599 | public HandleErrorResult handleFailover ( SQLException qe , Method method , Object [ ] args , Protocol protocol ) throws Throwable { if ( isExplicitClosed ( ) ) { throw new SQLException ( "Connection has been closed !" ) ; } //check that failover is due to kill command boolean killCmd = qe != null && qe . getSQLState ( ) != null && qe . getSQLState ( ) . equals ( "70100" ) && 1927 == qe . getErrorCode ( ) ; if ( protocol != null ) { if ( protocol . mustBeMasterConnection ( ) ) { if ( ! protocol . isMasterConnection ( ) ) { logger . warn ( "SQL Primary node [{}, conn={}] is now in read-only mode. Exception : {}" , this . currentProtocol . getHostAddress ( ) . toString ( ) , this . currentProtocol . getServerThreadId ( ) , qe . getMessage ( ) ) ; } else if ( setMasterHostFail ( ) ) { logger . warn ( "SQL Primary node [{}, conn={}] connection fail. Reason : {}" , this . currentProtocol . getHostAddress ( ) . toString ( ) , this . currentProtocol . getServerThreadId ( ) , qe . getMessage ( ) ) ; addToBlacklist ( protocol . getHostAddress ( ) ) ; } return primaryFail ( method , args , killCmd ) ; } else { if ( setSecondaryHostFail ( ) ) { logger . warn ( "SQL secondary node [{}, conn={}] connection fail. Reason : {}" , this . currentProtocol . getHostAddress ( ) . toString ( ) , this . currentProtocol . getServerThreadId ( ) , qe . getMessage ( ) ) ; addToBlacklist ( protocol . getHostAddress ( ) ) ; } return secondaryFail ( method , args , killCmd ) ; } } else { return primaryFail ( method , args , killCmd ) ; } } | Handle failover on master or slave connection . | 436 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.