Search in sources :

Example 21 with DBDAttributeBinding

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

the class ValidateUniqueKeyUsageDialog method useAllColumns.

private static boolean useAllColumns(ResultSetViewer viewer) {
    // Use all columns
    final DBDRowIdentifier identifier = viewer.getVirtualEntityIdentifier();
    DBVEntityConstraint constraint = (DBVEntityConstraint) identifier.getUniqueKey();
    List<DBSEntityAttribute> uniqueColumns = new ArrayList<>();
    for (DBDAttributeBinding binding : viewer.getModel().getAttributes()) {
        if (binding.getEntityAttribute() != null) {
            uniqueColumns.add(binding.getEntityAttribute());
        }
    }
    if (uniqueColumns.isEmpty()) {
        DBWorkbench.getPlatformUI().showError("Use All Columns", "No valid columns found for unique key");
        return false;
    }
    constraint.setAttributes(uniqueColumns);
    constraint.setUseAllColumns(true);
    try {
        identifier.reloadAttributes(new VoidProgressMonitor(), viewer.getModel().getAttributes());
    } catch (DBException e) {
        DBWorkbench.getPlatformUI().showError("Use All Columns", "Can't reload unique columns", e);
        return false;
    }
    return true;
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBSEntityAttribute(org.jkiss.dbeaver.model.struct.DBSEntityAttribute) ArrayList(java.util.ArrayList) VoidProgressMonitor(org.jkiss.dbeaver.model.runtime.VoidProgressMonitor) DBVEntityConstraint(org.jkiss.dbeaver.model.virtual.DBVEntityConstraint) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBDRowIdentifier(org.jkiss.dbeaver.model.data.DBDRowIdentifier)

Example 22 with DBDAttributeBinding

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

the class FilterSettingsDialog method createDialogArea.

@Override
protected Control createDialogArea(Composite parent) {
    getShell().setText(ResultSetMessages.controls_resultset_filter_title);
    getShell().setImage(DBeaverIcons.getImage(UIIcon.FILTER));
    Composite composite = (Composite) super.createDialogArea(parent);
    TabFolder tabFolder = new TabFolder(composite, SWT.NONE);
    tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
    TreeColumn criteriaColumn;
    {
        Composite columnsGroup = UIUtils.createPlaceholder(tabFolder, 1);
        FilteredTree filteredTree = new FilteredTree(columnsGroup, SWT.SINGLE | SWT.FULL_SELECTION | SWT.CHECK, new NamedObjectPatternFilter(), true) {

            @Override
            protected TreeViewer doCreateTreeViewer(Composite parent, int style) {
                columnsViewer = new CheckboxTreeViewer(parent, style);
                return columnsViewer;
            }
        };
        columnsViewer.setContentProvider(new TreeContentProvider() {

            @Override
            public Object[] getChildren(Object parentElement) {
                final java.util.List<DBDAttributeBinding> nestedBindings = ((DBDAttributeBinding) parentElement).getNestedBindings();
                if (nestedBindings == null || nestedBindings.isEmpty()) {
                    return null;
                }
                final DBDAttributeBinding[] res = nestedBindings.toArray(new DBDAttributeBinding[0]);
                Arrays.sort(res, activeSorter);
                return res;
            }

            @Override
            public boolean hasChildren(Object element) {
                final java.util.List<DBDAttributeBinding> nestedBindings = ((DBDAttributeBinding) element).getNestedBindings();
                return nestedBindings != null && !nestedBindings.isEmpty();
            }
        });
        columnsViewer.setLabelProvider(new ColumnLabelProvider());
        columnsViewer.setCheckStateProvider(new CheckStateProvider());
        final Tree columnsTree = columnsViewer.getTree();
        GridData gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = 300;
        columnsTree.setLayoutData(gd);
        columnsTree.setHeaderVisible(true);
        columnsTree.setLinesVisible(true);
        UIUtils.createTreeColumn(columnsTree, SWT.LEFT, ResultSetMessages.controls_resultset_filter_column_name);
        UIUtils.createTreeColumn(columnsTree, SWT.LEFT, "#");
        UIUtils.createTreeColumn(columnsTree, SWT.LEFT, ResultSetMessages.controls_resultset_filter_column_order);
        criteriaColumn = UIUtils.createTreeColumn(columnsTree, SWT.LEFT, ResultSetMessages.controls_resultset_filter_column_criteria);
        treeEditor = new FilterSettingsTreeEditor(columnsTree);
        columnsViewer.addCheckStateListener(event -> {
            DBDAttributeConstraint constraint = getBindingConstraint((DBDAttributeBinding) event.getElement());
            constraint.setVisible(event.getChecked());
        });
        {
            ToolBar toolbar = new ToolBar(columnsGroup, SWT.HORIZONTAL | SWT.RIGHT);
            gd = new GridData(GridData.FILL_HORIZONTAL);
            gd.verticalIndent = 3;
            toolbar.setLayoutData(gd);
            toolbar.setLayout(new FillLayout());
            moveTopButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_to_top, UIIcon.ARROW_TOP, () -> {
                int selectionIndex = getSelectionIndex(columnsViewer.getTree());
                moveColumns(selectionIndex, 0);
            });
            moveTopButton.setEnabled(false);
            moveUpButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_up, UIIcon.ARROW_UP, () -> {
                int selectionIndex = getSelectionIndex(columnsViewer.getTree());
                swapColumns(selectionIndex, selectionIndex - 1);
            });
            moveUpButton.setEnabled(false);
            moveDownButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_down, UIIcon.ARROW_DOWN, () -> {
                int selectionIndex = getSelectionIndex(columnsViewer.getTree());
                swapColumns(selectionIndex, selectionIndex + 1);
            });
            moveDownButton.setEnabled(false);
            moveBottomButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_move_to_bottom, UIIcon.ARROW_BOTTOM, () -> {
                int selectionIndex = getSelectionIndex(columnsViewer.getTree());
                moveColumns(selectionIndex, getItemsCount() - 1);
            });
            moveBottomButton.setEnabled(false);
            UIUtils.createToolBarSeparator(toolbar, SWT.VERTICAL);
            createToolItem(toolbar, ResultSetMessages.dialog_toolbar_sort, UIIcon.SORT, () -> {
                attributes.sort(ALPHA_SORTER);
                for (int i = 0; i < attributes.size(); i++) {
                    final DBDAttributeConstraint constraint = getBindingConstraint(attributes.get(i));
                    constraint.setVisualPosition(i);
                }
                columnsViewer.refresh();
            });
            UIUtils.createToolBarSeparator(toolbar, SWT.VERTICAL);
            ToolItem showAllButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_show_all, null, () -> {
                for (DBDAttributeConstraint constraint : constraints) {
                    constraint.setVisible(true);
                }
                columnsViewer.refresh();
            });
            showAllButton.setImage(UIUtils.getShardImage(ISharedImages.IMG_ETOOL_DEF_PERSPECTIVE));
            ToolItem showNoneButton = createToolItem(toolbar, ResultSetMessages.dialog_toolbar_show_none, null, () -> {
                for (DBDAttributeConstraint constraint : constraints) {
                    constraint.setVisible(false);
                }
                columnsViewer.refresh();
            });
            showNoneButton.setImage(UIUtils.getShardImage(ISharedImages.IMG_ELCL_REMOVEALL));
            createToolItem(toolbar, ResultSetMessages.dialog_toolbar_reset, UIIcon.REFRESH, () -> {
                dataFilter.reset();
                constraints = new ArrayList<>(dataFilter.getConstraints());
                refreshData();
                // columnsViewer.refresh();
                // $NON-NLS-1$
                orderText.setText("");
                // $NON-NLS-1$
                whereText.setText("");
            });
            columnsViewer.addSelectionChangedListener(event -> {
                int selectionIndex = getSelectionIndex(columnsViewer.getTree());
                moveTopButton.setEnabled(selectionIndex > 0);
                moveUpButton.setEnabled(selectionIndex > 0);
                moveDownButton.setEnabled(selectionIndex >= 0 && selectionIndex < getItemsCount() - 1);
                moveBottomButton.setEnabled(selectionIndex >= 0 && selectionIndex < getItemsCount() - 1);
            });
        }
        TabItem libsTab = new TabItem(tabFolder, SWT.NONE);
        libsTab.setText(ResultSetMessages.controls_resultset_filter_group_columns);
        libsTab.setToolTipText("Set criteria and order for individual column(s)");
        libsTab.setControl(columnsGroup);
    }
    createCustomFilters(tabFolder);
    // Fill columns
    columnsViewer.setInput(attributes);
    refreshData();
    // Pack UI
    UIUtils.asyncExec(() -> UIUtils.packColumns(columnsViewer.getTree(), true, new float[] { .45f, .05f, .05f, .45f }));
    if (criteriaColumn.getWidth() < 200) {
        criteriaColumn.setWidth(200);
    }
    if (!resultSetViewer.supportsDataFilter()) {
        Label warnLabel = new Label(composite, SWT.NONE);
        warnLabel.setText(ResultSetMessages.controls_resultset_filter_warning_custom_order_disabled);
        warnLabel.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_RED));
    }
    return parent;
}
Also used : java.util(java.util) Image(org.eclipse.swt.graphics.Image) CustomTreeEditor(org.jkiss.dbeaver.ui.controls.CustomTreeEditor) ControlEnableState(org.eclipse.jface.dialogs.ControlEnableState) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) IDialogSettings(org.eclipse.jface.dialogs.IDialogSettings) Nullable(org.jkiss.code.Nullable) DBDDataFilter(org.jkiss.dbeaver.model.data.DBDDataFilter) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) NotNull(org.jkiss.code.NotNull) FilteredTree(org.eclipse.ui.dialogs.FilteredTree) DBeaverIcons(org.jkiss.dbeaver.ui.DBeaverIcons) UIUtils(org.jkiss.dbeaver.ui.UIUtils) UIIcon(org.jkiss.dbeaver.ui.UIIcon) ResultSetMessages(org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages) GridData(org.eclipse.swt.layout.GridData) FillLayout(org.eclipse.swt.layout.FillLayout) HelpEnabledDialog(org.jkiss.dbeaver.ui.dialogs.HelpEnabledDialog) TreeContentProvider(org.jkiss.dbeaver.ui.controls.TreeContentProvider) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) GeneralUtils(org.jkiss.dbeaver.utils.GeneralUtils) CommonUtils(org.jkiss.utils.CommonUtils) DBValueFormatting(org.jkiss.dbeaver.model.DBValueFormatting) DBDAttributeConstraint(org.jkiss.dbeaver.model.data.DBDAttributeConstraint) org.eclipse.swt.widgets(org.eclipse.swt.widgets) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) org.eclipse.jface.viewers(org.eclipse.jface.viewers) ISharedImages(org.eclipse.ui.ISharedImages) List(java.util.List) DBIcon(org.jkiss.dbeaver.model.DBIcon) SWT(org.eclipse.swt.SWT) IHelpContextIds(org.jkiss.dbeaver.ui.IHelpContextIds) SQLUtils(org.jkiss.dbeaver.model.sql.SQLUtils) SelectionEvent(org.eclipse.swt.events.SelectionEvent) GridLayout(org.eclipse.swt.layout.GridLayout) NamedObjectPatternFilter(org.jkiss.dbeaver.ui.controls.NamedObjectPatternFilter) DBDAttributeConstraint(org.jkiss.dbeaver.model.data.DBDAttributeConstraint) FilteredTree(org.eclipse.ui.dialogs.FilteredTree) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) FilteredTree(org.eclipse.ui.dialogs.FilteredTree) NamedObjectPatternFilter(org.jkiss.dbeaver.ui.controls.NamedObjectPatternFilter) FillLayout(org.eclipse.swt.layout.FillLayout) DBDAttributeConstraint(org.jkiss.dbeaver.model.data.DBDAttributeConstraint) TreeContentProvider(org.jkiss.dbeaver.ui.controls.TreeContentProvider) java.util(java.util) GridData(org.eclipse.swt.layout.GridData)

