Search in sources :

Example 41 with Statement

use of java.sql.Statement in project siena by mandubian.

the class FullText method removeAllTriggers.

/**
     * Remove all triggers that start with the given prefix.
     *
     * @param conn the database connection
     * @param prefix the prefix
     */
protected static void removeAllTriggers(Connection conn, String prefix) throws SQLException {
    Statement stat = conn.createStatement();
    ResultSet rs = stat.executeQuery("SELECT * FROM INFORMATION_SCHEMA.TRIGGERS");
    Statement stat2 = conn.createStatement();
    while (rs.next()) {
        String schema = rs.getString("TRIGGER_SCHEMA");
        String name = rs.getString("TRIGGER_NAME");
        if (name.startsWith(prefix)) {
            name = StringUtils.quoteIdentifier(schema) + "." + StringUtils.quoteIdentifier(name);
            stat2.execute("DROP TRIGGER " + name);
        }
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 42 with Statement

use of java.sql.Statement in project liquibase by liquibase.

the class H2Database method setConnection.

@Override
public void setConnection(DatabaseConnection conn) {
    Connection sqlConn = null;
    if (!(conn instanceof OfflineConnection)) {
        try {
            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) {
            Statement statement = null;
            ResultSet resultSet = null;
            try {
                statement = sqlConn.createStatement();
                resultSet = statement.executeQuery("SELECT SCHEMA()");
                String schemaName = null;
                if (resultSet.next()) {
                    schemaName = resultSet.getString(1);
                }
                if (schemaName != null) {
                    this.connectionSchemaName = schemaName;
                }
            } catch (SQLException e) {
                LogFactory.getLogger().info("Could not read current schema name: " + e.getMessage());
            } finally {
                JdbcUtils.close(resultSet, statement);
            }
        }
    }
    super.setConnection(conn);
}
Also used : SQLException(java.sql.SQLException) 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) ParseException(java.text.ParseException) DatabaseException(liquibase.exception.DatabaseException) DateParseException(liquibase.exception.DateParseException)

Example 43 with Statement

use of java.sql.Statement 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 44 with Statement

use of java.sql.Statement in project liquibase by liquibase.

the class MissingDataExternalFileChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl outputControl, Database referenceDatabase, Database comparisionDatabase, ChangeGeneratorChain chain) {
    Statement stmt = null;
    ResultSet rs = null;
    try {
        Data data = (Data) missingObject;
        Table table = data.getTable();
        if (referenceDatabase.isLiquibaseObject(table)) {
            return null;
        }
        String sql = "SELECT * FROM " + referenceDatabase.escapeTableName(table.getSchema().getCatalogName(), table.getSchema().getName(), table.getName());
        stmt = ((JdbcConnection) referenceDatabase.getConnection()).createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(100);
        rs = stmt.executeQuery(sql);
        List<String> columnNames = new ArrayList<String>();
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            columnNames.add(rs.getMetaData().getColumnName(i + 1));
        }
        String fileName = table.getName().toLowerCase() + ".csv";
        if (dataDir != null) {
            fileName = dataDir + "/" + fileName;
            File parentDir = new File(dataDir);
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            if (!parentDir.isDirectory()) {
                throw new RuntimeException(parentDir + " is not a directory");
            }
        }
        CSVWriter outputFile = new CSVWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding())));
        String[] dataTypes = new String[columnNames.size()];
        String[] line = new String[columnNames.size()];
        for (int i = 0; i < columnNames.size(); i++) {
            line[i] = columnNames.get(i);
        }
        outputFile.writeNext(line);
        int rowNum = 0;
        while (rs.next()) {
            line = new String[columnNames.size()];
            for (int i = 0; i < columnNames.size(); i++) {
                Object value = JdbcUtils.getResultSetValue(rs, i + 1);
                if (dataTypes[i] == null && value != null) {
                    if (value instanceof Number) {
                        dataTypes[i] = "NUMERIC";
                    } else if (value instanceof Boolean) {
                        dataTypes[i] = "BOOLEAN";
                    } else if (value instanceof Date) {
                        dataTypes[i] = "DATE";
                    } else {
                        dataTypes[i] = "STRING";
                    }
                }
                if (value == null) {
                    line[i] = "NULL";
                } else {
                    if (value instanceof Date) {
                        line[i] = new ISODateFormat().format(((Date) value));
                    } else {
                        line[i] = value.toString();
                    }
                }
            }
            outputFile.writeNext(line);
            rowNum++;
            if (rowNum % 5000 == 0) {
                outputFile.flush();
            }
        }
        outputFile.flush();
        outputFile.close();
        LoadDataChange change = new LoadDataChange();
        change.setFile(fileName);
        change.setEncoding(LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
        if (outputControl.getIncludeCatalog()) {
            change.setCatalogName(table.getSchema().getCatalogName());
        }
        if (outputControl.getIncludeSchema()) {
            change.setSchemaName(table.getSchema().getName());
        }
        change.setTableName(table.getName());
        for (int i = 0; i < columnNames.size(); i++) {
            String colName = columnNames.get(i);
            LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
            columnConfig.setHeader(colName);
            columnConfig.setName(colName);
            columnConfig.setType(dataTypes[i]);
            change.addColumn(columnConfig);
        }
        return new Change[] { change };
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ignore) {
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ignore) {
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) CSVWriter(liquibase.util.csv.CSVWriter) BufferedWriter(java.io.BufferedWriter) ISODateFormat(liquibase.util.ISODateFormat) ResultSet(java.sql.ResultSet) LoadDataColumnConfig(liquibase.change.core.LoadDataColumnConfig) LoadDataChange(liquibase.change.core.LoadDataChange) Table(liquibase.structure.core.Table) Statement(java.sql.Statement) Data(liquibase.structure.core.Data) Change(liquibase.change.Change) LoadDataChange(liquibase.change.core.LoadDataChange) Date(java.util.Date) SQLException(java.sql.SQLException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) DatabaseObject(liquibase.structure.DatabaseObject) File(java.io.File) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 45 with Statement

