Search in sources :

Example 6 with NamingStrategy

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

the class MappedEntityVisitor method visitClass.

@Override
public void visitClass(ClassElement element, VisitorContext context) {
    NamingStrategy namingStrategy = resolveNamingStrategy(element);
    Optional<String> targetName = element.stringValue(MappedEntity.class);
    SourcePersistentEntity entity = entityResolver.apply(element);
    if (isMappedEntity() && !targetName.isPresent()) {
        element.annotate(MappedEntity.class, builder -> {
            String mappedName = namingStrategy.mappedName(entity);
            builder.value(mappedName);
        });
    }
    Map<String, DataType> dataTypes = getConfiguredDataTypes(element);
    Map<String, String> dataConverters = getConfiguredDataConverters(element);
    List<SourcePersistentProperty> properties = entity.getPersistentProperties();
    final List<AnnotationValue<Index>> indexes = properties.stream().filter(x -> ((PersistentProperty) x).findAnnotation(Indexes.class).isPresent()).map(prop -> prop.findAnnotation(Index.class)).flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
    if (!indexes.isEmpty()) {
        element.annotate(Indexes.class, builder -> builder.values(indexes.toArray(new AnnotationValue[] {})));
    }
    for (PersistentProperty property : properties) {
        computeMappingDefaults(namingStrategy, property, dataTypes, dataConverters, context);
    }
    SourcePersistentProperty identity = entity.getIdentity();
    if (identity != null) {
        computeMappingDefaults(namingStrategy, identity, dataTypes, dataConverters, context);
    }
    SourcePersistentProperty[] compositeIdentities = entity.getCompositeIdentity();
    if (compositeIdentities != null) {
        for (SourcePersistentProperty compositeIdentity : compositeIdentities) {
            computeMappingDefaults(namingStrategy, compositeIdentity, dataTypes, dataConverters, context);
        }
    }
    SourcePersistentProperty version = entity.getVersion();
    if (version != null) {
        computeMappingDefaults(namingStrategy, version, dataTypes, dataConverters, context);
    }
}
Also used : DataType(io.micronaut.data.model.DataType) MappedEntity(io.micronaut.data.annotation.MappedEntity) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) ClassElement(io.micronaut.inject.ast.ClassElement) HashMap(java.util.HashMap) TypeDef(io.micronaut.data.annotation.TypeDef) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Utils.getConfiguredDataTypes(io.micronaut.data.processor.visitors.Utils.getConfiguredDataTypes) Utils.getConfiguredDataConverters(io.micronaut.data.processor.visitors.Utils.getConfiguredDataConverters) TypeElementVisitor(io.micronaut.inject.visitor.TypeElementVisitor) MappedProperty(io.micronaut.data.annotation.MappedProperty) PropertyElement(io.micronaut.inject.ast.PropertyElement) InstantiationUtils(io.micronaut.core.reflect.InstantiationUtils) Map(java.util.Map) TypeUtils(io.micronaut.data.processor.visitors.finders.TypeUtils) AnnotationClassValue(io.micronaut.core.annotation.AnnotationClassValue) NamingStrategies(io.micronaut.data.model.naming.NamingStrategies) PersistentProperty(io.micronaut.data.model.PersistentProperty) Property(io.micronaut.context.annotation.Property) Index(io.micronaut.data.annotation.Index) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) Collectors(java.util.stream.Collectors) Indexes(io.micronaut.data.annotation.Indexes) Objects(java.util.Objects) NonNull(io.micronaut.core.annotation.NonNull) VisitorContext(io.micronaut.inject.visitor.VisitorContext) List(java.util.List) Association(io.micronaut.data.model.Association) Stream(java.util.stream.Stream) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Optional(java.util.Optional) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) AttributeConverter(io.micronaut.data.model.runtime.convert.AttributeConverter) Relation(io.micronaut.data.annotation.Relation) SourcePersistentEntity(io.micronaut.data.processor.model.SourcePersistentEntity) Index(io.micronaut.data.annotation.Index) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) PersistentProperty(io.micronaut.data.model.PersistentProperty) Indexes(io.micronaut.data.annotation.Indexes) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) SourcePersistentProperty(io.micronaut.data.processor.model.SourcePersistentProperty) DataType(io.micronaut.data.model.DataType) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Stream(java.util.stream.Stream)

