1 | /* |
2 | * Copyright 2006-2009 the original author or authors. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | package org.springframework.batch.item.database; |
18 | |
19 | import java.sql.Connection; |
20 | import java.sql.PreparedStatement; |
21 | import java.sql.ResultSet; |
22 | import java.sql.SQLException; |
23 | import java.sql.SQLWarning; |
24 | import java.sql.Statement; |
25 | |
26 | import javax.sql.DataSource; |
27 | |
28 | import org.apache.commons.logging.Log; |
29 | import org.apache.commons.logging.LogFactory; |
30 | import org.springframework.batch.item.ExecutionContext; |
31 | import org.springframework.batch.item.ItemStream; |
32 | import org.springframework.batch.item.ReaderNotOpenException; |
33 | import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader; |
34 | import org.springframework.beans.factory.InitializingBean; |
35 | import org.springframework.dao.InvalidDataAccessApiUsageException; |
36 | import org.springframework.dao.InvalidDataAccessResourceUsageException; |
37 | import org.springframework.jdbc.SQLWarningException; |
38 | import org.springframework.jdbc.datasource.DataSourceUtils; |
39 | import org.springframework.jdbc.support.JdbcUtils; |
40 | import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator; |
41 | import org.springframework.jdbc.support.SQLExceptionTranslator; |
42 | import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; |
43 | import org.springframework.transaction.support.TransactionSynchronizationManager; |
44 | import org.springframework.util.Assert; |
45 | |
46 | /** |
47 | * <p> |
48 | * Abstract base class for any simple item reader that opens a database cursor and continually retrieves |
49 | * the next row in the ResultSet. |
50 | * </p> |
51 | * |
52 | * <p> |
53 | * By default the cursor will be opened using a separate connection. The ResultSet for the cursor |
54 | * is held open regardless of commits or roll backs in a surrounding transaction. Clients of this |
55 | * reader are responsible for buffering the items in the case that they need to be re-presented on a |
56 | * rollback. This buffering is handled by the step implementations provided and is only a concern for |
57 | * anyone writing their own step implementations. |
58 | * </p> |
59 | * |
60 | * <p> |
61 | * There is an option ({@link #setUseSharedExtendedConnection(boolean)} that will share the connection |
62 | * used for the cursor with the rest of the step processing. If you set this flag to <code>true</code> |
63 | * then you must wrap the DataSource in a {@link ExtendedConnectionDataSourceProxy} to prevent the |
64 | * connection from being closed and released after each commit performed as part of the step processing. |
65 | * You must also use a JDBC driver supporting JDBC 3.0 or later since the cursor will be opened with the |
66 | * additional option of 'HOLD_CUSORS_OVER_COMMIT' enabled. |
67 | * </p> |
68 | * |
69 | * <p> |
70 | * Each call to {@link #read()} will attempt to map the row at the current position in the |
71 | * ResultSet. There is currently no wrapping of the ResultSet to suppress calls |
72 | * to next(). However, if the RowMapper (mistakenly) increments the current row, |
73 | * the next call to read will verify that the current row is at the expected |
74 | * position and throw a DataAccessException if it is not. The reason for such strictness on the |
75 | * ResultSet is due to the need to maintain control for transactions and |
76 | * restartability. This ensures that each call to {@link #read()} returns the |
77 | * ResultSet at the correct row, regardless of rollbacks or restarts. |
78 | * </p> |
79 | * |
80 | * <p> |
81 | * {@link ExecutionContext}: The current row is returned as restart data, and |
82 | * when restored from that same data, the cursor is opened and the current row |
83 | * set to the value within the restart data. See |
84 | * {@link #setDriverSupportsAbsolute(boolean)} for improving restart |
85 | * performance. |
86 | * </p> |
87 | * |
88 | * <p> |
89 | * Calling close on this {@link ItemStream} will cause all resources it is |
90 | * currently using to be freed. (Connection, ResultSet, etc). It is then illegal |
91 | * to call {@link #read()} again until it has been re-opened. |
92 | * </p> |
93 | * |
94 | * <p> |
95 | * Known limitation: when used with Derby |
96 | * {@link #setVerifyCursorPosition(boolean)} needs to be <code>false</code> |
97 | * because {@link ResultSet#getRow()} call used for cursor position verification |
98 | * is not available for 'TYPE_FORWARD_ONLY' result sets. |
99 | * </p> |
100 | * |
101 | * @author Lucas Ward |
102 | * @author Peter Zozom |
103 | * @author Robert Kasanicky |
104 | * @author Thomas Risberg |
105 | */ |
106 | public abstract class AbstractCursorItemReader<T> extends AbstractItemCountingItemStreamItemReader<T> |
107 | implements InitializingBean { |
108 | |
109 | /** Logger available to subclasses */ |
110 | protected final Log log = LogFactory.getLog(getClass()); |
111 | |
112 | public static final int VALUE_NOT_SET = -1; |
113 | private Connection con; |
114 | |
115 | protected ResultSet rs; |
116 | |
117 | private DataSource dataSource; |
118 | |
119 | private int fetchSize = VALUE_NOT_SET; |
120 | |
121 | private int maxRows = VALUE_NOT_SET; |
122 | |
123 | private int queryTimeout = VALUE_NOT_SET; |
124 | |
125 | private boolean ignoreWarnings = true; |
126 | |
127 | private boolean verifyCursorPosition = true; |
128 | |
129 | private SQLExceptionTranslator exceptionTranslator; |
130 | |
131 | private boolean initialized = false; |
132 | |
133 | private boolean driverSupportsAbsolute = false; |
134 | |
135 | private boolean useSharedExtendedConnection = false; |
136 | |
137 | |
138 | public AbstractCursorItemReader() { |
139 | super(); |
140 | } |
141 | |
142 | /** |
143 | * Assert that mandatory properties are set. |
144 | * |
145 | * @throws IllegalArgumentException if either data source or sql properties |
146 | * not set. |
147 | */ |
148 | public void afterPropertiesSet() throws Exception { |
149 | Assert.notNull(dataSource, "DataSource must be provided"); |
150 | } |
151 | |
152 | /** |
153 | * Public setter for the data source for injection purposes. |
154 | * |
155 | * @param dataSource |
156 | */ |
157 | public void setDataSource(DataSource dataSource) { |
158 | this.dataSource = dataSource; |
159 | } |
160 | |
161 | /** |
162 | * Public getter for the data source. |
163 | * |
164 | * @return the dataSource |
165 | */ |
166 | public DataSource getDataSource() { |
167 | return this.dataSource; |
168 | } |
169 | |
170 | /** |
171 | * Prepare the given JDBC Statement (or PreparedStatement or |
172 | * CallableStatement), applying statement settings such as fetch size, max |
173 | * rows, and query timeout. @param stmt the JDBC Statement to prepare |
174 | * @throws SQLException |
175 | * |
176 | * @see #setFetchSize |
177 | * @see #setMaxRows |
178 | * @see #setQueryTimeout |
179 | */ |
180 | protected void applyStatementSettings(PreparedStatement stmt) throws SQLException { |
181 | if (fetchSize != VALUE_NOT_SET) { |
182 | stmt.setFetchSize(fetchSize); |
183 | stmt.setFetchDirection(ResultSet.FETCH_FORWARD); |
184 | } |
185 | if (maxRows != VALUE_NOT_SET) { |
186 | stmt.setMaxRows(maxRows); |
187 | } |
188 | if (queryTimeout != VALUE_NOT_SET) { |
189 | stmt.setQueryTimeout(queryTimeout); |
190 | } |
191 | } |
192 | |
193 | /** |
194 | * Return the exception translator for this instance. |
195 | * |
196 | * Creates a default SQLErrorCodeSQLExceptionTranslator for the specified |
197 | * DataSource if none is set. |
198 | */ |
199 | protected SQLExceptionTranslator getExceptionTranslator() { |
200 | synchronized(this) { |
201 | if (exceptionTranslator == null) { |
202 | if (dataSource != null) { |
203 | exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dataSource); |
204 | } |
205 | else { |
206 | exceptionTranslator = new SQLStateSQLExceptionTranslator(); |
207 | } |
208 | } |
209 | } |
210 | return exceptionTranslator; |
211 | } |
212 | |
213 | /** |
214 | * Throw a SQLWarningException if we're not ignoring warnings, else log the |
215 | * warnings (at debug level). |
216 | * |
217 | * @param statement the current statement to obtain the warnings from, if there are any. |
218 | * @throws SQLException |
219 | * |
220 | * @see org.springframework.jdbc.SQLWarningException |
221 | */ |
222 | protected void handleWarnings(Statement statement) throws SQLWarningException, |
223 | SQLException { |
224 | if (ignoreWarnings) { |
225 | if (log.isDebugEnabled()) { |
226 | SQLWarning warningToLog = statement.getWarnings(); |
227 | while (warningToLog != null) { |
228 | log.debug("SQLWarning ignored: SQL state '" + warningToLog.getSQLState() + "', error code '" |
229 | + warningToLog.getErrorCode() + "', message [" + warningToLog.getMessage() + "]"); |
230 | warningToLog = warningToLog.getNextWarning(); |
231 | } |
232 | } |
233 | } |
234 | else { |
235 | SQLWarning warnings = statement.getWarnings(); |
236 | if (warnings != null) { |
237 | throw new SQLWarningException("Warning not ignored", warnings); |
238 | } |
239 | } |
240 | } |
241 | |
242 | /** |
243 | * Moves the cursor in the ResultSet to the position specified by the row |
244 | * parameter by traversing the ResultSet. |
245 | * @param row |
246 | */ |
247 | private void moveCursorToRow(int row) { |
248 | try { |
249 | int count = 0; |
250 | while (row != count && rs.next()) { |
251 | count++; |
252 | } |
253 | } |
254 | catch (SQLException se) { |
255 | throw getExceptionTranslator().translate("Attempted to move ResultSet to last committed row", getSql(), se); |
256 | } |
257 | } |
258 | |
259 | /** |
260 | * Gives the JDBC driver a hint as to the number of rows that should be |
261 | * fetched from the database when more rows are needed for this |
262 | * <code>ResultSet</code> object. If the fetch size specified is zero, the |
263 | * JDBC driver ignores the value. |
264 | * |
265 | * @param fetchSize the number of rows to fetch |
266 | * @see ResultSet#setFetchSize(int) |
267 | */ |
268 | public void setFetchSize(int fetchSize) { |
269 | this.fetchSize = fetchSize; |
270 | } |
271 | |
272 | /** |
273 | * Sets the limit for the maximum number of rows that any |
274 | * <code>ResultSet</code> object can contain to the given number. |
275 | * |
276 | * @param maxRows the new max rows limit; zero means there is no limit |
277 | * @see Statement#setMaxRows(int) |
278 | */ |
279 | public void setMaxRows(int maxRows) { |
280 | this.maxRows = maxRows; |
281 | } |
282 | |
283 | /** |
284 | * Sets the number of seconds the driver will wait for a |
285 | * <code>Statement</code> object to execute to the given number of seconds. |
286 | * If the limit is exceeded, an <code>SQLException</code> is thrown. |
287 | * |
288 | * @param queryTimeout seconds the new query timeout limit in seconds; zero |
289 | * means there is no limit |
290 | * @see Statement#setQueryTimeout(int) |
291 | */ |
292 | public void setQueryTimeout(int queryTimeout) { |
293 | this.queryTimeout = queryTimeout; |
294 | } |
295 | |
296 | /** |
297 | * Set whether SQLWarnings should be ignored (only logged) or exception |
298 | * should be thrown. |
299 | * |
300 | * @param ignoreWarnings if TRUE, warnings are ignored |
301 | */ |
302 | public void setIgnoreWarnings(boolean ignoreWarnings) { |
303 | this.ignoreWarnings = ignoreWarnings; |
304 | } |
305 | |
306 | /** |
307 | * Allow verification of cursor position after current row is processed by |
308 | * RowMapper or RowCallbackHandler. Default value is TRUE. |
309 | * |
310 | * @param verifyCursorPosition if true, cursor position is verified |
311 | */ |
312 | public void setVerifyCursorPosition(boolean verifyCursorPosition) { |
313 | this.verifyCursorPosition = verifyCursorPosition; |
314 | } |
315 | |
316 | /** |
317 | * Indicate whether the JDBC driver supports setting the absolute row on a |
318 | * {@link ResultSet}. It is recommended that this is set to |
319 | * <code>true</code> for JDBC drivers that supports ResultSet.absolute() as |
320 | * it may improve performance, especially if a step fails while working with |
321 | * a large data set. |
322 | * |
323 | * @see ResultSet#absolute(int) |
324 | * |
325 | * @param driverSupportsAbsolute <code>false</code> by default |
326 | */ |
327 | public void setDriverSupportsAbsolute(boolean driverSupportsAbsolute) { |
328 | this.driverSupportsAbsolute = driverSupportsAbsolute; |
329 | } |
330 | |
331 | /** |
332 | * Indicate whether the connection used for the cursor should be used by all other processing |
333 | * thus sharing the same transaction. If this is set to false, which is the default, then the |
334 | * cursor will be opened using in its connection and will not participate in any transactions |
335 | * started for the rest of the step processing. If you set this flag to true then you must |
336 | * wrap the DataSource in a {@link ExtendedConnectionDataSourceProxy} to prevent the |
337 | * connection from being closed and released after each commit. |
338 | * |
339 | * When you set this option to <code>true</code> then the statement used to open the cursor |
340 | * will be created with both 'READ_ONLY' and 'HOLD_CUSORS_OVER_COMMIT' options. This allows |
341 | * holding the cursor open over transaction start and commits performed in the step processing. |
342 | * To use this feature you need a database that supports this and a JDBC driver supporting |
343 | * JDBC 3.0 or later. |
344 | * |
345 | * @param useSharedExtendedConnection <code>false</code> by default |
346 | */ |
347 | public void setUseSharedExtendedConnection(boolean useSharedExtendedConnection) { |
348 | this.useSharedExtendedConnection = useSharedExtendedConnection; |
349 | } |
350 | |
351 | public boolean isUseSharedExtendedConnection() { |
352 | return useSharedExtendedConnection; |
353 | } |
354 | |
355 | public abstract String getSql(); |
356 | |
357 | /** |
358 | * Check the result set is in synch with the currentRow attribute. This is |
359 | * important to ensure that the user hasn't modified the current row. |
360 | */ |
361 | private void verifyCursorPosition(long expectedCurrentRow) throws SQLException { |
362 | if (verifyCursorPosition) { |
363 | if (expectedCurrentRow != this.rs.getRow()) { |
364 | throw new InvalidDataAccessResourceUsageException("Unexpected cursor position change."); |
365 | } |
366 | } |
367 | } |
368 | |
369 | /** |
370 | * Close the cursor and database connection. Make call to cleanupOnClose so sub classes can cleanup |
371 | * any resources they have allocated. |
372 | */ |
373 | protected void doClose() throws Exception { |
374 | initialized = false; |
375 | JdbcUtils.closeResultSet(this.rs); |
376 | rs = null; |
377 | cleanupOnClose(); |
378 | if (useSharedExtendedConnection && dataSource instanceof ExtendedConnectionDataSourceProxy) { |
379 | ((ExtendedConnectionDataSourceProxy)dataSource).stopCloseSuppression(this.con); |
380 | if (!TransactionSynchronizationManager.isActualTransactionActive()) { |
381 | DataSourceUtils.releaseConnection(con, dataSource); |
382 | } |
383 | } |
384 | else { |
385 | JdbcUtils.closeConnection(this.con); |
386 | } |
387 | } |
388 | |
389 | protected abstract void cleanupOnClose() throws Exception; |
390 | |
391 | /** |
392 | * Execute the statement to open the cursor. |
393 | */ |
394 | @Override |
395 | protected final void doOpen() throws Exception { |
396 | |
397 | Assert.state(!initialized, "Stream is already initialized. Close before re-opening."); |
398 | Assert.isNull(rs, "ResultSet still open! Close before re-opening."); |
399 | |
400 | initializeConnection(); |
401 | openCursor(con); |
402 | initialized = true; |
403 | |
404 | } |
405 | |
406 | protected void initializeConnection() { |
407 | Assert.state(getDataSource() != null, "DataSource must not be null."); |
408 | |
409 | try { |
410 | if (useSharedExtendedConnection) { |
411 | if (!(getDataSource() instanceof ExtendedConnectionDataSourceProxy)) { |
412 | throw new InvalidDataAccessApiUsageException( |
413 | "You must use a ExtendedConnectionDataSourceProxy for the dataSource when " + |
414 | "useSharedExtendedConnection is set to true."); |
415 | } |
416 | this.con = DataSourceUtils.getConnection(dataSource); |
417 | ((ExtendedConnectionDataSourceProxy)dataSource).startCloseSuppression(this.con); |
418 | } |
419 | else { |
420 | this.con = dataSource.getConnection(); |
421 | } |
422 | } |
423 | catch (SQLException se) { |
424 | close(); |
425 | throw getExceptionTranslator().translate("Executing query", getSql(), se); |
426 | } |
427 | } |
428 | |
429 | protected abstract void openCursor(Connection con); |
430 | |
431 | /** |
432 | * Read next row and map it to item, verify cursor position if |
433 | * {@link #setVerifyCursorPosition(boolean)} is true. |
434 | */ |
435 | protected T doRead() throws Exception { |
436 | if (rs == null) { |
437 | throw new ReaderNotOpenException("Reader must be open before it can be read."); |
438 | } |
439 | |
440 | try { |
441 | if (!rs.next()) { |
442 | return null; |
443 | } |
444 | int currentRow = getCurrentItemCount(); |
445 | T item = readCursor(rs, currentRow); |
446 | verifyCursorPosition(currentRow); |
447 | return item; |
448 | } |
449 | catch (SQLException se) { |
450 | throw getExceptionTranslator().translate("Attempt to process next row failed", getSql(), se); |
451 | } |
452 | } |
453 | |
454 | /** |
455 | * Read the cursor and map to the type of object this reader should return. This method must be |
456 | * overriden by subclasses. |
457 | * |
458 | * @param rs The current result set |
459 | * @param currentRow Current position of the result set |
460 | * @return the mapped object at the cursor position |
461 | * @throws SQLException |
462 | */ |
463 | protected abstract T readCursor(ResultSet rs, int currentRow) throws SQLException; |
464 | |
465 | /** |
466 | * Use {@link ResultSet#absolute(int)} if possible, otherwise scroll by |
467 | * calling {@link ResultSet#next()}. |
468 | */ |
469 | protected void jumpToItem(int itemIndex) throws Exception { |
470 | if (driverSupportsAbsolute) { |
471 | try { |
472 | rs.absolute(itemIndex); |
473 | } |
474 | catch (SQLException e) { |
475 | // Driver does not support rs.absolute(int) revert to |
476 | // traversing ResultSet |
477 | log.warn("The JDBC driver does not appear to support ResultSet.absolute(). Consider" |
478 | + " reverting to the default behavior setting the driverSupportsAbsolute to false", e); |
479 | |
480 | moveCursorToRow(itemIndex); |
481 | } |
482 | } |
483 | else { |
484 | moveCursorToRow(itemIndex); |
485 | } |
486 | } |
487 | |
488 | } |