com.mysql.cj.Query Java Examples

The following examples show how to use com.mysql.cj.Query. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NativeProtocol.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public <T extends Resultset> T invokeQueryInterceptorsPre(Supplier<String> sql, Query interceptedQuery, boolean forceExecute) {
    T previousResultSet = null;

    for (int i = 0, s = this.queryInterceptors.size(); i < s; i++) {
        QueryInterceptor interceptor = this.queryInterceptors.get(i);

        boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
        boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);

        if (shouldExecute) {
            T interceptedResultSet = interceptor.preProcess(sql, interceptedQuery);

            if (interceptedResultSet != null) {
                previousResultSet = interceptedResultSet;
            }
        }
    }

    return previousResultSet;
}
 
Example #2
Source File: NativeProtocol.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public <T extends Resultset> T invokeQueryInterceptorsPost(Supplier<String> sql, Query interceptedQuery, T originalResultSet, boolean forceExecute) {

        for (int i = 0, s = this.queryInterceptors.size(); i < s; i++) {
            QueryInterceptor interceptor = this.queryInterceptors.get(i);

            boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
            boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);

            if (shouldExecute) {
                T interceptedResultSet = interceptor.postProcess(sql, interceptedQuery, originalResultSet, this.serverSession);

                if (interceptedResultSet != null) {
                    originalResultSet = interceptedResultSet;
                }
            }
        }

        return originalResultSet;
    }
 
Example #3
Source File: MySQLQueryInterceptor.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {
    boolean noIndexUsed = serverSession.noIndexUsed();
    boolean badIndexUsed = serverSession.noGoodIndexUsed();
    if (noIndexUsed || badIndexUsed) {
        boolean suppress = suppressSlowSQLWarning();
        String message = noIndexUsed ? "no index used" : "bad index used";
        String sqlValue = sql.get();
        if (suppress) {
            LOGGER.debug("{}, sql={}", message, sqlValue);
        } else {
            LOGGER.warn(errorCode("SLOW_SQL"), "{}, sql={}", message, sqlValue);
        }
    }
    return null;
}
 
Example #4
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public <T extends Resultset> T invokeQueryInterceptorsPost(Supplier<String> sql, Query interceptedQuery, T originalResultSet, boolean forceExecute) {

        for (int i = 0, s = this.queryInterceptors.size(); i < s; i++) {
            QueryInterceptor interceptor = this.queryInterceptors.get(i);

            boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
            boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);

            if (shouldExecute) {
                T interceptedResultSet = interceptor.postProcess(sql, interceptedQuery, originalResultSet, this.serverSession);

                if (interceptedResultSet != null) {
                    originalResultSet = interceptedResultSet;
                }
            }
        }

        return originalResultSet;
    }
 
Example #5
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public <T extends Resultset> T invokeQueryInterceptorsPre(Supplier<String> sql, Query interceptedQuery, boolean forceExecute) {
    T previousResultSet = null;

    for (int i = 0, s = this.queryInterceptors.size(); i < s; i++) {
        QueryInterceptor interceptor = this.queryInterceptors.get(i);

        boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
        boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);

        if (shouldExecute) {
            T interceptedResultSet = interceptor.preProcess(sql, interceptedQuery);

            if (interceptedResultSet != null) {
                previousResultSet = interceptedResultSet;
            }
        }
    }

    return previousResultSet;
}
 
Example #6
Source File: SessionAssociationInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    String key = getSessionKey();

    if (key != null && !key.equals(this.currentSessionKey)) {

        try {
            PreparedStatement pstmt = this.connection.clientPrepareStatement("SET @mysql_proxy_session=?");

            try {
                pstmt.setString(1, key);
                pstmt.execute();
            } finally {
                pstmt.close();
            }
        } catch (SQLException ex) {
            throw ExceptionFactory.createException(ex.getMessage(), ex);
        }

        this.currentSessionKey = key;
    }

    return null;
}
 
