Search in sources :

Example 86 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class Trx method run.

/**
	 * Execute runnable object using provided transaction.
	 * If execution fails, database operations will be rolled back.
	 * <p>
	 * Example: <pre>
	 * Trx.run(null, new {@link TrxRunnable}() {
	 *     public void run(String trxName) {
	 *         // do something using trxName
	 *     }
	 * )};
	 * </pre>
	 * 
	 * @param trxName transaction name (if null, a new transaction will be created)
	 * @param r runnable object
	 */
public static void run(String trxName, TrxRunnable r) {
    boolean localTrx = false;
    if (trxName == null) {
        trxName = Trx.createTrxName("TrxRun");
        localTrx = true;
    }
    Trx trx = Trx.get(trxName, true);
    Savepoint savepoint = null;
    try {
        if (!localTrx)
            savepoint = trx.setSavepoint(null);
        r.run(trxName);
        if (localTrx)
            trx.commit(true);
    } catch (Throwable e) {
        // Rollback transaction
        if (localTrx) {
            trx.rollback();
        } else if (savepoint != null) {
            try {
                trx.rollback(savepoint);
            } catch (SQLException e2) {
                ;
            }
        }
        trx = null;
        // Throw exception
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new AdempiereException(e);
        }
    } finally {
        if (localTrx && trx != null) {
            trx.close();
            trx = null;
        }
    }
}
Also used : SQLException(java.sql.SQLException) AdempiereException(org.adempiere.exceptions.AdempiereException) Savepoint(java.sql.Savepoint)

Example 87 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class Migrate method cleanupTerminology.

/**
	 * synchronize terminology
	 */
