Search in sources :

Example 1 with BindingParameter

use of io.micronaut.data.model.query.BindingParameter in project micronaut-data by micronaut-projects.

the class MongoQueryBuilder method buildUpdate.

@Override
public QueryResult buildUpdate(AnnotationMetadata annotationMetadata, QueryModel query, Map<String, Object> propertiesToUpdate) {
    ArgumentUtils.requireNonNull("annotationMetadata", annotationMetadata);
    ArgumentUtils.requireNonNull("query", query);
    ArgumentUtils.requireNonNull("propertiesToUpdate", propertiesToUpdate);
    QueryState queryState = new QueryState(query, true);
    QueryModel.Junction criteria = query.getCriteria();
    String predicateQuery = "";
    if (!criteria.isEmpty()) {
        Map<String, Object> predicate = buildWhereClause(annotationMetadata, criteria, queryState);
        predicateQuery = toJsonString(predicate);
    }
    Map<String, Object> sets = new LinkedHashMap<>();
    for (Map.Entry<String, Object> e : propertiesToUpdate.entrySet()) {
        if (e.getValue() instanceof BindingParameter) {
            PersistentPropertyPath propertyPath = findProperty(queryState, e.getKey(), null);
            int index = queryState.pushParameter((BindingParameter) e.getValue(), newBindingContext(propertyPath));
            sets.put(e.getKey(), singletonMap(QUERY_PARAMETER_PLACEHOLDER, index));
        } else {
            sets.put(e.getKey(), e.getValue());
        }
    }
    String update = toJsonString(singletonMap("$set", sets));
    String finalPredicateQuery = predicateQuery;
    return new QueryResult() {

        @NonNull
        @Override
        public String getQuery() {
            return finalPredicateQuery;
        }

        @Override
        public String getUpdate() {
            return update;
        }

        @Override
        public List<String> getQueryParts() {
            return Collections.emptyList();
        }

        @Override
        public List<QueryParameterBinding> getParameterBindings() {
            return queryState.getParameterBindings();
        }

        @Override
        public Map<String, String> getAdditionalRequiredParameters() {
            return Collections.emptyMap();
        }
    };
}
Also used : QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) QueryModel(io.micronaut.data.model.query.QueryModel) LinkedHashMap(java.util.LinkedHashMap) QueryResult(io.micronaut.data.model.query.builder.QueryResult) BindingParameter(io.micronaut.data.model.query.BindingParameter) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Collections.singletonMap(java.util.Collections.singletonMap)

Example 2 with BindingParameter

use of io.micronaut.data.model.query.BindingParameter in project micronaut-data by micronaut-projects.

the class AbstractSqlLikeQueryBuilder method appendCriteriaForOperator.

private void appendCriteriaForOperator(StringBuilder whereClause, PropertyParameterCreator propertyParameterCreator, PersistentPropertyPath parameterPropertyPath, QueryPropertyPath propertyPath, Object value, String operator) {
    if (value instanceof BindingParameter) {
        BindingParameter bindingParameter = (BindingParameter) value;
        boolean computePropertyPaths = computePropertyPaths();
        if (!computePropertyPaths) {
            appendPropertyRef(whereClause, propertyPath);
            whereClause.append(operator);
            propertyParameterCreator.pushParameter(bindingParameter, newBindingContext(parameterPropertyPath, propertyPath.propertyPath));
            return;
        }
        String currentAlias = propertyPath.getTableAlias();
        NamingStrategy namingStrategy = propertyPath.getNamingStrategy();
        boolean shouldEscape = propertyPath.shouldEscape();
        int length = whereClause.length();
        traversePersistentProperties(propertyPath.getAssociations(), propertyPath.getProperty(), (associations, property) -> {
            String readTransformer = getDataTransformerReadValue(currentAlias, property).orElse(null);
            if (readTransformer != null) {
                whereClause.append(readTransformer);
            } else {
                if (currentAlias != null) {
                    whereClause.append(currentAlias).append(DOT);
                }
                String columnName = namingStrategy.mappedName(associations, property);
                if (shouldEscape) {
                    columnName = quote(columnName);
                }
                whereClause.append(columnName);
            }
            whereClause.append(operator);
            propertyParameterCreator.pushParameter(bindingParameter, newBindingContext(parameterPropertyPath, PersistentPropertyPath.of(associations, property)));
            whereClause.append(LOGICAL_AND);
        });
        int newLength = whereClause.length();
        if (newLength != length) {
            whereClause.setLength(newLength - LOGICAL_AND.length());
        }
    } else {
        appendPropertyRef(whereClause, propertyPath);
        whereClause.append(operator).append(asLiteral(value));
    }
}
Also used : NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) BindingParameter(io.micronaut.data.model.query.BindingParameter)

Example 3 with BindingParameter

use of io.micronaut.data.model.query.BindingParameter in project micronaut-data by micronaut-projects.

the class AbstractSqlLikeQueryBuilder method buildUpdateStatement.