Example #7
Source File: SessionAssociationInterceptor.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    String key = getSessionKey();

    if (key != null && !key.equals(this.currentSessionKey)) {

        try {
            PreparedStatement pstmt = this.connection.clientPrepareStatement("SET @mysql_proxy_session=?");

            try {
                pstmt.setString(1, key);
                pstmt.execute();
            } finally {
                pstmt.close();
            }
        } catch (SQLException ex) {
            throw ExceptionFactory.createException(ex.getMessage(), ex);
        }

        this.currentSessionKey = key;
    }

    return null;
}
 
Example #8
Source File: TracingQueryInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery,
  T originalResultSet, ServerSession serverSession) {
  if (interceptingExceptions && originalResultSet == null) {
    // Error case, the span will be finished in TracingExceptionInterceptor.
    return null;
  }
  Span span = ThreadLocalSpan.CURRENT_TRACER.remove();
  if (span == null || span.isNoop()) return null;

  span.finish();

  return null;
}
 
Example #9
Source File: TracingQueryInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * Uses {@link ThreadLocalSpan} as there's no attribute namespace shared between callbacks, but
 * all callbacks happen on the same thread.
 *
 * <p>Uses {@link ThreadLocalSpan#CURRENT_TRACER} and this interceptor initializes before
 * tracing.
 */
@Override
public <T extends Resultset> T preProcess(Supplier<String> sqlSupplier, Query interceptedQuery) {
  // Gets the next span (and places it in scope) so code between here and postProcess can read it
  Span span = ThreadLocalSpan.CURRENT_TRACER.next();
  if (span == null || span.isNoop()) return null;

  String sql = sqlSupplier.get();
  int spaceIndex = sql.indexOf(' '); // Allow span names of single-word statements like COMMIT
  span.kind(CLIENT).name(spaceIndex == -1 ? sql : sql.substring(0, spaceIndex));
  span.tag("sql.query", sql);
  parseServerIpAndPort(connection, span);
  span.start();
  return null;
}
 
Example #10
Source File: CharsetRegressionTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> str, Query interceptedQuery) {
    String sql = str.get();
    if (sql.contains("SET NAMES utf8") && !sql.contains("utf8mb4")) {
        throw ExceptionFactory.createException("Character set statement issued: " + sql);
    }
    return null;
}
 
Example #11
Source File: ConnectionTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> str, Query interceptedQuery) {
    String sql = str == null ? null : str.get();
    if (sql == null) {
        try {
            if (interceptedQuery instanceof ClientPreparedStatement) {
                sql = ((ClientPreparedStatement) interceptedQuery).asSql();
            } else if (interceptedQuery instanceof PreparedQuery<?>) {
                sql = ((PreparedQuery<?>) interceptedQuery).asSql();
            }
        } catch (SQLException ex) {
            throw ExceptionFactory.createException(ex.getMessage(), ex);
        }
    }

    int p;
    if (sql != null && (p = sql.indexOf("testEnableEscapeProcessing:")) != -1) {
        int tst = Integer.parseInt(sql.substring(sql.indexOf('(', p) + 1, sql.indexOf(')', p)));
        boolean enableEscapeProcessing = (tst & 0x1) != 0;
        boolean processEscapeCodesForPrepStmts = (tst & 0x2) != 0;
        boolean useServerPrepStmts = (tst & 0x4) != 0;
        boolean isPreparedStatement = interceptedQuery instanceof PreparedStatement || interceptedQuery instanceof PreparedQuery<?>;

        String testCase = String.format("Case: %d [ %s | %s | %s ]/%s", tst, enableEscapeProcessing ? "enEscProc" : "-",
                processEscapeCodesForPrepStmts ? "procEscProcPS" : "-", useServerPrepStmts ? "useSSPS" : "-",
                isPreparedStatement ? "PreparedStatement" : "Statement");

        boolean escapeProcessingDone = sql.indexOf('{') == -1;
        assertTrue(testCase, isPreparedStatement && processEscapeCodesForPrepStmts == escapeProcessingDone
                || !isPreparedStatement && enableEscapeProcessing == escapeProcessingDone);
    }
    final String fsql = sql;
    return super.preProcess(() -> {
        return fsql;
    }, interceptedQuery);
}
 