private void cleanupTerminology() {
    // only continue if we have required tables
    if (!m_source.isObjectExists("AD_Sequence", m_source.getTables()))
        return;
    if (!m_source.isObjectExists("AD_Element", m_source.getTables()))
        return;
    if (!m_source.isObjectExists("AD_Table", m_source.getTables()))
        return;
    if (!m_source.isObjectExists("AD_Column", m_source.getTables()))
        return;
    if (!m_source.isObjectExists("AD_Process_Para", m_source.getTables()))
        return;
    // reset DB objects
    resetDBObjects(null);
    m_counterUpd = new Integer(0);
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "cleanupTerminology", m_direction);
    String vendor = m_target.getVendor();
    String catalog = m_target.getCatalog();
    String schema = m_target.getSchema();
    // remember savepoint for rollback
    Savepoint sp = m_target.setSavepoint("synchronize terminology");
    // prepare statements
    // (we are only interested in the structure of sequences and elements as
    // defined in
    // the data dictionary and can ignore customizations, so it is
    // sufficient to only
    // look at the structure of source objects)
    ArrayList<String> insertColumnNames = new ArrayList<String>();
    ArrayList<String> updateColumnNames = new ArrayList<String>();
    ArrayList<String> whereColumnNames = new ArrayList<String>();
    // columns used by AD_Sequence
    DBObject table = m_source.getObjectByName("AD_Sequence", m_source.getTables());
    Vector<Integer> v = new Vector<Integer>(table.getContents().keySet());
    java.util.Collections.sort(v);
    for (Iterator<Integer> columnIterator = v.iterator(); columnIterator.hasNext(); ) {
        Integer key = columnIterator.next();
        DBObject_Table_Column sequenceColumn = (DBObject_Table_Column) table.getContents().get(key);
        String columnName = sequenceColumn.getName();
        // columns required for updating system sequence counters
        if (columnName.equalsIgnoreCase("Updated") || columnName.equalsIgnoreCase("CurrentNextSys") || columnName.equalsIgnoreCase("CurrentNext")) {
            updateColumnNames.add(columnName);
        }
        // columns to use in WHERE clause for updating sequence counters
        if (columnName.equalsIgnoreCase("Name")) {
            whereColumnNames.add(columnName);
        }
    }
    // columns used by AD_Element
    table = m_source.getObjectByName("AD_Element", m_source.getTables());
    v = new Vector<Integer>(table.getContents().keySet());
    java.util.Collections.sort(v);
    for (Iterator<Integer> columnIterator = v.iterator(); columnIterator.hasNext(); ) {
        Integer key = columnIterator.next();
        DBObject_Table_Column sequenceColumn = (DBObject_Table_Column) table.getContents().get(key);
        String columnName = sequenceColumn.getName();
        // columns required for inserting new elements
        if (columnName.equalsIgnoreCase("AD_Element_ID") || columnName.equalsIgnoreCase("AD_Client_ID") || columnName.equalsIgnoreCase("AD_Org_ID") || columnName.equalsIgnoreCase("IsActive") || columnName.equalsIgnoreCase("Created") || columnName.equalsIgnoreCase("CreatedBy") || columnName.equalsIgnoreCase("Updated") || columnName.equalsIgnoreCase("UpdatedBy") || columnName.equalsIgnoreCase("ColumnName") || columnName.equalsIgnoreCase("Name") || columnName.equalsIgnoreCase("PrintName") || columnName.equalsIgnoreCase("Description") || columnName.equalsIgnoreCase("Help") || columnName.equalsIgnoreCase("EntityType")) {
            insertColumnNames.add(columnName);
        }
    }
    PreparedStatementWrapper stmtLoadSequence = null;
    PreparedStatementWrapper stmtUpdateSequence = null;
    PreparedStatementWrapper stmtInsertElement = null;
    PreparedStatementWrapper stmtTranslatedColumns = null;
    // statement to load sequence number
    stmtLoadSequence = m_target.setPreparedStatement(s_dbEngine.sql_selectPreparedStatement(vendor, catalog, schema, "AD_Sequence", whereColumnNames));
    m_target.setPreparedStatementString(stmtLoadSequence, 1, "AD_Element");
    // statement to increment sequence number
    stmtUpdateSequence = m_target.setPreparedStatement(s_dbEngine.sql_updatePreparedStatement(vendor, catalog, schema, "AD_Sequence", updateColumnNames, whereColumnNames));
    m_target.setPreparedStatementString(stmtUpdateSequence, updateColumnNames.size() + 1, "AD_Element");
    // statement to add element
    stmtInsertElement = m_target.setPreparedStatement(s_dbEngine.sql_insertPreparedStatement(vendor, catalog, schema, "AD_Element", insertColumnNames));
    // statement to find translated columns
    stmtTranslatedColumns = m_target.setPreparedStatement(s_dbEngine.sqlAD_getTranslatedColumns(vendor, catalog, schema));
    // create new elements for system columns that do not yet have a base
    // element
    ArrayList<String> createdElements = new ArrayList<String>();
    String columnName = "";
    String name = "";
    String description = "";
    String help = "";
    String entityType = "";
    int sysNextSeq = 0;
    int userNextSeq = 0;
    int increment = 0;
    Statement stmt = m_target.setStatement();
    ResultSet rs = m_target.executeQuery(stmt, s_dbEngine.sqlAD_getSystemColumnsWithoutElement(vendor, catalog, schema, m_target.getCustomEntities()));
    while (m_target.getResultSetNext(rs)) {
        columnName = m_target.getResultSetString(rs, "ColumnName");
        name = m_target.getResultSetString(rs, "Name");
        description = m_target.getResultSetString(rs, "Description");
        help = m_target.getResultSetString(rs, "Help");
        entityType = m_target.getResultSetString(rs, "EntityType");
        if (!createdElements.contains(columnName)) {
            createdElements.add(columnName);
            // get next AD_Element_ID
            ResultSet rsLoadSequence = m_target.executeQuery(stmtLoadSequence);
            if (m_target.getResultSetNext(rsLoadSequence)) {
                sysNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNextSys");
                userNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNext");
                increment = m_target.getResultSetInt(rsLoadSequence, "IncrementNo");
            }
            m_target.releaseResultSet(rsLoadSequence);
            // increment to next AD_Element_ID and save
            for (int i = 0; i < updateColumnNames.size(); i++) {
                String currentColumnName = updateColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtUpdateSequence, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CurrentNextSys")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, sysNextSeq + increment);
                } else if (currentColumnName.equalsIgnoreCase("CurrentNext")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, userNextSeq);
                }
            }
            m_target.executeUpdate(stmtUpdateSequence, false);
            // create new element
            for (int i = 0; i < insertColumnNames.size(); i++) {
                String currentColumnName = insertColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("AD_Element_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, sysNextSeq);
                } else if (currentColumnName.equalsIgnoreCase("AD_Client_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("AD_Org_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("IsActive")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, "Y");
                } else if (currentColumnName.equalsIgnoreCase("Created")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CreatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("UpdatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("ColumnName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, columnName);
                } else if (currentColumnName.equalsIgnoreCase("Name")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("PrintName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("Description")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, description);
                } else if (currentColumnName.equalsIgnoreCase("Help")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, help);
                } else if (currentColumnName.equalsIgnoreCase("EntityType")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, entityType);
                }
            }
            Integer sqlResult = m_target.executeUpdate(stmtInsertElement, false);
            if (sqlResult != null) {
                logAddDetail(sqlResult, null);
            }
        }
    }
    m_target.releaseResultSet(rs);
    m_target.releaseStatement(stmt);
    // create new elements for custom columns that do not yet have a base
    // element
    columnName = "";
    name = "";
    description = "";
    help = "";
    entityType = "";
    sysNextSeq = 0;
    userNextSeq = 0;
    increment = 0;
    stmt = m_target.setStatement();
    rs = m_target.executeQuery(stmt, s_dbEngine.sqlAD_getCustomColumnsWithoutElement(vendor, catalog, schema, m_target.getCustomEntities()));
    while (m_target.getResultSetNext(rs)) {
        columnName = m_target.getResultSetString(rs, "ColumnName");
        name = m_target.getResultSetString(rs, "Name");
        description = m_target.getResultSetString(rs, "Description");
        help = m_target.getResultSetString(rs, "Help");
        entityType = m_target.getResultSetString(rs, "EntityType");
        if (!createdElements.contains(columnName)) {
            createdElements.add(columnName);
            // get next AD_Element_ID
            ResultSet rsLoadSequence = m_target.executeQuery(stmtLoadSequence);
            if (m_target.getResultSetNext(rsLoadSequence)) {
                sysNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNextSys");
                userNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNext");
                increment = m_target.getResultSetInt(rsLoadSequence, "IncrementNo");
            }
            m_target.releaseResultSet(rsLoadSequence);
            // increment to next AD_Element_ID and save
            for (int i = 0; i < updateColumnNames.size(); i++) {
                String currentColumnName = updateColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtUpdateSequence, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CurrentNextSys")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, sysNextSeq);
                } else if (currentColumnName.equalsIgnoreCase("CurrentNext")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, userNextSeq + increment);
                }
            }
            m_target.executeUpdate(stmtUpdateSequence, false);
            // create new element
            for (int i = 0; i < insertColumnNames.size(); i++) {
                String currentColumnName = insertColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("AD_Element_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, userNextSeq);
                } else if (currentColumnName.equalsIgnoreCase("AD_Client_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("AD_Org_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("IsActive")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, "Y");
                } else if (currentColumnName.equalsIgnoreCase("Created")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CreatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("UpdatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("ColumnName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, columnName);
                } else if (currentColumnName.equalsIgnoreCase("Name")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("PrintName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("Description")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, description);
                } else if (currentColumnName.equalsIgnoreCase("Help")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, help);
                } else if (currentColumnName.equalsIgnoreCase("EntityType")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, entityType);
                }
            }
            Integer sqlResult = m_target.executeUpdate(stmtInsertElement, false);
            if (sqlResult != null) {
                logAddDetail(sqlResult, null);
            }
        }
    }
    m_target.releaseResultSet(rs);
    m_target.releaseStatement(stmt);
    // create new elements for system parameters that do not yet have a base
    // element
    columnName = "";
    name = "";
    description = "";
    help = "";
    entityType = "";
    sysNextSeq = 0;
    userNextSeq = 0;
    increment = 0;
    stmt = m_target.setStatement();
    rs = m_target.executeQuery(stmt, s_dbEngine.sqlAD_getSystemParametersWithoutElement(vendor, catalog, schema, m_target.getCustomEntities()));
    while (m_target.getResultSetNext(rs)) {
        columnName = m_target.getResultSetString(rs, "ColumnName");
        name = m_target.getResultSetString(rs, "Name");
        description = m_target.getResultSetString(rs, "Description");
        help = m_target.getResultSetString(rs, "Help");
        entityType = m_target.getResultSetString(rs, "EntityType");
        if (!createdElements.contains(columnName)) {
            createdElements.add(columnName);
            // get next AD_Element_ID
            ResultSet rsLoadSequence = m_target.executeQuery(stmtLoadSequence);
            if (m_target.getResultSetNext(rsLoadSequence)) {
                sysNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNextSys");
                userNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNext");
                increment = m_target.getResultSetInt(rsLoadSequence, "IncrementNo");
            }
            m_target.releaseResultSet(rsLoadSequence);
            // increment to next AD_Element_ID and save
            for (int i = 0; i < updateColumnNames.size(); i++) {
                String currentColumnName = updateColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtUpdateSequence, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CurrentNextSys")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, sysNextSeq + increment);
                } else if (currentColumnName.equalsIgnoreCase("CurrentNext")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, userNextSeq);
                }
            }
            m_target.executeUpdate(stmtUpdateSequence, false);
            // create new element
            for (int i = 0; i < insertColumnNames.size(); i++) {
                String currentColumnName = insertColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("AD_Element_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, sysNextSeq);
                } else if (currentColumnName.equalsIgnoreCase("AD_Client_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("AD_Org_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("IsActive")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, "Y");
                } else if (currentColumnName.equalsIgnoreCase("Created")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CreatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("UpdatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("ColumnName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, columnName);
                } else if (currentColumnName.equalsIgnoreCase("Name")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("PrintName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("Description")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, description);
                } else if (currentColumnName.equalsIgnoreCase("Help")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, help);
                } else if (currentColumnName.equalsIgnoreCase("EntityType")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, entityType);
                }
            }
            Integer sqlResult = m_target.executeUpdate(stmtInsertElement, false);
            if (sqlResult != null) {
                logAddDetail(sqlResult, null);
            }
        }
    }
    m_target.releaseResultSet(rs);
    m_target.releaseStatement(stmt);
    // create new elements for custom parameters that do not yet have a base
    // element
    columnName = "";
    name = "";
    description = "";
    help = "";
    entityType = "";
    sysNextSeq = 0;
    userNextSeq = 0;
    increment = 0;
    stmt = m_target.setStatement();
    rs = m_target.executeQuery(stmt, s_dbEngine.sqlAD_getCustomParametersWithoutElement(vendor, catalog, schema, m_target.getCustomEntities()));
    while (m_target.getResultSetNext(rs)) {
        columnName = m_target.getResultSetString(rs, "ColumnName");
        name = m_target.getResultSetString(rs, "Name");
        description = m_target.getResultSetString(rs, "Description");
        help = m_target.getResultSetString(rs, "Help");
        entityType = m_target.getResultSetString(rs, "EntityType");
        if (!createdElements.contains(columnName)) {
            createdElements.add(columnName);
            // get next AD_Element_ID
            ResultSet rsLoadSequence = m_target.executeQuery(stmtLoadSequence);
            if (m_target.getResultSetNext(rsLoadSequence)) {
                sysNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNextSys");
                userNextSeq = m_target.getResultSetInt(rsLoadSequence, "CurrentNext");
                increment = m_target.getResultSetInt(rsLoadSequence, "IncrementNo");
            }
            m_target.releaseResultSet(rsLoadSequence);
            // increment to next AD_Element_ID and save
            for (int i = 0; i < updateColumnNames.size(); i++) {
                String currentColumnName = updateColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtUpdateSequence, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CurrentNextSys")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, sysNextSeq);
                } else if (currentColumnName.equalsIgnoreCase("CurrentNext")) {
                    m_target.setPreparedStatementInt(stmtUpdateSequence, parameterIndex, userNextSeq + increment);
                }
            }
            m_target.executeUpdate(stmtUpdateSequence, false);
            // create new element
            for (int i = 0; i < insertColumnNames.size(); i++) {
                String currentColumnName = insertColumnNames.get(i);
                int parameterIndex = i + 1;
                if (currentColumnName.equalsIgnoreCase("AD_Element_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, userNextSeq);
                } else if (currentColumnName.equalsIgnoreCase("AD_Client_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("AD_Org_ID")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("IsActive")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, "Y");
                } else if (currentColumnName.equalsIgnoreCase("Created")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("CreatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("Updated")) {
                    m_target.setPreparedStatementTimestamp(stmtInsertElement, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
                } else if (currentColumnName.equalsIgnoreCase("UpdatedBy")) {
                    m_target.setPreparedStatementInt(stmtInsertElement, parameterIndex, 0);
                } else if (currentColumnName.equalsIgnoreCase("ColumnName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, columnName);
                } else if (currentColumnName.equalsIgnoreCase("Name")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("PrintName")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, name);
                } else if (currentColumnName.equalsIgnoreCase("Description")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, description);
                } else if (currentColumnName.equalsIgnoreCase("Help")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, help);
                } else if (currentColumnName.equalsIgnoreCase("EntityType")) {
                    m_target.setPreparedStatementString(stmtInsertElement, parameterIndex, entityType);
                }
            }
            Integer sqlResult = m_target.executeUpdate(stmtInsertElement, false);
            if (sqlResult != null) {
                logAddDetail(sqlResult, null);
            }
        }
    }
    m_target.releaseResultSet(rs);
    m_target.releaseStatement(stmt);
    // (the link to the new element will be created later)
    if (createdElements != null && createdElements.size() > 0) {
        columnName = "";
        String sqlCommand = s_dbEngine.sql_updatePreparedStatement(vendor, catalog, schema, "AD_Column", new ArrayList<String>(Arrays.asList("AD_Element_ID")), new ArrayList<String>(Arrays.asList("ColumnName")));
        PreparedStatementWrapper pstmt = m_target.setPreparedStatement(sqlCommand);
        m_target.setPreparedStatementNull(pstmt, 1, java.sql.Types.INTEGER);
        Iterator<String> it = createdElements.iterator();
        while (it.hasNext()) {
            columnName = it.next();
            m_target.setPreparedStatementString(pstmt, 2, columnName);
            Integer sqlResult = m_target.executeUpdate(pstmt, false);
            if (sqlResult != null) {
                logUpdateDetail(sqlResult, null);
            }
        }
        m_target.releasePreparedStatement(pstmt);
    }
    // (the link to the new element will be created later)
    if (createdElements != null && createdElements.size() > 0) {
        columnName = "";
        String sqlCommand = s_dbEngine.sql_updatePreparedStatement(vendor, catalog, schema, "AD_Process_Para", new ArrayList<String>(Arrays.asList("AD_Element_ID")), new ArrayList<String>(Arrays.asList("ColumnName")));
        PreparedStatementWrapper pstmt = m_target.setPreparedStatement(sqlCommand);
        m_target.setPreparedStatementNull(pstmt, 1, java.sql.Types.INTEGER);
        Iterator<String> it = createdElements.iterator();
        while (it.hasNext()) {
            columnName = it.next();
            m_target.setPreparedStatementString(pstmt, 2, columnName);
            Integer sqlResult = m_target.executeUpdate(pstmt, false);
            if (sqlResult != null) {
                logUpdateDetail(sqlResult, null);
            }
        }
        m_target.releasePreparedStatement(pstmt);
    }
    // add missing element translations
    String tableName = "AD_Element";
    ArrayList<String> translatedColumnNames = new ArrayList<String>();
    m_target.setPreparedStatementString(stmtTranslatedColumns, 1, tableName);
    rs = m_target.executeQuery(stmtTranslatedColumns);
    while (m_target.getResultSetNext(rs)) {
        translatedColumnNames.add(m_target.getResultSetString(rs, "ColumnName"));
    }
    m_target.releaseResultSet(rs);
    if (translatedColumnNames.size() > 0) {
        String sqlCommand = s_dbEngine.sqlADAction_insertTranslation(vendor, catalog, schema, tableName, translatedColumnNames);
        stmt = m_target.setStatement();
        Integer sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
        if (sqlResult != null) {
            logAddDetail(sqlResult, null);
        }
        m_target.releaseStatement(stmt);
    }
    // link columns to elements
    String sqlCommand = s_dbEngine.sqlADAction_updateLinkColumnElement(vendor, catalog, schema);
    stmt = m_target.setStatement();
    Integer sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
    if (sqlResult != null) {
        logUpdateDetail(sqlResult, null);
    }
    m_target.releaseStatement(stmt);
    // link parameters to elements
    sqlCommand = s_dbEngine.sqlADAction_updateLinkParameterElement(vendor, catalog, schema);
    stmt = m_target.setStatement();
    sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
    if (sqlResult != null) {
        logUpdateDetail(sqlResult, null);
    }
    m_target.releaseStatement(stmt);
    // delete unused elements
    sqlCommand = s_dbEngine.sqlADAction_deleteUnusedElementTranslations(vendor, catalog, schema);
    stmt = m_target.setStatement();
    sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
    if (sqlResult != null) {
        logDropDetail(sqlResult, null);
    }
    m_target.releaseStatement(stmt);
    sqlCommand = s_dbEngine.sqlADAction_deleteUnusedElements(vendor, catalog, schema);
    stmt = m_target.setStatement();
    sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
    if (sqlResult != null) {
        logDropDetail(sqlResult, null);
    }
    m_target.releaseStatement(stmt);
    // close prepared statements
    m_target.releasePreparedStatement(stmtLoadSequence);
    m_target.releasePreparedStatement(stmtUpdateSequence);
    m_target.releasePreparedStatement(stmtInsertElement);
    m_target.releasePreparedStatement(stmtTranslatedColumns);
    // SYNCHRONIZE TERMINOLOGY
    terminologyCheck("columns", "AD_Column", "AD_Element", null, null, null, null);
    terminologyCheck("column translations", "AD_Column", "AD_Element", "AD_Column_Trl", "AD_Element_Trl", null, null);
    terminologyCheck("tables", "AD_Table", "AD_Element", null, null, null, null);
    terminologyCheck("table translations", "AD_Table", "AD_Element", "AD_Table_Trl", "AD_Element_Trl", null, null);
    terminologyCheck("fields", "AD_Field", "AD_Element", null, null, new ArrayList<String>(Arrays.asList("AD_Column")), null);
    terminologyCheck("field translations", "AD_Field", "AD_Element", "AD_Field_Trl", "AD_Element_Trl", new ArrayList<String>(Arrays.asList("AD_Column")), null);
    terminologyCheck("PO-fields", "AD_Field", "AD_Element", null, null, new ArrayList<String>(Arrays.asList("AD_Column")), new ArrayList<String>(Arrays.asList("AD_Window", "AD_Tab")));
    terminologyCheck("PO-field translations", "AD_Field", "AD_Element", "AD_Field_Trl", "AD_Element_Trl", new ArrayList<String>(Arrays.asList("AD_Column")), new ArrayList<String>(Arrays.asList("AD_Window", "AD_Tab")));
    terminologyCheck("fields from process", "AD_Field", "AD_Process", null, null, new ArrayList<String>(Arrays.asList("AD_Column")), null);
    terminologyCheck("field translations from process", "AD_Field", "AD_Process", "AD_Field_Trl", "AD_Process_Trl", new ArrayList<String>(Arrays.asList("AD_Column")), null);
    terminologyCheck("parameters", "AD_Process_Para", "AD_Element", null, null, null, null);
    terminologyCheck("parameter translations", "AD_Process_Para", "AD_Element", "AD_Process_Para_Trl", "AD_Element_Trl", null, null);
    terminologyCheck("workflow nodes from window", "AD_WF_Node", "AD_Window", null, null, null, null);
    terminologyCheck("workflow node translations from window", "AD_WF_Node", "AD_Window", "AD_WF_Node_Trl", "AD_Window_Trl", null, null);
    terminologyCheck("workflow nodes from form", "AD_WF_Node", "AD_Form", null, null, null, null);
    terminologyCheck("workflow node translations from form", "AD_WF_Node", "AD_Form", "AD_WF_Node_Trl", "AD_Form_Trl", null, null);
    terminologyCheck("workflow nodes from process", "AD_WF_Node", "AD_Process", null, null, null, null);
    terminologyCheck("workflow node translations from process", "AD_WF_Node", "AD_Process", "AD_WF_Node_Trl", "AD_Process_Trl", null, null);
    terminologyCheck("menus from window", "AD_Menu", "AD_Window", null, null, null, null);
    terminologyCheck("menu translations from window", "AD_Menu", "AD_Window", "AD_Menu_Trl", "AD_Window_Trl", null, null);
    terminologyCheck("menus from process", "AD_Menu", "AD_Process", null, null, null, null);
    terminologyCheck("menu translations from process", "AD_Menu", "AD_Process", "AD_Menu_Trl", "AD_Process_Trl", null, null);
    terminologyCheck("menus from form", "AD_Menu", "AD_Form", null, null, null, null);
    terminologyCheck("menu translations from form", "AD_Menu", "AD_Form", "AD_Menu_Trl", "AD_Form_Trl", null, null);
    terminologyCheck("menus from workflow", "AD_Menu", "AD_Workflow", null, null, null, null);
    terminologyCheck("menu translations from workflow", "AD_Menu", "AD_Workflow", "AD_Menu_Trl", "AD_Workflow_Trl", null, null);
    terminologyCheck("menus from task", "AD_Menu", "AD_Task", null, null, null, null);
    terminologyCheck("menu translations from task", "AD_Menu", "AD_Task", "AD_Menu_Trl", "AD_Task_Trl", null, null);
    terminologyCheck("print format item names", "AD_PrintFormatItem", "AD_Element", null, null, new ArrayList<String>(Arrays.asList("AD_Column")), new ArrayList<String>(Arrays.asList("AD_Client")));
    terminologyCheck("print format item print names", "AD_PrintFormatItem", "AD_Element", null, null, new ArrayList<String>(Arrays.asList("AD_Column")), new ArrayList<String>(Arrays.asList("AD_PrintFormat", "AD_Client")));
    terminologyCheck("print format item print name multi-lingual translations", "AD_PrintFormatItem", "AD_Element", "AD_PrintFormatItem_Trl", "AD_Element_Trl", new ArrayList<String>(Arrays.asList("AD_Column")), new ArrayList<String>(Arrays.asList("AD_PrintFormat", "AD_Client")));
    terminologyCheck("print format item print name mono-lingual translations", "AD_PrintFormatItem", "AD_PrintFormatItem", "AD_PrintFormatItem_Trl", null, null, new ArrayList<String>(Arrays.asList("AD_PrintFormat", "AD_Client")));
    terminologyCheck("unused print format item print name translations", "AD_PrintFormatItem", "AD_PrintFormatItem", "AD_PrintFormatItem_Trl", null, null, null);
    // release savepoint
    m_target.releaseSavepoint(sp);
    logResults();
}
Also used : Statement(java.sql.Statement) ArrayList(java.util.ArrayList) Savepoint(java.sql.Savepoint) Savepoint(java.sql.Savepoint) ResultSet(java.sql.ResultSet) Vector(java.util.Vector)

