Search in sources :

Example 11 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class NativeProtocol method explainSlowQuery.

/**
 * 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(getCommandBuilder().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());
        }
    }
}
Also used : Resultset(com.mysql.cj.protocol.Resultset) CJException(com.mysql.cj.exceptions.CJException) WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) InvalidPathException(java.nio.file.InvalidPathException) CJConnectionFeatureNotAvailableException(com.mysql.cj.exceptions.CJConnectionFeatureNotAvailableException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) CJPacketTooBigException(com.mysql.cj.exceptions.CJPacketTooBigException) URISyntaxException(java.net.URISyntaxException) DataTruncationException(com.mysql.cj.exceptions.DataTruncationException) FeatureNotAvailableException(com.mysql.cj.exceptions.FeatureNotAvailableException) MalformedURLException(java.net.MalformedURLException) CJOperationNotSupportedException(com.mysql.cj.exceptions.CJOperationNotSupportedException) ClosedOnExpiredPasswordException(com.mysql.cj.exceptions.ClosedOnExpiredPasswordException) CJException(com.mysql.cj.exceptions.CJException)

Example 12 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class NativeProtocol method appendDeadlockStatusInformation.

private void appendDeadlockStatusInformation(Session sess, String xOpen, StringBuilder errorBuf) {
    if (sess.getPropertySet().getBooleanProperty(PropertyKey.includeInnodbStatusInDeadlockExceptions).getValue() && xOpen != null && (xOpen.startsWith("40") || xOpen.startsWith("41")) && getStreamingData() == null) {
        try {
            NativePacketPayload resultPacket = sendCommand(getCommandBuilder().buildComQuery(getSharedSendPacket(), "SHOW ENGINE INNODB STATUS"), false, 0);
            Resultset rs = readAllResults(-1, false, resultPacket, false, null, new ResultsetFactory(Type.FORWARD_ONLY, null));
            int colIndex = 0;
            Field f = null;
            for (int i = 0; i < rs.getColumnDefinition().getFields().length; i++) {
                f = rs.getColumnDefinition().getFields()[i];
                if ("Status".equals(f.getName())) {
                    colIndex = i;
                    break;
                }
            }
            ValueFactory<String> vf = new StringValueFactory(this.propertySet);
            Row r;
            if ((r = rs.getRows().next()) != null) {
                errorBuf.append("\n\n").append(r.getValue(colIndex, vf));
            } else {
                errorBuf.append("\n\n").append(Messages.getString("MysqlIO.NoInnoDBStatusFound"));
            }
        } catch (IOException | CJException ex) {
            errorBuf.append("\n\n").append(Messages.getString("MysqlIO.InnoDBStatusFailed")).append("\n\n").append(Util.stackTraceToString(ex));
        }
    }
    if (sess.getPropertySet().getBooleanProperty(PropertyKey.includeThreadDumpInDeadlockExceptions).getValue()) {
        errorBuf.append("\n\n*** Java threads running at time of deadlock ***\n\n");
        ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean();
        long[] threadIds = threadMBean.getAllThreadIds();
        ThreadInfo[] threads = threadMBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
        List<ThreadInfo> activeThreads = new ArrayList<>();
        for (ThreadInfo info : threads) {
            if (info != null) {
                activeThreads.add(info);
            }
        }
        for (ThreadInfo threadInfo : activeThreads) {
            // "Thread-60" daemon prio=1 tid=0x093569c0 nid=0x1b99 in Object.wait()
            errorBuf.append('"').append(threadInfo.getThreadName()).append("\" tid=").append(threadInfo.getThreadId()).append(" ").append(threadInfo.getThreadState());
            if (threadInfo.getLockName() != null) {
                errorBuf.append(" on lock=").append(threadInfo.getLockName());
            }
            if (threadInfo.isSuspended()) {
                errorBuf.append(" (suspended)");
            }
            if (threadInfo.isInNative()) {
                errorBuf.append(" (running in native)");
            }
            StackTraceElement[] stackTrace = threadInfo.getStackTrace();
            if (stackTrace.length > 0) {
                errorBuf.append(" in ");
                errorBuf.append(stackTrace[0].getClassName()).append(".");
                errorBuf.append(stackTrace[0].getMethodName()).append("()");
            }
            errorBuf.append("\n");
            if (threadInfo.getLockOwnerName() != null) {
                errorBuf.append("\t owned by ").append(threadInfo.getLockOwnerName()).append(" Id=").append(threadInfo.getLockOwnerId()).append("\n");
            }
            for (int j = 0; j < stackTrace.length; j++) {
                StackTraceElement ste = stackTrace[j];
                errorBuf.append("\tat ").append(ste.toString()).append("\n");
            }
        }
    }
}
Also used : ThreadMXBean(java.lang.management.ThreadMXBean) StringValueFactory(com.mysql.cj.result.StringValueFactory) ArrayList(java.util.ArrayList) LazyString(com.mysql.cj.util.LazyString) IOException(java.io.IOException) Field(com.mysql.cj.result.Field) ThreadInfo(java.lang.management.ThreadInfo) Resultset(com.mysql.cj.protocol.Resultset) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) Row(com.mysql.cj.result.Row) CJException(com.mysql.cj.exceptions.CJException)

Example 13 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class BinaryResultsetReader method read.

@Override
public Resultset read(int maxRows, boolean streamResults, NativePacketPayload resultPacket, ColumnDefinition metadata, ProtocolEntityFactory<Resultset, NativePacketPayload> resultSetFactory) throws IOException {
    Resultset rs = null;
    // try {
    long columnCount = resultPacket.readInteger(IntegerDataType.INT_LENENC);
    if (columnCount > 0) {
        // Build a result set with rows.
        // Read in the column information
        ColumnDefinition cdef = this.protocol.read(ColumnDefinition.class, new MergingColumnDefinitionFactory(columnCount, metadata));
        boolean isCursorPossible = this.protocol.getPropertySet().getBooleanProperty(PropertyKey.useCursorFetch).getValue() && resultSetFactory.getResultSetType() == Type.FORWARD_ONLY && resultSetFactory.getFetchSize() > 0;
        // If CLIENT_DEPRECATE_EOF is set, there is no way to tell which one, OK or ResultsetRow, is the next packet, so it should be read with a special caching method.
        if (isCursorPossible || !this.protocol.getServerSession().isEOFDeprecated()) {
            // Read the next packet but leave it in the reader cache. In case it's not the OK or EOF one it will be read again by ResultSet factories.
            NativePacketPayload rowPacket = this.protocol.probeMessage(this.protocol.getReusablePacket());
            this.protocol.checkErrorMessage(rowPacket);
            if (rowPacket.isResultSetOKPacket() || rowPacket.isEOFPacket()) {
                // Consume the OK/EOF packet from the reader cache and read the status flags from it;
                // The SERVER_STATUS_CURSOR_EXISTS flag should indicate the cursor state in this case.
                rowPacket = this.protocol.readMessage(this.protocol.getReusablePacket());
                this.protocol.readServerStatusForResultSets(rowPacket, true);
            } else {
                // If it's not an OK/EOF then the cursor is not created and this recent packet is a row.
                // Retain the packet in the reader cache.
                isCursorPossible = false;
            }
        }
        ResultsetRows rows = null;
        if (isCursorPossible && this.protocol.getServerSession().cursorExists()) {
            rows = new ResultsetRowsCursor(this.protocol, cdef);
        } else if (!streamResults) {
            BinaryRowFactory brf = new BinaryRowFactory(this.protocol, cdef, resultSetFactory.getResultSetConcurrency(), false);
            ArrayList<ResultsetRow> rowList = new ArrayList<>();
            ResultsetRow row = this.protocol.read(ResultsetRow.class, brf);
            while (row != null) {
                if ((maxRows == -1) || (rowList.size() < maxRows)) {
                    rowList.add(row);
                }
                row = this.protocol.read(ResultsetRow.class, brf);
            }
            rows = new ResultsetRowsStatic(rowList, cdef);
        } else {
            rows = new ResultsetRowsStreaming<>(this.protocol, cdef, true, resultSetFactory);
            this.protocol.setStreamingData(rows);
        }
        /*
             * Build ResultSet from ResultsetRows
             */
        rs = resultSetFactory.createFromProtocolEntity(rows);
    } else {
        // check for file request
        if (columnCount == NativePacketPayload.NULL_LENGTH) {
            String charEncoding = this.protocol.getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue();
            String fileName = resultPacket.readString(StringSelfDataType.STRING_TERM, this.protocol.getServerSession().getCharsetSettings().doesPlatformDbCharsetMatches() ? null : charEncoding);
            resultPacket = this.protocol.sendFileToServer(fileName);
        }
        /*
             * Build ResultSet with no ResultsetRows
             */
        // read and parse OK packet
        // oldStatus set in sendCommand()
        OkPacket ok = this.protocol.readServerStatusForResultSets(resultPacket, false);
        rs = resultSetFactory.createFromProtocolEntity(ok);
    }
    return rs;
}
Also used : OkPacket(com.mysql.cj.protocol.a.result.OkPacket) ArrayList(java.util.ArrayList) ResultsetRows(com.mysql.cj.protocol.ResultsetRows) ResultsetRowsStreaming(com.mysql.cj.protocol.a.result.ResultsetRowsStreaming) ColumnDefinition(com.mysql.cj.protocol.ColumnDefinition) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ResultsetRowsCursor(com.mysql.cj.protocol.a.result.ResultsetRowsCursor) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) Resultset(com.mysql.cj.protocol.Resultset)

