Search in sources :

Example 91 with Savepoint

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

the class Migrate method bumpVersionInfo.

/**
	 * update version information
	 */
private void bumpVersionInfo() {
    // only continue if we have required tables
    if (!m_source.isObjectExists("AD_System", m_source.getTables()))
        return;
    // reset DB objects
    resetDBObjects(null);
    m_counterUpd = new Integer(0);
    m_totalUpd = new Integer(0);
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "bumpVersionInfo", m_direction);
    // target now has source's structure, so we need to use source metadata
    String sourceVendor = m_source.getVendor();
    String sourceCatalog = m_source.getCatalog();
    String sourceSchema = m_source.getSchema();
    String targetVendor = m_target.getVendor();
    String targetCatalog = m_target.getCatalog();
    String targetSchema = m_target.getSchema();
    // column lists
    ArrayList<String> updateColumnNames = new ArrayList<String>();
    ArrayList<String> whereColumnNames = new ArrayList<String>();
    DBObject table = m_source.getObjectByName("AD_System", 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 version information
        if (columnName.equalsIgnoreCase("Updated") || columnName.equalsIgnoreCase("UpdatedBy") || columnName.equalsIgnoreCase("Version") || columnName.equalsIgnoreCase("ReleaseNo")) {
            updateColumnNames.add(columnName);
        }
        // columns to use in WHERE clause for updating version information
        if (columnName.equalsIgnoreCase("AD_System_ID") || columnName.equalsIgnoreCase("AD_Client_ID")) {
            whereColumnNames.add(columnName);
        }
    }
    // remember savepoint for rollback
    Savepoint sp = m_target.setSavepoint("update version information");
    // prepared statement to update version number
    PreparedStatementWrapper stmtUpdateVersion = m_target.setPreparedStatement(s_dbEngine.sql_updatePreparedStatement(targetVendor, targetCatalog, targetSchema, "AD_System", updateColumnNames, whereColumnNames));
    // load version information from source
    Statement stmt = m_source.setStatement();
    ResultSet rs = m_source.executeQuery(stmt, s_dbEngine.sqlAD_getAdempiereVersion(sourceVendor, sourceCatalog, sourceSchema));
    // set version information in target
    while (m_source.getResultSetNext(rs)) {
        // fill update values
        for (int i = 0; i < updateColumnNames.size(); i++) {
            String columnName = updateColumnNames.get(i);
            int parameterIndex = 1 + i;
            if (columnName.equalsIgnoreCase("Updated")) {
                m_target.setPreparedStatementTimestamp(stmtUpdateVersion, parameterIndex, new java.sql.Timestamp(System.currentTimeMillis()));
            } else if (columnName.equalsIgnoreCase("UpdatedBy")) {
                m_target.setPreparedStatementInt(stmtUpdateVersion, parameterIndex, m_source.getResultSetInt(rs, columnName));
            } else if (columnName.equalsIgnoreCase("Version") || columnName.equalsIgnoreCase("ReleaseNo")) {
                m_target.setPreparedStatementString(stmtUpdateVersion, parameterIndex, m_source.getResultSetString(rs, columnName));
            }
        }
        // fill condition values
        for (int i = 0; i < whereColumnNames.size(); i++) {
            String columnName = whereColumnNames.get(i);
            int parameterIndex = updateColumnNames.size() + i + 1;
            if (columnName.equalsIgnoreCase("AD_System_ID") || columnName.equalsIgnoreCase("AD_Client_ID")) {
                m_target.setPreparedStatementInt(stmtUpdateVersion, parameterIndex, m_source.getResultSetInt(rs, columnName));
            }
        }
        // execute update
        Integer sqlResult = m_target.executeUpdate(stmtUpdateVersion, false);
        if (sqlResult != null) {
            m_counterUpd = new Integer(m_counterUpd.intValue() + sqlResult.intValue());
            m_totalUpd = new Integer(m_totalUpd.intValue() + sqlResult.intValue());
        } else {
            m_totalUpd = new Integer(m_totalUpd.intValue() + 1);
        }
    }
    // release source objects
    m_source.releaseResultSet(rs);
    m_source.releaseStatement(stmt);
    // release target objects
    m_target.releasePreparedStatement(stmtUpdateVersion);
    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 92 with Savepoint

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