Example 23 with DBDAttributeBinding

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

the class ResultSetFilterPanel method getProposals.

@Override
public IContentProposal[] getProposals(String contents, int position) {
    if (!viewer.getPreferenceStore().getBoolean(ResultSetPreferences.RESULT_SET_FILTER_AUTO_COMPLETE_PROPOSIAL)) {
        return null;
    }
    SQLSyntaxManager syntaxManager = new SQLSyntaxManager();
    DBPDataSource dataSource = viewer.getDataSource();
    if (dataSource != null) {
        syntaxManager.init(dataSource);
    }
    SQLWordPartDetector wordDetector = new SQLWordPartDetector(new Document(contents), syntaxManager, position);
    String word = wordDetector.getFullWord();
    final List<IContentProposal> proposals = new ArrayList<>();
    if (CommonUtils.isEmptyTrimmed(word))
        word = contents;
    word = word.toLowerCase(Locale.ENGLISH);
    String attrName = word;
    final DBRRunnableWithProgress reader = monitor -> {
        DBDAttributeBinding[] attributes = viewer.getModel().getAttributes();
        for (DBDAttributeBinding attribute : attributes) {
            if (attribute.isCustom()) {
                continue;
            }
            final String name = DBUtils.getUnQuotedIdentifier(attribute.getDataSource(), attribute.getName());
            if (CommonUtils.isEmpty(attrName) || name.toLowerCase(Locale.ENGLISH).startsWith(attrName)) {
                final String content = DBUtils.getQuotedIdentifier(attribute) + " ";
                proposals.add(new ContentProposalExt(content, attribute.getName(), DBInfoUtils.makeObjectDescription(monitor, attribute.getAttribute(), false), content.length(), DBValueFormatting.getObjectImage(attribute)));
            }
        }
    };
    SystemJob searchJob = new SystemJob("Extract attribute proposals", reader);
    searchJob.schedule();
    UIUtils.waitJobCompletion(searchJob);
    String[] filterKeywords = { SQLConstants.KEYWORD_AND, SQLConstants.KEYWORD_OR, SQLConstants.KEYWORD_IS, SQLConstants.KEYWORD_NOT, SQLConstants.KEYWORD_NULL };
    for (String kw : filterKeywords) {
        if (attrName.isEmpty() || kw.startsWith(attrName.toUpperCase())) {
            if (dataSource != null) {
                kw = dataSource.getSQLDialect().storesUnquotedCase().transform(kw);
            }
            proposals.add(new ContentProposal(kw + " ", kw + ": SQL expression keyword"));
        }
    }
    return proposals.toArray(new IContentProposal[0]);
}
Also used : ResultSetHandlerMain(org.jkiss.dbeaver.ui.controls.resultset.handler.ResultSetHandlerMain) org.jkiss.dbeaver.ui(org.jkiss.dbeaver.ui) StyledText(org.eclipse.swt.custom.StyledText) IWorkbenchCommandConstants(org.eclipse.ui.IWorkbenchCommandConstants) DBDDataFilter(org.jkiss.dbeaver.model.data.DBDDataFilter) ContentProposal(org.eclipse.jface.fieldassist.ContentProposal) Matcher(java.util.regex.Matcher) PartInitException(org.eclipse.ui.PartInitException) Locale(java.util.Locale) ContentProposalAdapter(org.eclipse.jface.fieldassist.ContentProposalAdapter) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) SystemJob(org.jkiss.dbeaver.model.runtime.SystemJob) IAdaptable(org.eclipse.core.runtime.IAdaptable) CommonUtils(org.jkiss.utils.CommonUtils) org.eclipse.swt.graphics(org.eclipse.swt.graphics) DBDAttributeConstraint(org.jkiss.dbeaver.model.data.DBDAttributeConstraint) StyledTextUtils(org.jkiss.dbeaver.ui.controls.StyledTextUtils) Collection(java.util.Collection) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBStyles(org.jkiss.dbeaver.ui.css.DBStyles) ContentAssistUtils(org.jkiss.dbeaver.ui.contentassist.ContentAssistUtils) List(java.util.List) DBException(org.jkiss.dbeaver.DBException) SWT(org.eclipse.swt.SWT) SQLSyntaxManager(org.jkiss.dbeaver.model.sql.SQLSyntaxManager) SQLUtils(org.jkiss.dbeaver.model.sql.SQLUtils) Pattern(java.util.regex.Pattern) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) ContentProposalExt(org.jkiss.dbeaver.ui.contentassist.ContentProposalExt) DBWorkbench(org.jkiss.dbeaver.runtime.DBWorkbench) SQLConstants(org.jkiss.dbeaver.model.sql.SQLConstants) Nullable(org.jkiss.code.Nullable) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) NotNull(org.jkiss.code.NotNull) UIServiceSQL(org.jkiss.dbeaver.runtime.ui.UIServiceSQL) ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) Log(org.jkiss.dbeaver.Log) ResultSetMessages(org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages) GridData(org.eclipse.swt.layout.GridData) FillLayout(org.eclipse.swt.layout.FillLayout) org.jkiss.dbeaver.model(org.jkiss.dbeaver.model) DBSEntity(org.jkiss.dbeaver.model.struct.DBSEntity) org.eclipse.swt.events(org.eclipse.swt.events) IContentProposalProvider(org.eclipse.jface.fieldassist.IContentProposalProvider) IUndoManager(org.eclipse.jface.text.IUndoManager) TextEditorUtils(org.jkiss.dbeaver.ui.editors.TextEditorUtils) org.eclipse.swt.widgets(org.eclipse.swt.widgets) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode) TextViewerUndoManager(org.eclipse.jface.text.TextViewerUndoManager) CSSUtils(org.jkiss.dbeaver.ui.css.CSSUtils) TextViewer(org.eclipse.jface.text.TextViewer) DBSDataContainer(org.jkiss.dbeaver.model.struct.DBSDataContainer) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) GridLayout(org.eclipse.swt.layout.GridLayout) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) ContentProposalExt(org.jkiss.dbeaver.ui.contentassist.ContentProposalExt) ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) SystemJob(org.jkiss.dbeaver.model.runtime.SystemJob) ContentProposal(org.eclipse.jface.fieldassist.ContentProposal) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) SQLSyntaxManager(org.jkiss.dbeaver.model.sql.SQLSyntaxManager) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress)

