org.springframework.data.repository.query.DefaultParameters Java Examples

The following examples show how to use org.springframework.data.repository.query.DefaultParameters. 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 File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void unspecifiedParametersTest() throws NoSuchMethodException {
	this.expectedEx.expect(IllegalArgumentException.class);
	this.expectedEx.expectMessage("The number of tags does not match the number of params.");
	when(this.queryMethod.getName()).thenReturn(
			"findTop3DistinctIdActionPriceByActionAndSymbolOrTraderIdAndPriceLessThanOrPriceGreater"
					+ "ThanEqualAndIdIsNotNullAndTraderIdIsNullOrderByIdDesc");
	this.partTreeSpannerQuery = createQuery();
	Method method = QueryHolder.class.getMethod("repositoryMethod4", Object.class, Object.class, Object.class);
	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	// There are too few params specified, so the exception will occur.
	Object[] params = new Object[] { "BUY", "abcd", "abc123", };

	this.partTreeSpannerQuery.execute(params);
}
 
Example #2
Source File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void unsupportedParamTypeTest() throws NoSuchMethodException {
	this.expectedEx.expect(IllegalArgumentException.class);
	this.expectedEx.expectMessage("is not a supported type: class org.springframework." +
			"cloud.gcp.data.spanner.repository.query.SpannerStatementQueryTests$Trade");
	when(this.queryMethod.getName()).thenReturn(
			"findTop3DistinctIdActionPriceByActionAndSymbolOrTraderIdAndPriceLessThanOrPriceGreater"
					+ "ThanEqualAndIdIsNotNullAndTraderIdIsNullOrderByIdDesc");
	this.partTreeSpannerQuery = createQuery();
	Method method = QueryHolder.class.getMethod("repositoryMethod2", Object.class, Object.class, Object.class,
			Object.class, Object.class, Trade.class, Object.class);

	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	// This parameter is an unsupported type for Spanner SQL.
	Object[] params = new Object[] { "BUY", "abcd", "abc123", 8.88, 3.33, new Trade(), "ignored", };

	this.partTreeSpannerQuery.execute(params);
}
 
Example #3
Source File: PartTreeDatastoreQueryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private void queryWithMockResult(String queryName, List results, Method m, boolean mockOptionalNullable,
		ProjectionInformation projectionInformation) {
	when(this.queryMethod.getName()).thenReturn(queryName);
	doReturn(new DefaultParameters(m))
			.when(this.queryMethod).getParameters();
	if (mockOptionalNullable) {
		DefaultRepositoryMetadata mockMetadata = mock(DefaultRepositoryMetadata.class);
		doReturn(m.getReturnType()).when(mockMetadata).getReturnedDomainClass(m);
		DatastoreQueryMethod datastoreQueryMethod =
				new DatastoreQueryMethod(m,
						mockMetadata,
						mock(SpelAwareProxyProjectionFactory.class));
		doReturn(datastoreQueryMethod.isOptionalReturnType())
				.when(this.queryMethod).isOptionalReturnType();
		doReturn(datastoreQueryMethod.isNullable())
				.when(this.queryMethod).isNullable();
	}

	this.partTreeDatastoreQuery = createQuery(false, false, projectionInformation);
	when(this.datastoreTemplate.queryKeysOrEntities(any(), Mockito.<Class<Trade>>any()))
			.thenReturn(new DatastoreResultsIterable<>(
					results != null ? results.iterator() : Collections.emptyIterator(), null));
}
 