the class Migrate method preserveParentLink.

/**
	 * Preserve or re-create link to parent from a given child table
	 *
	 * @param brokenTableName
	 *            the table for which to preserve links to parent
	 * @param brokenColumnName
	 *            the column which should contain link to parent
	 * @param brokenDefaultValue
	 *            the default value which the column will contain if the link to
	 *            parent is broken
	 * @param brokenCompareColumns
	 *            array of columns which can be used to get a hint for finding
	 *            the correct parent
	 * @param hintTableName
	 *            the table which contains hints to find the correct parent
	 * @param hintColumnName
	 *            the column which contains the link to the correct parent
	 * @param hintCompareColumns
	 *            array of columns which can be used to give a hint for finding
	 *            the correct parent
	 */
private void preserveParentLink(String brokenTableName, String brokenColumnName, String brokenDefaultValue, ArrayList<String> brokenCompareColumns, String hintTableName, String hintColumnName, ArrayList<String> hintCompareColumns) {
    String vendorName = m_target.getVendor();
    String catalogName = m_target.getCatalog();
    String schemaName = m_target.getSchema();
    // exists in the reference database
    if (m_source.isObjectExists(brokenTableName, m_source.getTables())) {
        // check whether the column for which to preserve a link to a parent
        // exists in the reference database
        boolean columnToPreserveLinkExists = false;
        DBObject tableToPreserveLink = m_source.getObjectByName(brokenTableName, m_source.getTables());
        HashMap<Integer, DBObjectDefinition> columns = tableToPreserveLink.getContents();
        Vector<Integer> vc = new Vector<Integer>(columns.keySet());
        for (Iterator<Integer> ic = vc.iterator(); ic.hasNext(); ) {
            int kc = ic.next();
            DBObject_Table_Column columnDetail = (DBObject_Table_Column) columns.get(kc);
            String columnName = columnDetail.getName();
            if (columnName.equalsIgnoreCase(brokenColumnName))
                columnToPreserveLinkExists = true;
        }
        // preserve the links to parent records
        if (columnToPreserveLinkExists) {
            s_logger.log(Level.FINE, "preserveParentLinkDetail", new Object[] { m_objectType, brokenTableName, m_direction });
            String sqlCommand = s_dbEngine.sqlAction_preserveParentLinks(vendorName, catalogName, schemaName, brokenTableName, brokenColumnName, brokenDefaultValue, brokenCompareColumns, hintTableName, hintColumnName, hintCompareColumns);
            if (sqlCommand != null) {
                // remember savepoint for rollback
                Savepoint sp = m_target.setSavepoint("preserveParentLinks");
                Statement stmt = m_target.setStatement();
                Integer sqlResult = m_target.executeUpdate(stmt, sqlCommand, false, false);
                if (sqlResult != null) {
                    logUpdateDetail(sqlResult, null);
                    m_counterUpd = new Integer(m_counterUpd.intValue() + 1);
                }
                m_target.releaseStatement(stmt);
                m_totalUpd = new Integer(m_totalUpd.intValue() + 1);
                // release savepoint
                m_target.releaseSavepoint(sp);
            }
        }
    }
}
Also used : Statement(java.sql.Statement) Savepoint(java.sql.Savepoint) Savepoint(java.sql.Savepoint) Vector(java.util.Vector)

Example 93 with Savepoint

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

the class Migrate method synchronizeData.

/**
	 * transfer data (insert or update) from source to target
	 */
