Skip to content

Commit

Permalink
Add a listener to SqlScript to allow for better feedback to the user.
Browse files Browse the repository at this point in the history
  • Loading branch information
chenson42 committed Nov 6, 2011
1 parent f444a71 commit d0ace52
Showing 1 changed file with 29 additions and 3 deletions.
Expand Up @@ -72,6 +72,8 @@ public class SqlScript {
private String fileName = MEMORY;

private String lineDeliminator;

private ISqlScriptListener listener;

public SqlScript(URL url, DataSource ds) {
this(url, ds, true, QUERY_ENDS, null);
Expand Down Expand Up @@ -114,6 +116,14 @@ public SqlScript(String sqlScript, DataSource ds, boolean failOnError, String de
throw new RuntimeException(ex);
}
}

public void setListener(ISqlScriptListener listener) {
this.listener = listener;
}

public ISqlScriptListener getListener() {
return listener;
}

private void init(List<String> sqlScript, DataSource ds, boolean failOnError, String delimiter,
Map<String, String> replacementTokens) {
Expand Down Expand Up @@ -155,7 +165,7 @@ public Long doInConnection(Connection connection) throws SQLException,
DataAccessException {
Statement st = null;
ResultSet rs = null;
long lineCount = 0;
int lineCount = 0;
long updateCount = 0;
try {
connection.setAutoCommit(autoCommit);
Expand Down Expand Up @@ -185,18 +195,29 @@ public Long doInConnection(Connection connection) throws SQLException,
if (log.isDebugEnabled()) {
log.debug("Message", toExecute);
}
long rowsRetreived = 0;
long rowsUpdated = 0;
if (st.execute(toExecute)) {
rs = st.getResultSet();
while(rs.next());
while(rs.next()) {rowsRetreived++;};
} else {
updateCount += st.getUpdateCount();
rowsUpdated = st.getUpdateCount();
updateCount+=rowsUpdated;
}

if (listener != null) {
listener.sqlApplied(toExecute, rowsUpdated, rowsRetreived, lineCount);
}

count++;
if (count % commitRate == 0) {
connection.commit();
}
}
} catch (SQLException e) {
if (listener != null) {
listener.sqlErrored(toExecute, e, lineCount);
}
if (failOnError) {
log.error("SqlError", e, sql.toString());
throw e;
Expand Down Expand Up @@ -263,5 +284,10 @@ public void setCommitRate(int commitRate) {
public void setLineDeliminator(String lineDeliminator) {
this.lineDeliminator = lineDeliminator;
}

public static interface ISqlScriptListener {
public void sqlApplied (String sql, long rowsUpdated, long rowsRetreived, int lineNumber);
public void sqlErrored(String sql, SQLException ex, int lineNumber);
}

}

0 comments on commit d0ace52

Please sign in to comment.