Search in sources :

Example 16 with SQLWarning

use of java.sql.SQLWarning in project flyway by flyway.

the class JdbcTemplate method executeStatement.

/**
     * Executes this sql statement using an ordinary Statement.
     *
     * @param sql The statement to execute.
     * @throws SQLException when the execution failed.
     */
public void executeStatement(String sql) throws SQLException {
    Statement statement = null;
    try {
        statement = connection.createStatement();
        statement.setEscapeProcessing(false);
        boolean hasResults = false;
        try {
            hasResults = statement.execute(sql);
        } finally {
            @SuppressWarnings("ThrowableResultOfMethodCallIgnored") SQLWarning warning = statement.getWarnings();
            while (warning != null) {
                if ("00000".equals(warning.getSQLState())) {
                    LOG.info("DB: " + warning.getMessage());
                } else {
                    LOG.warn("DB: " + warning.getMessage() + " (SQL State: " + warning.getSQLState() + " - Error Code: " + warning.getErrorCode() + ")");
                }
                warning = warning.getNextWarning();
            }
            // retrieve all results to ensure all errors are detected
            int updateCount = -1;
            while (hasResults || (updateCount = statement.getUpdateCount()) != -1) {
                if (updateCount != -1) {
                    LOG.debug("Update Count: " + updateCount);
                }
                hasResults = statement.getMoreResults();
            }
        }
    } finally {
        JdbcUtils.closeStatement(statement);
    }
}
Also used : SQLWarning(java.sql.SQLWarning) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement)

Example 17 with SQLWarning

use of java.sql.SQLWarning in project dbeaver by dbeaver.

the class TableToolDialog method getScriptListener.

@Override
protected SQLScriptProgressListener<PostgreObject> getScriptListener() {
    return new SQLScriptStatusDialog<PostgreObject>(getTitle() + " progress", null) {

        @Override
        protected void createStatusColumns(Tree objectTree) {
            TreeColumn msgColumn = new TreeColumn(objectTree, SWT.NONE);
            msgColumn.setText("Message");
        }

        @Override
        public void processObjectResults(@NotNull PostgreObject object, @Nullable DBCStatement statement, @Nullable DBCResultSet resultSet) throws DBCException {
            if (statement == null) {
                return;
            }
            TreeItem treeItem = getTreeItem(object);
            if (treeItem != null) {
                try {
                    int warnNum = 0;
                    SQLWarning warning = ((JDBCStatement) statement).getWarnings();
                    while (warning != null) {
                        if (warnNum == 0) {
                            treeItem.setText(1, warning.getMessage());
                        } else {
                            TreeItem warnItem = new TreeItem(treeItem, SWT.NONE);
                            warnItem.setText(0, "");
                            warnItem.setText(1, warning.getMessage());
                        }
                        warnNum++;
                        warning = warning.getNextWarning();
                    }
                    if (warnNum == 0) {
                        treeItem.setText(1, "Done");
                    }
                } catch (SQLException e) {
                // ignore
                }
                treeItem.setExpanded(true);
            }
        }

        @Override
        public void endObjectProcessing(@NotNull PostgreObject object, Exception error) {
            super.endObjectProcessing(object, error);
            if (error != null) {
                TreeItem treeItem = getTreeItem(object);
                if (treeItem != null) {
                    treeItem.setText(1, error.getMessage());
                }
            }
        }
    };
}
Also used : SQLWarning(java.sql.SQLWarning) TreeItem(org.eclipse.swt.widgets.TreeItem) SQLException(java.sql.SQLException) NotNull(org.jkiss.code.NotNull) DBCStatement(org.jkiss.dbeaver.model.exec.DBCStatement) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) SQLScriptStatusDialog(org.jkiss.dbeaver.ui.dialogs.sql.SQLScriptStatusDialog) DBCException(org.jkiss.dbeaver.model.exec.DBCException) SQLException(java.sql.SQLException) JDBCStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement) TreeColumn(org.eclipse.swt.widgets.TreeColumn) Tree(org.eclipse.swt.widgets.Tree) PostgreObject(org.jkiss.dbeaver.ext.postgresql.model.PostgreObject) DBCResultSet(org.jkiss.dbeaver.model.exec.DBCResultSet) Nullable(org.jkiss.code.Nullable)

Example 18 with SQLWarning

use of java.sql.SQLWarning in project invesdwin-context-persistence by subes.

the class MySqlLoadDataInfile method internalPersist.

