4
4
import io .r2dbc .postgresql .PostgresqlConnectionFactory ;
5
5
import io .r2dbc .spi .ConnectionFactory ;
6
6
7
+ import java .util .function .Supplier ;
8
+
7
9
import javax .sql .DataSource ;
8
10
9
11
import org .postgresql .ds .PGSimpleDataSource ;
18
20
*/
19
21
public class PostgresTestSupport {
20
22
21
- private static final PostgreSQLContainer POSTGRESQL_CONTAINER = new PostgreSQLContainer () ;
23
+ private static ExternalDatabase testContainerDatabase ;
22
24
23
25
public static String CREATE_TABLE_LEGOSET = "CREATE TABLE legoset (\n " //
24
26
+ " id integer CONSTRAINT id PRIMARY KEY,\n " //
@@ -41,11 +43,29 @@ public class PostgresTestSupport {
41
43
*/
42
44
public static ExternalDatabase database () {
43
45
44
- ExternalDatabase local = local ();
45
- if (local .checkValidity ()) {
46
- return local ;
46
+ if (Boolean .getBoolean ("spring.data.r2dbc.test.preferLocalDatabase" )) {
47
+
48
+ return getFirstWorkingDatabase ( //
49
+ PostgresTestSupport ::local , //
50
+ PostgresTestSupport ::testContainer //
51
+ );
52
+ } else {
53
+
54
+ return getFirstWorkingDatabase ( //
55
+ PostgresTestSupport ::testContainer , //
56
+ PostgresTestSupport ::local //
57
+ );
58
+ }
59
+ }
60
+
61
+ private static ExternalDatabase getFirstWorkingDatabase (Supplier <ExternalDatabase > first ,
62
+ Supplier <ExternalDatabase > second ) {
63
+
64
+ ExternalDatabase database = first .get ();
65
+ if (database .checkValidity ()) {
66
+ return database ;
47
67
} else {
48
- return testContainer ();
68
+ return second . get ();
49
69
}
50
70
}
51
71
@@ -67,14 +87,27 @@ private static ExternalDatabase local() {
67
87
*/
68
88
private static ExternalDatabase testContainer () {
69
89
70
- POSTGRESQL_CONTAINER . start ();
90
+ if ( testContainerDatabase == null ) {
71
91
72
- return ProvidedDatabase .builder () //
73
- .hostname ("localhost" ) //
74
- .port (POSTGRESQL_CONTAINER .getFirstMappedPort ()) //
75
- .database (POSTGRESQL_CONTAINER .getDatabaseName ()) //
76
- .username (POSTGRESQL_CONTAINER .getUsername ()) //
77
- .password (POSTGRESQL_CONTAINER .getPassword ()).build ();
92
+ try {
93
+ PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer ();
94
+ postgreSQLContainer .start ();
95
+
96
+ testContainerDatabase = ProvidedDatabase .builder () //
97
+ .hostname ("localhost" ) //
98
+ .port (postgreSQLContainer .getFirstMappedPort ()) //
99
+ .database (postgreSQLContainer .getDatabaseName ()) //
100
+ .username (postgreSQLContainer .getUsername ()) //
101
+ .password (postgreSQLContainer .getPassword ()).build ();
102
+
103
+ } catch (IllegalStateException ise ) {
104
+ // docker is not available.
105
+ testContainerDatabase = new ExternalDatabase .NoSuchDatabase ();
106
+ }
107
+
108
+ }
109
+
110
+ return testContainerDatabase ;
78
111
}
79
112
80
113
/**
@@ -106,4 +139,5 @@ public static DataSource createDataSource(ExternalDatabase database) {
106
139
107
140
return dataSource ;
108
141
}
142
+
109
143
}
0 commit comments