Search in sources :

Example 96 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class JpaDataStoreTransactionTest method testGetRelationDelegation.

@ParameterizedTest
@MethodSource("getTestArguments")
public void testGetRelationDelegation(boolean delegateToInMemory, int numberOfAuthors, FilterExpression filter, boolean usesInMemory) throws Exception {
    AbstractJpaTransaction tx = new AbstractJpaTransaction(entityManager, (unused) -> {
    }, DEFAULT_LOGGER, delegateToInMemory, false) {

        @Override
        public boolean isOpen() {
            return false;
        }

        @Override
        public void begin() {
        }

        @Override
        protected Predicate<Collection<?>> isPersistentCollection() {
            return (unused) -> true;
        }
    };
    EntityProjection projection = EntityProjection.builder().type(Author.class).build();
    List<Author> authors = new ArrayList<>();
    Author author1 = mock(Author.class);
    authors.add(author1);
    for (int idx = 1; idx < numberOfAuthors; idx++) {
        authors.add(mock(Author.class));
    }
    when(query.getResultList()).thenReturn(authors);
    DataStoreIterable<Author> loadedAuthors = tx.loadObjects(projection, scope);
    assertFalse(loadedAuthors.needsInMemoryPagination());
    assertFalse(loadedAuthors.needsInMemorySort());
    assertFalse(loadedAuthors.needsInMemoryFilter());
    Relationship relationship = Relationship.builder().name("books").projection(EntityProjection.builder().type(Book.class).filterExpression(filter).build()).build();
    PersistentSet returnCollection = mock(PersistentSet.class);
    when(author1.getBooks()).thenReturn(returnCollection);
    DataStoreIterable<Book> loadedBooks = tx.getToManyRelation(tx, author1, relationship, scope);
    assertEquals(usesInMemory, loadedBooks.needsInMemoryFilter());
    assertEquals(usesInMemory, loadedBooks.needsInMemorySort());
    assertEquals(usesInMemory, loadedBooks.needsInMemoryPagination());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Author(example.Author) ClassType(com.yahoo.elide.core.type.ClassType) PersistentSet(org.hibernate.collection.internal.PersistentSet) ArrayList(java.util.ArrayList) RSQLFilterDialect(com.yahoo.elide.core.filter.dialect.RSQLFilterDialect) TestInstance(org.junit.jupiter.api.TestInstance) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AbstractJpaTransaction(com.yahoo.elide.datastores.jpa.transaction.AbstractJpaTransaction) BeforeAll(org.junit.jupiter.api.BeforeAll) NO_VERSION(com.yahoo.elide.core.dictionary.EntityDictionary.NO_VERSION) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) Relationship(com.yahoo.elide.core.request.Relationship) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Arguments.arguments(org.junit.jupiter.params.provider.Arguments.arguments) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) RequestScope(com.yahoo.elide.core.RequestScope) MethodSource(org.junit.jupiter.params.provider.MethodSource) ValueSource(org.junit.jupiter.params.provider.ValueSource) DEFAULT_LOGGER(com.yahoo.elide.datastores.jpa.JpaDataStore.DEFAULT_LOGGER) Predicate(java.util.function.Predicate) Collection(java.util.Collection) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Book(example.Book) Mockito.when(org.mockito.Mockito.when) EntityManager(javax.persistence.EntityManager) Arguments(org.junit.jupiter.params.provider.Arguments) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Query(javax.persistence.Query) Stream(java.util.stream.Stream) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) EntityProjection(com.yahoo.elide.core.request.EntityProjection) ArrayList(java.util.ArrayList) PersistentSet(org.hibernate.collection.internal.PersistentSet) Book(example.Book) Relationship(com.yahoo.elide.core.request.Relationship) Collection(java.util.Collection) Author(example.Author) AbstractJpaTransaction(com.yahoo.elide.datastores.jpa.transaction.AbstractJpaTransaction) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 97 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class RootCollectionFetchQueryBuilder method build.

/**
 * Constructs a query that fetches a root collection.
 *
 * @return the constructed query
 */
