Java Code Examples for com.mysql.cj.protocol.Resultset

The following examples show how to use com.mysql.cj.protocol.Resultset. These examples are extracted from open source projects. 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 Project: quarkus   Source File: JDBCMySQLProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
List<NativeImageProxyDefinitionBuildItem> registerProxies() {
    List<NativeImageProxyDefinitionBuildItem> proxies = new ArrayList<>();
    proxies.add(new NativeImageProxyDefinitionBuildItem(JdbcConnection.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(MysqlConnection.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(Statement.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(AutoCloseable.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(JdbcStatement.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(Connection.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(ResultSet.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(JdbcPreparedStatement.class.getName(), JdbcStatement.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(JdbcPropertySet.class.getName(), PropertySet.class.getName(),
            Serializable.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(Resultset.class.getName(), ResultSetInternalMethods.class.getName()));
    proxies.add(new NativeImageProxyDefinitionBuildItem(LoadBalancedConnection.class.getName(),
            JdbcConnection.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(ReplicationConnection.class.getName(), JdbcConnection.class.getName()));
    proxies.add(
            new NativeImageProxyDefinitionBuildItem(ResultSetInternalMethods.class.getName(),
                    WarningListener.class.getName(), Resultset.class.getName()));
    return proxies;
}
 
Example 2
Source Project: FoxTelem   Source File: NativeSession.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String findProcessHost(long threadId) {
    try {
        String processHost = null;

        NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, "SHOW PROCESSLIST"), false, 0);
        Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));

        ValueFactory<Long> lvf = new LongValueFactory();
        ValueFactory<String> svf = new StringValueFactory(rs.getColumnDefinition().getFields()[2].getEncoding());
        Row r;
        while ((r = rs.getRows().next()) != null) {
            long id = r.getValue(0, lvf);
            if (threadId == id) {
                processHost = r.getValue(2, svf);
                break;
            }
        }

        return processHost;

    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
}
 
Example 3
Source Project: lams   Source File: NativeProtocol.java    License: 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 4
Source Project: lams   Source File: NativeProtocol.java    License: 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 5
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Runs an 'EXPLAIN' on the given query and dumps the results to the log
 * 
 * @param querySQL
 * @param truncatedQuery
 * 
 */
public void explainSlowQuery(String query, String truncatedQuery) {
    if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT)
            || (versionMeetsMinimum(5, 6, 3) && StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT_EXTENSION) != -1)) {

        try {
            NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "EXPLAIN " + query), false, 0);

            Resultset rs = readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));

            StringBuilder explainResults = new StringBuilder(Messages.getString("Protocol.6"));
            explainResults.append(truncatedQuery);
            explainResults.append(Messages.getString("Protocol.7"));

            appendResultSetSlashGStyle(explainResults, rs);

            this.log.logWarn(explainResults.toString());
        } catch (CJException sqlEx) {
            throw sqlEx;

        } catch (Exception ex) {
            throw ExceptionFactory.createException(ex.getMessage(), ex, getExceptionInterceptor());
        }
    }
}
 
Example 6
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 6 votes vote down vote up
public <T extends Resultset> T readAllResults(int maxRows, boolean streamResults, NativePacketPayload resultPacket, boolean isBinaryEncoded,
        ColumnDefinition metadata, ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {

    resultPacket.setPosition(0);
    T topLevelResultSet = read(Resultset.class, maxRows, streamResults, resultPacket, isBinaryEncoded, metadata, resultSetFactory);

    if (this.serverSession.hasMoreResults()) {
        T currentResultSet = topLevelResultSet;
        if (streamResults) {
            currentResultSet = readNextResultset(currentResultSet, maxRows, true, isBinaryEncoded, resultSetFactory);
        } else {
            while (this.serverSession.hasMoreResults()) {
                currentResultSet = readNextResultset(currentResultSet, maxRows, false, isBinaryEncoded, resultSetFactory);
            }
            clearInputStream();
        }
    }

    if (this.hadWarnings) {
        scanForAndThrowDataTruncation();
    }

    reclaimLargeReusablePacket();
    return topLevelResultSet;
}
 
Example 7
Source Project: lams   Source File: ServerPreparedQuery.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 * @param maxRowsToRetrieve
 * @param createStreamingResultSet
 * @param metadata
 * @return
 */
public <T extends Resultset> T serverExecute(int maxRowsToRetrieve, boolean createStreamingResultSet, ColumnDefinition metadata,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) {
    if (this.session.shouldIntercept()) {
        T interceptedResults = this.session.invokeQueryInterceptorsPre(() -> {
            return getOriginalSql();
        }, this, true);

        if (interceptedResults != null) {
            return interceptedResults;
        }
    }
    String queryAsString = "";
    if (this.profileSQL || this.logSlowQueries || this.gatherPerfMetrics.getValue()) {
        queryAsString = asSql(true);
    }

    NativePacketPayload packet = prepareExecutePacket();
    NativePacketPayload resPacket = sendExecutePacket(packet, queryAsString);
    T rs = readExecuteResult(resPacket, maxRowsToRetrieve, createStreamingResultSet, metadata, resultSetFactory, queryAsString);

    return rs;
}
 
Example 8
Source Project: FoxTelem   Source File: NativeSession.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get the variable value from server.
 * 
 * @param varName
 *            server variable name
 * @return server variable value
 */
public String queryServerVariable(String varName) {
    try {

        NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, "SELECT " + varName), false, 0);
        Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));

        ValueFactory<String> svf = new StringValueFactory(rs.getColumnDefinition().getFields()[0].getEncoding());
        Row r;
        if ((r = rs.getRows().next()) != null) {
            String s = r.getValue(0, svf);
            if (s != null) {
                return s;
            }
        }

        return null;

    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
}
 