Example 7 with NamingStrategy

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

the class SqlQueryBuilder method buildJoinTableInsert.

/**
 * Builds a join table insert statement for a given entity and association.
 *
 * @param entity      The entity
 * @param association The association
 * @return The join table insert statement
 */
@NonNull
public String buildJoinTableInsert(@NonNull PersistentEntity entity, @NonNull Association association) {
    if (!isForeignKeyWithJoinTable(association)) {
        throw new IllegalArgumentException("Join table inserts can only be built for foreign key associations that are mapped with a join table.");
    } else {
        Optional<Association> inverseSide = association.getInverseSide().map(Function.identity());
        Association owningAssociation = inverseSide.orElse(association);
        AnnotationMetadata annotationMetadata = owningAssociation.getAnnotationMetadata();
        NamingStrategy namingStrategy = entity.getNamingStrategy();
        String joinTableName = annotationMetadata.stringValue(ANN_JOIN_TABLE, "name").orElseGet(() -> namingStrategy.mappedName(association));
        List<String> leftJoinColumns = resolveJoinTableJoinColumns(annotationMetadata, true, entity, namingStrategy);
        List<String> rightJoinColumns = resolveJoinTableJoinColumns(annotationMetadata, false, association.getAssociatedEntity(), namingStrategy);
        boolean escape = shouldEscape(entity);
        String columns = Stream.concat(leftJoinColumns.stream(), rightJoinColumns.stream()).map(columnName -> escape ? quote(columnName) : columnName).collect(Collectors.joining(","));
        String placeholders = IntStream.range(0, leftJoinColumns.size() + rightJoinColumns.size()).mapToObj(i -> "?").collect(Collectors.joining(","));
        return INSERT_INTO + quote(joinTableName) + " (" + columns + ") VALUES (" + placeholders + ")";
    }
}
Also used : DataType(io.micronaut.data.model.DataType) SqlMembers(io.micronaut.data.annotation.sql.SqlMembers) Arrays(java.util.Arrays) IDENTITY(io.micronaut.data.annotation.GeneratedValue.Type.IDENTITY) ListIterator(java.util.ListIterator) ArrayUtils(io.micronaut.core.util.ArrayUtils) SEQUENCE(io.micronaut.data.annotation.GeneratedValue.Type.SEQUENCE) MappedProperty(io.micronaut.data.annotation.MappedProperty) GeneratedValue(io.micronaut.data.annotation.GeneratedValue) Locale(java.util.Locale) Map(java.util.Map) QueryResult(io.micronaut.data.model.query.builder.QueryResult) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) PersistentPropertyPath(io.micronaut.data.model.PersistentPropertyPath) PersistentProperty(io.micronaut.data.model.PersistentProperty) Index(io.micronaut.data.annotation.Index) MappingException(io.micronaut.data.exceptions.MappingException) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) AUTO(io.micronaut.data.annotation.GeneratedValue.Type.AUTO) StringUtils(io.micronaut.core.util.StringUtils) AbstractSqlLikeQueryBuilder(io.micronaut.data.model.query.builder.AbstractSqlLikeQueryBuilder) List(java.util.List) Stream(java.util.stream.Stream) UUID(io.micronaut.data.annotation.GeneratedValue.Type.UUID) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) Experimental(io.micronaut.core.annotation.Experimental) Pattern(java.util.regex.Pattern) Relation(io.micronaut.data.annotation.Relation) IntStream(java.util.stream.IntStream) QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) Join(io.micronaut.data.annotation.Join) Creator(io.micronaut.core.annotation.Creator) QueryModel(io.micronaut.data.model.query.QueryModel) MappedEntity(io.micronaut.data.annotation.MappedEntity) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Embedded(io.micronaut.data.model.Embedded) Pageable(io.micronaut.data.model.Pageable) BiConsumer(java.util.function.BiConsumer) Clob(java.sql.Clob) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Indexes(io.micronaut.data.annotation.Indexes) NonNull(io.micronaut.core.annotation.NonNull) JoinPath(io.micronaut.data.model.query.JoinPath) Association(io.micronaut.data.model.Association) PersistentEntity(io.micronaut.data.model.PersistentEntity) CollectionUtils(io.micronaut.core.util.CollectionUtils) StringJoiner(java.util.StringJoiner) QueryBuilder(io.micronaut.data.model.query.builder.QueryBuilder) Repository(io.micronaut.data.annotation.Repository) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Blob(java.sql.Blob) Collections(java.util.Collections) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Association(io.micronaut.data.model.Association) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) NonNull(io.micronaut.core.annotation.NonNull)

