Search in sources :

Example 41 with DBAttribute

use of com.cubrid.common.core.common.model.DBAttribute in project cubrid-manager by CUBRID.

the class DataCompareEditorPart method compareHashedCompareData.

private void compareHashedCompareData(Connection conn, DataCompare dataCompare, List<HashedCompareData> dataList) {
    // FIXME logic code move to core module
    if (dataList == null || dataList.size() == 0) {
        // TODO error
        return;
    }
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    SchemaInfo schemaInfo = dataCompare.getSchemaInfo();
    StringBuilder extraColumns = new StringBuilder();
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT MD5(CONCAT(");
    StringBuilder cols = new StringBuilder();
    List<DBAttribute> attrs = schemaInfo.getAttributes();
    // TODO Collections.sort
    for (int i = 0, len = attrs.size(); i < len; i++) {
        DBAttribute attr = attrs.get(i);
        if (cols.length() > 0) {
            cols.append(",");
        }
        makeColumnsClause(extraColumns, cols, attr);
    }
    sql.append(cols);
    sql.append(")) AS _record_hash_ ");
    if (extraColumns.length() > 0) {
        sql.append(",");
        sql.append(extraColumns);
    }
    String escapedTableName = QuerySyntax.escapeKeyword(schemaInfo.getClassname());
    sql.append(" FROM ").append(escapedTableName);
    sql.append(" WHERE ");
    {
        HashedCompareData data = dataList.get(0);
        for (int i = 0, len = data.getPkColumns().size(); i < len; i++) {
            if (i > 0) {
                sql.append(" AND ");
            }
            String columnName = data.getPkColumns().get(i);
            sql.append(QuerySyntax.escapeKeyword(columnName)).append("=?");
        }
    }
    for (HashedCompareData data : dataList) {
        if (runningState != RUNNING_SATE_ONLINE) {
            return;
        }
        boolean exists = false;
        String hash = null;
        try {
            pstmt = conn.prepareStatement(sql.toString());
            for (int i = 0, len = data.getPkColumns().size(); i < len; i++) {
                String columnValue = data.getPkValues().get(i);
                pstmt.setString(i + 1, columnValue);
            }
            rs = pstmt.executeQuery();
            if (!rs.next()) {
                exists = false;
            } else {
                exists = true;
                hash = rs.getString("_record_hash_");
            }
        } catch (SQLException e) {
            exists = false;
            printToConsoleOnWorkThread(StringUtil.NEWLINE, false);
            printToConsoleOnWorkThread(e.getMessage(), true);
            LOGGER.error(sql.toString(), e);
        } finally {
            QueryUtil.freeQuery(pstmt, rs);
        }
        dataCompare.increaseProgress();
        if (!exists) {
            dataCompare.increaseNotExists();
            addLog(schemaInfo.getClassname(), data, charset);
        } else {
            if (data.getHash().equals(hash)) {
                dataCompare.increaseMatches();
            } else {
                dataCompare.increaseNotMatches();
                addLog(schemaInfo.getClassname(), data, charset);
            }
        }
        completedRecords++;
        refreshProgressBar();
        Display.getDefault().syncExec(new Runnable() {

            public void run() {
                compareTableViewer.refresh();
            }
        });
    }
}
Also used : SQLException(java.sql.SQLException) DBAttribute(com.cubrid.common.core.common.model.DBAttribute) ResultSet(java.sql.ResultSet) HashedCompareData(com.cubrid.common.ui.compare.data.model.HashedCompareData) PreparedStatement(java.sql.PreparedStatement) Constraint(com.cubrid.common.core.common.model.Constraint) SchemaInfo(com.cubrid.common.core.common.model.SchemaInfo)

Example 42 with DBAttribute

use of com.cubrid.common.core.common.model.DBAttribute in project cubrid-manager by CUBRID.

the class DataCompareEditorPart method fetchHashedCompareData.

private List<HashedCompareData> fetchHashedCompareData(Connection conn, SchemaInfo schemaInfo, long start, int rows) {
    // FIXME logic code move to core module
    Statement stmt = null;
    ResultSet rs = null;
    StringBuilder pkColumns = new StringBuilder();
    Constraint constraint = schemaInfo.getPK();
    if (constraint != null) {
        for (String column : constraint.getAttributes()) {
            if (pkColumns.length() > 0) {
                pkColumns.append(",");
            }
            pkColumns.append(QuerySyntax.escapeKeyword(column));
        }
    }
    StringBuilder extraColumns = new StringBuilder();
    StringBuilder sql = new StringBuilder();
    sql.append(" SELECT ").append(pkColumns).append(", ");
    sql.append(" MD5(CONCAT(");
    StringBuilder cols = new StringBuilder();
    List<DBAttribute> attrs = schemaInfo.getAttributes();
    // TODO Collections.sort
    for (int i = 0, len = attrs.size(); i < len; i++) {
        DBAttribute attr = attrs.get(i);
        if (cols.length() > 0) {
            cols.append(",");
        }
        makeColumnsClause(extraColumns, cols, attr);
    }
    sql.append(cols);
    sql.append(")) AS _record_hash_ ");
    if (extraColumns.length() > 0) {
        sql.append(",");
        sql.append(extraColumns);
    }
    String escapedTableName = QuerySyntax.escapeKeyword(schemaInfo.getClassname());
    sql.append(" FROM ").append(escapedTableName);
    sql.append(" ORDER BY ").append(pkColumns);
    sql.append(" FOR ORDERBY_NUM() BETWEEN ").append(start + 1);
    sql.append(" AND ").append(start + rows);
    List<HashedCompareData> result = new ArrayList<HashedCompareData>();
    try {
        StringBuilder extra = new StringBuilder();
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql.toString());
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            String hash = null;
            boolean isPk = true;
            extra.delete(0, extra.length());
            List<String> pkColumnList = new ArrayList<String>();
            List<String> pkValueList = new ArrayList<String>();
            List<String> pkTypeList = new ArrayList<String>();
            for (int j = 1, len = meta.getColumnCount(); j <= len; j++) {
                String columnName = meta.getColumnName(j);
                String columnType = DataType.isNumberType(meta.getColumnTypeName(j)) ? HashedCompareData.NUMBER_TYPE : HashedCompareData.STRING_TYPE;
                if (columnName.equalsIgnoreCase("_record_hash_")) {
                    isPk = false;
                    hash = rs.getString(j);
                } else if (isPk) {
                    pkColumnList.add(columnName);
                    pkValueList.add(rs.getString(j));
                    pkTypeList.add(columnType);
                } else {
                    String val = null;
                    if (DataType.isSetDataType(meta.getColumnTypeName(j))) {
                        String colType = FieldHandlerUtils.amendDataTypeByResult(rs, j, meta.getColumnTypeName(j));
                        val = (String) FieldHandlerUtils.getRsValueForExport(colType, (CUBRIDResultSetProxy) rs, j, "{NULL}");
                    } else {
                        val = rs.getString(j);
                    }
                    if (val == null) {
                        val = "{NULL}";
                    }
                    extra.append(val);
                }
            }
            HashedCompareData data = new HashedCompareData(pkColumnList, pkValueList, pkTypeList, hash);
            result.add(data);
        }
    } catch (Exception e) {
        printToConsoleOnWorkThread(StringUtil.NEWLINE, false);
        printToConsoleOnWorkThread(e.getMessage(), true);
        LOGGER.error(sql.toString(), e);
    } finally {
        QueryUtil.freeQuery(stmt, rs);
    }
    return result;
}
Also used : CUBRIDResultSetProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetProxy) Constraint(com.cubrid.common.core.common.model.Constraint) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) Constraint(com.cubrid.common.core.common.model.Constraint) PartInitException(org.eclipse.ui.PartInitException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ResultSetMetaData(java.sql.ResultSetMetaData) DBAttribute(com.cubrid.common.core.common.model.DBAttribute) ResultSet(java.sql.ResultSet) HashedCompareData(com.cubrid.common.ui.compare.data.model.HashedCompareData)

Example 43 with DBAttribute

use of com.cubrid.common.core.common.model.DBAttribute in project cubrid-manager by CUBRID.

the class GetSchemaDDLTask method execute.

/**
	 * Execute the tasks
	 */
public void execute() {
    try {
        if (CompatibleUtil.isAfter900(databaseInfo)) {
            String sql = QueryUtil.getShowCreateSQL(schemaName, isTable);
            sql = DatabaseInfo.wrapShardQuery(databaseInfo, sql);
            StringBuilder sb = new StringBuilder();
            if (errorMsg != null && errorMsg.trim().length() > 0) {
                return;
            }
            if (connection == null || connection.isClosed()) {
                errorMsg = Messages.error_getConnection;
                return;
            }
            String viewName = null;
            stmt = connection.createStatement();
            rs = (CUBRIDResultSetProxy) stmt.executeQuery(sql);
            while (rs.next()) {
                if (isTable) {
                    sb.append(rs.getString(2));
                } else {
                    viewName = QuerySyntax.escapeKeyword(rs.getString(1));
                    if (sb.length() > 0) {
                        sb.append(" UNION ALL ");
                    }
                    sb.append(" ").append(rs.getString(2)).append(" ");
                }
            }
            if (isTable) {
                ddl = sb.toString();
            } else {
                ddl = "CREATE OR REPLACE VIEW " + viewName + " AS " + sb.toString() + ";";
            }
        } else {
            StringBuilder sqlScript = new StringBuilder();
            if (!isTable) {
                // Get class info
                GetAllClassListTask getAllClassListTask = new GetAllClassListTask(databaseInfo, connection);
                getAllClassListTask.setTableName(schemaName);
                getAllClassListTask.getClassInfoTaskExcute();
                // If failed
                if (getAllClassListTask.getErrorMsg() != null || getAllClassListTask.isCancel()) {
                    errorMsg = getAllClassListTask.getErrorMsg();
                    LOGGER.error(errorMsg);
                    return;
                }
                /*Check user cancel*/
                if (monitor != null && monitor.isCanceled()) {
                    errorMsg = "The user canceled.";
                    return;
                }
                ClassInfo classInfo = getAllClassListTask.getClassInfo();
                // Get view column
                GetViewAllColumnsTask getAllDBVclassTask = new GetViewAllColumnsTask(databaseInfo, connection);
                getAllDBVclassTask.setClassName(schemaName);
                getAllDBVclassTask.getAllVclassListTaskExcute();
                // If failed
                if (getAllDBVclassTask.getErrorMsg() != null || getAllDBVclassTask.isCancel()) {
                    errorMsg = getAllDBVclassTask.getErrorMsg();
                    LOGGER.error(errorMsg);
                    return;
                }
                /*Check user cancel*/
                if (monitor != null && monitor.isCanceled()) {
                    errorMsg = "The user canceled.";
                    return;
                }
                // Get query list
                List<String> vclassList = getAllDBVclassTask.getAllVclassList();
                List<Map<String, String>> queryListData = new ArrayList<Map<String, String>>();
                for (String sql : vclassList) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("0", sql);
                    queryListData.add(map);
                }
                /*Check user cancel*/
                if (monitor != null && monitor.isCanceled()) {
                    errorMsg = "The user canceled.";
                    return;
                }
                // Get all attribute
                GetAllAttrTask getAllAttrTask = new GetAllAttrTask(databaseInfo, connection);
                getAllAttrTask.setClassName(schemaName);
                getAllAttrTask.getAttrList();
                // If failed
                if (getAllAttrTask.getErrorMsg() != null) {
                    errorMsg = getAllAttrTask.getErrorMsg();
                    LOGGER.error(errorMsg);
                    return;
                }
                List<DBAttribute> attrList = getAllAttrTask.getAllAttrList();
                List<Map<String, String>> viewColListData = GetInfoDataUtil.getViewColMapList(attrList);
                sqlScript.append(GetInfoDataUtil.getViewCreateSQLScript(false, databaseInfo, classInfo, schemaName, viewColListData, queryListData));
            } else {
                String ddl = SQLGenerateUtils.getCreateSQL(databaseInfo, schemaName);
                sqlScript.append(ddl == null ? "" : ddl);
            }
            ddl = sqlScript.toString();
        }
    } catch (SQLException e) {
        LOGGER.error(e.getMessage(), e);
        errorMsg = e.getMessage();
    } finally {
        finish();
        if (StringUtil.isNotEmpty(ddl)) {
            SqlFormattingStrategy formator = new SqlFormattingStrategy();
            String formated = formator.format(ddl);
            ddl = formated;
        }
    }
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) SqlFormattingStrategy(com.cubrid.common.ui.query.format.SqlFormattingStrategy) GetAllClassListTask(com.cubrid.cubridmanager.core.cubrid.table.task.GetAllClassListTask) GetViewAllColumnsTask(com.cubrid.cubridmanager.core.cubrid.table.task.GetViewAllColumnsTask) DBAttribute(com.cubrid.common.core.common.model.DBAttribute) HashMap(java.util.HashMap) Map(java.util.Map) ClassInfo(com.cubrid.cubridmanager.core.cubrid.table.model.ClassInfo) GetAllAttrTask(com.cubrid.cubridmanager.core.cubrid.table.task.GetAllAttrTask)