Example 9
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 10
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 6 votes vote down vote up
public <T extends Resultset> T readAllResults(int maxRows, boolean streamResults, NativePacketPayload resultPacket, boolean isBinaryEncoded,
        ColumnDefinition metadata, ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {

    resultPacket.setPosition(0);
    T topLevelResultSet = read(Resultset.class, maxRows, streamResults, resultPacket, isBinaryEncoded, metadata, resultSetFactory);

    if (this.serverSession.hasMoreResults()) {
        T currentResultSet = topLevelResultSet;
        if (streamResults) {
            currentResultSet = readNextResultset(currentResultSet, maxRows, true, isBinaryEncoded, resultSetFactory);
        } else {
            while (this.serverSession.hasMoreResults()) {
                currentResultSet = readNextResultset(currentResultSet, maxRows, false, isBinaryEncoded, resultSetFactory);
            }
            clearInputStream();
        }
    }

    if (this.hadWarnings) {
        scanForAndThrowDataTruncation();
    }

    reclaimLargeReusablePacket();
    return topLevelResultSet;
}
 
Example 11
Source Project: lams   Source File: NativeSession.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String findProcessHost(long threadId) {
    try {
        String processHost = null;

        NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, "SHOW PROCESSLIST"), false, 0);
        Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));

        ValueFactory<Long> lvf = new LongValueFactory();
        ValueFactory<String> svf = new StringValueFactory(rs.getColumnDefinition().getFields()[2].getEncoding());
        Row r;
        while ((r = rs.getRows().next()) != null) {
            long id = r.getValue(0, lvf);
            if (threadId == id) {
                processHost = r.getValue(2, svf);
                break;
            }
        }

        return processHost;

    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
}
 
Example 12
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Runs an 'EXPLAIN' on the given query and dumps the results to the log
 * 
 * @param query
 *            full query string
 * @param truncatedQuery
 *            query string truncated for profiling
 * 
 */
public void explainSlowQuery(String query, String truncatedQuery) {
    if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT)
            || (versionMeetsMinimum(5, 6, 3) && StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT_EXTENSION) != -1)) {

        try {
            NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(getSharedSendPacket(), "EXPLAIN " + query), false, 0);

            Resultset rs = readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));

            StringBuilder explainResults = new StringBuilder(Messages.getString("Protocol.6"));
            explainResults.append(truncatedQuery);
            explainResults.append(Messages.getString("Protocol.7"));

            appendResultSetSlashGStyle(explainResults, rs);

            this.log.logWarn(explainResults.toString());
        } catch (CJException sqlEx) {
            throw sqlEx;

        } catch (Exception ex) {
            throw ExceptionFactory.createException(ex.getMessage(), ex, getExceptionInterceptor());
        }
    }
}
 
Example 13
Source Project: FoxTelem   Source File: NativeProtocol.java    License: 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 14
Source Project: FoxTelem   Source File: ServerPreparedQuery.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param <T>
 *            extends {@link Resultset}
 * @param maxRowsToRetrieve
 *            rows limit
 * @param createStreamingResultSet
 *            should c/J create a streaming result?
 * @param metadata
 *            use this metadata instead of the one provided on wire
 * @param resultSetFactory
 *            {@link ProtocolEntityFactory}
 * @return T instance
 */
