Search in sources :

Example 6 with SQLiteTable

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

the class SQLiteCommandFactory method deleteFor.

@NonNull
@Override
public SqlCommand deleteFor(@NonNull ModelSchema modelSchema, @NonNull QueryPredicate predicate) throws DataStoreException {
    final SQLiteTable table = SQLiteTable.fromSchema(modelSchema);
    final SQLPredicate sqlPredicate = new SQLPredicate(predicate);
    final String preparedDeleteStatement = "DELETE FROM" + SqlKeyword.DELIMITER + Wrap.inBackticks(table.getName()) + SqlKeyword.DELIMITER + SqlKeyword.WHERE + SqlKeyword.DELIMITER + sqlPredicate + ";";
    return new SqlCommand(table.getName(), preparedDeleteStatement, // WHERE clause
    sqlPredicate.getBindings());
}
Also used : SQLPredicate(com.amplifyframework.datastore.storage.sqlite.adapter.SQLPredicate) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) NonNull(androidx.annotation.NonNull)

Example 7 with SQLiteTable

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

the class SQLiteCommandFactory method updateFor.

@NonNull
@Override
public <T extends Model> SqlCommand updateFor(@NonNull ModelSchema modelSchema, @NonNull T model) throws DataStoreException {
    final SQLiteTable table = SQLiteTable.fromSchema(modelSchema);
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("UPDATE").append(SqlKeyword.DELIMITER).append(Wrap.inBackticks(table.getName())).append(SqlKeyword.DELIMITER).append("SET").append(SqlKeyword.DELIMITER);
    // Previously, we figured out the correct column names from the model schema.
    // Instead of figuring out the correct column names again, just iterate
    // over whatever is actually there (since it was "right".)
    final List<SQLiteColumn> columns = table.getSortedColumns();
    final Iterator<SQLiteColumn> columnsIterator = columns.iterator();
    while (columnsIterator.hasNext()) {
        final String columnName = columnsIterator.next().getName();
        stringBuilder.append(Wrap.inBackticks(columnName)).append(SqlKeyword.DELIMITER).append(SqlKeyword.EQUAL).append(SqlKeyword.DELIMITER).append("?");
        if (columnsIterator.hasNext()) {
            stringBuilder.append(", ");
        }
    }
    // Append WHERE statement
    final SQLiteTable sqliteTable = SQLiteTable.fromSchema(modelSchema);
    final String primaryKeyName = sqliteTable.getPrimaryKeyColumnName();
    final QueryPredicate matchId = QueryField.field(primaryKeyName).eq(model.getId());
    SQLPredicate sqlPredicate = new SQLPredicate(matchId);
    stringBuilder.append(SqlKeyword.DELIMITER).append(SqlKeyword.WHERE).append(SqlKeyword.DELIMITER).append(sqlPredicate).append(";");
    final String preparedUpdateStatement = stringBuilder.toString();
    // SET clause
    List<Object> bindings = extractFieldValues(model);
    // WHERE clause
    bindings.addAll(sqlPredicate.getBindings());
    return new SqlCommand(table.getName(), preparedUpdateStatement, bindings);
}
Also used : SQLPredicate(com.amplifyframework.datastore.storage.sqlite.adapter.SQLPredicate) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) SQLiteColumn(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) NonNull(androidx.annotation.NonNull)

Example 8 with SQLiteTable

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

the class SQLiteCommandFactory method existsFor.

@NonNull
@Override
public SqlCommand existsFor(@NonNull ModelSchema modelSchema, @NonNull QueryPredicate predicate) throws DataStoreException {
    final SQLiteTable table = SQLiteTable.fromSchema(modelSchema);
    final String tableName = table.getName();
    StringBuilder rawQuery = new StringBuilder();
    final List<Object> bindings = new ArrayList<>();
    // Start SELECT statement.
    // SELECT EXISTS(SELECT 1 FROM tableName
    rawQuery.append(SqlKeyword.SELECT).append(SqlKeyword.DELIMITER).append(SqlKeyword.EXISTS).append("(").append(SqlKeyword.SELECT).append(SqlKeyword.DELIMITER).append("1").append(SqlKeyword.DELIMITER).append(SqlKeyword.FROM).append(SqlKeyword.DELIMITER).append(Wrap.inBackticks(tableName));
    // WHERE condition
    if (!QueryPredicates.all().equals(predicate)) {
        final SQLPredicate sqlPredicate = new SQLPredicate(predicate);
        bindings.addAll(sqlPredicate.getBindings());
        rawQuery.append(SqlKeyword.DELIMITER).append(SqlKeyword.WHERE).append(SqlKeyword.DELIMITER).append(sqlPredicate);
    }
    // Close the parentheses for EXISTS, and end with a semicolon.
    rawQuery.append(");");
    final String queryString = rawQuery.toString();
    return new SqlCommand(table.getName(), queryString, bindings);
}
Also used : SQLPredicate(com.amplifyframework.datastore.storage.sqlite.adapter.SQLPredicate) ArrayList(java.util.ArrayList) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable) NonNull(androidx.annotation.NonNull)

Example 9 with SQLiteTable

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

the class SQLiteCommandFactory method extractFieldValues.

// extract model field values to save in database
private List<Object> extractFieldValues(@NonNull Model model) throws DataStoreException {
    final String modelName = model.getModelName();
    final ModelSchema schema = schemaRegistry.getModelSchemaForModelClass(modelName);
    final SQLiteTable table = SQLiteTable.fromSchema(schema);
    final SQLiteModelFieldTypeConverter converter = new SQLiteModelFieldTypeConverter(schema, schemaRegistry, gson);
    final Map<String, ModelField> modelFields = schema.getFields();
    final List<Object> bindings = new ArrayList<>();
    for (SQLiteColumn column : table.getSortedColumns()) {
        final ModelField modelField = Objects.requireNonNull(modelFields.get(column.getFieldName()));
        final Object fieldValue = converter.convertValueFromTarget(model, modelField);
        bindings.add(fieldValue);
    }
    return bindings;
}
Also used : ModelSchema(com.amplifyframework.core.model.ModelSchema) ModelField(com.amplifyframework.core.model.ModelField) SQLiteColumn(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn) ArrayList(java.util.ArrayList) SQLiteTable(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable)

Example 10 with SQLiteTable

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

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