Example 44 with DBAttribute

use of com.cubrid.common.core.common.model.DBAttribute in project cubrid-manager by CUBRID.

the class MakeSelectQueryAction method getStmtSQL.

/**
	 * Create select statement SQL
	 *
	 * @param schemaNode DefaultSchemaNode
	 * @return String
	 */
protected String getStmtSQL(DefaultSchemaNode schemaNode, IEditorPart editorPart) {
    // FIXME move this logic to core module
    String sql = "";
    if (schemaNode != null) {
        CubridDatabase db = schemaNode.getDatabase();
        if (db == null) {
            return sql;
        }
        DatabaseInfo dbInfo = db.getDatabaseInfo();
        if (dbInfo == null) {
            return sql;
        }
        GetAllAttrTask task = new GetAllAttrTask(dbInfo);
        task.setClassName(schemaNode.getName());
        task.getAttrList();
        if (task.getErrorMsg() != null) {
            return sql;
        }
        List<DBAttribute> allAttrList = task.getAllAttrList();
        sql = SQLGenerateUtils.getSelectSQLNoWhere(schemaNode.getName(), allAttrList, true);
        sql = wrapShardSQL(schemaNode, editorPart, sql);
    }
    try {
        return new SqlFormattingStrategy().format(sql).trim();
    } catch (Exception ignored) {
        return sql;
    }
}
Also used : DatabaseInfo(com.cubrid.cubridmanager.core.cubrid.database.model.DatabaseInfo) DBAttribute(com.cubrid.common.core.common.model.DBAttribute) CubridDatabase(com.cubrid.common.ui.spi.model.CubridDatabase) SqlFormattingStrategy(com.cubrid.common.ui.query.format.SqlFormattingStrategy) GetAllAttrTask(com.cubrid.cubridmanager.core.cubrid.table.task.GetAllAttrTask)

