Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kie-issues#1816: Make kie-flyway sanitize DataSource product name before loading migrations. #3843

Merged
merged 2 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions addons/common/flyway/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,21 @@

package org.kie.flyway.initializer;

import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.kie.flyway.KieFlywayException;
import org.kie.flyway.initializer.db.DataBaseInfo;
import org.kie.flyway.initializer.impl.DefaultKieModuleFlywayConfigLoader;
import org.kie.flyway.model.KieFlywayModuleConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.util.stream.Collectors.groupingBy;
import static org.kie.flyway.initializer.db.KieFlywayDataBaseHelper.readDataBaseInfo;

public class KieFlywayInitializer {
private static final String KIE_FLYWAY_BASELINE_VERSION = "0.0";
Expand All @@ -45,13 +46,13 @@ public class KieFlywayInitializer {

private final KieModuleFlywayConfigLoader configLoader;
private final DataSource dataSource;
private final String databaseType;
private final DataBaseInfo databaseInfo;
private final List<String> moduleExclusions;

private KieFlywayInitializer(KieModuleFlywayConfigLoader configLoader, DataSource dataSource, Collection<String> moduleExclusions) {
this.configLoader = configLoader;
this.dataSource = dataSource;
this.databaseType = getDataSourceType(dataSource);
this.databaseInfo = readDataBaseInfo(dataSource);
this.moduleExclusions = new ArrayList<>(moduleExclusions);
}

Expand Down Expand Up @@ -80,15 +81,6 @@ private void checkDuplicatedModuleConfigs(Collection<KieFlywayModuleConfig> conf
}
}

private String getDataSourceType(DataSource dataSource) {
try (Connection con = dataSource.getConnection()) {
return con.getMetaData().getDatabaseProductName().toLowerCase();
} catch (Exception e) {
LOGGER.error("Kie Flyway: Couldn't extract database product name from datasource ", e);
throw new KieFlywayException("Kie Flyway: Couldn't extract database product name from datasource.", e);
}
}

private void runFlyway(KieFlywayModuleConfig config) {
LOGGER.debug("Running Flyway for module: {}", config.getModule());

Expand All @@ -97,11 +89,11 @@ private void runFlyway(KieFlywayModuleConfig config) {
return;
}

String[] locations = config.getDBScriptLocations(databaseType);
String[] locations = config.getDBScriptLocations(databaseInfo.getNormalizedName());

if (Objects.isNull(locations)) {
LOGGER.warn("Cannot run Flyway migration for module `{}`, cannot find SQL Script locations for db `{}`", config.getModule(), databaseType);
throw new KieFlywayException("Cannot run Flyway migration for module `" + config.getModule() + "`, cannot find SQL Script locations for db `" + databaseType + "`");
LOGGER.warn("Cannot run Flyway migration for module `{}`, cannot find SQL Script locations for db `{}`", config.getModule(), databaseInfo);
throw new KieFlywayException("Cannot run Flyway migration for module `" + config.getModule() + "`, cannot find SQL Script locations for db `" + databaseInfo + "`");
Comment on lines +95 to +96
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nicely done @pefernan.

Just wondering if we need to override toString() to print the database info

}

Flyway.configure()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* http://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.kie.flyway.initializer.db;

public class DataBaseInfo {

private final String name;
private final String version;
private final String normalizedName;

public DataBaseInfo(String name, String version) {
this.name = name;
this.version = version;
this.normalizedName = normalizeName(name);
}

public String getName() {
return name;
}

public String getVersion() {
return version;
}

public String getNormalizedName() {
return normalizedName;
}

private String normalizeName(String name) {
final String NORMALIZATION_REGEX = "[^a-zA-Z0-9]+";
String[] fragments = name.split(NORMALIZATION_REGEX);
return String.join("-", fragments).toLowerCase();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* http://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.kie.flyway.initializer.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;

import javax.sql.DataSource;

import org.kie.flyway.KieFlywayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KieFlywayDataBaseHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(KieFlywayDataBaseHelper.class);

private KieFlywayDataBaseHelper() {
}

public static DataBaseInfo readDataBaseInfo(DataSource ds) {
try (Connection con = ds.getConnection()) {

DatabaseMetaData metadata = con.getMetaData();

String name = metadata.getDatabaseProductName();
String version = metadata.getDatabaseProductVersion();

LOGGER.info("Reading DataBase Product: '{}' Version: '{}'", name, version);

return new DataBaseInfo(name, version);
} catch (Exception e) {
LOGGER.error("Kie Flyway: Couldn't extract database product name from datasource ", e);
throw new KieFlywayException("Kie Flyway: Couldn't extract database product name from datasource.", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* http://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.kie.flyway.initializer.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.stream.Stream;

import javax.sql.DataSource;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.kie.flyway.KieFlywayException;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.kie.flyway.initializer.db.KieFlywayDataBaseHelper.readDataBaseInfo;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class KieFlywayDataBaseHelperTest {

@Mock
private DataSource dataSource;

@Mock
private Connection connection;

@Mock
private DatabaseMetaData metaData;

@BeforeEach
public void setup() throws Exception {
when(dataSource.getConnection()).thenReturn(connection);
when(connection.getMetaData()).thenReturn(metaData);
}

@Test
public void testReadDataBaseInfoWithException() {
Assertions.assertThatThrownBy(() -> readDataBaseInfo(dataSource))
.isInstanceOf(KieFlywayException.class)
.hasMessage("Kie Flyway: Couldn't extract database product name from datasource.");
}

@ParameterizedTest
@MethodSource("getDataBaseData")
public void testReadDataBaseInfo(String productName, String version, String normalizedName) throws Exception {
when(metaData.getDatabaseProductName()).thenReturn(productName);
when(metaData.getDatabaseProductVersion()).thenReturn(version);

Assertions.assertThat(readDataBaseInfo(dataSource))
.hasFieldOrPropertyWithValue("name", productName)
.hasFieldOrPropertyWithValue("version", version)
.hasFieldOrPropertyWithValue("normalizedName", normalizedName);
}

public static Stream<Arguments> getDataBaseData() {
return Stream.of(Arguments.of("H2", "2.3.232", "h2"),
Arguments.of("PostgreSQL", "42.7.4", "postgresql"),
Arguments.of("My Custom DB Type.", "v1.0", "my-custom-db-type"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

public class PostgreSQLTestDataSource implements TestDataSource {

private PGSimpleDataSource dataSource;
private final PGSimpleDataSource dataSource;

public PostgreSQLTestDataSource(KogitoPostgreSqlContainer pgContainer) {
dataSource = new PGSimpleDataSource();
Expand Down