Search in sources :

Example 1 with SQLiteColumn

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

the class SQLiteCommandFactory method parseForeignKeys.

// Utility method to parse foreign key references in CREATE TABLE
// Maintains groupings
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private StringBuilder parseForeignKeys(SQLiteTable table) {
    final StringBuilder builder = new StringBuilder();
    final Iterator<SQLiteColumn> foreignKeyIterator = table.getForeignKeys().iterator();
    while (foreignKeyIterator.hasNext()) {
        final SQLiteColumn foreignKey = foreignKeyIterator.next();
        String connectedName = foreignKey.getName();
        String connectedType = foreignKey.getOwnedType();
        String connectedId = PrimaryKey.fieldName();
        builder.append("FOREIGN KEY").append(SqlKeyword.DELIMITER).append("(" + Wrap.inBackticks(connectedName) + ")").append(SqlKeyword.DELIMITER).append("REFERENCES").append(SqlKeyword.DELIMITER).append(Wrap.inBackticks(connectedType)).append("(" + Wrap.inBackticks(connectedId) + ")").append(SqlKeyword.DELIMITER).append("ON DELETE CASCADE");
        if (foreignKeyIterator.hasNext()) {
            builder.append(",").append(SqlKeyword.DELIMITER);
        }
    }
    return builder;
}
Also used : SQLiteColumn(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn)

Example 2 with SQLiteColumn

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

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

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

the class SQLiteCommandFactory method parseColumns.

// Utility method to parse columns in CREATE TABLE
private StringBuilder parseColumns(SQLiteTable table) {
    final StringBuilder builder = new StringBuilder();
    final Iterator<SQLiteColumn> columnsIterator = table.getSortedColumns().iterator();
    while (columnsIterator.hasNext()) {
        final SQLiteColumn column = columnsIterator.next();
        final String columnName = column.getName();
        builder.append(Wrap.inBackticks(columnName)).append(SqlKeyword.DELIMITER).append(column.getColumnType());
        if (column.isPrimaryKey()) {
            builder.append(SqlKeyword.DELIMITER).append("PRIMARY KEY");
        }
        if (column.isNonNull()) {
            builder.append(SqlKeyword.DELIMITER).append("NOT NULL");
        }
        if (columnsIterator.hasNext()) {
            builder.append(",").append(SqlKeyword.DELIMITER);
        }
    }
    return builder;
}
Also used : SQLiteColumn(com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn)

Example 5 with SQLiteColumn

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

SQLiteColumn (com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteColumn)8 SQLiteTable (com.amplifyframework.datastore.storage.sqlite.adapter.SQLiteTable)5 NonNull (androidx.annotation.NonNull)3 ModelSchema (com.amplifyframework.core.model.ModelSchema)2 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)2 SQLPredicate (com.amplifyframework.datastore.storage.sqlite.adapter.SQLPredicate)2 ArrayList (java.util.ArrayList)2 AmplifyException (com.amplifyframework.AmplifyException)1 ModelField (com.amplifyframework.core.model.ModelField)1 QueryPaginationInput (com.amplifyframework.core.model.query.QueryPaginationInput)1 QuerySortBy (com.amplifyframework.core.model.query.QuerySortBy)1 QueryPredicateOperation (com.amplifyframework.core.model.query.predicate.QueryPredicateOperation)1 JavaFieldType (com.amplifyframework.core.model.types.JavaFieldType)1 DataStoreException (com.amplifyframework.datastore.DataStoreException)1 IOException (java.io.IOException)1 LocalTime (java.time.LocalTime)1 OffsetDateTime (java.time.OffsetDateTime)1 OffsetTime (java.time.OffsetTime)1 HashMap (java.util.HashMap)1 List (java.util.List)1