Skip to content

Commit

Permalink
add warn log when fail to get auto-generated keys. (apache#1259) (apa…
Browse files Browse the repository at this point in the history
…che#1261)

* add warn log when fail to get auto-generated keys. (apache#1259)

* add and remove blank line in InsertExecutor
  • Loading branch information
weijj authored and CoffeeLatte007 committed Jul 9, 2019
1 parent da9a944 commit b298a7c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import io.seata.rm.datasource.sql.struct.Null;
import io.seata.rm.datasource.sql.struct.TableMeta;
import io.seata.rm.datasource.sql.struct.TableRecords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
Expand All @@ -45,6 +47,7 @@
*/
public class InsertExecutor<T, S extends Statement> extends AbstractDMLBaseExecutor<T, S> {

private static final Logger LOGGER = LoggerFactory.getLogger(InsertExecutor.class);
protected static final String ERR_SQL_STATE = "S1009";

/**
Expand Down Expand Up @@ -135,6 +138,7 @@ protected List<Object> getPkValuesByAuto() throws SQLException {
// specify Statement.RETURN_GENERATED_KEYS to
// Statement.executeUpdate() or Connection.prepareStatement().
if (ERR_SQL_STATE.equalsIgnoreCase(e.getSQLState())) {
LOGGER.warn("Fail to get auto-generated keys, use \'SELECT LAST_INSERT_ID()\' instead. Be cautious, statement could be polluted. Recommend you set the statement to return generated keys.");
genKeys = statementProxy.getTargetStatement().executeQuery("SELECT LAST_INSERT_ID()");
} else {
throw e;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,23 @@ public void testGetPkValuesByAuto_SQLException() {
});
}

@Test
public void testGetPkValuesByAuto_SQLException_WarnLog() throws SQLException {
doReturn(tableMeta).when(insertExecutor).getTableMeta();
ColumnMeta columnMeta = mock(ColumnMeta.class);
Map<String, ColumnMeta> columnMetaMap = new HashMap<>();
columnMetaMap.put(ID_COLUMN, columnMeta);
when(columnMeta.isAutoincrement()).thenReturn(true);
when(tableMeta.getPrimaryKeyMap()).thenReturn(columnMetaMap);
PreparedStatement preparedStatement = mock(PreparedStatement.class);
when(statementProxy.getTargetStatement()).thenReturn(preparedStatement);
SQLException e = new SQLException("test warn log", InsertExecutor.ERR_SQL_STATE, 1);
when(preparedStatement.getGeneratedKeys()).thenThrow(e);
ResultSet genKeys = mock(ResultSet.class);
when(statementProxy.getTargetStatement().executeQuery("SELECT LAST_INSERT_ID()")).thenReturn(genKeys);
Assertions.assertTrue(insertExecutor.getPkValuesByAuto().isEmpty());
}

@Test
public void testGetPkValuesByAuto_GeneratedKeys_NoResult() throws SQLException {
doReturn(tableMeta).when(insertExecutor).getTableMeta();
Expand Down

0 comments on commit b298a7c

Please sign in to comment.