@Override public void deleteById(final UUID definitionId, final InternalCallContext context) throws TagDefinitionApiException { try { transactionalSqlDao.execute(false, new EntitySqlDaoTransactionWrapper<Void>() { @Override public Void inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) throws Exception { final TagDefinitionSqlDao tagDefinitionSqlDao = entitySqlDaoWrapperFactory.become(TagDefinitionSqlDao.class); // Make sure the tag definition exists final TagDefinitionModelDao tagDefinition = tagDefinitionSqlDao.getById(definitionId.toString(), context); if (tagDefinition == null) { throw new TagDefinitionApiException(ErrorCode.TAG_DEFINITION_DOES_NOT_EXIST, definitionId); } // Make sure it is not used currently if (tagDefinitionSqlDao.tagDefinitionUsageCount(definitionId.toString(), context) > 0) { throw new TagDefinitionApiException(ErrorCode.TAG_DEFINITION_IN_USE, definitionId); } // Delete it tagDefinitionSqlDao.markTagDefinitionAsDeleted(definitionId.toString(), context); postBusEventFromTransaction(tagDefinition, tagDefinition, ChangeType.DELETE, entitySqlDaoWrapperFactory, context); return null; } }); } catch (final TransactionFailedException exception) { if (exception.getCause() instanceof TagDefinitionApiException) { throw (TagDefinitionApiException) exception.getCause(); } else { throw exception; } } }
@Override protected void logException(long id, DBIException exception) { final Throwable cause = exception.getCause(); if (cause instanceof SQLException) { for (Throwable throwable : (SQLException) cause) { logger.error(formatLogMessage(id, throwable), throwable); } } else { logger.error(formatLogMessage(id, exception), exception); } } }
this.context.setAttribute("position", null); } catch (SQLException e) { throw new UnableToExecuteStatementException( String.format( "Exception while binding positional param at (0 based) position %d", "the JDBC 'start at 1' scheme) has been set.", named_param, i, i + 1); throw new UnableToExecuteStatementException(msg, context); i += Optional.ofNullable(pos).orElse(1); } catch (SQLException e) { throw new UnableToCreateStatementException(String.format( "Exception while binding '%s'", named_param), e, context);
throw new ResultSetException("Unable to obtain metadata from result set", e, ctx); throw new ResultSetException("Unable to access specific metadata from " + "result set metadata", e, ctx);
/** * Called when a transaction is rolled back * Will throw a RuntimeException to force transactional rollback */ public void rollback(Handle handle) { throw new TransactionException("Rollback called, this runtime exception thrown to halt the transaction"); }
final StatementContext statementContext = ((StatementException) t.getCause()).getStatementContext();
public void save(String project, ABTestingReport report) { if (report.id != -1) { throw new RakamException("Report already has an id.", HttpResponseStatus.BAD_REQUEST); } try (Handle handle = dbi.open()) { handle.createStatement("INSERT INTO ab_testing (project, name, variants, collection_name, connector_field, goals, options)" + " VALUES (:project, :name, :variants, :collection_name, :goals, :options)") .bind("project", project) .bind("name", report.name) .bind("collection_name", report.collectionName) .bind("variants", JsonHelper.encode(report.variants)) .bind("goals", JsonHelper.encode(ImmutableList.of(report.goal))) .bind("options", JsonHelper.encode(report.options, false)) .execute(); } catch (UnableToExecuteStatementException e) { if (e.getCause() instanceof SQLException && ((SQLException) e.getCause()).getSQLState().equals("23505")) { // TODO: replace throw new RakamException("Report already exists", HttpResponseStatus.BAD_REQUEST); } } }
/** * Munge up the SQL as desired. Responsible for figuring out ow to bind any * arguments in to the resultant prepared statement. * * @param sql The SQL to rewrite * @param params contains the arguments which have been bound to this statement. * @param ctx The statement context for the statement being executed * @return somethign which can provde the actual SQL to prepare a statement from * and which can bind the correct arguments to that prepared statement */ @Override public RewrittenStatement rewrite(final String sql, final Binding params, final StatementContext ctx) { final ParsedStatement stmt = new ParsedStatement(); try { final String parsedSql = parseString(sql, stmt, params); return new MyRewrittenStatement(parsedSql, stmt, ctx); } catch (IllegalArgumentException e) { throw new UnableToCreateStatementException( "Exception parsing for named parameter replacement", e, ctx); } }
public void tearDown() { try { new DBI(jdbcUri + ";drop=true").open().close(); } catch (UnableToObtainConnectionException e) { SQLException cause = (SQLException) e.getCause(); // error code "08006" indicates proper shutdown Assert.assertEquals(String.format("Derby not shutdown: [%s]", cause.toString()), "08006", cause.getSQLState() ); } }
@Override public void commitInsertTable(Table table, boolean overwrite) throws MetaException { LOG.debug("commit insert into table {} overwrite {}", table.getTableName(), overwrite); try { // Check if there segments to load final Path segmentDescriptorDir = getSegmentDescriptorDir(); final List<DataSegment> segmentsToLoad = fetchSegmentsMetadata(segmentDescriptorDir); final String dataSourceName = table.getParameters().get(Constants.DRUID_DATA_SOURCE); //No segments to load still need to honer overwrite if (segmentsToLoad.isEmpty() && overwrite) { //disable datasource //Case it is an insert overwrite we have to disable the existing Druid DataSource DruidStorageHandlerUtils.disableDataSource(getConnector(), getDruidMetadataStorageTablesConfig(), dataSourceName); } else if (!segmentsToLoad.isEmpty()) { // at this point we have Druid segments from reducers but we need to atomically // rename and commit to metadata // Moving Druid segments and committing to druid metadata as one transaction. checkLoadStatus(loadAndCommitDruidSegments(table, overwrite, segmentsToLoad)); } } catch (IOException e) { throw new MetaException(e.getMessage()); } catch (CallbackFailedException c) { LOG.error("Error while committing transaction to druid metadata storage", c); throw new MetaException(c.getCause().getMessage()); } finally { cleanWorkingDir(); } }
private Optional<List<KeyRecord>> getLocalKeys(Account destination, String deviceIdSelector) { try { if (deviceIdSelector.equals("*")) { return keys.get(destination.getNumber()); } long deviceId = Long.parseLong(deviceIdSelector); for (int i=0;i<20;i++) { try { return keys.get(destination.getNumber(), deviceId); } catch (UnableToExecuteStatementException e) { logger.info(e.getMessage()); } } throw new WebApplicationException(Response.status(500).build()); } catch (NumberFormatException e) { throw new WebApplicationException(Response.status(422).build()); } } }
@Override public SingularityRequestHistory map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { return new SingularityRequestHistory(r.getTimestamp("createdAt").getTime(), Optional.fromNullable(r.getString(userColumn)), RequestHistoryType.valueOf(r.getString("requestState")), singularityRequestTranscoder.fromBytes(r.getBytes("request")), Optional.fromNullable(r.getString("message"))); } catch (SingularityTranscoderException e) { throw new ResultSetException("Could not deserialize database result", e, ctx); } } }
/** * Release a previously created checkpoint * * @param handle the handle on which the checkpoint is being released * @param checkpointName the checkpoint to release */ public void release(Handle handle, String checkpointName) { throw new TransactionException("Rollback called, this runtime exception thrown to halt the transaction"); }
public static <T> T runTransaction(IDBI dbi, TransactionCallback<T> callback) { try { return dbi.inTransaction(callback); } catch (DBIException e) { propagateIfInstanceOf(e.getCause(), PrestoException.class); throw metadataError(e); } }
public void tearDown() { try { new DBI(jdbcUri + ";drop=true").open().close(); } catch (UnableToObtainConnectionException e) { SQLException cause = (SQLException) e.getCause(); // error code "08006" indicates proper shutdown Assert.assertEquals(StringUtils.format("Derby not shutdown: [%s]", cause.toString()), "08006", cause.getSQLState()); } }
@Override public SingularityTaskIdHistory map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { final SingularityTaskId taskId = singularityTaskIdTranscoder.fromString(r.getString("taskId")); final String lastTaskStatus = r.getString("lastTaskStatus"); Optional<ExtendedTaskState> lastTaskState = Optional.absent(); if (lastTaskStatus != null) { try { lastTaskState = Optional.of(ExtendedTaskState.valueOf(lastTaskStatus)); } catch (IllegalArgumentException e) { LOG.warn("Found invalid taskState {} in DB for task {}", lastTaskState, taskId, e); } } return new SingularityTaskIdHistory(taskId, r.getTimestamp("updatedAt").getTime(), lastTaskState, Optional.fromNullable(r.getString("runId"))); } catch (SingularityTranscoderException e) { throw new ResultSetException("Could not deserialize database result", e, ctx); } } }
/** * Called when a transaction is rolled back * Will throw a RuntimeException to force transactional rollback */ @Override public void rollback(Handle handle) { throw new TransactionException("Rollback called, this runtime exception thrown to halt the transaction"); }
/** * Release a previously created checkpoint * * @param handle the handle on which the checkpoint is being released * @param checkpointName the checkpoint to release */ @Override public void release(Handle handle, String checkpointName) { throw new TransactionException("Rollback called, this runtime exception thrown to halt the transaction"); }