Skip to content

Commit

Permalink
Merge pull request #20488 from mschnitzler/20177-multiple-sql-load-sc…
Browse files Browse the repository at this point in the history
…ripts

Add support for multiple sql load scripts
  • Loading branch information
geoand authored Oct 4, 2021
2 parents fdb9f5e + efa073f commit e0d19f3
Show file tree
Hide file tree
Showing 8 changed files with 133 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.nio.charset.Charset;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
Expand Down Expand Up @@ -70,7 +71,7 @@ public class HibernateOrmConfigPersistenceUnit {
*/
// @formatter:on
@ConfigItem(defaultValueDocumentation = "import.sql in DEV, TEST ; no-file otherwise")
public Optional<String> sqlLoadScript;
public Optional<List<String>> sqlLoadScript;

/**
* The size of the batches used when loading entities and collections.
Expand Down Expand Up @@ -446,4 +447,4 @@ public boolean isAnyPropertySet() {
return ignoreExplicitForJoined;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -769,18 +769,16 @@ public void registerInjectServiceMethodsForReflection(CombinedIndexBuildItem ind
}
}

private static Optional<String> getSqlLoadScript(Optional<String> sqlLoadScript, LaunchMode launchMode) {
private static List<String> getSqlLoadScript(Optional<List<String>> sqlLoadScript, LaunchMode launchMode) {
// Explicit file or default Hibernate ORM file.
if (sqlLoadScript.isPresent()) {
if (NO_SQL_LOAD_SCRIPT_FILE.equalsIgnoreCase(sqlLoadScript.get())) {
return Optional.empty();
} else {
return Optional.of(sqlLoadScript.get());
}
return sqlLoadScript.get().stream()
.filter(s -> !NO_SQL_LOAD_SCRIPT_FILE.equalsIgnoreCase(s))
.collect(Collectors.toList());
} else if (launchMode == LaunchMode.NORMAL) {
return Optional.empty();
return Collections.emptyList();
} else {
return Optional.of("import.sql");
return List.of("import.sql");
}
}

Expand Down Expand Up @@ -1021,26 +1019,33 @@ private static void producePersistenceUnitDescriptorFromConfig(
descriptor.getProperties().setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
}

// sql-load-script
Optional<String> importFile = getSqlLoadScript(persistenceUnitConfig.sqlLoadScript, launchMode);
// sql-load-scripts
List<String> importFiles = getSqlLoadScript(persistenceUnitConfig.sqlLoadScript, launchMode);

if (importFile.isPresent()) {
Path loadScriptPath = applicationArchivesBuildItem.getRootArchive().getChildPath(importFile.get());
if (!importFiles.isEmpty()) {
for (String importFile : importFiles) {
Path loadScriptPath = applicationArchivesBuildItem.getRootArchive().getChildPath(importFile);

if (loadScriptPath != null && !Files.isDirectory(loadScriptPath)) {
// enlist resource if present
nativeImageResources.produce(new NativeImageResourceBuildItem(importFile.get()));
descriptor.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, importFile.get());
} else if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
//raise exception if explicit file is not present (i.e. not the default)
throw new ConfigurationError(
"Unable to find file referenced in '"
+ HibernateOrmConfig.puPropertyKey(persistenceUnitName, "sql-load-script") + "="
+ persistenceUnitConfig.sqlLoadScript.get() + "'. Remove property or add file to your path.");
if (loadScriptPath != null && !Files.isDirectory(loadScriptPath)) {
// enlist resource if present
nativeImageResources.produce(new NativeImageResourceBuildItem(importFile));
} else if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
//raise exception if explicit file is not present (i.e. not the default)
throw new ConfigurationError(
"Unable to find file referenced in '"
+ HibernateOrmConfig.puPropertyKey(persistenceUnitName, "sql-load-script") + "="
+ String.join(",", persistenceUnitConfig.sqlLoadScript.get())
+ "'. Remove property or add file to your path.");
}
// in dev mode we want to make sure that we watch for changes to file even if it doesn't currently exist
// as a user could still add it after performing the initial configuration
hotDeploymentWatchedFiles.produce(new HotDeploymentWatchedFileBuildItem(importFile));
}

// only set the found import files if configured
if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
descriptor.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, String.join(",", importFiles));
}
// in dev mode we want to make sure that we watch for changes to file even if it doesn't currently exist
// as a user could still add it after performing the initial configuration
hotDeploymentWatchedFiles.produce(new HotDeploymentWatchedFileBuildItem(importFile.get()));
} else {
//Disable implicit loading of the default import script (import.sql)
descriptor.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, "");
Expand Down Expand Up @@ -1501,4 +1506,4 @@ static final class CachedProxy {
this.interfaces = interfaces;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package io.quarkus.hibernate.orm.sql_load_script;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.deployment.configuration.ConfigurationError;
import io.quarkus.hibernate.orm.MyEntity;
import io.quarkus.test.QuarkusUnitTest;

public class ImportMultipleSqlLoadScriptsFileAbsentTestCase {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.setExpectedException(ConfigurationError.class)
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(MyEntity.class, SqlLoadScriptTestResource.class)
.addAsResource("application-import-multiple-load-scripts-test.properties", "application.properties")
.addAsResource("import-multiple-load-scripts-1.sql", "import-1.sql"));

@Test
public void testImportMultipleSqlLoadScriptsTest() {
// should not be called, deployment exception should happen first:
// it's illegal to have Hibernate sql-load-script configuration property set
// to an absent file
Assertions.fail();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package io.quarkus.hibernate.orm.sql_load_script;

import org.hamcrest.Matchers;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.hibernate.orm.MyEntity;
import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;

public class ImportMultipleSqlLoadScriptsTestCase {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(MyEntity.class, SqlLoadScriptTestResource.class)
.addAsResource("application-import-multiple-load-scripts-test.properties", "application.properties")
.addAsResource("import-multiple-load-scripts-1.sql", "import-1.sql")
.addAsResource("import-multiple-load-scripts-2.sql", "import-2.sql"));

@Test
public void testImportMultipleSqlLoadScriptsTest() {
String name1 = "import-1.sql load script entity";
String name2 = "import-2.sql load script entity";

RestAssured.when().get("/orm-sql-load-script/1").then().body(Matchers.is(name1));
RestAssured.when().get("/orm-sql-load-script/2").then().body(Matchers.is(name2));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:test

quarkus.hibernate-orm.dialect=org.hibernate.dialect.H2Dialect
#quarkus.hibernate-orm.log.sql=true
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.hibernate-orm.sql-load-script=import-1.sql,import-2.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO MyEntity(id, name) VALUES(1, 'import-1.sql load script entity');
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO MyEntity(id, name) VALUES(2, 'import-2.sql load script entity');
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.persistence.SharedCacheMode;
import javax.persistence.spi.PersistenceUnitTransactionType;
Expand Down Expand Up @@ -292,22 +294,28 @@ private static ParsedPersistenceXmlDescriptor generateReactivePersistenceUnit(
}

// sql-load-script
Optional<String> importFile = getSqlLoadScript(persistenceUnitConfig.sqlLoadScript, launchMode);

if (importFile.isPresent()) {
Path loadScriptPath = applicationArchivesBuildItem.getRootArchive().getChildPath(importFile.get());

if (loadScriptPath != null && !Files.isDirectory(loadScriptPath)) {
// enlist resource if present
nativeImageResources.produce(new NativeImageResourceBuildItem(importFile.get()));
hotDeploymentWatchedFiles.produce(new HotDeploymentWatchedFileBuildItem(importFile.get()));
desc.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, importFile.get());
} else if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
//raise exception if explicit file is not present (i.e. not the default)
throw new ConfigurationError(
"Unable to find file referenced in '"
+ HibernateOrmConfig.puPropertyKey(persistenceUnitConfigName, "sql-load-script") + "="
+ persistenceUnitConfig.sqlLoadScript.get() + "'. Remove property or add file to your path.");
List<String> importFiles = getSqlLoadScript(persistenceUnitConfig.sqlLoadScript, launchMode);

if (!importFiles.isEmpty()) {
for (String importFile : importFiles) {
Path loadScriptPath = applicationArchivesBuildItem.getRootArchive().getChildPath(importFile);

if (loadScriptPath != null && !Files.isDirectory(loadScriptPath)) {
// enlist resource if present
nativeImageResources.produce(new NativeImageResourceBuildItem(importFile));
hotDeploymentWatchedFiles.produce(new HotDeploymentWatchedFileBuildItem(importFile));
} else if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
//raise exception if explicit file is not present (i.e. not the default)
throw new ConfigurationError(
"Unable to find file referenced in '"
+ HibernateOrmConfig.puPropertyKey(persistenceUnitConfigName, "sql-load-script") + "="
+ String.join(",", persistenceUnitConfig.sqlLoadScript.get())
+ "'. Remove property or add file to your path.");
}
}

if (persistenceUnitConfig.sqlLoadScript.isPresent()) {
desc.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, String.join(",", importFiles));
}
} else {
//Disable implicit loading of the default import script (import.sql)
Expand Down Expand Up @@ -342,23 +350,21 @@ private static void setMaxFetchDepth(ParsedPersistenceXmlDescriptor descriptor,
descriptor.getProperties().setProperty(AvailableSettings.MAX_FETCH_DEPTH, String.valueOf(maxFetchDepth.getAsInt()));
}

private static Optional<String> getSqlLoadScript(Optional<String> sqlLoadScript, LaunchMode launchMode) {
private static List<String> getSqlLoadScript(Optional<List<String>> sqlLoadScript, LaunchMode launchMode) {
// Explicit file or default Hibernate ORM file.
if (sqlLoadScript.isPresent()) {
if (HibernateOrmProcessor.NO_SQL_LOAD_SCRIPT_FILE.equalsIgnoreCase(sqlLoadScript.get())) {
return Optional.empty();
} else {
return Optional.of(sqlLoadScript.get());
}
return sqlLoadScript.get().stream()
.filter(s -> !HibernateOrmProcessor.NO_SQL_LOAD_SCRIPT_FILE.equalsIgnoreCase(s))
.collect(Collectors.toList());
} else if (launchMode == LaunchMode.NORMAL) {
return Optional.empty();
return Collections.emptyList();
} else {
return Optional.of("import.sql");
return List.of("import.sql");
}
}

private boolean hasEntities(JpaModelBuildItem jpaModel) {
return !jpaModel.getEntityClassNames().isEmpty();
}

}
}

0 comments on commit e0d19f3

Please sign in to comment.