@Override
public Query build() {
    Type<?> entityClass = this.entityProjection.getType();
    String entityName = entityClass.getCanonicalName();
    String entityAlias = getTypeAlias(entityClass);
    Query query;
    FilterExpression filterExpression = entityProjection.getFilterExpression();
    if (filterExpression != null) {
        PredicateExtractionVisitor extractor = new PredicateExtractionVisitor();
        Collection<FilterPredicate> predicates = filterExpression.accept(extractor);
        // Build the WHERE clause
        String filterClause = WHERE + new FilterTranslator(dictionary).apply(filterExpression, USE_ALIAS);
        // Build the JOIN clause
        String joinClause = getJoinClauseFromFilters(filterExpression) + getJoinClauseFromSort(entityProjection.getSorting()) + extractToOneMergeJoins(entityClass, entityAlias);
        boolean requiresDistinct = entityProjection.getPagination() != null && containsOneToMany(filterExpression);
        boolean sortOverRelationship = entityProjection.getSorting() != null && entityProjection.getSorting().getSortingPaths().keySet().stream().anyMatch(path -> path.getPathElements().size() > 1);
        if (requiresDistinct && sortOverRelationship) {
            // SQL does not support distinct and order by on columns which are not selected
            throw new InvalidValueException("Combination of pagination, sorting over relationship and" + " filtering over toMany relationships unsupported");
        }
        query = session.createQuery(SELECT + (requiresDistinct ? DISTINCT : "") + entityAlias + FROM + entityName + AS + entityAlias + SPACE + joinClause + SPACE + filterClause + SPACE + getSortClause(entityProjection.getSorting()));
        // Fill in the query parameters
        supplyFilterQueryParameters(query, predicates);
    } else {
        query = session.createQuery(SELECT + entityAlias + FROM + entityName + AS + entityAlias + SPACE + getJoinClauseFromSort(entityProjection.getSorting()) + extractToOneMergeJoins(entityClass, entityAlias) + SPACE + getSortClause(entityProjection.getSorting()));
    }
    addPaginationToQuery(query);
    return query;
}
Also used : PredicateExtractionVisitor(com.yahoo.elide.core.filter.expression.PredicateExtractionVisitor) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) Type(com.yahoo.elide.core.type.Type) Collection(java.util.Collection) TypeHelper.getTypeAlias(com.yahoo.elide.core.utils.TypeHelper.getTypeAlias) EntityProjection(com.yahoo.elide.core.request.EntityProjection) Session(com.yahoo.elide.datastores.jpql.porting.Session) FilterTranslator(com.yahoo.elide.datastores.jpql.filter.FilterTranslator) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) Query(com.yahoo.elide.datastores.jpql.porting.Query) InvalidValueException(com.yahoo.elide.core.exceptions.InvalidValueException) Query(com.yahoo.elide.datastores.jpql.porting.Query) PredicateExtractionVisitor(com.yahoo.elide.core.filter.expression.PredicateExtractionVisitor) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) FilterTranslator(com.yahoo.elide.datastores.jpql.filter.FilterTranslator)

Example 98 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class PersistentResourceTest method testFilterExpressionByType.

@Test
public void testFilterExpressionByType() {
    MultivaluedMap<String, String> queryParams = new MultivaluedHashMap<>();
    queryParams.add("filter[author.name][infix]", "Hemingway");
    RequestScope scope = buildRequestScope("/", mock(DataStoreTransaction.class), new TestUser("1"), queryParams);
    Optional<FilterExpression> filter = scope.getLoadFilterExpression(ClassType.of(Author.class));
    FilterPredicate predicate = (FilterPredicate) filter.get();
    assertEquals("name", predicate.getField());
    assertEquals("name", predicate.getFieldPath());
    assertEquals(Operator.INFIX, predicate.getOperator());
    assertEquals(Arrays.asList("Hemingway"), predicate.getValues());
    assertEquals("[Author].name", predicate.getPath().toString());
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) DataStoreTransaction(com.yahoo.elide.core.datastore.DataStoreTransaction) Author(example.Author) FilterPredicate(com.yahoo.elide.core.filter.predicates.FilterPredicate) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) PatchRequestScope(com.yahoo.elide.jsonapi.extensions.PatchRequestScope) TestUser(com.yahoo.elide.core.security.TestUser) Test(org.junit.jupiter.api.Test)

