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.logging.Log;
27 import org.apache.ibatis.logging.LogFactory;
28
29
30
31
32
33
34
35
36
37
38
39
40 public class VendorDatabaseIdProvider implements DatabaseIdProvider {
41
42 private Properties properties;
43
44 @Override
45 public String getDatabaseId(DataSource dataSource) {
46 if (dataSource == null) {
47 throw new NullPointerException("dataSource cannot be null");
48 }
49 try {
50 return getDatabaseName(dataSource);
51 } catch (Exception e) {
52 LogHolder.log.error("Could not get a databaseId from dataSource", e);
53 }
54 return null;
55 }
56
57 @Override
58 public void setProperties(Properties p) {
59 this.properties = p;
60 }
61
62 private String getDatabaseName(DataSource dataSource) throws SQLException {
63 String productName = getDatabaseProductName(dataSource);
64 if (this.properties != null) {
65 for (Map.Entry<Object, Object> property : properties.entrySet()) {
66 if (productName.contains((String) property.getKey())) {
67 return (String) property.getValue();
68 }
69 }
70
71 return null;
72 }
73 return productName;
74 }
75
76 private String getDatabaseProductName(DataSource dataSource) throws SQLException {
77 try (Connection con = dataSource.getConnection()) {
78 DatabaseMetaData metaData = con.getMetaData();
79 return metaData.getDatabaseProductName();
80 }
81
82 }
83
84 private static class LogHolder {
85 private static final Log log = LogFactory.getLog(VendorDatabaseIdProvider.class);
86 }
87
88 }