001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 * http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package de.softwareforge.testing.postgres.embedded;
015
016import static com.google.common.base.Preconditions.checkState;
017import static java.lang.String.format;
018
019import java.sql.SQLException;
020import java.util.Optional;
021import java.util.stream.Collectors;
022import javax.sql.DataSource;
023
024import com.google.auto.value.AutoValue;
025import com.google.common.collect.ImmutableMap;
026import edu.umd.cs.findbugs.annotations.NonNull;
027
028/**
029 * Information about a database located on a PostgreSQL server connected to an {@link EmbeddedPostgres} instance.
030 */
031@AutoValue
032public abstract class DatabaseInfo {
033
034    private static final String JDBC_FORMAT = "jdbc:postgresql://localhost:%d/%s?user=%s";
035
036    DatabaseInfo() {
037    }
038
039    /**
040     * The default user used for databases.
041     */
042    static final String PG_DEFAULT_USER = "postgres";
043
044    /**
045     * The default database name.
046     */
047    static final String PG_DEFAULT_DB = "postgres";
048
049    /**
050     * Returns the name of the database.
051     *
052     * @return Name of the database. Is never null.
053     */
054    @NonNull
055    public abstract String dbName();
056
057    /**
058     * Returns the TCP port for the database server.
059     *
060     * @return A port number. May be -1 if this objects represents an error connection.
061     */
062    public abstract int port();
063
064    /**
065     * Returns the user that can connect to this database.
066     *
067     * @return The user name. Is never null.
068     */
069    @NonNull
070    public abstract String user();
071
072    /**
073     * Returns all properties that are be applied to a new data source connection to this database. See
074     * <a href="https://jdbc.postgresql.org/documentation/head/connect.html#connection-parameters">the
075     * PostgreSQL JDBC driver documentation</a> for a comprehensive list.
076     *
077     * @return Map of key-value pairs representing data source connection properties.
078     * @since 3.0
079     */
080    @NonNull
081    public abstract ImmutableMap<String, String> connectionProperties();
082
083    @NonNull
084    abstract Optional<SQLException> exception();
085
086    @NonNull
087    static Builder builder() {
088        return new AutoValue_DatabaseInfo.Builder()
089                .dbName(PG_DEFAULT_DB)
090                .user(PG_DEFAULT_USER);
091    }
092
093    @NonNull
094    static DatabaseInfo forException(SQLException e) {
095        return builder().exception(e).port(-1).build();
096    }
097
098    /**
099     * Returns a JDBC url to connect to the described database.
100     *
101     * @return A JDBC url that can be used to connect to the database. Never null.
102     */
103    @NonNull
104    public String asJdbcUrl() {
105        checkState(exception().isEmpty(), "DatabaseInfo contains SQLException: %s", exception());
106
107        String additionalParameters = connectionProperties().entrySet().stream()
108                .map(e -> format("&%s=%s", e.getKey(), e.getValue()))
109                .collect(Collectors.joining());
110        return format(JDBC_FORMAT, port(), dbName(), user()) + additionalParameters;
111    }
112
113    /**
114     * Returns a {@link DataSource} instance connected to the described database.
115     *
116     * @return An initialized {@link DataSource} object. Never null.
117     * @throws SQLException A problem occurred trying to connect to the database.
118     */
119    @NonNull
120    public DataSource asDataSource() throws SQLException {
121        if (exception().isPresent()) {
122            throw exception().get();
123        }
124
125        return EmbeddedPostgres.createDataSource(user(), dbName(), port(), connectionProperties());
126    }
127
128    @AutoValue.Builder
129    abstract static class Builder {
130
131        abstract Builder dbName(String dbName);
132
133        abstract Builder port(int port);
134
135        abstract Builder user(String user);
136
137        abstract Builder exception(SQLException exception);
138
139        abstract ImmutableMap.Builder<String, String> connectionPropertiesBuilder();
140
141        final Builder addConnectionProperty(String key, String value) {
142            connectionPropertiesBuilder().put(key, value);
143            return this;
144        }
145
146        abstract Builder connectionProperties(ImmutableMap<String, String> connectionProperties);
147
148        abstract DatabaseInfo build();
149
150    }
151}