Java Code Examples for com.google.cloud.datastore.GqlQuery

The following examples show how to use com.google.cloud.datastore.GqlQuery. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQuery.java    License: Apache License 2.0 6 votes vote down vote up
private GqlQuery<? extends BaseEntity> bindArgsToGqlQuery() {
	Builder builder = GqlQuery.newGqlQueryBuilder(this.finalGql);
	builder.setAllowLiteral(true);
	if (this.tagsOrdered.size() != this.params.size()) {
		throw new DatastoreDataException("Annotated GQL Query Method "
				+ GqlDatastoreQuery.this.queryMethod.getName() + " has " + this.tagsOrdered.size()
				+ " tags but a different number of parameter values: " + this.params.size());
	}
	for (int i = 0; i < this.tagsOrdered.size(); i++) {
		Object val = this.params.get(i);
		Object boundVal;
		if (val instanceof Cursor) {
			boundVal = val;
		}
		else if (ValueUtil.isCollectionLike(val.getClass())) {
			boundVal = convertCollectionParamToCompatibleArray((List) ValueUtil.toListIfArray(val));
		}
		else {
			boundVal = GqlDatastoreQuery.this.datastoreOperations.getDatastoreEntityConverter().getConversions()
					.convertOnWriteSingle(convertEntitiesToKeys(val)).get();
		}
		DatastoreNativeTypes.bindValueToGqlBuilder(builder, this.tagsOrdered.get(i), boundVal);
	}
	return builder.build();
}
 
Example 2
Source Project: catatumbo   Source File: DefaultDatastoreMetadata.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getKinds(boolean excludeSystemKinds) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_KINDS + " ORDER BY __key__";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    gqlQueryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    QueryResults<Key> results = entityManager.getDatastore().run(gqlQuery);
    List<String> kinds = new ArrayList<>(50);
    while (results.hasNext()) {
      Key key = results.next();
      String kind = key.getName();
      if (excludeSystemKinds && kind.startsWith("__")) {
        continue;
      }
      kinds.add(key.getName());
    }
    return kinds;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 3
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(Object[] parameters) {
	if (getAnnotation(this.entityType.getSuperclass(), DiscriminatorField.class) != null) {
		throw new DatastoreDataException("Can't append discrimination condition");
	}

	ParsedQueryWithTagsAndValues parsedQueryWithTagsAndValues =
			new ParsedQueryWithTagsAndValues(this.originalParamTags, parameters);

	GqlQuery query = parsedQueryWithTagsAndValues.bindArgsToGqlQuery();

	Class returnedItemType = this.queryMethod.getReturnedObjectType();

	boolean isNonEntityReturnType = isNonEntityReturnedType(returnedItemType);

	DatastoreResultsIterable found = isNonEntityReturnType
			? this.datastoreOperations.queryIterable(query, GqlDatastoreQuery::getNonEntityObjectFromRow)
			: this.datastoreOperations.queryKeysOrEntities(query, this.entityType);

	Object result;
	if (isPageQuery() || isSliceQuery()) {
		result = buildPageOrSlice(parameters, parsedQueryWithTagsAndValues, found);
	}
	else if (this.queryMethod.isCollectionQuery()) {
		result = convertCollectionResult(returnedItemType, found);
	}
	else {
		result = convertSingularResult(returnedItemType, isNonEntityReturnType, found);
	}

	return result;
}
 
Example 4
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
private Slice buildSlice(Pageable pageableParam, ParsedQueryWithTagsAndValues parsedQueryWithTagsAndValues,
		Cursor cursor, List resultsList) {
	GqlQuery nextQuery = parsedQueryWithTagsAndValues.bindArgsToGqlQuery(cursor, 1);
	DatastoreResultsIterable<?> next = this.datastoreOperations.queryKeysOrEntities(nextQuery, this.entityType);

	Pageable pageable = DatastorePageable.from(pageableParam, cursor, null);
	return new SliceImpl(resultsList, pageable, next.iterator().hasNext());
}
 