Example #12
Source File: ResultSetScannerInterceptor.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {

    // requirement of anonymous class
    final T finalResultSet = originalResultSet;

    return (T) Proxy.newProxyInstance(originalResultSet.getClass().getClassLoader(), new Class<?>[] { Resultset.class, ResultSetInternalMethods.class },
            new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    if ("equals".equals(method.getName())) {
                        // Let args[0] "unwrap" to its InvocationHandler if it is a proxy.
                        return args[0].equals(this);
                    }

                    Object invocationResult = method.invoke(finalResultSet, args);

                    String methodName = method.getName();

                    if (invocationResult != null && invocationResult instanceof String || "getString".equals(methodName) || "getObject".equals(methodName)
                            || "getObjectStoredProc".equals(methodName)) {
                        Matcher matcher = ResultSetScannerInterceptor.this.regexP.matcher(invocationResult.toString());

                        if (matcher.matches()) {
                            throw new SQLException(Messages.getString("ResultSetScannerInterceptor.2"));
                        }
                    }

                    return invocationResult;
                }
            });

}
 
Example #13
Source File: ResultSetScannerInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {

    // requirement of anonymous class
    final T finalResultSet = originalResultSet;

    return (T) Proxy.newProxyInstance(originalResultSet.getClass().getClassLoader(), new Class<?>[] { Resultset.class, ResultSetInternalMethods.class },
            new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    if ("equals".equals(method.getName())) {
                        // Let args[0] "unwrap" to its InvocationHandler if it is a proxy.
                        return args[0].equals(this);
                    }

                    Object invocationResult = method.invoke(finalResultSet, args);

                    String methodName = method.getName();

                    if (invocationResult != null && invocationResult instanceof String || "getString".equals(methodName) || "getObject".equals(methodName)
                            || "getObjectStoredProc".equals(methodName)) {
                        Matcher matcher = ResultSetScannerInterceptor.this.regexP.matcher(invocationResult.toString());

                        if (matcher.matches()) {
                            throw new SQLException(Messages.getString("ResultSetScannerInterceptor.2"));
                        }
                    }

                    return invocationResult;
                }
            });

}
 
Example #14
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Build a query packet from the given string and send it to the server.
 * 
 * @param <T>
 *            extends {@link Resultset}
 * @param callingQuery
 *            {@link Query}
 * @param query
 *            query string
 * @param characterEncoding
 *            Java encoding name
 * @param maxRows
 *            rows limit
 * @param streamResults
 *            whether a stream result should be created
 * @param catalog
 *            database name
 * @param cachedMetadata
 *            use this metadata instead of the one provided on wire
 * @param getProfilerEventHandlerInstanceFunction
 *            {@link com.mysql.cj.protocol.Protocol.GetProfilerEventHandlerInstanceFunction}
 * @param resultSetFactory
 *            {@link ProtocolEntityFactory}
 * @return T instance
 * @throws IOException
 *             if an i/o error occurs
 */
public final <T extends Resultset> T sendQueryString(Query callingQuery, String query, String characterEncoding, int maxRows, boolean streamResults,
        String catalog, ColumnDefinition cachedMetadata, GetProfilerEventHandlerInstanceFunction getProfilerEventHandlerInstanceFunction,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {
    String statementComment = this.queryComment;

    if (this.propertySet.getBooleanProperty(PropertyKey.includeThreadNamesAsStatementComment).getValue()) {
        statementComment = (statementComment != null ? statementComment + ", " : "") + "java thread: " + Thread.currentThread().getName();
    }

    // We don't know exactly how many bytes we're going to get from the query. Since we're dealing with UTF-8, the max is 4, so pad it
    // (4 * query) + space for headers
    int packLength = 1 + (query.length() * 4) + 2;

    byte[] commentAsBytes = null;

    if (statementComment != null) {
        commentAsBytes = StringUtils.getBytes(statementComment, characterEncoding);

        packLength += commentAsBytes.length;
        packLength += 6; // for /*[space] [space]*/
    }

    // TODO decide how to safely use the shared this.sendPacket
    //if (this.sendPacket == null) {
    NativePacketPayload sendPacket = new NativePacketPayload(packLength);
    //}

    sendPacket.setPosition(0);

    sendPacket.writeInteger(IntegerDataType.INT1, NativeConstants.COM_QUERY);

    if (commentAsBytes != null) {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SLASH_STAR_SPACE_AS_BYTES);
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, commentAsBytes);
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
    }

    if (!this.platformDbCharsetMatches && StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query));
    } else {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query, characterEncoding));
    }

    return sendQueryPacket(callingQuery, sendPacket, maxRows, streamResults, catalog, cachedMetadata, getProfilerEventHandlerInstanceFunction,
            resultSetFactory);
}
 
