Search in sources :

Example 1 with ParamSetException

use of com.cubrid.common.ui.spi.util.paramSetter.ParamSetException in project cubrid-manager by CUBRID.

the class QueryExecuter method updateValues.

/**
	 * Update values on the query result editor.
	 *
	 * @param queryConn Connection
	 * @return
	 * @throws SQLException
	 * @throws ParamSetException
	 */
private Map<String, Map<String, CellValue>> updateValues() throws SQLException, ParamSetException {
    Map<String, Map<String, CellValue>> successedMap = new HashMap<String, Map<String, CellValue>>();
    ParamSetter paramSetter = new ParamSetter();
    if (oldValues == null || oldValues.size() == 0) {
        return successedMap;
    }
    if (newValues == null || newValues.size() == 0) {
        return successedMap;
    }
    Connection conn = connection.checkAndConnect();
    try {
        String tableName = UIQueryUtil.getTableNameFromQuery(conn, query);
        String escapedTable = QuerySyntax.escapeKeyword(tableName);
        if (tableName == null) {
            CommonUITool.openErrorBox(Messages.errModifiedOneTable);
            return successedMap;
        }
        List<ColumnInfo> colInfoList = getAllColumnList();
        PreparedStatement pstmt = null;
        for (String key : oldValues.keySet()) {
            try {
                Map<String, CellValue> oldValueMap = oldValues.get(key);
                Map<String, CellValue> newValueMap = newValues.get(key);
                if (oldValueMap == null || oldValueMap.size() == 0 || newValueMap == null || newValueMap.size() == 0) {
                    continue;
                }
                StringBuilder updateSQLBuffer = new StringBuilder();
                List<ColumnInfo> updatedColInfoList = new ArrayList<ColumnInfo>();
                List<CellValue> newValueList = new ArrayList<CellValue>();
                for (int i = 0; i < colInfoList.size(); i++) {
                    ColumnInfo colInfo = colInfoList.get(i);
                    CellValue newValue = newValueMap.get(colInfo.getIndex());
                    CellValue oldValue = oldValueMap.get(colInfo.getIndex());
                    if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null)) {
                        newValueList.add(newValue);
                        updatedColInfoList.add(colInfo);
                    } else if (oldValue != null && newValue != null && !oldValue.equals(newValue)) {
                        newValueList.add(newValue);
                        updatedColInfoList.add(colInfo);
                    }
                }
                if (updatedColInfoList.isEmpty()) {
                    continue;
                }
                updateSQLBuffer.append("UPDATE ").append(escapedTable).append(" SET ");
                StringBuilder setSQLBf = new StringBuilder();
                List<PstmtParameter> pstmtParaList = new ArrayList<PstmtParameter>();
                int valueParamIndex = 1;
                for (int i = 0; i < updatedColInfoList.size(); i++) {
                    ColumnInfo colInfo = updatedColInfoList.get(i);
                    CellValue newValue = newValueMap.get(colInfo.getIndex());
                    String colName = colInfo.getName();
                    if (queryEditor.isIgnoreType(colInfo.getType())) {
                        continue;
                    }
                    if (setSQLBf.length() > 0) {
                        setSQLBf.append(", ");
                    }
                    CellValue cellValue = newValueMap.get(colInfo.getIndex());
                    if (DataType.DATATYPE_NATIONAL_CHARACTER.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_NCHAR_VARYING.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_NCHAR.equalsIgnoreCase(colInfo.getType())) {
                        String dataType = DataType.makeType(colInfo.getType(), colInfo.getChildElementType(), colInfo.getPrecision(), colInfo.getScale());
                        String charset = getDatabaseInfo() != null ? getDatabaseInfo().getCharSet() : null;
                        FormatDataResult result = DBAttrTypeFormatter.format(dataType, cellValue.getStringValue(), null, false, charset, false);
                        if (result.isSuccess()) {
                            setSQLBf.append(QuerySyntax.escapeKeyword(colName));
                            setSQLBf.append(" = ").append(result.getFormatedString());
                        } else {
                            throw new ParamSetException("Format data \"" + cellValue.getStringValue() + "\"error for data type " + dataType);
                        }
                    } else if ((DataType.DATATYPE_BIT.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_BIT_VARYING.equalsIgnoreCase(colInfo.getType())) && newValue.getValue() instanceof String) {
                        String dataType = DataType.makeType(colInfo.getType(), colInfo.getChildElementType(), colInfo.getPrecision(), colInfo.getScale());
                        String charset = getDatabaseInfo() != null ? getDatabaseInfo().getCharSet() : null;
                        FormatDataResult result = DBAttrTypeFormatter.format(dataType, cellValue.getStringValue(), null, false, charset, false);
                        setSQLBf.append(QuerySyntax.escapeKeyword(colName));
                        setSQLBf.append(" = ").append(result.getFormatedString());
                    } else {
                        setSQLBf.append(QuerySyntax.escapeKeyword(colName)).append(" = ?");
                        PstmtParameter pstmtParameter = new PstmtParameter(colInfo.getName(), valueParamIndex++, colInfo.getComleteType(), cellValue.getValue());
                        pstmtParaList.add(pstmtParameter);
                    }
                }
                if (setSQLBf.length() < 1) {
                    continue;
                }
                updateSQLBuffer.append(setSQLBf);
                updateSQLBuffer.append(" WHERE ");
                List<String> pkList = UIQueryUtil.getPkList(getDatabaseInfo(), tableName);
                int pkParamIndex = 0;
                for (int i = 0; i < newValueMap.size(); i++) {
                    ColumnInfo colInfo = ((ColumnInfo) getAllColumnList().get(i));
                    String col = colInfo.getName();
                    if (!pkList.contains(col)) {
                        continue;
                    }
                    if (queryEditor.isIgnoreType(colInfo.getType())) {
                        continue;
                    }
                    if (pkParamIndex > 0) {
                        updateSQLBuffer.append(" AND ");
                    }
                    updateSQLBuffer.append(QuerySyntax.escapeKeyword(col)).append(" = ?");
                    CellValue object = oldValueMap.get(colInfo.getIndex());
                    PstmtParameter pstmtParameter = new PstmtParameter(colInfo.getName(), valueParamIndex++, colInfo.getComleteType(), object.getValue());
                    pstmtParaList.add(pstmtParameter);
                    pkParamIndex++;
                }
                pstmt = conn.prepareStatement(updateSQLBuffer.toString());
                for (PstmtParameter pstmtParameter : pstmtParaList) {
                    paramSetter.handle(pstmt, pstmtParameter);
                }
                pstmt.executeUpdate();
                successedMap.put(key, newValueMap);
                if (!connection.isAutoCommit() && queryEditor.getConnection() == connection) {
                    queryEditor.setHaveActiveTransaction(true);
                }
                for (ColumnInfo colInfo : updatedColInfoList) {
                    CellValue newValue = newValueMap.get(colInfo.getIndex());
                    CellValue oldValue = oldValueMap.get(colInfo.getIndex());
                    if (newValue != null && oldValue != null) {
                        oldValue.setValue(newValue.getValue());
                    }
                }
            } catch (SQLException e) {
                if (successedMap.containsKey(key)) {
                    successedMap.remove(key);
                }
                LOGGER.error("", e);
                logMessageText.setText(e.getLocalizedMessage());
                throw e;
            } finally {
                QueryUtil.freeQuery(pstmt);
            }
        }
    } finally {
        if (connection != null && connection.isAutoClosable()) {
            connection.commit();
            connection.close();
        }
    }
    return successedMap;
}
Also used : HashMap(java.util.HashMap) ParamSetException(com.cubrid.common.ui.spi.util.paramSetter.ParamSetException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) DBConnection(com.cubrid.cubridmanager.core.common.jdbc.DBConnection) ArrayList(java.util.ArrayList) ParamSetter(com.cubrid.common.ui.spi.util.paramSetter.ParamSetter) PreparedStatement(java.sql.PreparedStatement) Point(org.eclipse.swt.graphics.Point) PstmtParameter(com.cubrid.common.ui.cubrid.table.dialog.PstmtParameter) FormatDataResult(com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult) CellValue(com.cubrid.common.ui.spi.table.CellValue) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with ParamSetException