Example 5
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
private Page buildPage(Pageable pageableParam, ParsedQueryWithTagsAndValues parsedQueryWithTagsAndValues,
		Cursor cursor, List resultsList) {
	Long count = pageableParam instanceof DatastorePageable
			? ((DatastorePageable) pageableParam).getTotalCount()
			: null;
	if (count == null) {
		GqlQuery nextQuery = parsedQueryWithTagsAndValues.bindArgsToGqlQueryNoLimit();
		DatastoreResultsIterable<?> next = this.datastoreOperations.queryKeysOrEntities(nextQuery,
				this.entityType);
		count = StreamSupport.stream(next.spliterator(), false).count();
	}

	Pageable pageable = DatastorePageable.from(pageableParam, cursor, count);
	return new PageImpl(resultsList, pageable, count);
}
 
Example 6
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
private GqlQuery<? extends BaseEntity> bindArgsToGqlQueryNoLimit() {
	this.finalGql = this.noLimitQuery;
	this.tagsOrdered = this.tagsOrdered.subList(0, this.limitPosition);
	this.params = this.params.subList(0, this.limitPosition);

	return bindArgsToGqlQuery();
}
 
Example 7
Source Project: catatumbo   Source File: DefaultDatastoreMetadata.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QueryResponse<String> getNamespaces(DatastoreCursor fromCursor, int limit) {
  try {
    String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__";
    if (limit > 0) {
      query += " LIMIT @Limit";
    }
    query += " OFFSET @Offset";
    GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query);
    if (limit > 0) {
      gqlQueryBuilder.setBinding("Limit", limit);
    }
    gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded()));
    GqlQuery<Key> gqlQuery = gqlQueryBuilder.build();
    Datastore datastore = entityManager.getDatastore();
    QueryResults<Key> results = datastore.run(gqlQuery);
    DefaultQueryResponse<String> response = new DefaultQueryResponse<>();
    List<String> namespaces = new ArrayList<>(Math.max(limit, 50));
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Key key = results.next();
      String name = key.getName();
      namespaces.add(name == null ? "" : name);
    }
    response.setResults(namespaces);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 8
Source Project: catatumbo   Source File: QueryUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given positional bindings to the given query builder.
 * 
 * @param queryBuilder
 *          the query builder
 * @param positionalBindings
 *          the positional bindings.
 */
static void applyPositionalBindings(GqlQuery.Builder<?> queryBuilder,
    Object... positionalBindings) {
  if (positionalBindings != null) {
    for (Object binding : positionalBindings) {
      addPositionalBinding(queryBuilder, binding);
    }
  }
}
 
Example 9
Source Project: catatumbo   Source File: QueryUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given positional bindings to the given query builder.
 * 
 * @param queryBuilder
 *          the query builder
 * @param positionalBindings
 *          the positional bindings.
 */
static void applyPositionalBindings(GqlQuery.Builder<?> queryBuilder,
    List<Object> positionalBindings) {
  if (positionalBindings != null) {
    for (Object binding : positionalBindings) {
      addPositionalBinding(queryBuilder, binding);
    }
  }
}
 
Example 10
Source Project: catatumbo   Source File: DefaultDatastoreReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link EntityQueryRequest} and returns the response.
 * 
 * @param expectedResultType
 *          the expected type of results.
 * @param request
 *          the entity query request
 * @return the query response
 */
