Search in sources :

Example 6 with PersistentEntity

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

the class SqlQueryBuilder method buildInsert.

@NonNull
@Override
public QueryResult buildInsert(AnnotationMetadata repositoryMetadata, PersistentEntity entity) {
    boolean escape = shouldEscape(entity);
    final String unescapedTableName = getUnescapedTableName(entity);
    NamingStrategy namingStrategy = entity.getNamingStrategy();
    Collection<? extends PersistentProperty> persistentProperties = entity.getPersistentProperties();
    List<QueryParameterBinding> parameterBindings = new ArrayList<>();
    List<String> columns = new ArrayList<>();
    List<String> values = new ArrayList<>();
    for (PersistentProperty prop : persistentProperties) {
        if (!prop.isGenerated()) {
            traversePersistentProperties(prop, (associations, property) -> {
                addWriteExpression(values, prop);
                String key = String.valueOf(values.size());
                String[] path = asStringPath(associations, property);
                parameterBindings.add(new QueryParameterBinding() {

                    @Override
                    public String getKey() {
                        return key;
                    }

                    @Override
                    public DataType getDataType() {
                        return property.getDataType();
                    }

                    @Override
                    public String[] getPropertyPath() {
                        return path;
                    }
                });
                String columnName = namingStrategy.mappedName(associations, property);
                if (escape) {
                    columnName = quote(columnName);
                }
                columns.add(columnName);
            });
        }
    }
    PersistentProperty version = entity.getVersion();
    if (version != null) {
        addWriteExpression(values, version);
        String key = String.valueOf(values.size());
        parameterBindings.add(new QueryParameterBinding() {

            @Override
            public String getKey() {
                return key;
            }

            @Override
            public DataType getDataType() {
                return version.getDataType();
            }

            @Override
            public String[] getPropertyPath() {
                return new String[] { version.getName() };
            }
        });
        String columnName = namingStrategy.mappedName(Collections.emptyList(), version);
        if (escape) {
            columnName = quote(columnName);
        }
        columns.add(columnName);
    }
    PersistentProperty identity = entity.getIdentity();
    if (identity != null) {
        traversePersistentProperties(identity, (associations, property) -> {
            boolean isSequence = false;
            if (isNotForeign(associations)) {
                Optional<AnnotationValue<GeneratedValue>> generated = property.findAnnotation(GeneratedValue.class);
                if (generated.isPresent()) {
                    GeneratedValue.Type idGeneratorType = generated.flatMap(av -> av.enumValue(GeneratedValue.Type.class)).orElseGet(() -> selectAutoStrategy(property));
                    if (idGeneratorType == GeneratedValue.Type.SEQUENCE) {
                        isSequence = true;
                    } else if (dialect != Dialect.MYSQL || property.getDataType() != DataType.UUID) {
                        // Property skipped
                        return;
                    }
                }
            }
            if (isSequence) {
                values.add(getSequenceStatement(unescapedTableName, property));
            } else {
                addWriteExpression(values, property);
                String key = String.valueOf(values.size());
                String[] path = asStringPath(associations, property);
                parameterBindings.add(new QueryParameterBinding() {

                    @Override
                    public String getKey() {
                        return key;
                    }

                    @Override
                    public DataType getDataType() {
                        return property.getDataType();
                    }

                    @Override
                    public String[] getPropertyPath() {
                        return path;
                    }
                });
            }
            String columnName = namingStrategy.mappedName(associations, property);
            if (escape) {
                columnName = quote(columnName);
            }
            columns.add(columnName);
        });
    }
    String builder = INSERT_INTO + getTableName(entity) + " (" + String.join(",", columns) + CLOSE_BRACKET + " " + "VALUES (" + String.join(String.valueOf(COMMA), values) + CLOSE_BRACKET;
    return QueryResult.of(builder, Collections.emptyList(), parameterBindings, Collections.emptyMap());
}
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) QueryParameterBinding(io.micronaut.data.model.query.builder.QueryParameterBinding) ArrayList(java.util.ArrayList) PersistentProperty(io.micronaut.data.model.PersistentProperty) GeneratedValue(io.micronaut.data.annotation.GeneratedValue) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) DataType(io.micronaut.data.model.DataType) AnnotationValue(io.micronaut.core.annotation.AnnotationValue) NonNull(io.micronaut.core.annotation.NonNull)