use of com.cubrid.common.ui.spi.util.paramSetter.ParamSetException in project cubrid-manager by CUBRID.

the class QueryResultComposite method makeResult.

/**
	 * make the result contents.
	 * 
	 * @param result QueryExecuter
	 */
private void makeResult(final QueryExecuter result, CTabFolder parentFolder) {
    editor.getCombinedQueryComposite().getRecentlyUsedSQLComposite().refreshRecentlyUsedSQLList();
    //final CTabFolder queryResultTabFolder = ((QueryResultComposite)queryResultTabItem.getControl()).queryResultTabFolder;
    ViewForm viewForm = new ViewForm(parentFolder, SWT.NONE);
    // create the bottom sash
    final SashForm tableLogSash = new SashForm(viewForm, SWT.VERTICAL);
    tableLogSash.SASH_WIDTH = SASH_WIDTH;
    tableLogSash.setBackground(CombinedQueryEditorComposite.BACK_COLOR);
    final Composite resultContainer = new Composite(tableLogSash, SWT.None);
    resultContainer.setLayout(new FormLayout());
    final Table resultTable = new Table(resultContainer, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
    setDropTraget(resultTable);
    resultTable.setHeaderVisible(true);
    resultTable.setLinesVisible(true);
    resultTable.setBackground(BACKGROUND_NORMAL);
    CommonUITool.hackForYosemite(resultTable);
    // display data compare label for multiple queries
    if (this.multiResultsCompare == true) {
        Composite compareButtonComposite = new Composite(resultContainer, SWT.None);
        compareButtonComposite.setLayout(new FillLayout());
        displayDataCompareLabel(compareButtonComposite, resultTable);
        FormData tableData = new FormData();
        tableData.top = new FormAttachment(0, 0);
        tableData.bottom = new FormAttachment(100, -28);
        tableData.left = new FormAttachment(0, 0);
        tableData.right = new FormAttachment(100, 0);
        resultTable.setLayoutData(tableData);
        FormData compareData = new FormData();
        compareData.top = new FormAttachment(100, -28);
        compareData.bottom = new FormAttachment(100, 0);
        compareData.left = new FormAttachment(0, 0);
        compareData.right = new FormAttachment(100, 0);
        compareButtonComposite.setLayoutData(compareData);
    } else {
        FormData tableData = new FormData();
        tableData.top = new FormAttachment(0, 0);
        tableData.bottom = new FormAttachment(100, 0);
        tableData.left = new FormAttachment(0, 0);
        tableData.right = new FormAttachment(100, 0);
        resultTable.setLayoutData(tableData);
    }
    final SashForm logSash = new SashForm(tableLogSash, SWT.HORIZONTAL);
    logSash.SASH_WIDTH = SASH_WIDTH;
    logSash.setBackground(CombinedQueryEditorComposite.BACK_COLOR);
    logSash.setLayoutData(CommonUITool.createGridData(GridData.FILL_BOTH, 1, 1, -1, -1));
    StyledText messagesArea = new StyledText(logSash, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY | SWT.WRAP);
    CommonUITool.registerCopyPasteContextMenu(messagesArea, false, false);
    tableLogSash.setWeights(new int[] { 8, 2 });
    messagesArea.setToolTipText(Messages.tooltipHowToExpandLogPane);
    messagesArea.addFocusListener(new FocusListener() {

        public void focusLost(FocusEvent e) {
            tableLogSash.setWeights(new int[] { 8, 2 });
        }

        public void focusGained(FocusEvent e) {
            tableLogSash.setWeights(new int[] { 2, 8 });
        }
    });
    TableCursor cursor = new TableCursor(resultTable, SWT.NONE);
    TableSelectSupport tableSelectSupport = new TableSelectSupport(resultTable, cursor);
    if (this.multiResultsCompare == true) {
        result.setMultiResultsCompare(true);
        result.setBaseQueryExecuter(this.baseQueryExecuter);
    }
    result.makeResult(tableSelectSupport, messagesArea, isMutliQuery);
    // Auto set column size, maximum is 300px,minimum is 50px
    for (int i = 1; i < resultTable.getColumnCount(); i++) {
        resultTable.getColumns()[i].pack();
        if (resultTable.getColumns()[i].getWidth() > 300) {
            resultTable.getColumns()[i].setWidth(300);
        }
        if (resultTable.getColumns()[i].getWidth() < 50) {
            resultTable.getColumns()[i].setWidth(50);
        }
    }
    // fill the view form action on top right corner
    ToolBar topRightToolBar = new ToolBar(viewForm, SWT.FLAT);
    ToolBarManager toolBarManager = new ToolBarManager(topRightToolBar);
    result.makeActions(toolBarManager, resultTable);
    // fill the view form action on top right corner
    ToolBar topLeftToolBar = new ToolBar(viewForm, SWT.FLAT);
    swRecordItem = new ToolItem(topLeftToolBar, SWT.CHECK);
    result.swRecordItem = swRecordItem;
    swRecordItem.setToolTipText(Messages.getOidOn);
    swRecordItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/query_update.png"));
    swRecordItem.setEnabled(true);
    swRecordItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (editor.isCollectExecStats()) {
                result.swRecordItem.setSelection(false);
                CommonUITool.openErrorBox(getShell(), Messages.errNotEditableOnStat);
                return;
            }
            if (!result.isContainPrimayKey()) {
                result.swRecordItem.setSelection(false);
                CommonUITool.openErrorBox(getShell(), Messages.errNoPrimaryKey);
                return;
            }
            if (!result.isSingleTableQuery()) {
                result.swRecordItem.setSelection(false);
                CommonUITool.openErrorBox(getShell(), Messages.errNotInOneTable);
                return;
            }
            if (!checkConnection()) {
                result.swRecordItem.setSelection(false);
                CommonUITool.openErrorBox(getShell(), Messages.errMsgExecuteInResult);
                return;
            }
            result.tblResult.forceFocus();
            if (result.swRecordItem.getSelection()) {
                result.swRecordItem.setToolTipText(Messages.getOidOn);
                result.setEditMode(true);
                result.insertRecordItem.setEnabled(true);
                if (result.tblResult.getSelectionCount() > 0) {
                    result.delRecordItem.setEnabled(true);
                }
            } else {
                if (result.isModifiedResult()) {
                    result.swRecordItem.setSelection(true);
                    CommonUITool.openErrorBox(getShell(), Messages.errHasNoCommit);
                    return;
                }
                result.swRecordItem.setToolTipText(Messages.getOidOff);
                result.setEditMode(false);
                result.insertRecordItem.setEnabled(false);
                result.delRecordItem.setEnabled(false);
            }
        }
    });
    //added by kevin, for insert record
    insertRecordItem = new ToolItem(topLeftToolBar, SWT.PUSH);
    result.insertRecordItem = insertRecordItem;
    insertRecordItem.setToolTipText(com.cubrid.common.ui.cubrid.table.Messages.insertInstanceMsgTitle);
    insertRecordItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/table_record_insert.png"));
    insertRecordItem.setDisabledImage(CommonUIPlugin.getImage("icons/queryeditor/table_record_insert_disabled.png"));
    insertRecordItem.setEnabled(false);
    insertRecordItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (!result.getEditable()) {
                CommonUITool.openErrorBox(getShell(), Messages.errNotEditable);
                return;
            }
            if (!checkConnection()) {
                CommonUITool.openErrorBox(getShell(), Messages.errMsgExecuteInResult);
                return;
            }
            result.insertSaveItem.setEnabled(result.getEditable());
            result.rollbackModifiedItem.setEnabled(result.getEditable());
            result.addNewItem();
        }
    });
    delRecordItem = new ToolItem(topLeftToolBar, SWT.PUSH);
    result.delRecordItem = delRecordItem;
    delRecordItem.setToolTipText(Messages.delete);
    delRecordItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/table_record_delete.png"));
    delRecordItem.setDisabledImage(CommonUIPlugin.getImage("icons/queryeditor/table_record_delete_disabled.png"));
    delRecordItem.setEnabled(false);
    delRecordItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (!result.getEditable()) {
                CommonUITool.openErrorBox(getShell(), Messages.errNotEditable);
                return;
            }
            if (!checkConnection()) {
                CommonUITool.openErrorBox(getShell(), Messages.errMsgExecuteInResult);
                return;
            }
            result.tblResult.forceFocus();
            result.deleteRecord(result.tblResult, null);
        }
    });
    insertSaveItem = new ToolItem(topLeftToolBar, SWT.PUSH);
    result.insertSaveItem = insertSaveItem;
    insertSaveItem.setToolTipText(Messages.insertCommit);
    insertSaveItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/query_commit.png"));
    insertSaveItem.setDisabledImage(CommonUIPlugin.getImage("icons/queryeditor/query_commit_disabled.png"));
    insertSaveItem.setEnabled(false);
    insertSaveItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (!checkConnection()) {
                CommonUITool.openErrorBox(getShell(), Messages.errMsgExecuteInResult);
                return;
            }
            if (result.getQueryEditor().isActive()) {
                CommonUITool.openWarningBox(Messages.msgActiveTran);
                return;
            }
            if (!CommonUITool.openConfirmBox(getShell(), (Messages.msgCommitEdited))) {
                return;
            }
            try {
                if (result.saveInsertedUpdatedDeletedRecords()) {
                    insertSaveItem.setEnabled(false);
                    result.rollbackModifiedItem.setEnabled(false);
                    result.swRecordItem.setSelection(false);
                }
                result.swRecordItem.setSelection(false);
                result.insertRecordItem.setEnabled(false);
                result.delRecordItem.setEnabled(false);
                result.setEditMode(false);
            } catch (ParamSetException e) {
                if (e.getParameter() != null && !StringUtil.isEmpty(e.getParameter().getDataType())) {
                    CommonUITool.openErrorBox(Messages.bind(Messages.errTextTypeNotMatch, e.getParameter().getDataType()) + StringUtil.NEWLINE + e.getLocalizedMessage());
                } else {
                    CommonUITool.openErrorBox(getShell(), e.getLocalizedMessage());
                }
            } catch (SQLException e) {
                e.printStackTrace();
                CommonUITool.openErrorBox(getShell(), e.getErrorCode() + StringUtil.NEWLINE + e.getMessage());
                /*Can't edit any data if necessary*/
                //					result.setEditMode(false);
                //				    delRecordItem.setEnabled(false);
                //					insertRecordItem.setEnabled(false);
                //					insertSaveItem.setEnabled(false) ;
                //					swRecordItem.setEnabled(false);
                //					rollbackModifiedItem.setEnabled(false);
                result.getTblResult().setBackground(BACKGROUND_DIRTY);
            }
        }
    });
    rollbackModifiedItem = new ToolItem(topLeftToolBar, SWT.PUSH);
    result.rollbackModifiedItem = rollbackModifiedItem;
    rollbackModifiedItem.setToolTipText(Messages.insertRollback);
    rollbackModifiedItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/query_rollback.png"));
    rollbackModifiedItem.setDisabledImage(CommonUIPlugin.getImage("icons/queryeditor/query_rollback_disabled.png"));
    rollbackModifiedItem.setEnabled(false);
    rollbackModifiedItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (!CommonUITool.openConfirmBox(getShell(), (Messages.msgRollbackEdited))) {
                return;
            }
            result.tblResult.forceFocus();
            insertSaveItem.setEnabled(false);
            rollbackModifiedItem.setEnabled(false);
            result.clearModifiedLog();
            QueryInfo queryInfo = result.getQueryInfo();
            queryInfo.setCurrentPage(queryInfo.getCurrentPage());
            result.makeItem();
            result.updateActions();
            result.swRecordItem.setSelection(false);
            result.insertRecordItem.setEnabled(false);
            result.delRecordItem.setEnabled(false);
            result.setEditMode(false);
            result.tblResult.setBackground(BACKGROUND_NORMAL);
        }
    });
    if (!isMutliQuery) {
        new ToolItem(topLeftToolBar, SWT.SEPARATOR);
        copyInsertSqlFromRecordsItem = new ToolItem(topLeftToolBar, SWT.PUSH);
        copyInsertSqlFromRecordsItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/record_to_insert.png"));
        copyInsertSqlFromRecordsItem.setToolTipText(Messages.makeInsertFromSelectedRecord);
        copyInsertSqlFromRecordsItem.addSelectionListener(new SelectionListener() {

            public void widgetSelected(SelectionEvent e) {
                if (editor == null) {
                    return;
                }
                String text = editor.getQueryExecuter().makeInsertQueryWithSelectedRecords();
                if (StringUtil.isEmpty(text)) {
                    CommonUITool.openErrorBox(getShell(), Messages.canNotMakeQueryBecauseNoSelected);
                    return;
                }
                CommonUITool.copyContentToClipboard(text);
            }

            public void widgetDefaultSelected(SelectionEvent e) {
            }
        });
        copyUpdateSqlFromRecordsItem = new ToolItem(topLeftToolBar, SWT.PUSH);
        copyUpdateSqlFromRecordsItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/record_to_update.png"));
        copyUpdateSqlFromRecordsItem.setToolTipText(Messages.makeUpdateFromSelectedRecord);
        copyUpdateSqlFromRecordsItem.addSelectionListener(new SelectionListener() {

            public void widgetSelected(SelectionEvent e) {
                if (editor == null) {
                    return;
                }
                String text = editor.getQueryExecuter().makeUpdateQueryWithSelectedRecords();
                if (StringUtil.isEmpty(text)) {
                    CommonUITool.openErrorBox(getShell(), Messages.canNotMakeQueryBecauseNoSelected);
                    return;
                }
                CommonUITool.copyContentToClipboard(text);
            }

            public void widgetDefaultSelected(SelectionEvent e) {
            }
        });
    }
    new ToolItem(topLeftToolBar, SWT.SEPARATOR);
    final ToolItem exportDataItem = new ToolItem(topLeftToolBar, SWT.PUSH);
    exportDataItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/table_data_export.png"));
    exportDataItem.setToolTipText(Messages.msgExportAllQueryResults);
    exportDataItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            CTabItem[] items = queryResultTabFolder.getItems();
            if (items == null || items.length == 0) {
                return;
            }
            List<QueryExecuter> qeList = new ArrayList<QueryExecuter>();
            for (CTabItem item : items) {
                if (!(item.getData() instanceof QueryExecuter)) {
                    continue;
                }
                QueryExecuter qe = (QueryExecuter) item.getData();
                qeList.add(qe);
            }
            if (qeList.isEmpty()) {
                return;
            }
            ExportQueryResultDialog dialog = new ExportQueryResultDialog(getShell(), qeList);
            dialog.open();
        }
    });
    new ToolItem(topLeftToolBar, SWT.SEPARATOR);
    final ToolItem showLogItem = new ToolItem(topLeftToolBar, SWT.PUSH);
    showLogItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/qe_panel_down.png"));
    showLogItem.setToolTipText(Messages.tooltip_qedit_log_show_hide);
    showLogItem.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (tableLogSash.getMaximizedControl() == null) {
                tableLogSash.setMaximizedControl(resultContainer);
                showLogItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/qe_panel_up.png"));
                tableLogSash.layout(true);
            } else {
                tableLogSash.setMaximizedControl(null);
                showLogItem.setImage(CommonUIPlugin.getImage("icons/queryeditor/qe_panel_down.png"));
                tableLogSash.layout(true);
            }
        }
    });
    new ToolItem(topLeftToolBar, SWT.SEPARATOR);
    viewForm.setContent(tableLogSash);
    viewForm.setTopRight(topRightToolBar);
    viewForm.setTopLeft(topLeftToolBar);
    final QueryTableTabItem queryTableTabItem = new QueryTableTabItem(parentFolder, SWT.NONE);
    queryTableTabItem.setText(Messages.qedit_result + (result.idx + 1));
    queryTableTabItem.setControl(viewForm);
    queryTableTabItem.setData(result);
    queryTableTabItem.addDisposeListener(new DisposeListener() {

        public void widgetDisposed(DisposeEvent e) {
            InfoWindowManager.getInstance().updateContent(editor);
        }
    });
    parentFolder.setSelection(queryTableTabItem);
    tableSelectSupport.addSelectChangeListener(new ISelectionChangeListener() {

        @SuppressWarnings("unchecked")
        public void selectionChanged(SelectionChangeEvent event) {
            boolean active = event.selectedArray.length > 0;
            boolean canEdit = active && result.getEditable() && result.isEditMode();
            if (delRecordItem != null) {
                delRecordItem.setEnabled(canEdit);
            }
            if (copyInsertSqlFromRecordsItem != null) {
                copyInsertSqlFromRecordsItem.setEnabled(active);
            }
            if (copyUpdateSqlFromRecordsItem != null) {
                copyUpdateSqlFromRecordsItem.setEnabled(active);
            }
            /*TOOLS-3632 Add calculation info*/
            int count = event.selectedArray.length;
            BigDecimal sum = new BigDecimal(0);
            BigDecimal average = null;
            int numericCount = 0;
            QueryResultTableCalcInfo queryResultTableCalcInfo = null;
            StatusLineContrItem statusCont = LayoutManager.getInstance().getStatusLineContrItem();
            if (count > 1) {
                for (Point p : event.selectedArray) {
                    TableColumn column = result.tblResult.getColumn(p.x);
                    if (column == null) {
                        continue;
                    }
                    ColumnInfo columnInfo = (ColumnInfo) column.getData();
                    if (columnInfo == null) {
                        continue;
                    }
                    String dataType = columnInfo.getType();
                    if (!DataType.isNumberType(dataType)) {
                        continue;
                    }
                    TableItem item = result.tblResult.getItem(p.y);
                    if (item == null || item.getData() == null) {
                        continue;
                    }
                    Map<String, CellValue> dataMap = (Map<String, CellValue>) item.getData();
                    CellValue cellValue = dataMap.get(Integer.toString(p.x));
                    if (cellValue != null && cellValue.getValue() != null) {
                        numericCount++;
                        Object value = cellValue.getValue();
                        if (value instanceof Integer) {
                            sum = sum.add(new BigDecimal((Integer) value));
                        } else if (value instanceof Short) {
                            sum = sum.add(new BigDecimal((Short) value));
                        } else if (value instanceof Long) {
                            sum = sum.add(new BigDecimal((Long) value));
                        } else if (value instanceof Float) {
                            sum = sum.add(new BigDecimal((Float) value));
                        } else if (value instanceof Double) {
                            sum = sum.add(new BigDecimal((Double) value));
                        } else if (value instanceof BigDecimal) {
                            sum = sum.add((BigDecimal) value);
                        }
                    }
                }
                if (numericCount > 0) {
                    average = sum.divide(new BigDecimal(numericCount), 3, RoundingMode.HALF_UP);
                    queryResultTableCalcInfo = new QueryResultTableCalcInfo(count, average, sum);
                } else {
                    queryResultTableCalcInfo = new QueryResultTableCalcInfo(count);
                }
            }
            queryTableTabItem.setQueryResultTableCalcInfo(queryResultTableCalcInfo);
            InfoWindowManager.getInstance().updateContent(editor);
            statusCont.changeStuatusLineForViewOrEditPart(editor.getSelectedDatabase(), editor);
        }
    });
}
Also used : TableItem(org.eclipse.swt.widgets.TableItem) DisposeEvent(org.eclipse.swt.events.DisposeEvent) FocusEvent(org.eclipse.swt.events.FocusEvent) CTabItem(org.eclipse.swt.custom.CTabItem) SelectionEvent(org.eclipse.swt.events.SelectionEvent) List(java.util.List) ArrayList(java.util.ArrayList) CellValue(com.cubrid.common.ui.spi.table.CellValue) FormAttachment(org.eclipse.swt.layout.FormAttachment) FormData(org.eclipse.swt.layout.FormData) StatusLineContrItem(com.cubrid.common.ui.spi.contribution.StatusLineContrItem) StyledText(org.eclipse.swt.custom.StyledText) ParamSetException(com.cubrid.common.ui.spi.util.paramSetter.ParamSetException) FillLayout(org.eclipse.swt.layout.FillLayout) TableColumn(org.eclipse.swt.widgets.TableColumn) SelectionChangeEvent(com.cubrid.common.ui.spi.table.SelectionChangeEvent) ViewForm(org.eclipse.swt.custom.ViewForm) QueryResultTableCalcInfo(com.cubrid.common.ui.query.editor.QueryResultTableCalcInfo) ExportQueryResultDialog(com.cubrid.common.ui.query.dialog.ExportQueryResultDialog) FocusListener(org.eclipse.swt.events.FocusListener) Map(java.util.Map) SelectionListener(org.eclipse.swt.events.SelectionListener) DisposeListener(org.eclipse.swt.events.DisposeListener) TableCursor(org.eclipse.swt.custom.TableCursor) SQLException(java.sql.SQLException) ToolBarManager(org.eclipse.jface.action.ToolBarManager) ToolItem(org.eclipse.swt.widgets.ToolItem) FormLayout(org.eclipse.swt.layout.FormLayout) Table(org.eclipse.swt.widgets.Table) Composite(org.eclipse.swt.widgets.Composite) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) QueryTableTabItem(com.cubrid.common.ui.query.editor.QueryTableTabItem) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) BigDecimal(java.math.BigDecimal) SashForm(org.eclipse.swt.custom.SashForm) TableSelectSupport(com.cubrid.common.ui.spi.table.TableSelectSupport) ToolBar(org.eclipse.swt.widgets.ToolBar) ISelectionChangeListener(com.cubrid.common.ui.spi.table.ISelectionChangeListener)

