Search in sources :

Example 1 with RuntimeEntityRegistry

use of io.micronaut.data.model.runtime.RuntimeEntityRegistry 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 2 with RuntimeEntityRegistry

use of io.micronaut.data.model.runtime.RuntimeEntityRegistry 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)

Example 3 with RuntimeEntityRegistry

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

the class SchemaGenerator method createSchema.

/**
 * Initialize the schema for the configuration.
 * @param beanLocator The bean locator
 */
@PostConstruct
public void createSchema(BeanLocator beanLocator) {
    RuntimeEntityRegistry runtimeEntityRegistry = beanLocator.getBean(RuntimeEntityRegistry.class);
    for (DataJdbcConfiguration configuration : configurations) {
        Dialect dialect = configuration.getDialect();
        SchemaGenerate schemaGenerate = configuration.getSchemaGenerate();
        if (schemaGenerate != null && schemaGenerate != SchemaGenerate.NONE) {
            String name = configuration.getName();
            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(beanIntrospection -> runtimeEntityRegistry.getEntity(beanIntrospection.getBeanType())).toArray(PersistentEntity[]::new);
            if (ArrayUtils.isNotEmpty(entities)) {
                DataSource dataSource = DelegatingDataSource.unwrapDataSource(beanLocator.getBean(DataSource.class, Qualifiers.byName(name)));
                try {
                    try (Connection connection = dataSource.getConnection()) {
                        SqlQueryBuilder builder = new SqlQueryBuilder(dialect);
                        if (dialect.allowBatch() && configuration.isBatchGenerate()) {
                            switch(schemaGenerate) {
                                case CREATE_DROP:
                                    try {
                                        String sql = builder.buildBatchDropTableStatement(entities);
                                        if (DataSettings.QUERY_LOG.isDebugEnabled()) {
                                            DataSettings.QUERY_LOG.debug("Dropping Tables: \n{}", sql);
                                        }
                                        try (PreparedStatement ps = connection.prepareStatement(sql)) {
                                            ps.executeUpdate();
                                        }
                                    } catch (SQLException e) {
                                        if (DataSettings.QUERY_LOG.isTraceEnabled()) {
                                            DataSettings.QUERY_LOG.trace("Drop Unsuccessful: " + e.getMessage());
                                        }
                                    }
                                case CREATE:
                                    String sql = builder.buildBatchCreateTableStatement(entities);
                                    if (DataSettings.QUERY_LOG.isDebugEnabled()) {
                                        DataSettings.QUERY_LOG.debug("Creating Tables: \n{}", sql);
                                    }
                                    try (PreparedStatement ps = connection.prepareStatement(sql)) {
                                        ps.executeUpdate();
                                    }
                                    break;
                                default:
                            }
                        } else {
                            switch(schemaGenerate) {
                                case CREATE_DROP:
                                    for (PersistentEntity entity : entities) {
                                        try {
                                            String[] statements = builder.buildDropTableStatements(entity);
                                            for (String sql : statements) {
                                                if (DataSettings.QUERY_LOG.isDebugEnabled()) {
                                                    DataSettings.QUERY_LOG.debug("Dropping Table: \n{}", sql);
                                                }
                                                try (PreparedStatement ps = connection.prepareStatement(sql)) {
                                                    ps.executeUpdate();
                                                }
                                            }
                                        } catch (SQLException e) {
                                            if (DataSettings.QUERY_LOG.isTraceEnabled()) {
                                                DataSettings.QUERY_LOG.trace("Drop Unsuccessful: " + e.getMessage());
                                            }
                                        }
                                    }
                                case CREATE:
                                    for (PersistentEntity entity : entities) {
                                        String[] sql = builder.buildCreateTableStatements(entity);
                                        for (String stmt : sql) {
                                            if (DataSettings.QUERY_LOG.isDebugEnabled()) {
                                                DataSettings.QUERY_LOG.debug("Executing CREATE statement: \n{}", stmt);
                                            }
                                            try {
                                                try (PreparedStatement ps = connection.prepareStatement(stmt)) {
                                                    ps.executeUpdate();
                                                }
                                            } catch (SQLException e) {
                                                if (DataSettings.QUERY_LOG.isWarnEnabled()) {
                                                    DataSettings.QUERY_LOG.warn("CREATE Statement Unsuccessful: " + e.getMessage());
                                                }
                                            }
                                        }
                                    }
                                    break;
                                default:
                            }
                        }
                    } catch (SQLException e) {
                        throw new DataAccessException("Unable to create database schema: " + e.getMessage(), e);
                    }
                } catch (NoSuchBeanException e) {
                    throw new ConfigurationException("No DataSource configured for setting [" + DataJdbcConfiguration.PREFIX + name + "]. Ensure the DataSource is configured correctly and try again.", e);
                }
            }
        }
    }
}
Also used : Connection(java.sql.Connection) ArrayUtils(io.micronaut.core.util.ArrayUtils) MappedEntity(io.micronaut.data.annotation.MappedEntity) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) Internal(io.micronaut.core.annotation.Internal) DelegatingDataSource(io.micronaut.transaction.jdbc.DelegatingDataSource) SQLException(java.sql.SQLException) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) DataSource(javax.sql.DataSource) DataAccessException(io.micronaut.data.exceptions.DataAccessException) BeanLocator(io.micronaut.context.BeanLocator) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) Context(io.micronaut.context.annotation.Context) Collection(java.util.Collection) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) PreparedStatement(java.sql.PreparedStatement) SchemaGenerate(io.micronaut.data.runtime.config.SchemaGenerate) List(java.util.List) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) PersistentEntity(io.micronaut.data.model.PersistentEntity) CollectionUtils(io.micronaut.core.util.CollectionUtils) Dialect(io.micronaut.data.model.query.builder.sql.Dialect) PostConstruct(javax.annotation.PostConstruct) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) BeanIntrospector(io.micronaut.core.beans.BeanIntrospector) DataSettings(io.micronaut.data.runtime.config.DataSettings) Collections(java.util.Collections) SQLException(java.sql.SQLException) NoSuchBeanException(io.micronaut.context.exceptions.NoSuchBeanException) MappedEntity(io.micronaut.data.annotation.MappedEntity) PersistentEntity(io.micronaut.data.model.PersistentEntity) Connection(java.sql.Connection) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) PreparedStatement(java.sql.PreparedStatement) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) DelegatingDataSource(io.micronaut.transaction.jdbc.DelegatingDataSource) DataSource(javax.sql.DataSource) BeanIntrospection(io.micronaut.core.beans.BeanIntrospection) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) Dialect(io.micronaut.data.model.query.builder.sql.Dialect) SchemaGenerate(io.micronaut.data.runtime.config.SchemaGenerate) DataAccessException(io.micronaut.data.exceptions.DataAccessException) PostConstruct(javax.annotation.PostConstruct)