Example #4
Source File: VaultQueryCreatorUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
VaultQuery createQuery(String methodName, String value, String anotherValue) {

		DefaultParameters defaultParameters = new DefaultParameters(
				ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", String.class, String.class));

		PartTree partTree = new PartTree(methodName, Credentials.class);
		VaultQueryCreator queryCreator = new VaultQueryCreator(partTree,
				new ParametersParameterAccessor(defaultParameters, new Object[] { value, anotherValue }),
				this.mappingContext);

		return queryCreator.createQuery().getCriteria();
	}
 
Example #5
Source File: VaultQueryCreatorUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
VaultQuery createQuery(String methodName, List<String> value) {

		DefaultParameters defaultParameters = new DefaultParameters(
				ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", List.class));

		PartTree partTree = new PartTree(methodName, Credentials.class);
		VaultQueryCreator queryCreator = new VaultQueryCreator(partTree,
				new ParametersParameterAccessor(defaultParameters, new Object[] { value }), this.mappingContext);

		return queryCreator.createQuery().getCriteria();
	}
 
Example #6
Source File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void runPageableOrSortTest(Object[] params, Method method, String expectedSql) {
	when(this.queryMethod.getName()).thenReturn(
			"findByPriceLessThan");
	this.partTreeSpannerQuery = spy(createQuery());

	when(this.spannerTemplate.query((Function<Struct, Object>) any(), any(), any()))
			.thenReturn(Collections.singletonList(1L));

	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	when(this.spannerTemplate.query((Class) any(), any(), any()))
			.thenAnswer((invocation) -> {
				Statement statement = invocation.getArgument(1);

				assertThat(statement.getSql()).isEqualTo(expectedSql);

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

				assertThat(paramMap.get("tag0").getFloat64()).isEqualTo(params[0]);
				assertThat(paramMap).hasSize(1);

				return null;
			});

	doReturn(Object.class).when(this.partTreeSpannerQuery)
			.getReturnedSimpleConvertableItemType();
	doReturn(null).when(this.partTreeSpannerQuery).convertToSimpleReturnType(any(),
			any());

	this.partTreeSpannerQuery.execute(params);
	verify(this.spannerTemplate, times(1)).query((Class) any(),
			any(), any());
}
 
Example #7
Source File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void unSupportedPredicateTest() throws NoSuchMethodException {
	this.expectedEx.expect(UnsupportedOperationException.class);
	this.expectedEx.expectMessage("The statement type: BETWEEN (2): [IsBetween, " +
			"Between] is not supported.");
	when(this.queryMethod.getName()).thenReturn("countByTraderIdBetween");
	Method method = Object.class.getMethod("toString");
	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	this.partTreeSpannerQuery = createQuery();
	this.partTreeSpannerQuery.execute(EMPTY_PARAMETERS);
}
 
Example #8
Source File: VaultQueryCreatorUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
VaultQuery createQuery(String methodName, String value) {

		DefaultParameters defaultParameters = new DefaultParameters(
				ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", String.class));

		PartTree partTree = new PartTree(methodName, Credentials.class);
		VaultQueryCreator queryCreator = new VaultQueryCreator(partTree,
				new ParametersParameterAccessor(defaultParameters, new Object[] { value }), this.mappingContext);

		return queryCreator.createQuery().getCriteria();
	}
 
Example #9
Source File: PartTreeEbeanQuery.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link PartTreeEbeanQuery}.
 *
 * @param method      must not be {@literal null}.
 * @param ebeanServer must not be {@literal null}.
 */
public PartTreeEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer) {
    super(method, ebeanServer);

    this.domainClass = method.getEntityInformation().getJavaType();
    this.tree = new PartTree(method.getName(), domainClass);
    this.parameters = (DefaultParameters) method.getParameters();
    this.queryPreparer = new QueryPreparer(ebeanServer);
}
 
Example #10
Source File: SpelExpressionStringQueryParameterBinder.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SpelExpressionStringQueryParameterBinder}.
 *
 * @param parameters                must not be {@literal null}
 * @param values                    must not be {@literal null}
 * @param query                     must not be {@literal null}
 * @param evaluationContextProvider must not be {@literal null}
 * @param parser                    must not be {@literal null}
 */
public SpelExpressionStringQueryParameterBinder(DefaultParameters parameters, Object[] values, StringQuery query,
                                                QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

    super(parameters, values, query);
    Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");
    Assert.notNull(parser, "SpelExpressionParser must not be null!");

    this.evaluationContextProvider = evaluationContextProvider;
    this.query = query;
    this.parser = parser;
}
 
Example #11
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void dmlTest() throws NoSuchMethodException {
	String sql = "dml statement here";

	TransactionContext context = mock(TransactionContext.class);
	TransactionRunner transactionRunner = mock(TransactionRunner.class);
	when(this.databaseClient.readWriteTransaction()).thenReturn(transactionRunner);

	when(transactionRunner.run(any())).thenAnswer((invocation) -> {
		TransactionRunner.TransactionCallable transactionCallable = invocation.getArgument(0);
		return transactionCallable.run(context);
	});

	Method method = QueryHolder.class.getMethod("noParamMethod");

	Mockito.<Parameters>when(this.queryMethod.getParameters())
			.thenReturn(new DefaultParameters(method));


	SqlSpannerQuery sqlSpannerQuery = spy(createQuery(sql, Trade.class, true));

	doReturn(long.class).when(sqlSpannerQuery)
			.getReturnedSimpleConvertableItemType();
	doReturn(null).when(sqlSpannerQuery).convertToSimpleReturnType(any(),
			any());

	sqlSpannerQuery.execute(new Object[] {});

	verify(this.spannerTemplate, times(1)).executeDmlStatement(any());
}
 
