Skip to content

Commit

Permalink
Support data.sql in Spring Data JPA module
Browse files Browse the repository at this point in the history
  • Loading branch information
geoand authored and poldinik committed Apr 29, 2024
1 parent 0e4f98f commit cce47db
Show file tree
Hide file tree
Showing 7 changed files with 230 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.quarkus.spring.data.deployment;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.smallrye.config.PropertiesConfigSource;
import io.smallrye.config.SmallRyeConfigBuilder;
import io.smallrye.config.SmallRyeConfigBuilderCustomizer;

public class SqlFileConfigBuilderCustomizer implements SmallRyeConfigBuilderCustomizer {
@Override
public void configBuilder(SmallRyeConfigBuilder builder) {
List<String> supportedSqlFiles = List.of("import.sql", "data.sql");
List<String> sqlFilesThatExist = new ArrayList<>();

for (String sqlFile : supportedSqlFiles) {
URL resource = Thread.currentThread().getContextClassLoader().getResource(sqlFile);
// we only check for files that are part of the application itself,
// this is done as to follow what the HibernateOrmProcessor does
if ((resource != null) && !resource.getProtocol().equals("jar")) {
sqlFilesThatExist.add(sqlFile);
}
}

// use a priority of 50 to make sure that this is overridable by any of the standard methods
if (!sqlFilesThatExist.isEmpty()) {
builder.withSources(
new PropertiesConfigSource(
Map.of("quarkus.hibernate-orm.sql-load-script", String.join(",", sqlFilesThatExist)),
"quarkus-spring-data-jpa", 50));
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
io.quarkus.spring.data.deployment.SqlFileConfigBuilderCustomizer
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.quarkus.spring.data.deployment;

import static org.assertj.core.api.Assertions.assertThat;

import jakarta.inject.Inject;
import jakarta.transaction.Transactional;

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.test.QuarkusUnitTest;

public class BothImportAndDataSqlTest {

@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource("users1.sql", "data.sql")
.addAsResource("users2.sql", "import.sql")
.addClasses(User.class, LoginEvent.class, UserRepository.class))
.withConfigurationResource("application.properties");

@Inject
UserRepository repo;

@Test
@Transactional
public void test() {
assertThat(repo.count()).isEqualTo(2);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package io.quarkus.spring.data.deployment;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.ZonedDateTime;
import java.util.Optional;

import jakarta.inject.Inject;
import jakarta.transaction.Transactional;

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

import io.quarkus.test.QuarkusUnitTest;

public class ModifyingQueryWithFlushAndClearUsingDataSqlTest {

@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource("import_users.sql", "data.sql")
.addClasses(User.class, LoginEvent.class, UserRepository.class))
.withConfigurationResource("application.properties");

@Inject
UserRepository repo;

@BeforeEach
@Transactional
public void setUp() {
final User user = getUser("JOHN");
user.setLoginCounter(0);
repo.save(user);
}

@Test
@Transactional
public void testNoAutoClear() {
getUser("JOHN"); // read user to attach it to entity manager

repo.incrementLoginCounterPlain("JOHN");

final User userAfterIncrement = getUser("JOHN"); // we get the cached entity
// the read doesn't re-read the incremented counter and is therefore equal to the old value
assertThat(userAfterIncrement.getLoginCounter()).isEqualTo(0);
}

@Test
@Transactional
public void testAutoClear() {
getUser("JOHN"); // read user to attach it to entity manager

repo.incrementLoginCounterAutoClear("JOHN");

final User userAfterIncrement = getUser("JOHN");
assertThat(userAfterIncrement.getLoginCounter()).isEqualTo(1);
}

@Test
@Transactional
public void testNoAutoFlush() {
final User user = getUser("JOHN");
createLoginEvent(user);

repo.processLoginEventsPlain();

final User verifyUser = getUser("JOHN");
// processLoginEvents did not see the new login event
final boolean allProcessed = verifyUser.getLoginEvents().stream()
.allMatch(loginEvent -> loginEvent.isProcessed());
assertThat(allProcessed).describedAs("all LoginEvents are marked as processed").isFalse();
}

@Test
@Transactional
public void testAutoFlush() {
final User user = getUser("JOHN");
createLoginEvent(user);

repo.processLoginEventsPlainAutoClearAndFlush();

final User verifyUser = getUser("JOHN");
final boolean allProcessed = verifyUser.getLoginEvents().stream()
.allMatch(loginEvent -> loginEvent.isProcessed());
assertThat(allProcessed).describedAs("all LoginEvents are marked as processed").isTrue();
}

@Test
@Transactional
public void testNamedQueryOnEntities() {
User user = repo.getUserByFullNameUsingNamedQuery("John Doe");
assertThat(user).isNotNull();
}

@Test
@Transactional
public void testNamedQueriesOnEntities() {
User user = repo.getUserByFullNameUsingNamedQueries("John Doe");
assertThat(user).isNotNull();
}

private LoginEvent createLoginEvent(User user) {
final LoginEvent loginEvent = new LoginEvent();
loginEvent.setUser(user);
loginEvent.setZonedDateTime(ZonedDateTime.now());
user.addEvent(loginEvent);
return loginEvent;
}

private User getUser(String userId) {
final Optional<User> user = repo.findById(userId);
assertThat(user).describedAs("user <%s>", userId).isPresent();
return user.get();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.quarkus.spring.data.devmode;

import static org.hamcrest.CoreMatchers.containsString;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusDevModeTest;
import io.restassured.RestAssured;

public class RepositoryReloadWithDataSqlTest {

@RegisterExtension
static QuarkusDevModeTest TEST = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar
.addAsResource("application.properties")
.addAsResource("import_books.sql", "data.sql")
.addClasses(Book.class, BookRepository.class, BookResource.class));

@Test
public void testRepositoryIsReloaded() {
RestAssured.get("/book").then()
.statusCode(200)
.body(containsString("Strangers"), containsString("Ascent"), containsString("Everything"));

TEST.modifySourceFile("BookRepository.java", s -> s.replace("// <placeholder>",
"java.util.Optional<Book> findById(Integer id);"));

TEST.modifySourceFile("BookResource.java", s -> s.replace("// <placeholder>",
"@GET @Path(\"/{id}\") @Produces(MediaType.APPLICATION_JSON)\n" +
" public java.util.Optional<Book> findById(@jakarta.ws.rs.PathParam(\"id\") Integer id) {\n" +
" return bookRepository.findById(id);\n" +
" }"));

RestAssured.get("/book/1").then()
.statusCode(200)
.body(containsString("Strangers"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO user_(userid, fullname, logincounter, active) VALUES ('JOHN', 'John Doe', 0, true);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
INSERT INTO user_(userid, fullname, logincounter, active) VALUES ('JANE', 'Jane Doe', 1, true);

0 comments on commit cce47db

Please sign in to comment.