Search in sources :

Example 1 with QuerySortBy

use of com.amplifyframework.core.model.query.QuerySortBy in project amplify-android by aws-amplify.

the class ModelSorterTest method sortReturnsSortedList.

/**
 * Sort method returns sorted list.
 */
@Test
public void sortReturnsSortedList() {
    List<String> names = Arrays.asList("John", "Jacob", "Joe", "Bob", "Bobby", "Bobb", "Dan", "Dany", "Daniel");
    List<String> weas = Arrays.asList("pon", "lth", "ver", "kly", "ken", "sel", "ner", "rer", "ned");
    List<BlogOwner> owners = new ArrayList<>();
    for (int i = 0; i < names.size() / 2; i++) {
        BlogOwner owner = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
        owners.add(owner);
    }
    List<QuerySortBy> sortBy = new ArrayList<>();
    sortBy.add(BlogOwner.NAME.descending());
    sortBy.add(BlogOwner.WEA.ascending());
    ModelSorter<BlogOwner> subject = new ModelSorter<>();
    subject.sort(new ObserveQueryOptions(null, sortBy), owners, BlogOwner.class, value -> {
    });
    List<BlogOwner> sorted = new ArrayList<>(owners);
    Collections.sort(sorted, Comparator.comparing(BlogOwner::getName).reversed().thenComparing(BlogOwner::getWea));
    assertEquals(sorted, owners);
}
Also used : QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) ArrayList(java.util.ArrayList) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Test(org.junit.Test)

Example 2 with QuerySortBy

use of com.amplifyframework.core.model.query.QuerySortBy in project amplify-android by aws-amplify.

the class ObserveQueryExecutorTest method observeQueryReturnsSortedListOfTotalItems.

/**
 * observe Query Returns Sorted List Of Total Items.
 * @throws InterruptedException InterruptedException
 * @throws DataStoreException DataStoreException
 */
@Test
public void observeQueryReturnsSortedListOfTotalItems() throws InterruptedException, DataStoreException {
    CountDownLatch latch = new CountDownLatch(1);
    CountDownLatch changeLatch = new CountDownLatch(1);
    AtomicInteger count = new AtomicInteger();
    List<String> names = Arrays.asList("John", "Jacob", "Joe", "Bob", "Bobby", "Bobb", "Dan", "Dany", "Daniel");
    List<String> weas = Arrays.asList("pon", "lth", "ver", "kly", "ken", "sel", "ner", "rer", "ned");
    List<BlogOwner> owners = new ArrayList<>();
    for (int i = 0; i < names.size() / 2; i++) {
        BlogOwner owner = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
        owners.add(owner);
    }
    int maxRecords = 50;
    Consumer<Cancelable> observationStarted = NoOpConsumer.create();
    SyncStatus mockSyncStatus = mock(SyncStatus.class);
    when(mockSyncStatus.get(any(), any())).thenReturn(false);
    Subject<StorageItemChange<? extends Model>> subject = PublishSubject.<StorageItemChange<? extends Model>>create().toSerialized();
    Consumer<DataStoreQuerySnapshot<BlogOwner>> onQuerySnapshot = value -> {
        if (count.get() == 0) {
            Assert.assertTrue(value.getItems().contains(owners.get(0)));
            latch.countDown();
        } else if (count.get() == 1) {
            List<BlogOwner> sorted = new ArrayList<>(owners);
            Collections.sort(sorted, Comparator.comparing(BlogOwner::getName).reversed().thenComparing(BlogOwner::getWea));
            assertEquals(sorted, value.getItems());
            Assert.assertEquals(8, value.getItems().size());
            changeLatch.countDown();
        }
        count.getAndIncrement();
    };
    Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
    Action onObservationComplete = () -> {
    };
    SqlQueryProcessor mockSqlQueryProcessor = mock(SqlQueryProcessor.class);
    when(mockSqlQueryProcessor.queryOfflineData(eq(BlogOwner.class), any(), any())).thenReturn(owners);
    when(mockSqlQueryProcessor.modelExists(any(), any())).thenReturn(true);
    ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
    ObserveQueryExecutor<BlogOwner> observeQueryExecutor = new ObserveQueryExecutor<>(subject, mockSqlQueryProcessor, threadPool, mockSyncStatus, new ModelSorter<>(), maxRecords, 1);
    List<QuerySortBy> sortBy = new ArrayList<>();
    sortBy.add(BlogOwner.NAME.descending());
    sortBy.add(BlogOwner.WEA.ascending());
    observeQueryExecutor.observeQuery(BlogOwner.class, new ObserveQueryOptions(null, sortBy), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
    Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
    for (int i = (names.size() / 2) + 1; i < names.size(); i++) {
        BlogOwner itemChange = BlogOwner.builder().name(names.get(i)).wea(weas.get(i)).build();
        owners.add(itemChange);
        try {
            subject.onNext(StorageItemChange.<BlogOwner>builder().changeId(UUID.randomUUID().toString()).initiator(StorageItemChange.Initiator.SYNC_ENGINE).item(itemChange).patchItem(SerializedModel.create(itemChange, ModelSchema.fromModelClass(BlogOwner.class))).modelSchema(ModelSchema.fromModelClass(BlogOwner.class)).predicate(QueryPredicates.all()).type(StorageItemChange.Type.CREATE).build());
        } catch (AmplifyException exception) {
            exception.printStackTrace();
        }
    }
    Assert.assertTrue(changeLatch.await(7, TimeUnit.SECONDS));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) ExecutorService(java.util.concurrent.ExecutorService) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) SerializedModel(com.amplifyframework.core.model.SerializedModel) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Model(com.amplifyframework.core.model.Model) Test(org.junit.Test) Action(com.amplifyframework.core.Action) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Assert(org.junit.Assert) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) AmplifyException(com.amplifyframework.AmplifyException) ArrayList(java.util.ArrayList) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Cancelable(com.amplifyframework.core.async.Cancelable) DataStoreException(com.amplifyframework.datastore.DataStoreException) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model) ExecutorService(java.util.concurrent.ExecutorService) Test(org.junit.Test)

