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.builder.BuilderException;
25  
26  /**
27   * Vendor DatabaseId provider.
28   * <p>
29   * It returns database product name as a databaseId. If the user provides a properties it uses it to translate database
30   * product name key="Microsoft SQL Server", value="ms" will return "ms". It can return null, if no database product name
31   * or a properties was specified and no translation was found.
32   *
33   * @author Eduardo Macarron
34   */
35  public class VendorDatabaseIdProvider implements DatabaseIdProvider {
36  
37    private Properties properties;
38  
39    @Override
40    public String getDatabaseId(DataSource dataSource) {
41      if (dataSource == null) {
42        throw new NullPointerException("dataSource cannot be null");
43      }
44      try {
45        return getDatabaseName(dataSource);
46      } catch (SQLException e) {
47        throw new BuilderException("Error occurred when getting DB product name.", e);
48      }
49    }
50  
51    @Override
52    public void setProperties(Properties p) {
53      this.properties = p;
54    }
55  
56    private String getDatabaseName(DataSource dataSource) throws SQLException {
57      String productName = getDatabaseProductName(dataSource);
58      if (this.properties != null) {
59        return properties.entrySet().stream().filter(entry -> productName.contains((String) entry.getKey()))
60            .map(entry -> (String) entry.getValue()).findFirst().orElse(null);
61      }
62      return productName;
63    }
64  
65    private String getDatabaseProductName(DataSource dataSource) throws SQLException {
66      try (Connection con = dataSource.getConnection()) {
67        return con.getMetaData().getDatabaseProductName();
68      }
69    }
70  
71  }