Example 88 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class Migrate method purgeSystemRecords.

/**
	 * purge system entries from database
	 *
	 * @param truncatedTables
	 *            list of tables already truncated that should not be purged
	 *            again
	 */
private void purgeSystemRecords(ArrayList<String> truncatedTables) {
    // temporarily disconnect from source to ease burden on server
    m_source.temporarilyDisconnectSource();
    resetDBObjects(DBObject_Table.class);
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "purgeSystemRecords", new Object[] { m_objectTypes, m_direction });
    m_counterPrg = new Integer(0);
    m_totalPrg = new Integer(0);
    // exclude tables already truncated from being purged
    for (Iterator<String> it = truncatedTables.iterator(); it.hasNext(); ) {
        m_trackingList.add(it.next());
    }
    // exclude translations from being purged
    for (Iterator<String> it = m_targetMap.keySet().iterator(); it.hasNext(); ) {
        String key = it.next();
        DBObject obj = m_targetMap.get(key);
        String tableName = obj.getName().toUpperCase();
        if (tableName.endsWith("_TRL"))
            m_trackingList.add(tableName);
    }
    // exclude ad_system from being purged
    m_trackingList.add("AD_SYSTEM");
    // exclude ad_user from being purged
    // (we need to preserve the system passwords)
    m_trackingList.add("AD_USER");
    // remember savepoint
    Savepoint sp = m_target.setSavepoint("purge system records");
    // first go through tree nodes before other system data,
    // which might be needed for node resolution, is purged
    m_nodesToPreserve = new HashMap<String, String>();
    Vector<String> v = new Vector<String>(m_targetMap.keySet());
    java.util.Collections.sort(v);
    for (Iterator<String> it = v.iterator(); it.hasNext(); ) {
        String key = it.next();
        DBObject obj = m_targetMap.get(key);
        if (obj.getName().toUpperCase().startsWith("AD_TREENODE")) {
            String exclusionClause = protectCustomizedNodes(obj);
            if (exclusionClause != null && exclusionClause.length() > 0)
                m_nodesToPreserve.put(obj.getName(), exclusionClause);
        }
    }
    // then iterate through all tables
    v = new Vector<String>(m_targetMap.keySet());
    java.util.Collections.sort(v);
    for (Iterator<String> it = v.iterator(); it.hasNext(); ) {
        String key = it.next();
        DBObject obj = m_targetMap.get(key);
        purgeSystemRecord(obj);
    }
    // release savepoint
    m_target.releaseSavepoint(sp);
    logResults();
    // reconnect to source
    m_source.reconnectSource();
}
Also used : Savepoint(java.sql.Savepoint) Vector(java.util.Vector)

