Java Code Examples for com.mysql.cj.util.StringUtils#startsWithIgnoreCaseAndWs()

The following examples show how to use com.mysql.cj.util.StringUtils#startsWithIgnoreCaseAndWs() . 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
/**
 * 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 2
Source Project: lams   File: StatementImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static int findStartOfStatement(String sql) {
    int statementStartPos = 0;

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
        statementStartPos = sql.indexOf("*/");

        if (statementStartPos == -1) {
            statementStartPos = 0;
        } else {
            statementStartPos += 2;
        }
    } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
        statementStartPos = sql.indexOf('\n');

        if (statementStartPos == -1) {
            statementStartPos = sql.indexOf('\r');

            if (statementStartPos == -1) {
                statementStartPos = 0;
            }
        }
    }

    return statementStartPos;
}
 
Example 3
/**
 * Creates a new CallableStatement
 * 
 * @param conn
 *            the connection creating this statement
 * @param sql
 *            the SQL to prepare
 * @param catalog
 *            the current catalog
 * 
 * @throws SQLException
 *             if an error occurs
 */
public CallableStatement(JdbcConnection conn, String sql, String catalog, boolean isFunctionCall) throws SQLException {
    super(conn, sql, catalog);

    this.callingStoredFunction = isFunctionCall;

    if (!this.callingStoredFunction) {
        if (!StringUtils.startsWithIgnoreCaseAndWs(sql, "CALL")) {
            // not really a stored procedure call
            fakeParameterTypes(false);
        } else {
            determineParameterTypes();
        }

        generateParameterMap();
    } else {
        determineParameterTypes();
        generateParameterMap();

        ((PreparedQuery<?>) this.query).setParameterCount(((PreparedQuery<?>) this.query).getParameterCount() + 1);
    }

    this.retrieveGeneratedKeys = true; // not provided for in the JDBC spec
    this.noAccessToProcedureBodies = conn.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_noAccessToProcedureBodies).getValue();
}
 
Example 4
Source Project: lams   File: ParseInfo.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static int findStartOfStatement(String sql) {
    int statementStartPos = 0;

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
        statementStartPos = sql.indexOf("*/");

        if (statementStartPos == -1) {
            statementStartPos = 0;
        } else {
            statementStartPos += 2;
        }
    } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
        statementStartPos = sql.indexOf('\n');

        if (statementStartPos == -1) {
            statementStartPos = sql.indexOf('\r');

            if (statementStartPos == -1) {
                statementStartPos = 0;
            }
        }
    }

    return statementStartPos;
}
 
Example 5
Source Project: lams   File: ParseInfo.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static boolean canRewrite(String sql, boolean isOnDuplicateKeyUpdate, int locationOfOnDuplicateKeyUpdate, int statementStartPos) {
    // Needs to be INSERT or REPLACE.
    // Can't have INSERT ... SELECT or INSERT ... ON DUPLICATE KEY UPDATE with an id=LAST_INSERT_ID(...).

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "INSERT", statementStartPos)) {
        if (StringUtils.indexOfIgnoreCase(statementStartPos, sql, "SELECT", "\"'`", "\"'`", StringUtils.SEARCH_MODE__MRK_COM_WS) != -1) {
            return false;
        }
        if (isOnDuplicateKeyUpdate) {
            int updateClausePos = StringUtils.indexOfIgnoreCase(locationOfOnDuplicateKeyUpdate, sql, " UPDATE ");
            if (updateClausePos != -1) {
                return StringUtils.indexOfIgnoreCase(updateClausePos, sql, "LAST_INSERT_ID", "\"'`", "\"'`", StringUtils.SEARCH_MODE__MRK_COM_WS) == -1;
            }
        }
        return true;
    }

    return StringUtils.startsWithIgnoreCaseAndWs(sql, "REPLACE", statementStartPos)
            && StringUtils.indexOfIgnoreCase(statementStartPos, sql, "SELECT", "\"'`", "\"'`", StringUtils.SEARCH_MODE__MRK_COM_WS) == -1;
}
 