Example 8 with NamingStrategy

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

the class SqlQueryBuilder method buildDropTableStatements.

/**
 * Builds the drop table statement. Designed for testing and not production usage. For production a
 * SQL migration tool such as Flyway or Liquibase is recommended.
 *
 * @param entity The entity
 * @return The tables for the give entity
 */
@Experimental
@NonNull
public String[] buildDropTableStatements(@NonNull PersistentEntity entity) {
    String tableName = getTableName(entity);
    boolean escape = shouldEscape(entity);
    String sql = "DROP TABLE " + tableName;
    Collection<Association> foreignKeyAssociations = getJoinTableAssociations(entity);
    List<String> dropStatements = new ArrayList<>();
    for (Association association : foreignKeyAssociations) {
        AnnotationMetadata associationMetadata = association.getAnnotationMetadata();
        NamingStrategy namingStrategy = entity.getNamingStrategy();
        String joinTableName = associationMetadata.stringValue(ANN_JOIN_TABLE, "name").orElseGet(() -> namingStrategy.mappedName(association));
        dropStatements.add("DROP TABLE " + (escape ? quote(joinTableName) : joinTableName) + ";");
    }
    dropStatements.add(sql);
    return dropStatements.toArray(new String[0]);
}
Also used : NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Association(io.micronaut.data.model.Association) ArrayList(java.util.ArrayList) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Experimental(io.micronaut.core.annotation.Experimental) NonNull(io.micronaut.core.annotation.NonNull)

Example 9 with NamingStrategy

use of io.micronaut.data.model.naming.NamingStrategy 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 10 with NamingStrategy

use of io.micronaut.data.model.naming.NamingStrategy 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

NamingStrategy (io.micronaut.data.model.naming.NamingStrategy)15 Association (io.micronaut.data.model.Association)11 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)10 NonNull (io.micronaut.core.annotation.NonNull)10 PersistentProperty (io.micronaut.data.model.PersistentProperty)10 Relation (io.micronaut.data.annotation.Relation)9 ArrayList (java.util.ArrayList)9 List (java.util.List)9 Optional (java.util.Optional)9 MappedEntity (io.micronaut.data.annotation.MappedEntity)8 HashMap (java.util.HashMap)8 Map (java.util.Map)8 Function (java.util.function.Function)8 Collectors (java.util.stream.Collectors)8 PersistentEntity (io.micronaut.data.model.PersistentEntity)7 PersistentPropertyPath (io.micronaut.data.model.PersistentPropertyPath)7 Collection (java.util.Collection)7 AnnotationValue (io.micronaut.core.annotation.AnnotationValue)6 ArgumentUtils (io.micronaut.core.util.ArgumentUtils)6 CollectionUtils (io.micronaut.core.util.CollectionUtils)6