Search in sources :

Example 11 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by dbeaver.

the class JDBCReference method getReferencedObject.

@Override
public Object getReferencedObject(DBCSession session) throws DBCException {
    if (refObject == null) {
        try {
            session.getProgressMonitor().beginTask("Retrieve references object", 3);
            try {
                session.getProgressMonitor().worked(1);
                Object refValue = value.getObject();
                session.getProgressMonitor().worked(1);
                DBDValueHandler valueHandler = DBUtils.findValueHandler(session, type);
                refObject = valueHandler.getValueFromObject(session, type, refValue, false, false);
                session.getProgressMonitor().worked(1);
            } finally {
                session.getProgressMonitor().done();
            }
        } catch (SQLException e) {
            throw new DBCException("Can't obtain object reference");
        }
    }
    return refObject;
}
Also used : SQLException(java.sql.SQLException) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBCException(org.jkiss.dbeaver.model.exec.DBCException)

Example 12 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by dbeaver.

the class ResultSetHandlerMain method execute.

@Nullable
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
    if (activePart == null) {
        return null;
    }
    final ResultSetViewer rsv = (ResultSetViewer) getActiveResultSet(activePart);
    if (rsv == null) {
        return null;
    }
    Shell activeShell = HandlerUtil.getActiveShell(event);
    String actionId = event.getCommand().getId();
    IResultSetPresentation presentation = rsv.getActivePresentation();
    DBPDataSource dataSource = rsv.getDataSource();
    switch(actionId) {
        case IWorkbenchCommandConstants.FILE_REFRESH:
            rsv.refreshData(null);
            break;
        case CMD_TOGGLE_MODE:
            rsv.toggleMode();
            break;
        case CMD_TOGGLE_PANELS:
            rsv.showPanels(!rsv.isPanelsVisible(), true, true);
            break;
        case CMD_ACTIVATE_PANELS:
            rsv.togglePanelsFocus();
            break;
        case CMD_TOGGLE_MAXIMIZE:
            rsv.togglePanelsMaximize();
            break;
        case CMD_TOGGLE_LAYOUT:
            rsv.toggleVerticalLayout();
            break;
        case CMD_FOCUS_FILTER:
            rsv.switchFilterFocus();
            break;
        case CMD_SWITCH_PRESENTATION:
            rsv.switchPresentation();
            break;
        case CMD_ROW_PREVIOUS:
        case ITextEditorActionDefinitionIds.WORD_PREVIOUS:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.PREVIOUS);
            break;
        case CMD_ROW_NEXT:
        case ITextEditorActionDefinitionIds.WORD_NEXT:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT);
            break;
        case CMD_ROW_FIRST:
        case ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.FIRST);
            break;
        case CMD_ROW_LAST:
        case ITextEditorActionDefinitionIds.SELECT_WORD_NEXT:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.LAST);
            break;
        case CMD_FETCH_PAGE:
            rsv.readNextSegment();
            break;
        case CMD_FETCH_ALL:
            rsv.readAllData();
            break;
        case CMD_ROW_EDIT:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).openValueEditor(false);
            }
            break;
        case CMD_ROW_EDIT_INLINE:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).openValueEditor(true);
            }
            break;
        case CMD_ROW_ADD:
        case CMD_ROW_COPY:
            {
                boolean copy = actionId.equals(CMD_ROW_COPY);
                boolean shiftPressed = event.getTrigger() instanceof Event && ((((Event) event.getTrigger()).stateMask & SWT.SHIFT) == SWT.SHIFT);
                boolean insertAfter = rsv.getPreferenceStore().getBoolean(ResultSetPreferences.RS_EDIT_NEW_ROWS_AFTER);
                if (shiftPressed)
                    insertAfter = !insertAfter;
                rsv.addNewRow(copy, insertAfter, true);
                if (insertAfter) {
                    presentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT);
                }
                break;
            }
        case CMD_ROW_DELETE:
        case IWorkbenchCommandConstants.EDIT_DELETE:
            rsv.deleteSelectedRows();
            break;
        case CMD_CELL_SET_NULL:
        case CMD_CELL_SET_DEFAULT:
        case CMD_CELL_RESET:
            {
                IResultSetSelection selection = rsv.getSelection();
                for (Object cell : selection.toArray()) {
                    DBDAttributeBinding attr = selection.getElementAttribute(cell);
                    ResultSetRow row = selection.getElementRow(cell);
                    if (row != null && attr != null) {
                        ResultSetValueController valueController = new ResultSetValueController(rsv, attr, row, IValueController.EditType.NONE, null);
                        if (actionId.equals(CMD_CELL_SET_NULL)) {
                            valueController.updateValue(BaseValueManager.makeNullValue(valueController), false);
                        } else if (actionId.equals(CMD_CELL_SET_DEFAULT)) {
                            DBDValueHandler valueHandler = valueController.getValueHandler();
                            if (valueHandler instanceof DBDValueDefaultGenerator) {
                                try (DBCSession session = rsv.getExecutionContext().openSession(new VoidProgressMonitor(), DBCExecutionPurpose.UTIL, "Generate default value")) {
                                    Object defValue = ((DBDValueDefaultGenerator) valueHandler).generateDefaultValue(session, valueController.getValueType());
                                    valueController.updateValue(defValue, false);
                                }
                            }
                        } else {
                            rsv.getModel().resetCellValue(attr, row);
                        }
                    }
                }
                rsv.redrawData(false, false);
                rsv.updatePanelsContent(false);
                break;
            }
        case CMD_APPLY_CHANGES:
            {
                if (dataSource == null) {
                    return null;
                }
                ResultSetSaveSettings saveSettings = new ResultSetSaveSettings();
                rsv.applyChanges(null, saveSettings);
                break;
            }
        case CMD_REJECT_CHANGES:
            rsv.rejectChanges();
            break;
        case CMD_GENERATE_SCRIPT:
            {
                ResultSetSaveReport saveReport = rsv.generateChangesReport();
                if (saveReport == null) {
                    return null;
                }
                ResultSetSaveSettings saveSettings = showPreviewScript(rsv, saveReport);
                if (saveSettings != null) {
                    rsv.applyChanges(null, saveSettings);
                }
                break;
            }
        case CMD_COPY_COLUMN_NAMES:
            {
                StringBuilder buffer = new StringBuilder();
                String columnNames = event.getParameter("columns");
                IResultSetSelection selection = rsv.getSelection();
                List<DBDAttributeBinding> attrs = selection.isEmpty() ? rsv.getModel().getVisibleAttributes() : selection.getSelectedAttributes();
                if (!CommonUtils.isEmpty(columnNames) && attrs.size() == 1) {
                    attrs = new ArrayList<>();
                    for (String colName : columnNames.split(",")) {
                        for (DBDAttributeBinding attr : rsv.getModel().getVisibleAttributes()) {
                            if (colName.equals(attr.getName())) {
                                attrs.add(attr);
                            }
                        }
                    }
                }
                ResultSetCopySettings settings = new ResultSetCopySettings();
                if (attrs.size() > 1) {
                    ResultSetHandlerCopySpecial.CopyConfigDialog configDialog = new ResultSetHandlerCopySpecial.CopyConfigDialog(activeShell, "CopyGridNamesOptionsDialog");
                    if (configDialog.open() != IDialogConstants.OK_ID) {
                        return null;
                    }
                    settings = configDialog.copySettings;
                }
                for (DBDAttributeBinding attr : attrs) {
                    if (buffer.length() > 0) {
                        buffer.append(settings.getColumnDelimiter());
                    }
                    String colName = attr.getLabel();
                    if (CommonUtils.isEmpty(colName)) {
                        colName = attr.getName();
                    }
                    if (dataSource == null) {
                        buffer.append(colName);
                    } else {
                        buffer.append(DBUtils.getQuotedIdentifier(dataSource, colName));
                    }
                }
                ResultSetUtils.copyToClipboard(buffer.toString());
                break;
            }
        case CMD_COPY_ROW_NAMES:
            {
                StringBuilder buffer = new StringBuilder();
                List<ResultSetRow> selectedRows = rsv.getSelection().getSelectedRows();
                ResultSetCopySettings settings = new ResultSetCopySettings();
                if (selectedRows.size() > 1) {
                    ResultSetHandlerCopySpecial.CopyConfigDialog configDialog = new ResultSetHandlerCopySpecial.CopyConfigDialog(activeShell, "CopyGridNamesOptionsDialog");
                    if (configDialog.open() != IDialogConstants.OK_ID) {
                        return null;
                    }
                    settings = configDialog.copySettings;
                }
                for (ResultSetRow row : selectedRows) {
                    if (buffer.length() > 0) {
                        buffer.append(settings.getRowDelimiter());
                    }
                    buffer.append(row.getVisualNumber() + 1);
                }
                ResultSetUtils.copyToClipboard(buffer.toString());
                break;
            }
        case IWorkbenchCommandConstants.EDIT_COPY:
            ResultSetUtils.copyToClipboard(presentation.copySelection(new ResultSetCopySettings(false, false, false, true, false, null, null, null, DBDDisplayFormat.EDIT)));
            break;
        case IWorkbenchCommandConstants.EDIT_PASTE:
        case IActionConstants.CMD_PASTE_SPECIAL:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).pasteFromClipboard(actionId.equals(IActionConstants.CMD_PASTE_SPECIAL));
            }
            break;
        case IWorkbenchCommandConstants.EDIT_CUT:
            ResultSetUtils.copyToClipboard(presentation.copySelection(new ResultSetCopySettings(false, false, true, true, false, null, null, null, DBDDisplayFormat.EDIT)));
            break;
        case IWorkbenchCommandConstants.FILE_PRINT:
            presentation.printResultSet();
            break;
        case ITextEditorActionDefinitionIds.SMART_ENTER:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).openValueEditor(false);
            }
            break;
        case IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE:
            IAction action = TextEditorUtils.createFindReplaceAction(activeShell, rsv.getAdapter(IFindReplaceTarget.class));
            action.run();
            break;
        case CMD_NAVIGATE_LINK:
            {
                final DBDAttributeBinding attr = rsv.getActivePresentation().getCurrentAttribute();
                if (attr != null) {
                    new AbstractJob("Navigate association") {

                        @Override
                        protected IStatus run(DBRProgressMonitor monitor) {
                            try {
                                rsv.navigateAssociation(monitor, rsv.getModel(), DBExecUtils.getAssociationByAttribute(attr), rsv.getSelection().getSelectedRows(), false);
                            } catch (DBException e) {
                                return GeneralUtils.makeExceptionStatus(e);
                            }
                            return Status.OK_STATUS;
                        }
                    }.schedule();
                }
                break;
            }
        case CMD_COUNT:
            rsv.updateRowCount();
            break;
        case IWorkbenchCommandConstants.NAVIGATE_BACKWARD_HISTORY:
            {
                final int hp = rsv.getHistoryPosition();
                if (hp > 0) {
                    rsv.navigateHistory(hp - 1);
                }
                break;
            }
        case IWorkbenchCommandConstants.NAVIGATE_FORWARD_HISTORY:
            {
                final int hp = rsv.getHistoryPosition();
                if (hp < rsv.getHistorySize() - 1) {
                    rsv.navigateHistory(hp + 1);
                }
                break;
            }
        case ITextEditorActionDefinitionIds.LINE_GOTO:
            {
                ResultSetRow currentRow = rsv.getCurrentRow();
                final int rowCount = rsv.getModel().getRowCount();
                if (rowCount <= 0) {
                    break;
                }
                GotoLineDialog d = new GotoLineDialog(activeShell, "Go to Row", "Enter row number (1.." + rowCount + ")", String.valueOf(currentRow == null ? 1 : currentRow.getVisualNumber() + 1), input -> {
                    try {
                        int i = Integer.parseInt(input);
                        if (i <= 0 || rowCount < i) {
                            return "Row number is out of range";
                        }
                    } catch (NumberFormatException x) {
                        return "Not a number";
                    }
                    return null;
                });
                if (d.open() == Window.OK) {
                    int line = Integer.parseInt(d.getValue());
                    rsv.setCurrentRow(rsv.getModel().getRow(line - 1));
                    rsv.getActivePresentation().scrollToRow(IResultSetPresentation.RowPosition.CURRENT);
                }
                break;
            }
        case CMD_FILTER_MENU:
            {
                rsv.showFiltersMenu();
                break;
            }
        case CMD_FILTER_MENU_DISTINCT:
            {
                DBDAttributeBinding curAttribute = rsv.getActivePresentation().getCurrentAttribute();
                if (curAttribute != null) {
                    rsv.showFiltersDistinctMenu(curAttribute, true);
                }
                break;
            }
        case CMD_FILTER_EDIT_SETTINGS:
            {
                rsv.showFilterSettingsDialog();
                break;
            }
        case CMD_FILTER_SAVE_SETTING:
            {
                rsv.saveDataFilter();
                break;
            }
        case CMD_FILTER_CLEAR_SETTING:
            {
                rsv.clearDataFilter(true);
            }
        case CMD_REFERENCES_MENU:
            {
                boolean shiftPressed = event.getTrigger() instanceof Event && ((((Event) event.getTrigger()).stateMask & SWT.SHIFT) == SWT.SHIFT);
                rsv.showReferencesMenu(shiftPressed);
                break;
            }
        case CMD_EXPORT:
            {
                List<Long> selectedRows = new ArrayList<>();
                for (ResultSetRow selectedRow : rsv.getSelection().getSelectedRows()) {
                    selectedRows.add(Long.valueOf(selectedRow.getRowNumber()));
                }
                List<String> selectedAttributes = new ArrayList<>();
                for (DBDAttributeBinding attributeBinding : rsv.getSelection().getSelectedAttributes()) {
                    selectedAttributes.add(attributeBinding.getName());
                }
                ResultSetDataContainerOptions options = new ResultSetDataContainerOptions();
                options.setSelectedRows(selectedRows);
                options.setSelectedColumns(selectedAttributes);
                ResultSetDataContainer dataContainer = new ResultSetDataContainer(rsv, options);
                DataTransferWizard.openWizard(HandlerUtil.getActiveWorkbenchWindow(event), Collections.singletonList(new DatabaseTransferProducer(dataContainer, rsv.getModel().getDataFilter())), null, rsv.getSelection());
                break;
            }
        case CMD_ZOOM_IN:
        case CMD_ZOOM_OUT:
            {
                FontRegistry fontRegistry = rsv.getSite().getWorkbenchWindow().getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry();
                Font font = fontRegistry.get(ThemeConstants.FONT_SQL_RESULT_SET);
                if (font != null) {
                    FontData[] fondData = font.getFontData();
                    if (fondData != null) {
                        int zoomFactor = actionId.equals(CMD_ZOOM_IN) ? 1 : -1;
                        FontDescriptor fd = createFontDescriptor(fondData, zoomFactor);
                        fontRegistry.put(ThemeConstants.FONT_SQL_RESULT_SET, fd.getFontData());
                    }
                }
                break;
            }
        case CMD_TOGGLE_ORDER:
            {
                final DBDAttributeBinding attr = rsv.getActivePresentation().getCurrentAttribute();
                if (attr != null) {
                    rsv.toggleSortOrder(attr, false, false);
                }
                break;
            }
    }
    return null;
}
Also used : DBCSession(org.jkiss.dbeaver.model.exec.DBCSession) IWorkbenchPartSite(org.eclipse.ui.IWorkbenchPartSite) IAction(org.eclipse.jface.action.IAction) IWorkbenchCommandConstants(org.eclipse.ui.IWorkbenchCommandConstants) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) IDialogSettings(org.eclipse.jface.dialogs.IDialogSettings) FontRegistry(org.eclipse.jface.resource.FontRegistry) IStatus(org.eclipse.core.runtime.IStatus) DBDDisplayFormat(org.jkiss.dbeaver.model.data.DBDDisplayFormat) ITextEditorActionDefinitionIds(org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) DBDValueDefaultGenerator(org.jkiss.dbeaver.model.data.DBDValueDefaultGenerator) GeneralUtils(org.jkiss.dbeaver.utils.GeneralUtils) CommonUtils(org.jkiss.utils.CommonUtils) MultiPageAbstractEditor(org.jkiss.dbeaver.ui.editors.MultiPageAbstractEditor) DatabaseTransferProducer(org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer) DBUtils(org.jkiss.dbeaver.model.DBUtils) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) Status(org.eclipse.core.runtime.Status) IFindReplaceTarget(org.eclipse.jface.text.IFindReplaceTarget) org.jkiss.dbeaver.ui.controls.resultset(org.jkiss.dbeaver.ui.controls.resultset) DBCExecutionPurpose(org.jkiss.dbeaver.model.exec.DBCExecutionPurpose) BaseValueManager(org.jkiss.dbeaver.ui.data.managers.BaseValueManager) Window(org.eclipse.jface.window.Window) List(java.util.List) DBExecUtils(org.jkiss.dbeaver.model.exec.DBExecUtils) DBException(org.jkiss.dbeaver.DBException) SWT(org.eclipse.swt.SWT) AbstractHandler(org.eclipse.core.commands.AbstractHandler) VoidProgressMonitor(org.jkiss.dbeaver.model.runtime.VoidProgressMonitor) ExecutionEvent(org.eclipse.core.commands.ExecutionEvent) InputDialog(org.eclipse.jface.dialogs.InputDialog) DBWorkbench(org.jkiss.dbeaver.runtime.DBWorkbench) Nullable(org.jkiss.code.Nullable) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) Event(org.eclipse.swt.widgets.Event) HandlerUtil(org.eclipse.ui.handlers.HandlerUtil) ArrayList(java.util.ArrayList) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) UIUtils(org.jkiss.dbeaver.ui.UIUtils) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) Font(org.eclipse.swt.graphics.Font) IValueController(org.jkiss.dbeaver.ui.data.IValueController) FontDescriptor(org.eclipse.jface.resource.FontDescriptor) Shell(org.eclipse.swt.widgets.Shell) TextEditorUtils(org.jkiss.dbeaver.ui.editors.TextEditorUtils) ExecutionException(org.eclipse.core.commands.ExecutionException) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DataTransferWizard(org.jkiss.dbeaver.tools.transfer.ui.wizard.DataTransferWizard) IInputValidator(org.eclipse.jface.dialogs.IInputValidator) FontData(org.eclipse.swt.graphics.FontData) IActionConstants(org.jkiss.dbeaver.ui.IActionConstants) Collections(java.util.Collections) Control(org.eclipse.swt.widgets.Control) DBException(org.jkiss.dbeaver.DBException) ArrayList(java.util.ArrayList) FontRegistry(org.eclipse.jface.resource.FontRegistry) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) Font(org.eclipse.swt.graphics.Font) DBCSession(org.jkiss.dbeaver.model.exec.DBCSession) Shell(org.eclipse.swt.widgets.Shell) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) List(java.util.List) ArrayList(java.util.ArrayList) FontDescriptor(org.eclipse.jface.resource.FontDescriptor) IAction(org.eclipse.jface.action.IAction) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) DBDValueDefaultGenerator(org.jkiss.dbeaver.model.data.DBDValueDefaultGenerator) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DatabaseTransferProducer(org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer) ExecutionEvent(org.eclipse.core.commands.ExecutionEvent) Event(org.eclipse.swt.widgets.Event) VoidProgressMonitor(org.jkiss.dbeaver.model.runtime.VoidProgressMonitor) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) IFindReplaceTarget(org.eclipse.jface.text.IFindReplaceTarget) Nullable(org.jkiss.code.Nullable)

