PostgreSQLDataSourceChecker extends AbstractDataSourceChecker { @Override public void checkPrivilege(final Collection<? extends DataSource> dataSources) { try { for (DataSource dataSource : dataSources) { String tableName; try (Connection connection = dataSource.getConnection()) { ResultSet tables = connection.getMetaData().getTables(connection.getCatalog(), null, "%", new String[]{"TABLE"}); if (tables.next()) { tableName = tables.getString(3); } else { throw new PrepareFailedException("No tables find in the source data source"); } connection.prepareStatement(String.format("SELECT * FROM %s LIMIT 1", tableName)).executeQuery(); } } } catch (final SQLException ex) { throw new PrepareFailedException("Data sources privilege check failed!", ex); } }  @Override void checkPrivilege(final Collection<? extends DataSource> dataSources); @Override void checkVariable(final Collection<? extends DataSource> dataSources);  }
@Test public void assertCheckPrivilege() throws SQLException { when(resultSet.next()).thenReturn(true); when(resultSet.getString(3)).thenReturn("test"); PostgreSQLDataSourceChecker dataSourceChecker = new PostgreSQLDataSourceChecker(); dataSourceChecker.checkPrivilege(dataSources); verify(preparedStatement).executeQuery(); }
@Test(expected = PrepareFailedException.class) public void assertCheckPrivilegeWithoutTable() throws SQLException { when(resultSet.next()).thenReturn(false); PostgreSQLDataSourceChecker dataSourceChecker = new PostgreSQLDataSourceChecker(); dataSourceChecker.checkPrivilege(dataSources); }
@Test(expected = PrepareFailedException.class) public void assertCheckPrivilegeFailure() throws SQLException { when(resultSet.next()).thenReturn(true); when(resultSet.getString(3)).thenReturn("test"); when(connection.prepareStatement("SELECT * FROM test LIMIT 1")).thenThrow(new SQLException("")); PostgreSQLDataSourceChecker dataSourceChecker = new PostgreSQLDataSourceChecker(); dataSourceChecker.checkPrivilege(dataSources); }