Search in sources :

Example 1 with SpannerTemplate

use of org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate in project spring-cloud-gcp by spring-cloud.

the class SpannerRepositoryIntegrationTests method queryMethodsTest.

@Test
public void queryMethodsTest() {
    final int subTrades = 42;
    Trade trade = Trade.aTrade(null, subTrades);
    this.spannerOperations.insert(trade);
    final String identifier = trade.getTradeDetail().getId();
    final String traderId = trade.getTraderId();
    Optional<Trade> fetchedTrade = tradeRepository.fetchById(trade.getId());
    assertThat(fetchedTrade.get().getBigDecimalField()).isEqualTo(trade.getBigDecimalField());
    assertThat(fetchedTrade.get().getBigDecimals()).isEqualTo(trade.getBigDecimals());
    long count = subTradeRepository.countBy(identifier, traderId);
    assertThat(count).isEqualTo(subTrades);
    List<SubTrade> list = subTradeRepository.getList(identifier, traderId, Sort.by(Order.desc("subTradeId")));
    assertThat(list).hasSize(subTrades);
    assertThat(list.get(subTrades - 1)).satisfies(s -> assertThat(s.getSubTradeId()).isEqualTo("subTrade0"));
    List<SubTrade> page = subTradeRepository.getPage(identifier, traderId, PageRequest.of(0, 1024, Sort.by(Order.asc("subTradeId"))));
    assertThat(page).hasSize(subTrades);
    assertThat(page.get(0)).satisfies(s -> assertThat(s.getSubTradeId()).isEqualTo("subTrade0"));
    this.tradeRepository.deleteAll();
    List<Trade> trader1BuyTrades = insertTrades("trader1", "BUY", 3);
    List<Trade> trader1SellTrades = insertTrades("trader1", "SELL", 2);
    List<Trade> trader2Trades = insertTrades("trader2", "SELL", 3);
    List<Trade> allTrades = new ArrayList<>();
    allTrades.addAll(trader1BuyTrades);
    allTrades.addAll(trader1SellTrades);
    allTrades.addAll(trader2Trades);
    Trade buyTrade1 = trader1BuyTrades.get(0);
    this.tradeRepository.updateActionTradeById(buyTrade1.getId(), "invalid action");
    assertThat(this.tradeRepository.findById(this.spannerSchemaUtils.getKey(buyTrade1)).get().getAction()).isEqualTo("invalid action");
    this.tradeRepository.updateActionTradeById(buyTrade1.getId(), "BUY");
    assertThat(this.tradeRepository.findById(this.spannerSchemaUtils.getKey(buyTrade1)).get().getAction()).isEqualTo("BUY");
    assertThat(this.tradeRepository.count()).isEqualTo(8L);
    arrayParameterBindTest();
    assertThat(this.tradeRepository.deleteByAction("BUY")).isEqualTo(3);
    assertThat(this.tradeRepository.count()).isEqualTo(5L);
    List<Trade> deletedBySymbol = this.tradeRepository.deleteBySymbol("ABCD");
    assertThat(deletedBySymbol).hasSize(5);
    assertThat(this.tradeRepository.count()).isEqualTo(0L);
    this.tradeRepository.saveAll(deletedBySymbol);
    assertThat(this.tradeRepository.count()).isEqualTo(5L);
    this.tradeRepository.deleteBySymbolAndAction("ABCD", "SELL");
    assertThat(this.tradeRepository.count()).isEqualTo(0L);
    this.tradeRepository.saveAll(allTrades);
    List<Trade> allTradesRetrieved = this.spannerOperations.readAll(Trade.class);
    assertThat(allTradesRetrieved).containsExactlyInAnyOrderElementsOf(allTrades);
    assertThat(this.tradeRepository.countByAction("BUY")).isEqualTo(3);
    assertThat(this.tradeRepository.countByActionQuery("BUY")).isEqualTo(3);
    assertThat(this.tradeRepository.existsByActionQuery("BUY")).isTrue();
    assertThat(this.tradeRepository.getOneTrade("BUY")).isNotNull();
    assertThat(this.tradeRepository.getFirstString("BUY")).isEqualTo("BUY");
    assertThat(this.tradeRepository.getFirstStringList("BUY")).containsExactlyInAnyOrder("BUY", "BUY", "BUY");
    List<Trade> trader2TradesRetrieved = this.tradeRepository.findByTraderId("trader2");
    assertThat(trader2TradesRetrieved).containsExactlyInAnyOrderElementsOf(trader2Trades);
    assertThat(this.tradeRepository.findByTraderId("trader2", PageRequest.of(0, 2, Sort.by("tradeTime")))).containsExactlyInAnyOrder(trader2Trades.get(0), trader2Trades.get(1));
    assertThat(this.tradeRepository.findByTraderId("trader2", PageRequest.of(1, 2, Sort.by("tradeTime")))).containsExactlyInAnyOrder(trader2Trades.get(2));
    assertThat(this.tradeRepository.findByTraderId("trader2", PageRequest.of(0, 2, Sort.by(Direction.DESC, "tradeTime")))).containsExactlyInAnyOrder(trader2Trades.get(2), trader2Trades.get(1));
    assertThat(this.tradeRepository.findByTraderId("trader2", PageRequest.of(1, 2, Sort.by(Direction.DESC, "tradeTime")))).containsExactlyInAnyOrder(trader2Trades.get(0));
    assertThat(this.tradeRepository.findTop2ByTraderIdOrderByTradeTimeAsc("trader2", Pageable.unpaged())).containsExactlyInAnyOrder(trader2Trades.get(0), trader2Trades.get(1));
    assertThat(this.tradeRepository.findTop2ByTraderIdOrderByTradeTimeAsc("trader2", PageRequest.of(0, 1))).containsExactlyInAnyOrder(trader2Trades.get(0));
    assertThat(this.tradeRepository.findTop2ByTraderIdOrderByTradeTimeAsc("trader2", PageRequest.of(0, 1, Sort.by(Direction.DESC, "tradeTime")))).containsExactlyInAnyOrder(trader2Trades.get(2));
    List<TradeProjection> tradeProjectionsRetrieved = this.tradeRepository.findByActionIgnoreCase("bUy");
    assertThat(tradeProjectionsRetrieved).hasSize(3);
    for (TradeProjection tradeProjection : tradeProjectionsRetrieved) {
        assertThat(tradeProjection.getAction()).isEqualTo("BUY");
        assertThat(tradeProjection.getSymbolAndAction()).isEqualTo("ABCD BUY");
    }
    List<Trade> tradesReceivedPage0 = this.tradeRepository.findAll(PageRequest.of(0, 3, Sort.by(Order.asc("id")))).getContent();
    assertThat(tradesReceivedPage0).hasSize(3);
    assertThat(tradesReceivedPage0.get(0).getId().compareTo(tradesReceivedPage0.get(1).getId())).isNegative();
    assertThat(tradesReceivedPage0.get(1).getId().compareTo(tradesReceivedPage0.get(2).getId())).isNegative();
    List<Trade> tradesReceivedPage1 = this.tradeRepository.findAll(PageRequest.of(1, 3, Sort.by(Order.asc("id")))).getContent();
    assertThat(tradesReceivedPage1).hasSize(3);
    assertThat(tradesReceivedPage0.get(2).getId().compareTo(tradesReceivedPage1.get(0).getId())).isNegative();
    assertThat(tradesReceivedPage1.get(0).getId().compareTo(tradesReceivedPage1.get(1).getId())).isNegative();
    assertThat(tradesReceivedPage1.get(1).getId().compareTo(tradesReceivedPage1.get(2).getId())).isNegative();
    List<Trade> tradesReceivedPage2 = this.tradeRepository.findAll(PageRequest.of(2, 3, Sort.by(Order.asc("id")))).getContent();
    assertThat(tradesReceivedPage2).hasSize(2);
    assertThat(tradesReceivedPage1.get(2).getId().compareTo(tradesReceivedPage2.get(0).getId())).isNegative();
    assertThat(tradesReceivedPage2.get(0).getId().compareTo(tradesReceivedPage2.get(1).getId())).isNegative();
    List<Trade> buyTradesRetrieved = this.tradeRepository.annotatedTradesByAction("BUY", PageRequest.of(0, 100, Sort.by(Order.desc("id"))));
    assertThat(buyTradesRetrieved).containsExactlyInAnyOrderElementsOf(trader1BuyTrades);
    assertThat(buyTradesRetrieved.get(0).getId()).isGreaterThan(buyTradesRetrieved.get(1).getId());
    assertThat(buyTradesRetrieved.get(1).getId()).isGreaterThan(buyTradesRetrieved.get(2).getId());
    List<Trade> customSortedTrades = this.tradeRepository.sortedTrades(PageRequest.of(2, 2, org.springframework.data.domain.Sort.by(Order.asc("id"))));
    assertThat(customSortedTrades).hasSize(2);
    assertThat(customSortedTrades.get(0).getId().compareTo(customSortedTrades.get(1).getId())).isNegative();
    this.tradeRepository.findBySymbolLike("%BCD").forEach((x) -> assertThat(x.getSymbol()).isEqualTo("ABCD"));
    assertThat(this.tradeRepository.findBySymbolNotLike("%BCD")).isEmpty();
    this.tradeRepository.findBySymbolContains("BCD").forEach((x) -> assertThat(x.getSymbol()).isEqualTo("ABCD"));
    assertThat(this.tradeRepository.findBySymbolNotContains("BCD")).isEmpty();
    assertThat(this.tradeRepository.findBySymbolAndActionPojo(new SymbolAction("ABCD", "BUY"))).hasSize(3);
    assertThat(this.tradeRepository.findBySymbolAndActionStruct(Struct.newBuilder().set("symbol").to("ABCD").set("action").to("BUY").build())).hasSize(3);
    // testing setting some columns to null.
    Trade someTrade = this.tradeRepository.findBySymbolContains("ABCD").get(0);
    assertThat(someTrade.getExecutionTimes()).isNotNull();
    assertThat(someTrade.getSymbol()).isNotNull();
    someTrade.setExecutionTimes(null);
    someTrade.setSymbol(null);
    this.tradeRepository.save(someTrade);
    someTrade = this.tradeRepository.findById(this.spannerSchemaUtils.getKey(someTrade)).get();
    assertThat(someTrade.getExecutionTimes()).isNull();
    assertThat(someTrade.getSymbol()).isNull();
    // testing parent-child relationships
    assertThat(someTrade.getSubTrades()).hasSize(0);
    SubTrade subTrade1 = new SubTrade(someTrade.getTradeDetail().getId(), someTrade.getTraderId(), "subTrade1");
    SubTrade subTrade2 = new SubTrade(someTrade.getTradeDetail().getId(), someTrade.getTraderId(), "subTrade2");
    SubTradeComponent subTradeComponent11 = new SubTradeComponent(someTrade.getTradeDetail().getId(), someTrade.getTraderId(), "subTrade1", "11a", "11b");
    subTradeComponent11.setCommitTimestamp(Timestamp.ofTimeMicroseconds(11));
    SubTradeComponent subTradeComponent21 = new SubTradeComponent(someTrade.getTradeDetail().getId(), someTrade.getTraderId(), "subTrade2", "21a", "21b");
    subTradeComponent21.setCommitTimestamp(Timestamp.ofTimeMicroseconds(21));
    SubTradeComponent subTradeComponent22 = new SubTradeComponent(someTrade.getTradeDetail().getId(), someTrade.getTraderId(), "subTrade2", "22a", "22b");
    subTradeComponent22.setCommitTimestamp(Timestamp.ofTimeMicroseconds(22));
    subTrade1.setSubTradeComponentList(Arrays.asList(subTradeComponent11));
    subTrade2.setSubTradeComponentList(Arrays.asList(subTradeComponent21, subTradeComponent22));
    someTrade.setSubTrades(Arrays.asList(subTrade1, subTrade2));
    this.tradeRepository.save(someTrade);
    assertThat(this.subTradeRepository.count()).isEqualTo(2);
    assertThat(this.subTradeComponentRepository.count()).isEqualTo(3);
    // test eager-fetch in @Query
    Mockito.clearInvocations(spannerTemplate);
    final Trade aTrade = someTrade;
    assertThat(tradeRepository.fetchById(aTrade.getId())).isNotEmpty().hasValueSatisfying(t -> assertThat(t.getId()).isEqualTo(aTrade.getId())).hasValueSatisfying(t -> assertThat(t.getTraderId()).isEqualTo(aTrade.getTraderId())).hasValueSatisfying(t -> assertThat(t.getSymbol()).isEqualTo(aTrade.getSymbol())).hasValueSatisfying(t -> assertThat(t.getSubTrades()).hasSize(aTrade.getSubTrades().size()));
    Mockito.verify(spannerTemplate, Mockito.times(1)).executeQuery(any(Statement.class), any());
    Mockito.verify(spannerTemplate, Mockito.times(1)).query(eq(Trade.class), any(Statement.class), any(SpannerQueryOptions.class));
    List<SubTradeComponent> subTradeComponents = (List) this.subTradeComponentRepository.findAll();
    assertThat(subTradeComponents.get(0).getCommitTimestamp()).isEqualTo(subTradeComponents.get(1).getCommitTimestamp());
    assertThat(subTradeComponents.get(0).getCommitTimestamp()).isEqualTo(subTradeComponents.get(2).getCommitTimestamp());
    assertThat(subTradeComponents.get(0).getCommitTimestamp()).isGreaterThan(Timestamp.ofTimeMicroseconds(22));
    this.subTradeRepository.deleteById(this.spannerSchemaUtils.getKey(subTrade1));
    assertThat(this.subTradeComponentRepository.count()).isEqualTo(2);
    someTrade = this.tradeRepository.findById(this.spannerSchemaUtils.getKey(someTrade)).get();
    assertThat(someTrade.getSubTrades()).hasSize(1);
    assertThat(someTrade.getSubTrades().get(0).getSubTradeId()).isEqualTo("subTrade2");
    assertThat(someTrade.getSubTrades().get(0).getSubTradeComponentList()).hasSize(2);
    this.tradeRepository.delete(someTrade);
    assertThat(this.subTradeComponentRepository.count()).isEqualTo(0);
    assertThat(this.subTradeRepository.count()).isEqualTo(0);
    this.tradeRepository.deleteAll();
    this.tradeRepositoryTransactionalService.testTransactionalAnnotation(3);
    assertThat(this.tradeRepository.count()).isEqualTo(1L);
    List<Trade> trades = (List) tradeRepository.findAll();
    someTrade = trades.get(0);
    assertThat(someTrade.getSubTrades()).hasSize(3);
    SubTrade someSubTrade = trades.get(0).getSubTrades().get(0);
    // a soft-delete
    someSubTrade.setDisabled(true);
    subTradeRepository.save(someSubTrade);
    someTrade = this.tradeRepository.findById(this.spannerSchemaUtils.getKey(someTrade)).get();
    assertThat(someTrade.getSubTrades()).doesNotContain(// "someSubTrade" was soft-deleted
    someSubTrade).hasSize(2);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) Order(org.springframework.data.domain.Sort.Order) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) Autowired(org.springframework.beans.factory.annotation.Autowired) Timestamp(com.google.cloud.Timestamp) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) Sets(org.assertj.core.util.Sets) TradeProjection(org.springframework.cloud.gcp.data.spanner.test.domain.TradeProjection) ArrayList(java.util.ArrayList) SpannerQueryOptions(org.springframework.cloud.gcp.data.spanner.core.SpannerQueryOptions) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) SubTradeComponent(org.springframework.cloud.gcp.data.spanner.test.domain.SubTradeComponent) SubTrade(org.springframework.cloud.gcp.data.spanner.test.domain.SubTrade) Key(com.google.cloud.spanner.Key) After(org.junit.After) SpannerTemplate(org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate) SymbolAction(org.springframework.cloud.gcp.data.spanner.test.domain.SymbolAction) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) SpannerPersistentEntity(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentEntity) TradeRepository(org.springframework.cloud.gcp.data.spanner.test.domain.TradeRepository) Direction(org.springframework.data.domain.Sort.Direction) SpringRunner(org.springframework.test.context.junit4.SpringRunner) SpannerMappingContext(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerMappingContext) Trade(org.springframework.cloud.gcp.data.spanner.test.domain.Trade) Before(org.junit.Before) AbstractSpannerIntegrationTest(org.springframework.cloud.gcp.data.spanner.test.AbstractSpannerIntegrationTest) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) PersistentProperty(org.springframework.data.mapping.PersistentProperty) SpyBean(org.springframework.boot.test.mock.mockito.SpyBean) SubTradeRepository(org.springframework.cloud.gcp.data.spanner.test.domain.SubTradeRepository) PageRequest(org.springframework.data.domain.PageRequest) Test(org.junit.Test) SubTradeComponentRepository(org.springframework.cloud.gcp.data.spanner.test.domain.SubTradeComponentRepository) Statement(com.google.cloud.spanner.Statement) Mockito(org.mockito.Mockito) List(java.util.List) Struct(com.google.cloud.spanner.Struct) Optional(java.util.Optional) Collections(java.util.Collections) Transactional(org.springframework.transaction.annotation.Transactional) SubTradeComponent(org.springframework.cloud.gcp.data.spanner.test.domain.SubTradeComponent) Statement(com.google.cloud.spanner.Statement) ArrayList(java.util.ArrayList) SubTrade(org.springframework.cloud.gcp.data.spanner.test.domain.SubTrade) SymbolAction(org.springframework.cloud.gcp.data.spanner.test.domain.SymbolAction) SpannerQueryOptions(org.springframework.cloud.gcp.data.spanner.core.SpannerQueryOptions) SubTrade(org.springframework.cloud.gcp.data.spanner.test.domain.SubTrade) Trade(org.springframework.cloud.gcp.data.spanner.test.domain.Trade) ArrayList(java.util.ArrayList) List(java.util.List) TradeProjection(org.springframework.cloud.gcp.data.spanner.test.domain.TradeProjection) AbstractSpannerIntegrationTest(org.springframework.cloud.gcp.data.spanner.test.AbstractSpannerIntegrationTest) Test(org.junit.Test)

