001/*
002 * The contents of this file are subject to the license and copyright
003 * detailed in the LICENSE and NOTICE files at the root of the source
004 * tree.
005 */
006
007package org.fcrepo.common.db;
008
009import org.slf4j.Logger;
010import org.slf4j.LoggerFactory;
011
012import javax.sql.DataSource;
013import java.sql.SQLException;
014
015/**
016 * Detects the database platform from a datasource.
017 *
018 * @author pwinckles
019 * @since 6.0.0
020 */
021public enum DbPlatform {
022
023    POSTGRESQL("PostgreSQL"),
024    H2("H2"),
025    MYSQL("MySQL"),
026    MARIADB("MariaDB");
027
028    private static final Logger LOGGER = LoggerFactory.getLogger(DbPlatform.class);
029
030    private final String name;
031
032    DbPlatform(final String name) {
033        this.name = name;
034    }
035
036    public static DbPlatform fromDataSource(final DataSource dataSource) {
037        try (final var connection = dataSource.getConnection()) {
038            final var name = connection.getMetaData().getDatabaseProductName();
039            LOGGER.debug("Identified database as: {}", name);
040            return fromString(name);
041        } catch (final SQLException e) {
042            throw new RuntimeException(e);
043        }
044    }
045
046    public static DbPlatform fromString(final String name) {
047        for (final var platform : values()) {
048            if (platform.name.equals(name)) {
049                return platform;
050            }
051        }
052        throw new IllegalArgumentException("Unknown database platform: " + name);
053    }
054
055    public String getName() {
056        return name;
057    }
058}