Skip to content

Commit

Permalink
spring-projectsGH-685 - Introduce spring.modulith.events.jdbc.schema …
Browse files Browse the repository at this point in the history
…to allow defining the database schema for the event_publication table.
  • Loading branch information
raedbh committed Jul 6, 2024
1 parent debe021 commit 10db3e9
Show file tree
Hide file tree
Showing 8 changed files with 339 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,78 @@
*/
package org.springframework.modulith.events.jdbc;

import java.sql.Connection;

import javax.sql.DataSource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.util.ObjectUtils;

/**
* Initializes the DB schema used to store events
*
* @author Dmitry Belyaev
* @author Björn Kieling
* @author Oliver Drotbohm
* @author Raed Ben Hamouda
*/
interface DatabaseSchemaInitializer extends InitializingBean {}
class DatabaseSchemaInitializer implements InitializingBean {

private final DataSource dataSource;
private final ResourceLoader resourceLoader;
private final DatabaseType databaseType;
private final JdbcTemplate jdbcTemplate;
private final JdbcConfigurationProperties properties;

DatabaseSchemaInitializer(DataSource dataSource, ResourceLoader resourceLoader, DatabaseType databaseType,
JdbcTemplate jdbcTemplate, JdbcConfigurationProperties properties) {

this.dataSource = dataSource;
this.resourceLoader = resourceLoader;
this.databaseType = databaseType;
this.jdbcTemplate = jdbcTemplate;
this.properties = properties;
}

@Override
public void afterPropertiesSet() throws Exception {

String initialSchema;
try (Connection connection = dataSource.getConnection()) {

initialSchema = connection.getSchema();

String schemaName = properties.getSchema();
if (!ObjectUtils.isEmpty(schemaName)) { // A schema name has been specified.

if (eventPublicationTableExists(jdbcTemplate, schemaName)) {
return;
}

jdbcTemplate.execute("CREATE SCHEMA IF NOT EXISTS " + schemaName);
jdbcTemplate.execute(databaseType.sqlStatementSetSchema(schemaName));
}

var locator = new DatabaseSchemaLocator(resourceLoader);
new ResourceDatabasePopulator(locator.getSchemaResource(databaseType)).execute(dataSource);

// Return to the initial schema.
if (initialSchema != null) {
jdbcTemplate.execute(databaseType.sqlStatementSetSchema(initialSchema));
}
}
}

private boolean eventPublicationTableExists(JdbcTemplate jdbcTemplate, String schema) {
String query = """
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = ? AND table_name = 'EVENT_PUBLICATION'
""";
Integer count = jdbcTemplate.queryForObject(query, Integer.class, schema);
return count != null && count > 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
* @author Dmitry Belyaev
* @author Björn Kieling
* @author Oliver Drotbohm
* @author Raed Ben Hamouda
*/
enum DatabaseType {

Expand Down Expand Up @@ -75,4 +76,11 @@ UUID databaseToUUID(Object id) {
String getSchemaResourceFilename() {
return "/schema-" + value + ".sql";
}

String sqlStatementSetSchema(String schema) {
return switch (this) {
case MYSQL, H2, HSQLDB -> "SET SCHEMA " + schema;
case POSTGRES -> "SET search_path TO " + schema;
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2022-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.events.jdbc;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.ConstructorBinding;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.lang.Nullable;

/**
* Configuration properties for JDBC.
*
* @author Raed Ben Hamouda
*/
@ConfigurationProperties(prefix = "spring.modulith.events.jdbc")
class JdbcConfigurationProperties {

private final boolean schemaInitializationEnabled;
private final String schema;

/**
* Creates a new {@link JdbcConfigurationProperties} instance.
*
* @param schemaInitializationEnabled whether to initialize the JDBC event publication schema. Defaults to {@literal false}.
* @param schema the schema name of event publication table, can be {@literal null}.
*/
@ConstructorBinding
JdbcConfigurationProperties(@DefaultValue("false") boolean schemaInitializationEnabled, @Nullable String schema) {

this.schemaInitializationEnabled = schemaInitializationEnabled;
this.schema = schema;
}

/**
* Whether to initialize the JDBC event publication schema.
*/
public boolean isSchemaInitializationEnabled() {
return schemaInitializationEnabled;
}

/**
* The name of the schema where the event publication table resides.
*
* @return can be {@literal null}.
*/
public String getSchema() {
return schema;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.modulith.events.config.EventPublicationAutoConfiguration;
import org.springframework.modulith.events.config.EventPublicationConfigurationExtension;
Expand All @@ -35,9 +35,11 @@
* @author Dmitry Belyaev
* @author Björn Kieling
* @author Oliver Drotbohm
* @author Raed Ben Hamouda
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(EventPublicationAutoConfiguration.class)
@EnableConfigurationProperties(JdbcConfigurationProperties.class)
class JdbcEventPublicationAutoConfiguration implements EventPublicationConfigurationExtension {

@Bean
Expand All @@ -47,22 +49,17 @@ DatabaseType databaseType(DataSource dataSource) {

@Bean
JdbcEventPublicationRepository jdbcEventPublicationRepository(JdbcTemplate jdbcTemplate,
EventSerializer serializer, DatabaseType databaseType) {
EventSerializer serializer, DatabaseType databaseType, JdbcConfigurationProperties properties) {

return new JdbcEventPublicationRepository(jdbcTemplate, serializer, databaseType);
return new JdbcEventPublicationRepository(jdbcTemplate, serializer, databaseType, properties);
}

@Bean
@ConditionalOnProperty(name = "spring.modulith.events.jdbc.schema-initialization.enabled", havingValue = "true")
DatabaseSchemaInitializer databaseSchemaInitializer(DataSource dataSource, ResourceLoader resourceLoader,
DatabaseType databaseType) {
DatabaseType databaseType, JdbcTemplate jdbcTemplate, JdbcConfigurationProperties properties) {

return () -> {

var locator = new DatabaseSchemaLocator(resourceLoader);

new ResourceDatabasePopulator(locator.getSchemaResource(databaseType)).execute(dataSource);
};
return new DatabaseSchemaInitializer(dataSource, resourceLoader, databaseType, jdbcTemplate, properties);
}

private static String fromDataSource(DataSource dataSource) {
Expand Down
Loading

0 comments on commit 10db3e9

Please sign in to comment.