private void synchronizeData() {
    resetDBObjects(DBObject_Table.class);
    m_objectType = s_logger.localizeMessage("record");
    m_objectTypes = s_logger.localizeMessage("records");
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "synchronizeData", new Object[] { m_objectTypes, m_direction });
    // reset counters
    m_counterUpd = new Integer(0);
    m_totalUpd = new Integer(0);
    m_counterAdd = new Integer(0);
    m_totalAdd = new Integer(0);
    // target's structure is no longer valid and should now be same as
    // source,
    // so we need to use source metadata
    String sourceVendor = m_source.getVendor();
    String sourceCatalog = m_source.getCatalog();
    String sourceSchema = m_source.getSchema();
    String targetVendor = m_target.getVendor();
    String targetCatalog = m_target.getCatalog();
    String targetSchema = m_target.getSchema();
    // iterate through all tables and transfer data
    Vector<String> v = new Vector<String>(m_sourceMap.keySet());
    java.util.Collections.sort(v);
    for (Iterator<String> it = v.iterator(); it.hasNext(); ) {
        String key = it.next();
        // table
        DBObject table = m_sourceMap.get(key);
        String tableName = table.getName();
        // AD_System table should not be overwritten!
        if (isCopy() || !tableName.equalsIgnoreCase("AD_System")) {
            s_logger.log(Level.FINE, "transferRecords", new Object[] { m_objectTypes, tableName, m_direction });
            // columns (name and type)
            ArrayList<String> insertColumnNames = new ArrayList<String>();
            ArrayList<Integer> insertColumnTypes = new ArrayList<Integer>();
            ArrayList<String> updateColumnNames = new ArrayList<String>();
            ArrayList<Integer> updateColumnTypes = new ArrayList<Integer>();
            HashMap<String, Integer> columnTypeMap = new HashMap<String, Integer>();
            Vector<Integer> v2 = new Vector<Integer>(table.getContents().keySet());
            java.util.Collections.sort(v2);
            for (Iterator<Integer> i = v2.iterator(); i.hasNext(); ) {
                Integer j = i.next();
                DBObject_Table_Column col = (DBObject_Table_Column) table.getContents().get(j);
                String columnName = col.getName();
                int columnType = s_dbEngine.getDataTypeID(sourceVendor, col.getType());
                insertColumnNames.add(columnName);
                insertColumnTypes.add(columnType);
                // source
                if (!(tableName.equalsIgnoreCase("AD_USER") && columnName.equalsIgnoreCase("password"))) {
                    updateColumnNames.add(columnName);
                    updateColumnTypes.add(columnType);
                }
                columnTypeMap.put(columnName.toUpperCase(), columnType);
            }
            // primary key
            boolean isPkFound = false;
            ArrayList<String> pkColumns = new ArrayList<String>();
            ArrayList<Integer> pkTypes = new ArrayList<Integer>();
            if (m_source.getPrimaryKeys() != null) {
                // this table
                for (Iterator<String> i = m_source.getPrimaryKeys().keySet().iterator(); i.hasNext(); ) {
                    String j = i.next();
                    DBObject obj = m_source.getPrimaryKeys().get(j);
                    DBObject_PrimaryKey_Table objHeader = (DBObject_PrimaryKey_Table) obj.getHeaders().get(0);
                    if (objHeader.getTable().equalsIgnoreCase(tableName)) {
                        isPkFound = true;
                        // build a list of columns contained in the primary
                        // key
                        v2 = new Vector<Integer>(obj.getContents().keySet());
                        java.util.Collections.sort(v2);
                        for (Iterator<Integer> m = v2.iterator(); m.hasNext(); ) {
                            Integer n = m.next();
                            DBObject_PrimaryKey_Column col = (DBObject_PrimaryKey_Column) obj.getContents().get(n);
                            pkColumns.add(col.getColumn());
                            pkTypes.add(columnTypeMap.get(col.getColumn().toUpperCase()));
                        }
                    }
                }
            }
            // try to find a unique index if no primary key was found
            if (!isPkFound) {
                if (m_source.getUniques() != null) {
                    // matching this table
                    for (Iterator<String> i = m_source.getUniques().keySet().iterator(); i.hasNext(); ) {
                        String j = i.next();
                        DBObject obj = m_source.getUniques().get(j);
                        DBObject_Unique_Table objHeader = (DBObject_Unique_Table) obj.getHeaders().get(0);
                        if (objHeader.getTable().equalsIgnoreCase(tableName)) {
                            // build a list of columns contained in the
                            // unique index
                            v2 = new Vector<Integer>(obj.getContents().keySet());
                            java.util.Collections.sort(v2);
                            for (Iterator<Integer> m = v2.iterator(); m.hasNext(); ) {
                                Integer n = m.next();
                                DBObject_Unique_Column col = (DBObject_Unique_Column) obj.getContents().get(n);
                                pkColumns.add(col.getColumn());
                                pkTypes.add(columnTypeMap.get(col.getColumn().toUpperCase()));
                            }
                        }
                    }
                }
            }
            // remember savepoint for rollback
            Savepoint sp = m_target.setSavepoint(tableName);
            // All indexes have been dropped, so each search involves a full
            // table scan.
            // If we check whether a record already exists only after
            // inserting other records,
            // the lookup would incrementally take longer after each
            // iteration.
            // Therefore, we first go through all source records and
            // remember those which already exist.
            // iterate through data records in source and check for existing
            // records in target
            // (only needed if this is an upgrade)
            ArrayList<String> existingRecords = new ArrayList<String>();
            if (isUpgrade()) {
                String targetSqlCheckExists = s_dbEngine.sql_selectPreparedStatement(targetVendor, targetCatalog, targetSchema, tableName, pkColumns);
                PreparedStatementWrapper targetStmtCheckExists = m_target.setPreparedStatement(targetSqlCheckExists);
                Statement sourceStmt = m_source.setStatement(true);
                String sourceSql = s_dbEngine.sql_select(sourceVendor, sourceCatalog, sourceSchema, tableName);
                ResultSet sourceRs = m_source.executeQuery(sourceStmt, sourceSql);
                while (m_source.getResultSetNext(sourceRs)) {
                    // load primary key values
                    StringBuffer pksb = new StringBuffer();
                    for (int i = 0; i < pkColumns.size(); i++) {
                        String colName = pkColumns.get(i);
                        int colType = pkTypes.get(i);
                        String colValue = m_source.getResultSetString(sourceRs, colName);
                        pksb.append(colValue).append("-");
                        int colIndex = i + 1;
                        if (colType >= s_dbEngine.CLOB && colType <= s_dbEngine.NCLOB) {
                            m_target.setPreparedStatementClob(targetStmtCheckExists, colIndex, m_source.getResultSetClob(sourceRs, colName));
                        } else if (colType >= s_dbEngine.BINTYPE_START && colType <= s_dbEngine.BINTYPE_END) {
                            m_target.setPreparedStatementBytes(targetStmtCheckExists, colIndex, m_source.getResultSetBytes(sourceRs, colName));
                        } else {
                            m_target.setPreparedStatementObject(targetStmtCheckExists, colIndex, m_source.getResultSetObject(sourceRs, colName));
                        }
                    }
                    String pkStringIdentifier = pksb.toString();
                    // find out if record already exists in target
                    if (pkColumns.size() > 0) {
                        ResultSet targetRs = m_target.executeQuery(targetStmtCheckExists);
                        if (m_target.getResultSetNext(targetRs)) {
                            if (!existingRecords.contains(pkStringIdentifier))
                                existingRecords.add(pkStringIdentifier);
                        }
                        m_target.releaseResultSet(targetRs);
                    }
                }
                m_source.releaseResultSet(sourceRs);
                m_source.releaseStatement(sourceStmt);
                m_target.releasePreparedStatement(targetStmtCheckExists);
            }
            // iterate through data records in source and insert or update
            // them in target
            PreparedStatementWrapper targetStmtUpdateRecord = m_target.setPreparedStatement(s_dbEngine.sql_updatePreparedStatement(targetVendor, targetCatalog, targetSchema, tableName, updateColumnNames, pkColumns));
            PreparedStatementWrapper targetStmtInsertRecord = m_target.setPreparedStatement(s_dbEngine.sql_insertPreparedStatement(targetVendor, targetCatalog, targetSchema, tableName, insertColumnNames));
            Statement sourceStmt = m_source.setStatement(true);
            String sourceSql = s_dbEngine.sql_select(sourceVendor, sourceCatalog, sourceSchema, tableName);
            ResultSet sourceRs = m_source.executeQuery(sourceStmt, sourceSql);
            while (m_source.getResultSetNext(sourceRs)) {
                // load primary key values
                StringBuffer pksb = new StringBuffer();
                for (int i = 0; i < pkColumns.size(); i++) {
                    String colName = pkColumns.get(i);
                    int colType = pkTypes.get(i);
                    String colValue = m_source.getResultSetString(sourceRs, colName);
                    pksb.append(colValue).append("-");
                    int colIndex = updateColumnNames.size() + i + 1;
                    if (colType >= s_dbEngine.CLOB && colType <= s_dbEngine.NCLOB) {
                        m_target.setPreparedStatementClob(targetStmtUpdateRecord, colIndex, m_source.getResultSetClob(sourceRs, colName));
                    } else if (colType >= s_dbEngine.BINTYPE_START && colType <= s_dbEngine.BINTYPE_END) {
                        m_target.setPreparedStatementBytes(targetStmtUpdateRecord, colIndex, m_source.getResultSetBytes(sourceRs, colName));
                    } else {
                        m_target.setPreparedStatementObject(targetStmtUpdateRecord, colIndex, m_source.getResultSetObject(sourceRs, colName));
                    }
                }
                String pkStringIdentifier = pksb.toString();
                // update existing record or insert new record into target
                if (existingRecords.contains(pkStringIdentifier)) {
                    // record with same PK already exists in target, update
                    // it
                    // (but preserve system language settings)
                    boolean processThis = true;
                    if (tableName.equalsIgnoreCase("AD_Language")) {
                        // extract language from primary key identifier
                        String currentLanguage = pkStringIdentifier.substring(0, 5);
                        // check if language is marked as system language
                        if (m_target.getSystemLanguages().contains(currentLanguage)) {
                            processThis = false;
                        }
                    }
                    if (processThis) {
                        // set column values from source record
                        for (int i = 0; i < updateColumnNames.size(); i++) {
                            String colName = updateColumnNames.get(i);
                            int colType = updateColumnTypes.get(i);
                            int colIndex = i + 1;
                            // copy values from source to target
                            if (colType >= s_dbEngine.CLOB && colType <= s_dbEngine.NCLOB) {
                                m_target.setPreparedStatementClob(targetStmtUpdateRecord, colIndex, m_source.getResultSetClob(sourceRs, colName));
                            } else if (colType >= s_dbEngine.BINTYPE_START && colType <= s_dbEngine.BINTYPE_END) {
                                m_target.setPreparedStatementBytes(targetStmtUpdateRecord, colIndex, m_source.getResultSetBytes(sourceRs, colName));
                            } else {
                                m_target.setPreparedStatementObject(targetStmtUpdateRecord, colIndex, m_source.getResultSetObject(sourceRs, colName));
                            }
                        }
                        Integer sqlResult = m_target.executeUpdate(targetStmtUpdateRecord, false);
                        if (sqlResult != null) {
                            if (pkStringIdentifier.endsWith("-"))
                                pkStringIdentifier = pkStringIdentifier.substring(0, pkStringIdentifier.length() - 1);
                            logUpdateDetail(sqlResult, new StringBuffer("(").append(tableName).append(": ").append(pkStringIdentifier).append(")").toString());
                            m_counterUpd = new Integer(m_counterUpd.intValue() + 1);
                        }
                        m_totalUpd = new Integer(m_totalUpd.intValue() + 1);
                    }
                } else {
                    // set column values from source record
                    for (int i = 0; i < insertColumnNames.size(); i++) {
                        String colName = insertColumnNames.get(i);
                        int colType = insertColumnTypes.get(i);
                        int colIndex = i + 1;
                        if (colType >= s_dbEngine.CLOB && colType <= s_dbEngine.NCLOB) {
                            m_target.setPreparedStatementClob(targetStmtInsertRecord, colIndex, m_source.getResultSetClob(sourceRs, colName));
                        } else if (colType >= s_dbEngine.BINTYPE_START && colType <= s_dbEngine.BINTYPE_END) {
                            m_target.setPreparedStatementBytes(targetStmtInsertRecord, colIndex, m_source.getResultSetBytes(sourceRs, colName));
                        } else {
                            m_target.setPreparedStatementObject(targetStmtInsertRecord, colIndex, m_source.getResultSetObject(sourceRs, colName));
                        }
                    }
                    Integer sqlResult = m_target.executeUpdate(targetStmtInsertRecord, false);
                    if (sqlResult != null) {
                        if (pkStringIdentifier.endsWith("-"))
                            pkStringIdentifier = pkStringIdentifier.substring(0, pkStringIdentifier.length() - 1);
                        logAddDetail(sqlResult, new StringBuffer("(").append(tableName).append(": ").append(pkStringIdentifier).append(")").toString());
                        m_counterAdd = new Integer(m_counterAdd.intValue() + 1);
                    }
                    m_totalAdd = new Integer(m_totalAdd.intValue() + 1);
                }
            }
            m_source.releaseResultSet(sourceRs);
            m_source.releaseStatement(sourceStmt);
            m_target.releasePreparedStatement(targetStmtUpdateRecord);
            m_target.releasePreparedStatement(targetStmtInsertRecord);
            // release savepoint
            m_target.releaseSavepoint(sp);
        }
    }
    logResults();
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Savepoint(java.sql.Savepoint) ResultSet(java.sql.ResultSet) Vector(java.util.Vector) Statement(java.sql.Statement) Savepoint(java.sql.Savepoint)