Example 3 with QuerySortBy

use of com.amplifyframework.core.model.query.QuerySortBy in project amplify-android by aws-amplify.

the class SQLiteCommandFactory method queryFor.

@NonNull
@Override
public SqlCommand queryFor(@NonNull ModelSchema modelSchema, @NonNull QueryOptions options) throws DataStoreException {
    final SQLiteTable table = SQLiteTable.fromSchema(modelSchema);
    final String tableName = table.getName();
    StringBuilder rawQuery = new StringBuilder();
    StringBuilder selectColumns = new StringBuilder();
    StringBuilder joinStatement = new StringBuilder();
    final List<Object> bindings = new ArrayList<>();
    // Track the list of columns to return, along with the alias for the corresponding table
    Map<String, List<SQLiteColumn>> columns = new HashMap<>();
    columns.put(table.getName(), table.getSortedColumns());
    Map<String, Integer> tableCount = new HashMap<>();
    tableCount.put(tableName, 1);
    // Joins the foreign keys
    recursivelyBuildJoins(table, columns, joinStatement, tableCount, tableName);
    // Convert columns to comma-separated column names
    boolean firstTable = true;
    for (String tableAlias : columns.keySet()) {
        if (!firstTable) {
            selectColumns.append(",").append(SqlKeyword.DELIMITER);
        } else {
            firstTable = false;
        }
        Iterator<SQLiteColumn> columnsIterator = Objects.requireNonNull(columns.get(tableAlias)).iterator();
        while (columnsIterator.hasNext()) {
            final SQLiteColumn column = columnsIterator.next();
            String columnName = column.getQuotedColumnName().replace(column.getTableName(), tableAlias);
            selectColumns.append(columnName);
            // Alias columns with a unique alias to avoid duplicate column names or alias names
            String columnAlias = column.getAliasedName() + tableAlias.substring(column.getTableName().length());
            selectColumns.append(SqlKeyword.DELIMITER).append(SqlKeyword.AS).append(SqlKeyword.DELIMITER).append(Wrap.inBackticks(columnAlias));
            if (columnsIterator.hasNext()) {
                selectColumns.append(",").append(SqlKeyword.DELIMITER);
            }
        }
    }
    // Start SELECT statement.
    // SELECT columns FROM tableName
    rawQuery.append(SqlKeyword.SELECT).append(SqlKeyword.DELIMITER).append(selectColumns.toString()).append(SqlKeyword.DELIMITER).append(SqlKeyword.FROM).append(SqlKeyword.DELIMITER).append(Wrap.inBackticks(tableName));
    // LEFT JOIN tableTwo ON tableName.id=tableTwo.foreignKey
    if (!joinStatement.toString().isEmpty()) {
        rawQuery.append(SqlKeyword.DELIMITER).append(joinStatement.toString());
    }
    // Append predicates.
    // WHERE condition
    final QueryPredicate predicate = options.getQueryPredicate();
    if (!QueryPredicates.all().equals(predicate)) {
        final SQLPredicate sqlPredicate = new SQLPredicate(predicate);
        bindings.addAll(sqlPredicate.getBindings());
        String sqlPredicateString = sqlPredicate.toString();
        if (predicate instanceof QueryPredicateOperation) {
            QueryPredicateOperation<?> predicateOperation = (QueryPredicateOperation<?>) predicate;
            String predicateOperationField = predicateOperation.field();
            if (predicateOperationField.equals(PrimaryKey.fieldName()) && predicateOperation.modelName() == null && predicateOperation.operator().type() == QueryOperator.Type.EQUAL) {
                // The WHERE condition is Where.id("some-ID") but no model name is given.
                sqlPredicateString = sqlPredicateString.replace(predicateOperationField, tableName + "." + predicateOperationField);
            }
        }
        rawQuery.append(SqlKeyword.DELIMITER).append(SqlKeyword.WHERE).append(SqlKeyword.DELIMITER).append(sqlPredicateString);
    }
    // Append order by
    final List<QuerySortBy> sortByList = options.getSortBy();
    if (sortByList != null) {
        rawQuery.append(SqlKeyword.DELIMITER).append(SqlKeyword.ORDER_BY).append(SqlKeyword.DELIMITER);
        Iterator<QuerySortBy> sortByIterator = sortByList.iterator();
        while (sortByIterator.hasNext()) {
            final QuerySortBy sortBy = sortByIterator.next();
            String modelName = Wrap.inBackticks(sortBy.getModelName());
            String fieldName = Wrap.inBackticks(sortBy.getField());
            if (modelName == null) {
                modelName = Wrap.inBackticks(tableName);
            }
            final String columnName = modelName + "." + fieldName;
            rawQuery.append(columnName).append(SqlKeyword.DELIMITER).append(SqlKeyword.fromQuerySortOrder(sortBy.getSortOrder()));
            if (sortByIterator.hasNext()) {
                rawQuery.append(",").append(SqlKeyword.DELIMITER);
            }
        }
    }
    // Append pagination after order by
    final QueryPaginationInput paginationInput = options.getPaginationInput();
    if (paginationInput != null) {
        rawQuery.append(SqlKeyword.DELIMITER).append(SqlKeyword.LIMIT).append(SqlKeyword.DELIMITER).append("?").append(SqlKeyword.DELIMITER).append(SqlKeyword.OFFSET).append(SqlKeyword.DELIMITER).append("?");
        bindings.add(paginationInput.getLimit());
        bindings.add(paginationInput.getPage() * paginationInput.getLimit());
    }
    rawQuery.append(";");
    final String queryString = rawQuery.toString();
    return new SqlCommand(table.getName(), queryString, bindings);
}
Also used : QueryPredicateOperation(com.amplifyframework.core.model.query.predicate.QueryPredicateOperation) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) SQLPredicate(com.amplifyframework.datastore.storage.sqlite.adapter.SQLPredicate) SQLiteColumn(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn) QueryPaginationInput(com.amplifyframework.core.model.query.QueryPaginationInput) ArrayList(java.util.ArrayList) List(java.util.List) NonNull(androidx.annotation.NonNull)

