Search in sources :

Example 1 with DataStoreIterableBuilder

use of com.yahoo.elide.core.datastore.DataStoreIterableBuilder in project elide by yahoo.

the class AggregationDataStoreTransaction method loadObjects.

@Override
public <T> DataStoreIterable<T> loadObjects(EntityProjection entityProjection, RequestScope scope) {
    QueryResult result = null;
    QueryResponse response = null;
    String cacheKey = null;
    try {
        // Convert multivalued map to map.
        Map<String, String> headers = scope.getRequestHeaders().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, (entry) -> entry.getValue().stream().collect(Collectors.joining(" "))));
        queryLogger.acceptQuery(scope.getRequestId(), scope.getUser(), headers, scope.getApiVersion(), scope.getQueryParams(), scope.getPath());
        Query query = buildQuery(entityProjection, scope);
        Table table = (Table) query.getSource();
        if (cache != null && !query.isBypassingCache()) {
            String tableVersion = queryEngine.getTableVersion(table, queryEngineTransaction);
            tableVersion = tableVersion == null ? "" : tableVersion;
            cacheKey = tableVersion + ';' + QueryKeyExtractor.extractKey(query);
            result = cache.get(cacheKey);
        }
        boolean isCached = result != null;
        List<String> queryText = queryEngine.explain(query);
        queryLogger.processQuery(scope.getRequestId(), query, queryText, isCached);
        if (result == null) {
            result = queryEngine.executeQuery(query, queryEngineTransaction);
            if (cacheKey != null) {
                // The query result needs to be streamed into an in memory list before caching.
                // TODO - add a cap to how many records can be streamed back.  If this is exceeded, abort caching
                // and return the results.
                QueryResult cacheableResult = QueryResult.builder().data(Lists.newArrayList(result.getData().iterator())).pageTotals(result.getPageTotals()).build();
                cache.put(cacheKey, cacheableResult);
                result = cacheableResult;
            }
        }
        if (entityProjection.getPagination() != null && entityProjection.getPagination().returnPageTotals()) {
            entityProjection.getPagination().setPageTotals(result.getPageTotals());
        }
        response = new QueryResponse(HttpStatus.SC_OK, result.getData(), null);
        return new DataStoreIterableBuilder(result.getData()).build();
    } catch (HttpStatusException e) {
        response = new QueryResponse(e.getStatus(), null, e.getMessage());
        throw e;
    } catch (Exception e) {
        response = new QueryResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, null, e.getMessage());
        throw e;
    } finally {
        queryLogger.completeQuery(scope.getRequestId(), response);
    }
}
Also used : HttpStatus(com.yahoo.elide.core.exceptions.HttpStatus) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) QueryResponse(com.yahoo.elide.datastores.aggregation.core.QueryResponse) HashMap(java.util.HashMap) Argument(com.yahoo.elide.core.request.Argument) InvalidOperationException(com.yahoo.elide.core.exceptions.InvalidOperationException) Map(java.util.Map) MatchesTemplateVisitor(com.yahoo.elide.datastores.aggregation.filter.visitor.MatchesTemplateVisitor) Column(com.yahoo.elide.datastores.aggregation.metadata.models.Column) ToString(lombok.ToString) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) RequestScope(com.yahoo.elide.core.RequestScope) RequiresFilter(com.yahoo.elide.datastores.aggregation.metadata.models.RequiresFilter) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) HttpStatusException(com.yahoo.elide.core.exceptions.HttpStatusException) Cache(com.yahoo.elide.datastores.aggregation.cache.Cache) Lists(org.apache.commons.compress.utils.Lists) EntityProjection(com.yahoo.elide.core.request.EntityProjection) QueryResult(com.yahoo.elide.datastores.aggregation.query.QueryResult) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Query(com.yahoo.elide.datastores.aggregation.query.Query) List(java.util.List) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) QueryKeyExtractor(com.yahoo.elide.datastores.aggregation.cache.QueryKeyExtractor) Type(com.yahoo.elide.core.type.Type) Table(com.yahoo.elide.datastores.aggregation.metadata.models.Table) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MetaDataStore(com.yahoo.elide.datastores.aggregation.metadata.MetaDataStore) QueryLogger(com.yahoo.elide.datastores.aggregation.core.QueryLogger) Table(com.yahoo.elide.datastores.aggregation.metadata.models.Table) Query(com.yahoo.elide.datastores.aggregation.query.Query) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) HttpStatusException(com.yahoo.elide.core.exceptions.HttpStatusException) ToString(lombok.ToString) InvalidOperationException(com.yahoo.elide.core.exceptions.InvalidOperationException) HttpStatusException(com.yahoo.elide.core.exceptions.HttpStatusException) IOException(java.io.IOException) BadRequestException(com.yahoo.elide.core.exceptions.BadRequestException) QueryResult(com.yahoo.elide.datastores.aggregation.query.QueryResult) QueryResponse(com.yahoo.elide.datastores.aggregation.core.QueryResponse) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with DataStoreIterableBuilder