Example 6
protected static int findStartOfStatement(String sql) {
    int statementStartPos = 0;

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
        statementStartPos = sql.indexOf("*/");

        if (statementStartPos == -1) {
            statementStartPos = 0;
        } else {
            statementStartPos += 2;
        }
    } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
        statementStartPos = sql.indexOf('\n');

        if (statementStartPos == -1) {
            statementStartPos = sql.indexOf('\r');

            if (statementStartPos == -1) {
                statementStartPos = 0;
            }
        }
    }

    return statementStartPos;
}
 
Example 7
Source Project: FoxTelem   File: ParseInfo.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected static boolean canRewrite(String sql, boolean isOnDuplicateKeyUpdate, int locationOfOnDuplicateKeyUpdate, int statementStartPos) {
    // Needs to be INSERT or REPLACE.
    // Can't have INSERT ... SELECT or INSERT ... ON DUPLICATE KEY UPDATE with an id=LAST_INSERT_ID(...).

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "INSERT", statementStartPos)) {
        if (StringUtils.indexOfIgnoreCase(statementStartPos, sql, "SELECT", "\"'`", "\"'`", StringUtils.SEARCH_MODE__MRK_COM_WS) != -1) {
            return false;
        }
        if (isOnDuplicateKeyUpdate) {
            int updateClausePos = StringUtils.indexOfIgnoreCase(locationOfOnDuplicateKeyUpdate, sql, " UPDATE ");
            if (updateClausePos != -1) {
                return StringUtils.indexOfIgnoreCase(updateClausePos, sql, "LAST_INSERT_ID", "\"'`", "\"'`", StringUtils.SEARCH_MODE__MRK_COM_WS) == -1;
            }
        }
        return true;
    }

    return StringUtils.startsWithIgnoreCaseAndWs(sql, "REPLACE", statementStartPos)
            && StringUtils.indexOfIgnoreCase(statementStartPos, sql, "SELECT", "\"'`", "\"'`", StringUtils.SEARCH_MODE__MRK_COM_WS) == -1;
}
 
Example 8
public void configureCharacterSets() {
    //
    // We need to figure out what character set metadata and error messages will be returned in, and then map them to Java encoding names
    //
    // We've already set it, and it might be different than what was originally on the server, which is why we use the "special" key to retrieve it
    String characterSetResultsOnServerMysql = getServerVariable(LOCAL_CHARACTER_SET_RESULTS);

    if (characterSetResultsOnServerMysql == null || StringUtils.startsWithIgnoreCaseAndWs(characterSetResultsOnServerMysql, "NULL")
            || characterSetResultsOnServerMysql.length() == 0) {
        String defaultMetadataCharsetMysql = getServerVariable("character_set_system");
        String defaultMetadataCharset = null;

        if (defaultMetadataCharsetMysql != null) {
            defaultMetadataCharset = CharsetMapping.getJavaEncodingForMysqlCharset(defaultMetadataCharsetMysql);
        } else {
            defaultMetadataCharset = "UTF-8";
        }

        this.characterSetMetadata = defaultMetadataCharset;
        setErrorMessageEncoding("UTF-8");
    } else {
        this.characterSetResultsOnServer = CharsetMapping.getJavaEncodingForMysqlCharset(characterSetResultsOnServerMysql);
        this.characterSetMetadata = this.characterSetResultsOnServer;
        setErrorMessageEncoding(this.characterSetResultsOnServer);
    }

    this.metadataCollationIndex = CharsetMapping.getCollationIndexForJavaEncoding(this.characterSetMetadata, getServerVersion());
}
 
Example 9
Source Project: lams   File: StatementImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if the given SQL query with the given first non-ws char is a DML
 * statement. Throws an exception if it is.
 * 
 * @param sql
 *            the SQL to check
 * @param firstStatementChar
 *            the UC first non-ws char of the statement
 * 
 * @throws SQLException
 *             if the statement contains DML
 */