Example 89 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class Migrate method truncateTemporaryTables.

/**
	 * purge old data from temporary tables
	 */
private void truncateTemporaryTables() {
    resetDBObjects(DBObject_Table.class);
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "truncateTemporaryTables", new Object[] { m_objectTypes, m_direction });
    m_counterPrg = new Integer(0);
    m_totalPrg = new Integer(0);
    Vector<String> v = new Vector<String>(m_targetMap.keySet());
    java.util.Collections.sort(v);
    for (Iterator<String> it = v.iterator(); it.hasNext(); ) {
        String key = it.next();
        DBObject obj = m_targetMap.get(key);
        String vendor = m_target.getVendor();
        String catalog = m_target.getCatalog();
        String schema = m_target.getSchema();
        String table = obj.getName();
        String sql = null;
        // temporary tables
        if (table.toUpperCase().startsWith("T_"))
            sql = s_dbEngine.sql_delete(vendor, catalog, schema, table);
        else // imported records from import tables
        if (table.toUpperCase().startsWith("I_"))
            sql = s_dbEngine.sql_deleteByCondition(vendor, catalog, schema, table, "I_IsImported='Y'");
        else // test table
        if (table.equalsIgnoreCase("Test"))
            sql = s_dbEngine.sql_delete(vendor, catalog, schema, table);
        else // processes and errors
        if (table.toUpperCase().startsWith("AD_PINSTANCE") || table.equalsIgnoreCase("AD_Find") || table.equalsIgnoreCase("AD_Error") || table.equalsIgnoreCase("AD_Issue"))
            sql = s_dbEngine.sql_delete(vendor, catalog, schema, table);
        else // changes which are not customizations
        if (table.equalsIgnoreCase("AD_ChangeLog"))
            sql = s_dbEngine.sql_deleteByCondition(vendor, catalog, schema, table, "IsCustomization != 'Y'");
        else // sessions older than a week
        if (table.equalsIgnoreCase("AD_Session")) {
            if (hasTableColumn(obj, "updated"))
                sql = s_dbEngine.sql_delete(vendor, catalog, schema, table, "AD_Session_ID NOT IN (SELECT AD_Session_ID FROM AD_ChangeLog)", 7);
            else
                sql = s_dbEngine.sql_deleteByCondition(vendor, catalog, schema, table, "AD_Session_ID NOT IN (SELECT AD_Session_ID FROM AD_ChangeLog)");
        } else // notes which have been processed
        if (table.equalsIgnoreCase("AD_Note"))
            sql = s_dbEngine.sql_deleteByCondition(vendor, catalog, schema, table, "Processed='Y'");
        else // log entries older than a week
        if (table.toUpperCase().endsWith("LOG")) {
            if (hasTableColumn(obj, "updated"))
                sql = s_dbEngine.sql_deleteByAge(vendor, catalog, schema, table, 7);
            else
                sql = s_dbEngine.sql_delete(vendor, catalog, schema, table);
        }
        if (sql != null) {
            s_logger.log(Level.FINE, "purgeTableToTruncate", new Object[] { m_objectType, table, m_direction });
            // purge temporary data no longer required
            Savepoint sp = m_target.setSavepoint(table);
            Statement stmt = m_target.setStatement();
            Integer sqlResult = m_target.executeUpdate(stmt, sql, false, false);
            if (sqlResult != null) {
                logDropDetail(sqlResult, null);
                m_trackingList.add(table.toUpperCase());
                m_counterPrg = new Integer(m_counterPrg.intValue() + 1);
            }
            m_target.releaseStatement(stmt);
            m_target.releaseSavepoint(sp);
            m_totalPrg = new Integer(m_totalPrg.intValue() + 1);
        }
    }
    logResults();
}
Also used : Statement(java.sql.Statement) Savepoint(java.sql.Savepoint) Vector(java.util.Vector)