use of com.yahoo.elide.core.datastore.DataStoreIterableBuilder in project elide by yahoo.

the class LifeCycleTest method testRemoveFromCollectionTrigger.

@Test
public void testRemoveFromCollectionTrigger() {
    PropertyTestModel mockModel = mock(PropertyTestModel.class);
    DataStoreTransaction tx = mock(DataStoreTransaction.class);
    RequestScope scope = buildRequestScope(dictionary, tx);
    when(tx.createNewObject(ClassType.of(PropertyTestModel.class), scope)).thenReturn(mockModel);
    PropertyTestModel childModel1 = mock(PropertyTestModel.class);
    PropertyTestModel childModel2 = mock(PropertyTestModel.class);
    PropertyTestModel childModel3 = mock(PropertyTestModel.class);
    when(childModel1.getId()).thenReturn("2");
    when(childModel2.getId()).thenReturn("3");
    when(childModel3.getId()).thenReturn("4");
    // First we test removing from a newly created object.
    PersistentResource resource = PersistentResource.createObject(ClassType.of(PropertyTestModel.class), scope, Optional.of("1"));
    PersistentResource childResource1 = new PersistentResource(childModel1, "2", scope);
    PersistentResource childResource2 = new PersistentResource(childModel2, "3", scope);
    PersistentResource childResource3 = new PersistentResource(childModel3, "3", scope);
    resource.updateRelation("models", new HashSet<>(Arrays.asList(childResource1, childResource2)));
    scope.runQueuedPreSecurityTriggers();
    scope.runQueuedPreCommitTriggers();
    scope.runQueuedPostCommitTriggers();
    verify(mockModel, never()).relationCallback(eq(UPDATE), any(), any());
    ArgumentCaptor<ChangeSpec> changes = ArgumentCaptor.forClass(ChangeSpec.class);
    verify(mockModel, times(1)).relationCallback(eq(CREATE), eq(POSTCOMMIT), changes.capture());
    changes.getValue().getModified().equals(List.of(childModel1, childModel2));
    changes.getValue().getOriginal().equals(List.of());
    // Build another resource, scope & reset the mock to do a pure update (no create):
    scope = buildRequestScope(dictionary, tx);
    resource = new PersistentResource(mockModel, scope.getUUIDFor(mockModel), scope);
    reset(mockModel);
    Relationship relationship = Relationship.builder().projection(EntityProjection.builder().type(PropertyTestModel.class).build()).name("models").build();
    when(tx.getToManyRelation(tx, mockModel, relationship, scope)).thenReturn(new DataStoreIterableBuilder<Object>(Arrays.asList(childModel1, childModel2)).build());
    when(mockModel.getModels()).thenReturn(new HashSet<>(Arrays.asList(childModel1, childModel2)));
    resource.updateRelation("models", new HashSet<>(Arrays.asList(childResource1, childResource3)));
    scope.runQueuedPreSecurityTriggers();
    scope.runQueuedPreCommitTriggers();
    scope.runQueuedPostCommitTriggers();
    verify(mockModel, never()).relationCallback(eq(CREATE), any(), any());
    changes = ArgumentCaptor.forClass(ChangeSpec.class);
    verify(mockModel, times(1)).relationCallback(eq(UPDATE), eq(POSTCOMMIT), changes.capture());
    changes.getValue().getModified().equals(List.of(childModel1, childModel3));
    changes.getValue().getOriginal().equals(List.of(childModel1, childModel2));
}
Also used : PersistentResource(com.yahoo.elide.core.PersistentResource) ChangeSpec(com.yahoo.elide.core.security.ChangeSpec) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) Relationship(com.yahoo.elide.core.request.Relationship) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) RequestScope(com.yahoo.elide.core.RequestScope) Test(org.junit.jupiter.api.Test)

