01: package liquibase.database;
02:
03: import liquibase.exception.JDBCException;
04: import liquibase.log.LogFactory;
05:
06: import java.sql.Connection;
07: import java.sql.SQLException;
08: import java.util.ArrayList;
09: import java.util.Arrays;
10: import java.util.List;
11: import java.util.logging.Logger;
12:
13: public class DatabaseFactory {
14:
15: private static DatabaseFactory instance = new DatabaseFactory();
16:
17: private static final Logger log = LogFactory.getLogger();
18:
19: private List<Database> implementedDatabases = new ArrayList<Database>(
20: Arrays.asList((Database) new OracleDatabase(),
21: new PostgresDatabase(), new MSSQLDatabase(),
22: new MySQLDatabase(), new DerbyDatabase(),
23: new HsqlDatabase(), new DB2Database(),
24: new SybaseDatabase(), new H2Database(),
25: new CacheDatabase(), new FirebirdDatabase(),
26: new MaxDBDatabase()));
27:
28: private DatabaseFactory() {
29: }
30:
31: public static DatabaseFactory getInstance() {
32: return instance;
33: }
34:
35: /**
36: * Returns instances of all implemented database types.
37: */
38: public List<Database> getImplementedDatabases() {
39: return implementedDatabases;
40: }
41:
42: public void addDatabaseImplementation(Database database) {
43: implementedDatabases.add(0, database);
44: }
45:
46: public Database findCorrectDatabaseImplementation(
47: Connection connection) throws JDBCException {
48: Database database = null;
49:
50: boolean foundImplementation = false;
51:
52: for (Database implementedDatabase : getImplementedDatabases()) {
53: database = implementedDatabase;
54: if (database.isCorrectDatabaseImplementation(connection)) {
55: foundImplementation = true;
56: break;
57: }
58: }
59:
60: if (!foundImplementation) {
61: try {
62: log.warning("Unknown database: "
63: + connection.getMetaData()
64: .getDatabaseProductName());
65: } catch (SQLException e) {
66: throw new JDBCException(e);
67: }
68: database = new UnsupportedDatabase();
69: }
70:
71: Database returnDatabase;
72: try {
73: returnDatabase = database.getClass().newInstance();
74: } catch (Exception e) {
75: throw new RuntimeException(e);
76: }
77: returnDatabase.setConnection(connection);
78: return returnDatabase;
79: }
80:
81: public Database findCorrectDatabaseImplementation(
82: DatabaseConnection connection) throws JDBCException {
83: return findCorrectDatabaseImplementation(connection
84: .getUnderlyingConnection());
85: }
86:
87: public String findDefaultDriver(String url) {
88: for (Database database : this .getImplementedDatabases()) {
89: String defaultDriver = database.getDefaultDriver(url);
90: if (defaultDriver != null) {
91: return defaultDriver;
92: }
93: }
94:
95: return null;
96: }
97:
98: }
|