Example #15
Source File: NativeProtocol.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Build a query packet from the given string and send it to the server.
 * 
 * @param callingQuery
 * @param query
 * @param characterEncoding
 * @param maxRows
 * @param streamResults
 * @param catalog
 * @param cachedMetadata
 * @param getProfilerEventHandlerInstanceFunction
 * @param resultSetFactory
 * @return
 * @throws IOException
 */
public final <T extends Resultset> T sendQueryString(Query callingQuery, String query, String characterEncoding, int maxRows, boolean streamResults,
        String catalog, ColumnDefinition cachedMetadata, GetProfilerEventHandlerInstanceFunction getProfilerEventHandlerInstanceFunction,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {
    String statementComment = this.queryComment;

    if (this.propertySet.getBooleanReadableProperty(PropertyDefinitions.PNAME_includeThreadNamesAsStatementComment).getValue()) {
        statementComment = (statementComment != null ? statementComment + ", " : "") + "java thread: " + Thread.currentThread().getName();
    }

    // We don't know exactly how many bytes we're going to get from the query. Since we're dealing with UTF-8, the max is 4, so pad it
    // (4 * query) + space for headers
    int packLength = 1 + (query.length() * 4) + 2;

    byte[] commentAsBytes = null;

    if (statementComment != null) {
        commentAsBytes = StringUtils.getBytes(statementComment, characterEncoding);

        packLength += commentAsBytes.length;
        packLength += 6; // for /*[space] [space]*/
    }

    // TODO decide how to safely use the shared this.sendPacket
    //if (this.sendPacket == null) {
    NativePacketPayload sendPacket = new NativePacketPayload(packLength);
    //}

    sendPacket.setPosition(0);

    sendPacket.writeInteger(IntegerDataType.INT1, NativeConstants.COM_QUERY);

    if (commentAsBytes != null) {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SLASH_STAR_SPACE_AS_BYTES);
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, commentAsBytes);
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
    }

    if (!this.platformDbCharsetMatches && StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query));
    } else {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query, characterEncoding));
    }

    return sendQueryPacket(callingQuery, sendPacket, maxRows, streamResults, catalog, cachedMetadata, getProfilerEventHandlerInstanceFunction,
            resultSetFactory);
}
 
Example #16
Source File: StatementImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public CancelQueryTask startQueryTimer(Query stmtToCancel, int timeout) {
    return this.query.startQueryTimer(stmtToCancel, timeout);
}
 
Example #17
Source File: StatementImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public Query getQuery() {
    return this.query;
}
 
Example #18
Source File: MySQLQueryInterceptor.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    return null;
}
 
Example #19
Source File: LoadBalancedAutoCommitInterceptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("resource")
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {

    try {
        // Don't count SETs neither SHOWs. Those are mostly used internally and must not trigger a connection switch.
        if (!this.countStatements || StringUtils.startsWithIgnoreCase(sql.get(), "SET") || StringUtils.startsWithIgnoreCase(sql.get(), "SHOW")) {
            return originalResultSet;
        }

        // Don't care if auto-commit is not enabled.
        if (!this.conn.getAutoCommit()) {
            this.matchingAfterStatementCount = 0;
            return originalResultSet;
        }

        if (this.proxy == null && this.conn.isProxySet()) {
            JdbcConnection lcl_proxy = this.conn.getMultiHostSafeProxy();
            while (lcl_proxy != null && !(lcl_proxy instanceof LoadBalancedMySQLConnection)) {
                lcl_proxy = lcl_proxy.getMultiHostSafeProxy();
            }
            if (lcl_proxy != null) {
                this.proxy = ((LoadBalancedMySQLConnection) lcl_proxy).getThisAsProxy();
            }
        }

        // Connection is not ready to rebalance yet.
        if (this.proxy == null) {
            return originalResultSet;
        }

        // Increment the match count if no regex specified, or if matches.
        if (this.matchingAfterStatementRegex == null || sql.get().matches(this.matchingAfterStatementRegex)) {
            this.matchingAfterStatementCount++;
        }

        // Trigger rebalance if count exceeds threshold.
        if (this.matchingAfterStatementCount >= this.matchingAfterStatementThreshold) {
            this.matchingAfterStatementCount = 0;
            try {
                this.proxy.pickNewConnection();
            } catch (SQLException e) {
                // eat this exception, the auto-commit statement completed, but we could not rebalance for some reason.  User may get exception when using
                // connection next.
            }
        }
    } catch (SQLException ex) {
        throw ExceptionFactory.createException(ex.getMessage(), ex);
    }
    // always return the original result set.
    return originalResultSet;
}
 