Example 3 with DataStoreIterableBuilder

use of com.yahoo.elide.core.datastore.DataStoreIterableBuilder in project elide by yahoo.

the class PersistentResourceTest method testGetRelationByIdSuccess.

@Test
public void testGetRelationByIdSuccess() {
    FunWithPermissions fun = new FunWithPermissions();
    Child child1 = newChild(1);
    Child child2 = newChild(2);
    Child child3 = newChild(3);
    fun.setRelation2(Sets.newHashSet(child1, child2, child3));
    when(tx.getToManyRelation(eq(tx), any(), any(), any())).thenReturn(new DataStoreIterableBuilder(Sets.newHashSet(child1)).build());
    RequestScope goodScope = buildRequestScope(tx, goodUser);
    PersistentResource<FunWithPermissions> funResource = new PersistentResource<>(fun, "3", goodScope);
    PersistentResource<?> result = funResource.getRelation(getRelationship(ClassType.of(FunWithPermissions.class), "relation2"), "1");
    assertEquals(1, ((Child) result.getObject()).getId(), "The correct relationship element should be returned");
}
Also used : DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) FunWithPermissions(example.FunWithPermissions) Child(example.Child) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) Test(org.junit.jupiter.api.Test)

Example 4 with DataStoreIterableBuilder

use of com.yahoo.elide.core.datastore.DataStoreIterableBuilder in project elide by yahoo.

the class InMemoryStoreTransactionTest method testSortOnComplexAttribute.

@Test
public void testSortOnComplexAttribute() {
    Map<String, Sorting.SortOrder> sortOrder = new HashMap<>();
    sortOrder.put("homeAddress.street1", Sorting.SortOrder.asc);
    Sorting sorting = new SortingImpl(sortOrder, Author.class, dictionary);
    EntityProjection projection = EntityProjection.builder().type(Author.class).sorting(sorting).build();
    DataStoreIterable sortInMemory = new DataStoreIterableBuilder(Arrays.asList(author1, author2)).sortInMemory(true).build();
    when(wrappedTransaction.loadObjects(any(), eq(scope))).thenReturn(sortInMemory);
    Collection<Object> loaded = Lists.newArrayList(inMemoryStoreTransaction.loadObjects(projection, scope));
    assertEquals(2, loaded.size());
    Object[] sorted = loaded.toArray();
    assertEquals(author2, sorted[0]);
    assertEquals(author1, sorted[1]);
}
Also used : EntityProjection(com.yahoo.elide.core.request.EntityProjection) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) HashMap(java.util.HashMap) SortingImpl(com.yahoo.elide.core.sort.SortingImpl) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) Sorting(com.yahoo.elide.core.request.Sorting) Test(org.junit.jupiter.api.Test)

Example 5 with DataStoreIterableBuilder

use of com.yahoo.elide.core.datastore.DataStoreIterableBuilder in project elide by yahoo.

the class InMemoryStoreTransactionTest method testSortingRequiresInMemoryPagination.