protected void checkForDml(String sql, char firstStatementChar) throws SQLException {
    if ((firstStatementChar == 'I') || (firstStatementChar == 'U') || (firstStatementChar == 'D') || (firstStatementChar == 'A')
            || (firstStatementChar == 'C') || (firstStatementChar == 'T') || (firstStatementChar == 'R')) {
        String noCommentSql = StringUtils.stripComments(sql, "'\"", "'\"", true, false, true, true);

        if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "TRUNCATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "RENAME")) {
            throw SQLError.createSQLException(Messages.getString("Statement.57"), MysqlErrorNumbers.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }
    }
}
 
Example 10
/**
 * Checks if the given SQL query with the given first non-ws char is a DML
 * statement. Throws an exception if it is.
 * 
 * @param sql
 *            the SQL to check
 * @param firstStatementChar
 *            the UC first non-ws char of the statement
 * 
 * @throws SQLException
 *             if the statement contains DML
 */
protected void checkForDml(String sql, char firstStatementChar) throws SQLException {
    if ((firstStatementChar == 'I') || (firstStatementChar == 'U') || (firstStatementChar == 'D') || (firstStatementChar == 'A')
            || (firstStatementChar == 'C') || (firstStatementChar == 'T') || (firstStatementChar == 'R')) {
        String noCommentSql = StringUtils.stripComments(sql, "'\"", "'\"", true, false, true, true);

        if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "TRUNCATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "RENAME")) {
            throw SQLError.createSQLException(Messages.getString("Statement.57"), MysqlErrorNumbers.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }
    }
}
 
Example 11
public void configureCharacterSets() {
    //
    // We need to figure out what character set metadata and error messages will be returned in, and then map them to Java encoding names
    //
    // We've already set it, and it might be different than what was originally on the server, which is why we use the "special" key to retrieve it
    String characterSetResultsOnServerMysql = getServerVariable(LOCAL_CHARACTER_SET_RESULTS);

    if (characterSetResultsOnServerMysql == null || StringUtils.startsWithIgnoreCaseAndWs(characterSetResultsOnServerMysql, "NULL")
            || characterSetResultsOnServerMysql.length() == 0) {
        String defaultMetadataCharsetMysql = getServerVariable("character_set_system");
        String defaultMetadataCharset = null;

        if (defaultMetadataCharsetMysql != null) {
            defaultMetadataCharset = CharsetMapping.getJavaEncodingForMysqlCharset(defaultMetadataCharsetMysql);
        } else {
            defaultMetadataCharset = "UTF-8";
        }

        this.characterSetMetadata = defaultMetadataCharset;
        setErrorMessageEncoding("UTF-8");
    } else {
        this.characterSetResultsOnServer = CharsetMapping.getJavaEncodingForMysqlCharset(characterSetResultsOnServerMysql);
        this.characterSetMetadata = this.characterSetResultsOnServer;
        setErrorMessageEncoding(this.characterSetResultsOnServer);
    }

    this.metadataCollationIndex = CharsetMapping.getCollationIndexForJavaEncoding(this.characterSetMetadata, getServerVersion());
}
 
Example 12
/**
 * 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 13
/**
 * 
 * @param sql
 * @throws IOException
 */