Example 2 with SpannerTemplate

use of org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate in project spring-cloud-gcp by spring-cloud.

the class SqlSpannerQueryTests method initMocks.

@Before
public void initMocks() throws NoSuchMethodException {
    this.queryMethod = mock(SpannerQueryMethod.class);
    // this is a dummy object. it is not mockable otherwise.
    Method method = Object.class.getMethod("toString");
    when(this.queryMethod.getMethod()).thenReturn(method);
    when(this.spannerEntityProcessor.getWriteConverter()).thenReturn(new SpannerWriteConverter());
    this.spannerTemplate = spy(new SpannerTemplate(() -> this.databaseClient, this.spannerMappingContext, this.spannerEntityProcessor, mock(SpannerMutationFactory.class), new SpannerSchemaUtils(this.spannerMappingContext, this.spannerEntityProcessor, true)));
    this.expressionParser = new SpelExpressionParser();
    this.evaluationContextProvider = mock(QueryMethodEvaluationContextProvider.class);
}
Also used : SpannerMutationFactory(org.springframework.cloud.gcp.data.spanner.core.SpannerMutationFactory) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) QueryMethodEvaluationContextProvider(org.springframework.data.repository.query.QueryMethodEvaluationContextProvider) SpannerTemplate(org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate) SpannerSchemaUtils(org.springframework.cloud.gcp.data.spanner.core.admin.SpannerSchemaUtils) Method(java.lang.reflect.Method) SpannerWriteConverter(org.springframework.cloud.gcp.data.spanner.core.convert.SpannerWriteConverter) Before(org.junit.Before)

Aggregations

Before (org.junit.Before)2 SpannerTemplate (org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate)2 Timestamp (com.google.cloud.Timestamp)1 Key (com.google.cloud.spanner.Key)1 Statement (com.google.cloud.spanner.Statement)1 Struct (com.google.cloud.spanner.Struct)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Optional (java.util.Optional)1 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)1 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)1 Sets (org.assertj.core.util.Sets)1 After (org.junit.After)1 Test (org.junit.Test)1 RunWith (org.junit.runner.RunWith)1 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)1 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)1