Search in sources :

Example 11 with PersistentEntity

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

the class AbstractSqlLikeQueryBuilder method getAliasName.

/**
 * Get the alias name.
 *
 * @param joinPath The join path
 * @return The alias
 */
public String getAliasName(JoinPath joinPath) {
    return joinPath.getAlias().orElseGet(() -> {
        String joinPathAlias = getPathOnlyAliasName(joinPath);
        PersistentEntity owner = joinPath.getAssociationPath()[0].getOwner();
        String ownerAlias = getAliasName(owner);
        if (ownerAlias.endsWith("_") && joinPathAlias.startsWith("_")) {
            return ownerAlias + joinPathAlias.substring(1);
        } else {
            return ownerAlias + joinPathAlias;
        }
    });
}
Also used : PersistentEntity(io.micronaut.data.model.PersistentEntity)

Example 12 with PersistentEntity

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

the class AbstractCriteriaMethodMatch method extractPredicates.

@Nullable
private Predicate extractPredicates(List<ParameterElement> queryParams, PersistentEntityRoot<?> root, SourcePersistentEntityCriteriaBuilder cb) {
    if (CollectionUtils.isNotEmpty(queryParams)) {
        PersistentEntity rootEntity = root.getPersistentEntity();
        List<Predicate> predicates = new ArrayList<>(queryParams.size());
        for (ParameterElement queryParam : queryParams) {
            String paramName = queryParam.getName();
            PersistentProperty prop = rootEntity.getPropertyByName(paramName);
            ParameterExpression<Object> param = cb.parameter(queryParam);
            if (prop == null) {
                if (TypeRole.ID.equals(paramName) && (rootEntity.hasIdentity() || rootEntity.hasCompositeIdentity())) {
                    predicates.add(cb.equal(root.id(), param));
                } else {
                    throw new MatchFailedException("Cannot query persistentEntity [" + rootEntity.getSimpleName() + "] on non-existent property: " + paramName);
                }
            } else if (prop == rootEntity.getIdentity()) {
                predicates.add(cb.equal(root.id(), param));
            } else if (prop == rootEntity.getVersion()) {
                predicates.add(cb.equal(root.version(), param));
            } else {
                predicates.add(cb.equal(root.get(prop.getName()), param));
            }
        }
        if (predicates.isEmpty()) {
            return null;
        }
        return cb.and(predicates);
    }
    return null;
}
Also used : MatchFailedException(io.micronaut.data.processor.visitors.MatchFailedException) PersistentEntity(io.micronaut.data.model.PersistentEntity) ArrayList(java.util.ArrayList) ParameterElement(io.micronaut.inject.ast.ParameterElement) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) PersistentProperty(io.micronaut.data.model.PersistentProperty) Predicate(jakarta.persistence.criteria.Predicate) Nullable(io.micronaut.core.annotation.Nullable)

Example 13 with PersistentEntity

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

the class AbstractCriteriaMethodMatch method findProperty.

@Nullable
protected final <T> io.micronaut.data.model.jpa.criteria.PersistentPropertyPath<Object> findProperty(PersistentEntityRoot<T> root, String propertyName) {
    propertyName = NameUtils.decapitalize(propertyName);
    PersistentEntity entity = root.getPersistentEntity();
    PersistentProperty prop = entity.getPropertyByName(propertyName);
    PersistentPropertyPath pp;
    if (prop == null) {
        Optional<String> propertyPath = entity.getPath(propertyName);
        if (propertyPath.isPresent()) {
            String path = propertyPath.get();
            pp = entity.getPropertyPath(path);
            if (pp == null) {
                return null;
            }
        } else {
            return null;
        }
    } else {
        pp = PersistentPropertyPath.of(Collections.emptyList(), prop, propertyName);
    }
    PersistentEntityFrom<?, ?> path = root;
    for (Association association : pp.getAssociations()) {
        path = path.join(association.getName());
    }
    Path<Object> exp;
    if (pp.getProperty() instanceof Association && ((Association) pp.getProperty()).getKind() != Relation.Kind.EMBEDDED) {
        exp = path.join(pp.getProperty().getName());
    } else {
        exp = path.get(pp.getProperty().getName());
    }
    return CriteriaUtils.requireProperty(exp);
}
Also used : Association(io.micronaut.data.model.Association) PersistentEntity(io.micronaut.data.model.PersistentEntity) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) PersistentProperty(io.micronaut.data.model.PersistentProperty) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) Nullable(io.micronaut.core.annotation.Nullable)

Example 14 with PersistentEntity

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

the class SourcePersistentEntityCriteriaQueryImpl method getQueryResultTypeName.

