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.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
29
30
31
32
33
34
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 }