Example 3 with ParamSetException

use of com.cubrid.common.ui.spi.util.paramSetter.ParamSetException in project cubrid-manager by CUBRID.

the class AbsImportRunnable method processRowData.

protected ImportRowData processRowData(String[] columnArray, String[] columnPattern, int currentRow, File parentFile) throws StopPerformException {
    // FIXME move this logic to core module
    ImportRowData rowData = new ImportRowData(currentRow);
    ImportColumnData columnData = null;
    boolean isSuccess = false;
    try {
        for (int j = 0; j < tableConfig.getPstmList().size(); j++) {
            PstmtParameter pstmtParameter = tableConfig.getPstmList().get(j);
            int column = Integer.parseInt(pstmtParameter.getStringParamValue());
            String content = null;
            String pattern = null;
            if (columnArray.length > column) {
                content = columnArray[column];
            }
            if (columnPattern != null && columnPattern.length > column) {
                pattern = columnPattern[column];
            }
            /*Recored the origin data*/
            columnData = new ImportColumnData(content);
            rowData.getColumnList().add(columnData);
            String dataType = DataType.getRealType(pstmtParameter.getDataType());
            Object value = getRealValueForImport(dataType, content, parentFile);
            try {
                PstmtParameter parameter = new PstmtParameter(pstmtParameter.getParamName(), pstmtParameter.getParamIndex(), pstmtParameter.getDataType(), value);
                parameter.setCharSet(importConfig.getFilesCharset());
                if (StringUtil.isNotEmpty(pattern)) {
                    parameter.setDatePattern(pattern);
                }
                if (value != null && value instanceof File) {
                    parameter.setFileValue(true);
                }
                setPreparedStatementValue(pStmt, parameter, dbCharset);
                columnData.setStatus(ImportStatus.STATUS_FORMAT_SUCCESS);
                isSuccess = true;
            } catch (ParamSetException ex) {
                isSuccess = false;
                LOGGER.debug(ex.getMessage());
            } catch (SQLException ex) {
                isSuccess = false;
                LOGGER.debug(ex.getMessage());
            } finally {
                if (!isSuccess) {
                    columnData.setStatus(ImportStatus.STATUS_FORMAT_FAILED);
                    dataTypeErrorHandling(getErrorMsg(currentRow, column, dataType));
                    PstmtParameter parameter = new PstmtParameter(pstmtParameter.getParamName(), pstmtParameter.getParamIndex(), pstmtParameter.getDataType(), null);
                    parameter.setCharSet(importConfig.getFilesCharset());
                    try {
                        setPreparedStatementNULL(pStmt, parameter);
                    } catch (SQLException e) {
                        LOGGER.debug(e.getMessage());
                    }
                }
            }
        }
    } catch (OutOfMemoryError error) {
        throw new RuntimeException(error);
    }
    return rowData;
}
Also used : ImportRowData(com.cubrid.common.ui.cubrid.table.dialog.imp.model.ImportRowData) ImportColumnData(com.cubrid.common.ui.cubrid.table.dialog.imp.model.ImportColumnData) PstmtParameter(com.cubrid.common.ui.cubrid.table.dialog.PstmtParameter) ParamSetException(com.cubrid.common.ui.spi.util.paramSetter.ParamSetException) SQLException(java.sql.SQLException) File(java.io.File)

