Example usage for org.springframework.jdbc.datasource.init ScriptStatementFailedException buildErrorMessage

List of usage examples for org.springframework.jdbc.datasource.init ScriptStatementFailedException buildErrorMessage

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource.init ScriptStatementFailedException buildErrorMessage.

Prototype

public static String buildErrorMessage(String stmt, int stmtNumber, EncodedResource encodedResource) 

Source Link

Document

Build an error message for an SQL script execution failure, based on the supplied arguments.

Usage

From source file:org.springframework.jdbc.datasource.init.ScriptUtils.java

/**
 * Execute the given SQL script./*from   www.ja  v  a  2s . c om*/
 * <p>Statement separators and comments will be removed before executing
 * individual statements within the supplied script.
 * <p><strong>Warning</strong>: this method does <em>not</em> release the
 * provided {@link Connection}.
 * @param connection the JDBC connection to use to execute the script; already
 * configured and ready to use
 * @param resource the resource (potentially associated with a specific encoding)
 * to load the SQL script from
 * @param continueOnError whether or not to continue without throwing an exception
 * in the event of an error
 * @param ignoreFailedDrops whether or not to continue in the event of specifically
 * an error on a {@code DROP} statement
 * @param commentPrefix the prefix that identifies single-line comments in the
 * SQL script &mdash; typically "--"
 * @param separator the script statement separator; defaults to
 * {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to
 * {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort; may be set to
 * {@value #EOF_STATEMENT_SEPARATOR} to signal that the script contains a
 * single statement without a separator
 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter; never
 * {@code null} or empty
 * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter; never
 * {@code null} or empty
 * @throws ScriptException if an error occurred while executing the SQL script
 * @see #DEFAULT_STATEMENT_SEPARATOR
 * @see #FALLBACK_STATEMENT_SEPARATOR
 * @see #EOF_STATEMENT_SEPARATOR
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection
 * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
 */
public static void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
        boolean ignoreFailedDrops, String commentPrefix, @Nullable String separator,
        String blockCommentStartDelimiter, String blockCommentEndDelimiter) throws ScriptException {

    try {
        if (logger.isInfoEnabled()) {
            logger.info("Executing SQL script from " + resource);
        }
        long startTime = System.currentTimeMillis();

        String script;
        try {
            script = readScript(resource, commentPrefix, separator);
        } catch (IOException ex) {
            throw new CannotReadScriptException(resource, ex);
        }

        if (separator == null) {
            separator = DEFAULT_STATEMENT_SEPARATOR;
        }
        if (!EOF_STATEMENT_SEPARATOR.equals(separator) && !containsSqlScriptDelimiters(script, separator)) {
            separator = FALLBACK_STATEMENT_SEPARATOR;
        }

        List<String> statements = new LinkedList<>();
        splitSqlScript(resource, script, separator, commentPrefix, blockCommentStartDelimiter,
                blockCommentEndDelimiter, statements);

        int stmtNumber = 0;
        Statement stmt = connection.createStatement();
        try {
            for (String statement : statements) {
                stmtNumber++;
                try {
                    stmt.execute(statement);
                    int rowsAffected = stmt.getUpdateCount();
                    if (logger.isDebugEnabled()) {
                        logger.debug(rowsAffected + " returned as update count for SQL: " + statement);
                        SQLWarning warningToLog = stmt.getWarnings();
                        while (warningToLog != null) {
                            logger.debug("SQLWarning ignored: SQL state '" + warningToLog.getSQLState()
                                    + "', error code '" + warningToLog.getErrorCode() + "', message ["
                                    + warningToLog.getMessage() + "]");
                            warningToLog = warningToLog.getNextWarning();
                        }
                    }
                } catch (SQLException ex) {
                    boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
                    if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(ScriptStatementFailedException.buildErrorMessage(statement, stmtNumber,
                                    resource), ex);
                        }
                    } else {
                        throw new ScriptStatementFailedException(statement, stmtNumber, resource, ex);
                    }
                }
            }
        } finally {
            try {
                stmt.close();
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Statement", ex);
            }
        }

        long elapsedTime = System.currentTimeMillis() - startTime;
        if (logger.isInfoEnabled()) {
            logger.info("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
        }
    } catch (Exception ex) {
        if (ex instanceof ScriptException) {
            throw (ScriptException) ex;
        }
        throw new UncategorizedScriptException(
                "Failed to execute database script from resource [" + resource + "]", ex);
    }
}