Example 24 with DBDAttributeBinding

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

the class DataExporterXLSX method printHeader.

private void printHeader(DBCResultSet resultSet, Worksheet wsh) throws DBException {
    boolean hasDescription = false;
    if (showDescription) {
        // Read bindings to extract column descriptions
        boolean bindingsOk = true;
        DBDAttributeBindingMeta[] bindings = new DBDAttributeBindingMeta[columns.length];
        for (int i = 0; i < columns.length; i++) {
            if (columns[i] instanceof DBDAttributeBindingMeta) {
                bindings[i] = (DBDAttributeBindingMeta) columns[i];
            } else {
                bindingsOk = false;
                break;
            }
        }
        if (bindingsOk) {
            DBSEntity sourceEntity = null;
            if (getSite().getSource() instanceof DBSEntity) {
                sourceEntity = (DBSEntity) getSite().getSource();
            }
            DBExecUtils.bindAttributes(resultSet.getSession(), sourceEntity, resultSet, bindings, null);
        }
        for (DBDAttributeBinding column : columns) {
            if (!CommonUtils.isEmpty(column.getDescription())) {
                hasDescription = true;
                break;
            }
        }
    }
    SXSSFSheet sh = (SXSSFSheet) wsh.getSh();
    Row row = sh.createRow(wsh.getCurrentRow());
    int startCol = rowNumber ? 1 : 0;
    sh.trackAllColumnsForAutoSizing();
    for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
        DBDAttributeBinding column = columns[i];
        String colName = column.getLabel();
        if (CommonUtils.isEmpty(colName)) {
            colName = column.getName();
        }
        Cell cell = row.createCell(i + startCol, CellType.STRING);
        cell.setCellValue(colName);
        cell.setCellStyle(styleHeader);
    }
    if (hasDescription) {
        wsh.incRow();
        Row descRow = sh.createRow(wsh.getCurrentRow());
        for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
            Cell descCell = descRow.createCell(i + startCol, CellType.STRING);
            String description = columns[i].getDescription();
            if (CommonUtils.isEmpty(description)) {
                description = "";
            }
            descCell.setCellValue(description);
            descCell.setCellStyle(styleHeader);
        }
    }
    for (int i = 0, columnsSize = columns.length; i < columnsSize; i++) {
        sh.autoSizeColumn(i);
    }
    wsh.incRow();
    try {
        sh.flushRows();
    } catch (IOException e) {
        throw new DBException("Error processing header", e);
    }
    sh.untrackAllColumnsForAutoSizing();
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBDAttributeBindingMeta(org.jkiss.dbeaver.model.data.DBDAttributeBindingMeta) DBSEntity(org.jkiss.dbeaver.model.struct.DBSEntity) IOException(java.io.IOException) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) SXSSFSheet(org.apache.poi.xssf.streaming.SXSSFSheet)

