VendorDatabaseIdProvider.java

  1. /*
  2.  *    Copyright 2009-2023 the original author or authors.
  3.  *
  4.  *    Licensed under the Apache License, Version 2.0 (the "License");
  5.  *    you may not use this file except in compliance with the License.
  6.  *    You may obtain a copy of the License at
  7.  *
  8.  *       https://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  *    Unless required by applicable law or agreed to in writing, software
  11.  *    distributed under the License is distributed on an "AS IS" BASIS,
  12.  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  *    See the License for the specific language governing permissions and
  14.  *    limitations under the License.
  15.  */
  16. package org.apache.ibatis.mapping;

  17. import java.sql.Connection;
  18. import java.sql.SQLException;
  19. import java.util.Properties;

  20. import javax.sql.DataSource;

  21. import org.apache.ibatis.logging.Log;
  22. import org.apache.ibatis.logging.LogFactory;

  23. /**
  24.  * Vendor DatabaseId provider.
  25.  * <p>
  26.  * It returns database product name as a databaseId. If the user provides a properties it uses it to translate database
  27.  * product name key="Microsoft SQL Server", value="ms" will return "ms". It can return null, if no database product name
  28.  * or a properties was specified and no translation was found.
  29.  *
  30.  * @author Eduardo Macarron
  31.  */
  32. public class VendorDatabaseIdProvider implements DatabaseIdProvider {

  33.   private Properties properties;

  34.   @Override
  35.   public String getDatabaseId(DataSource dataSource) {
  36.     if (dataSource == null) {
  37.       throw new NullPointerException("dataSource cannot be null");
  38.     }
  39.     try {
  40.       return getDatabaseName(dataSource);
  41.     } catch (Exception e) {
  42.       LogHolder.log.error("Could not get a databaseId from dataSource", e);
  43.     }
  44.     return null;
  45.   }

  46.   @Override
  47.   public void setProperties(Properties p) {
  48.     this.properties = p;
  49.   }

  50.   private String getDatabaseName(DataSource dataSource) throws SQLException {
  51.     String productName = getDatabaseProductName(dataSource);
  52.     if (this.properties != null) {
  53.       return properties.entrySet().stream().filter(entry -> productName.contains((String) entry.getKey()))
  54.           .map(entry -> (String) entry.getValue()).findFirst().orElse(null);
  55.     }
  56.     return productName;
  57.   }

  58.   private String getDatabaseProductName(DataSource dataSource) throws SQLException {
  59.     try (Connection con = dataSource.getConnection()) {
  60.       return con.getMetaData().getDatabaseProductName();
  61.     }
  62.   }

  63.   private static class LogHolder {
  64.     private static final Log log = LogFactory.getLog(VendorDatabaseIdProvider.class);
  65.   }

  66. }