/** * Performs the {@link #delete(String, String)} (String, String)} operation via N1QL ("DELETE"). * * If this option should be used, the "-p couchbase.kv=false" property must be set. * * @param docId the document ID. * @return The result of the operation. */ private Status deleteN1ql(final String docId) throws Exception { String deleteQuery = "DELETE FROM `" + bucketName + "` USE KEYS [$1]"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( deleteQuery, JsonArray.from(docId), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + deleteQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
@Test public void shouldExecuteN1ql() { getBucket().query(N1qlQuery.simple("INSERT INTO " + TEST_BUCKET + " (KEY, VALUE) VALUES ('" + ID + "', " + DOCUMENT + ")")); N1qlQueryResult query = getBucket().query(N1qlQuery.simple("SELECT * FROM " + TEST_BUCKET + " USE KEYS '" + ID + "'")); Assert.assertTrue(query.parseSuccess()); Assert.assertTrue(query.finalSuccess()); List<N1qlQueryRow> n1qlQueryRows = query.allRows(); Assert.assertEquals(1, n1qlQueryRows.size()); Assert.assertEquals(DOCUMENT, n1qlQueryRows.get(0).value().get(TEST_BUCKET).toString()); }
@Override public long removeByPattern(String regex) throws IOException { Statement statement = Delete.deleteFromCurrentBucket().where(regexpContains("meta().id", regex)); final N1qlQueryResult result = bucket.query(N1qlQuery.simple(statement)); if (logger.isDebugEnabled()) { logger.debug("Deleted documents using regex {}, result={}", regex, result); } return result.info().mutationCount(); } }
)); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + readQuery + ", Errors: " + queryResult.errors()); row = queryResult.rows().next(); } catch (NoSuchElementException ex) { return Status.NOT_FOUND;
@Override public <T> List<T> findByN1QLProjection(N1qlQuery n1ql, Class<T> entityClass) { checkN1ql(); try { N1qlQueryResult queryResult = queryN1QL(n1ql); if (queryResult.finalSuccess()) { List<N1qlQueryRow> allRows = queryResult.allRows(); List<T> result = new ArrayList<T>(allRows.size()); for (N1qlQueryRow row : allRows) { JsonObject json = row.value(); T decoded = translationService.decodeFragment(json.toString(), entityClass); result.add(decoded); } return result; } else { StringBuilder message = new StringBuilder("Unable to execute query due to the following n1ql errors: "); for (JsonObject error : queryResult.errors()) { message.append('\n').append(error); } throw new CouchbaseQueryExecutionException(message.toString()); } } catch (TranscodingException e) { throw new CouchbaseQueryExecutionException("Unable to execute query", e); } }
/** * Validate query results. * * @param query * the query * @param result * the result */ private void validateQueryResults(String query, N1qlQueryResult result) { LOGGER.debug("Query output status: " + result.finalSuccess()); if (!result.finalSuccess()) { StringBuilder errorBuilder = new StringBuilder(); for (JsonObject obj : result.errors()) { errorBuilder.append(obj.toString()); errorBuilder.append("\n"); } errorBuilder.deleteCharAt(errorBuilder.length() - 1); String errors = errorBuilder.toString(); LOGGER.error(errors); throw new KunderaException("Not able to execute query/statement:" + query + ". More details : " + errors); } }
@Override public N1qlQueryResult execute(String statement) throws ResourceException { N1qlQueryResult result = this.bucket.query(N1qlQuery.simple(statement, N1qlParams.build().consistency(scanConsistency))); if (!result.finalSuccess()) { throw new ResourceException(UTIL.gs("query_error", result.errors()), result.status()); //$NON-NLS-1$ } return result; }
/** * Execute native query. * * @param n1qlQuery * the n1ql query * @param em * the entity manager * @return the list */ public List executeNativeQuery(String n1qlQuery, EntityMetadata em) { N1qlQueryResult result = bucket .query(N1qlQuery.simple(n1qlQuery, N1qlParams.build().consistency(ScanConsistency.REQUEST_PLUS))); LOGGER.debug("Executed query : " + n1qlQuery + " on the " + bucket.name() + " Bucket"); validateQueryResults(n1qlQuery, result); return result.allRows(); }
@Override public <T> List<T> findByN1QLProjection(N1qlQuery n1ql, Class<T> entityClass) { checkN1ql(); try { N1qlQueryResult queryResult = queryN1QL(n1ql); if (queryResult.finalSuccess()) { List<N1qlQueryRow> allRows = queryResult.allRows(); List<T> result = new ArrayList<T>(allRows.size()); for (N1qlQueryRow row : allRows) { JsonObject json = row.value(); T decoded = translationService.decodeFragment(json.toString(), entityClass); result.add(decoded); } return result; } else { StringBuilder message = new StringBuilder("Unable to execute query due to the following n1ql errors: "); for (JsonObject error : queryResult.errors()) { message.append('\n').append(error); } throw new CouchbaseQueryExecutionException(message.toString()); } } catch (TranscodingException e) { throw new CouchbaseQueryExecutionException("Unable to execute query", e); } }
private void createPrimaryIndex(Bucket bucket, CouchbaseBuildDefinition buildDefinition) { LOG.debug("Creating primary index in bucket '{}'", buildDefinition.getBucketName()); N1qlQueryResult result = bucket.query(N1qlQuery.simple( Index.createPrimaryIndex().on(bucket.name()) )); if (!result.finalSuccess()) { LOG.error("Failed to create primary index: {}", result.errors()); throw new EnvironmentBuilderException("Failed to create primary index for " + buildDefinition.getBucketName()); } LOG.debug("Primary index created in bucket '{}'", buildDefinition.getBucketName()); }
@Override public N1qlQueryResult execute(String statement) throws TranslatorException { N1qlQueryResult result = this.bucket.query(N1qlQuery.simple(statement, N1qlParams.build().consistency(scanConsistency))); if (!result.finalSuccess()) { TranslatorException te = new TranslatorException(UTIL.gs("query_error", result.errors())); //$NON-NLS-1$ te.setCode(result.status()); throw te; } return result; }
static List<DocumentEntity> convert(N1qlQueryResult result, String database) { return result.allRows().stream() .map(N1qlQueryRow::value) .map(JsonObject::toMap) .map(m -> m.get(database)) .filter(Objects::nonNull) .filter(Map.class::isInstance) .map(m -> (Map<String, Object>) m) .map(map -> { List<Document> documents = toDocuments(map); Optional<Document> keyDocument = documents.stream().filter(d -> KEY_FIELD.equals(d.getName())).findFirst(); String collection = keyDocument.map(d -> d.get(String.class)).orElse(database).split(SPLIT_KEY)[0]; return DocumentEntity.of(collection, documents); }).collect(toList()); }
N1qlQueryResult queryResult = queryN1QL(n1ql); if (queryResult.finalSuccess()) { List<N1qlQueryRow> allRows = queryResult.allRows(); List<T> result = new ArrayList<T>(allRows.size()); for (N1qlQueryRow row : allRows) { for (JsonObject error : queryResult.errors()) { message.append('\n').append(error);
/** * Performs the {@link #insert(String, String, Map)} operation via N1QL ("INSERT"). * * If this option should be used, the "-p couchbase.kv=false" property must be set. * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status insertN1ql(final String docId, final Map<String, ByteIterator> values) throws Exception { String insertQuery = "INSERT INTO `" + bucketName + "`(KEY,VALUE) VALUES ($1,$2)"; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( insertQuery, JsonArray.from(docId, valuesToJsonObject(values)), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + insertQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
/** * Query and get a result by username. * * @param usernameAttribute the username attribute * @param usernameValue the username value * @return the n1ql query result * @throws GeneralSecurityException the general security exception */ public N1qlQueryResult query(final String usernameAttribute, final String usernameValue) throws GeneralSecurityException { val theBucket = getBucket(); val statement = Select.select("*") .from(Expression.i(theBucket.name())) .where(Expression.x(usernameAttribute).eq('\'' + usernameValue + '\'')); LOGGER.debug("Running query [{}] on bucket [{}]", statement.toString(), theBucket.name()); val query = N1qlQuery.simple(statement); val result = theBucket.query(query, timeout, TimeUnit.MILLISECONDS); if (!result.finalSuccess()) { LOGGER.error("Couchbase query failed with [{}]", result.errors() .stream() .map(JsonObject::toString) .collect(Collectors.joining(","))); throw new GeneralSecurityException("Could not locate account for user " + usernameValue); } return result; }
/** {@inheritDoc} */ @Override public Map<String, Property<?>> readAllProperties() { N1qlQuery queryFeatures = N1qlQuery.simple("SELECT * FROM " + couchBaseConnection.getFf4jPropertyBucketName()); N1qlQueryResult queryResult = getPropertyBucket().query(queryFeatures); Map<String, Property<?>> allProperties = new HashMap<>(); for (N1qlQueryRow row : queryResult.allRows()) { Property<?> p = PropertyJsonParser.parseProperty(row.value().get(couchBaseConnection.getFf4jPropertyBucketName()).toString()); allProperties.put(p.getName(), p); } return allProperties; }
private List<JsonObject> executeQuery(N1qlQuery query) { if(this.bucket.isClosed()){ throw new RuntimeException("bucket has been closed before performing the query"); } N1qlQueryResult queryResult = this.bucket.query(query); List<JsonObject> result = null; if (queryResult != null && queryResult.info().errorCount() == 0 && queryResult.info().resultCount() > 0) { result = new ArrayList<JsonObject>(); for (N1qlQueryRow queryRow : queryResult) { result.add(queryRow.value()); } } return result; } }
N1qlQueryResult queryResult = queryN1QL(n1ql); if (queryResult.finalSuccess()) { List<N1qlQueryRow> allRows = queryResult.allRows(); List<T> result = new ArrayList<T>(allRows.size()); for (N1qlQueryRow row : allRows) { for (JsonObject error : queryResult.errors()) { message.append('\n').append(error);
/** * Performs the {@link #update(String, String, Map)} operation via N1QL ("UPDATE"). * * If this option should be used, the "-p couchbase.kv=false" property must be set. * * @param docId the document ID * @param values the values to update the document with. * @return The result of the operation. */ private Status updateN1ql(final String docId, final Map<String, ByteIterator> values) throws Exception { String fields = encodeN1qlFields(values); String updateQuery = "UPDATE `" + bucketName + "` USE KEYS [$1] SET " + fields; N1qlQueryResult queryResult = bucket.query(N1qlQuery.parameterized( updateQuery, JsonArray.from(docId), N1qlParams.build().adhoc(adhoc).maxParallelism(maxParallelism) )); if (!queryResult.parseSuccess() || !queryResult.finalSuccess()) { throw new DBException("Error while parsing N1QL Result. Query: " + updateQuery + ", Errors: " + queryResult.errors()); } return Status.OK; }
/** {@inheritDoc} */ @Override public Map<String, Feature> readAll() { // To retrieve the items we use the BUCKET (not view as KEY/VALUE searches) N1qlQuery queryFeatures = N1qlQuery.simple("SELECT * FROM " + couchBaseConnection.getFf4jFeatureBucketName()); N1qlQueryResult queryResult = getFeatureBucket().query(queryFeatures); Map<String, Feature> allFeatures = new HashMap<>(); for (N1qlQueryRow row : queryResult.allRows()) { Feature f = FeatureJsonParser.parseFeature(row.value().get(couchBaseConnection.getFf4jFeatureBucketName()).toString()); allFeatures.put(f.getUid(), f); } return allFeatures; }