Search in sources :

Example 1 with KeyValue

use of com.google.cloud.datastore.KeyValue in project spring-cloud-gcp by spring-cloud.

the class GqlDatastoreQueryTests method compoundNameConventionTest.

@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 " + "( action=@tag0 AND ticker=@tag1 ) OR " + "( trader_id=@tag2 AND price<@tag3 ) OR ( price>=@tag4 AND id<>NULL AND " + "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND " + "price>@tag6 AND price<=@tag7 AND trade_ref = @tag8) ORDER BY id DESC LIMIT 3;";
    String entityResolvedGql = "SELECT * FROM trades" + " WHERE price=@SpELtag1 AND price<>@SpELtag2 OR price<>@SpELtag3 AND " + "( action=@tag0 AND ticker=@tag1 ) OR " + "( trader_id=@tag2 AND price<@tag3 ) OR ( price>=@tag4 AND id<>NULL AND " + "trader_id=NULL AND trader_id LIKE %@tag5 AND price=TRUE AND price=FALSE AND " + "price>@tag6 AND price<=@tag7 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 }, // this parameter is a simple int, which is not a directly supported type and uses
    3, // 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));
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) KeyValue(com.google.cloud.datastore.KeyValue) GqlQuery(com.google.cloud.datastore.GqlQuery) DoubleValue(com.google.cloud.datastore.DoubleValue) LongValue(com.google.cloud.datastore.LongValue) DoubleValue(com.google.cloud.datastore.DoubleValue) KeyValue(com.google.cloud.datastore.KeyValue) Value(com.google.cloud.datastore.Value) ArrayList(java.util.ArrayList) List(java.util.List) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) KeyFactory(com.google.cloud.datastore.KeyFactory) Key(com.google.cloud.datastore.Key) Test(org.junit.Test)

Example 2 with KeyValue

use of com.google.cloud.datastore.KeyValue in project spring-cloud-gcp by spring-cloud.

the class DatastoreTemplate method getReferenceEntitiesForSave.

