Search in sources :

Example 1 with Dialect

use of io.micronaut.data.model.query.builder.sql.Dialect 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)

Example 2 with Dialect

use of io.micronaut.data.model.query.builder.sql.Dialect in project micronaut-data by micronaut-projects.

the class DefaultJdbcRepositoryOperations method deleteAll.

@Override
public <T> Optional<Number> deleteAll(@NonNull DeleteBatchOperation<T> operation) {
    return Optional.ofNullable(executeWrite(connection -> {
        SqlQueryBuilder queryBuilder = queryBuilders.getOrDefault(operation.getRepositoryType(), DEFAULT_SQL_BUILDER);
        JdbcOperationContext ctx = new JdbcOperationContext(operation.getAnnotationMetadata(), operation.getRepositoryType(), queryBuilder.dialect(), connection);
        Dialect dialect = queryBuilder.dialect();
        RuntimePersistentEntity<T> persistentEntity = getEntity(operation.getRootEntity());
        if (isSupportsBatchDelete(persistentEntity, dialect)) {
            DBOperation dbOperation = new StoredQuerySqlOperation(queryBuilder, operation.getStoredQuery());
            JdbcEntitiesOperations<T> op = new JdbcEntitiesOperations<>(ctx, getEntity(operation.getRootEntity()), operation, dbOperation);
            op.delete();
            return op.rowsUpdated;
        }
        return sum(operation.split().stream().map(deleteOp -> {
            DBOperation dbOperation = new StoredQuerySqlOperation(queryBuilder, operation.getStoredQuery());
            JdbcEntityOperations<T> op = new JdbcEntityOperations<>(ctx, getEntity(deleteOp.getRootEntity()), deleteOp.getEntity(), dbOperation);
            op.delete();
            return op.rowsUpdated;
        }));
    }));
}
Also used : DataType(io.micronaut.data.model.DataType) Arrays(java.util.Arrays) ExecutorReactiveOperations(io.micronaut.data.runtime.operations.ExecutorReactiveOperations) Internal(io.micronaut.core.annotation.Internal) ResultSet(java.sql.ResultSet) Map(java.util.Map) DataJdbcConfiguration(io.micronaut.data.jdbc.config.DataJdbcConfiguration) ArgumentUtils(io.micronaut.core.util.ArgumentUtils) RuntimePersistentProperty(io.micronaut.data.model.runtime.RuntimePersistentProperty) DBOperation(io.micronaut.data.runtime.operations.internal.DBOperation) Set(java.util.Set) PreparedStatement(java.sql.PreparedStatement) Executors(java.util.concurrent.Executors) PreparedQuery(io.micronaut.data.model.runtime.PreparedQuery) Serializable(java.io.Serializable) Stream(java.util.stream.Stream) Dialect(io.micronaut.data.model.query.builder.sql.Dialect) Parameter(io.micronaut.context.annotation.Parameter) SqlDTOMapper(io.micronaut.data.runtime.mapper.sql.SqlDTOMapper) BeanProperty(io.micronaut.core.beans.BeanProperty) ArrayList(java.util.ArrayList) TypeMapper(io.micronaut.data.runtime.mapper.TypeMapper) SQLException(java.sql.SQLException) OperationContext(io.micronaut.data.runtime.operations.internal.OperationContext) Nullable(io.micronaut.core.annotation.Nullable) ReactiveCapableRepository(io.micronaut.data.operations.reactive.ReactiveCapableRepository) ExecutorAsyncOperations(io.micronaut.data.runtime.operations.ExecutorAsyncOperations) StreamSupport(java.util.stream.StreamSupport) Argument(io.micronaut.core.type.Argument) AbstractConversionContext(io.micronaut.data.runtime.support.AbstractConversionContext) JdbcConversionContext(io.micronaut.data.jdbc.convert.JdbcConversionContext) AttributeConverterRegistry(io.micronaut.data.model.runtime.AttributeConverterRegistry) ReactiveRepositoryOperations(io.micronaut.data.operations.reactive.ReactiveRepositoryOperations) StoredQuerySqlOperation(io.micronaut.data.runtime.operations.internal.StoredQuerySqlOperation) InsertBatchOperation(io.micronaut.data.model.runtime.InsertBatchOperation) JoinPath(io.micronaut.data.model.query.JoinPath) Statement(java.sql.Statement) InsertOperation(io.micronaut.data.model.runtime.InsertOperation) AbstractSyncEntitiesOperations(io.micronaut.data.runtime.operations.internal.AbstractSyncEntitiesOperations) UpdateBatchOperation(io.micronaut.data.model.runtime.UpdateBatchOperation) UpdateOperation(io.micronaut.data.model.runtime.UpdateOperation) RuntimePersistentPropertyConversionContext(io.micronaut.data.runtime.convert.RuntimePersistentPropertyConversionContext) Connection(java.sql.Connection) BeanContext(io.micronaut.context.BeanContext) Spliterators(java.util.Spliterators) LoggerFactory(org.slf4j.LoggerFactory) DataSourceUtils(io.micronaut.transaction.jdbc.DataSourceUtils) PreDestroy(javax.annotation.PreDestroy) EachBean(io.micronaut.context.annotation.EachBean) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) DataAccessException(io.micronaut.data.exceptions.DataAccessException) DeleteOperation(io.micronaut.data.model.runtime.DeleteOperation) RuntimeAssociation(io.micronaut.data.model.runtime.RuntimeAssociation) AsyncCapableRepository(io.micronaut.data.operations.async.AsyncCapableRepository) DTOMapper(io.micronaut.data.runtime.mapper.DTOMapper) ConnectionCallback(io.micronaut.data.jdbc.runtime.ConnectionCallback) Predicate(java.util.function.Predicate) SqlResultConsumer(io.micronaut.data.jdbc.mapper.SqlResultConsumer) AbstractSqlRepositoryOperations(io.micronaut.data.runtime.operations.internal.AbstractSqlRepositoryOperations) PreparedStatementCallback(io.micronaut.data.jdbc.runtime.PreparedStatementCallback) Collectors(java.util.stream.Collectors) StoredSqlOperation(io.micronaut.data.runtime.operations.internal.StoredSqlOperation) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) SqlTypeMapper(io.micronaut.data.runtime.mapper.sql.SqlTypeMapper) Spliterator(java.util.Spliterator) Named(jakarta.inject.Named) ColumnIndexResultSetReader(io.micronaut.data.jdbc.mapper.ColumnIndexResultSetReader) QueryParameterBinding(io.micronaut.data.model.runtime.QueryParameterBinding) TransactionOperations(io.micronaut.transaction.TransactionOperations) ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RuntimeEntityRegistry(io.micronaut.data.model.runtime.RuntimeEntityRegistry) Function(java.util.function.Function) DelegatingDataSource(io.micronaut.transaction.jdbc.DelegatingDataSource) JdbcQueryStatement(io.micronaut.data.jdbc.mapper.JdbcQueryStatement) Page(io.micronaut.data.model.Page) DataSource(javax.sql.DataSource) OpContext(io.micronaut.data.runtime.operations.internal.OpContext) NoSuchElementException(java.util.NoSuchElementException) DateTimeProvider(io.micronaut.data.runtime.date.DateTimeProvider) ExecutorService(java.util.concurrent.ExecutorService) MediaTypeCodec(io.micronaut.http.codec.MediaTypeCodec) PagedQuery(io.micronaut.data.model.runtime.PagedQuery) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) AbstractSyncEntityOperations(io.micronaut.data.runtime.operations.internal.AbstractSyncEntityOperations) DataConversionService(io.micronaut.data.runtime.convert.DataConversionService) ResultConsumer(io.micronaut.data.runtime.mapper.ResultConsumer) SyncCascadeOperations(io.micronaut.data.runtime.operations.internal.SyncCascadeOperations) Consumer(java.util.function.Consumer) NonNull(io.micronaut.core.annotation.NonNull) ConversionContext(io.micronaut.core.convert.ConversionContext) ColumnNameResultSetReader(io.micronaut.data.jdbc.mapper.ColumnNameResultSetReader) DeleteBatchOperation(io.micronaut.data.model.runtime.DeleteBatchOperation) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) RuntimePersistentEntity(io.micronaut.data.model.runtime.RuntimePersistentEntity) ResultReader(io.micronaut.data.runtime.mapper.ResultReader) SqlResultEntityTypeMapper(io.micronaut.data.runtime.mapper.sql.SqlResultEntityTypeMapper) DBOperation(io.micronaut.data.runtime.operations.internal.DBOperation) RuntimePersistentEntity(io.micronaut.data.model.runtime.RuntimePersistentEntity) SqlQueryBuilder(io.micronaut.data.model.query.builder.sql.SqlQueryBuilder) Dialect(io.micronaut.data.model.query.builder.sql.Dialect) StoredQuerySqlOperation(io.micronaut.data.runtime.operations.internal.StoredQuerySqlOperation)

Aggregations

Internal (io.micronaut.core.annotation.Internal)2 DataAccessException (io.micronaut.data.exceptions.DataAccessException)2 Dialect (io.micronaut.data.model.query.builder.sql.Dialect)2 SqlQueryBuilder (io.micronaut.data.model.query.builder.sql.SqlQueryBuilder)2 RuntimeEntityRegistry (io.micronaut.data.model.runtime.RuntimeEntityRegistry)2 DelegatingDataSource (io.micronaut.transaction.jdbc.DelegatingDataSource)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2 List (java.util.List)2 DataSource (javax.sql.DataSource)2 BeanContext (io.micronaut.context.BeanContext)1 BeanLocator (io.micronaut.context.BeanLocator)1 Context (io.micronaut.context.annotation.Context)1 EachBean (io.micronaut.context.annotation.EachBean)1 Parameter (io.micronaut.context.annotation.Parameter)1 ConfigurationException (io.micronaut.context.exceptions.ConfigurationException)1 NoSuchBeanException (io.micronaut.context.exceptions.NoSuchBeanException)1 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)1 NonNull (io.micronaut.core.annotation.NonNull)1