Search in sources :

Example 61 with DBDAttributeBinding

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

the class TransformerSettingsDialog method updateTransformItem.

private void updateTransformItem(TableItem attrItem) {
    DBDAttributeBinding attr = (DBDAttributeBinding) attrItem.getData();
    String transformStr = "";
    DBVEntityAttribute vAttr = vEntity.getVirtualAttribute(attr, false);
    if (vAttr != null) {
        DBVTransformSettings settings = vAttr.getTransformSettings();
        if (settings != null) {
            if (!CommonUtils.isEmpty(settings.getIncludedTransformers())) {
                transformStr = String.join(",", settings.getIncludedTransformers());
            } else if (!CommonUtils.isEmpty(settings.getCustomTransformer())) {
                DBDAttributeTransformerDescriptor td = DBWorkbench.getPlatform().getValueHandlerRegistry().getTransformer(settings.getCustomTransformer());
                if (td != null) {
                    transformStr = td.getName();
                }
            }
        }
    }
    attrItem.setText(1, transformStr);
}
Also used : DBDAttributeTransformerDescriptor(org.jkiss.dbeaver.model.data.DBDAttributeTransformerDescriptor) DBVEntityAttribute(org.jkiss.dbeaver.model.virtual.DBVEntityAttribute) DBVTransformSettings(org.jkiss.dbeaver.model.virtual.DBVTransformSettings) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding)

Example 62 with DBDAttributeBinding

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

the class SQLGeneratorSelectManyFromData method generateSQL.

@Override
public void generateSQL(DBRProgressMonitor monitor, StringBuilder sql, IResultSetController object) {
    Collection<DBDAttributeBinding> keyAttributes = getKeyAttributes(monitor, object);
    sql.append("SELECT ");
    boolean hasAttr = false;
    for (DBSAttributeBase attr : getAllAttributes(monitor, object)) {
        if (hasAttr)
            sql.append(", ");
        sql.append(DBUtils.getObjectFullName(attr, DBPEvaluationContext.DML));
        hasAttr = true;
    }
    sql.append(getLineSeparator()).append("FROM ").append(getEntityName(getSingleEntity()));
    sql.append(getLineSeparator()).append("WHERE ");
    boolean multiKey = keyAttributes.size() > 1;
    if (multiKey)
        sql.append("(");
    hasAttr = false;
    for (DBDAttributeBinding binding : keyAttributes) {
        if (hasAttr)
            sql.append(",");
        sql.append(DBUtils.getObjectFullName(binding.getAttribute(), DBPEvaluationContext.DML));
        hasAttr = true;
    }
    if (multiKey)
        sql.append(")");
    sql.append(" IN (");
    if (multiKey)
        sql.append("\n");
    List<ResultSetRow> selectedRows = getSelectedRows();
    for (int i = 0; i < selectedRows.size(); i++) {
        ResultSetRow firstRow = selectedRows.get(i);
        if (multiKey)
            sql.append("(");
        hasAttr = false;
        for (DBDAttributeBinding binding : keyAttributes) {
            if (hasAttr)
                sql.append(",");
            appendAttributeValue(getController(), sql, binding, firstRow);
            hasAttr = true;
        }
        if (multiKey)
            sql.append(")");
        if (i < selectedRows.size() - 1)
            sql.append(",");
        if (multiKey)
            sql.append("\n");
    }
    sql.append(");\n");
}
Also used : DBSAttributeBase(org.jkiss.dbeaver.model.struct.DBSAttributeBase) ResultSetRow(org.jkiss.dbeaver.ui.controls.resultset.ResultSetRow) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding)

Example 63 with DBDAttributeBinding

use of org.jkiss.dbeaver.model.data.DBDAttributeBinding 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 64 with DBDAttributeBinding

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

the class ResultSetHandlerOpenWith method openResultsWith.