public void serverPrepare(String sql) throws IOException {
    this.session.checkClosed();

    synchronized (this.session) {
        long begin = 0;

        if (this.profileSQL) {
            begin = System.currentTimeMillis();
        }

        boolean loadDataQuery = StringUtils.startsWithIgnoreCaseAndWs(sql, "LOAD DATA");

        String characterEncoding = null;
        String connectionEncoding = this.session.getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_characterEncoding).getValue();

        if (!loadDataQuery && (connectionEncoding != null)) {
            characterEncoding = connectionEncoding;
        }

        NativePacketPayload prepareResultPacket = this.session
                .sendCommand(this.commandBuilder.buildComStmtPrepare(this.session.getSharedSendPacket(), sql, characterEncoding), false, 0);

        // 4.1.1 and newer use the first byte as an 'ok' or 'error' flag, so move the buffer pointer past it to start reading the statement id.
        prepareResultPacket.setPosition(1);

        this.serverStatementId = prepareResultPacket.readInteger(IntegerDataType.INT4);
        int fieldCount = (int) prepareResultPacket.readInteger(IntegerDataType.INT2);
        setParameterCount((int) prepareResultPacket.readInteger(IntegerDataType.INT2));

        this.queryBindings = new ServerPreparedQueryBindings(this.parameterCount, this.session);
        this.queryBindings.setLoadDataQuery(loadDataQuery);

        this.session.incrementNumberOfPrepares();

        if (this.profileSQL) {
            this.eventSink.consumeEvent(new ProfilerEventImpl(ProfilerEvent.TYPE_PREPARE, "", this.getCurrentCatalog(), this.session.getThreadId(),
                    this.statementId, -1, System.currentTimeMillis(), this.session.getCurrentTimeNanosOrMillis() - begin,
                    this.session.getQueryTimingUnits(), null, LogUtils.findCallingClassAndMethod(new Throwable()), truncateQueryToLog(sql)));
        }

        boolean checkEOF = !this.session.getServerSession().isEOFDeprecated();

        if (this.parameterCount > 0) {
            if (checkEOF) { // Skip the following EOF packet.
                this.session.getProtocol().skipPacket();
            }

            this.parameterFields = this.session.getProtocol().read(ColumnDefinition.class, new ColumnDefinitionFactory(this.parameterCount, null))
                    .getFields();
        }

        // Read in the result set column information
        if (fieldCount > 0) {
            this.resultFields = this.session.getProtocol().read(ColumnDefinition.class, new ColumnDefinitionFactory(fieldCount, null));
        }
    }
}
 
Example 14
Source Project: lams   File: StatementImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
protected long executeUpdateInternal(String sql, boolean isBatch, boolean returnGeneratedKeys) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        JdbcConnection locallyScopedConn = this.connection;

        checkNullOrEmptyQuery(sql);

        resetCancelledState();

        char firstStatementChar = StringUtils.firstAlphaCharUc(sql, findStartOfStatement(sql));

        this.retrieveGeneratedKeys = returnGeneratedKeys;

        this.lastQueryIsOnDupKeyUpdate = returnGeneratedKeys && firstStatementChar == 'I' && containsOnDuplicateKeyInString(sql);

        ResultSetInternalMethods rs = null;

        if (this.doEscapeProcessing) {
            Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, this.session.getServerSession().getDefaultTimeZone(),
                    this.session.getServerSession().getCapabilities().serverSupportsFracSecs(), getExceptionInterceptor());
            sql = escapedSqlResult instanceof String ? (String) escapedSqlResult : ((EscapeProcessorResult) escapedSqlResult).escapedSql;
        }

        if (locallyScopedConn.isReadOnly(false)) {
            throw SQLError.createSQLException(Messages.getString("Statement.42") + Messages.getString("Statement.43"),
                    MysqlErrorNumbers.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }

        if (StringUtils.startsWithIgnoreCaseAndWs(sql, "select")) {
            throw SQLError.createSQLException(Messages.getString("Statement.46"), "01S03", getExceptionInterceptor());
        }

        implicitlyCloseAllOpenResults();

        // The checking and changing of catalogs must happen in sequence, so synchronize on the same mutex that _conn is using

        CancelQueryTask timeoutTask = null;

        String oldCatalog = null;

        try {
            timeoutTask = startQueryTimer(this, getTimeoutInMillis());

            if (!locallyScopedConn.getCatalog().equals(getCurrentCatalog())) {
                oldCatalog = locallyScopedConn.getCatalog();
                locallyScopedConn.setCatalog(getCurrentCatalog());
            }

            //
            // Only apply max_rows to selects
            //
            locallyScopedConn.setSessionMaxRows(-1);

            statementBegins();

            // null catalog: force read of field info on DML
            rs = ((NativeSession) locallyScopedConn.getSession()).execSQL(this, sql, -1, null, false, getResultSetFactory(), getCurrentCatalog(), null,
                    isBatch);

            if (timeoutTask != null) {
                stopQueryTimer(timeoutTask, true, true);
                timeoutTask = null;
            }

        } catch (CJTimeoutException | OperationCancelledException e) {
            throw SQLExceptionsMapping.translateException(e, this.exceptionInterceptor);

        } finally {
            stopQueryTimer(timeoutTask, false, false);

            if (oldCatalog != null) {
                locallyScopedConn.setCatalog(oldCatalog);
            }

            if (!isBatch) {
                this.query.getStatementExecuting().set(false);
            }
        }

        this.results = rs;

        rs.setFirstCharOfQuery(firstStatementChar);

        this.updateCount = rs.getUpdateCount();

        this.lastInsertId = rs.getUpdateID();

        return this.updateCount;
    }
}
 