Example 4 with ParamSetException

use of com.cubrid.common.ui.spi.util.paramSetter.ParamSetException in project cubrid-manager by CUBRID.

the class QueryExecuter method insertValues.

/**
	 * Insert values on the query result editor.
	 *
	 * @return
	 * @throws SQLException
	 */
private Map<String, Map<String, CellValue>> insertValues() throws SQLException, ParamSetException {
    Map<String, Map<String, CellValue>> successedMap = new HashMap<String, Map<String, CellValue>>();
    if (insValues == null || insValues.size() == 0) {
        return successedMap;
    }
    ParamSetter paramSetter = new ParamSetter();
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);
    Connection conn = connection.checkAndConnect();
    try {
        String tableName = UIQueryUtil.getTableNameFromQuery(conn, query);
        String escapedTable = QuerySyntax.escapeKeyword(tableName);
        if (tableName == null) {
            CommonUITool.openErrorBox(Messages.errModifiedOneTable);
            return successedMap;
        }
        PreparedStatement pstmt = null;
        List<ColumnInfo> allColumnList = getAllColumnList();
        for (String key : insValues.keySet()) {
            Map<String, CellValue> valuesMap = insValues.get(key);
            if (valuesMap == null) {
                continue;
            }
            try {
                List<ColumnInfo> colInfoList = new ArrayList<ColumnInfo>();
                List<ColumnInfo> unPColInfoList = new ArrayList<ColumnInfo>();
                for (int i = 0; i < allColumnList.size(); i++) {
                    ColumnInfo colInfo = allColumnList.get(i);
                    if (queryEditor.isIgnoreType(colInfo.getType())) {
                        continue;
                    }
                    CellValue value = valuesMap.get(colInfo.getIndex());
                    if (value == null || value.getValue() == null) {
                        continue;
                    }
                    if (DataType.DATATYPE_NATIONAL_CHARACTER.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_NCHAR_VARYING.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_NCHAR.equalsIgnoreCase(colInfo.getType())) {
                        unPColInfoList.add(colInfo);
                        continue;
                    }
                    if ((DataType.DATATYPE_BIT.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_BIT_VARYING.equalsIgnoreCase(colInfo.getType())) && value.getValue() instanceof String) {
                        unPColInfoList.add(colInfo);
                        continue;
                    }
                    colInfoList.add(colInfo);
                }
                StringBuilder sqlBuffer = new StringBuilder();
                sqlBuffer.append("INSERT INTO ").append(escapedTable).append(" (");
                int paramCount = 0;
                for (ColumnInfo columnInfo : colInfoList) {
                    if (paramCount > 0) {
                        sqlBuffer.append(",");
                    }
                    sqlBuffer.append(QuerySyntax.escapeKeyword(columnInfo.getName()));
                    paramCount++;
                }
                for (ColumnInfo columnInfo : unPColInfoList) {
                    if (paramCount > 0) {
                        sqlBuffer.append(",");
                    }
                    sqlBuffer.append(QuerySyntax.escapeKeyword(columnInfo.getName()));
                    paramCount++;
                }
                sqlBuffer.append(") VALUES (");
                int dataIndex = 1;
                List<PstmtParameter> pstmtParaList = new ArrayList<PstmtParameter>();
                for (ColumnInfo columnInfo : colInfoList) {
                    if (dataIndex > 1) {
                        sqlBuffer.append(",");
                    }
                    sqlBuffer.append("?");
                    CellValue value = valuesMap.get(columnInfo.getIndex());
                    PstmtParameter pstmtParameter = new PstmtParameter(columnInfo.getName(), dataIndex, columnInfo.getComleteType(), value.getValue());
                    pstmtParaList.add(pstmtParameter);
                    dataIndex++;
                }
                String charset = getDatabaseInfo() != null ? getDatabaseInfo().getCharSet() : null;
                for (ColumnInfo columnInfo : unPColInfoList) {
                    if (dataIndex > 1) {
                        sqlBuffer.append(",");
                    }
                    CellValue value = valuesMap.get(columnInfo.getIndex());
                    String dataType = DataType.makeType(columnInfo.getType(), columnInfo.getChildElementType(), columnInfo.getPrecision(), columnInfo.getScale());
                    FormatDataResult result = DBAttrTypeFormatter.format(dataType, value.getStringValue(), null, false, charset, false);
                    if (result.isSuccess()) {
                        sqlBuffer.append(result.getFormatedString());
                    } else {
                        throw new ParamSetException("Format data \"" + value.getStringValue() + "\"error for data type " + dataType);
                    }
                }
                sqlBuffer.append(")");
                pstmt = conn.prepareStatement(sqlBuffer.toString());
                for (PstmtParameter pstmtParameter : pstmtParaList) {
                    paramSetter.handle(pstmt, pstmtParameter);
                }
                pstmt.executeUpdate();
                successedMap.put(key, valuesMap);
                if (!connection.isAutoCommit() && queryEditor.getConnection() == connection) {
                    queryEditor.setHaveActiveTransaction(true);
                }
            } catch (SQLException e) {
                if (successedMap.containsKey(key)) {
                    successedMap.remove(key);
                }
                LOGGER.error("", e);
                logMessageText.setText(e.getLocalizedMessage());
                throw e;
            } finally {
                QueryUtil.freeQuery(pstmt);
            }
        }
    } finally {
        if (connection != null && connection.isAutoClosable()) {
            connection.commit();
            connection.close();
        }
    }
    return successedMap;
}
Also used : HashMap(java.util.HashMap) ParamSetException(com.cubrid.common.ui.spi.util.paramSetter.ParamSetException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) DBConnection(com.cubrid.cubridmanager.core.common.jdbc.DBConnection) ArrayList(java.util.ArrayList) ParamSetter(com.cubrid.common.ui.spi.util.paramSetter.ParamSetter) PreparedStatement(java.sql.PreparedStatement) Point(org.eclipse.swt.graphics.Point) PstmtParameter(com.cubrid.common.ui.cubrid.table.dialog.PstmtParameter) FormatDataResult(com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult) CellValue(com.cubrid.common.ui.spi.table.CellValue) Map(java.util.Map) HashMap(java.util.HashMap) NumberFormat(java.text.NumberFormat)