Example 7 with PersistentEntity

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

the class MongoCollectionsCreator method initialize.

@PostConstruct
void initialize(BeanLocator beanLocator, RuntimeEntityRegistry runtimeEntityRegistry, List<AbstractMongoConfiguration> mongoConfigurations) {
    super.initialize(runtimeEntityRegistry, mongoConfigurations, mongoConfiguration -> {
        MongoDatabaseFactory mongoDatabaseFactory = getMongoFactory(MongoDatabaseFactory.class, beanLocator, mongoConfiguration);
        Map<String, Set<String>> databaseCollections = new HashMap<>();
        return new DatabaseOperations<MongoDatabase>() {

            @Override
            public String getDatabaseName(MongoDatabase database) {
                return database.getName();
            }

            @Override
            public MongoDatabase find(PersistentEntity persistentEntity) {
                return mongoDatabaseFactory.getDatabase(persistentEntity);
            }

            @Override
            public Set<String> listCollectionNames(MongoDatabase database) {
                return databaseCollections.computeIfAbsent(database.getName(), s -> database.listCollectionNames().into(new HashSet<>()));
            }

            @Override
            public void createCollection(MongoDatabase database, String collection) {
                database.createCollection(collection);
            }
        };
    });
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) MongoDatabaseFactory(io.micronaut.data.mongodb.database.MongoDatabaseFactory) PersistentEntity(io.micronaut.data.model.PersistentEntity) MongoDatabase(com.mongodb.client.MongoDatabase) HashSet(java.util.HashSet) PostConstruct(javax.annotation.PostConstruct)

Example 8 with PersistentEntity

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

the class AbstractMongoCollectionsCreator method initialize.

/**
 * Initialize the collections.
 *
 * @param runtimeEntityRegistry      The entity registry
 * @param mongoConfigurations        The configuration
 * @param databaseOperationsProvider The database provider
 */
protected void initialize(RuntimeEntityRegistry runtimeEntityRegistry, List<AbstractMongoConfiguration> mongoConfigurations, DatabaseOperationsProvider<Dtbs> databaseOperationsProvider) {
    for (AbstractMongoConfiguration mongoConfiguration : mongoConfigurations) {
        // TODO: different initializer per conf
        Collection<BeanIntrospection<Object>> 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);
        DatabaseOperations<Dtbs> databaseOperations = databaseOperationsProvider.get(mongoConfiguration);
        for (PersistentEntity entity : entities) {
            Dtbs database = databaseOperations.find(entity);
            Set<String> collections = databaseOperations.listCollectionNames(database);
            String persistedName = entity.getPersistedName();
            if (collections.add(persistedName)) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Creating collection: {} in database: {}", persistedName, databaseOperations.getDatabaseName(database));
                }
                databaseOperations.createCollection(database, persistedName);
            }
            for (PersistentProperty persistentProperty : entity.getPersistentProperties()) {
                if (persistentProperty instanceof Association) {
                    Association association = (Association) persistentProperty;
                    Optional<Association> inverseSide = association.getInverseSide().map(Function.identity());
                    if (association.getKind() == Relation.Kind.MANY_TO_MANY || association.isForeignKey() && !inverseSide.isPresent()) {
                        Association owningAssociation = inverseSide.orElse(association);
                        NamingStrategy namingStrategy = association.getOwner().getNamingStrategy();
                        String joinCollectionName = namingStrategy.mappedName(owningAssociation);
                        if (collections.add(joinCollectionName)) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("Creating collection: {} in database: {}", persistedName, databaseOperations.getDatabaseName(database));
                            }
                            databaseOperations.createCollection(database, joinCollectionName);
                        }
                    }
                }
            }
        }
    }
}
Also used : PersistentProperty(io.micronaut.data.model.PersistentProperty) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Logger(org.slf4j.Logger) Context(io.micronaut.context.annotation.Context) Qualifier(io.micronaut.context.Qualifier) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) MappedEntity(io.micronaut.data.annotation.MappedEntity) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Set(java.util.Set) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) Internal(io.micronaut.core.annotation.Internal) Function(java.util.function.Function) List(java.util.List) Association(io.micronaut.data.model.Association) AbstractMongoConfiguration(io.micronaut.configuration.mongo.core.AbstractMongoConfiguration) NamedMongoConfiguration(io.micronaut.configuration.mongo.core.NamedMongoConfiguration) PersistentEntity(io.micronaut.data.model.PersistentEntity) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) Optional(java.util.Optional) BeanLocator(io.micronaut.context.BeanLocator) BeanIntrospector(io.micronaut.core.beans.BeanIntrospector) DefaultMongoConfiguration(io.micronaut.configuration.mongo.core.DefaultMongoConfiguration) Relation(io.micronaut.data.annotation.Relation) PersistentEntity(io.micronaut.data.model.PersistentEntity) PersistentProperty(io.micronaut.data.model.PersistentProperty) NamingStrategy(io.micronaut.data.model.naming.NamingStrategy) Association(io.micronaut.data.model.Association) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) AbstractMongoConfiguration(io.micronaut.configuration.mongo.core.AbstractMongoConfiguration)

