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     */
079    @NonNull
080    public abstract ImmutableMap<String, String> connectionProperties();
081
082    @NonNull
083    abstract Optional<SQLException> exception();
084
085    @NonNull
086    static Builder builder() {
087        return new AutoValue_DatabaseInfo.Builder()
088                .dbName(PG_DEFAULT_DB)
089                .user(PG_DEFAULT_USER);
090    }
091
092    @NonNull
093    static DatabaseInfo forException(SQLException e) {
094        return builder().exception(e).port(-1).build();
095    }
096
097    /**
098     * Returns a JDBC url to connect to the described database.
099     *
100     * @return A JDBC url that can be used to connect to the database. Never null.
101     */
102    @NonNull
103    public String asJdbcUrl() {
104        checkState(exception().isEmpty(), "DatabaseInfo contains SQLException: %s", exception());
105
106        String additionalParameters = connectionProperties().entrySet().stream()
107                .map(e -> format("&%s=%s", e.getKey(), e.getValue()))
108                .collect(Collectors.joining());
109        return format(JDBC_FORMAT, port(), dbName(), user()) + additionalParameters;
110    }
111
112    /**
113     * Returns a {@link DataSource} instance connected to the described database.
114     *
115     * @return An initialized {@link DataSource} object. Never null.
116     * @throws SQLException A problem occured trying to connect to the database.
117     */
118    @NonNull
119    public DataSource asDataSource() throws SQLException {
120        if (exception().isPresent()) {
121            throw exception().get();
122        }
123
124        return EmbeddedPostgres.createDataSource(user(), dbName(), port(), connectionProperties());
125    }
126
127    @AutoValue.Builder
128    abstract static class Builder {
129
130        abstract Builder dbName(String dbName);
131
132        abstract Builder port(int port);
133
134        abstract Builder user(String user);
135
136        abstract Builder exception(SQLException exception);
137
138        abstract ImmutableMap.Builder<String, String> connectionPropertiesBuilder();
139
140        final Builder addConnectionProperty(String key, String value) {
141            connectionPropertiesBuilder().put(key, value);
142            return this;
143        }
144
145        abstract Builder connectionProperties(ImmutableMap<String, String> connectionProperties);
146
147        abstract DatabaseInfo build();
148
149    }
150}