001// Licensed under the MIT license. See LICENSE file in the project root for full license information.
002
003package de.bytefish.pgbulkinsert.util;
004
005import de.bytefish.pgbulkinsert.exceptions.PgConnectionException;
006import org.postgresql.PGConnection;
007import org.postgresql.core.Utils;
008
009import java.sql.Connection;
010import java.sql.SQLException;
011import java.util.Optional;
012
013public final class PostgreSqlUtils {
014
015    private PostgreSqlUtils() {
016    }
017
018    public static PGConnection getPGConnection(final Connection connection) {
019        return tryGetPGConnection(connection).orElseThrow(() -> new PgConnectionException("Could not obtain a PGConnection"));
020    }
021
022    public static Optional<PGConnection> tryGetPGConnection(final Connection connection) {
023        final Optional<PGConnection> fromCast = tryCastConnection(connection);
024        if (fromCast.isPresent()) {
025            return fromCast;
026        }
027        return tryUnwrapConnection(connection);
028    }
029
030    private static Optional<PGConnection> tryCastConnection(final Connection connection) {
031        if (connection instanceof PGConnection) {
032            return Optional.of((PGConnection) connection);
033        }
034        return Optional.empty();
035    }
036
037    private static Optional<PGConnection> tryUnwrapConnection(final Connection connection) {
038        try {
039            if (connection.isWrapperFor(PGConnection.class)) {
040                return Optional.of(connection.unwrap(PGConnection.class));
041            }
042        } catch (Exception e) {
043            // do nothing
044        }
045        return Optional.empty();
046    }
047
048    public static String quoteIdentifier(String identifier) {
049        try {
050            return Utils.escapeIdentifier(null, identifier).toString();
051        } catch (SQLException e) {
052            throw new IllegalArgumentException("Invalid identifier", e);
053        }
054    }
055
056    public static String getFullyQualifiedTableName(String schemaName, String tableName, boolean usePostgresQuoting) {
057        if (usePostgresQuoting) {
058            return StringUtils.isNullOrWhiteSpace(schemaName) ? quoteIdentifier(tableName)
059                    : String.format("%s.%s", quoteIdentifier(schemaName), quoteIdentifier(tableName));
060        }
061
062        if (StringUtils.isNullOrWhiteSpace(schemaName)) {
063            return tableName;
064        }
065
066        return String.format("%1$s.%2$s", schemaName, tableName);
067    }
068}