Example #12
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@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());
}
 
Example #13
Source File: AbstractEbeanQuery.java    From spring-data-ebean with Apache License 2.0 4 votes vote down vote up
protected ParameterBinder createBinder(Object[] values) {
    return new ParameterBinder((DefaultParameters) getQueryMethod().getParameters(), values);
}
 
Example #14
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@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());
}
 
Example #15
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void compoundNameConventionTest() throws NoSuchMethodException {

	String sql = "SELECT DISTINCT * FROM "
			+ ":org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Trade:"
			+ "@{index=fakeindex}"
			+ " WHERE price=#{#tag3 * -1} AND price<>#{#tag3 * -1} OR "
			+ "price<>#{#tag4 * -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 "
			+ "struct_val = @tag8 AND struct_val = @tag9 "
			+ "price>@tag6 AND price<=@tag7 and price in unnest(@tag10)) ORDER BY id DESC LIMIT 3;";

	// @formatter:off
	String entityResolvedSql = "SELECT *, " +
			"ARRAY (SELECT AS STRUCT disabled, id, childId, value, " +
				"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 children WHERE (children.id = trades.id) AND (disabled = false)) AS children FROM "
			+ "(SELECT DISTINCT * FROM trades@{index=fakeindex}"
			+ " WHERE price=@SpELtag1 AND price<>@SpELtag1 OR price<>@SpELtag2 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 "
			+ "struct_val = @tag8 AND struct_val = @tag9 "
			+ "price>@tag6 AND price<=@tag7 and price in unnest(@tag10)) ORDER BY id DESC LIMIT 3) trades "
			+ "ORDER BY COLA ASC , COLB DESC LIMIT 10 OFFSET 30";
	// @formatter:on

	Object[] params = new Object[] { "BUY", this.pageable, "abcd", "abc123", 8.88,
			3.33, "blahblah",
			1.11, 2.22, Struct.newBuilder().set("symbol").to("ABCD").set("action")
					.to("BUY").build(),
			new SymbolAction("ABCD", "BUY"), Arrays.asList("a", "b") };

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

	when(queryMethod.isCollectionQuery()).thenReturn(false);
	when(queryMethod.getReturnedObjectType()).thenReturn((Class) Trade.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, Trade.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("tag0").getString()).isEqualTo(params[0]);
		//params[1] is this.pageable that is ignored, hence no synthetic tag is created for it
		assertThat(paramMap.get("tag1").getString()).isEqualTo(params[2]);
		assertThat(paramMap.get("tag2").getString()).isEqualTo(params[3]);
		assertThat(paramMap.get("tag3").getFloat64()).isEqualTo(params[4]);
		assertThat(paramMap.get("tag4").getFloat64()).isEqualTo(params[5]);
		assertThat(paramMap.get("tag5").getString()).isEqualTo(params[6]);
		assertThat(paramMap.get("tag6").getFloat64()).isEqualTo(params[7]);
		assertThat(paramMap.get("tag7").getFloat64()).isEqualTo(params[8]);
		assertThat(paramMap.get("tag8").getStruct()).isEqualTo(params[9]);
		assertThat(paramMap.get("tag10").getStringArray()).isEqualTo(params[11]);
		verify(this.spannerEntityProcessor, times(1)).write(same(params[10]), any());

		assertThat(paramMap.get("SpELtag1").getFloat64()).isEqualTo(-8.88, DELTA);
		assertThat(paramMap.get("SpELtag2").getFloat64()).isEqualTo(-3.33, DELTA);

		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("dummyMethod", Object.class, Pageable.class, Object.class,
			Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class,
			Object.class, List.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());
}
 
Example #16
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void sortParamQueryTest() 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";
	// @formatter:on

	Object[] params = new Object[] { "ID", "TRADER_ID", Sort.by(Order.asc("trader_id"))};
	String[] paramNames = new String[] { "id", "trader_id", "ignoredSort" };

	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();

		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("dummyMethod5", String.class, String.class, Sort.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());
}
 
Example #17
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void pageableParamQueryTest() 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 10 OFFSET 30";
	// @formatter:on

	Object[] params = new Object[] { "ID", "TRADER_ID", PageRequest.of(3, 10, Sort.by(Order.asc("trader_id")))};
	String[] paramNames = new String[] { "id", "trader_id", "ignoredPageable" };

	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("ignoredPageable")).isNull();

		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("dummyMethod4", String.class, String.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());
}
 
