@Test public void isUnhealthyIfTransactionFails() throws Exception { MockDataProvider mockDataProvider = new MockDataProvider() { @Override public MockResult[] execute(MockExecuteContext ctx) throws SQLException { throw new SQLException("BOOM"); } }; try { runHealthCheck(mockDataProvider); assert_().fail(); } catch (DataAccessException e) { assertThat(e.getMessage()).contains(validationQuery); assertThat(e.getMessage()).contains("BOOM"); } }
@Override public void update(SettingsForm form) { String eMails = join(form.getRecipients()); String features = join(form.getEnabledFeatures()); try { ctx.update(SETTINGS) .set(SETTINGS.HEARTBEAT_INTERVAL_IN_SECONDS, toSec(form.getHeartbeat())) .set(SETTINGS.HOURS_TO_EXPIRE, form.getExpiration()) .set(SETTINGS.MAIL_ENABLED, form.getEnabled()) .set(SETTINGS.MAIL_HOST, form.getHost()) .set(SETTINGS.MAIL_USERNAME, form.getUsername()) .set(SETTINGS.MAIL_PASSWORD, form.getPassword()) .set(SETTINGS.MAIL_FROM, form.getFrom()) .set(SETTINGS.MAIL_PROTOCOL, form.getProtocol()) .set(SETTINGS.MAIL_PORT, form.getPort()) .set(SETTINGS.MAIL_RECIPIENTS, eMails) .set(SETTINGS.NOTIFICATION_FEATURES, features) .where(SETTINGS.APP_ID.eq(APP_ID)) .execute(); } catch (DataAccessException e) { throw new SteveException("FAILED to save the settings", e); } }
@Override public int addOcppTag(OcppTagForm u) { try { return ctx.insertInto(OCPP_TAG) .set(OCPP_TAG.ID_TAG, u.getIdTag()) .set(OCPP_TAG.PARENT_ID_TAG, u.getParentIdTag()) .set(OCPP_TAG.EXPIRY_DATE, toDateTime(u.getExpiration())) .set(OCPP_TAG.NOTE, u.getNote()) .set(OCPP_TAG.BLOCKED, false) .set(OCPP_TAG.IN_TRANSACTION, false) .returning(OCPP_TAG.OCPP_TAG_PK) .fetchOne() .getOcppTagPk(); } catch (DataAccessException e) { if (e.getCause() instanceof SQLIntegrityConstraintViolationException) { throw new SteveException("A user with idTag '%s' already exists.", u.getIdTag()); } else { throw new SteveException("Execution of addOcppTag for idTag '%s' FAILED.", u.getIdTag(), e); } } }
@Test public void hasIpv6_falseWhenKnownSQLState() throws SQLException { SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException( "Unknown column 'zipkin_annotations.endpoint_ipv6' in 'field list'", "42S22", 1054); DataSource dataSource = mock(DataSource.class); // cheats to lower mock count: this exception is really thrown during execution of the query when(dataSource.getConnection()).thenThrow( new DataAccessException(sqlException.getMessage(), sqlException)); Boolean result = MySQLStorage.builder() .executor(Runnable::run) .datasource(dataSource) .build().hasIpv6.get(); assertThat(result).isFalse(); }
/** * This returns false instead of failing when the SQLState code doesn't imply the column is * missing. This is to prevent zipkin from crashing due to scenarios we haven't thought up, yet. * The root error goes into the log in this case. */ @Test public void hasIpv6_falseWhenUnknownSQLState() throws SQLException { SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException( "java.sql.SQLSyntaxErrorException: Table 'zipkin.zipkin_annotations' doesn't exist", "42S02", 1146); DataSource dataSource = mock(DataSource.class); // cheats to lower mock count: this exception is really thrown during execution of the query when(dataSource.getConnection()).thenThrow( new DataAccessException(sqlException.getMessage(), sqlException)); Boolean result = MySQLStorage.builder() .executor(Runnable::run) .datasource(dataSource) .build().hasIpv6.get(); assertThat(result).isFalse(); }
@Test public void hasDependencies_missing() throws SQLException { SQLSyntaxErrorException sqlException = new SQLSyntaxErrorException( "SQL [select count(*) from `zipkin_dependencies`]; Table 'zipkin.zipkin_dependencies' doesn't exist\n" + " Query is : select count(*) from `zipkin_dependencies`", "42S02", 1146); DataSource dataSource = mock(DataSource.class); // cheats to lower mock count: this exception is really thrown during execution of the query when(dataSource.getConnection()).thenThrow( new DataAccessException(sqlException.getMessage(), sqlException)); Boolean result = MySQLStorage.builder() .executor(Runnable::run) .datasource(dataSource) .build().hasPreAggregatedDependencies.get(); assertThat(result).isFalse(); }
@Override public MockResult[] execute(MockExecuteContext ctx) throws SQLException { MockResult[] mock = new MockResult[1]; // The execute context contains SQL string(s), bind values, and other meta-data String sql = ctx.sql(); // Exceptions are propagated through the JDBC and jOOQ APIs if (sql.equals("SELECT 1")) { mock[0] = new MockResult(1, DSL.using(SQLDialect.HSQLDB).newResult()); } else { throw new DataAccessException("Incorrect validation query"); } return mock; }
/** * @param entity to add * @return the persisted entity * @throws ActivityTrackerException */ @Override public E add(E entity) throws ActivityTrackerException { E transformedEntity = null; try { R persisted; persisted = jooq.insertInto(transformer.getTable()) .set(transformer.createRecord(entity)) .returning() .fetchOne(); transformedEntity = transformer.mapToEntity(persisted); } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN, e.getMessage()); } return transformedEntity; }
/** * @return all the entities currently in the database * @throws ActivityTrackerException */ @Override public List<E> findAll() throws ActivityTrackerException { List<E> entries = null; try { entries = new ArrayList<>(); List<R> queryResults = jooq.selectFrom(transformer.getTable()).fetchInto(transformer.getRecordClass()); for (R queryResult : queryResults) { E entry = transformer.mapToEntity(queryResult); entries.add(entry); } } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN, e.getMessage()); } return entries; }
@Override public CompletableFuture<Boolean> execute(final String query, final Object... params) { return CompletableFuture.supplyAsync(() -> { try (Connection connection = getConnection()) { try (PreparedStatement stmt = prepareStatement(connection, query)) { bindValues(stmt, params); return stmt.execute(); } } catch (SQLException e) { throw new DataAccessException("SQL-Error while doing an execute-query: " + query, e); } }); }
@Override public CompletableFuture<Integer> update(final String query, final Object... params) { return CompletableFuture.supplyAsync(() -> { try (Connection connection = getConnection()) { try (PreparedStatement stmt = prepareStatement(connection, query)) { bindValues(stmt, params); return stmt.executeUpdate(); } } catch (SQLException e) { throw new DataAccessException("SQL-Error while doing an update-query: " + query, e); } }, this.executor); }
protected String getRandomString(String name, boolean visible, boolean uuid) { String value = get(name); if ( value == null ) { if ( uuid ) { value = UUID.randomUUID().toString(); } else { byte[] bytes = new byte[64]; random.nextBytes(bytes); value = Base64.encodeBase64String(bytes); } try { set(name, value, visible); } catch (DataAccessException e) { value = get(name); if ( value == null ) { throw e; } } } return value; }
protected RuntimeException apply(Client client, String itemName) { try { create() .insertInto(CONFIG_ITEM_STATUS, CONFIG_ITEM_STATUS.NAME, CONFIG_ITEM_STATUS.AGENT_ID, CONFIG_ITEM_STATUS.REQUESTED_VERSION, CONFIG_ITEM_STATUS.REQUESTED_UPDATED) .values( itemName, new Long(client.getResourceId()), 1L, new Timestamp(System.currentTimeMillis())) .execute(); return null; } catch ( DataAccessException e ) { return e; } }
@Override public void register(String name) { Task task = getTask(name); if ( task == null ) { try { create() .insertInto(TASK, TASK.NAME) .values(name) .execute(); } catch ( DataAccessException e ) { if ( getTask(name) == null ) { throw e; } } } }
@Test public void logsAllUnderlyingCauses() { SQLException one = new SQLException("a"); SQLException two = new SQLException("b"); SQLException e = new SQLException("fail"); e.setNextException(one); e.setNextException(two); DataAccessException dae = new DataAccessException("moar fail", e); mapper.logException(0, dae); verify(logger).error(anyString(), eq(e)); verify(logger).error(anyString(), eq(one)); verify(logger).error(anyString(), eq(two)); }
/** * @param entity to add * @return the persisted entity */ public E add(E entity) throws BazaarException { E transformedEntity = null; try { R persisted; persisted = jooq.insertInto(transformer.getTable()) .set(transformer.createRecord(entity)) .returning() .fetchOne(); transformedEntity = transformer.getEntityFromTableRecord(persisted); } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN, e.getMessage()); } return transformedEntity; }
/** * @return all the entities currently in the database */ public List<E> findAll() throws BazaarException { List<E> entries = null; try { entries = new ArrayList<>(); List<R> queryResults = jooq.selectFrom(transformer.getTable()).fetchInto(transformer.getRecordClass()); for (R queryResult : queryResults) { E entry = transformer.getEntityFromTableRecord(queryResult); entries.add(entry); } } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN, e.getMessage()); } return entries; }
@Override public List<E> findAll(Pageable pageable) throws BazaarException { List<E> entries = null; try { entries = new ArrayList<>(); List<R> queryResults = jooq.selectFrom(transformer.getTable()) .orderBy(transformer.getSortFields(pageable.getSorts())) .limit(pageable.getPageSize()) .offset(pageable.getOffset()) .fetchInto(transformer.getRecordClass()); for (R queryResult : queryResults) { E entry = transformer.getEntityFromTableRecord(queryResult); entries.add(entry); } } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN, e.getMessage()); } return entries; }
@Override public boolean belongsToPublicProject(int id) throws BazaarException { try { Integer countOfPublicProjects = jooq.selectCount() .from(transformer.getTable()) .join(REQUIREMENT).on(REQUIREMENT.ID.eq(ATTACHMENT.REQUIREMENT_ID)) .join(PROJECT).on(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) .where(transformer.getTableId().eq(id).and(PROJECT.VISIBILITY.isTrue())) .fetchOne(0, int.class); return (countOfPublicProjects == 1); } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); } return false; }
@Override public boolean belongsToPublicProject(int id) throws BazaarException { try { Integer countOfPublicProjects = jooq.selectCount() .from(transformer.getTable()) .join(REQUIREMENT).on(REQUIREMENT.ID.eq(COMMENT.REQUIREMENT_ID)) .join(PROJECT).on(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) .where(transformer.getTableId().eq(id).and(PROJECT.VISIBILITY.isTrue())) .fetchOne(0, int.class); return (countOfPublicProjects == 1); } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); } return false; }
@Test public void createUserWontCreateTwiceWhenErrorOnDb() { User result = new User(); PersonAdapter person = new PersonAdapter(UUID.randomUUID().toString()); when(broker.find(eq(ANY_PROVIDER), eq(ANY_ID), eq(personManager))) .thenReturn(Optional.empty(), Optional.of(result)); when(personManager.createPerson()).thenReturn(person); doThrow(DataAccessException.class).when(broker).persist(any()); User user = manager.createUser(bean); assertEquals(result, user); verify(broker, times(2)).find(eq(ANY_PROVIDER), eq(ANY_ID), eq(personManager)); verify(broker, times(1)).persist(argThat((a) -> matches((User.Login) a))); verify(personManager).createPerson(); assertFound(user, ANY_PROVIDER, ANY_ID); verifyNoMoreInteractions(broker); verifyNoMoreInteractions(personManager); }
@Test public void createUserFailsWhenDbIsDownOrInconsistent() { PersonAdapter person = new PersonAdapter(UUID.randomUUID().toString()); when(broker.find(eq(ANY_PROVIDER), eq(ANY_ID), eq(personManager))) .thenReturn(Optional.empty()); when(personManager.createPerson()).thenReturn(person); doThrow(DataAccessException.class).when(broker).persist(any()); try { User user = manager.createUser(bean); fail("Should have thrown an error"); } catch(DataAccessException e) { //expected } verify(broker, times(2)).find(eq(ANY_PROVIDER), eq(ANY_ID), eq(personManager)); verify(broker, times(1)).persist(argThat((a) -> matches((User.Login) a))); verify(personManager).createPerson(); verifyNoMoreInteractions(broker); verifyNoMoreInteractions(personManager); }
@SuppressWarnings({ "rawtypes", "unchecked" }) protected <T> T fetch(UUID id, Class<?> record, DataFetchingEnvironment env) { Table<?> table = TABLES.get(record); Field field; try { field = (Field) table.getClass() .getField("ID") .get(table); } catch (DataAccessException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { throw new IllegalStateException(String.format("Cannot access 'id' field on %s", record.getCanonicalName()), e); } return (T) WorkspaceSchema.ctx(env) .create() .selectFrom(table) .where(field.eq(id)) .fetchOne(); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private <T> T fetchAll(Class<?> record, DataFetchingEnvironment env) { Table<?> table = TABLES.get(record); Field field; try { field = (Field) table.getClass() .getField("WORKSPACE") .get(table); } catch (DataAccessException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { throw new IllegalStateException(String.format("Cannot access 'id' field on %s", record.getCanonicalName()), e); } return (T) WorkspaceSchema.ctx(env) .create() .selectFrom(table) .where(field.eq(PhantasmContext.getWorkspace(env) .getId())) .fetch() .stream() .collect(Collectors.toList()); }
@Override public void updateOcppTag(OcppTagForm u) { try { ctx.update(OCPP_TAG) .set(OCPP_TAG.PARENT_ID_TAG, u.getParentIdTag()) .set(OCPP_TAG.EXPIRY_DATE, toDateTime(u.getExpiration())) .set(OCPP_TAG.NOTE, u.getNote()) .set(OCPP_TAG.BLOCKED, u.getBlocked()) .where(OCPP_TAG.OCPP_TAG_PK.equal(u.getOcppTagPk())) .execute(); } catch (DataAccessException e) { throw new SteveException("Execution of updateOcppTag for idTag '%s' FAILED.", u.getIdTag(), e); } }
@Override public void deleteOcppTag(int ocppTagPk) { try { ctx.delete(OCPP_TAG) .where(OCPP_TAG.OCPP_TAG_PK.equal(ocppTagPk)) .execute(); } catch (DataAccessException e) { throw new SteveException("Execution of deleteOcppTag for idTag FAILED.", e); } }
private void internalUpdateReservation(int reservationId, ReservationStatus status) { try { ctx.update(RESERVATION) .set(RESERVATION.STATUS, status.name()) .where(RESERVATION.RESERVATION_PK.equal(reservationId)) .execute(); } catch (DataAccessException e) { log.error("Updating of reservationId '{}' to status '{}' FAILED.", reservationId, status, e); } }
@Override public int addOcppTag(String rfid) { return ctx.transactionResult(configuration -> { try { int ocppTagPk = insertLocal(rfid); insertExternal(ocppTagPk); return ocppTagPk; } catch (DataAccessException e) { throw new SteveException("Failed to insert the OCPP tag", e); } }); }
private void blockCallInternal(String rfid, boolean blocked, String note) { try { ctx.update(OCPP_TAG) .set(OCPP_TAG.NOTE, note) .set(OCPP_TAG.BLOCKED, blocked) .where(OCPP_TAG.ID_TAG.equal(rfid)) .execute(); } catch (DataAccessException e) { throw new SteveException("Execution of updateOcppTag for idTag '%s' FAILED.", rfid, e); } }
@Test public void whenSQLQueryIsInvalid_ExceptionIsThrown() throws SQLException { exception.expect(DataAccessException.class); try(Connection connection = setupExample(factory, "pokemon")) { String query = "SELECT * FROM nonexistant"; String template = "" + "insert $x isa pokemon-type " + " has type-id <ID> " + " has description <IDENTIFIER>; "; migrator.load(template, new SQLMigrator(query, connection).convert()); } }
@Test public void insertReturningShouldFailOnDuplicateKey() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Something something = createSomething(); dao.insertReturningPrimaryAsync(something). thenCompose(id -> dao.insertReturningPrimaryAsync(something.setSomeid(id))). exceptionally(x -> { Assert.assertNotNull(x); Assert.assertEquals(DataAccessException.class, x.getCause().getClass()); return null; }). thenCompose(v -> dao.deleteExecAsync(DSL.trueCondition())). whenComplete(failOrCountDown(latch)); await(latch); }
@Test public void insertReturningShouldFailOnDuplicateKey() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Something something = createSomething(); dao.insertReturningPrimaryAsync(something) .flatMap(id -> dao.insertReturningPrimaryAsync(something.setSomeid(id))) .onErrorResumeNext(err -> { Assert.assertEquals(DataAccessException.class, err.getClass()); return dao.deleteExecAsync(Tables.SOMETHING.SOMEID.eq(something.getSomeid())); }).subscribe(failOrCountDownSingleObserver(latch)); await(latch); }
@Test public void insertReturningShouldFailOnDuplicateKey() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Something something = createSomething(); dao.insertReturningPrimaryAsync(something,consumeOrFailHandler(c->{ dao.insertReturningPrimaryAsync(something.setSomeid(c), h -> { Assert.assertTrue(h.failed()); Assert.assertEquals(DataAccessException.class,h.cause().getClass()); dao.deleteByIdAsync(c,countdownLatchHandler(latch)); }); })); await(latch); }
@Override protected Result check() throws Exception { try { databaseAgnostic(dataSource).selectOne().execute(); } catch (DataAccessException | SQLException e) { switch (onFailure) { case LOG_ONLY: logger.warn("Unhealthy connection to database."); break; case RETURN_UNHEALTHY: return Result.unhealthy("Unhealthy connection to database."); } } return Result.healthy(); }