Skip to content

Commit

Permalink
chore: clean codes
Browse files Browse the repository at this point in the history
  • Loading branch information
hantsy committed Dec 12, 2022
1 parent 88120ed commit 625f9ea
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 80 deletions.
23 changes: 20 additions & 3 deletions boot/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@
<skip.integration.tests>true</skip.integration.tests>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>1.17.6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down Expand Up @@ -73,10 +85,15 @@
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
</dependencies>



<build>
<plugins>
<plugin>
Expand Down
67 changes: 2 additions & 65 deletions boot/src/main/java/com/example/demo/DemoApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.data.repository.query.ReactiveQueryByExampleExecutor;
import org.springframework.r2dbc.connection.init.CompositeDatabasePopulator;
import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer;
import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator;
Expand Down Expand Up @@ -70,56 +71,6 @@ public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@Bean
ApplicationRunner initialize(
DatabaseClient databaseClient,
PostRepository posts,
CommentRepository comments,
TransactionalOperator operator
) {
log.info("start data initialization...");
return args -> {
databaseClient
.sql("INSERT INTO posts (title, content, metadata) VALUES (:title, :content, :metadata)")
.filter((statement, executeFunction) -> statement.returnGeneratedValues("id").execute())
.bind("title", "my first post")
.bind("content", "content of my first post")
.bind("metadata", Json.of("{\"tags\":[\"spring\", \"r2dbc\"]}"))
.fetch()
.first()
.subscribe(
data -> log.info("inserted data : {}", data),
error -> log.error("error: {}", error)
);

posts
.save(Post.builder().title("another post").content("content of another post").build())
.map(p -> {
p.setTitle("new Title");
return p;
})
.flatMap(posts::save)
.flatMap(saved -> comments
.save(Comment.builder()
.content("dummy comments")
.postId(saved.getId())
.build()
)
)
.log()
.then()
.thenMany(posts.findAll())
.as(operator::transactional)
.subscribe(
data -> log.info("saved data: {}", data),
err -> log.error("err: {}", err)
);


};

}

@Bean
@Qualifier("pgConnectionFactory")
public ConnectionFactory pgConnectionFactory() {
Expand All @@ -134,20 +85,6 @@ public ConnectionFactory pgConnectionFactory() {
);
}

@Bean
public ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {

ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);

CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("schema.sql")));
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("data.sql")));
initializer.setDatabasePopulator(populator);

return initializer;
}

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
Expand Down Expand Up @@ -423,7 +360,7 @@ public Mono<ServerResponse> delete(ServerRequest req) {
}
}