Example 99 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class FilteredIteratorTest method testEmptyResult.

@Test
public void testEmptyResult() throws Exception {
    EntityDictionary dictionary = EntityDictionary.builder().build();
    dictionary.bindEntity(Book.class);
    List<Book> books = List.of();
    RSQLFilterDialect filterDialect = RSQLFilterDialect.builder().dictionary(dictionary).build();
    FilterExpression expression = filterDialect.parse(ClassType.of(Book.class), new HashSet<>(), "title==*bar", NO_VERSION);
    RequestScope scope = new TestRequestScope(null, null, dictionary);
    Iterator<Book> bookIterator = new FilteredIterator<>(expression, scope, books.iterator());
    assertFalse(bookIterator.hasNext());
    assertThrows(NoSuchElementException.class, () -> bookIterator.next());
}
Also used : TestRequestScope(com.yahoo.elide.core.TestRequestScope) Book(example.Book) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) EntityDictionary(com.yahoo.elide.core.dictionary.EntityDictionary) RSQLFilterDialect(com.yahoo.elide.core.filter.dialect.RSQLFilterDialect) RequestScope(com.yahoo.elide.core.RequestScope) TestRequestScope(com.yahoo.elide.core.TestRequestScope) Test(org.junit.jupiter.api.Test)

Example 100 with FilterExpression

use of com.yahoo.elide.core.filter.expression.FilterExpression in project elide by yahoo.

the class InMemoryStoreTransactionTest method testFilterPredicateInMemoryOnComplexAttribute.

@Test
public void testFilterPredicateInMemoryOnComplexAttribute() {
    FilterExpression expression = new InPredicate(new Path(Author.class, dictionary, "homeAddress.street1"), "Foo");
    EntityProjection projection = EntityProjection.builder().type(Author.class).filterExpression(expression).build();
    DataStoreIterable filterInMemory = new DataStoreIterableBuilder(Arrays.asList(author1, author2)).filterInMemory(true).build();
    when(wrappedTransaction.loadObjects(any(), eq(scope))).thenReturn(filterInMemory);
    Collection<Object> loaded = ImmutableList.copyOf(inMemoryStoreTransaction.loadObjects(projection, scope));
    assertEquals(1, loaded.size());
    assertTrue(loaded.contains(author1));
}
Also used : Path(com.yahoo.elide.core.Path) EntityProjection(com.yahoo.elide.core.request.EntityProjection) DataStoreIterableBuilder(com.yahoo.elide.core.datastore.DataStoreIterableBuilder) Author(example.Author) FilterExpression(com.yahoo.elide.core.filter.expression.FilterExpression) InPredicate(com.yahoo.elide.core.filter.predicates.InPredicate) DataStoreIterable(com.yahoo.elide.core.datastore.DataStoreIterable) Test(org.junit.jupiter.api.Test)

Aggregations

FilterExpression (com.yahoo.elide.core.filter.expression.FilterExpression)214 Test (org.junit.jupiter.api.Test)161 OrFilterExpression (com.yahoo.elide.core.filter.expression.OrFilterExpression)91 AndFilterExpression (com.yahoo.elide.core.filter.expression.AndFilterExpression)72 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)49 FilterPredicate (com.yahoo.elide.core.filter.predicates.FilterPredicate)46 Path (com.yahoo.elide.core.Path)44 Query (com.yahoo.elide.datastores.aggregation.query.Query)42 Argument (com.yahoo.elide.core.request.Argument)39 SQLUnitTest (com.yahoo.elide.datastores.aggregation.framework.SQLUnitTest)39 DataStoreTransaction (com.yahoo.elide.core.datastore.DataStoreTransaction)34 SQLTable (com.yahoo.elide.datastores.aggregation.queryengines.sql.metadata.SQLTable)34 HashMap (java.util.HashMap)29 Book (example.Book)28 NotFilterExpression (com.yahoo.elide.core.filter.expression.NotFilterExpression)24 EntityProjection (com.yahoo.elide.core.request.EntityProjection)22 Date (java.util.Date)21 EntityDictionary (com.yahoo.elide.core.dictionary.EntityDictionary)20 Day (com.yahoo.elide.datastores.aggregation.timegrains.Day)19 HashSet (java.util.HashSet)18