Example 13 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by dbeaver.

the class ExecuteBatchImpl method processBatch.

/**
 * Execute batch OR generate batch script.
 * @param session    session
 * @param actions    script actions. If not null then no execution will be done
 * @return execution statistics
 * @throws DBCException
 */
@NotNull
private DBCStatistics processBatch(@NotNull DBCSession session, @Nullable List<DBEPersistAction> actions) throws DBCException {
    DBDValueHandler[] handlers = new DBDValueHandler[attributes.length];
    for (int i = 0; i < attributes.length; i++) {
        if (attributes[i] instanceof DBDAttributeBinding) {
            handlers[i] = ((DBDAttributeBinding) attributes[i]).getValueHandler();
        } else {
            handlers[i] = DBUtils.findValueHandler(session, attributes[i]);
        }
    }
    boolean useBatch = session.getDataSource().getInfo().supportsBatchUpdates() && reuseStatement;
    if (values.size() <= 1) {
        useBatch = false;
    }
    DBCStatistics statistics = new DBCStatistics();
    DBCStatement statement = null;
    try {
        // Here we'll try to reuse prepared statement.
        // It makes a great sense in case of data transfer where we need millions of inserts.
        // We must be aware of nulls because actual insert statements may differ depending on null values.
        // So if row nulls aren't the same as in previous row we need to prepare new statement and restart batch.
        // Quite complicated but works.
        boolean[] prevNulls = new boolean[attributes.length];
        boolean[] nulls = new boolean[attributes.length];
        int statementsInBatch = 0;
        for (Object[] rowValues : values) {
            boolean reuse = reuseStatement;
            if (reuse) {
                for (int i = 0; i < rowValues.length; i++) {
                    nulls[i] = DBUtils.isNullValue(rowValues[i]);
                }
                if (!Arrays.equals(prevNulls, nulls) && statementsInBatch > 0) {
                    reuse = false;
                }
                System.arraycopy(nulls, 0, prevNulls, 0, nulls.length);
                if (!reuse && statementsInBatch > 0) {
                    // Flush batch
                    if (actions == null) {
                        flushBatch(statistics, statement);
                    }
                    statement.close();
                    statement = null;
                    statementsInBatch = 0;
                    reuse = true;
                }
            }
            if (statement == null || !reuse) {
                statement = prepareStatement(session, rowValues);
                statistics.setQueryText(statement.getQueryString());
                statistics.addStatementsCount();
            }
            try {
                bindStatement(handlers, statement, rowValues);
                if (actions == null) {
                    if (useBatch) {
                        statement.addToBatch();
                        statementsInBatch++;
                    } else {
                        // Execute each row separately
                        long startTime = System.currentTimeMillis();
                        executeStatement(statement);
                        statistics.addExecuteTime(System.currentTimeMillis() - startTime);
                        long rowCount = statement.getUpdateRowCount();
                        if (rowCount > 0) {
                            statistics.addRowsUpdated(rowCount);
                        }
                        // Read keys
                        if (keysReceiver != null) {
                            try {
                                readKeys(statement.getSession(), statement, keysReceiver);
                            } catch (Exception e) {
                                log.warn("Error reading auto-generated keys", e);
                            }
                        }
                    }
                } else {
                    String queryString;
                    if (statement instanceof DBCParameterizedStatement) {
                        queryString = ((DBCParameterizedStatement) statement).getFormattedQuery();
                    } else {
                        queryString = statement.getQueryString();
                    }
                    actions.add(new SQLDatabasePersistAction("Execute statement", queryString));
                }
            } finally {
                if (!reuse) {
                    statement.close();
                }
            }
        }
        values.clear();
        if (statementsInBatch > 0) {
            if (actions == null) {
                flushBatch(statistics, statement);
            }
            statement.close();
            statement = null;
        }
    } finally {
        if (reuseStatement && statement != null) {
            statement.close();
        }
    }
    return statistics;
}
Also used : DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction) NotNull(org.jkiss.code.NotNull)

