DatabaseAccessObject { public boolean columnExists(Connection conn, String tableName, String columnName) { boolean columnExists = false; try (PreparedStatement pstmt = conn.prepareStatement("SELECT " + columnName + " FROM " + tableName);){ pstmt.executeQuery(); columnExists = true; } catch (SQLException e) { s_logger.debug("Field " + columnName + " doesn't exist in " + tableName + " ignoring exception: " + e.getMessage()); } return columnExists; }  void dropKey(Connection conn, String tableName, String key, boolean isForeignKey); void dropPrimaryKey(Connection conn, String tableName); void dropColumn(Connection conn, String tableName, String columnName); boolean columnExists(Connection conn, String tableName, String columnName);  }
@Test public void testColumnExists() throws Exception { when(connectionMock.prepareStatement(contains("SELECT"))).thenReturn(preparedStatementMock); Connection conn = connectionMock; String tableName = "tableName"; String columnName = "columnName"; dao.columnExists(conn, tableName, columnName); verify(connectionMock, times(1)).prepareStatement(anyString()); verify(preparedStatementMock, times(1)).executeQuery(); verify(preparedStatementMock, times(1)).close(); verify(loggerMock, times(0)).debug(anyString(), any(Throwable.class)); }
@Test(expected = NullPointerException.class) public void testColumnExistsWhenConnectionIsNull() throws Exception { Connection conn = null; String tableName = "tableName"; String columnName = "columnName"; dao.columnExists(conn, tableName, columnName); }
@Test public void testColumnExistsWhenTableNameIsNull() throws Exception { SQLException sqlException = new SQLException(); when(connectionMock.prepareStatement(contains("FROM null"))).thenReturn(preparedStatementMock); when(preparedStatementMock.executeQuery()).thenThrow(sqlException); Connection conn = connectionMock; String tableName = null; String columnName = "columnName"; dao.columnExists(conn, tableName, columnName); verify(connectionMock, times(1)).prepareStatement(anyString()); verify(preparedStatementMock, times(1)).executeQuery(); verify(preparedStatementMock, times(1)).close(); verify(loggerMock, times(1)).debug(anyString()); }
@Test public void testColumnExistsWhenColumnNameIsNull() throws Exception { SQLException sqlException = new SQLException(); when(connectionMock.prepareStatement(contains("SELECT null"))).thenReturn(preparedStatementMock); when(preparedStatementMock.executeQuery()).thenThrow(sqlException); Connection conn = connectionMock; String tableName = "tableName"; String columnName = null; dao.columnExists(conn, tableName, columnName); verify(connectionMock, times(1)).prepareStatement(anyString()); verify(preparedStatementMock, times(1)).executeQuery(); verify(preparedStatementMock, times(1)).close(); verify(loggerMock, times(1)).debug(anyString()); }