VendorDatabaseIdProvider.java

  1. /*
  2.  *    Copyright 2009-2024 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.builder.BuilderException;

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

  32.   private Properties properties;

  33.   @Override
  34.   public String getDatabaseId(DataSource dataSource) {
  35.     if (dataSource == null) {
  36.       throw new NullPointerException("dataSource cannot be null");
  37.     }
  38.     try {
  39.       return getDatabaseName(dataSource);
  40.     } catch (SQLException e) {
  41.       throw new BuilderException("Error occurred when getting DB product name.", e);
  42.     }
  43.   }

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

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

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

  61. }