private static void openResultsWith(IResultSetController resultSet, DataTransferProcessorDescriptor processor) {
    ResultSetDataContainerOptions options = new ResultSetDataContainerOptions();
    IResultSetSelection rsSelection = resultSet.getSelection();
    List<ResultSetRow> rsSelectedRows = rsSelection.getSelectedRows();
    List<DBDAttributeBinding> rsSelectedAttributes = rsSelection.getSelectedAttributes();
    if (rsSelectedRows.size() > 1 || rsSelectedAttributes.size() > 1) {
        List<Long> selectedRows = new ArrayList<>();
        for (ResultSetRow selectedRow : rsSelectedRows) {
            selectedRows.add((long) selectedRow.getRowNumber());
        }
        List<String> selectedAttributes = new ArrayList<>();
        for (DBDAttributeBinding attributeBinding : rsSelectedAttributes) {
            selectedAttributes.add(attributeBinding.getName());
        }
        options.setSelectedRows(selectedRows);
        options.setSelectedColumns(selectedAttributes);
    }
    ResultSetDataContainer dataContainer = new ResultSetDataContainer(resultSet, options);
    if (dataContainer.getDataSource() == null) {
        DBWorkbench.getPlatformUI().showError("Open " + processor.getAppName(), ModelMessages.error_not_connected_to_database);
        return;
    }
    DBPPreferenceStore preferenceStore = DBWorkbench.getPlatform().getPreferenceStore();
    String prevActiveApp = preferenceStore.getString(PARAM_ACTIVE_APP);
    if (!CommonUtils.equalObjects(prevActiveApp, processor.getFullId())) {
    // preferenceStore.setValue(PARAM_ACTIVE_APP, processor.getFullId());
    // resultSet.updateEditControls();
    // resultSet.getControl().layout(true);
    }
    AbstractJob exportJob = new AbstractJob("Open " + processor.getAppName()) {

        {
            setUser(true);
            setSystem(false);
        }

        @Override
        protected IStatus run(DBRProgressMonitor monitor) {
            try {
                File tempDir = DBWorkbench.getPlatform().getTempFolder(monitor, "data-files");
                File tempFile = new File(tempDir, new SimpleDateFormat("yyyyMMdd-HHmmss").format(System.currentTimeMillis()) + "." + processor.getAppFileExtension());
                tempFile.deleteOnExit();
                IDataTransferProcessor processorInstance = processor.getInstance();
                if (!(processorInstance instanceof IStreamDataExporter)) {
                    return Status.CANCEL_STATUS;
                }
                IStreamDataExporter exporter = (IStreamDataExporter) processorInstance;
                StreamTransferConsumer consumer = new StreamTransferConsumer();
                StreamConsumerSettings settings = new StreamConsumerSettings();
                settings.setOutputEncodingBOM(false);
                settings.setOpenFolderOnFinish(false);
                settings.setOutputFolder(tempDir.getAbsolutePath());
                settings.setOutputFilePattern(tempFile.getName());
                Map<String, Object> properties = new HashMap<>();
                // Default values from wizard
                IDialogSettings dtSettings = DataTransferWizard.getWizardDialogSettings();
                IDialogSettings procListSection = dtSettings.getSection("processors");
                IDialogSettings procSettings = null;
                if (procListSection != null) {
                    procSettings = procListSection.getSection("stream_consumer:" + processor.getId());
                }
                for (DBPPropertyDescriptor prop : processor.getProperties()) {
                    Object defValue = procSettings == null ? null : procSettings.get(CommonUtils.toString(prop.getId()));
                    properties.put(prop.getId(), defValue != null ? defValue : prop.getDefaultValue());
                }
                // Remove extension property (we specify file name directly)
                properties.remove(StreamConsumerSettings.PROP_FILE_EXTENSION);
                consumer.initTransfer(dataContainer, settings, new IDataTransferConsumer.TransferParameters(processor.isBinaryFormat(), processor.isHTMLFormat()), exporter, properties);
                DBDDataFilter dataFilter = resultSet.getModel().getDataFilter();
                DatabaseTransferProducer producer = new DatabaseTransferProducer(dataContainer, dataFilter);
                DatabaseProducerSettings producerSettings = new DatabaseProducerSettings();
                producerSettings.setExtractType(DatabaseProducerSettings.ExtractType.SINGLE_QUERY);
                producerSettings.setQueryRowCount(false);
                // disable OpenNewconnection by default (#6432)
                producerSettings.setOpenNewConnections(false);
                producerSettings.setSelectedRowsOnly(!CommonUtils.isEmpty(options.getSelectedRows()));
                producerSettings.setSelectedColumnsOnly(!CommonUtils.isEmpty(options.getSelectedColumns()));
                producer.transferData(monitor, consumer, null, producerSettings, null);
                consumer.finishTransfer(monitor, false);
                UIUtils.asyncExec(() -> {
                    if (!UIUtils.launchProgram(tempFile.getAbsolutePath())) {
                        DBWorkbench.getPlatformUI().showError("Open " + processor.getAppName(), "Can't open " + processor.getAppFileExtension() + " file '" + tempFile.getAbsolutePath() + "'");
                    }
                });
            } catch (Exception e) {
                DBWorkbench.getPlatformUI().showError("Error opening in " + processor.getAppName(), null, e);
            }
            return Status.OK_STATUS;
        }
    };
    exportJob.schedule();
}
Also used : DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) StreamConsumerSettings(org.jkiss.dbeaver.tools.transfer.stream.StreamConsumerSettings) DBDDataFilter(org.jkiss.dbeaver.model.data.DBDDataFilter) StreamTransferConsumer(org.jkiss.dbeaver.tools.transfer.stream.StreamTransferConsumer) IDataTransferConsumer(org.jkiss.dbeaver.tools.transfer.IDataTransferConsumer) DBPPreferenceStore(org.jkiss.dbeaver.model.preferences.DBPPreferenceStore) IDataTransferProcessor(org.jkiss.dbeaver.tools.transfer.IDataTransferProcessor) ExecutionException(org.eclipse.core.commands.ExecutionException) DBPPropertyDescriptor(org.jkiss.dbeaver.model.preferences.DBPPropertyDescriptor) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) IDialogSettings(org.eclipse.jface.dialogs.IDialogSettings) DatabaseTransferProducer(org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer) DatabaseProducerSettings(org.jkiss.dbeaver.tools.transfer.database.DatabaseProducerSettings) IStreamDataExporter(org.jkiss.dbeaver.tools.transfer.stream.IStreamDataExporter) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 65 with DBDAttributeBinding

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

