Search in sources :

Example 31 with ModelSchema

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

the class SQLiteStorageAdapter method delete.

/**
 * {@inheritDoc}
 */
@Override
public <T extends Model> void delete(@NonNull Class<T> itemClass, @NonNull StorageItemChange.Initiator initiator, @NonNull QueryPredicate predicate, @NonNull Action onSuccess, @NonNull Consumer<DataStoreException> onError) {
    Objects.requireNonNull(itemClass);
    Objects.requireNonNull(initiator);
    Objects.requireNonNull(predicate);
    Objects.requireNonNull(onSuccess);
    Objects.requireNonNull(onError);
    threadPool.submit(() -> {
        final ModelSchema modelSchema = schemaRegistry.getModelSchemaForModelClass(itemClass);
        QueryOptions options = Where.matches(predicate);
        try (Cursor cursor = sqlCommandProcessor.rawQuery(sqlCommandFactory.queryFor(modelSchema, options))) {
            final SQLiteTable sqliteTable = SQLiteTable.fromSchema(modelSchema);
            final String primaryKeyName = sqliteTable.getPrimaryKey().getAliasedName();
            // identify items that meet the predicate
            List<T> items = new ArrayList<>();
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(primaryKeyName);
                do {
                    String id = cursor.getString(index);
                    String dummyJson = gson.toJson(Collections.singletonMap("id", id));
                    T dummyItem = gson.fromJson(dummyJson, itemClass);
                    items.add(dummyItem);
                } while (cursor.moveToNext());
            }
            // identify every model to delete as a result of this operation
            List<Model> modelsToDelete = new ArrayList<>(items);
            List<Model> cascadedModels = sqliteModelTree.descendantsOf(items);
            modelsToDelete.addAll(cascadedModels);
            // execute local deletions
            sqlCommandProcessor.execute(sqlCommandFactory.deleteFor(modelSchema, predicate));
            // publish every deletion
            for (Model model : modelsToDelete) {
                ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(model.getModelName());
                itemChangeSubject.onNext(StorageItemChange.builder().item(model).patchItem(SerializedModel.create(model, schema)).modelSchema(schema).type(StorageItemChange.Type.DELETE).predicate(QueryPredicates.all()).initiator(initiator).build());
            }
            onSuccess.call();
        } catch (DataStoreException dataStoreException) {
            onError.accept(dataStoreException);
        } catch (Exception someOtherTypeOfException) {
            DataStoreException dataStoreException = new DataStoreException("Error in deleting models.", someOtherTypeOfException, "See attached exception for details.");
            onError.accept(dataStoreException);
        }
    });
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) ArrayList(java.util.ArrayList) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) Cursor(android.database.Cursor) QueryOptions(com.amplifyframework.core.model.query.QueryOptions) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) AmplifyException(com.amplifyframework.AmplifyException) DataStoreException(com.amplifyframework.datastore.DataStoreException) ModelSchema(com.amplifyframework.core.model.ModelSchema) SerializedModel(com.amplifyframework.core.model.SerializedModel) Model(com.amplifyframework.core.model.Model)

Example 32 with ModelSchema

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

the class SqlQueryProcessor method modelExists.

boolean modelExists(Model model, QueryPredicate predicate) throws DataStoreException {
    final String modelName = model.getModelName();
    final ModelSchema schema = modelSchemaRegistry.getModelSchemaForModelClass(modelName);
    final SQLiteTable table = SQLiteTable.fromSchema(schema);
    final String tableName = table.getName();
    final String primaryKeyName = table.getPrimaryKey().getName();
    final QueryPredicate matchId = QueryField.field(tableName, primaryKeyName).eq(model.getId());
    final QueryPredicate condition = predicate.and(matchId);
    return sqlCommandProcessor.executeExists(sqlCommandFactory.existsFor(schema, condition));
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable)

Example 33 with ModelSchema

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

the class AppSyncRequestFactoryTest method validateDeleteWithPredicateGeneration.

/**
 * Checks that we're getting the expected output for a mutation with predicate.
 * @throws DataStoreException If the output does not match.
 * @throws AmplifyException On failure to parse ModelSchema from model class
 * @throws JSONException from JSONAssert.assertEquals.
 */
@Test
public void validateDeleteWithPredicateGeneration() throws AmplifyException, JSONException {
    ModelSchema schema = ModelSchema.fromModelClass(Person.class);
    Person person = Person.justId("17521540-ccaa-4357-a622-34c42d8cfa24");
    JSONAssert.assertEquals(Resources.readAsString("delete-person-with-predicate.txt"), AppSyncRequestFactory.buildDeletionRequest(schema, person, 456, Person.AGE.gt(40), DEFAULT_STRATEGY).getContent(), true);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) Person(com.amplifyframework.testmodels.personcar.Person) Test(org.junit.Test)

Example 34 with ModelSchema

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

the class AppSyncRequestFactoryTest method validateSubscriptionGenerationOnCreateBlog.

/**
 * Validates that a GraphQL request document can be created, to get onCreate
 * subscription notifications for a Blog.class.
 * @throws DataStoreException On failure to interrogate the Blog.class.
 * @throws AmplifyException On failure to parse ModelSchema from model class
 * @throws JSONException from JSONAssert.assertEquals.
 */
@Test
public void validateSubscriptionGenerationOnCreateBlog() throws AmplifyException, JSONException {
    ModelSchema schema = ModelSchema.fromModelClass(Blog.class);
    JSONAssert.assertEquals(Resources.readAsString("on-create-request-for-blog.txt"), AppSyncRequestFactory.buildSubscriptionRequest(schema, SubscriptionType.ON_CREATE, DEFAULT_STRATEGY).getContent(), true);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) Test(org.junit.Test)

Example 35 with ModelSchema

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

the class AppSyncRequestFactoryTest method validateSubscriptionGenerationOnDeleteBlogOwner.

/**
 * Validates generation of a GraphQL document which requests a subscription for deletes.
 * for the BlogOwner.class.
 * @throws DataStoreException On failure to interrogate the fields in BlogOwner.class.
 * @throws AmplifyException On failure to parse ModelSchema from model class
 * @throws JSONException from JSONAssert.assertEquals.
 */
@Test
public void validateSubscriptionGenerationOnDeleteBlogOwner() throws AmplifyException, JSONException {
    ModelSchema schema = ModelSchema.fromModelClass(BlogOwner.class);
    JSONAssert.assertEquals(Resources.readAsString("on-delete-request-for-blog-owner.txt"), AppSyncRequestFactory.buildSubscriptionRequest(schema, SubscriptionType.ON_DELETE, DEFAULT_STRATEGY).getContent(), true);
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) Test(org.junit.Test)

Aggregations

ModelSchema (com.amplifyframework.core.model.ModelSchema)109 Test (org.junit.Test)69 SerializedModel (com.amplifyframework.core.model.SerializedModel)34 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)30 Model (com.amplifyframework.core.model.Model)28 DataStoreException (com.amplifyframework.datastore.DataStoreException)26 HashMap (java.util.HashMap)23 ArrayList (java.util.ArrayList)22 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)21 AmplifyException (com.amplifyframework.AmplifyException)19 Consumer (com.amplifyframework.core.Consumer)19 List (java.util.List)17 NonNull (androidx.annotation.NonNull)14 Cancelable (com.amplifyframework.core.async.Cancelable)14 TimeUnit (java.util.concurrent.TimeUnit)14 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)13 Action (com.amplifyframework.core.Action)12 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)12 Collections (java.util.Collections)12 ModelProvider (com.amplifyframework.core.model.ModelProvider)11