@Override
public String getQueryResultTypeName() {
    if (selection instanceof ISelection) {
        String[] result = new String[1];
        ((SelectionVisitable) selection).accept(new SelectionVisitor() {

            @Override
            public void visit(Predicate predicate) {
            }

            @Override
            public void visit(PersistentPropertyPath<?> persistentPropertyPath) {
                result[0] = ((SourcePersistentPropertyPath) persistentPropertyPath).getProperty().getType().getName();
            }

            @Override
            public void visit(AliasedSelection<?> aliasedSelection) {
                ((SelectionVisitable) aliasedSelection.getSelection()).accept(this);
            }

            @Override
            public void visit(PersistentEntityRoot<?> entityRoot) {
                result[0] = ((SourcePersistentEntity) entityRoot.getPersistentEntity()).getType().getName();
            }

            @Override
            public void visit(AggregateExpression<?, ?> aggregateExpression) {
                switch(aggregateExpression.getType()) {
                    case COUNT:
                    case COUNT_DISTINCT:
                        result[0] = Long.class.getName();
                        break;
                    case MAX:
                    case MIN:
                        result[0] = requireProperty(aggregateExpression.getExpression()).getProperty().getTypeName();
                        break;
                    case SUM:
                    case AVG:
                        ClassElement type = ((SourcePersistentProperty) requireProperty(aggregateExpression.getExpression()).getProperty()).getType();
                        if (aggregateExpression.getExpressionType() != null) {
                            result[0] = aggregateExpression.getExpressionType().getName();
                        }
                        if (TypeUtils.isNumber(type)) {
                            result[0] = Number.class.getName();
                        } else {
                            result[0] = type.getName();
                        }
                        break;
                    default:
                        return;
                }
            }

            @Override
            public void visit(CompoundSelection<?> compoundSelection) {
                if (compoundSelection.getCompoundSelectionItems().size() == 1) {
                    // Multiple selection shouldn't result in one type
                    compoundSelection.getCompoundSelectionItems().forEach(s -> ((SelectionVisitable) s).accept(this));
                }
            }

            @Override
            public void visit(LiteralExpression<?> literalExpression) {
                result[0] = literalExpression.getValue().getClass().getName();
            }

            @Override
            public void visit(IdExpression<?, ?> idExpression) {
                SourcePersistentEntity persistentEntity = (SourcePersistentEntity) idExpression.getRoot().getPersistentEntity();
                if (persistentEntity.hasCompositeIdentity()) {
                    throw new IllegalStateException("IdClass is unknown!");
                }
                result[0] = persistentEntity.getIdentity().getType().getName();
            }
        });
        return result[0];
    }
    return null;
}
Also used : IdExpression(io.micronaut.data.model.jpa.criteria.impl.IdExpression) Predicate(jakarta.persistence.criteria.Predicate) LiteralExpression(io.micronaut.data.model.jpa.criteria.impl.LiteralExpression) SelectionVisitor(io.micronaut.data.model.jpa.criteria.impl.SelectionVisitor) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) ClassElement(io.micronaut.inject.ast.ClassElement) Internal(io.micronaut.core.annotation.Internal) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) SourcePersistentEntityCriteriaQuery(io.micronaut.data.processor.model.criteria.SourcePersistentEntityCriteriaQuery) Function(java.util.function.Function) ISelection(io.micronaut.data.model.jpa.criteria.ISelection) PersistentEntityRoot(io.micronaut.data.model.jpa.criteria.PersistentEntityRoot) AbstractPersistentEntityCriteriaQuery(io.micronaut.data.model.jpa.criteria.impl.AbstractPersistentEntityCriteriaQuery) AggregateExpression(io.micronaut.data.model.jpa.criteria.impl.selection.AggregateExpression) PersistentEntity(io.micronaut.data.model.PersistentEntity) CriteriaUtils.requireProperty(io.micronaut.data.model.jpa.criteria.impl.CriteriaUtils.requireProperty) PersistentPropertyPath(io.micronaut.data.model.jpa.criteria.PersistentPropertyPath) SelectionVisitable(io.micronaut.data.model.jpa.criteria.impl.SelectionVisitable) TypeUtils(io.micronaut.data.processor.visitors.finders.TypeUtils) CompoundSelection(io.micronaut.data.model.jpa.criteria.impl.selection.CompoundSelection) AliasedSelection(io.micronaut.data.model.jpa.criteria.impl.selection.AliasedSelection) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) SelectionVisitor(io.micronaut.data.model.jpa.criteria.impl.SelectionVisitor) ClassElement(io.micronaut.inject.ast.ClassElement) Predicate(jakarta.persistence.criteria.Predicate) ISelection(io.micronaut.data.model.jpa.criteria.ISelection) SelectionVisitable(io.micronaut.data.model.jpa.criteria.impl.SelectionVisitable)

Example 15 with PersistentEntity

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

the class R2dbcSchemaGenerator method createSchema.

/**
 * Creates the schema.
 *
 * @param beanLocator The bean locator
 */
