Search in sources :

Example 11 with Value

use of com.google.cloud.spanner.Value in project spring-cloud-gcp by spring-cloud.

the class ConverterAwareMappingSpannerEntityWriterTests method testCommitTimestampsType.

@Test
public void testCommitTimestampsType() {
    CommitTimestamps entity = new CommitTimestamps();
    doWithFields(CommitTimestamps.class, f -> setField(f, entity, CommitTimestamp.of(f.getType())), ff -> !ff.isSynthetic() && Objects.isNull(ff.getAnnotation(PrimaryKey.class)));
    WriteBuilder writeBuilder = Mutation.newInsertBuilder("commit_timestamps_table");
    this.spannerEntityWriter.write(entity, writeBuilder::set);
    Mutation mutation = writeBuilder.build();
    assertThat(mutation.asMap().entrySet().stream().filter(e -> !"id".equals(e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList())).allMatch(Value::isCommitTimestamp);
}
Also used : CommitTimestamps(org.springframework.cloud.gcp.data.spanner.test.domain.CommitTimestamps) WriteBuilder(com.google.cloud.spanner.Mutation.WriteBuilder) Value(com.google.cloud.spanner.Value) PrimaryKey(org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey) Mutation(com.google.cloud.spanner.Mutation) Map(java.util.Map) Test(org.junit.Test)

Example 12 with Value

use of com.google.cloud.spanner.Value in project spring-cloud-gcp by spring-cloud.

the class SqlSpannerQueryTests method sortAndPageableQueryTest.

@Test
public void sortAndPageableQueryTest() throws NoSuchMethodException {
    String sql = "SELECT * FROM :org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Child:" + " WHERE id = @id AND trader_id = @trader_id";
    // @formatter:off
    String entityResolvedSql = "SELECT *, " + "ARRAY (SELECT AS STRUCT canceled, documentId, id, childId, content " + "FROM documents WHERE (documents.id = children.id AND documents.childId = children.childId) " + "AND (canceled = false)) AS documents " + "FROM (SELECT * FROM children WHERE id = @id AND trader_id = @trader_id) children " + "WHERE disabled = false ORDER BY trader_id ASC LIMIT 2 OFFSET 2";
    // @formatter:on
    Object[] params = new Object[] { "ID", "TRADER_ID", Sort.by(Order.asc("trader_id")), PageRequest.of(1, 2) };
    String[] paramNames = new String[] { "id", "trader_id", "ignoredSort", "pageable" };
    when(queryMethod.isCollectionQuery()).thenReturn(false);
    when(queryMethod.getReturnedObjectType()).thenReturn((Class) Child.class);
    EvaluationContext evaluationContext = new StandardEvaluationContext();
    for (int i = 0; i < params.length; i++) {
        evaluationContext.setVariable(paramNames[i], params[i]);
    }
    when(this.evaluationContextProvider.getEvaluationContext(any(), any())).thenReturn(evaluationContext);
    SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Child.class, false);
    doAnswer((invocation) -> {
        Statement statement = invocation.getArgument(0);
        SpannerQueryOptions queryOptions = invocation.getArgument(1);
        assertThat(queryOptions.isAllowPartialRead()).isTrue();
        assertThat(statement.getSql()).isEqualTo(entityResolvedSql);
        Map<String, Value> paramMap = statement.getParameters();
        assertThat(paramMap.get("id").getString()).isEqualTo(params[0]);
        assertThat(paramMap.get("trader_id").getString()).isEqualTo(params[1]);
        assertThat(paramMap.get("ignoredSort")).isNull();
        assertThat(paramMap.get("pageable")).isNull();
        return null;
    }).when(this.spannerTemplate).executeQuery(any(), any());
    Method method = QueryHolder.class.getMethod("sortAndPageable", String.class, String.class, Sort.class, Pageable.class);
    when(this.queryMethod.getMethod()).thenReturn(method);
    Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(new DefaultParameters(method));
    sqlSpannerQuery.execute(params);
    verify(this.spannerTemplate, times(1)).executeQuery(any(), any());
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Statement(com.google.cloud.spanner.Statement) Method(java.lang.reflect.Method) SpannerQueryOptions(org.springframework.cloud.gcp.data.spanner.core.SpannerQueryOptions) DefaultParameters(org.springframework.data.repository.query.DefaultParameters) Value(com.google.cloud.spanner.Value) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Test(org.junit.Test)

Example 13 with Value

use of com.google.cloud.spanner.Value in project spring-cloud-gcp by spring-cloud.

the class SqlSpannerQueryTests method sqlCountWithWhereTest.

@Test
public void sqlCountWithWhereTest() throws NoSuchMethodException {
    String sql = "SELECT count(1) FROM :org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Child:" + " WHERE id = @id AND trader_id = @trader_id";
    String entityResolvedSql = "SELECT count(1) FROM children WHERE id = @id AND trader_id = @trader_id";
    Object[] params = new Object[] { "ID", "TRADER_ID" };
    String[] paramNames = new String[] { "id", "trader_id" };
    when(queryMethod.isCollectionQuery()).thenReturn(false);
    when(queryMethod.getReturnedObjectType()).thenReturn((Class) long.class);
    EvaluationContext evaluationContext = new StandardEvaluationContext();
    for (int i = 0; i < params.length; i++) {
        evaluationContext.setVariable(paramNames[i], params[i]);
    }
    when(this.evaluationContextProvider.getEvaluationContext(any(), any())).thenReturn(evaluationContext);
    SqlSpannerQuery sqlSpannerQuery = createQuery(sql, long.class, false);
    doAnswer((invocation) -> {
        Statement statement = invocation.getArgument(0);
        SpannerQueryOptions queryOptions = invocation.getArgument(1);
        assertThat(queryOptions.isAllowPartialRead()).isTrue();
        assertThat(statement.getSql()).isEqualTo(entityResolvedSql);
        Map<String, Value> paramMap = statement.getParameters();
        assertThat(paramMap.get("id").getString()).isEqualTo(params[0]);
        assertThat(paramMap.get("trader_id").getString()).isEqualTo(params[1]);
        return null;
    }).when(this.spannerTemplate).executeQuery(any(), any());
    // This dummy method was created so the metadata for the ARRAY param inner type is
    // provided.
    Method method = QueryHolder.class.getMethod("dummyMethod3", String.class, String.class);
    when(this.queryMethod.getMethod()).thenReturn(method);
    Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(new DefaultParameters(method));
    sqlSpannerQuery.execute(params);
    verify(this.spannerTemplate, times(1)).executeQuery(any(), any());
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Statement(com.google.cloud.spanner.Statement) Method(java.lang.reflect.Method) SpannerQueryOptions(org.springframework.cloud.gcp.data.spanner.core.SpannerQueryOptions) DefaultParameters(org.springframework.data.repository.query.DefaultParameters) Value(com.google.cloud.spanner.Value) EvaluationContext(org.springframework.expression.EvaluationContext) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Test(org.junit.Test)

Example 14 with Value

use of com.google.cloud.spanner.Value in project spring-cloud-gcp by spring-cloud.

the class SpannerWriteMethodCoverageTests method allKnownMappingTypesTest.

// Checks that the converter is aware of all Cloud Spanner mutation binder types
@Test
public void allKnownMappingTypesTest() throws NoSuchFieldException {
    for (Method method : ValueBinder.class.getMethods()) {
        String methodName = method.getName();
        // ignoring non-public and non "to" named binder methods
        if (!Modifier.isPublic(method.getModifiers()) || !methodName.startsWith("to") || method.getParameterCount() != 1) {
            continue;
        }
        Class<?> paramType = ConversionUtils.boxIfNeeded(method.getParameterTypes()[0]);
        if (paramType.equals(Struct.class) || paramType.equals(Value.class)) {
            /*
				 * 1. there is a method for binding a Struct value, but because Struct
				 * values cannot be written to table columns we will ignore it. 2. there
				 * is a method for binding a Value value. However, the purpose of the
				 * converters is to wrap java types into the Value for the user.
				 * Furthermore, the Cloud Spanner client lib does not give a way to read a
				 * Value back from a Struct, so we will ignore this method.
				 */
            continue;
        } else if (ConversionUtils.isIterableNonByteArrayType(paramType)) {
            Class<?> innerParamType = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0];
            assertThat(ConverterAwareMappingSpannerEntityWriter.iterablePropertyTypeToMethodMap.keySet()).contains(innerParamType);
        } else {
            assertThat(ConverterAwareMappingSpannerEntityWriter.singleItemTypeValueBinderMethodMap.keySet()).contains(paramType);
        }
    }
}
Also used : Value(com.google.cloud.spanner.Value) Method(java.lang.reflect.Method) Struct(com.google.cloud.spanner.Struct) Test(org.junit.Test)

Aggregations

Value (com.google.cloud.spanner.Value)14 Test (org.junit.Test)9 Statement (com.google.cloud.spanner.Statement)8 Method (java.lang.reflect.Method)8 DefaultParameters (org.springframework.data.repository.query.DefaultParameters)8 SpannerQueryOptions (org.springframework.cloud.gcp.data.spanner.core.SpannerQueryOptions)5 EvaluationContext (org.springframework.expression.EvaluationContext)5 StandardEvaluationContext (org.springframework.expression.spel.support.StandardEvaluationContext)5 Struct (com.google.cloud.spanner.Struct)3 Mutation (com.google.cloud.spanner.Mutation)1 WriteBuilder (com.google.cloud.spanner.Mutation.WriteBuilder)1 Type (com.google.cloud.spanner.Type)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ColumnType (org.apache.beam.sdk.io.gcp.spanner.changestreams.model.ColumnType)1 PrimaryKey (org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey)1 CommitTimestamps (org.springframework.cloud.gcp.data.spanner.test.domain.CommitTimestamps)1