Search in sources :

Example 1 with SQLiteTable

use of com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable in project amplify-android by aws-amplify.

the class SQLiteStorageAdapter method modelExists.

private boolean modelExists(Model model, QueryPredicate predicate) throws DataStoreException {
    final String modelName = model.getModelName();
    final ModelSchema schema = schemaRegistry.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 2 with SQLiteTable

use of com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable in project amplify-android by aws-amplify.

the class SQLiteStorageAdapter method query.

/**
 * Helper method to synchronously query for a single model instance.  Used before any save initiated by
 * DATASTORE_API in order to determine which fields have changed.
 * @param model a Model that we want to query for the same type and id in SQLite.
 * @return the Model instance from SQLite, if it exists, otherwise null.
 */
private Model query(Model model) {
    final String modelName = model.getModelName();
    final ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(modelName);
    final SQLiteTable table = SQLiteTable.fromSchema(schema);
    final String primaryKeyName = table.getPrimaryKey().getName();
    final QueryPredicate matchId = QueryField.field(modelName, primaryKeyName).eq(model.getId());
    Iterator<? extends Model> result = Single.<Iterator<? extends Model>>create(emitter -> {
        if (model instanceof SerializedModel) {
            query(model.getModelName(), Where.matches(matchId), emitter::onSuccess, emitter::onError);
        } else {
            query(model.getClass(), Where.matches(matchId), emitter::onSuccess, emitter::onError);
        }
    }).blockingGet();
    return result.hasNext() ? result.next() : null;
}
Also used : ObjectsCompat(androidx.core.util.ObjectsCompat) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) ModelProvider(com.amplifyframework.core.model.ModelProvider) StorageItemChange(com.amplifyframework.datastore.storage.StorageItemChange) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Gson(com.google.gson.Gson) Map(java.util.Map) PublishSubject(io.reactivex.rxjava3.subjects.PublishSubject) QueryOptions(com.amplifyframework.core.model.query.QueryOptions) CustomTypeSchema(com.amplifyframework.core.model.CustomTypeSchema) SerializedModel(com.amplifyframework.core.model.SerializedModel) Immutable(com.amplifyframework.util.Immutable) Set(java.util.Set) Executors(java.util.concurrent.Executors) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) DataStoreException(com.amplifyframework.datastore.DataStoreException) LocalStorageAdapter(com.amplifyframework.datastore.storage.LocalStorageAdapter) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) Disposable(io.reactivex.rxjava3.disposables.Disposable) Context(android.content.Context) SerializedCustomType(com.amplifyframework.core.model.SerializedCustomType) QueryField(com.amplifyframework.core.model.query.predicate.QueryField) Single(io.reactivex.rxjava3.core.Single) ObserveQueryOptions(com.amplifyframework.core.model.query.ObserveQueryOptions) SystemModelsProviderFactory(com.amplifyframework.datastore.model.SystemModelsProviderFactory) HashMap(java.util.HashMap) CustomTypeField(com.amplifyframework.core.model.CustomTypeField) ModelField(com.amplifyframework.core.model.ModelField) ArrayList(java.util.ArrayList) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) GsonFactory(com.amplifyframework.util.GsonFactory) HashSet(java.util.HashSet) Consumer(com.amplifyframework.core.Consumer) CompositeDisposable(io.reactivex.rxjava3.disposables.CompositeDisposable) ModelSchema(com.amplifyframework.core.model.ModelSchema) Subject(io.reactivex.rxjava3.subjects.Subject) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) ExecutorService(java.util.concurrent.ExecutorService) Cursor(android.database.Cursor) DataStoreQuerySnapshot(com.amplifyframework.datastore.DataStoreQuerySnapshot) DataStoreConfiguration(com.amplifyframework.datastore.DataStoreConfiguration) Amplify(com.amplifyframework.core.Amplify) CompoundModelProvider(com.amplifyframework.datastore.model.CompoundModelProvider) Iterator(java.util.Iterator) Model(com.amplifyframework.core.model.Model) Completable(io.reactivex.rxjava3.core.Completable) Action(com.amplifyframework.core.Action) Where(com.amplifyframework.core.model.query.Where) ModelAssociation(com.amplifyframework.core.model.ModelAssociation) TimeUnit(java.util.concurrent.TimeUnit) ModelMigrations(com.amplifyframework.datastore.storage.sqlite.migrations.ModelMigrations) VisibleForTesting(androidx.annotation.VisibleForTesting) Collections(java.util.Collections) ModelSchema(com.amplifyframework.core.model.ModelSchema) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) SerializedModel(com.amplifyframework.core.model.SerializedModel)

Example 3 with SQLiteTable

use of com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable 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 4 with SQLiteTable

use of com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable 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 5 with SQLiteTable

use of com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable in project amplify-android by aws-amplify.

the class SQLiteCommandFactory method createTableFor.

@NonNull
@Override
public SqlCommand createTableFor(@NonNull ModelSchema modelSchema) {
    final SQLiteTable table = SQLiteTable.fromSchema(modelSchema);
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("CREATE TABLE IF NOT EXISTS").append(SqlKeyword.DELIMITER).append(Wrap.inBackticks(table.getName())).append(SqlKeyword.DELIMITER);
    if (Empty.check(table.getColumns())) {
        return new SqlCommand(table.getName(), stringBuilder.toString());
    }
    stringBuilder.append("(").append(parseColumns(table));
    if (!table.getForeignKeys().isEmpty()) {
        stringBuilder.append(",").append(SqlKeyword.DELIMITER).append(parseForeignKeys(table));
    }
    stringBuilder.append(");");
    final String createSqlStatement = stringBuilder.toString();
    return new SqlCommand(table.getName(), createSqlStatement);
}
Also used : SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) NonNull(androidx.annotation.NonNull)

Aggregations

SQLiteTable (com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable)15 NonNull (androidx.annotation.NonNull)8 ModelSchema (com.amplifyframework.core.model.ModelSchema)8 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)6 SQLiteColumn (com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn)5 ArrayList (java.util.ArrayList)5 SQLPredicate (com.amplifyframework.datastore.storage.sqlite.adapter.SQLPredicate)4 Cursor (android.database.Cursor)3 DataStoreException (com.amplifyframework.datastore.DataStoreException)3 AmplifyException (com.amplifyframework.AmplifyException)2 Model (com.amplifyframework.core.model.Model)2 ModelAssociation (com.amplifyframework.core.model.ModelAssociation)2 ModelField (com.amplifyframework.core.model.ModelField)2 SerializedModel (com.amplifyframework.core.model.SerializedModel)2 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)2 QueryOptions (com.amplifyframework.core.model.query.QueryOptions)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Context (android.content.Context)1