@Override public Response deleteRecord(String keyspaceName, String tableName, String identifier) { long startTime = System.currentTimeMillis(); ProjectLogger.log("Cassandra Service deleteRecord method started at ==" + startTime, LoggerEnum.PERF_LOG); Response response = new Response(); try { Delete.Where delete = QueryBuilder.delete().from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log("Cassandra Service deleteRecord method end at ==" + stopTime + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return response; }
@Override public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { String tokenValue = refreshToken.getValue(); // Lookup RefreshTokenToAccessToken table for locating access token RefreshTokenToAccessToken refreshTokenToAccessToken = refreshTokenToAccessTokenRepository.findOne(tokenValue); if (refreshTokenToAccessToken != null) { String accessTokenKey = refreshTokenToAccessToken.getAccessTokenKey(); AccessToken accessToken = accessTokenRepository.findOne(accessTokenKey); String jsonOAuth2AccessToken = accessToken.getoAuth2AccessToken(); OAuth2AccessToken oAuth2AccessToken = OAuthUtil.deserializeOAuth2AccessToken(jsonOAuth2AccessToken); // Delete access token from all related tables List<RegularStatement> statementList = prepareRemoveAccessTokenStatements(oAuth2AccessToken); // Delete from RefreshTokenToAccessToken table Delete refreshTokenToAccessTokenDelete = CassandraTemplate.createDeleteQuery(RefreshTokenToAccessToken.TABLE, refreshTokenToAccessToken, null, cassandraTemplate.getConverter()); statementList.add(refreshTokenToAccessTokenDelete); Batch batch = QueryBuilder.batch(statementList.toArray(new RegularStatement[statementList.size()])); cassandraTemplate.execute(batch); } }
public void deleteRows(String tablename, Map<String, String> cols) { String ns = ""; String tbl = tablename; int ix = tbl.indexOf('.'); if (ix >= 0) { ns = tablename.substring(0, ix); tbl = tablename.substring(ix+1); } Delete stmt = QueryBuilder.delete().from(ns, tbl); if (cols.size() == 1) { // only handles 1 WHERE value right now String k = cols.keySet().iterator().next(); Clause eqclause = QueryBuilder.eq(k, cols.get(k)); session.execute(stmt.where(eqclause)); } else { session.execute(stmt); } }
private static String processKeys(String[] columnNames, BuiltStatement delete) { BuiltStatement query = null; boolean isWhereNeeded = true; for (String columnName : columnNames) { if (isWhereNeeded) { if (delete instanceof Delete) { query = ((Delete) delete).where(QueryBuilder.eq(columnName, "?")); } else { query = ((Select) delete).where(QueryBuilder.eq(columnName, "?")); } isWhereNeeded = false; } else { if (delete instanceof Delete) { query = ((Delete.Where) query).and(QueryBuilder.eq(columnName, "?")); } else { query = ((Select.Where) query).and(QueryBuilder.eq(columnName, "?")); } } } return query != null ? query.getQueryString() : null; }
@SuppressWarnings("rawtypes") public void delete(String keyspace, String table, JSONArray columns, JSONObject where, ConsistencyLevel consistency_level) throws MemnonException, IOException { Delete.Selection selection = QueryBuilder.delete(); if (columns == null) { selection.all(); } else { Iterator columnIterator = columns.iterator(); while (columnIterator.hasNext()) { selection.column((String) columnIterator.next()); } } Delete statement = selection.from(table); Iterator whereIterator = where.entrySet().iterator(); while (whereIterator.hasNext()) { Map.Entry pair = (Map.Entry) whereIterator.next(); Clause clause = QueryBuilder.eq((String) pair.getKey(), pair.getValue()); statement.where(clause); } executeStatement(keyspace, statement); }
/** * Generate delete where columns = ? CQL. */ public static Delete generateDelete(String table, String[] whereColumns, int whereColumnsMaxIndex, boolean ifExists) { Delete delete = delete().from(table); if (isWhereClause(whereColumns, whereColumnsMaxIndex)) { Delete.Where where = delete.where(); for (int i = 0; i < whereColumns.length && i < whereColumnsMaxIndex; i++) { where.and(eq(whereColumns[i], bindMarker())); } } if (ifExists) { delete = delete.ifExists(); } return delete; }
private void initDeleteIfIdStatement() { Delete delete = generateDelete(table, pkColumns, false); Delete.Conditions deleteIf = delete.onlyIf(eq(exchangeIdColumn, bindMarker())); deleteIf = applyConsistencyLevel(deleteIf, writeConsistencyLevel); LOGGER.debug("Generated Delete If Id {}", deleteIf); deleteIfIdStatement = getSession().prepare(deleteIf); }
@Inject public CassandraSampleRepository(CassandraSession session, @Named("samples.cassandra.time-to-live") int ttl, MetricRegistry registry, SampleProcessorService processorService, ContextConfigurations contextConfigurations) { m_session = checkNotNull(session, "session argument"); checkArgument(ttl >= 0, "Negative Cassandra column TTL"); m_ttl = ttl; checkNotNull(registry, "metric registry argument"); m_processorService = processorService; m_contextConfigurations = checkNotNull(contextConfigurations, "contextConfigurations argument"); Select select = QueryBuilder.select().from(SchemaConstants.T_SAMPLES); select.where(eq(SchemaConstants.F_CONTEXT, bindMarker(SchemaConstants.F_CONTEXT))); select.where(eq(SchemaConstants.F_PARTITION, bindMarker(SchemaConstants.F_PARTITION))); select.where(eq(SchemaConstants.F_RESOURCE, bindMarker(SchemaConstants.F_RESOURCE))); select.where(gte(SchemaConstants.F_COLLECTED, bindMarker("start"))); select.where(lte(SchemaConstants.F_COLLECTED, bindMarker("end"))); m_selectStatement = m_session.prepare(select.toString()); Delete delete = QueryBuilder.delete().from(SchemaConstants.T_SAMPLES); delete.where(eq(SchemaConstants.F_CONTEXT, bindMarker(SchemaConstants.F_CONTEXT))); delete.where(eq(SchemaConstants.F_PARTITION, bindMarker(SchemaConstants.F_PARTITION))); delete.where(eq(SchemaConstants.F_RESOURCE, bindMarker(SchemaConstants.F_RESOURCE))); m_deleteStatement = m_session.prepare(delete.toString()); m_sampleSelectTimer = registry.timer(metricName("sample-select-timer")); m_measurementSelectTimer = registry.timer(metricName("measurement-select-timer")); m_insertTimer = registry.timer(metricName("insert-timer")); m_samplesInserted = registry.meter(metricName("samples-inserted")); m_samplesSelected = registry.meter(metricName("samples-selected")); }
@Override public void removeByEndpointKeyHashAndConfigurationVersion(byte[] endpointKeyHash, Integer confSchemaVersion) { LOG.debug("Remove endpoint specific configuration by endpointKeyHash {} and confSchemaVersion {}", endpointKeyHash, confSchemaVersion); Delete.Where deleteQuery = delete().from(getColumnFamilyName()) .where(eq(EPS_CONFIGURATION_KEY_HASH_PROPERTY, getByteBuffer(endpointKeyHash))) .and(eq(EP_CONFIGURATION_VERSION_PROPERTY, confSchemaVersion)); LOG.trace("Remove endpoint specific configuration by endpointKeyHash and confSchemaVersion query {}", deleteQuery); execute(deleteQuery); }
@Override public void remove(String applicationId, String credentialsId) { LOG.debug("Deleting credential by applicationID[{}] and credentialsID[{}]", applicationId, credentialsId); Delete.Where query = delete().from(getColumnFamilyName()) .where(eq(CREDENTIALS_ID_PROPERTY, credentialsId)) .and(eq(CREDENTIALS_APPLICATION_ID_PROPERTY, applicationId)); execute(query); }
@Override public void removeById(String id) { LOG.debug("Remove notification by id {}", id); CassandraNotification nf = new CassandraNotification(id); Delete.Where deleteQuery = delete().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, nf.getTopicId())) .and(eq(NF_NOTIFICATION_TYPE_PROPERTY, nf.getType().name())) .and(eq(NF_VERSION_PROPERTY, nf.getNfVersion())) .and(eq(NF_SEQ_NUM_PROPERTY, nf.getSeqNum())); LOG.trace("Remove notification by id {}", deleteQuery); execute(deleteQuery); }
@Override public void removeNotificationsByTopicId(String topicId) { LOG.debug("Remove notifications by topic id {}", topicId); Delete.Where query = delete().from(getColumnFamilyName()) .where(eq(NF_TOPIC_ID_PROPERTY, topicId)) .and(QueryBuilder.in( NF_NOTIFICATION_TYPE_PROPERTY, getStringTypes(NotificationTypeDto.values()))); execute(query); LOG.trace("Execute query {}", query); }
/** * This method returns CQL Qeury for DeleteByQuery method. * refer: http://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlDelete.html * * @param mapping Cassandra Mapping {@link CassandraMapping} * @param cassandraQuery Cassandra Query {@link CassandraQuery} * @param objects field values * @return CQL Query */ static String getDeleteByQuery(CassandraMapping mapping, Query cassandraQuery, List<Object> objects) { String[] columns = null; if (cassandraQuery.getFields() != null) { columns = getColumnNames(mapping, Arrays.asList(cassandraQuery.getFields())); } Delete delete; if (columns != null) { delete = QueryBuilder.delete(columns).from(mapping.getKeySpace().getName(), mapping.getCoreName()); } else { delete = QueryBuilder.delete().from(mapping.getKeySpace().getName(), mapping.getCoreName()); } return processQuery(cassandraQuery, delete, mapping, objects); }
private Collection<RegularStatement> diffMap(String table, String column, Clause whereClause, Map<?, ?> past, Map<?, ?> present) { List<RegularStatement> queries = Lists.newArrayList(); Set<?> removed = Sets.newHashSet(past.keySet()); removed.removeAll(present.keySet()); if (!removed.isEmpty()) { Delete.Selection delete = QueryBuilder.delete(); for (Object o : removed) { delete.mapElt(column, o); } queries.add(delete.from(table).where(whereClause)); } Set<Entry<?, ?>> changed = Sets.<Entry<?, ?>> newHashSet(present.entrySet()); changed.removeAll(past.entrySet()); if (!changed.isEmpty()) { Update update = QueryBuilder.update(table); for (Entry<?, ?> entry : changed) { update.with(QueryBuilder.put(column, entry.getKey(), entry.getValue())); } queries.add(update.where(whereClause)); } return queries; }
public static Statement makeCQLforDeleteUUIDFromIndex_WorkaroundForUnpreparableTimestamp(String keyspace, CDefinition def, CIndex index, UUID uuid, Map<String,Object> indexValues, Long timestamp){ Statement ret = QueryBuilder.delete() .from(keyspace,makeIndexTableName(def,index)) .using(QueryBuilder.timestamp(timestamp)) .where(QueryBuilder.eq("id",uuid)) .and(QueryBuilder.eq("shardid", Long.valueOf(index.getShardingStrategy().getShardKey(uuid)))); for(String key : indexValues.keySet()){ ((Delete.Where)ret).and(QueryBuilder.eq(key,indexValues.get(key))); } return ret; }
private List<RegularStatement> prepareRemoveAccessTokenStatements(OAuth2AccessToken token) { //String tokenId = token.getValue(); String tokenValue = token.getValue(); String jsonOAuth2AccessToken = OAuthUtil.serializeOAuth2AccessToken(token); List<RegularStatement> statementList = new ArrayList<RegularStatement>(); // Delete from AccessToken table RegularStatement accessTokenDelete = prepareDeleteByPrimaryKeyRegularStatement(AccessToken.class, tokenValue); statementList.add(accessTokenDelete); // Lookup Authentication table for further deleting from AuthenticationToAccessToken table Authentication authentication = authenticationRepository.findOne(tokenValue); if (authentication != null) { ByteBuffer bufferedOAuth2Authentication = authentication.getoAuth2Authentication(); byte[] serializedOAuth2Authentication = new byte[bufferedOAuth2Authentication.remaining()]; bufferedOAuth2Authentication.get(serializedOAuth2Authentication); OAuth2Authentication oAuth2Authentication = SerializationUtils.deserialize(serializedOAuth2Authentication); String clientId = oAuth2Authentication.getOAuth2Request().getClientId(); // Delete from Authentication table RegularStatement authenticationDelete = prepareDeleteByPrimaryKeyRegularStatement(Authentication.class, tokenValue); statementList.add(authenticationDelete); // Delete from AuthenticationToAccessToken table RegularStatement authToAccessDelete = prepareDeleteByPrimaryKeyRegularStatement(AuthenticationToAccessToken.class, authenticationKeyGenerator.extractKey(oAuth2Authentication)); statementList.add(authToAccessDelete); // Delete from UsernameToAccessToken table Optional<UsernameToAccessToken> optionalUsernameToAccessToken = usernameToAccessTokenRepository.findByKeyAndOAuth2AccessToken(OAuthUtil.getApprovalKey(clientId, oAuth2Authentication.getName()), jsonOAuth2AccessToken); optionalUsernameToAccessToken.ifPresent(usernameToAccessToken -> { Delete usernameToAccessDelete = CassandraTemplate.createDeleteQuery(UsernameToAccessToken.TABLE, usernameToAccessToken, null, cassandraTemplate.getConverter()); statementList.add(usernameToAccessDelete); }); // Delete from ClientIdToAccessToken table Optional<ClientIdToAccessToken> optionalClientIdToAccessToken = clientIdToAccessTokenRepository.findByKeyAndOAuth2AccessToken(clientId, jsonOAuth2AccessToken); optionalClientIdToAccessToken.ifPresent(clientIdToAccessToken -> { Delete clientIdToAccessDelete = CassandraTemplate.createDeleteQuery(ClientIdToAccessToken.TABLE, clientIdToAccessToken, null, cassandraTemplate.getConverter()); statementList.add(clientIdToAccessDelete); }); } return statementList; }
private Delete.Where removeAnalyse(Identifier accId, String analyseId) { return QueryBuilder.delete().all().from(TABLE_NAME) .where(eq("id", UUID.fromString(analyseId))).and(eq("account_id", accId.toString())); }
protected Delete.Where delete(Identifier accId, UUID uuid, String column, Object key) { return QueryBuilder.delete().mapElt(column, key).from(TABLE_NAME).where(eq("id", uuid)).and(eq("account_id", accId.toString())); }
/** * Generate delete where columns = ? CQL. */ public static Delete generateDelete(String table, String[] whereColumns, boolean ifExists) { return generateDelete(table, whereColumns, size(whereColumns), ifExists); }
private void initDeleteStatement() { Delete delete = generateDelete(table, pkColumns, false); delete = applyConsistencyLevel(delete, writeConsistencyLevel); LOGGER.debug("Generated Delete {}", delete); deleteStatement = getSession().prepare(delete); }
protected void initDeleteStatement() { Delete delete = generateDelete(table, pkColumns, true); delete = applyConsistencyLevel(delete, writeConsistencyLevel); LOGGER.debug("Generated Delete {}", delete); deleteStatement = getSession().prepare(delete); }
private void clearState() { Delete deleteStatement = delete().all().from(KEYSPACE_NAME, TABLE_NAME); deleteStatement.where(eq(KEY_NAME, "MD")); clientFactory.getSession().execute(deleteStatement); }
@Override public void deletePath(K rowKey, Path path, BatchContext batchContext) { Batch batch = validateAndGetBatch(batchContext); validateArgs(rowKey, path); // converting from a string and back normalizes the path, e.g. makes sure ends with the delimiter character String start = path.toString(); String finish = getFinishString(start); // would like to just do a delete with a where clause, but unfortunately Cassandra can't do that in CQL (either) // with >= and <= // Since the path column is in the primary key, we need to just delete whole rows. Object[] args = {rowKey,start,finish}; ResultSet resultSet = session.execute(readForDeleteQuery.bind(args)); if (resultSet.isExhausted()) { // not found return; } Delete deleteStatement = delete().from(tableName); deleteStatement .using(timestamp(getCurrentMicros())) .where(eq(partitionKeyColumnName, rowKey)) .and(eq(pathColumnName, bindMarker())); batch = batchContext == null ? batch() : batch; List<Object> bindArguments = batchContext == null ? new ArrayList<Object>() : ((CqlBatchContext)batchContext).getBindArguments(); for (Row row : resultSet) { String pathToDelete = row.getString(0); batch.add(deleteStatement); bindArguments.add(pathToDelete); } if (batchContext == null) { BoundStatement query = session.prepare(batch.getQueryString()).bind(bindArguments.toArray()); query.setConsistencyLevel(defaultConsistencyLevel); session.execute(query); } }
/** * This method return the CQL query to delete a persistent in the table. * refer : http://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlDelete.html * * @param mapping Cassandra Mapping {@link CassandraMapping} * @param fields filed list to be deleted * @return CQL Query */ static String getDeleteDataQuery(CassandraMapping mapping, List<String> fields) { String[] columnNames = getColumnNames(mapping, fields); String[] objects = new String[fields.size()]; Arrays.fill(objects, "?"); Delete delete = QueryBuilder.delete().from(mapping.getKeySpace().getName(), mapping.getCoreName()); return processKeys(columnNames, delete); }