From f032e21ce93603a8f3491cdcb5ff4532e0373bf9 Mon Sep 17 00:00:00 2001 From: Sanny Sanoff Date: Fri, 15 Jul 2016 21:29:16 +0300 Subject: more bulletproof reply sequence generator. --- .../java/com/juick/server/MessagesQueries.java | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/juick-core/src/main/java/com/juick/server/MessagesQueries.java b/juick-core/src/main/java/com/juick/server/MessagesQueries.java index b39de0ed..e6188a86 100644 --- a/juick-core/src/main/java/com/juick/server/MessagesQueries.java +++ b/juick-core/src/main/java/com/juick/server/MessagesQueries.java @@ -158,24 +158,26 @@ public class MessagesQueries { public static int getReplyIDIncrement(JdbcTemplate sql, int mid) { return sql.execute((ConnectionCallback) conn -> { conn.setAutoCommit(false); - try (PreparedStatement ps = conn.prepareStatement("UPDATE messages SET maxreplyid=maxreplyid+1 WHERE message_id=?")) { - ps.setInt(1, mid); - if (ps.executeUpdate() != 1) { - throw new IncorrectResultSizeDataAccessException("Cannot find a message to update: " + mid, 1, 0); - } - } - try (PreparedStatement ps = conn.prepareStatement("SELECT maxreplyid FROM messages WHERE message_id=?")) { + final int replyNo; + try (PreparedStatement ps = conn.prepareStatement("SELECT maxreplyid+1 FROM messages WHERE message_id=? FOR UPDATE")) { ps.setInt(1, mid); try (ResultSet resultSet = ps.executeQuery()) { if (resultSet.next()) { - int rv = resultSet.getInt(1); - conn.commit(); - return rv; + replyNo = resultSet.getInt(1); } else { throw new IncorrectResultSizeDataAccessException("while getting getReplyIDIncrement, mid=" + mid, 1, 0); } } } + try (PreparedStatement ps = conn.prepareStatement("UPDATE messages SET maxreplyid=? WHERE message_id=?")) { + ps.setInt(1, mid); + ps.setInt(2, replyNo); + if (ps.executeUpdate() != 1) { + throw new IncorrectResultSizeDataAccessException("Cannot find a message to update: " + mid, 1, 0); + } + } + conn.commit(); + return replyNo; }); } -- cgit v1.2.3