private void buildUpdateStatement(QueryState queryState, Map<String, Object> propertiesToUpdate) {
    StringBuilder queryString = queryState.getQuery();
    queryString.append(SPACE).append("SET").append(SPACE);
    // keys need to be sorted before query is built
    List<Map.Entry<QueryPropertyPath, Object>> update = propertiesToUpdate.entrySet().stream().map(e -> {
        QueryPropertyPath propertyPath = findProperty(queryState, e.getKey(), null);
        if (propertyPath.getProperty() instanceof Association && ((Association) propertyPath.getProperty()).isForeignKey()) {
            throw new IllegalArgumentException("Foreign key associations cannot be updated as part of a batch update statement");
        }
        return new AbstractMap.SimpleEntry<>(propertyPath, e.getValue());
    }).filter(e -> !(e.getValue() instanceof QueryParameter) || !e.getKey().getProperty().isGenerated()).collect(Collectors.toList());
    int length = queryString.length();
    if (!computePropertyPaths()) {
        for (Map.Entry<QueryPropertyPath, Object> entry : update) {
            QueryPropertyPath propertyPath = entry.getKey();
            PersistentProperty prop = propertyPath.getProperty();
            String tableAlias = propertyPath.getTableAlias();
            if (tableAlias != null) {
                queryString.append(tableAlias).append(DOT);
            }
            queryString.append(propertyPath.getPath()).append('=');
            if (entry.getValue() instanceof BindingParameter) {
                appendUpdateSetParameter(queryString, tableAlias, prop, () -> {
                    queryState.pushParameter((BindingParameter) entry.getValue(), newBindingContext(propertyPath.propertyPath));
                });
            } else {
                queryString.append(asLiteral(entry.getValue()));
            }
            queryString.append(COMMA);
        }
    } else {
        NamingStrategy namingStrategy = queryState.getEntity().getNamingStrategy();
        for (Map.Entry<QueryPropertyPath, Object> entry : update) {
            QueryPropertyPath propertyPath = entry.getKey();
            if (entry.getValue() instanceof BindingParameter) {
                traversePersistentProperties(propertyPath.getAssociations(), propertyPath.getProperty(), (associations, property) -> {
                    String tableAlias = propertyPath.getTableAlias();
                    if (tableAlias != null) {
                        queryString.append(tableAlias).append(DOT);
                    }
                    String columnName = namingStrategy.mappedName(associations, property);
                    if (queryState.escape) {
                        columnName = quote(columnName);
                    }
                    queryString.append(columnName).append('=');
                    appendUpdateSetParameter(queryString, tableAlias, property, () -> {
                        queryState.pushParameter((BindingParameter) entry.getValue(), newBindingContext(propertyPath.propertyPath, PersistentPropertyPath.of(associations, property, asPath(associations, property))));
                    });
                    queryString.append(COMMA);
                });
            } else {
                String tableAlias = propertyPath.getTableAlias();
                if (tableAlias != null) {
                    queryString.append(tableAlias).append(DOT);
                }
                queryString.append(propertyPath.getPath()).append('=');
                queryString.append(asLiteral(entry.getValue()));
                queryString.append(COMMA);
            }
        }
    }
    int newLength = queryString.length();
    if (length != newLength) {
        queryString.setLength(newLength - 1);
    }
}
Also used : Join(io.micronaut.data.annotation.Join) QueryModel(io.micronaut.data.model.query.QueryModel) TypeRole(io.micronaut.data.annotation.TypeRole) LiteralExpression(io.micronaut.data.model.jpa.criteria.impl.LiteralExpression) MappedEntity(io.micronaut.data.annotation.MappedEntity) HashMap(java.util.HashMap) Internal(io.micronaut.core.annotation.Internal) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Embedded(io.micronaut.data.model.Embedded) Matcher(java.util.regex.Matcher) Where(io.micronaut.data.annotation.Where) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Nullable(io.micronaut.core.annotation.Nullable) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) QueryParameter(io.micronaut.data.model.query.QueryParameter) PersistentProperty(io.micronaut.data.model.PersistentProperty) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Iterator(java.util.Iterator) Sort(io.micronaut.data.model.Sort) Collection(java.util.Collection) AssociationQuery(io.micronaut.data.model.query.AssociationQuery) DataTransformer(io.micronaut.data.annotation.DataTransformer) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) WhereSpecifications(io.micronaut.data.annotation.repeatable.WhereSpecifications) NonNull(io.micronaut.core.annotation.NonNull) StringUtils(io.micronaut.core.util.StringUtils) JoinPath(io.micronaut.data.model.query.JoinPath) BindingParameter(io.micronaut.data.model.query.BindingParameter) AbstractMap(java.util.AbstractMap) List(java.util.List) Association(io.micronaut.data.model.Association) PersistentEntity(io.micronaut.data.model.PersistentEntity) CollectionUtils(io.micronaut.core.util.CollectionUtils) StringJoiner(java.util.StringJoiner) Dialect(io.micronaut.data.model.query.builder.sql.Dialect) Optional(java.util.Optional) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Comparator(java.util.Comparator) Collections(java.util.Collections) QueryParameter(io.micronaut.data.model.query.QueryParameter) PersistentProperty(io.micronaut.data.model.PersistentProperty) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Association(io.micronaut.data.model.Association) BindingParameter(io.micronaut.data.model.query.BindingParameter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) AbstractMap(java.util.AbstractMap)

Aggregations

BindingParameter (io.micronaut.data.model.query.BindingParameter)3 PersistentPropertyPath (io.micronaut.data.model.PersistentPropertyPath)2 NamingStrategy (io.micronaut.data.model.naming.NamingStrategy)2 QueryModel (io.micronaut.data.model.query.QueryModel)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)1 Internal (io.micronaut.core.annotation.Internal)1 NonNull (io.micronaut.core.annotation.NonNull)1 Nullable (io.micronaut.core.annotation.Nullable)1 ArgumentUtils (io.micronaut.core.util.ArgumentUtils)1 CollectionUtils (io.micronaut.core.util.CollectionUtils)1 StringUtils (io.micronaut.core.util.StringUtils)1 DataTransformer (io.micronaut.data.annotation.DataTransformer)1 Join (io.micronaut.data.annotation.Join)1 MappedEntity (io.micronaut.data.annotation.MappedEntity)1 TypeRole (io.micronaut.data.annotation.TypeRole)1 Where (io.micronaut.data.annotation.Where)1 WhereSpecifications (io.micronaut.data.annotation.repeatable.WhereSpecifications)1