Example 14 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by dbeaver.

the class JDBCTableConstraint method readKeyEnumeration.

private Collection<DBDLabelValuePair> readKeyEnumeration(DBCSession session, DBSEntityAttribute keyColumn, Object keyPattern, List<DBDAttributeValue> preceedingKeys, int maxResults) throws DBException {
    final TABLE table = getParentObject();
    assert table != null;
    DBDValueHandler keyValueHandler = DBUtils.findValueHandler(session, keyColumn);
    if (keyPattern != null) {
        if (keyPattern instanceof CharSequence) {
            if (((CharSequence) keyPattern).length() > 0) {
                keyPattern = "%" + keyPattern.toString() + "%";
            } else {
                keyPattern = null;
            }
        } else if (keyPattern instanceof Number) {
            // Subtract gap value to see some values before specified
            int gapSize = maxResults / 2;
            if (keyPattern instanceof Integer) {
                keyPattern = (Integer) keyPattern - gapSize;
            } else if (keyPattern instanceof Short) {
                keyPattern = (Short) keyPattern - gapSize;
            } else if (keyPattern instanceof Long) {
                keyPattern = (Long) keyPattern - gapSize;
            } else if (keyPattern instanceof Float) {
                keyPattern = (Float) keyPattern - gapSize;
            } else if (keyPattern instanceof Double) {
                keyPattern = (Double) keyPattern - gapSize;
            } else if (keyPattern instanceof BigInteger) {
                keyPattern = ((BigInteger) keyPattern).subtract(BigInteger.valueOf(gapSize));
            } else if (keyPattern instanceof BigDecimal) {
                keyPattern = ((BigDecimal) keyPattern).subtract(new BigDecimal(gapSize));
            }
        } else {
            // not supported
            keyPattern = null;
        }
    }
    StringBuilder query = new StringBuilder();
    query.append("SELECT ").append(DBUtils.getQuotedIdentifier(keyColumn));
    String descColumns = DBVUtils.getDictionaryDescriptionColumns(session.getProgressMonitor(), keyColumn);
    Collection<DBSEntityAttribute> descAttributes = null;
    if (descColumns != null) {
        descAttributes = DBVEntity.getDescriptionColumns(session.getProgressMonitor(), table, descColumns);
        query.append(", ").append(descColumns);
    }
    query.append(" FROM ").append(DBUtils.getObjectFullName(table, DBPEvaluationContext.DML));
    if (!CommonUtils.isEmpty(preceedingKeys) || keyPattern != null) {
        query.append(" WHERE ");
    }
    boolean hasCond = false;
    // Preceeding keys
    if (preceedingKeys != null && !preceedingKeys.isEmpty()) {
        for (int i = 0; i < preceedingKeys.size(); i++) {
            if (hasCond)
                query.append(" AND ");
            query.append(DBUtils.getQuotedIdentifier(getDataSource(), preceedingKeys.get(i).getAttribute().getName())).append(" = ?");
            hasCond = true;
        }
    }
    if (keyPattern != null) {
        if (hasCond)
            query.append(" AND (");
        query.append(DBUtils.getQuotedIdentifier(keyColumn));
        if (keyPattern instanceof CharSequence) {
            query.append(" LIKE ?");
        } else {
            query.append(" >= ?");
        }
        // Add desc columns conditions
        if (keyPattern instanceof CharSequence && descAttributes != null) {
            for (DBSEntityAttribute descAttr : descAttributes) {
                if (descAttr.getDataKind() == DBPDataKind.STRING) {
                    query.append(" OR ").append(DBUtils.getQuotedIdentifier(descAttr)).append(" LIKE ?");
                }
            }
        }
        if (hasCond)
            query.append(")");
        query.append(" ORDER BY ").append(DBUtils.getQuotedIdentifier(keyColumn));
    }
    try (DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false)) {
        int paramPos = 0;
        if (preceedingKeys != null && !preceedingKeys.isEmpty()) {
            for (DBDAttributeValue precAttribute : preceedingKeys) {
                DBDValueHandler precValueHandler = DBUtils.findValueHandler(session, precAttribute.getAttribute());
                precValueHandler.bindValueObject(session, dbStat, precAttribute.getAttribute(), paramPos++, precAttribute.getValue());
            }
        }
        if (keyPattern != null) {
            keyValueHandler.bindValueObject(session, dbStat, keyColumn, paramPos++, keyPattern);
        }
        if (keyPattern instanceof CharSequence && descAttributes != null) {
            for (DBSEntityAttribute descAttr : descAttributes) {
                if (descAttr.getDataKind() == DBPDataKind.STRING) {
                    final DBDValueHandler valueHandler = DBUtils.findValueHandler(session, descAttr);
                    valueHandler.bindValueObject(session, dbStat, keyColumn, paramPos++, keyPattern);
                }
            }
        }
        dbStat.setLimit(0, maxResults);
        if (dbStat.executeStatement()) {
            try (DBCResultSet dbResult = dbStat.openResultSet()) {
                return DBVUtils.readDictionaryRows(session, keyColumn, keyValueHandler, dbResult);
            }
        } else {
            return Collections.emptyList();
        }
    }
}
Also used : DBDAttributeValue(org.jkiss.dbeaver.model.data.DBDAttributeValue) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) DBCStatement(org.jkiss.dbeaver.model.exec.DBCStatement) BigDecimal(java.math.BigDecimal) DBSEntityConstraint(org.jkiss.dbeaver.model.struct.DBSEntityConstraint) AbstractTableConstraint(org.jkiss.dbeaver.model.impl.struct.AbstractTableConstraint) BigInteger(java.math.BigInteger) DBSEntityAttribute(org.jkiss.dbeaver.model.struct.DBSEntityAttribute) BigInteger(java.math.BigInteger) DBCResultSet(org.jkiss.dbeaver.model.exec.DBCResultSet)

