Search in sources :

Example 1 with SchemaGenerate

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

use of io.micronaut.data.runtime.config.SchemaGenerate 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)2 Context (io.micronaut.context.annotation.Context)2 Internal (io.micronaut.core.annotation.Internal)2 BeanIntrospection (io.micronaut.core.beans.BeanIntrospection)2 BeanIntrospector (io.micronaut.core.beans.BeanIntrospector)2 ArrayUtils (io.micronaut.core.util.ArrayUtils)2 CollectionUtils (io.micronaut.core.util.CollectionUtils)2 MappedEntity (io.micronaut.data.annotation.MappedEntity)2 PersistentEntity (io.micronaut.data.model.PersistentEntity)2 SqlQueryBuilder (io.micronaut.data.model.query.builder.sql.SqlQueryBuilder)2 RuntimeEntityRegistry (io.micronaut.data.model.runtime.RuntimeEntityRegistry)2 DataSettings (io.micronaut.data.runtime.config.DataSettings)2 SchemaGenerate (io.micronaut.data.runtime.config.SchemaGenerate)2 Collection (java.util.Collection)2 List (java.util.List)2 PostConstruct (javax.annotation.PostConstruct)2 ConfigurationException (io.micronaut.context.exceptions.ConfigurationException)1 NoSuchBeanException (io.micronaut.context.exceptions.NoSuchBeanException)1 DataAccessException (io.micronaut.data.exceptions.DataAccessException)1 Dialect (io.micronaut.data.model.query.builder.sql.Dialect)1