Example 15
protected boolean isSelectQuery() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        return StringUtils.startsWithIgnoreCaseAndWs(
                StringUtils.stripComments(((PreparedQuery<?>) this.query).getOriginalSql(), "'\"", "'\"", true, false, true, true), "SELECT");
    }
}
 
Example 16
/**
 * Check whether the stored procedure alters any data or is safe for read-only usage.
 * 
 * @return true if procedure does not alter data
 * @throws SQLException
 */
private boolean checkReadOnlyProcedure() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.noAccessToProcedureBodies) {
            return false;
        }

        if (this.paramInfo.isReadOnlySafeChecked) {
            return this.paramInfo.isReadOnlySafeProcedure;
        }

        ResultSet rs = null;
        java.sql.PreparedStatement ps = null;

        try {
            String procName = extractProcedureName();

            String catalog = this.getCurrentCatalog();

            if (procName.indexOf(".") != -1) {
                catalog = procName.substring(0, procName.indexOf("."));

                if (StringUtils.startsWithIgnoreCaseAndWs(catalog, "`") && catalog.trim().endsWith("`")) {
                    catalog = catalog.substring(1, catalog.length() - 1);
                }

                procName = procName.substring(procName.indexOf(".") + 1);
                procName = StringUtils.toString(StringUtils.stripEnclosure(StringUtils.getBytes(procName), "`", "`"));
            }
            ps = this.connection.prepareStatement("SELECT SQL_DATA_ACCESS FROM information_schema.routines WHERE routine_schema = ? AND routine_name = ?");
            ps.setMaxRows(0);
            ps.setFetchSize(0);

            ps.setString(1, catalog);
            ps.setString(2, procName);
            rs = ps.executeQuery();
            if (rs.next()) {
                String sqlDataAccess = rs.getString(1);
                if ("READS SQL DATA".equalsIgnoreCase(sqlDataAccess) || "NO SQL".equalsIgnoreCase(sqlDataAccess)) {
                    synchronized (this.paramInfo) {
                        this.paramInfo.isReadOnlySafeChecked = true;
                        this.paramInfo.isReadOnlySafeProcedure = true;
                    }
                    return true;
                }
            }
        } catch (SQLException e) {
            // swallow the Exception
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }

        }
        this.paramInfo.isReadOnlySafeChecked = false;
        this.paramInfo.isReadOnlySafeProcedure = false;
    }
    return false;

}
 
Example 17
/**
 * 
 * @param sql
 *            query string
 * @throws IOException
 *             if an i/o error occurs
 */