Example 94 with Savepoint

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

the class Migrate method purgeOrphans.

/**
	 * remove orphaned data from target
	 */
private void purgeOrphans() {
    // 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, "purgeOrphans", new Object[] { m_objectTypes, m_direction });
    // reset counters
    m_counterPrg = new Integer(0);
    m_totalPrg = new Integer(0);
    // remember savepoint for rollback
    Savepoint sp = m_target.setSavepoint("purge orphans");
    // first iterate through all source tables
    Vector<String> v = new Vector<String>(m_sourceMap.keySet());
    java.util.Collections.sort(v);
    for (Iterator<String> it = v.iterator(); it.hasNext(); ) {
        String key = it.next();
        DBObject obj = m_sourceMap.get(key);
        purgeOrphan(obj, false);
    }
    // then iterate through target 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);
        if (obj.getCustomizationLevel() > s_parameters.CUSTOMNONE)
            purgeOrphan(obj, true);
    }
    // release savepoint
    m_target.releaseSavepoint(sp);
    logResults();
    // reconnect to source
    m_source.reconnectSource();
}
Also used : Savepoint(java.sql.Savepoint) Vector(java.util.Vector)

Example 95 with Savepoint

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

the class Migrate method cleanupCustomizations.

/**
	 * re-apply customizations
	 */