public <T extends Resultset> T serverExecute(int maxRowsToRetrieve, boolean createStreamingResultSet, ColumnDefinition metadata,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) {
    if (this.session.shouldIntercept()) {
        T interceptedResults = this.session.invokeQueryInterceptorsPre(() -> {
            return getOriginalSql();
        }, this, true);

        if (interceptedResults != null) {
            return interceptedResults;
        }
    }
    String queryAsString = "";
    if (this.profileSQL || this.logSlowQueries || this.gatherPerfMetrics.getValue()) {
        queryAsString = asSql(true);
    }

    NativePacketPayload packet = prepareExecutePacket();
    NativePacketPayload resPacket = sendExecutePacket(packet, queryAsString);
    T rs = readExecuteResult(resPacket, maxRowsToRetrieve, createStreamingResultSet, metadata, resultSetFactory, queryAsString);

    return rs;
}
 
Example 15
Source Project: brave   Source File: TracingQueryInterceptor.java    License: 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 16
Source Project: lams   Source File: TextRowFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
public TextRowFactory(NativeProtocol protocol, ColumnDefinition columnDefinition, Resultset.Concurrency resultSetConcurrency,
        boolean canReuseRowPacketForBufferRow) {
    this.columnDefinition = columnDefinition;
    this.resultSetConcurrency = resultSetConcurrency;
    this.canReuseRowPacketForBufferRow = canReuseRowPacketForBufferRow;
    this.useBufferRowSizeThreshold = protocol.getPropertySet().getMemorySizeReadableProperty(PropertyDefinitions.PNAME_largeRowSizeThreshold);
    this.exceptionInterceptor = protocol.getExceptionInterceptor();
    this.valueDecoder = new MysqlTextValueDecoder();
}
 
Example 17
Source Project: FoxTelem   Source File: NativeSession.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String getProcessHost() {
    try {
        long threadId = getThreadId();
        String processHost = findProcessHost(threadId);

        if (processHost == null) {
            // http://bugs.mysql.com/bug.php?id=44167 - connection ids on the wire wrap at 4 bytes even though they're 64-bit numbers
            this.log.logWarn(String.format(
                    "Connection id %d not found in \"SHOW PROCESSLIST\", assuming 32-bit overflow, using SELECT CONNECTION_ID() instead", threadId));

            NativePacketPayload resultPacket = sendCommand(this.commandBuilder.buildComQuery(null, "SELECT CONNECTION_ID()"), false, 0);
            Resultset rs = ((NativeProtocol) this.protocol).readAllResults(-1, false, resultPacket, false, null,
                    new ResultsetFactory(Type.FORWARD_ONLY, null));

            ValueFactory<Long> lvf = new LongValueFactory();
            Row r;
            if ((r = rs.getRows().next()) != null) {
                threadId = r.getValue(0, lvf);
                processHost = findProcessHost(threadId);
            } else {
                this.log.logError("No rows returned for statement \"SELECT CONNECTION_ID()\", local connection check will most likely be incorrect");
            }
        }

        if (processHost == null) {
            this.log.logWarn(String.format(
                    "Cannot find process listing for connection %d in SHOW PROCESSLIST output, unable to determine if locally connected", threadId));
        }
        return processHost;
    } catch (IOException e) {
        throw ExceptionFactory.createException(e.getMessage(), e);
    }
}
 
Example 18
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public <T extends ProtocolEntity> T read(Class<Resultset> requiredClass, int maxRows, boolean streamResults, NativePacketPayload resultPacket,
        boolean isBinaryEncoded, ColumnDefinition metadata, ProtocolEntityFactory<T, NativePacketPayload> protocolEntityFactory) throws IOException {
    @SuppressWarnings("unchecked")
    ProtocolEntityReader<T, NativePacketPayload> sr = isBinaryEncoded
            ? (ProtocolEntityReader<T, NativePacketPayload>) this.PROTOCOL_ENTITY_CLASS_TO_BINARY_READER.get(requiredClass)
            : (ProtocolEntityReader<T, NativePacketPayload>) this.PROTOCOL_ENTITY_CLASS_TO_TEXT_READER.get(requiredClass);
    if (sr == null) {
        throw ExceptionFactory.createException(FeatureNotAvailableException.class, "ProtocolEntityReader isn't available for class " + requiredClass);
    }
    return sr.read(maxRows, streamResults, resultPacket, metadata, protocolEntityFactory);
}
 
Example 19
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Read next result set from multi-result chain.
 * 
 * @param currentProtocolEntity
 * @param maxRows
 * @param streamResults
 * @param isBinaryEncoded
 * @param resultSetFactory
 * @return
 * @throws IOException
 */