Example 25 with DBDAttributeBinding

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

the class OpenSpreadsheetHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IResultSetController resultSet = ResultSetHandlerMain.getActiveResultSet(HandlerUtil.getActivePart(event));
    if (resultSet == null) {
        DBWorkbench.getPlatformUI().showError("Open Excel", "No active results viewer");
        return null;
    }
    ResultSetDataContainerOptions options = new ResultSetDataContainerOptions();
    IResultSetSelection rsSelection = resultSet.getSelection();
    List<ResultSetRow> rsSelectedRows = rsSelection.getSelectedRows();
    if (rsSelectedRows.size() > 1) {
        List<Long> selectedRows = new ArrayList<>();
        for (ResultSetRow selectedRow : rsSelectedRows) {
            selectedRows.add((long) selectedRow.getRowNumber());
        }
        List<String> selectedAttributes = new ArrayList<>();
        for (DBDAttributeBinding attributeBinding : rsSelection.getSelectedAttributes()) {
            selectedAttributes.add(attributeBinding.getName());
        }
        options.setSelectedRows(selectedRows);
        options.setSelectedColumns(selectedAttributes);
    }
    ResultSetDataContainer dataContainer = new ResultSetDataContainer(resultSet, options);
    if (dataContainer.getDataSource() == null) {
        DBWorkbench.getPlatformUI().showError("Open Excel", ModelMessages.error_not_connected_to_database);
        return null;
    }
    AbstractJob exportJob = new AbstractJob("Open Excel") {

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

        @Override
        protected IStatus run(DBRProgressMonitor monitor) {
            try {
                File tempDir = DBWorkbench.getPlatform().getTempFolder(monitor, "office-files");
                File tempFile = new File(tempDir, CommonUtils.escapeFileName(CommonUtils.truncateString(dataContainer.getName(), 32)) + "." + new SimpleDateFormat("yyyyMMdd-HHmmss").format(System.currentTimeMillis()) + ".xlsx");
                tempFile.deleteOnExit();
                StreamExporterAbstract exporter = new DataExporterXLSX();
                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 = DataExporterXLSX.getDefaultProperties();
                consumer.initTransfer(dataContainer, settings, new IDataTransferConsumer.TransferParameters(true, false), 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);
                producerSettings.setSelectedRowsOnly(true);
                producerSettings.setSelectedColumnsOnly(true);
                producer.transferData(monitor, consumer, null, producerSettings, null);
                consumer.finishTransfer(monitor, false);
                UIUtils.asyncExec(() -> {
                    if (!UIUtils.launchProgram(tempFile.getAbsolutePath())) {
                        DBWorkbench.getPlatformUI().showError("Open XLSX", "Can't open XLSX file '" + tempFile.getAbsolutePath() + "'");
                    }
                });
            } catch (Exception e) {
                DBWorkbench.getPlatformUI().showError("Error opening in Excel", null, e);
            }
            return Status.OK_STATUS;
        }
    };
    exportJob.schedule();
    return null;
}
Also used : StreamExporterAbstract(org.jkiss.dbeaver.tools.transfer.stream.exporter.StreamExporterAbstract) ArrayList(java.util.ArrayList) 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) ExecutionException(org.eclipse.core.commands.ExecutionException) DataExporterXLSX(org.jkiss.dbeaver.data.office.export.DataExporterXLSX) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DatabaseTransferProducer(org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer) DatabaseProducerSettings(org.jkiss.dbeaver.tools.transfer.database.DatabaseProducerSettings) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

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