public <E> QueryResponse<E> executeEntityQueryRequest(Class<E> expectedResultType,
    EntityQueryRequest request) {
  try {
    GqlQuery.Builder<Entity> queryBuilder = Query.newGqlQueryBuilder(ResultType.ENTITY,
        request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<Entity> gqlQuery = queryBuilder.build();
    QueryResults<Entity> results = nativeReader.run(gqlQuery);
    List<E> entities = new ArrayList<>();
    DefaultQueryResponse<E> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Entity result = results.next();
      E entity = Unmarshaller.unmarshal(result, expectedResultType);
      entities.add(entity);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities);
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 11
Source Project: catatumbo   Source File: DefaultDatastoreReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link ProjectionQueryRequest} and returns the response.
 * 
 * @param expectedResultType
 *          the expected type of results.
 * @param request
 *          the projection query request
 * @return the query response
 */
public <E> QueryResponse<E> executeProjectionQueryRequest(Class<E> expectedResultType,
    ProjectionQueryRequest request) {
  try {
    GqlQuery.Builder<ProjectionEntity> queryBuilder = Query
        .newGqlQueryBuilder(ResultType.PROJECTION_ENTITY, request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<ProjectionEntity> gqlQuery = queryBuilder.build();
    QueryResults<ProjectionEntity> results = nativeReader.run(gqlQuery);
    List<E> entities = new ArrayList<>();
    DefaultQueryResponse<E> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      ProjectionEntity result = results.next();
      E entity = Unmarshaller.unmarshal(result, expectedResultType);
      entities.add(entity);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    // TODO should we invoke PostLoad callback for projected entities?
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 12
Source Project: catatumbo   Source File: DefaultDatastoreReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link KeyQueryRequest} and returns the response.
 * 
 * @param request
 *          the key query request
 * @return the query response
 */
public QueryResponse<DatastoreKey> executeKeyQueryRequest(KeyQueryRequest request) {
  try {
    GqlQuery.Builder<Key> queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY,
        request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<Key> gqlQuery = queryBuilder.build();
    QueryResults<Key> results = nativeReader.run(gqlQuery);
    List<DatastoreKey> entities = new ArrayList<>();
    DefaultQueryResponse<DatastoreKey> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      Key result = results.next();
      DatastoreKey datastoreKey = new DefaultDatastoreKey(result);
      entities.add(datastoreKey);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 13
Source Project: catatumbo   Source File: DefaultEntityManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public long deleteAll(String kind) {
  if (Utility.isNullOrEmpty(kind)) {
    throw new IllegalArgumentException("kind cannot be null or blank");
  }
  String query = "SELECT __key__ FROM " + kind;
  try {
    GqlQuery<Key> gqlQuery = Query.newGqlQueryBuilder(Query.ResultType.KEY, query)
        .setNamespace(getEffectiveNamespace()).build();
    QueryResults<Key> keys = datastore.run(gqlQuery);
    Key[] nativeKeys = new Key[DEFAULT_DELETE_ALL_BATCH_SIZE];
    long deleteCount = 0;
    int i = 0;
    while (keys.hasNext()) {
      nativeKeys[i++] = keys.next();
      if (i % DEFAULT_DELETE_ALL_BATCH_SIZE == 0) {
        datastore.delete(nativeKeys);
        deleteCount += DEFAULT_DELETE_ALL_BATCH_SIZE;
        i = 0;
      }
    }
    if (i > 0) {
      datastore.delete(Arrays.copyOfRange(nativeKeys, 0, i));
      deleteCount += i;
    }
    return deleteCount;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example 14
Source Project: styx   Source File: InstrumentedQueryResults.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> String queryKind(Query<T> query) {
  final String kind;
  if (query instanceof StructuredQuery) {
    kind = ((StructuredQuery<T>) query).getKind();
  } else if (query instanceof GqlQuery) {
    kind = "<gql>";
  } else {
    kind = "<unknown>";
  }
  return kind;
}
 
Example 15
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQuery.java    License: Apache License 2.0 4 votes vote down vote up
private GqlQuery<? extends BaseEntity> bindArgsToGqlQuery(Cursor newCursor, int newLimit) {
	this.params.set(this.cursorPosition, newCursor);
	this.params.set(this.limitPosition, newLimit);

	return bindArgsToGqlQuery();
}
 
Example 16
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQueryTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void compoundNameConventionTest() {

	String gql = "SELECT * FROM "
			+ "|org.springframework.cloud.gcp.data.datastore."
			+ "repository.query.GqlDatastoreQueryTests$Trade|"
			+ " WHERE price=:#{#tag6 * -1} AND price<>:#{#tag6 * -1} OR "
			+ "price<>:#{#tag7 * -1} AND " + "( [email protected] AND [email protected] ) OR "
			+ "( [email protected] AND price<@tag3 ) OR ( price>[email protected] AND id<>NULL AND "
			+ "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND "
			+ "price>@tag6 AND price<[email protected] AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3;";

	String entityResolvedGql = "SELECT * FROM trades"
			+ " WHERE [email protected] AND price<>@SpELtag2 OR price<>@SpELtag3 AND "
			+ "( [email protected] AND [email protected] ) OR "
			+ "( [email protected] AND price<@tag3 ) OR ( price>[email protected] AND id<>NULL AND "
			+ "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND "
			+ "price>@tag6 AND price<[email protected] AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3";


	Trade trade = new Trade();
	trade.id = "tradeId1";

	Object[] paramVals = new Object[] { "BUY", "abcd",
			// this is an array param of the non-natively supported type and will need conversion
			new int[] { 1, 2 },
			new double[] { 8.88, 9.99 },
			3, // this parameter is a simple int, which is not a directly supported type and uses
				// conversions
			"blahblah", 1.11, 2.22, trade };

	String[] paramNames = new String[] { "tag0", "tag1", "tag2", "tag3", "tag4",
			"tag5", "tag6", "tag7", "tag8" };

	buildParameters(paramVals, paramNames);

	KeyFactory keyFactory = new KeyFactory("proj");
	keyFactory.setKind("kind");
	Key key = keyFactory.newKey("tradeid1-key");

	doReturn(key).when(this.datastoreTemplate).getKey(any());

	EvaluationContext evaluationContext = new StandardEvaluationContext();
	for (int i = 0; i < paramVals.length; i++) {
		evaluationContext.setVariable(paramNames[i], paramVals[i]);
	}
	when(this.evaluationContextProvider.getEvaluationContext(any(), any()))
			.thenReturn(evaluationContext);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, false);

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString()).isEqualTo(entityResolvedGql);

		Map<String, Value> paramMap = statement.getNamedBindings();

		assertThat(paramMap.get("tag0").get()).isEqualTo(paramVals[0]);
		assertThat(paramMap.get("tag1").get()).isEqualTo(paramVals[1]);

		// custom conversion is expected to have been used in this param
		assertThat((long) ((LongValue) (((List) paramMap.get("tag2").get()).get(0))).get()).isEqualTo(1L);
		assertThat((long) ((LongValue) (((List) paramMap.get("tag2").get()).get(1))).get()).isEqualTo(2L);

		double actual = ((DoubleValue) (((List) paramMap.get("tag3").get()).get(0))).get();
		assertThat(actual).isEqualTo(((double[]) paramVals[3])[0], DELTA);

		actual = ((DoubleValue) (((List) paramMap.get("tag3").get()).get(1))).get();
		assertThat(actual).isEqualTo(((double[]) paramVals[3])[1], DELTA);

		// 3L is expected even though 3 int was the original param due to custom conversions
		assertThat(paramMap.get("tag4").get()).isEqualTo(3L);
		assertThat(paramMap.get("tag5").get()).isEqualTo(paramVals[5]);
		assertThat(paramMap.get("tag6").get()).isEqualTo(paramVals[6]);
		assertThat(paramMap.get("tag7").get()).isEqualTo(paramVals[7]);

		assertThat((double) paramMap.get("SpELtag1").get()).isEqualTo(-1 * (double) paramVals[6],
				DELTA);
		assertThat((double) paramMap.get("SpELtag2").get()).isEqualTo(-1 * (double) paramVals[6],
				DELTA);
		assertThat((double) paramMap.get("SpELtag3").get()).isEqualTo(-1 * (double) paramVals[7],
				DELTA);

		assertThat(((KeyValue) paramMap.get("tag8")).get()).isSameAs(key);

		return null;
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());

	gqlDatastoreQuery.execute(paramVals);

	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), eq(Trade.class));
}
 
Example 17
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQueryTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void pageableTestPage() {

	String gql = "SELECT * FROM trades WHERE [email protected]";
	String expected = "SELECT * FROM trades WHERE [email protected] LIMIT @limit OFFSET @offset";

	Object[] paramVals = new Object[] {1, PageRequest.of(0, 2)};

	String[] paramNames = new String[] { "price", null };

	Parameters parameters = buildParameters(paramVals, paramNames);

	Mockito.<Class>when(this.queryMethod.getReturnedObjectType())
			.thenReturn(Trade.class);
	when(parameters.hasPageableParameter()).thenReturn(true);
	when(parameters.getPageableIndex()).thenReturn(1);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, true, true);

	Cursor cursor = Cursor.copyFrom("abc".getBytes());

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString().equals(gql) || statement.getQueryString().equals(expected))
				.isEqualTo(true);
		Map<String, Value> paramMap = statement.getNamedBindings();

		if (statement.getQueryString().equals(expected)) {
			assertThat(paramMap.size()).isEqualTo(3);
			assertThat(paramMap.get("price").get()).isEqualTo(1L);
			assertThat(paramMap.get("limit").get()).isEqualTo(2L);
			assertThat(paramMap.get("offset").get()).isEqualTo(0L);
			return new DatastoreResultsIterable(Collections.emptyList(), cursor);
		}
		else if (statement.getQueryString().equals(gql)) {
			assertThat(paramMap.size()).isEqualTo(1);
			assertThat(paramMap.get("price").get()).isEqualTo(1L);
			return new DatastoreResultsIterable(Arrays.asList(1L, 2L), cursor);
		}
		return null;
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());
	doAnswer((invocation) -> invocation.getArgument(0)).when(gqlDatastoreQuery)
			.processRawObjectForProjection(any());

	Slice result = (Page) gqlDatastoreQuery.execute(paramVals);

	assertThat(((DatastorePageable) result.getPageable()).toCursor()).isEqualTo(cursor);
	assertThat(((DatastorePageable) result.getPageable()).getTotalCount()).isEqualTo(2L);

	assertThat(((Page) result).getTotalElements()).isEqualTo(2L);

	verify(this.datastoreTemplate, times(2))
			.queryKeysOrEntities(any(), eq(Trade.class));
}
 