public void serverPrepare(String sql) throws IOException {
    this.session.checkClosed();

    synchronized (this.session) {
        long begin = 0;

        if (this.profileSQL) {
            begin = System.currentTimeMillis();
        }

        boolean loadDataQuery = StringUtils.startsWithIgnoreCaseAndWs(sql, "LOAD DATA");

        String characterEncoding = null;
        String connectionEncoding = this.session.getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue();

        if (!loadDataQuery && (connectionEncoding != null)) {
            characterEncoding = connectionEncoding;
        }

        NativePacketPayload prepareResultPacket = this.session
                .sendCommand(this.commandBuilder.buildComStmtPrepare(this.session.getSharedSendPacket(), sql, characterEncoding), false, 0);

        // 4.1.1 and newer use the first byte as an 'ok' or 'error' flag, so move the buffer pointer past it to start reading the statement id.
        prepareResultPacket.setPosition(1);

        this.serverStatementId = prepareResultPacket.readInteger(IntegerDataType.INT4);
        int fieldCount = (int) prepareResultPacket.readInteger(IntegerDataType.INT2);
        setParameterCount((int) prepareResultPacket.readInteger(IntegerDataType.INT2));

        this.queryBindings = new ServerPreparedQueryBindings(this.parameterCount, this.session);
        this.queryBindings.setLoadDataQuery(loadDataQuery);

        this.session.incrementNumberOfPrepares();

        if (this.profileSQL) {
            this.eventSink.consumeEvent(new ProfilerEventImpl(ProfilerEvent.TYPE_PREPARE, "", this.getCurrentCatalog(), this.session.getThreadId(),
                    this.statementId, -1, System.currentTimeMillis(), this.session.getCurrentTimeNanosOrMillis() - begin,
                    this.session.getQueryTimingUnits(), null, LogUtils.findCallingClassAndMethod(new Throwable()), truncateQueryToLog(sql)));
        }

        boolean checkEOF = !this.session.getServerSession().isEOFDeprecated();

        if (this.parameterCount > 0) {
            if (checkEOF) { // Skip the following EOF packet.
                this.session.getProtocol().skipPacket();
            }

            this.parameterFields = this.session.getProtocol().read(ColumnDefinition.class, new ColumnDefinitionFactory(this.parameterCount, null))
                    .getFields();
        }

        // Read in the result set column information
        if (fieldCount > 0) {
            this.resultFields = this.session.getProtocol().read(ColumnDefinition.class, new ColumnDefinitionFactory(fieldCount, null));
        }
    }
}
 
Example 18
protected boolean isSelectQuery() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        return StringUtils.startsWithIgnoreCaseAndWs(
                StringUtils.stripComments(((PreparedQuery<?>) this.query).getOriginalSql(), "'\"", "'\"", true, false, true, true), "SELECT");
    }
}
 
Example 19
/**
 * Check whether the stored procedure alters any data or is safe for read-only usage.
 * 
 * @return true if procedure does not alter data
 * @throws SQLException
 *             if a database access error occurs or this method is called on a closed PreparedStatement
 */
private boolean checkReadOnlyProcedure() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.noAccessToProcedureBodies) {
            return false;
        }

        if (this.paramInfo.isReadOnlySafeChecked) {
            return this.paramInfo.isReadOnlySafeProcedure;
        }

        ResultSet rs = null;
        java.sql.PreparedStatement ps = null;

        try {
            String procName = extractProcedureName();

            String catalog = this.getCurrentCatalog();

            if (procName.indexOf(".") != -1) {
                catalog = procName.substring(0, procName.indexOf("."));

                if (StringUtils.startsWithIgnoreCaseAndWs(catalog, "`") && catalog.trim().endsWith("`")) {
                    catalog = catalog.substring(1, catalog.length() - 1);
                }

                procName = procName.substring(procName.indexOf(".") + 1);
                procName = StringUtils.toString(StringUtils.stripEnclosure(StringUtils.getBytes(procName), "`", "`"));
            }
            ps = this.connection.prepareStatement("SELECT SQL_DATA_ACCESS FROM information_schema.routines WHERE routine_schema = ? AND routine_name = ?");
            ps.setMaxRows(0);
            ps.setFetchSize(0);

            ps.setString(1, catalog);
            ps.setString(2, procName);
            rs = ps.executeQuery();
            if (rs.next()) {
                String sqlDataAccess = rs.getString(1);
                if ("READS SQL DATA".equalsIgnoreCase(sqlDataAccess) || "NO SQL".equalsIgnoreCase(sqlDataAccess)) {
                    synchronized (this.paramInfo) {
                        this.paramInfo.isReadOnlySafeChecked = true;
                        this.paramInfo.isReadOnlySafeProcedure = true;
                    }
                    return true;
                }
            }
        } catch (SQLException e) {
            // swallow the Exception
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }

        }
        this.paramInfo.isReadOnlySafeChecked = false;
        this.paramInfo.isReadOnlySafeProcedure = false;
    }
    return false;

}
 
Example 20
/**
 * 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);
}