View Javadoc
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  
18  import java.sql.Connection;
19  import java.sql.SQLException;
20  import java.util.Properties;
21  
22  import javax.sql.DataSource;
23  
24  import org.apache.ibatis.logging.Log;
25  import org.apache.ibatis.logging.LogFactory;
26  
27  /**
28   * Vendor DatabaseId provider.
29   * <p>
30   * It returns database product name as a databaseId. If the user provides a properties it uses it to translate database
31   * product name key="Microsoft SQL Server", value="ms" will return "ms". It can return null, if no database product name
32   * or a properties was specified and no translation was found.
33   *
34   * @author Eduardo Macarron
35   */
36  public class VendorDatabaseIdProvider implements DatabaseIdProvider {
37  
38    private Properties properties;
39  
40    @Override
41    public String getDatabaseId(DataSource dataSource) {
42      if (dataSource == null) {
43        throw new NullPointerException("dataSource cannot be null");
44      }
45      try {
46        return getDatabaseName(dataSource);
47      } catch (Exception e) {
48        LogHolder.log.error("Could not get a databaseId from dataSource", e);
49      }
50      return null;
51    }
52  
53    @Override
54    public void setProperties(Properties p) {
55      this.properties = p;
56    }
57  
58    private String getDatabaseName(DataSource dataSource) throws SQLException {
59      String productName = getDatabaseProductName(dataSource);
60      if (this.properties != null) {
61        return properties.entrySet().stream().filter(entry -> productName.contains((String) entry.getKey()))
62            .map(entry -> (String) entry.getValue()).findFirst().orElse(null);
63      }
64      return productName;
65    }
66  
67    private String getDatabaseProductName(DataSource dataSource) throws SQLException {
68      try (Connection con = dataSource.getConnection()) {
69        return con.getMetaData().getDatabaseProductName();
70      }
71    }
72  
73    private static class LogHolder {
74      private static final Log log = LogFactory.getLog(VendorDatabaseIdProvider.class);
75    }
76  
77  }