Example 18
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQueryTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void pageableTestPageCursor() {
	String gql = "SELECT * FROM trades WHERE [email protected]";
	String expected = "SELECT * FROM trades WHERE [email protected] LIMIT @limit OFFSET @offset";

	Cursor cursorInPageable = Cursor.copyFrom("cde".getBytes());
	long countInPageable = 123L;
	Object[] paramVals = new Object[] { 1,
			new DatastorePageable(PageRequest.of(0, 2), cursorInPageable, countInPageable) };

	String[] paramNames = new String[] { "price", null };

	Parameters parameters = buildParameters(paramVals, paramNames);

	Mockito.<Class>when(this.queryMethod.getReturnedObjectType())
			.thenReturn(Trade.class);
	when(parameters.hasPageableParameter()).thenReturn(true);
	when(parameters.getPageableIndex()).thenReturn(1);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, true, true);

	Cursor cursor = Cursor.copyFrom("abc".getBytes());

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString()).isEqualTo(expected);
		Map<String, Object> paramMap = statement.getNamedBindings();

			assertThat(paramMap.size()).isEqualTo(3);
			assertThat(((Value) paramMap.get("price")).get()).isEqualTo(1L);
			assertThat(((Value) paramMap.get("limit")).get()).isEqualTo(2L);
			assertThat(paramMap.get("offset")).isEqualTo(cursorInPageable);
			return new DatastoreResultsIterable(Collections.emptyList(), cursor);
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());
	doAnswer((invocation) -> invocation.getArgument(0)).when(gqlDatastoreQuery)
			.processRawObjectForProjection(any());

	Slice result = (Page) gqlDatastoreQuery.execute(paramVals);

	assertThat(((DatastorePageable) result.getPageable()).toCursor()).isEqualTo(cursor);
	assertThat(((DatastorePageable) result.getPageable()).getTotalCount()).isEqualTo(countInPageable);

	assertThat(((Page) result).getTotalElements()).isEqualTo(countInPageable);

	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), eq(Trade.class));
}
 