Aggregations

BeanLocator (io.micronaut.context.BeanLocator)3 Context (io.micronaut.context.annotation.Context)3 Internal (io.micronaut.core.annotation.Internal)3 BeanIntrospection (io.micronaut.core.beans.BeanIntrospection)3 BeanIntrospector (io.micronaut.core.beans.BeanIntrospector)3 MappedEntity (io.micronaut.data.annotation.MappedEntity)3 PersistentEntity (io.micronaut.data.model.PersistentEntity)3 RuntimeEntityRegistry (io.micronaut.data.model.runtime.RuntimeEntityRegistry)3 Collection (java.util.Collection)3 List (java.util.List)3 ArrayUtils (io.micronaut.core.util.ArrayUtils)2 CollectionUtils (io.micronaut.core.util.CollectionUtils)2 SqlQueryBuilder (io.micronaut.data.model.query.builder.sql.SqlQueryBuilder)2 DataSettings (io.micronaut.data.runtime.config.DataSettings)2 SchemaGenerate (io.micronaut.data.runtime.config.SchemaGenerate)2 Qualifiers (io.micronaut.inject.qualifiers.Qualifiers)2 PostConstruct (javax.annotation.PostConstruct)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 AbstractMongoConfiguration (io.micronaut.configuration.mongo.core.AbstractMongoConfiguration)1