Skip to content

Commit

Permalink
[CONJ-953] PreparedStatement.getGeneratedKeys() returns rows when no …
Browse files Browse the repository at this point in the history
…keys are generated in insert
  • Loading branch information
rusher committed Jun 22, 2022
1 parent b06d958 commit e6fa71d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/main/java/org/mariadb/jdbc/Statement.java
Original file line number Diff line number Diff line change
Expand Up @@ -853,16 +853,19 @@ public ResultSet getGeneratedKeys() throws SQLException {
}

if (currResult instanceof OkPacket) {

OkPacket ok = ((OkPacket) currResult);
List<String[]> insertIds = new ArrayList<>();
insertIds.add(new String[] {String.valueOf(ok.getLastInsertId())});
for (Completion result : results) {
if (result instanceof OkPacket) {
insertIds.add(new String[] {String.valueOf(((OkPacket) result).getLastInsertId())});
if (ok.getLastInsertId() != 0) {
List<String[]> insertIds = new ArrayList<>();
insertIds.add(new String[]{String.valueOf(ok.getLastInsertId())});
for (Completion result : results) {
if (result instanceof OkPacket) {
insertIds.add(new String[]{String.valueOf(((OkPacket) result).getLastInsertId())});
}
}
String[][] ids = insertIds.toArray(new String[0][]);
return CompleteResult.createResultSet("insert_id", DataType.BIGINT, ids, con.getContext());
}
String[][] ids = insertIds.toArray(new String[0][]);
return CompleteResult.createResultSet("insert_id", DataType.BIGINT, ids, con.getContext());
}

return new CompleteResult(new ColumnDefinitionPacket[0], new byte[0][], con.getContext());
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/org/mariadb/jdbc/integration/StatementTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,24 @@ public static void beforeAll2() throws SQLException {
stmt.execute("FLUSH TABLES");
}

@Test
public void ensureGetGeneratedKeysReturnsEmptyResult() throws SQLException {
Statement stmt = sharedConn.createStatement();
stmt.execute("CREATE TABLE IF NOT EXISTS key_test (id INT(11) NOT NULL)");
try (PreparedStatement ps = sharedConn.prepareStatement("INSERT INTO key_test(id) VALUES(5)", Statement.RETURN_GENERATED_KEYS)) {
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
assertFalse(rs.next());
}
try (PreparedStatement ps = sharedConn.prepareStatement("UPDATE key_test set id=7 WHERE id=5", Statement.RETURN_GENERATED_KEYS)) {
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
assertFalse(rs.next());
}

stmt.execute("DROP TABLE key_test");
}

@Test
public void longGeneratedId() throws SQLException {
longGeneratedId(BigInteger.ONE);
Expand Down

0 comments on commit e6fa71d

Please sign in to comment.