private List<Entity> getReferenceEntitiesForSave(Object entity, Builder builder, Set<Key> persistedEntities) {
    DatastorePersistentEntity datastorePersistentEntity = this.datastoreMappingContext.getPersistentEntity(entity.getClass());
    List<Entity> entitiesToSave = new ArrayList<>();
    datastorePersistentEntity.doWithAssociations((AssociationHandler) (association) -> {
        PersistentProperty persistentProperty = association.getInverse();
        PersistentPropertyAccessor accessor = datastorePersistentEntity.getPropertyAccessor(entity);
        Object val = accessor.getProperty(persistentProperty);
        if (val == null) {
            return;
        }
        Value<?> value;
        if (LazyUtil.isLazyAndNotLoaded(val)) {
            value = LazyUtil.getKeys(val);
        } else if (persistentProperty.isCollectionLike()) {
            Iterable<?> iterableVal = (Iterable<?>) ValueUtil.toListIfArray(val);
            entitiesToSave.addAll(getEntitiesForSave(iterableVal, persistedEntities));
            List<KeyValue> keyValues = StreamSupport.stream((iterableVal).spliterator(), false).map((o) -> KeyValue.of(this.getKey(o, false))).collect(Collectors.toList());
            value = ListValue.of(keyValues);
        } else {
            entitiesToSave.addAll(getEntitiesForSave(Collections.singletonList(val), persistedEntities));
            Key key = getKey(val, false);
            value = KeyValue.of(key);
        }
        builder.set(((DatastorePersistentProperty) persistentProperty).getFieldName(), value);
    });
    return entitiesToSave;
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) Query(com.google.cloud.datastore.Query) Builder(com.google.cloud.datastore.Entity.Builder) PathElement(com.google.cloud.datastore.PathElement) SliceUtil(org.springframework.cloud.gcp.data.datastore.core.util.SliceUtil) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) Filter(com.google.cloud.datastore.StructuredQuery.Filter) AfterQueryEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterQueryEvent) KeyQuery(com.google.cloud.datastore.KeyQuery) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) QueryResults(com.google.cloud.datastore.QueryResults) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) PersistentProperty(org.springframework.data.mapping.PersistentProperty) AfterFindByKeyEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterFindByKeyEvent) BaseEntity(com.google.cloud.datastore.BaseEntity) DatastoreDataException(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException) Collection(java.util.Collection) KeyValue(com.google.cloud.datastore.KeyValue) AfterSaveEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterSaveEvent) Set(java.util.Set) DatastorePersistentEntity(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentEntity) Example(org.springframework.data.domain.Example) Collectors(java.util.stream.Collectors) IncompleteKey(com.google.cloud.datastore.IncompleteKey) Slice(org.springframework.data.domain.Slice) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) KeyUtil(org.springframework.cloud.gcp.data.datastore.core.util.KeyUtil) ListValue(com.google.cloud.datastore.ListValue) DatastoreMappingContext(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext) BeforeDeleteEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.BeforeDeleteEvent) Key(com.google.cloud.datastore.Key) BeforeSaveEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.BeforeSaveEvent) DatastoreEntityConverter(org.springframework.cloud.gcp.data.datastore.core.convert.DatastoreEntityConverter) SliceImpl(org.springframework.data.domain.SliceImpl) HashMap(java.util.HashMap) Datastore(com.google.cloud.datastore.Datastore) ProjectionEntityQuery(com.google.cloud.datastore.ProjectionEntityQuery) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Cursor(com.google.cloud.datastore.Cursor) HashSet(java.util.HashSet) NullHandler(org.springframework.data.domain.ExampleMatcher.NullHandler) ValueUtil(org.springframework.cloud.gcp.data.datastore.core.util.ValueUtil) Entity(com.google.cloud.datastore.Entity) PropertyFilter(com.google.cloud.datastore.StructuredQuery.PropertyFilter) NullValue(com.google.cloud.datastore.NullValue) StreamSupport(java.util.stream.StreamSupport) Nullable(org.springframework.lang.Nullable) LinkedList(java.util.LinkedList) StructuredQuery(com.google.cloud.datastore.StructuredQuery) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Iterator(java.util.Iterator) TypeUtils(org.springframework.util.TypeUtils) ObjectToKeyFactory(org.springframework.cloud.gcp.data.datastore.core.convert.ObjectToKeyFactory) ExampleMatcher(org.springframework.data.domain.ExampleMatcher) DatastoreReaderWriter(com.google.cloud.datastore.DatastoreReaderWriter) EntityQuery(com.google.cloud.datastore.EntityQuery) AfterDeleteEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterDeleteEvent) ApplicationEvent(org.springframework.context.ApplicationEvent) AssociationHandler(org.springframework.data.mapping.AssociationHandler) BaseKey(com.google.cloud.datastore.BaseKey) Value(com.google.cloud.datastore.Value) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty) Collections(java.util.Collections) DatastorePageable(org.springframework.cloud.gcp.data.datastore.repository.query.DatastorePageable) Assert(org.springframework.util.Assert) FullEntity(com.google.cloud.datastore.FullEntity) BaseEntity(com.google.cloud.datastore.BaseEntity) DatastorePersistentEntity(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentEntity) Entity(com.google.cloud.datastore.Entity) KeyValue(com.google.cloud.datastore.KeyValue) DatastorePersistentEntity(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentEntity) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) ArrayList(java.util.ArrayList) PersistentProperty(org.springframework.data.mapping.PersistentProperty) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty) KeyValue(com.google.cloud.datastore.KeyValue) ListValue(com.google.cloud.datastore.ListValue) NullValue(com.google.cloud.datastore.NullValue) Value(com.google.cloud.datastore.Value) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty) IncompleteKey(com.google.cloud.datastore.IncompleteKey) Key(com.google.cloud.datastore.Key) BaseKey(com.google.cloud.datastore.BaseKey)

Aggregations

Key (com.google.cloud.datastore.Key)2 KeyValue (com.google.cloud.datastore.KeyValue)2 Value (com.google.cloud.datastore.Value)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 BaseEntity (com.google.cloud.datastore.BaseEntity)1 BaseKey (com.google.cloud.datastore.BaseKey)1 Cursor (com.google.cloud.datastore.Cursor)1 Datastore (com.google.cloud.datastore.Datastore)1 DatastoreReaderWriter (com.google.cloud.datastore.DatastoreReaderWriter)1 DoubleValue (com.google.cloud.datastore.DoubleValue)1 Entity (com.google.cloud.datastore.Entity)1 Builder (com.google.cloud.datastore.Entity.Builder)1 EntityQuery (com.google.cloud.datastore.EntityQuery)1 FullEntity (com.google.cloud.datastore.FullEntity)1 GqlQuery (com.google.cloud.datastore.GqlQuery)1 IncompleteKey (com.google.cloud.datastore.IncompleteKey)1 KeyFactory (com.google.cloud.datastore.KeyFactory)1 KeyQuery (com.google.cloud.datastore.KeyQuery)1 ListValue (com.google.cloud.datastore.ListValue)1