@Test
public void testSortingRequiresInMemoryPagination() {
    PaginationImpl pagination = new PaginationImpl(ClassType.of(Book.class), 0, 3, 10, 10, true, false);
    Map<String, Sorting.SortOrder> sortOrder = new HashMap<>();
    sortOrder.put("title", Sorting.SortOrder.desc);
    Sorting sorting = new SortingImpl(sortOrder, Book.class, dictionary);
    EntityProjection projection = EntityProjection.builder().type(Book.class).sorting(sorting).pagination(pagination).build();
    DataStoreIterable sortInMemory = new DataStoreIterableBuilder(books).sortInMemory(true).build();
    when(wrappedTransaction.loadObjects(any(), eq(scope))).thenReturn(sortInMemory);
    Collection<Object> loaded = Lists.newArrayList(inMemoryStoreTransaction.loadObjects(projection, scope));
    verify(wrappedTransaction, times(1)).loadObjects(any(EntityProjection.class), eq(scope));
    assertEquals(3, loaded.size());
    List<String> bookTitles = loaded.stream().map((o) -> ((Book) o).getTitle()).collect(Collectors.toList());
    assertEquals(Lists.newArrayList("Book 3", "Book 2", "Book 1"), bookTitles);
    assertEquals(3, pagination.getPageTotals());
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Path(com.yahoo.elide.core.Path) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Publisher(example.Publisher) SortingImpl(com.yahoo.elide.core.sort.SortingImpl) ClassType(com.yahoo.elide.core.type.ClassType) Map(java.util.Map) PersistentResource(com.yahoo.elide.core.PersistentResource) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) Relationship(com.yahoo.elide.core.request.Relationship) RequestScope(com.yahoo.elide.core.RequestScope) ImmutableSet(com.google.common.collect.ImmutableSet) DefaultClassScanner(com.yahoo.elide.core.utils.DefaultClassScanner) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Sets(com.google.common.collect.Sets) Test(org.junit.jupiter.api.Test) List(java.util.List) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ElideSettingsBuilder(com.yahoo.elide.ElideSettingsBuilder) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) PaginationImpl(com.yahoo.elide.core.pagination.PaginationImpl) HashMap(java.util.HashMap) Author(example.Author) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) Editor(example.Editor) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) LinkedHashSet(java.util.LinkedHashSet) ElideSettings(com.yahoo.elide.ElideSettings) Price(example.Price) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) Sorting(com.yahoo.elide.core.request.Sorting) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) Mockito.times(org.mockito.Mockito.times) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Book(example.Book) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Address(example.Address) Mockito.reset(org.mockito.Mockito.reset) EntityProjection(com.yahoo.elide.core.request.EntityProjection) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) HashMap(java.util.HashMap) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) Sorting(com.yahoo.elide.core.request.Sorting) PaginationImpl(com.yahoo.elide.core.pagination.PaginationImpl) SortingImpl(com.yahoo.elide.core.sort.SortingImpl) Book(example.Book) Test(org.junit.jupiter.api.Test)

Aggregations

DataStoreIterableBuilder (com.yahoo.elide.core.datastore.DataStoreIterableBuilder)46 Test (org.junit.jupiter.api.Test)41 PatchRequestScope (com.yahoo.elide.jsonapi.extensions.PatchRequestScope)20 Child (example.Child)16 Book (example.Book)15 EntityProjection (com.yahoo.elide.core.request.EntityProjection)13 DataStoreIterable (com.yahoo.elide.core.datastore.DataStoreIterable)12 FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)11 Parent (example.Parent)11 Path (com.yahoo.elide.core.Path)8 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)7 InPredicate (com.yahoo.elide.core.filter.predicates.InPredicate)7 Sorting (com.yahoo.elide.core.request.Sorting)7 GraphQLTest (com.yahoo.elide.graphql.GraphQLTest)7 Author (example.Author)7 ArrayList (java.util.ArrayList)7 RequestScope (com.yahoo.elide.core.RequestScope)6 PaginationImpl (com.yahoo.elide.core.pagination.PaginationImpl)6 Relationship (com.yahoo.elide.core.request.Relationship)6 HashMap (java.util.HashMap)6