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