Search in sources :

Example 6 with JdbcConnection

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);
    }
}
Also used : SQLException(java.sql.SQLException) RawSqlStatement(liquibase.statement.core.RawSqlStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) DatabaseConnection(liquibase.database.DatabaseConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) OfflineConnection(liquibase.database.OfflineConnection) DatabaseException(liquibase.exception.DatabaseException)

Example 7 with JdbcConnection

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);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) DatabaseConnection(liquibase.database.DatabaseConnection) OfflineConnection(liquibase.database.OfflineConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) Driver(java.sql.Driver) JdbcConnection(liquibase.database.jvm.JdbcConnection) OfflineConnection(liquibase.database.OfflineConnection) Properties(java.util.Properties) DatabaseFactory(liquibase.database.DatabaseFactory) Database(liquibase.database.Database) DatabaseConnection(liquibase.database.DatabaseConnection) BuildException(org.apache.tools.ant.BuildException) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) DatabaseException(liquibase.exception.DatabaseException)

Example 8 with JdbcConnection

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);
}
Also used : SQLException(java.sql.SQLException) Matcher(java.util.regex.Matcher) RawCallStatement(liquibase.statement.core.RawCallStatement) RawSqlStatement(liquibase.statement.core.RawSqlStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) DatabaseConnection(liquibase.database.DatabaseConnection) OfflineConnection(liquibase.database.OfflineConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) ResultSet(java.sql.ResultSet) JdbcConnection(liquibase.database.jvm.JdbcConnection) OfflineConnection(liquibase.database.OfflineConnection) Method(java.lang.reflect.Method) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) SQLException(java.sql.SQLException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

Example 9 with JdbcConnection

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);
        }
    }
}
Also used : RawCallStatement(liquibase.statement.core.RawCallStatement) RawSqlStatement(liquibase.statement.core.RawSqlStatement) SqlStatement(liquibase.statement.SqlStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) JdbcConnection(liquibase.database.jvm.JdbcConnection) Logger(liquibase.logging.Logger) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException)

Example 10 with JdbcConnection

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;
}
Also used : DB2Database(liquibase.database.core.DB2Database) SQLException(java.sql.SQLException) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DB2Database(liquibase.database.core.DB2Database) MockDatabase(liquibase.sdk.database.MockDatabase) ExampleCustomDatabase(liquibase.database.example.ExampleCustomDatabase) JdbcConnection(liquibase.database.jvm.JdbcConnection) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

JdbcConnection (liquibase.database.jvm.JdbcConnection)26 DatabaseException (liquibase.exception.DatabaseException)15 SQLException (java.sql.SQLException)13 OfflineConnection (liquibase.database.OfflineConnection)11 DatabaseConnection (liquibase.database.DatabaseConnection)10 Connection (java.sql.Connection)8 Database (liquibase.database.Database)8 ResultSet (java.sql.ResultSet)7 Statement (java.sql.Statement)6 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)6 RawSqlStatement (liquibase.statement.core.RawSqlStatement)5 Driver (java.sql.Driver)3 ArrayList (java.util.ArrayList)3 Liquibase (liquibase.Liquibase)3 DatabaseFactory (liquibase.database.DatabaseFactory)3 Method (java.lang.reflect.Method)2 CallableStatement (java.sql.CallableStatement)2 PreparedStatement (java.sql.PreparedStatement)2 DataSource (javax.sql.DataSource)2 LiquibaseException (liquibase.exception.LiquibaseException)2