interface PostRepository extends R2dbcRepository<Post, UUID> {
interface PostRepository extends R2dbcRepository<Post, UUID>, ReactiveQueryByExampleExecutor<Post> {

@Query("SELECT * FROM posts where title like :title")
public Flux<Post> findByTitleContains(String title);
Expand Down
2 changes: 1 addition & 1 deletion boot/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ management.endpoint.health.probes.enabled=true
management.endpoint.health.show-components=always
management.endpoint.health.show-details=always
# embedded, always
spring.sql.init.mode=never
spring.sql.init.mode=always
#
# Logging level
#
Expand Down
1 change: 1 addition & 0 deletions boot/src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
DELETE FROM posts;
INSERT INTO posts (title, content) VALUES ('R2dbc is refined', 'R2dbc is now part of Spring framework core');
INSERT INTO posts (title, content) VALUES ('Spring Data Relational is refined', 'Spring Data R2dbc is now a subproject of Spring Data Relational');
42 changes: 39 additions & 3 deletions boot/src/test/java/com/example/demo/PostRepositoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,18 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.r2dbc.DataR2dbcTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.MountableFile;
import reactor.test.StepVerifier;

import java.time.Duration;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.toList;
Expand All @@ -19,9 +26,23 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;

@DataR2dbcTest()
@Testcontainers
@Slf4j
public class PostRepositoryTest {

@Container
static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer<>("postgres:12")
.withCopyFileToContainer(MountableFile.forClasspathResource("init.sql"), "/docker-entrypoint-initdb.d/init.sql");

@DynamicPropertySource
static void registerDynamicProperties(DynamicPropertyRegistry registry) {
registry.add("spring.r2dbc.url", () -> "r2dbc:postgresql:https://"
+ postgreSQLContainer.getHost() + ":" + postgreSQLContainer.getFirstMappedPort()
+ "/" + postgreSQLContainer.getDatabaseName());
registry.add("spring.r2dbc.username", () -> postgreSQLContainer.getUsername());
registry.add("spring.r2dbc.password", () -> postgreSQLContainer.getPassword());
}

@Autowired
R2dbcEntityTemplate template;

Expand All @@ -30,7 +51,7 @@ public class PostRepositoryTest {

@BeforeEach
public void setup() {
this.template.delete(Post.class).all().block(Duration.ofSeconds(5));

}

@Test
Expand All @@ -43,6 +64,21 @@ public void testPostRepositoryExisted() {
assertNotNull(posts);
}

@Test
public void testQueryByExample() {
var post = Post.builder().title("r2dbc").build();
var exampleMatcher = ExampleMatcher.matching().withMatcher("title", matcher -> matcher.ignoreCase().contains());
var example = Example.of(post, exampleMatcher);
var data = posts.findBy(example, postReactiveFluentQuery -> postReactiveFluentQuery.page(PageRequest.of(0, 10)));

StepVerifier.create(data)
.consumeNextWith(p -> {
log.debug("post data: {}", p.getContent());
assertThat( p.getTotalElements()).isEqualTo(1);
})
.verifyComplete();
}

@Test
public void testInsertAndQuery() {
this.template.insert(Post.builder().title("test title").content("content of test").build())
Expand Down Expand Up @@ -83,7 +119,7 @@ public void testInsertAndCount() {
public void testInsertAndFindByTitleLike() {
var data = IntStream.range(1, 101)
.mapToObj(
i-> Post.builder().title("test title#"+i).content("content of test").build()
i -> Post.builder().title("test title#" + i).content("content of test").build()
)
.collect(toList());
this.posts.saveAll(data)
Expand Down
19 changes: 19 additions & 0 deletions boot/src/test/resources/init.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- There is no 'if not exists' for type
-- But use a 'Drop' will cause exception if the type is applied in table schema.
-- DROP TYPE post_status;

-- The value only accept single quotes.
-- CREATE TYPE post_status AS ENUM( 'DRAFT', 'PENDING_MODERATION', 'PUBLISHED');

-- A simple way to skip exception when creating type if it is existed.
DO $$ BEGIN
CREATE TYPE post_status AS ENUM( 'DRAFT', 'PENDING_MODERATION', 'PUBLISHED');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;

-- Use EnumCodec to handle enum between Java and pg.
-- see: https://github.com/pgjdbc/r2dbc-postgresql#postgres-enum-types
-- CREATE CAST (varchar AS post_status) WITH INOUT AS IMPLICIT;
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
package com.example.demo;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.data.relational.core.query.Query;
import org.springframework.data.relational.core.query.Update;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.UUID;

import static org.springframework.data.relational.core.query.Criteria.where;

public interface PostRepository extends R2dbcRepository<Post, UUID> {
public Flux<Post> findByTitleContains(String name);

public Mono<Long> countByTitleContains(String name);

}
1 change: 1 addition & 0 deletions jooq/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ logging.level.root=info
logging.level.com.example=DEBUG
logging.group.r2dbc=org.springframework.r2dbc,org.springframework.data.r2dbc,org.jooq
logging.level.r2dbc=DEBUG
logging.level.org.jooq.tools.LoggerListener=DEBUG
logging.level.sql=TRACE
logging.level.web=DEBUG

0 comments on commit 625f9ea

Please sign in to comment.