use of liquibase.database.jvm.JdbcConnection in project liquibase by liquibase.
the class JdbcExecutor method execute.
public Object execute(StatementCallback action, List<SqlVisitor> sqlVisitors) throws DatabaseException {
DatabaseConnection con = database.getConnection();
Statement stmt = null;
try {
if (con instanceof OfflineConnection) {
throw new DatabaseException("Cannot execute commands against an offline database");
}
stmt = ((JdbcConnection) con).getUnderlyingConnection().createStatement();
Statement stmtToUse = stmt;
return action.doInStatement(stmtToUse);
} catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
JdbcUtils.closeStatement(stmt);
stmt = null;
String url;
if (con.isClosed()) {
url = "CLOSED CONNECTION";
} else {
url = con.getURL();
}
throw new DatabaseException("Error executing SQL " + StringUtils.join(applyVisitors(action.getStatement(), sqlVisitors), "; on " + url) + ": " + ex.getMessage(), ex);
} finally {
JdbcUtils.closeStatement(stmt);
}
}
use of liquibase.database.jvm.JdbcConnection in project liquibase by liquibase.
the class DatabaseType method createDatabase.
public Database createDatabase(ClassLoader classLoader) {
logParameters();
validateParameters();
try {
DatabaseFactory databaseFactory = DatabaseFactory.getInstance();
if (databaseClass != null) {
Database databaseInstance = (Database) ClasspathUtils.newInstance(databaseClass, classLoader, Database.class);
databaseFactory.register(databaseInstance);
}
DatabaseConnection jdbcConnection;
if (getUrl().startsWith("offline:")) {
jdbcConnection = new OfflineConnection(getUrl(), new ClassLoaderResourceAccessor(classLoader));
} else {
Driver driver = (Driver) ClasspathUtils.newInstance(getDriver(), classLoader, Driver.class);
if (driver == null) {
throw new BuildException("Unable to create Liquibase Database instance. Could not instantiate the JDBC driver.");
}
Properties connectionProps = new Properties();
String user = getUser();
if (user != null && !user.isEmpty()) {
connectionProps.setProperty(USER, user);
}
String password = getPassword();
if (password != null && !password.isEmpty()) {
connectionProps.setProperty(PASSWORD, password);
}
ConnectionProperties connectionProperties = getConnectionProperties();
if (connectionProperties != null) {
connectionProps.putAll(connectionProperties.buildProperties());
}
Connection connection = driver.connect(getUrl(), connectionProps);
if (connection == null) {
throw new BuildException("Unable to create Liquibase Database instance. Could not connect to the database.");
}
jdbcConnection = new JdbcConnection(connection);
}
Database database = databaseFactory.findCorrectDatabaseImplementation(jdbcConnection);
String schemaName = getDefaultSchemaName();
if (schemaName != null) {
database.setDefaultSchemaName(schemaName);
}
String catalogName = getDefaultCatalogName();
if (catalogName != null) {
database.setDefaultCatalogName(catalogName);
}
String currentDateTimeFunction = getCurrentDateTimeFunction();
if (currentDateTimeFunction != null) {
database.setCurrentDateTimeFunction(currentDateTimeFunction);
}
database.setOutputDefaultSchema(isOutputDefaultSchema());
database.setOutputDefaultCatalog(isOutputDefaultCatalog());
String liquibaseSchemaName = getLiquibaseSchemaName();
if (liquibaseSchemaName != null) {
database.setLiquibaseSchemaName(liquibaseSchemaName);
}
String liquibaseCatalogName = getLiquibaseCatalogName();
if (liquibaseCatalogName != null) {
database.setLiquibaseCatalogName(liquibaseCatalogName);
}
String databaseChangeLogTableName = getDatabaseChangeLogTableName();
if (databaseChangeLogTableName != null) {
database.setDatabaseChangeLogTableName(databaseChangeLogTableName);
}
String databaseChangeLogLockTableName = getDatabaseChangeLogLockTableName();
if (databaseChangeLogLockTableName != null) {
database.setDatabaseChangeLogLockTableName(databaseChangeLogLockTableName);
}
String liquibaseTablespaceName = getLiquibaseTablespaceName();
if (liquibaseTablespaceName != null) {
database.setLiquibaseTablespaceName(liquibaseTablespaceName);
}
return database;
} catch (SQLException e) {
throw new BuildException("Unable to create Liquibase database instance. A JDBC error occurred. " + e.toString(), e);
} catch (DatabaseException e) {
throw new BuildException("Unable to create Liquibase database instance. " + e.toString(), e);
}
}
use of liquibase.database.jvm.JdbcConnection in project liquibase by liquibase.
the class OracleDatabase method setConnection.
@Override
public void setConnection(DatabaseConnection conn) {
//more reserved words not returned by driver
reservedWords.addAll(Arrays.asList("GROUP", "USER", "SESSION", "PASSWORD", "RESOURCE", "START", "SIZE", "UID", "DESC", "ORDER"));
Connection sqlConn = null;
if (!(conn instanceof OfflineConnection)) {
try {
/**
* Don't try to call getWrappedConnection if the conn instance is
* is not a JdbcConnection. This happens for OfflineConnection.
* @see <a href="https://liquibase.jira.com/browse/CORE-2192">CORE-2192</a>
**/
if (conn instanceof JdbcConnection) {
Method wrappedConn = conn.getClass().getMethod("getWrappedConnection");
wrappedConn.setAccessible(true);
sqlConn = (Connection) wrappedConn.invoke(conn);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
if (sqlConn != null) {
try {
reservedWords.addAll(Arrays.asList(sqlConn.getMetaData().getSQLKeywords().toUpperCase().split(",\\s*")));
} catch (SQLException e) {
LogFactory.getLogger().info("Could get sql keywords on OracleDatabase: " + e.getMessage());
//can not get keywords. Continue on
}
try {
Method method = sqlConn.getClass().getMethod("setRemarksReporting", Boolean.TYPE);
method.setAccessible(true);
method.invoke(sqlConn, true);
} catch (Exception e) {
LogFactory.getLogger().info("Could not set remarks reporting on OracleDatabase: " + e.getMessage());
//cannot set it. That is OK
;
}
Statement statement = null;
ResultSet resultSet = null;
try {
statement = sqlConn.createStatement();
resultSet = statement.executeQuery("SELECT value FROM v$parameter WHERE name = 'compatible'");
String compatibleVersion = null;
if (resultSet.next()) {
compatibleVersion = resultSet.getString("value");
}
if (compatibleVersion != null) {
Matcher majorVersionMatcher = Pattern.compile("(\\d+)\\..*").matcher(compatibleVersion);
if (majorVersionMatcher.matches()) {
this.databaseMajorVersion = Integer.valueOf(majorVersionMatcher.group(1));
}
}
} catch (SQLException e) {
String message = "Cannot read from v$parameter: " + e.getMessage();
LogFactory.getLogger().info("Could not set check compatibility mode on OracleDatabase, assuming not running in any sort of compatibility mode: " + message);
} finally {
JdbcUtils.close(resultSet, statement);
}
}
}
super.setConnection(conn);
}
use of liquibase.database.jvm.JdbcConnection in project liquibase by liquibase.
the class PostgresDatabase method setConnection.
@Override
public void setConnection(DatabaseConnection conn) {
super.setConnection(conn);
Logger log = LogFactory.getInstance().getLog();
if (conn instanceof JdbcConnection) {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = ((JdbcConnection) conn).createStatement();
resultSet = statement.executeQuery("select setting from pg_settings where name = 'edb_redwood_date'");
if (resultSet.next()) {
String setting = resultSet.getString(1);
if (setting != null && setting.equals("on")) {
log.warning("EnterpriseDB " + conn.getURL() + " does not store DATE columns. Auto-converts them to TIMESTAMPs. (edb_redwood_date=true)");
}
}
} catch (Exception e) {
log.info("Cannot check pg_settings", e);
} finally {
JdbcUtils.close(resultSet, statement);
}
}
}
use of liquibase.database.jvm.JdbcConnection in project liquibase by liquibase.
the class DatabaseTestContext method openConnection.
private DatabaseConnection openConnection(final String url) throws Exception {
if (connectionsAttempted.containsKey(url)) {
JdbcConnection connection = (JdbcConnection) connectionsByUrl.get(url);
if (connection == null) {
return null;
} else if (connection.getUnderlyingConnection().isClosed()) {
connectionsByUrl.put(url, openDatabaseConnection(url));
}
return connectionsByUrl.get(url);
}
connectionsAttempted.put(url, Boolean.TRUE);
if (System.getProperty(TEST_DATABASES_PROPERTY) != null) {
boolean shouldTest = false;
String[] databasesToTest = System.getProperty(TEST_DATABASES_PROPERTY).split("\\s*,\\s*");
for (String database : databasesToTest) {
if (url.indexOf(database) >= 0) {
shouldTest = true;
}
}
if (!shouldTest) {
System.out.println("test.databases system property forbids testing against " + url);
return null;
} else {
System.out.println("Will be tested against " + url);
}
}
DatabaseConnection connection = openDatabaseConnection(url);
if (connection == null) {
return null;
}
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
final DatabaseConnection databaseConnection = database.getConnection();
if (databaseConnection.getAutoCommit()) {
databaseConnection.setAutoCommit(false);
}
try {
if (url.startsWith("jdbc:hsql")) {
((JdbcConnection) databaseConnection).getUnderlyingConnection().createStatement().execute("CREATE SCHEMA " + ALT_SCHEMA + " AUTHORIZATION DBA");
} else if (url.startsWith("jdbc:sqlserver") || url.startsWith("jdbc:postgresql") || url.startsWith("jdbc:h2")) {
((JdbcConnection) databaseConnection).getUnderlyingConnection().createStatement().execute("CREATE SCHEMA " + ALT_SCHEMA);
}
if (!databaseConnection.getAutoCommit()) {
databaseConnection.commit();
}
} catch (SQLException e) {
//schema already exists
;
} finally {
try {
databaseConnection.rollback();
} catch (DatabaseException e) {
if (database instanceof DB2Database) {
// expected, there is a problem with it
} else {
throw e;
}
}
}
connectionsByUrl.put(url, databaseConnection);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
try {
try {
if (!((JdbcConnection) databaseConnection).getUnderlyingConnection().getAutoCommit()) {
((JdbcConnection) databaseConnection).getUnderlyingConnection().rollback();
}
} catch (SQLException e) {
;
}
((JdbcConnection) databaseConnection).getUnderlyingConnection().close();
} catch (SQLException e) {
System.out.println("Could not close " + url);
e.printStackTrace();
}
}
}));
return databaseConnection;
}
Aggregations