Example 4 with QuerySortBy

use of com.amplifyframework.core.model.query.QuerySortBy in project amplify-android by aws-amplify.

the class SQLiteStorageAdapterObserveQueryTest method queryWithOrderByRelatedModel.

/**
 * Test query with order by.  Validate that a list of Blog can be sorted by the names of BlogOwners.
 *
 * @throws DataStoreException On failure to arrange items into store, or from the query action itself.
 * @throws InterruptedException InterruptedException.
 */
@Test
public void queryWithOrderByRelatedModel() throws DataStoreException, InterruptedException {
    // Expect: Create BlogOwners and their respective blogs
    List<String> names = Arrays.asList("Joe", "Bob", "Dan", "Jane");
    List<Blog> blogs = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    for (String name : names) {
        BlogOwner owner = BlogOwner.builder().name(name).build();
        adapter.save(owner);
        Blog blog = Blog.builder().name("").owner(owner).build();
        adapter.save(blog);
        blogs.add(blog);
    }
    List<Blog> sorted = new ArrayList<>(blogs);
    Collections.sort(sorted, Comparator.comparing(blog -> blog.getOwner().getName()));
    Consumer<Cancelable> observationStarted = NoOpConsumer.create();
    Consumer<DataStoreQuerySnapshot<Blog>> onQuerySnapshot = value -> {
        assertEquals(sorted, value.getItems());
        latch.countDown();
    };
    Consumer<DataStoreException> onObservationError = NoOpConsumer.create();
    Action onObservationComplete = NoOpAction.create();
    List<QuerySortBy> sortBy = new ArrayList<>();
    sortBy.add(BlogOwner.NAME.ascending());
    // Act: Query Blogs sorted by owner's name
    adapter.observeQuery(Blog.class, new ObserveQueryOptions(null, sortBy), observationStarted, onQuerySnapshot, onObservationError, onObservationComplete);
    // assert
    assertTrue(latch.await(30, TimeUnit.SECONDS));
}
Also used : Arrays(java.util.Arrays) BeforeClass(org.junit.BeforeClass) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) Blog(com.amplifyframework.testmodels.commentsblog.Blog) ArrayList(java.util.ArrayList) SynchronousStorageAdapter(com.amplifyframework.datastore.storage.SynchronousStorageAdapter) HashSet(java.util.HashSet) Consumer(com.amplifyframework.core.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) NoOpConsumer(com.amplifyframework.core.NoOpConsumer) PostStatus(com.amplifyframework.testmodels.commentsblog.PostStatus) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) Before(org.junit.Before) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Comment(com.amplifyframework.testmodels.commentsblog.Comment) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Action(com.amplifyframework.core.Action) StrictMode(com.amplifyframework.datastore.StrictMode) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) Assert.assertFalse(org.junit.Assert.assertFalse) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Comparator(java.util.Comparator) NoOpAction(com.amplifyframework.core.NoOpAction) AmplifyModelProvider(com.amplifyframework.testmodels.commentsblog.AmplifyModelProvider) Post(com.amplifyframework.testmodels.commentsblog.Post) Collections(java.util.Collections) QueryPredicate.not(com.amplifyframework.core.model.query.predicate.QueryPredicate.not) Assert.assertEquals(org.junit.Assert.assertEquals) DataStoreException(com.amplifyframework.datastore.DataStoreException) Action(com.amplifyframework.core.Action) NoOpAction(com.amplifyframework.core.NoOpAction) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) BlogOwner(com.amplifyframework.testmodels.commentsblog.BlogOwner) Blog(com.amplifyframework.testmodels.commentsblog.Blog) Cancelable(com.amplifyframework.core.async.Cancelable) Test(org.junit.Test)