@SuppressWarnings("GuardedBy")
@Transactional
private int internalPersist(final StringBuilder workFileAndOutputStream) throws SQLException {
    try (Connection conn = ds.getConnection()) {
        try (com.mysql.jdbc.Statement stmt = conn.createStatement().unwrap(com.mysql.jdbc.Statement.class)) {
            final boolean prevAutoCommit = conn.getAutoCommit();
            if (disabledChecks) {
                if (prevAutoCommit) {
                    stmt.execute("set autocommit=0");
                }
                stmt.execute("set unique_checks=0");
                stmt.execute("set foreign_key_checks=0");
            }
            final String query = createQuery("memoryFile.txt");
            // http://jeffrick.com/2010/03/23/bulk-insert-into-a-mysql-database/
            stmt.setLocalInfileInputStream(IOUtils.toInputStream(workFileAndOutputStream.toString(), Charset.defaultCharset()));
            final int countUpdated = stmt.executeUpdate(query);
            final SQLWarning warnings = conn.getWarnings();
            if (disabledChecks) {
                stmt.execute("set foreign_key_checks=1");
                stmt.execute("set unique_checks=1");
                if (prevAutoCommit) {
                    stmt.execute("set autocommit=1");
                }
            }
            if (warnings != null) {
                throw warnings;
            }
            return countUpdated;
        }
    }
}
Also used : SQLWarning(java.sql.SQLWarning) Connection(java.sql.Connection) Transactional(org.springframework.transaction.annotation.Transactional)

Example 19 with SQLWarning

use of java.sql.SQLWarning in project mssql-jdbc by Microsoft.

the class JDBCSyntaxTranslator method getNextResult.

/**
 * Get the next result in the TDS response token stream, which may be a result set, update count or exception.
 *
 * @return true if another result (ResultSet or update count) was available; false if there were no more results.
 */
final boolean getNextResult() throws SQLServerException {
    /**
     * TDS response token stream handler used to locate the next result in the TDS response token stream.
     */
    final class NextResult extends TDSTokenHandler {

        private StreamDone stmtDoneToken = null;

        final boolean isUpdateCount() {
            return null != stmtDoneToken;
        }

        final long getUpdateCount() {
            return stmtDoneToken.getUpdateCount();
        }

        private boolean isResultSet = false;

        final boolean isResultSet() {
            return isResultSet;
        }

        private StreamRetStatus procedureRetStatToken = null;

        NextResult() {
            super("getNextResult");
        }

        boolean onColMetaData(TDSReader tdsReader) throws SQLServerException {
            // so return it.
            if (null != stmtDoneToken)
                return false;
            // up as an SQLException.
            if (null != getDatabaseError())
                return false;
            // Otherwise, column metadata indicates the start of a ResultSet
            isResultSet = true;
            return false;
        }

        boolean onDone(TDSReader tdsReader) throws SQLServerException {
            // Consume the done token and decide what to do with it...
            // Handling DONE/DONEPROC/DONEINPROC tokens is a little tricky...
            StreamDone doneToken = new StreamDone();
            doneToken.setFromTDS(tdsReader);
            // whether we've seen this ack.
            if (doneToken.isAttnAck())
                return false;
            // other tokens. And there are exceptions to that rule ...
            if (doneToken.cmdIsDMLOrDDL()) {
                // status (Statement.SUCCESS_NO_INFO)
                if (-1 == doneToken.getUpdateCount() && EXECUTE_BATCH != executeMethod)
                    return true;
                if (-1 != doneToken.getUpdateCount() && EXECUTE_QUERY == executeMethod)
                    return true;
                // Otherwise, the update count is valid. Now determine whether we should
                // return it as a result...
                stmtDoneToken = doneToken;
                // another as they are both just concatenated statements.
                if (TDS.TDS_DONEINPROC != doneToken.getTokenType())
                    return false;
                if (EXECUTE_BATCH != executeMethod) {
                    // Always return update counts from statements executed in stored procedure calls.
                    if (null != procedureName)
                        return false;
                    // Always return all update counts from statements executed through Statement.execute()
                    if (EXECUTE == executeMethod)
                        return false;
                    // Otherwise (lastUpdateCount=false), return this update count.
                    if (!connection.useLastUpdateCount())
                        return false;
                // An update count from a statement that appears to have been executed in a stored
                // procedure call, when no stored procedure was called, is assumed to be the result of
                // a trigger firing. Skip it for now until/unless it is shown to be the last update
                // count of a statement's execution.
                }
            } else // A done token without an update count usually just indicates the execution
            // of a SQL statement that isn't an INSERT, UPDATE, DELETE or DDL, and it should
            // be ignored. However, some of these done tokens have special meaning that we
            // need to consider...
            {
                // even if there is no update count.
                if (doneToken.isFinal()) {
                    moreResults = false;
                    return false;
                }
                if (EXECUTE_BATCH == executeMethod) {
                    // of the result, even if there is no update count.
                    if (TDS.TDS_DONEINPROC != doneToken.getTokenType() || doneToken.wasRPCInBatch()) {
                        moreResults = false;
                        return false;
                    }
                }
            }
            // In this case, the command is likely to be a RAISERROR, but it could be anything.
            if (doneToken.isError())
                return false;
            // In all other cases, keep parsing
            return true;
        }

        boolean onRetStatus(TDSReader tdsReader) throws SQLServerException {
            // the prepared statement handle from them.
            if (consumeExecOutParam(tdsReader)) {
                moreResults = false;
            } else // If this RETSTATUS token is not the one that begins the statement execution OUT
            // parameters, then it must be one from a stored procedure that was called by
            // the query itself. In that case, it should be ignored as it does not contribute
            // to any result. It may mark the start of application OUT parameters, however,
            // so remember that we've seen it so that we don't ignore the RETVALUE tokens that
            // may follow.
            {
                procedureRetStatToken = new StreamRetStatus();
                procedureRetStatToken.setFromTDS(tdsReader);
            }
            return true;
        }

        boolean onRetValue(TDSReader tdsReader) throws SQLServerException {
            // token, is a TEXTPTR return value that should be ignored.
            if (moreResults && null == procedureRetStatToken) {
                Parameter p = new Parameter(Util.shouldHonorAEForParameters(stmtColumnEncriptionSetting, connection));
                p.skipRetValStatus(tdsReader);
                p.skipValue(tdsReader, true);
                return true;
            }
            return false;
        }

        boolean onInfo(TDSReader tdsReader) throws SQLServerException {
            StreamInfo infoToken = new StreamInfo();
            infoToken.setFromTDS(tdsReader);
            // 
            if (16954 == infoToken.msg.getErrorNumber())
                executedSqlDirectly = true;
            SQLWarning warning = new SQLWarning(infoToken.msg.getMessage(), SQLServerException.generateStateCode(connection, infoToken.msg.getErrorNumber(), infoToken.msg.getErrorState()), infoToken.msg.getErrorNumber());
            if (sqlWarnings == null) {
                sqlWarnings = new Vector<>();
            } else {
                int n = sqlWarnings.size();
                SQLWarning w = sqlWarnings.elementAt(n - 1);
                w.setNextWarning(warning);
            }
            sqlWarnings.add(warning);
            return true;
        }
    }
    // If the statement has no results yet, then return
    if (!wasExecuted()) {
        moreResults = false;
        return false;
    }
    // Clear out previous results
    clearLastResult();
    // All we had to do was to close out the previous results.
    if (!moreResults)
        return false;
    // Figure out the next result.
    NextResult nextResult = new NextResult();
    TDSParser.parse(resultsReader(), nextResult);
    // Check for errors first.
    if (null != nextResult.getDatabaseError()) {
        SQLServerException.makeFromDatabaseError(connection, null, nextResult.getDatabaseError().getMessage(), nextResult.getDatabaseError(), false);
    } else // Not an error. Is it a result set?
    if (nextResult.isResultSet()) {
        // Make sure SQLServerResultSet42 is used for 4.2 and above
        if (Util.use42Wrapper() || Util.use43Wrapper()) {
            resultSet = new SQLServerResultSet42(this);
        } else {
            resultSet = new SQLServerResultSet(this);
        }
        return true;
    } else // update count arrays).
    if (nextResult.isUpdateCount()) {
        updateCount = nextResult.getUpdateCount();
        return true;
    }
    // None of the above. Last chance here... Going into the parser above, we know
    // moreResults was initially true. If we come out with moreResults false, then
    // we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates
    // that the batch succeeded overall, but that there is no information on individual
    // statements' update counts. This is similar to the last case above, except that
    // there is no update count. That is: we have a successful result (return true),
    // but we have no other information about it (updateCount = -1).
    updateCount = -1;
    if (!moreResults)
        return true;
    // Only way to get here (moreResults is still true, but no apparent results of any kind)
    // is if the TDSParser didn't actually parse _anything_. That is, we are at EOF in the
    // response. In that case, there truly are no more results. We're done.
    moreResults = false;
    return false;
}
Also used : SQLWarning(java.sql.SQLWarning)

