001/* 002 * Licensed to DuraSpace under one or more contributor license agreements. 003 * See the NOTICE file distributed with this work for additional information 004 * regarding copyright ownership. 005 * 006 * DuraSpace licenses this file to you under the Apache License, 007 * Version 2.0 (the "License"); you may not use this file except in 008 * compliance with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019package org.fcrepo.common.db; 020 021import org.slf4j.Logger; 022import org.slf4j.LoggerFactory; 023 024import javax.sql.DataSource; 025import java.sql.SQLException; 026 027/** 028 * Detects the database platform from a datasource. 029 * 030 * @author pwinckles 031 * @since 6.0.0 032 */ 033public enum DbPlatform { 034 035 POSTGRESQL("PostgreSQL"), 036 H2("H2"), 037 MYSQL("MySQL"), 038 MARIADB("MariaDB"); 039 040 private static final Logger LOGGER = LoggerFactory.getLogger(DbPlatform.class); 041 042 private final String name; 043 044 DbPlatform(final String name) { 045 this.name = name; 046 } 047 048 public static DbPlatform fromDataSource(final DataSource dataSource) { 049 try (final var connection = dataSource.getConnection()) { 050 final var name = connection.getMetaData().getDatabaseProductName(); 051 LOGGER.debug("Identified database as: {}", name); 052 return fromString(name); 053 } catch (final SQLException e) { 054 throw new RuntimeException(e); 055 } 056 } 057 058 public static DbPlatform fromString(final String name) { 059 for (final var platform : values()) { 060 if (platform.name.equals(name)) { 061 return platform; 062 } 063 } 064 throw new IllegalArgumentException("Unknown database platform: " + name); 065 } 066 067 public String getName() { 068 return name; 069 } 070}