Example 9 with PersistentEntity

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

the class AbstractSqlLikeQueryBuilder method traversePersistentProperties.

private void traversePersistentProperties(List<Association> associations, PersistentProperty property, BiConsumer<List<Association>, PersistentProperty> consumerProperty) {
    if (property instanceof Embedded) {
        Embedded embedded = (Embedded) property;
        PersistentEntity embeddedEntity = embedded.getAssociatedEntity();
        Collection<? extends PersistentProperty> embeddedProperties = embeddedEntity.getPersistentProperties();
        List<Association> newAssociations = new ArrayList<>(associations);
        newAssociations.add((Association) property);
        for (PersistentProperty embeddedProperty : embeddedProperties) {
            traversePersistentProperties(newAssociations, embeddedProperty, consumerProperty);
        }
    } else if (property instanceof Association) {
        Association association = (Association) property;
        if (association.isForeignKey()) {
            return;
        }
        List<Association> newAssociations = new ArrayList<>(associations);
        newAssociations.add((Association) property);
        PersistentEntity associatedEntity = association.getAssociatedEntity();
        PersistentProperty assocIdentity = associatedEntity.getIdentity();
        if (assocIdentity == null) {
            throw new IllegalStateException("Identity cannot be missing for: " + associatedEntity);
        }
        if (assocIdentity instanceof Association) {
            traversePersistentProperties(newAssociations, assocIdentity, consumerProperty);
        } else {
            consumerProperty.accept(newAssociations, assocIdentity);
        }
    } else {
        consumerProperty.accept(associations, property);
    }
}
Also used : Association(io.micronaut.data.model.Association) PersistentEntity(io.micronaut.data.model.PersistentEntity) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Embedded(io.micronaut.data.model.Embedded) PersistentProperty(io.micronaut.data.model.PersistentProperty)

Example 10 with PersistentEntity

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

the class AbstractSqlLikeQueryBuilder method buildUpdate.

@Override
public QueryResult buildUpdate(@NonNull AnnotationMetadata annotationMetadata, @NonNull QueryModel query, @NonNull Map<String, Object> propertiesToUpdate) {
    if (propertiesToUpdate.isEmpty()) {
        throw new IllegalArgumentException("No properties specified to update");
    }
    PersistentEntity entity = query.getPersistentEntity();
    QueryState queryState = newQueryState(query, false, isAliasForBatch());
    StringBuilder queryString = queryState.getQuery();
    String tableAlias = queryState.getRootAlias();
    String tableName = getTableName(entity);
    queryString.append(UPDATE_CLAUSE).append(tableName);
    if (tableAlias != null) {
        queryString.append(SPACE).append(tableAlias);
    }
    buildUpdateStatement(queryState, propertiesToUpdate);
    buildWhereClause(annotationMetadata, query.getCriteria(), queryState);
    return QueryResult.of(queryState.getFinalQuery(), queryState.getQueryParts(), queryState.getParameterBindings(), queryState.getAdditionalRequiredParameters());
}
Also used : PersistentEntity(io.micronaut.data.model.PersistentEntity)

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