Search in sources :

Example 1 with QueryParameter

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

the class AbstractSqlRepositoryOperations method resolveEntityUpdate.

/**
 * Resolves a stored update for the given entity.
 *
 * @param annotationMetadata The repository annotation metadata
 * @param repositoryType     The repository type
 * @param rootEntity         The root entity
 * @param persistentEntity   The persistent entity
 * @return The insert
 */
@NonNull
protected DBOperation resolveEntityUpdate(AnnotationMetadata annotationMetadata, Class<?> repositoryType, @NonNull Class<?> rootEntity, @NonNull RuntimePersistentEntity<?> persistentEntity) {
    final QueryKey key = new QueryKey(repositoryType, rootEntity);
    // noinspection unchecked
    return entityUpdates.computeIfAbsent(key, (queryKey) -> {
        final SqlQueryBuilder queryBuilder = queryBuilders.getOrDefault(repositoryType, DEFAULT_SQL_BUILDER);
        final String idName;
        final PersistentProperty identity = persistentEntity.getIdentity();
        if (identity != null) {
            idName = identity.getName();
        } else {
            idName = TypeRole.ID;
        }
        final QueryModel queryModel = QueryModel.from(persistentEntity).idEq(new QueryParameter(idName));
        List<String> updateProperties = persistentEntity.getPersistentProperties().stream().filter(p -> !((p instanceof Association) && ((Association) p).isForeignKey()) && p.getAnnotationMetadata().booleanValue(AutoPopulated.class, "updateable").orElse(true)).map(PersistentProperty::getName).collect(Collectors.toList());
        final QueryResult queryResult = queryBuilder.buildUpdate(annotationMetadata, queryModel, updateProperties);
        return new QueryResultSqlOperation(queryBuilder, queryResult);
    });
}
Also used : QueryParameter(io.micronaut.data.model.query.QueryParameter) QueryResult(io.micronaut.data.model.query.builder.QueryResult) RuntimeAssociation(io.micronaut.data.model.runtime.RuntimeAssociation) Association(io.micronaut.data.model.Association) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) PersistentProperty(io.micronaut.data.model.PersistentProperty) RuntimePersistentProperty(io.micronaut.data.model.runtime.RuntimePersistentProperty) QueryModel(io.micronaut.data.model.query.QueryModel) AutoPopulated(io.micronaut.data.annotation.AutoPopulated) NonNull(io.micronaut.core.annotation.NonNull)

Example 2 with QueryParameter

use of io.micronaut.data.model.query.QueryParameter 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

NonNull (io.micronaut.core.annotation.NonNull)2 Association (io.micronaut.data.model.Association)2 PersistentProperty (io.micronaut.data.model.PersistentProperty)2 QueryModel (io.micronaut.data.model.query.QueryModel)2 QueryParameter (io.micronaut.data.model.query.QueryParameter)2 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)1 Internal (io.micronaut.core.annotation.Internal)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 AutoPopulated (io.micronaut.data.annotation.AutoPopulated)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 Embedded (io.micronaut.data.model.Embedded)1 PersistentEntity (io.micronaut.data.model.PersistentEntity)1