Example 15 with DBDValueHandler

use of org.jkiss.dbeaver.model.data.DBDValueHandler in project dbeaver by dbeaver.

the class GenerateUUIDHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
    if (activePart == null) {
        return null;
    }
    IResultSetController rsc = activePart.getAdapter(IResultSetController.class);
    if (rsc != null && UIUtils.hasFocus(rsc.getControl())) {
        IResultSetSelection selection = rsc.getSelection();
        if (selection != null && !selection.isEmpty()) {
            for (Object cell : selection.toArray()) {
                DBDAttributeBinding attr = selection.getElementAttribute(cell);
                ResultSetRow row = selection.getElementRow(cell);
                if (row != null && attr != null) {
                    ResultSetValueController valueController = new ResultSetValueController(rsc, attr, row, IValueController.EditType.NONE, null);
                    DBDValueHandler valueHandler = valueController.getValueHandler();
                    String uuid = generateUUID();
                    valueController.updateValue(uuid, false);
                }
            }
            rsc.redrawData(false, false);
            rsc.updateEditControls();
        }
    } else {
        ITextViewer textViewer = activePart.getAdapter(ITextViewer.class);
        if (textViewer != null) {
            ISelection selection = textViewer.getSelectionProvider().getSelection();
            if (selection instanceof TextSelection) {
                try {
                    int offset = ((TextSelection) selection).getOffset();
                    int length = ((TextSelection) selection).getLength();
                    String uuid = generateUUID();
                    textViewer.getDocument().replace(offset, length, uuid);
                    textViewer.getSelectionProvider().setSelection(new TextSelection(offset + uuid.length(), 0));
                } catch (BadLocationException e) {
                    DBWorkbench.getPlatformUI().showError("Insert UUID", "Error inserting UUID in text editor", e);
                }
            }
        }
    }
    return null;
}
Also used : TextSelection(org.eclipse.jface.text.TextSelection) IResultSetSelection(org.jkiss.dbeaver.ui.controls.resultset.IResultSetSelection) DBDValueHandler(org.jkiss.dbeaver.model.data.DBDValueHandler) ResultSetRow(org.jkiss.dbeaver.ui.controls.resultset.ResultSetRow) IResultSetController(org.jkiss.dbeaver.ui.controls.resultset.IResultSetController) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) ITextViewer(org.eclipse.jface.text.ITextViewer) IWorkbenchPart(org.eclipse.ui.IWorkbenchPart) ISelection(org.eclipse.jface.viewers.ISelection) ResultSetValueController(org.jkiss.dbeaver.ui.controls.resultset.ResultSetValueController) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

DBDValueHandler (org.jkiss.dbeaver.model.data.DBDValueHandler)22 NotNull (org.jkiss.code.NotNull)10 DBDAttributeBinding (org.jkiss.dbeaver.model.data.DBDAttributeBinding)8 DBCResultSet (org.jkiss.dbeaver.model.exec.DBCResultSet)6 DBCStatement (org.jkiss.dbeaver.model.exec.DBCStatement)6 JDBCCollection (org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection)6 DBSTypedObject (org.jkiss.dbeaver.model.struct.DBSTypedObject)6 IWorkbenchPart (org.eclipse.ui.IWorkbenchPart)4 SQLDatabasePersistAction (org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction)4 DBDCollection (org.jkiss.dbeaver.model.data.DBDCollection)3 BigDecimal (java.math.BigDecimal)2 BigInteger (java.math.BigInteger)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 List (java.util.List)2 AbstractHandler (org.eclipse.core.commands.AbstractHandler)2 ExecutionEvent (org.eclipse.core.commands.ExecutionEvent)2 ExecutionException (org.eclipse.core.commands.ExecutionException)2 IStatus (org.eclipse.core.runtime.IStatus)2