Example #20
Source File: MetadataTest.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    interceptedQueries.add(sql.get());
    return super.preProcess(sql, interceptedQuery);
}
 
Example #21
Source File: BaseQueryInterceptor.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {
    return originalResultSet;
}
 
Example #22
Source File: BaseQueryInterceptor.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    return null;
}
 
Example #23
Source File: LoadBalancedAutoCommitInterceptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    // we do nothing before execution, it's unsafe to swap servers at this point.
    return null;
}
 
Example #24
Source File: SessionAssociationInterceptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {
    return null;
}
 
Example #25
Source File: StatementImpl.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public CancelQueryTask startQueryTimer(Query stmtToCancel, int timeout) {
    return this.query.startQueryTimer(stmtToCancel, timeout);
}
 
Example #26
Source File: StatementImpl.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Query getQuery() {
    return this.query;
}
 
Example #27
Source File: ResultSetScannerInterceptor.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    // we don't care about this event

    return null;
}
 
Example #28
Source File: ResultSetScannerInterceptor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    // we don't care about this event

    return null;
}
 
Example #29
Source File: LoadBalancedAutoCommitInterceptor.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("resource")
public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {

    try {
        // Don't count SETs neither SHOWs. Those are mostly used internally and must not trigger a connection switch.
        if (!this.countStatements || StringUtils.startsWithIgnoreCase(sql.get(), "SET") || StringUtils.startsWithIgnoreCase(sql.get(), "SHOW")) {
            return originalResultSet;
        }

        // Don't care if auto-commit is not enabled.
        if (!this.conn.getAutoCommit()) {
            this.matchingAfterStatementCount = 0;
            return originalResultSet;
        }

        if (this.proxy == null && this.conn.isProxySet()) {
            JdbcConnection lcl_proxy = this.conn.getMultiHostSafeProxy();
            while (lcl_proxy != null && !(lcl_proxy instanceof LoadBalancedMySQLConnection)) {
                lcl_proxy = lcl_proxy.getMultiHostSafeProxy();
            }
            if (lcl_proxy != null) {
                this.proxy = ((LoadBalancedMySQLConnection) lcl_proxy).getThisAsProxy();
            }
        }

        // Connection is not ready to rebalance yet.
        if (this.proxy == null) {
            return originalResultSet;
        }

        // Increment the match count if no regex specified, or if matches.
        if (this.matchingAfterStatementRegex == null || sql.get().matches(this.matchingAfterStatementRegex)) {
            this.matchingAfterStatementCount++;
        }

        // Trigger rebalance if count exceeds threshold.
        if (this.matchingAfterStatementCount >= this.matchingAfterStatementThreshold) {
            this.matchingAfterStatementCount = 0;
            try {
                this.proxy.pickNewConnection();
            } catch (SQLException e) {
                // eat this exception, the auto-commit statement completed, but we could not rebalance for some reason.  User may get exception when using
                // connection next.
            }
        }
    } catch (SQLException ex) {
        throw ExceptionFactory.createException(ex.getMessage(), ex);
    }
    // always return the original result set.
    return originalResultSet;
}
 
Example #30
Source File: LoadBalancedAutoCommitInterceptor.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T extends Resultset> T preProcess(Supplier<String> sql, Query interceptedQuery) {
    // we do nothing before execution, it's unsafe to swap servers at this point.
    return null;
}