6
6
import org .springframework .beans .factory .annotation .Value ;
7
7
import org .springframework .boot .jdbc .DataSourceBuilder ;
8
8
import org .springframework .context .annotation .Bean ;
9
- import org .springframework .context .annotation .Primary ;
10
9
11
10
import javax .sql .DataSource ;
12
11
import java .sql .*;
13
12
import java .util .Optional ;
14
13
15
14
@ Slf4j
16
- public class PostgresConfiguration {
15
+ abstract public class AbstractPostgresConfig {
17
16
private static final String RESOURCE_TYPE = "sqldb.blockware.com/v1/postgresql" ;
18
17
19
18
private static final String PORT_TYPE = "postgres" ;
@@ -24,37 +23,37 @@ public class PostgresConfiguration {
24
23
@ Autowired
25
24
private BlockwareClusterService blockwareClusterService ;
26
25
27
- private String getDatabaseName () {
28
- return applicationName ;
26
+ private final String resourceName ;
27
+
28
+ public AbstractPostgresConfig (String resourceName ) {
29
+ this .resourceName = resourceName ;
29
30
}
30
31
31
32
@ Bean
32
- @ Primary
33
33
public DataSource dataSource () {
34
34
35
- final BlockwareClusterService .ResourceInfo info = blockwareClusterService .getResourceInfo (RESOURCE_TYPE , PORT_TYPE );
35
+ final BlockwareClusterService .ResourceInfo info = blockwareClusterService .getResourceInfo (RESOURCE_TYPE , PORT_TYPE , resourceName );
36
36
Optional <String > dbUsername = Optional .ofNullable (info .getCredentials ().get ("username" ));
37
37
Optional <String > dbPassword = Optional .ofNullable (info .getCredentials ().get ("password" ));
38
38
39
+ String databaseName = String .valueOf (info .getOptions ().getOrDefault ("dbName" , resourceName ));
40
+
39
41
String jdbcBaseUrl = String .format ("jdbc:postgresql://%s:%s" , info .getHost (), info .getPort ());
40
42
41
- log .info ("Connecting to postgres server: {}" , jdbcBaseUrl );
43
+ log .info ("Connecting to postgres server: {} for database: {} " , jdbcBaseUrl , databaseName );
42
44
43
- String jdbcUrl = String .format ("%s/%s" , jdbcBaseUrl , getDatabaseName () );
45
+ String jdbcUrl = String .format ("%s/%s" , jdbcBaseUrl , databaseName );
44
46
45
47
final DataSourceBuilder <?> builder = DataSourceBuilder .create ();
46
48
47
49
builder .url (jdbcUrl );
48
50
49
- if (dbUsername .isPresent ()) {
50
- builder .username (dbUsername .get ())
51
- .password (dbPassword .orElse ("" ));
52
- }
53
-
51
+ dbUsername .ifPresent (s -> builder .username (s )
52
+ .password (dbPassword .orElse ("" )));
54
53
55
54
try {
56
55
ensureDatabase (jdbcBaseUrl ,
57
- getDatabaseName () ,
56
+ databaseName ,
58
57
dbUsername .orElse (null ),
59
58
dbPassword .orElse (null )
60
59
);
0 commit comments