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);
}
}
}
}
}
}
}
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();
}
}
}
}
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);
}
}
}
}
}
Aggregations