Example 19
Source Project: spring-cloud-gcp   Source File: DatastoreTemplateTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void queryKeysTest() {
	KeyQuery keyQuery = GqlQuery.newKeyQueryBuilder().build();
	this.datastoreTemplate.queryKeys(keyQuery).iterator();
	verify(this.datastore, times(1)).run(keyQuery);
}
 
Example 20
Source Project: catatumbo   Source File: QueryUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Adds the given binding to the given query builder's to the list of positional bindings.
 * 
 * @param queryBuilder
 *          the query builder
 * @param binding
 *          the positional binding to add
 */
static void addPositionalBinding(GqlQuery.Builder<?> queryBuilder, Object binding) {
  if (binding == null) {
    throw new IllegalArgumentException("binding cannot be null. Use IS NULL in your query");
  }
  if (binding instanceof Short) {
    queryBuilder.addBinding((short) binding);
  } else if (binding instanceof Integer) {
    queryBuilder.addBinding((int) binding);
  } else if (binding instanceof Long) {
    queryBuilder.addBinding((long) binding);
  } else if (binding instanceof Float) {
    queryBuilder.addBinding((float) binding);
  } else if (binding instanceof Double) {
    queryBuilder.addBinding((double) binding);
  } else if (binding instanceof Boolean) {
    queryBuilder.addBinding((boolean) binding);
  } else if (binding instanceof Character) {
    queryBuilder.addBinding(String.valueOf((char) binding));
  } else if (binding instanceof String) {
    queryBuilder.addBinding((String) binding);
  } else if (binding instanceof Calendar) {
    queryBuilder.addBinding(toTimestamp((Calendar) binding));
  } else if (binding instanceof Date) {
    queryBuilder.addBinding(toTimestamp((Date) binding));
  } else if (binding instanceof LocalDate) {
    queryBuilder.addBinding(((LocalDate) binding).toString());
  } else if (binding instanceof LocalTime) {
    queryBuilder.addBinding(((LocalTime) binding).format(LocalTimeMapper.FORMATTER));
  } else if (binding instanceof LocalDateTime) {
    queryBuilder.addBinding(((LocalDateTime) binding).format(LocalDateTimeMapper.FORMATTER));
  } else if (binding instanceof OffsetDateTime) {
    queryBuilder.addBinding(toTimestamp((OffsetDateTime) binding));
  } else if (binding instanceof ZonedDateTime) {
    queryBuilder.addBinding(toTimestamp((ZonedDateTime) binding));
  } else if (binding instanceof byte[]) {
    queryBuilder.addBinding(Blob.copyFrom((byte[]) binding));
  } else if (binding instanceof DatastoreKey) {
    queryBuilder.addBinding(((DatastoreKey) binding).nativeKey());
  } else if (binding instanceof DatastoreCursor) {
    queryBuilder.addBinding(Cursor.fromUrlSafe(((DatastoreCursor) binding).getEncoded()));
  } else if (binding instanceof GeoLocation) {
    // TODO no support for GeoLocation in the gcloud API
  }
}
 