private void cleanupCustomizations() {
    // only continue if we have required tables
    if (!m_source.isObjectExists("AD_ChangeLog", 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_Reference", m_source.getTables()))
        return;
    // reset DB objects
    resetDBObjects(null);
    m_objectType = s_logger.localizeMessage("customization");
    m_objectTypes = s_logger.localizeMessage("customizations");
    m_counterUpd = new Integer(0);
    m_totalUpd = new Integer(0);
    s_logger.log(Level.CONFIG, "");
    s_logger.log(Level.CONFIG, "cleanupCustomizations", new Object[] { m_objectTypes, 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("reapply customizations");
    // load customizations
    Statement stmtLoadCustomizations = m_target.setStatement();
    ResultSet rsLoadCustomizations = m_target.executeQuery(stmtLoadCustomizations, s_dbEngine.sqlAD_getCustomizationChangeLogs(vendor, catalog, schema));
    while (m_target.getResultSetNext(rsLoadCustomizations)) {
        String tableName = m_target.getResultSetString(rsLoadCustomizations, "TABLENAME");
        int recordID = m_target.getResultSetInt(rsLoadCustomizations, "RECORDID");
        String columnName = m_target.getResultSetString(rsLoadCustomizations, "COLUMNNAME");
        String newValue = m_target.getResultSetString(rsLoadCustomizations, "NEWVALUE");
        String displayType = m_target.getResultSetString(rsLoadCustomizations, "DISPLAYTYPE");
        // null
        if (newValue == null || newValue.length() == 0 || newValue.equalsIgnoreCase("NULL")) {
            newValue = null;
        } else // boolean
        if (displayType.equalsIgnoreCase("YES-NO")) {
            if (newValue.equalsIgnoreCase("true"))
                newValue = "Y";
            else
                newValue = "N";
        }
        // get data type
        int dataType = 0;
        DBObject table = m_source.getObjectByName(tableName, m_source.getTables());
        String checkVendor = m_source.getVendor();
        // target
        if (table == null) {
            table = m_target.getObjectByName(tableName, m_target.getTables());
            checkVendor = m_target.getVendor();
            // ignored
            if (table != null && table.getCustomizationLevel() == s_parameters.CUSTOMNONE)
                table = null;
        }
        if (table != null) {
            HashMap<Integer, DBObjectDefinition> columns = table.getContents();
            for (Iterator<Integer> it = columns.keySet().iterator(); it.hasNext(); ) {
                int key = it.next();
                DBObject_Table_Column column = (DBObject_Table_Column) columns.get(key);
                if (column.getName().equalsIgnoreCase(columnName)) {
                    dataType = s_dbEngine.getDataTypeID(checkVendor, column.getType());
                    break;
                }
            }
        }
        // (if we do not, it means the table or column no longer exists)
        if (dataType != 0) {
            // column name as array
            ArrayList<String> columnNames = new ArrayList<String>();
            columnNames.add(columnName);
            // where condition as array
            ArrayList<String> whereColumnNames = new ArrayList<String>();
            String whereColumnName = new StringBuffer(tableName).append("_ID").toString();
            if (tableName.equalsIgnoreCase("AD_Ref_Table"))
                whereColumnName = "AD_Reference_ID";
            whereColumnNames.add(whereColumnName);
            // customize record in database
            PreparedStatementWrapper stmtReapplyCustomization = m_target.setPreparedStatement(s_dbEngine.sql_updatePreparedStatement(vendor, catalog, schema, tableName, columnNames, whereColumnNames));
            // set value depending on data type
            if (dataType >= s_dbEngine.DATETYPE_START && dataType <= s_dbEngine.TIMESTAMPTYPE_END) {
                // dates and times
                if (newValue != null)
                    m_target.setPreparedStatementTimestamp(stmtReapplyCustomization, 1, java.sql.Timestamp.valueOf(newValue));
                else
                    m_target.setPreparedStatementNull(stmtReapplyCustomization, 1, java.sql.Types.TIMESTAMP);
            } else if (dataType < s_dbEngine.CHARTYPE_START) {
                // numbers
                if (newValue != null)
                    m_target.setPreparedStatementBigDecimal(stmtReapplyCustomization, 1, new BigDecimal(newValue));
                else
                    m_target.setPreparedStatementNull(stmtReapplyCustomization, 1, java.sql.Types.NUMERIC);
            } else {
                // treat everything else as String
                if (newValue != null)
                    m_target.setPreparedStatementString(stmtReapplyCustomization, 1, newValue);
                else
                    m_target.setPreparedStatementNull(stmtReapplyCustomization, 1, java.sql.Types.VARCHAR);
            }
            // set WHERE clause to record to customize
            m_target.setPreparedStatementInt(stmtReapplyCustomization, 2, recordID);
            // execute the update
            Integer sqlResult = m_target.executeUpdate(stmtReapplyCustomization, false);
            if (sqlResult != null) {
                logUpdateDetail(sqlResult, null);
                m_counterUpd = new Integer(m_counterUpd.intValue() + 1);
            }
            // release prepared statement
            m_target.releasePreparedStatement(stmtReapplyCustomization);
        }
        // increment total counter
        // counts all active change logs marked as customizations
        // also those for which the target table no longer exists
        m_totalUpd = new Integer(m_totalUpd.intValue() + 1);
    }
    // release customization result set
    m_target.releaseResultSet(rsLoadCustomizations);
    m_target.releaseStatement(stmtLoadCustomizations);
    // 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)

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