Example 5 with ParamSetException

use of com.cubrid.common.ui.spi.util.paramSetter.ParamSetException in project cubrid-manager by CUBRID.

the class QueryExecuter method saveInsertedUpdatedDeletedRecords.

/**
	 * Save all new inserted/updated records to database
	 * @throws ParamSetException
	 */
@SuppressWarnings("unchecked")
public boolean saveInsertedUpdatedDeletedRecords() throws SQLException, ParamSetException {
    logMessageText.setText("");
    // delete
    if (delValues.size() > 0) {
        Map<String, Map<String, CellValue>> deleteValuesMap = deleteValues();
        if (deleteValuesMap.size() == 0) {
            return false;
        }
    }
    // insert
    int insertCounts = 0;
    if (insValues.size() > 0) {
        Map<String, TableItem> insertedTableItems = new HashMap<String, TableItem>();
        for (TableItem recordItem : tblResult.getItems()) {
            String key = "" + recordItem.hashCode();
            Map<String, CellValue> newValue = (Map<String, CellValue>) recordItem.getData(LASTEST_DATA_FLAG);
            if (insValues.containsKey(key) && newValue != null) {
                Map<String, CellValue> insertValue = new HashMap<String, CellValue>();
                insertValue.putAll(newValue);
                insValues.put(key, insertValue);
                insertedTableItems.put(key, recordItem);
            }
            insertCounts++;
        }
        Map<String, Map<String, CellValue>> insertValuesMap = insertValues();
        if (insertValuesMap.size() == 0) {
            return false;
        }
    }
    // update
    if (oldValues.size() > 0 && newValues.size() > 0) {
        Map<String, Map<String, CellValue>> updateValuesMap = updateValues();
        if (updateValuesMap.size() == 0) {
            return false;
        }
    }
    clearModifiedLog();
    if (insertCounts > 0) {
        reloadQuery();
    }
    try {
        for (CombinedQueryEditorComposite combinedQueryEditorComposite : getQueryEditor().getAllCombinedQueryEditorComposite()) {
            combinedQueryEditorComposite.getRecentlyUsedSQLComposite().refreshRecentlyUsedSQLList();
        }
    } catch (Exception ignored) {
    }
    return true;
}
Also used : HashMap(java.util.HashMap) TableItem(org.eclipse.swt.widgets.TableItem) CellValue(com.cubrid.common.ui.spi.table.CellValue) Map(java.util.Map) HashMap(java.util.HashMap) Point(org.eclipse.swt.graphics.Point) ParamSetException(com.cubrid.common.ui.spi.util.paramSetter.ParamSetException) SQLException(java.sql.SQLException) IOException(java.io.IOException)