Example 14 with Resultset

use of com.mysql.cj.protocol.Resultset in project aws-mysql-jdbc by awslabs.

the class ResultSetScannerInterceptor method postProcess.

@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;
        }
    });
}
Also used : ResultSetInternalMethods(com.mysql.cj.jdbc.result.ResultSetInternalMethods) Matcher(java.util.regex.Matcher) SQLException(java.sql.SQLException) Resultset(com.mysql.cj.protocol.Resultset) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Aggregations

Resultset (com.mysql.cj.protocol.Resultset)14 IOException (java.io.IOException)9 Row (com.mysql.cj.result.Row)7 NativePacketPayload (com.mysql.cj.protocol.a.NativePacketPayload)6 StringValueFactory (com.mysql.cj.result.StringValueFactory)6 NativeProtocol (com.mysql.cj.protocol.a.NativeProtocol)5 ResultsetFactory (com.mysql.cj.protocol.a.ResultsetFactory)5 ResultsetRow (com.mysql.cj.protocol.ResultsetRow)4 ArrayList (java.util.ArrayList)4 ColumnDefinition (com.mysql.cj.protocol.ColumnDefinition)3 ResultsetRows (com.mysql.cj.protocol.ResultsetRows)3 Test (org.junit.jupiter.api.Test)3 CJException (com.mysql.cj.exceptions.CJException)2 ClientPreparedStatement (com.mysql.cj.jdbc.ClientPreparedStatement)2 ResultSetInternalMethods (com.mysql.cj.jdbc.result.ResultSetInternalMethods)2 OkPacket (com.mysql.cj.protocol.a.result.OkPacket)2 ResultsetRowsStatic (com.mysql.cj.protocol.a.result.ResultsetRowsStatic)2 Field (com.mysql.cj.result.Field)2 LongValueFactory (com.mysql.cj.result.LongValueFactory)2 InputStream (java.io.InputStream)2