the class PlainTextPresentation method printGrid.

private void printGrid(boolean append) {
    DBPPreferenceStore prefs = getController().getPreferenceStore();
    int maxColumnSize = prefs.getInt(ResultSetPreferences.RESULT_TEXT_MAX_COLUMN_SIZE);
    boolean delimLeading = prefs.getBoolean(ResultSetPreferences.RESULT_TEXT_DELIMITER_LEADING);
    boolean delimTrailing = prefs.getBoolean(ResultSetPreferences.RESULT_TEXT_DELIMITER_TRAILING);
    boolean extraSpaces = prefs.getBoolean(ResultSetPreferences.RESULT_TEXT_EXTRA_SPACES);
    this.showNulls = getController().getPreferenceStore().getBoolean(ResultSetPreferences.RESULT_TEXT_SHOW_NULLS);
    DBDDisplayFormat displayFormat = DBDDisplayFormat.safeValueOf(prefs.getString(ResultSetPreferences.RESULT_TEXT_VALUE_FORMAT));
    StringBuilder grid = new StringBuilder(512);
    ResultSetModel model = controller.getModel();
    List<DBDAttributeBinding> attrs = model.getVisibleAttributes();
    List<ResultSetRow> allRows = model.getAllRows();
    int extraSpacesNum = extraSpaces ? 2 : 0;
    if (colWidths == null) {
        // Calculate column widths
        colWidths = new int[attrs.size()];
        for (int i = 0; i < attrs.size(); i++) {
            DBDAttributeBinding attr = attrs.get(i);
            colWidths[i] = getAttributeName(attr).length() + extraSpacesNum;
            if (showNulls && !attr.isRequired()) {
                colWidths[i] = Math.max(colWidths[i], DBConstants.NULL_VALUE_LABEL.length());
            }
            for (ResultSetRow row : allRows) {
                String displayString = getCellString(model, attr, row, displayFormat);
                colWidths[i] = Math.max(colWidths[i], getStringWidth(displayString) + extraSpacesNum);
            }
        }
        for (int i = 0; i < colWidths.length; i++) {
            if (colWidths[i] > maxColumnSize) {
                colWidths[i] = maxColumnSize;
            }
        }
    }
    if (!append) {
        // Print header
        if (delimLeading)
            grid.append("|");
        for (int i = 0; i < attrs.size(); i++) {
            if (i > 0)
                grid.append("|");
            if (extraSpaces)
                grid.append(" ");
            DBDAttributeBinding attr = attrs.get(i);
            String attrName = getAttributeName(attr);
            grid.append(attrName);
            for (int k = colWidths[i] - attrName.length() - extraSpacesNum; k > 0; k--) {
                grid.append(" ");
            }
            if (extraSpaces)
                grid.append(" ");
        }
        if (delimTrailing)
            grid.append("|");
        grid.append("\n");
        // Print header
        if (delimLeading)
            grid.append("|");
        for (int i = 0; i < attrs.size(); i++) {
            if (i > 0)
                grid.append("|");
            for (int k = colWidths[i]; k > 0; k--) {
                grid.append("-");
            }
        }
        if (delimTrailing)
            grid.append("|");
        grid.append("\n");
    }
    // Print rows
    int firstRow = append ? totalRows : 0;
    if (append) {
        grid.append("\n");
    }
    for (int i = firstRow; i < allRows.size(); i++) {
        ResultSetRow row = allRows.get(i);
        if (delimLeading)
            grid.append("|");
        for (int k = 0; k < attrs.size(); k++) {
            if (k > 0)
                grid.append("|");
            DBDAttributeBinding attr = attrs.get(k);
            String displayString = getCellString(model, attr, row, displayFormat);
            if (displayString.length() >= colWidths[k]) {
                displayString = CommonUtils.truncateString(displayString, colWidths[k]);
            }
            int stringWidth = getStringWidth(displayString);
            if (extraSpaces)
                grid.append(" ");
            DBPDataKind dataKind = attr.getDataKind();
            if ((dataKind == DBPDataKind.NUMERIC && rightJustifyNumbers) || (dataKind == DBPDataKind.DATETIME && rightJustifyDateTime)) {
                // Right justify value
                for (int j = colWidths[k] - stringWidth - extraSpacesNum; j > 0; j--) {
                    grid.append(" ");
                }
                grid.append(displayString);
            } else {
                grid.append(displayString);
                for (int j = colWidths[k] - stringWidth - extraSpacesNum; j > 0; j--) {
                    grid.append(" ");
                }
            }
            if (extraSpaces)
                grid.append(" ");
        }
        if (delimTrailing)
            grid.append("|");
        grid.append("\n");
    }
    // cut last line feed
    grid.setLength(grid.length() - 1);
    if (append) {
        text.append(grid.toString());
    } else {
        text.setText(grid.toString());
    }
    totalRows = allRows.size();
}
Also used : DBDDisplayFormat(org.jkiss.dbeaver.model.data.DBDDisplayFormat) DBPDataKind(org.jkiss.dbeaver.model.DBPDataKind) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBPPreferenceStore(org.jkiss.dbeaver.model.preferences.DBPPreferenceStore)

