coverity 1116564: complicated update of sequences fixed

Signed-off-by: Daan Hoogland <daan@onecht.net>

This closes #564
This commit is contained in:
Daan Hoogland 2015-07-08 00:26:13 +02:00
parent 0cd8c06f7d
commit b0136c56e7

View File

@ -94,15 +94,14 @@ public class SequenceFetcher {
@Override
@SuppressWarnings("unchecked")
public T call() throws Exception {
try {
PreparedStatement stmt = null;
StringBuilder sql = new StringBuilder("SELECT ");
sql.append(_tg.valueColumnName()).append(" FROM ").append(_tg.table());
sql.append(" WHERE ").append(_tg.pkColumnName()).append(" = ? FOR UPDATE");
TransactionLegacy txn = TransactionLegacy.open("Sequence");
try (TransactionLegacy txn = TransactionLegacy.open("Sequence");
PreparedStatement selectStmt = txn.prepareStatement(sql.toString());
) {
if (_key == null) {
selectStmt.setString(1, _tg.pkColumnValue());
} else {
@ -113,7 +112,7 @@ public class SequenceFetcher {
sql.append(_tg.table()).append(" SET ").append(_tg.valueColumnName()).append("=").append("?+?");
sql.append(" WHERE ").append(_tg.pkColumnName()).append("=?");
PreparedStatement updateStmt = txn.prepareStatement(sql.toString());
try (PreparedStatement updateStmt = txn.prepareStatement(sql.toString());) {
if (isRandom) {
updateStmt.setInt(2, random.nextInt(10) + 1);
} else {
@ -125,13 +124,10 @@ public class SequenceFetcher {
updateStmt.setObject(3, _key);
}
ResultSet rs = null;
try {
txn.start();
stmt = selectStmt;
rs = stmt.executeQuery();
Object obj = null;
try (ResultSet rs = selectStmt.executeQuery();) {
while (rs.next()) {
if (_clazz.isAssignableFrom(Long.class)) {
obj = rs.getLong(1);
@ -141,6 +137,9 @@ public class SequenceFetcher {
obj = rs.getObject(1);
}
}
} catch (SQLException e) {
s_logger.warn("Caught this exception when running: " + (selectStmt != null ? selectStmt.toString() : ""), e);
}
if (obj == null) {
s_logger.warn("Unable to get a sequence: " + updateStmt.toString());
@ -148,20 +147,14 @@ public class SequenceFetcher {
}
updateStmt.setObject(1, obj);
stmt = updateStmt;
int rows = stmt.executeUpdate();
try {
int rows = updateStmt.executeUpdate();
assert rows == 1 : "Come on....how exactly did we update this many rows " + rows + " for " + updateStmt.toString();
txn.commit();
return (T)obj;
} catch (SQLException e) {
s_logger.warn("Caught this exception when running: " + (stmt != null ? stmt.toString() : ""), e);
} finally {
if (rs != null) {
rs.close();
s_logger.warn("Caught this exception when running: " + (updateStmt != null ? updateStmt.toString() : ""), e);
}
selectStmt.close();
updateStmt.close();
txn.close();
}
} catch (Exception e) {
s_logger.warn("Caught this exception when running.", e);
@ -169,5 +162,4 @@ public class SequenceFetcher {
return null;
}
}
}