1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.mapping;
17
18 import java.sql.Connection;
19 import java.sql.DatabaseMetaData;
20 import java.sql.SQLException;
21 import java.util.Map;
22 import java.util.Properties;
23
24 import javax.sql.DataSource;
25
26 import org.apache.ibatis.executor.BaseExecutor;
27 import org.apache.ibatis.logging.Log;
28 import org.apache.ibatis.logging.LogFactory;
29
30
31
32
33
34
35
36
37
38
39
40
41 public class VendorDatabaseIdProvider implements DatabaseIdProvider {
42
43 private static final Log log = LogFactory.getLog(BaseExecutor.class);
44
45 private Properties properties;
46
47 @Override
48 public String getDatabaseId(DataSource dataSource) {
49 if (dataSource == null) {
50 throw new NullPointerException("dataSource cannot be null");
51 }
52 try {
53 return getDatabaseName(dataSource);
54 } catch (Exception e) {
55 log.error("Could not get a databaseId from dataSource", e);
56 }
57 return null;
58 }
59
60 @Override
61 public void setProperties(Properties p) {
62 this.properties = p;
63 }
64
65 private String getDatabaseName(DataSource dataSource) throws SQLException {
66 String productName = getDatabaseProductName(dataSource);
67 if (this.properties != null) {
68 for (Map.Entry<Object, Object> property : properties.entrySet()) {
69 if (productName.contains((String) property.getKey())) {
70 return (String) property.getValue();
71 }
72 }
73
74 return null;
75 }
76 return productName;
77 }
78
79 private String getDatabaseProductName(DataSource dataSource) throws SQLException {
80 Connection con = null;
81 try {
82 con = dataSource.getConnection();
83 DatabaseMetaData metaData = con.getMetaData();
84 return metaData.getDatabaseProductName();
85 } finally {
86 if (con != null) {
87 try {
88 con.close();
89 } catch (SQLException e) {
90
91 }
92 }
93 }
94 }
95
96 }