Example #18
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void noPageableParamQueryTest() throws NoSuchMethodException {
	String sql = "SELECT DISTINCT * FROM "
			+ ":org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Trade:";
	// @formatter:off
	String entityResolvedSql = "SELECT *, " +
			"ARRAY (SELECT AS STRUCT disabled, id, childId, value, " +
				"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 children WHERE (children.id = trades.id) AND (disabled = false)) AS children " +
			"FROM (SELECT DISTINCT * FROM trades) trades";
	// @formatter:on

	final Class toReturn = Trade.class;
	when(queryMethod.isCollectionQuery()).thenReturn(false);
	when(queryMethod.getReturnedObjectType()).thenReturn(toReturn);

	EvaluationContext evaluationContext = new StandardEvaluationContext();
	when(this.evaluationContextProvider.getEvaluationContext(any(), any()))
			.thenReturn(evaluationContext);

	SqlSpannerQuery sqlSpannerQuery = createQuery(sql, toReturn, false);

	doAnswer((invocation) -> {
		Statement statement = invocation.getArgument(0);
		SpannerQueryOptions queryOptions = invocation.getArgument(1);
		assertThat(queryOptions.isAllowPartialRead()).isTrue();

		assertThat(statement.getSql()).isEqualTo(entityResolvedSql);

		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("dummyMethod2");
	when(this.queryMethod.getMethod()).thenReturn(method);
	Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(new DefaultParameters(method));

	sqlSpannerQuery.execute(new Object[] {});

	verify(this.spannerTemplate, times(1)).executeQuery(any(), any());
}
 
Example #19
Source File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void compoundNameConventionCountTest() throws NoSuchMethodException {
	when(this.queryMethod.getName()).thenReturn(
			"existsDistinctByActionIgnoreCaseAndSymbolOrTraderIdAndPriceLessThanOrPriceGreater"
					+ "ThanEqualAndIdIsNotNullAndTraderIdIsNullAndTraderIdLikeAndPriceTrueAndPriceFalse"
					+ "AndPriceGreaterThanAndPriceLessThanEqualOrderByIdDesc");
	this.partTreeSpannerQuery = spy(createQuery());

	when(this.spannerTemplate.query((Function<Struct, Object>) any(), any(), any()))
			.thenReturn(Collections.singletonList(1L));

	Object[] params = new Object[] { Trade.Action.BUY, "abcd", "abc123", 8.88, 3.33, "ignored",
			"ignored", "blahblah", "ignored", "ignored", 1.11, 2.22, };
	Method method = QueryHolder.class.getMethod("repositoryMethod3",
			Object.class, Object.class, Object.class,
			Object.class, Object.class, Object.class,
			Object.class, Object.class, Object.class,
			Object.class, Object.class, Object.class);
	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	when(this.spannerTemplate.query((Function<Struct, Object>) any(), any(), any()))
			.thenAnswer((invocation) -> {
				Statement statement = invocation.getArgument(1);

				String expectedSql = "SELECT EXISTS"
						+ "(SELECT DISTINCT shares, trader_id, ticker, price, action, id "
						+ "FROM trades WHERE ( LOWER(action)=LOWER(@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 @tag7 AND price=TRUE AND price=FALSE AND "
						+ "price>@tag10 AND price<=@tag11 ) ORDER BY id DESC LIMIT 1)";
				assertThat(statement.getSql()).isEqualTo(expectedSql);

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

				assertThat(paramMap.get("tag0").getString()).isEqualTo(params[0].toString());
				assertThat(paramMap.get("tag1").getString()).isEqualTo(params[1]);
				assertThat(paramMap.get("tag2").getString()).isEqualTo(params[2]);
				assertThat(paramMap.get("tag3").getFloat64()).isEqualTo(params[3]);
				assertThat(paramMap.get("tag4").getFloat64()).isEqualTo(params[4]);
				assertThat(paramMap.get("tag5").getString()).isEqualTo(params[5]);
				assertThat(paramMap.get("tag6").getString()).isEqualTo(params[6]);
				assertThat(paramMap.get("tag7").getString()).isEqualTo(params[7]);
				assertThat(paramMap.get("tag8").getString()).isEqualTo(params[8]);
				assertThat(paramMap.get("tag9").getString()).isEqualTo(params[9]);
				assertThat(paramMap.get("tag10").getFloat64()).isEqualTo(params[10]);
				assertThat(paramMap.get("tag11").getFloat64()).isEqualTo(params[11]);

				return null;
			});

	doReturn(Object.class).when(this.partTreeSpannerQuery)
			.getReturnedSimpleConvertableItemType();
	doReturn(null).when(this.partTreeSpannerQuery).convertToSimpleReturnType(any(),
			any());

	this.partTreeSpannerQuery.execute(params);
	verify(this.spannerTemplate, times(1)).query((Function<Struct, Object>) any(),
			any(), any());
}
 
Example #20
Source File: SpannerStatementQueryTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void compoundNameConventionTest() throws NoSuchMethodException {
	when(this.queryMethod.getName()).thenReturn(
			"findTop3DistinctByActionIgnoreCaseAndSymbolOrTraderIdAndPriceLessThanOrPriceGreater"
					+ "ThanEqualAndIdIsNotNullAndTraderIdIsNullAndTraderIdLikeAndPriceTrueAndPriceFalse"
					+ "AndPriceGreaterThanAndPriceLessThanEqualAndPriceInOrderByIdDesc");
	this.partTreeSpannerQuery = spy(createQuery());

	Object[] params = new Object[] { Trade.Action.BUY, "abcd", "abc123",
			8, // an int is not a natively supported type, and is intentionally used to use custom
				// converters
			3.33, "ignored",
			"ignored", "blahblah", "ignored", "ignored", 1.11, 2.22, Arrays.asList(1, 2) };

	when(this.spannerTemplate.query((Class<Object>) any(), any(), any()))
			.thenAnswer((invocation) -> {
				Statement statement = invocation.getArgument(1);

				String expectedQuery =
						"SELECT DISTINCT shares, trader_id, ticker, price, action, id "
								+ "FROM trades WHERE ( LOWER(action)=LOWER(@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 @tag7 AND price=TRUE AND price=FALSE AND "
								+ "price>@tag10 AND price<=@tag11 AND price IN UNNEST(@tag12) ) ORDER BY id DESC LIMIT 3";

				assertThat(statement.getSql()).isEqualTo(expectedQuery);

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

				assertThat(paramMap.get("tag0").getString()).isEqualTo(params[0].toString());
				assertThat(paramMap.get("tag1").getString()).isEqualTo(params[1]);
				assertThat(paramMap.get("tag2").getString()).isEqualTo(params[2]);
				assertThat(paramMap.get("tag3").getInt64()).isEqualTo(8L);
				assertThat(paramMap.get("tag4").getFloat64()).isEqualTo(params[4]);
				assertThat(paramMap.get("tag5").getString()).isEqualTo(params[5]);
				assertThat(paramMap.get("tag6").getString()).isEqualTo(params[6]);
				assertThat(paramMap.get("tag7").getString()).isEqualTo(params[7]);
				assertThat(paramMap.get("tag8").getString()).isEqualTo(params[8]);
				assertThat(paramMap.get("tag9").getString()).isEqualTo(params[9]);
				assertThat(paramMap.get("tag10").getFloat64()).isEqualTo(params[10]);
				assertThat(paramMap.get("tag11").getFloat64()).isEqualTo(params[11]);
				assertThat(paramMap.get("tag12").getInt64Array()).isEqualTo(Arrays.asList(1L, 2L));

				return null;
			});

	doReturn(Object.class).when(this.partTreeSpannerQuery)
			.getReturnedSimpleConvertableItemType();
	doReturn(null).when(this.partTreeSpannerQuery).convertToSimpleReturnType(any(),
			any());

	// This dummy method was created so the metadata for the ARRAY param inner type is
	// provided.
	Method method = QueryHolder.class.getMethod("repositoryMethod1", Object.class, Object.class, Object.class,
			Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class,
			Object.class, Object.class, List.class);
	when(this.queryMethod.getMethod()).thenReturn(method);
	doReturn(new DefaultParameters(method)).when(this.queryMethod).getParameters();

	this.partTreeSpannerQuery.execute(params);
	verify(this.spannerTemplate, times(1)).query((Class<Object>) any(), any(), any());
}
 
Example #21
Source File: StringQueryParameterBinder.java    From spring-data-ebean with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new {@link StringQueryParameterBinder} from the given {@link Parameters}, method arguments and
 * {@link StringQuery}.
 *
 * @param parameters must not be {@literal null}.
 * @param values     must not be {@literal null}.
 * @param query      must not be {@literal null}.
 */
public StringQueryParameterBinder(DefaultParameters parameters, Object[] values, StringQuery query) {

    super(parameters, values);

    Assert.notNull(query, "StringQuery must not be null!");
    this.query = query;
}