public <T extends ProtocolEntity> T readNextResultset(T currentProtocolEntity, int maxRows, boolean streamResults, boolean isBinaryEncoded,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {

    T result = null;
    if (Resultset.class.isAssignableFrom(currentProtocolEntity.getClass()) && this.serverSession.useMultiResults()) {
        if (this.serverSession.hasMoreResults()) {

            T currentResultSet = currentProtocolEntity;
            T newResultSet;
            do {
                NativePacketPayload fieldPacket = checkErrorMessage();
                fieldPacket.setPosition(0);
                newResultSet = read(Resultset.class, maxRows, streamResults, fieldPacket, isBinaryEncoded, null, resultSetFactory);
                ((Resultset) currentResultSet).setNextResultset((Resultset) newResultSet);
                currentResultSet = newResultSet;

                if (result == null) {
                    // we should return the first result set in chain
                    result = currentResultSet;
                }
            } while (streamResults && this.serverSession.hasMoreResults() // we need to consume all result sets which don't contain rows from streamer right now,
                    && !((Resultset) currentResultSet).hasRows()); // because next data portion from streamer is available only via ResultsetRows.next() 

        }
    }
    return result;
}
 
Example 20
Source Project: lams   Source File: NativeProtocol.java    License: GNU General Public License v2.0 5 votes vote down vote up
private StringBuilder appendResultSetSlashGStyle(StringBuilder appendTo, Resultset rs) {
    Field[] fields = rs.getColumnDefinition().getFields();
    int maxWidth = 0;
    for (int i = 0; i < fields.length; i++) {
        if (fields[i].getColumnLabel().length() > maxWidth) {
            maxWidth = fields[i].getColumnLabel().length();
        }
    }

    int rowCount = 1;
    Row r;
    while ((r = rs.getRows().next()) != null) {
        appendTo.append("*************************** ");
        appendTo.append(rowCount++);
        appendTo.append(". row ***************************\n");

        for (int i = 0; i < fields.length; i++) {
            int leftPad = maxWidth - fields[i].getColumnLabel().length();
            for (int j = 0; j < leftPad; j++) {
                appendTo.append(" ");
            }
            appendTo.append(fields[i].getColumnLabel()).append(": ");
            String stringVal = r.getValue(i, new StringValueFactory(fields[i].getEncoding()));
            appendTo.append(stringVal != null ? stringVal : "NULL").append("\n");
        }
        appendTo.append("\n");
    }
    return appendTo;
}
 
Example 21
Source Project: lams   Source File: BinaryRowFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
public BinaryRowFactory(NativeProtocol protocol, ColumnDefinition columnDefinition, Resultset.Concurrency resultSetConcurrency,
        boolean canReuseRowPacketForBufferRow) {
    this.columnDefinition = columnDefinition;
    this.resultSetConcurrency = resultSetConcurrency;
    this.canReuseRowPacketForBufferRow = canReuseRowPacketForBufferRow;
    this.useBufferRowSizeThreshold = protocol.getPropertySet().getMemorySizeReadableProperty(PropertyDefinitions.PNAME_largeRowSizeThreshold);
    this.exceptionInterceptor = protocol.getExceptionInterceptor();
    this.valueDecoder = new MysqlBinaryValueDecoder();
}
 
Example 22
Source Project: core-ng-project   Source File: MySQLQueryInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void defaultBehaviors() {
    assertThat(interceptor.init(null, null, null)).isSameAs(interceptor);
    Resultset result = interceptor.preProcess(null, null);
    assertThat(result).isNull();
    assertThat(interceptor.executeTopLevelOnly()).isTrue();
    interceptor.destroy();
}
 
Example 23
Source Project: lams   Source File: StatementImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the result set type for result sets generated by this statement
 * 
 * @param typeFlag
 * @throws SQLException
 */
void setResultSetType(Resultset.Type typeFlag) throws SQLException {
    try {
        synchronized (checkClosed().getConnectionMutex()) {
            this.query.setResultType(typeFlag);
            // updating resultset factory because type is cached there
            this.resultSetFactory = new ResultSetFactory(this.connection, this);
        }
    } catch (StatementIsClosedException e) {
        // FIXME: Can't break interface atm, we'll get the exception later when you try and do something useful with a closed statement...
    }
}
 
Example 24
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Read next result set from multi-result chain.
 * 
 * @param <T>
 *            extends {@link ProtocolEntity}
 * @param currentProtocolEntity
 *            T instance
 * @param maxRows
 *            rows limit
 * @param streamResults
 *            whether a stream result should be created
 * @param isBinaryEncoded
 *            true for binary protocol
 * @param resultSetFactory
 *            {@link ProtocolEntityFactory}
 * @return T instance
 * @throws IOException
 *             if an i/o error occurs
 */
public <T extends ProtocolEntity> T readNextResultset(T currentProtocolEntity, int maxRows, boolean streamResults, boolean isBinaryEncoded,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {

    T result = null;
    if (Resultset.class.isAssignableFrom(currentProtocolEntity.getClass()) && this.serverSession.useMultiResults()) {
        if (this.serverSession.hasMoreResults()) {

            T currentResultSet = currentProtocolEntity;
            T newResultSet;
            do {
                NativePacketPayload fieldPacket = checkErrorMessage();
                fieldPacket.setPosition(0);
                newResultSet = read(Resultset.class, maxRows, streamResults, fieldPacket, isBinaryEncoded, null, resultSetFactory);
                ((Resultset) currentResultSet).setNextResultset((Resultset) newResultSet);
                currentResultSet = newResultSet;

                if (result == null) {
                    // we should return the first result set in chain
                    result = currentResultSet;
                }
            } while (streamResults && this.serverSession.hasMoreResults() // we need to consume all result sets which don't contain rows from streamer right now,
                    && !((Resultset) currentResultSet).hasRows()); // because next data portion from streamer is available only via ResultsetRows.next() 

        }
    }
    return result;
}
 
Example 25
@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 26
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T extends ProtocolEntity> T read(Class<Resultset> requiredClass, int maxRows, boolean streamResults, NativePacketPayload resultPacket,
        boolean isBinaryEncoded, ColumnDefinition metadata, ProtocolEntityFactory<T, NativePacketPayload> protocolEntityFactory) throws IOException {
    @SuppressWarnings("unchecked")
    ProtocolEntityReader<T, NativePacketPayload> sr = isBinaryEncoded
            ? (ProtocolEntityReader<T, NativePacketPayload>) this.PROTOCOL_ENTITY_CLASS_TO_BINARY_READER.get(requiredClass)
            : (ProtocolEntityReader<T, NativePacketPayload>) this.PROTOCOL_ENTITY_CLASS_TO_TEXT_READER.get(requiredClass);
    if (sr == null) {
        throw ExceptionFactory.createException(FeatureNotAvailableException.class, "ProtocolEntityReader isn't available for class " + requiredClass);
    }
    return sr.read(maxRows, streamResults, resultPacket, metadata, protocolEntityFactory);
}
 
Example 27
Source Project: FoxTelem   Source File: NativeProtocol.java    License: GNU General Public License v3.0 5 votes vote down vote up
private StringBuilder appendResultSetSlashGStyle(StringBuilder appendTo, Resultset rs) {
    Field[] fields = rs.getColumnDefinition().getFields();
    int maxWidth = 0;
    for (int i = 0; i < fields.length; i++) {
        if (fields[i].getColumnLabel().length() > maxWidth) {
            maxWidth = fields[i].getColumnLabel().length();
        }
    }

    int rowCount = 1;
    Row r;
    while ((r = rs.getRows().next()) != null) {
        appendTo.append("*************************** ");
        appendTo.append(rowCount++);
        appendTo.append(". row ***************************\n");

        for (int i = 0; i < fields.length; i++) {
            int leftPad = maxWidth - fields[i].getColumnLabel().length();
            for (int j = 0; j < leftPad; j++) {
                appendTo.append(" ");
            }
            appendTo.append(fields[i].getColumnLabel()).append(": ");
            String stringVal = r.getValue(i, new StringValueFactory(fields[i].getEncoding()));
            appendTo.append(stringVal != null ? stringVal : "NULL").append("\n");
        }
        appendTo.append("\n");
    }
    return appendTo;
}
 
Example 28
Source Project: FoxTelem   Source File: StatementImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets the result set type for result sets generated by this statement
 * 
 * @param typeFlag
 *            {@link com.mysql.cj.protocol.Resultset.Type}
 * @throws SQLException
 *             if a database access error occurs or this method is called on a closed PreparedStatement
 */
void setResultSetType(Resultset.Type typeFlag) throws SQLException {
    try {
        synchronized (checkClosed().getConnectionMutex()) {
            this.query.setResultType(typeFlag);
            // updating resultset factory because type is cached there
            this.resultSetFactory = new ResultSetFactory(this.connection, this);
        }
    } catch (StatementIsClosedException e) {
        // FIXME: Can't break interface atm, we'll get the exception later when you try and do something useful with a closed statement...
    }
}
 
Example 29
Source Project: FoxTelem   Source File: ConnectionTest.java    License: 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 30
@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;
                }
            });

}