Example 5 with QuerySortBy

use of com.amplifyframework.core.model.query.QuerySortBy in project amplify-android by aws-amplify.

the class SqlCommandTest method queryWithSortBy.

/**
 * Validates that a query, with an order by clause is generated correctly.
 * @throws DataStoreException From {@link SQLCommandFactory#queryFor(ModelSchema, QueryOptions)}
 */
@Test
public void queryWithSortBy() throws DataStoreException {
    final ModelSchema personSchema = getPersonModelSchema();
    final SqlCommand sqlCommand = sqlCommandFactory.queryFor(personSchema, Where.matchesAll().sorted(new QuerySortBy("lastName", QuerySortOrder.ASCENDING), new QuerySortBy("firstName", QuerySortOrder.DESCENDING)));
    assertNotNull(sqlCommand);
    assertEquals(PERSON_BASE_QUERY + " ORDER BY `Person`.`lastName` ASC, `Person`.`firstName` DESC;", sqlCommand.sqlStatement());
    assertEquals(0, sqlCommand.getBindings().size());
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) QuerySortBy(com.amplifyframework.core.model.query.QuerySortBy) Test(org.junit.Test)

Aggregations

QuerySortBy (com.amplifyframework.core.model.query.QuerySortBy)8 ArrayList (java.util.ArrayList)6 Test (org.junit.Test)6 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)5 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)5 List (java.util.List)5 Action (com.amplifyframework.core.Action)4 Consumer (com.amplifyframework.core.Consumer)4 NoOpAction (com.amplifyframework.core.NoOpAction)4 NoOpConsumer (com.amplifyframework.core.NoOpConsumer)4 Cancelable (com.amplifyframework.core.async.Cancelable)4 DataStoreException (com.amplifyframework.datastore.DataStoreException)4 DataStoreQuerySnapshot (com.amplifyframework.datastore.DataStoreQuerySnapshot)4 Post (com.amplifyframework.testmodels.commentsblog.Post)4 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)4 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 Comparator (java.util.Comparator)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 TimeUnit (java.util.concurrent.TimeUnit)4