Example 21
Source Project: catatumbo   Source File: QueryUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Applies the given positional bindings to the given query builder.
 * 
 * @param queryBuilder
 *          the query builder
 * @param namedBindings
 *          the named bindings to apply
 */
static void applyNamedBindings(GqlQuery.Builder<?> queryBuilder,
    Map<String, Object> namedBindings) {
  if (namedBindings != null) {
    for (Map.Entry<String, Object> entry : namedBindings.entrySet()) {
      String bindingName = entry.getKey();
      Object bindingValue = entry.getValue();
      if (bindingValue instanceof Short) {
        queryBuilder.setBinding(bindingName, (short) bindingValue);
      } else if (bindingValue instanceof Integer) {
        queryBuilder.setBinding(bindingName, (int) bindingValue);
      } else if (bindingValue instanceof Long) {
        queryBuilder.setBinding(bindingName, (long) bindingValue);
      } else if (bindingValue instanceof Float) {
        queryBuilder.setBinding(bindingName, (float) bindingValue);
      } else if (bindingValue instanceof Double) {
        queryBuilder.setBinding(bindingName, (double) bindingValue);
      } else if (bindingValue instanceof Boolean) {
        queryBuilder.setBinding(bindingName, (boolean) bindingValue);
      } else if (bindingValue instanceof String) {
        queryBuilder.setBinding(bindingName, (String) bindingValue);
      } else if (bindingValue instanceof Calendar) {
        queryBuilder.setBinding(bindingName, toTimestamp((Calendar) bindingValue));
      } else if (bindingValue instanceof Date) {
        queryBuilder.setBinding(bindingName, toTimestamp((Date) bindingValue));
      } else if (bindingValue instanceof LocalDate) {
        queryBuilder.setBinding(bindingName, ((LocalDate) bindingValue).toString());
      } else if (bindingValue instanceof LocalTime) {
        queryBuilder.setBinding(bindingName,
            ((LocalTime) bindingValue).format(LocalTimeMapper.FORMATTER));
      } else if (bindingValue instanceof LocalDateTime) {
        queryBuilder.setBinding(bindingName,
            ((LocalDateTime) bindingValue).format(LocalDateTimeMapper.FORMATTER));
      } else if (bindingValue instanceof OffsetDateTime) {
        queryBuilder.setBinding(bindingName, toTimestamp((OffsetDateTime) bindingValue));
      } else if (bindingValue instanceof ZonedDateTime) {
        queryBuilder.setBinding(bindingName, toTimestamp((ZonedDateTime) bindingValue));
      } else if (bindingValue instanceof byte[]) {
        queryBuilder.setBinding(bindingName, Blob.copyFrom((byte[]) bindingValue));
      } else if (bindingValue instanceof DatastoreKey) {
        queryBuilder.setBinding(bindingName, ((DatastoreKey) bindingValue).nativeKey());
      } else if (bindingValue instanceof DatastoreCursor) {
        queryBuilder.setBinding(bindingName,
            Cursor.fromUrlSafe(((DatastoreCursor) bindingValue).getEncoded()));
      } else if (bindingValue instanceof GeoLocation) {
        // TODO no support for GeoLocation in the gcloud API
      }
    }
  }
}
 