Aggregations

DBDAttributeBinding (org.jkiss.dbeaver.model.data.DBDAttributeBinding)147 ArrayList (java.util.ArrayList)32 DBException (org.jkiss.dbeaver.DBException)29 ResultSetRow (org.jkiss.dbeaver.ui.controls.resultset.ResultSetRow)24 DBDContent (org.jkiss.dbeaver.model.data.DBDContent)23 DBDContentStorage (org.jkiss.dbeaver.model.data.DBDContentStorage)23 List (java.util.List)18 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)16 DBSAttributeBase (org.jkiss.dbeaver.model.struct.DBSAttributeBase)14 Reader (java.io.Reader)13 PrintWriter (java.io.PrintWriter)12 GridData (org.eclipse.swt.layout.GridData)12 Nullable (org.jkiss.code.Nullable)12 AbstractJob (org.jkiss.dbeaver.model.runtime.AbstractJob)12 Date (java.util.Date)10 SWT (org.eclipse.swt.SWT)10 NotNull (org.jkiss.code.NotNull)10 DBDDataFilter (org.jkiss.dbeaver.model.data.DBDDataFilter)10 DBPPreferenceStore (org.jkiss.dbeaver.model.preferences.DBPPreferenceStore)10 DBSEntityAttribute (org.jkiss.dbeaver.model.struct.DBSEntityAttribute)10