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

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

Introduction

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

Prototype

public ScriptStatementFailedException(String stmt, int stmtNumber, EncodedResource encodedResource,
        Throwable cause) 

Source Link

Document

Construct a new ScriptStatementFailedException .

Usage

From source file:com.excilys.ebi.bank.jdbc.SimpleBatchResourceDatabasePopulator.java

/**
 * Execute the given SQL script.//from  w ww .j  ava 2  s  .c  o m
 * <p>
 * The script will normally be loaded by classpath. There should be one
 * statement per line. Any {@link #setSeparator(String) statement
 * separators} will be removed.
 * <p>
 * <b>Do not use this method to execute DDL if you expect rollback.</b>
 *
 * @param connection
 *            the JDBC Connection with which to perform JDBC operations
 * @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 of not to continue in the event of specifically an
 *            error on a <code>DROP</code>
 */
private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
        boolean ignoreFailedDrops) throws SQLException, IOException {

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Executing SQL script from " + resource);
    }

    long startTime = System.currentTimeMillis();
    Iterator<String> statements = IOUtils.lineIterator(resource.getReader());
    int lineNumber = 0;

    boolean initialAutoCommitState = connection.getAutoCommit();

    connection.setAutoCommit(false);
    Statement stmt = connection.createStatement();
    try {
        while (statements.hasNext()) {
            String statement = statements.next();
            lineNumber++;
            try {
                stmt.addBatch(statement);

                if (lineNumber % batchSize == 0) {
                    stmt.executeBatch();
                    connection.commit();
                }
            } catch (SQLException ex) {
                boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
                if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Failed to execute SQL script statement at line " + lineNumber
                                + " of resource " + resource + ": " + statement, ex);
                    }
                } else {
                    Exception nextException = ex.getNextException();
                    throw new ScriptStatementFailedException(statement, lineNumber, resource,
                            nextException != null ? nextException : ex);
                }
            }
        }
    } finally {
        stmt.executeBatch();
        connection.commit();

        connection.setAutoCommit(initialAutoCommitState);

        try {
            stmt.close();
        } catch (Throwable ex) {
            LOGGER.debug("Could not close JDBC Statement", ex);
        }
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
    }
}

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

/**
 * Execute the given SQL script.//www .ja v  a2  s  .  co  m
 * <p>The script will normally be loaded by classpath. There should be one statement
 * per line. Any {@link #setSeparator(String) statement separators} will be removed.
 * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
 * @param connection the JDBC Connection with which to perform JDBC operations
 * @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 of not to continue in the event of specifically an error on a {@code DROP}
 */
private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
        boolean ignoreFailedDrops) throws SQLException {

    if (logger.isInfoEnabled()) {
        logger.info("Executing SQL script from " + resource);
    }
    long startTime = System.currentTimeMillis();
    List<String> statements = new LinkedList<String>();
    String script;
    try {
        script = readScript(resource);
    } catch (IOException ex) {
        throw new CannotReadScriptException(resource, ex);
    }
    String delimiter = this.separator;
    if (delimiter == null) {
        delimiter = DEFAULT_STATEMENT_SEPARATOR;
        if (!containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = "\n";
        }
    }
    splitSqlScript(script, delimiter, this.commentPrefix, statements);
    int lineNumber = 0;
    Statement stmt = connection.createStatement();
    try {
        for (String statement : statements) {
            lineNumber++;
            try {
                stmt.execute(statement);
                int rowsAffected = stmt.getUpdateCount();
                if (logger.isDebugEnabled()) {
                    logger.debug(rowsAffected + " returned as updateCount for SQL: " + statement);
                }
            } catch (SQLException ex) {
                boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
                if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Failed to execute SQL script statement at line " + lineNumber
                                + " of resource " + resource + ": " + statement, ex);
                    }
                } else {
                    throw new ScriptStatementFailedException(statement, lineNumber, 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("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
    }
}

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

/**
 * Execute the given SQL script.//  w  ww . j av a 2 s.  c o m
 * <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);
    }
}