Example 45 with DBAttribute

use of com.cubrid.common.core.common.model.DBAttribute in project cubrid-manager by CUBRID.

the class AttributeTableViewerContentProvider method getElements.

/**
	 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
	 * @param inputElement the input element
	 * @return the array of elements to display in the viewer
	 */
public Object[] getElements(Object inputElement) {
    if (inputElement instanceof SchemaInfo) {
        SchemaInfo schema = (SchemaInfo) inputElement;
        List<DBAttribute> list = new ArrayList<DBAttribute>();
        if (showClassAttribute) {
            list.addAll(schema.getClassAttributes());
        }
        list.addAll(schema.getAttributes());
        return list.toArray();
    } else {
        return new Object[0];
    }
}
Also used : DBAttribute(com.cubrid.common.core.common.model.DBAttribute) ArrayList(java.util.ArrayList) SchemaInfo(com.cubrid.common.core.common.model.SchemaInfo)

Aggregations

DBAttribute (com.cubrid.common.core.common.model.DBAttribute)130 SchemaInfo (com.cubrid.common.core.common.model.SchemaInfo)57 Constraint (com.cubrid.common.core.common.model.Constraint)53 ArrayList (java.util.ArrayList)46 HashMap (java.util.HashMap)16 List (java.util.List)15 SerialInfo (com.cubrid.common.core.common.model.SerialInfo)14 TableItem (org.eclipse.swt.widgets.TableItem)13 ERTableColumn (com.cubrid.common.ui.er.model.ERTableColumn)11 CubridDatabase (com.cubrid.common.ui.spi.model.CubridDatabase)11 GetAllAttrTask (com.cubrid.cubridmanager.core.cubrid.table.task.GetAllAttrTask)10 SchemaComment (com.cubrid.common.core.schemacomment.model.SchemaComment)8 Map (java.util.Map)8 Point (org.eclipse.swt.graphics.Point)8 DatabaseInfo (com.cubrid.cubridmanager.core.cubrid.database.model.DatabaseInfo)7 SQLException (java.sql.SQLException)7 PreparedStatement (java.sql.PreparedStatement)6 DBResolution (com.cubrid.common.core.common.model.DBResolution)5 PartitionInfo (com.cubrid.common.core.common.model.PartitionInfo)5 SqlFormattingStrategy (com.cubrid.common.ui.query.format.SqlFormattingStrategy)5