Example 20 with SQLWarning

use of java.sql.SQLWarning in project mssql-jdbc by Microsoft.

the class JDBCSyntaxTranslator method getWarnings.

/* L0 */
public final SQLWarning getWarnings() throws SQLServerException {
    loggerExternal.entering(getClassNameLogging(), "getWarnings");
    checkClosed();
    if (sqlWarnings == null)
        return null;
    SQLWarning warn = sqlWarnings.elementAt(0);
    loggerExternal.exiting(getClassNameLogging(), "getWarnings", warn);
    return warn;
}
Also used : SQLWarning(java.sql.SQLWarning)

Aggregations

SQLWarning (java.sql.SQLWarning)147 SQLException (java.sql.SQLException)47 Statement (java.sql.Statement)35 PreparedStatement (java.sql.PreparedStatement)30 Connection (java.sql.Connection)24 ResultSet (java.sql.ResultSet)23 Test (org.testng.annotations.Test)19 Test (org.junit.Test)17 BaseTest (util.BaseTest)15 CallableStatement (java.sql.CallableStatement)13 ArrayList (java.util.ArrayList)9 JDBCStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement)8 ResultSetMetaData (java.sql.ResultSetMetaData)6 Expectations (org.jmock.Expectations)6 IOException (java.io.IOException)4 FilterChainImpl (com.alibaba.druid.filter.FilterChainImpl)3 PrestoWarning (com.facebook.presto.spi.PrestoWarning)3 HashSet (java.util.HashSet)3 Properties (java.util.Properties)3 LanguageConnectionContext (org.apache.derby.iapi.sql.conn.LanguageConnectionContext)3