Example 22
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQueryTests.java    License: Apache License 2.0 3 votes vote down vote up
@Test
public void pageableTest() {

	String gql = "SELECT * FROM trades WHERE [email protected]";

	Object[] paramVals = new Object[] {1, PageRequest.of(0, 2)};

	String[] paramNames = new String[] { "price", null };

	Parameters parameters = buildParameters(paramVals, paramNames);

	when(parameters.hasPageableParameter()).thenReturn(true);
	when(parameters.getPageableIndex()).thenReturn(1);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, false);

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString()).isEqualTo("SELECT * FROM trades WHERE [email protected] LIMIT @limit OFFSET @offset");

		Map<String, Value> paramMap = statement.getNamedBindings();

		assertThat(paramMap.get("price").get()).isEqualTo(1L);
		assertThat(paramMap.get("limit").get()).isEqualTo(2L);
		assertThat(paramMap.get("offset").get()).isEqualTo(0L);

		return null;
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());

	gqlDatastoreQuery.execute(paramVals);

	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), eq(Trade.class));
}
 
Example 23
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQueryTests.java    License: Apache License 2.0 3 votes vote down vote up
@Test
public void pageableTestSort() {

	String gql = "SELECT * FROM trades WHERE [email protected]";

	Object[] paramVals = new Object[] {1, Sort.by(Sort.Order.asc("p1"), Sort.Order.desc("p2"))};

	String[] paramNames = new String[] { "price", null };

	Parameters parameters = buildParameters(paramVals, paramNames);

	when(parameters.hasSortParameter()).thenReturn(true);
	when(parameters.getSortIndex()).thenReturn(1);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, false);

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString())
				.isEqualTo("SELECT * FROM trades WHERE [email protected] ORDER BY p1 ASC, p2 DESC");

		Map<String, Value> paramMap = statement.getNamedBindings();

		assertThat(paramMap.get("price").get()).isEqualTo(1L);

		return null;
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());

	gqlDatastoreQuery.execute(paramVals);

	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), eq(Trade.class));
}
 
Example 24
Source Project: spring-cloud-gcp   Source File: GqlDatastoreQueryTests.java    License: Apache License 2.0 2 votes vote down vote up
@Test
public void pageableTestSlice() {

	String gql = "SELECT * FROM trades WHERE [email protected]";

	Object[] paramVals = new Object[] {1, PageRequest.of(0, 2)};

	String[] paramNames = new String[] { "price", null };

	Parameters parameters = buildParameters(paramVals, paramNames);

	Mockito.<Class>when(this.queryMethod.getReturnedObjectType())
			.thenReturn(Trade.class);
	when(parameters.hasPageableParameter()).thenReturn(true);
	when(parameters.getPageableIndex()).thenReturn(1);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, true);

	Cursor cursor = Cursor.copyFrom("abc".getBytes());
	List<Map> params = new ArrayList<>();
	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString()).isEqualTo("SELECT * FROM trades WHERE [email protected] LIMIT @limit OFFSET @offset");

		Map paramMap = statement.getNamedBindings();

		params.add(paramMap);


		return new DatastoreResultsIterable(Collections.emptyList(), cursor);
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());
	doAnswer((invocation) -> invocation.getArgument(0)).when(gqlDatastoreQuery)
			.processRawObjectForProjection(any());

	Slice result = (Slice) gqlDatastoreQuery.execute(paramVals);

	assertThat(((DatastorePageable) result.getPageable()).toCursor()).isEqualTo(cursor);

	verify(this.datastoreTemplate, times(2))
			.queryKeysOrEntities(any(), eq(Trade.class));

	assertThat(((Value) params.get(0).get("price")).get()).isEqualTo(1L);
	assertThat(((Value) params.get(0).get("limit")).get()).isEqualTo(2L);
	assertThat(((Value) params.get(0).get("offset")).get()).isEqualTo(0L);

	assertThat(((Value) params.get(1).get("price")).get()).isEqualTo(1L);
	assertThat(((Value) params.get(1).get("limit")).get()).isEqualTo(1L);
	assertThat(params.get(1).get("offset")).isEqualTo(cursor);

}