Example 90 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class Migrate method cleanupTranslations.

/**
	 * add missing translations
	 */
private void cleanupTranslations() {
    // only continue if we have required tables
    if (!m_source.isObjectExists("AD_Table", m_source.getTables()))
        return;
    if (!m_source.isObjectExists("AD_Column", m_source.getTables()))
        return;
    // reset DB objects
    resetDBObjects(null);
    m_objectType = "table";
    m_objectTypes = "tables";
    m_detailType = "translation";
    m_detailTypes = "translations";
    m_counterUpd = new Integer(0);
    m_totalUpd = new Integer(0);
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "cleanupTranslations", m_direction);
    String vendor = m_target.getVendor();
    String catalog = m_target.getCatalog();
    String schema = m_target.getSchema();
    // remember savepoint for rollback
    Savepoint sp = m_target.setSavepoint("add translations");
    // find tables which need to be translated
    ArrayList<String> tableNames = new ArrayList<String>();
    String sqlCommand = s_dbEngine.sqlAD_getTranslatedTables(vendor, catalog, schema);
    Statement stmt = m_target.setStatement();
    ResultSet rs = m_target.executeQuery(stmt, sqlCommand);
    while (m_target.getResultSetNext(rs)) {
        tableNames.add(m_target.getResultSetString(rs, "TableName"));
        m_totalUpd = new Integer(m_totalUpd.intValue() + 1);
    }
    m_target.releaseResultSet(rs);
    m_target.releaseStatement(stmt);
    // find columns which need to be translated
    HashMap<String, ArrayList<String>> missingTranslations = new HashMap<String, ArrayList<String>>();
    sqlCommand = s_dbEngine.sqlAD_getTranslatedColumns(vendor, catalog, schema);
    PreparedStatementWrapper pstmt = m_target.setPreparedStatement(sqlCommand);
    // iterate through tables
    for (Iterator<String> i = tableNames.iterator(); i.hasNext(); ) {
        String tableName = i.next();
        ArrayList<String> columnNames = new ArrayList<String>();
        m_target.setPreparedStatementString(pstmt, 1, tableName);
        rs = m_target.executeQuery(pstmt);
        while (m_target.getResultSetNext(rs)) {
            columnNames.add(m_target.getResultSetString(rs, "ColumnName"));
        }
        m_target.releaseResultSet(rs);
        missingTranslations.put(tableName, columnNames);
    }
    m_target.releasePreparedStatement(pstmt);
    // add missing translations
    for (Iterator<String> i = tableNames.iterator(); i.hasNext(); ) {
        String tableName = i.next();
        ArrayList<String> columnNames = missingTranslations.get(tableName);
        sqlCommand = s_dbEngine.sqlADAction_insertTranslation(vendor, catalog, schema, tableName, columnNames);
        stmt = m_target.setStatement();
        Integer sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
        if (sqlResult != null) {
            logAddDetail(sqlResult, null);
            m_counterUpd = new Integer(m_counterUpd.intValue() + 1);
        }
        m_target.releaseStatement(stmt);
    }
    // release savepoint
    m_target.releaseSavepoint(sp);
    logResults();
}
Also used : HashMap(java.util.HashMap) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) Savepoint(java.sql.Savepoint)

Aggregations

Savepoint (java.sql.Savepoint)167 Statement (java.sql.Statement)61 Connection (java.sql.Connection)56 SQLException (java.sql.SQLException)55 PreparedStatement (java.sql.PreparedStatement)32 Test (org.junit.Test)31 ResultSet (java.sql.ResultSet)26 DatabaseMetaData (java.sql.DatabaseMetaData)13 UnitTest (nl.topicus.jdbc.test.category.UnitTest)13 TransactionStatus (org.springframework.transaction.TransactionStatus)12 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)12 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)12 ArrayList (java.util.ArrayList)11 Vector (java.util.Vector)11 Test (org.junit.jupiter.api.Test)10 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)10 SQLClientInfoException (java.sql.SQLClientInfoException)7 HashMap (java.util.HashMap)5 ConcurrencyFailureException (org.springframework.dao.ConcurrencyFailureException)5 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)4