Aggregations

ParamSetException (com.cubrid.common.ui.spi.util.paramSetter.ParamSetException)6 SQLException (java.sql.SQLException)6 CellValue (com.cubrid.common.ui.spi.table.CellValue)5 Map (java.util.Map)5 Point (org.eclipse.swt.graphics.Point)5 PstmtParameter (com.cubrid.common.ui.cubrid.table.dialog.PstmtParameter)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 ParamSetter (com.cubrid.common.ui.spi.util.paramSetter.ParamSetter)3 DBConnection (com.cubrid.cubridmanager.core.common.jdbc.DBConnection)3 FormatDataResult (com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult)3 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 TableItem (org.eclipse.swt.widgets.TableItem)2 ImportColumnData (com.cubrid.common.ui.cubrid.table.dialog.imp.model.ImportColumnData)1 ImportRowData (com.cubrid.common.ui.cubrid.table.dialog.imp.model.ImportRowData)1 ExportQueryResultDialog (com.cubrid.common.ui.query.dialog.ExportQueryResultDialog)1 QueryResultTableCalcInfo (com.cubrid.common.ui.query.editor.QueryResultTableCalcInfo)1 QueryTableTabItem (com.cubrid.common.ui.query.editor.QueryTableTabItem)1 StatusLineContrItem (com.cubrid.common.ui.spi.contribution.StatusLineContrItem)1