@PostConstruct
protected void createSchema(BeanLocator beanLocator) {
    RuntimeEntityRegistry runtimeEntityRegistry = beanLocator.getBean(RuntimeEntityRegistry.class);
    for (DataR2dbcConfiguration configuration : configurations) {
        SchemaGenerate schemaGenerate = configuration.getSchemaGenerate();
        if (schemaGenerate != null && schemaGenerate != SchemaGenerate.NONE) {
            List<String> packages = configuration.getPackages();
            Collection<BeanIntrospection<Object>> introspections;
            if (CollectionUtils.isNotEmpty(packages)) {
                introspections = BeanIntrospector.SHARED.findIntrospections(MappedEntity.class, packages.toArray(new String[0]));
            } else {
                introspections = BeanIntrospector.SHARED.findIntrospections(MappedEntity.class);
            }
            PersistentEntity[] entities = introspections.stream().filter(i -> !i.getBeanType().getName().contains("$")).filter(i -> !java.lang.reflect.Modifier.isAbstract(i.getBeanType().getModifiers())).map(e -> runtimeEntityRegistry.getEntity(e.getBeanType())).toArray(PersistentEntity[]::new);
            if (ArrayUtils.isNotEmpty(entities)) {
                R2dbcOperations r2dbcOperations = configuration.getR2dbcOperations();
                SqlQueryBuilder builder = new SqlQueryBuilder(configuration.getDialect());
                Mono.from(r2dbcOperations.withConnection(connection -> {
                    List<String> createStatements = Arrays.stream(entities).flatMap(entity -> Arrays.stream(builder.buildCreateTableStatements(entity))).collect(Collectors.toList());
                    Flux<Void> createTablesFlow = Flux.fromIterable(createStatements).concatMap(sql -> {
                        if (DataSettings.QUERY_LOG.isDebugEnabled()) {
                            DataSettings.QUERY_LOG.debug("Creating Table: \n{}", sql);
                        }
                        return execute(connection, sql).onErrorResume((throwable -> {
                            if (LOG.isWarnEnabled()) {
                                LOG.warn("Unable to create table :{}", throwable.getMessage());
                            }
                            return Mono.empty();
                        }));
                    });
                    switch(schemaGenerate) {
                        case CREATE_DROP:
                            List<String> dropStatements = Arrays.stream(entities).flatMap(entity -> Arrays.stream(builder.buildDropTableStatements(entity))).collect(Collectors.toList());
                            return Flux.fromIterable(dropStatements).concatMap(sql -> {
                                if (DataSettings.QUERY_LOG.isDebugEnabled()) {
                                    DataSettings.QUERY_LOG.debug("Dropping Table: \n{}", sql);
                                }
                                return execute(connection, sql).onErrorResume((throwable -> Mono.empty()));
                            }).thenMany(createTablesFlow).then();
                        case CREATE:
                        default:
                            return createTablesFlow.then();
                    }
                })).block();
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) R2dbcOperations(io.micronaut.data.r2dbc.operations.R2dbcOperations) Logger(org.slf4j.Logger) Context(io.micronaut.context.annotation.Context) Collection(java.util.Collection) ArrayUtils(io.micronaut.core.util.ArrayUtils) LoggerFactory(org.slf4j.LoggerFactory) MappedEntity(io.micronaut.data.annotation.MappedEntity) Mono(reactor.core.publisher.Mono) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) Internal(io.micronaut.core.annotation.Internal) SchemaGenerate(io.micronaut.data.runtime.config.SchemaGenerate) Collectors(java.util.stream.Collectors) Connection(io.r2dbc.spi.Connection) Flux(reactor.core.publisher.Flux) List(java.util.List) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) PersistentEntity(io.micronaut.data.model.PersistentEntity) CollectionUtils(io.micronaut.core.util.CollectionUtils) PostConstruct(javax.annotation.PostConstruct) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) BeanLocator(io.micronaut.context.BeanLocator) BeanIntrospector(io.micronaut.core.beans.BeanIntrospector) DataSettings(io.micronaut.data.runtime.config.DataSettings) MappedEntity(io.micronaut.data.annotation.MappedEntity) PersistentEntity(io.micronaut.data.model.PersistentEntity) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) SchemaGenerate(io.micronaut.data.runtime.config.SchemaGenerate) R2dbcOperations(io.micronaut.data.r2dbc.operations.R2dbcOperations) PostConstruct(javax.annotation.PostConstruct)

Aggregations

PersistentEntity (io.micronaut.data.model.PersistentEntity)27 PersistentProperty (io.micronaut.data.model.PersistentProperty)15 Association (io.micronaut.data.model.Association)13 Embedded (io.micronaut.data.model.Embedded)11 List (java.util.List)11 ArrayList (java.util.ArrayList)10 Collection (java.util.Collection)9 CollectionUtils (io.micronaut.core.util.CollectionUtils)8 MappedEntity (io.micronaut.data.annotation.MappedEntity)8 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)7 NonNull (io.micronaut.core.annotation.NonNull)7 ArrayUtils (io.micronaut.core.util.ArrayUtils)7 Relation (io.micronaut.data.annotation.Relation)7 PersistentPropertyPath (io.micronaut.data.model.PersistentPropertyPath)7 NamingStrategy (io.micronaut.data.model.naming.NamingStrategy)7 JoinPath (io.micronaut.data.model.query.JoinPath)7 ArgumentUtils (io.micronaut.core.util.ArgumentUtils)6 StringUtils (io.micronaut.core.util.StringUtils)6 MappingException (io.micronaut.data.exceptions.MappingException)6 Pageable (io.micronaut.data.model.Pageable)6