use of java.sql.Statement in project liquibase by liquibase.

the class OracleDatabase method canAccessDbaRecycleBin.

public boolean canAccessDbaRecycleBin() {
    if (canAccessDbaRecycleBin == null) {
        DatabaseConnection connection = getConnection();
        if (connection == null || connection instanceof OfflineConnection) {
            return false;
        }
        Statement statement = null;
        try {
            statement = ((JdbcConnection) connection).createStatement();
            ResultSet resultSet = statement.executeQuery("select 1 from dba_recyclebin where 0=1");
            //don't need to do anything with the result set, just make sure statement ran.
            resultSet.close();
            this.canAccessDbaRecycleBin = true;
        } catch (Exception e) {
            if (e instanceof SQLException && e.getMessage().startsWith("ORA-00942")) {
                //ORA-00942: table or view does not exist
                this.canAccessDbaRecycleBin = false;
            } else {
                LogFactory.getInstance().getLog().warning("Cannot check dba_recyclebin access", e);
                this.canAccessDbaRecycleBin = false;
            }
        } finally {
            JdbcUtils.close(null, statement);
        }
    }
    return canAccessDbaRecycleBin;
}
Also used : SQLException(java.sql.SQLException) RawCallStatement(liquibase.statement.core.RawCallStatement) RawSqlStatement(liquibase.statement.core.RawSqlStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) DatabaseConnection(liquibase.database.DatabaseConnection) OfflineConnection(liquibase.database.OfflineConnection) SQLException(java.sql.SQLException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

Statement (java.sql.Statement)3054 Connection (java.sql.Connection)1634 ResultSet (java.sql.ResultSet)1631 SQLException (java.sql.SQLException)1529 PreparedStatement (java.sql.PreparedStatement)1329 Test (org.junit.Test)570 ArrayList (java.util.ArrayList)323 CallableStatement (java.sql.CallableStatement)135 ResultSetMetaData (java.sql.ResultSetMetaData)127 IOException (java.io.IOException)121 Properties (java.util.Properties)114 HashMap (java.util.HashMap)83 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)81 DruidPooledStatement (com.alibaba.druid.pool.DruidPooledStatement)71 StringPlus (mom.trd.opentheso.bdd.tools.StringPlus)63 DataSource (javax.sql.DataSource)62 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)61 Vector (java.util.Vector)61 DatabaseMetaData (java.sql.DatabaseMetaData)53 KeyValue (org.vcell.util.document.KeyValue)49