Search in sources :

Example 21 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class DataSourceHandler method connectToDataSource.

/**
     * Connects datasource
     * @param monitor progress monitor or null. If nul then new job will be started
     * @param dataSourceContainer    container to connect
     * @param onFinish               finish handler
     */
public static void connectToDataSource(@Nullable DBRProgressMonitor monitor, @NotNull DBPDataSourceContainer dataSourceContainer, @Nullable final DBRProgressListener onFinish) {
    if (dataSourceContainer instanceof DataSourceDescriptor && !dataSourceContainer.isConnected()) {
        final DataSourceDescriptor dataSourceDescriptor = (DataSourceDescriptor) dataSourceContainer;
        if (!ArrayUtils.isEmpty(Job.getJobManager().find(dataSourceDescriptor))) {
            // Already connecting/disconnecting - just return
            return;
        }
        final ConnectJob connectJob = new ConnectJob(dataSourceDescriptor);
        final JobChangeAdapter jobChangeAdapter = new JobChangeAdapter() {

            @Override
            public void done(IJobChangeEvent event) {
                IStatus result = connectJob.getConnectStatus();
                if (result.isOK()) {
                    if (!dataSourceDescriptor.isSavePassword()) {
                    // Rest password back to null
                    // TODO: to be correct we need to reset password info.
                    // but we need a password to open isolated contexts (e.g. for data export)
                    // Currently it is not possible to ask for password from isolation context opening
                    // procedure. We need to do something here...
                    //dataSourceDescriptor.getConnectionConfiguration().setUserName(oldName);
                    //dataSourceDescriptor.getConnectionConfiguration().setUserPassword(oldPassword);
                    }
                }
                if (onFinish != null) {
                    onFinish.onTaskFinished(result);
                } else if (!result.isOK()) {
                    DBUserInterface.getInstance().showError(connectJob.getName(), //NLS.bind(CoreMessages.runtime_jobs_connect_status_error, dataSourceContainer.getName()),
                    null, result);
                }
            }
        };
        if (monitor != null) {
            connectJob.runSync(monitor);
            jobChangeAdapter.done(new IJobChangeEvent() {

                @Override
                public long getDelay() {
                    return 0;
                }

                @Override
                public Job getJob() {
                    return connectJob;
                }

                @Override
                public IStatus getResult() {
                    return connectJob.getConnectStatus();
                }

                public IStatus getJobGroupResult() {
                    return null;
                }
            });
        } else {
            connectJob.addJobChangeListener(jobChangeAdapter);
            // Schedule in UI because connect may be initiated during application startup
            // and UI is still not initiated. In this case no progress dialog will appear
            // to be sure run in UI async
            DBeaverUI.asyncExec(new Runnable() {

                @Override
                public void run() {
                    connectJob.schedule();
                }
            });
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) ConnectJob(org.jkiss.dbeaver.runtime.jobs.ConnectJob) JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent) DisconnectJob(org.jkiss.dbeaver.runtime.jobs.DisconnectJob) ConnectJob(org.jkiss.dbeaver.runtime.jobs.ConnectJob) Job(org.eclipse.core.runtime.jobs.Job) DataSourceDescriptor(org.jkiss.dbeaver.registry.DataSourceDescriptor)

Example 22 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class SQLQueryJob method run.

@Override
protected IStatus run(DBRProgressMonitor monitor) {
    RuntimeUtils.setThreadName("SQL script execution");
    statistics = new DBCStatistics();
    try {
        DBCExecutionContext context = getExecutionContext();
        DBCTransactionManager txnManager = DBUtils.getTransactionManager(context);
        DBCExecutionPurpose purpose = queries.size() > 1 ? DBCExecutionPurpose.USER_SCRIPT : DBCExecutionPurpose.USER;
        try (DBCSession session = context.openSession(monitor, purpose, "SQL Query")) {
            // Set transaction settings (only if autocommit is off)
            QMUtils.getDefaultHandler().handleScriptBegin(session);
            boolean oldAutoCommit = txnManager == null || txnManager.isAutoCommit();
            boolean newAutoCommit = (commitType == SQLScriptCommitType.AUTOCOMMIT);
            if (txnManager != null && !oldAutoCommit && newAutoCommit) {
                txnManager.setAutoCommit(monitor, true);
            }
            monitor.beginTask(this.getName(), queries.size());
            // Notify job start
            if (listener != null) {
                try {
                    listener.onStartScript();
                } catch (Exception e) {
                    log.error(e);
                }
            }
            resultSetNumber = 0;
            for (int queryNum = 0; queryNum < queries.size(); ) {
                // Execute query
                SQLQuery query = queries.get(queryNum);
                fetchResultSetNumber = resultSetNumber;
                boolean runNext = executeSingleQuery(session, query, true);
                if (!runNext) {
                    // Ask to continue
                    if (lastError != null) {
                        log.error(lastError);
                    }
                    boolean isQueue = queryNum < queries.size() - 1;
                    ExecutionQueueErrorResponse response = ExecutionQueueErrorJob.showError(isQueue ? "SQL script execution" : "SQL query execution", lastError, isQueue);
                    boolean stopScript = false;
                    switch(response) {
                        case STOP:
                            // just stop execution
                            stopScript = true;
                            break;
                        case RETRY:
                            // just make it again
                            continue;
                        case IGNORE:
                            // Just do nothing
                            break;
                        case IGNORE_ALL:
                            errorHandling = SQLScriptErrorHandling.IGNORE;
                            break;
                    }
                    if (stopScript) {
                        break;
                    }
                }
                // Check monitor
                if (monitor.isCanceled()) {
                    break;
                }
                monitor.worked(1);
                queryNum++;
            }
            showExecutionResult(session);
            monitor.done();
            // Commit data
            if (txnManager != null && !oldAutoCommit && commitType != SQLScriptCommitType.AUTOCOMMIT) {
                if (lastError == null || errorHandling == SQLScriptErrorHandling.STOP_COMMIT) {
                    if (commitType != SQLScriptCommitType.NO_COMMIT) {
                        monitor.beginTask("Commit data", 1);
                        txnManager.commit(session);
                        monitor.done();
                    }
                } else {
                    monitor.beginTask("Rollback data", 1);
                    txnManager.rollback(session, null);
                    monitor.done();
                }
            }
            // Restore transactions settings
            if (txnManager != null && !oldAutoCommit && newAutoCommit) {
                txnManager.setAutoCommit(monitor, false);
            }
            QMUtils.getDefaultHandler().handleScriptEnd(session);
            // Return success
            return new Status(Status.OK, DBeaverCore.getCorePluginID(), "SQL job completed");
        }
    } catch (Throwable ex) {
        return new Status(Status.ERROR, DBeaverCore.getCorePluginID(), "Error during SQL job execution: " + ex.getMessage());
    } finally {
        // Notify job end
        if (listener != null) {
            try {
                listener.onEndScript(statistics, lastError != null);
            } catch (Exception e) {
                log.error(e);
            }
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ExecutionQueueErrorResponse(org.jkiss.dbeaver.ui.dialogs.exec.ExecutionQueueErrorResponse) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) DBException(org.jkiss.dbeaver.DBException)

Example 23 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class SearchMetadataPage method createControl.

@Override
public void createControl(Composite parent) {
    super.createControl(parent);
    initializeDialogUnits(parent);
    Composite searchGroup = new Composite(parent, SWT.NONE);
    searchGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
    searchGroup.setLayout(new GridLayout(3, false));
    setControl(searchGroup);
    UIUtils.createControlLabel(searchGroup, CoreMessages.dialog_search_objects_label_object_name);
    searchText = new Combo(searchGroup, SWT.DROP_DOWN);
    searchText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    if (nameMask != null) {
        searchText.setText(nameMask);
    }
    for (String history : searchHistory) {
        searchText.add(history);
    }
    searchText.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            nameMask = searchText.getText();
            updateEnablement();
        }
    });
    Composite optionsGroup = new SashForm(searchGroup, SWT.NONE);
    GridLayout layout = new GridLayout(2, true);
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    optionsGroup.setLayout(layout);
    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.horizontalSpan = 3;
    optionsGroup.setLayoutData(gd);
    {
        final DBeaverCore core = DBeaverCore.getInstance();
        Group sourceGroup = UIUtils.createControlGroup(optionsGroup, CoreMessages.dialog_search_objects_group_objects_source, 1, GridData.FILL_BOTH, 0);
        gd = new GridData(GridData.FILL_BOTH);
        //gd.heightHint = 300;
        sourceGroup.setLayoutData(gd);
        final DBNProject projectNode = core.getNavigatorModel().getRoot().getProject(core.getProjectRegistry().getActiveProject());
        DBNNode rootNode = projectNode == null ? core.getNavigatorModel().getRoot() : projectNode.getDatabases();
        dataSourceTree = new DatabaseNavigatorTree(sourceGroup, rootNode, SWT.SINGLE);
        gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = 300;
        dataSourceTree.setLayoutData(gd);
        dataSourceTree.getViewer().addFilter(new ViewerFilter() {

            @Override
            public boolean select(Viewer viewer, Object parentElement, Object element) {
                if (element instanceof TreeLoadNode) {
                    return true;
                }
                if (element instanceof DBNNode) {
                    if (element instanceof DBNDatabaseFolder) {
                        DBNDatabaseFolder folder = (DBNDatabaseFolder) element;
                        Class<? extends DBSObject> folderItemsClass = folder.getChildrenClass();
                        return folderItemsClass != null && DBSObjectContainer.class.isAssignableFrom(folderItemsClass);
                    }
                    if (element instanceof DBNLocalFolder || element instanceof DBNProjectDatabases || element instanceof DBNDataSource || (element instanceof DBSWrapper && ((DBSWrapper) element).getObject() instanceof DBSObjectContainer)) {
                        return true;
                    }
                }
                return false;
            }
        });
        dataSourceTree.getViewer().addSelectionChangedListener(new ISelectionChangedListener() {

            @Override
            public void selectionChanged(SelectionChangedEvent event) {
                fillObjectTypes();
                updateEnablement();
                IStructuredSelection structSel = (IStructuredSelection) event.getSelection();
                Object object = structSel.isEmpty() ? null : structSel.getFirstElement();
                if (object instanceof DBNNode) {
                    for (DBNNode node = (DBNNode) object; node != null; node = node.getParentNode()) {
                        if (node instanceof DBNDataSource) {
                            DBNDataSource dsNode = (DBNDataSource) node;
                            dsNode.initializeNode(null, new DBRProgressListener() {

                                @Override
                                public void onTaskFinished(IStatus status) {
                                    if (status.isOK()) {
                                        DBeaverUI.asyncExec(new Runnable() {

                                            @Override
                                            public void run() {
                                                if (!dataSourceTree.isDisposed()) {
                                                    fillObjectTypes();
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                            break;
                        }
                    }
                }
            }
        });
    }
    {
        Group settingsGroup = UIUtils.createControlGroup(optionsGroup, "Settings", 2, GridData.FILL_BOTH, 0);
        gd = new GridData(GridData.FILL_BOTH);
        gd.heightHint = 300;
        settingsGroup.setLayoutData(gd);
        {
            //new Label(searchGroup, SWT.NONE);
            UIUtils.createControlLabel(settingsGroup, CoreMessages.dialog_search_objects_label_name_match);
            final Combo matchCombo = new Combo(settingsGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
            matchCombo.add(CoreMessages.dialog_search_objects_combo_starts_with, SearchMetadataConstants.MATCH_INDEX_STARTS_WITH);
            matchCombo.add(CoreMessages.dialog_search_objects_combo_contains, SearchMetadataConstants.MATCH_INDEX_CONTAINS);
            matchCombo.add(CoreMessages.dialog_search_objects_combo_like, SearchMetadataConstants.MATCH_INDEX_LIKE);
            matchCombo.select(0);
            matchCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            if (matchTypeIndex >= 0) {
                matchCombo.select(matchTypeIndex);
            }
            matchCombo.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    matchTypeIndex = matchCombo.getSelectionIndex();
                }
            });
            matchCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
            if (maxResults <= 0) {
                maxResults = 100;
            }
            final Spinner maxResultsSpinner = UIUtils.createLabelSpinner(settingsGroup, CoreMessages.dialog_search_objects_spinner_max_results, maxResults, 1, 10000);
            maxResultsSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            maxResultsSpinner.addModifyListener(new ModifyListener() {

                @Override
                public void modifyText(ModifyEvent e) {
                    maxResults = maxResultsSpinner.getSelection();
                }
            });
            maxResultsSpinner.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
            final Button caseCheckbox = UIUtils.createLabelCheckbox(settingsGroup, CoreMessages.dialog_search_objects_case_sensitive, caseSensitive);
            caseCheckbox.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    caseSensitive = caseCheckbox.getSelection();
                }
            });
            caseCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        }
        Label otLabel = UIUtils.createControlLabel(settingsGroup, CoreMessages.dialog_search_objects_group_object_types);
        otLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
        typesTable = new Table(settingsGroup, SWT.CHECK | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
        typesTable.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                //checkedTypes.clear();
                for (TableItem item : typesTable.getItems()) {
                    DBSObjectType objectType = (DBSObjectType) item.getData();
                    if (item.getChecked()) {
                        checkedTypes.add(objectType);
                    } else {
                        checkedTypes.remove(objectType);
                    }
                }
                updateEnablement();
            }
        });
        typesTable.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseDoubleClick(MouseEvent e) {
                TableItem tableItem = typesTable.getSelection()[0];
                tableItem.setChecked(!tableItem.getChecked());
            }
        });
        typesTable.setLayoutData(new GridData(GridData.FILL_BOTH));
        UIUtils.createTableColumn(typesTable, SWT.LEFT, CoreMessages.dialog_search_objects_column_type);
        UIUtils.createTableColumn(typesTable, SWT.LEFT, CoreMessages.dialog_search_objects_column_description);
    }
    try {
        DBeaverUI.runInProgressDialog(new DBRRunnableWithProgress() {

            @Override
            public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask("Load database nodes", 1);
                try {
                    monitor.subTask("Load tree state");
                    sourceNodes = loadTreeState(monitor, DBeaverCore.getGlobalPreferenceStore(), PROP_SOURCES);
                } finally {
                    monitor.done();
                }
            }
        });
    } catch (InvocationTargetException e) {
        UIUtils.showErrorDialog(getShell(), "Data sources load", "Error loading settings", e.getTargetException());
    }
    if (!sourceNodes.isEmpty()) {
        dataSourceTree.getViewer().setSelection(new StructuredSelection(sourceNodes));
        dataSourceTree.getViewer().reveal(NavigatorUtils.getDataSourceNode(sourceNodes.get(0)));
    } else {
        updateEnablement();
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) GridLayout(org.eclipse.swt.layout.GridLayout) TreeLoadNode(org.jkiss.dbeaver.ui.navigator.database.load.TreeLoadNode) DBeaverCore(org.jkiss.dbeaver.core.DBeaverCore) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) DatabaseNavigatorTree(org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTree) InvocationTargetException(java.lang.reflect.InvocationTargetException) SashForm(org.eclipse.swt.custom.SashForm) GridData(org.eclipse.swt.layout.GridData) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 24 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class PostgreBackupWizardPageObjects method loadTables.

private void loadTables(final PostgreSchema catalog) {
    if (catalog != null) {
        curSchema = catalog;
    }
    if (curSchema == null) {
        return;
    }
    final boolean isCatalogChecked = isChecked(curSchema);
    final Set<PostgreTableBase> checkedObjects = this.checkedObjects.get(curSchema);
    new AbstractJob("Load '" + curSchema.getName() + "' tables") {

        {
            setUser(true);
        }

        @Override
        protected IStatus run(DBRProgressMonitor monitor) {
            try {
                final List<PostgreTableBase> objects = new ArrayList<>();
                objects.addAll(curSchema.getTables(monitor));
                if (wizard.showViews) {
                    objects.addAll(curSchema.getViews(monitor));
                }
                Collections.sort(objects, DBUtils.nameComparator());
                DBeaverUI.syncExec(new Runnable() {

                    @Override
                    public void run() {
                        tablesTable.removeAll();
                        for (PostgreTableBase table : objects) {
                            TableItem item = new TableItem(tablesTable, SWT.NONE);
                            item.setImage(DBeaverIcons.getImage(table.isView() ? DBIcon.TREE_VIEW : DBIcon.TREE_TABLE));
                            item.setText(0, table.getName());
                            item.setData(table);
                            item.setChecked(isCatalogChecked && (checkedObjects == null || checkedObjects.contains(table)));
                        }
                    }
                });
            } catch (DBException e) {
                UIUtils.showErrorDialog(null, "Table list", "Can't read table list", e);
            }
            return Status.OK_STATUS;
        }
    }.schedule();
}
Also used : AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) PostgreTableBase(org.jkiss.dbeaver.ext.postgresql.model.PostgreTableBase) List(java.util.List) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 25 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class ResultSetCommandHandler method execute.

@Nullable
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final ResultSetViewer rsv = (ResultSetViewer) getActiveResultSet(HandlerUtil.getActivePart(event));
    if (rsv == null) {
        return null;
    }
    boolean shiftPressed = event.getTrigger() instanceof Event && ((((Event) event.getTrigger()).stateMask & SWT.SHIFT) == SWT.SHIFT);
    String actionId = event.getCommand().getId();
    IResultSetPresentation presentation = rsv.getActivePresentation();
    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());
            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:
            rsv.addNewRow(false, shiftPressed);
            break;
        case CMD_ROW_COPY:
            rsv.addNewRow(true, shiftPressed);
            break;
        case CMD_ROW_DELETE:
        case IWorkbenchCommandConstants.EDIT_DELETE:
            rsv.deleteSelectedRows();
            break;
        case CMD_CELL_SET_NULL:
        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 {
                            rsv.getModel().resetCellValue(attr, row);
                        }
                    }
                }
                rsv.redrawData(false, false);
                rsv.updatePanelsContent(false);
                break;
            }
        case CMD_APPLY_CHANGES:
            rsv.applyChanges(null);
            break;
        case CMD_REJECT_CHANGES:
            rsv.rejectChanges();
            break;
        case CMD_GENERATE_SCRIPT:
            {
                try {
                    final List<DBEPersistAction> sqlScript = new ArrayList<>();
                    try {
                        DBeaverUI.runInProgressService(new DBRRunnableWithProgress() {

                            @Override
                            public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                                List<DBEPersistAction> script = rsv.generateChangesScript(monitor);
                                if (script != null) {
                                    sqlScript.addAll(script);
                                }
                            }
                        });
                    } catch (InterruptedException e) {
                    // ignore
                    }
                    if (!sqlScript.isEmpty()) {
                        String scriptText = SQLUtils.generateScript(rsv.getDataContainer() == null ? null : rsv.getDataContainer().getDataSource(), sqlScript.toArray(new DBEPersistAction[sqlScript.size()]), false);
                        scriptText = SQLUtils.generateCommentLine(rsv.getExecutionContext() == null ? null : rsv.getExecutionContext().getDataSource(), "Actual parameter values may differ, what you see is a default string representation of values") + scriptText;
                        ViewSQLDialog dialog = new ViewSQLDialog(HandlerUtil.getActivePart(event).getSite(), rsv.getExecutionContext(), CoreMessages.editors_entity_dialog_preview_title, UIIcon.SQL_PREVIEW, scriptText);
                        dialog.open();
                    }
                } catch (InvocationTargetException e) {
                    UIUtils.showErrorDialog(HandlerUtil.getActiveShell(event), "Script generation", "Can't generate changes script", e.getTargetException());
                }
                break;
            }
        case CMD_COPY_COLUMN_NAMES:
            {
                StringBuilder buffer = new StringBuilder();
                IResultSetSelection selection = rsv.getSelection();
                Collection<DBDAttributeBinding> attrs = selection.isEmpty() ? rsv.getModel().getVisibleAttributes() : selection.getSelectedAttributes();
                for (DBDAttributeBinding attr : attrs) {
                    if (buffer.length() > 0) {
                        buffer.append("\t");
                    }
                    buffer.append(attr.getName());
                }
                ResultSetUtils.copyToClipboard(buffer.toString());
                break;
            }
        case CMD_COPY_ROW_NAMES:
            {
                StringBuilder buffer = new StringBuilder();
                IResultSetSelection selection = rsv.getSelection();
                for (ResultSetRow row : ((IResultSetSelection) selection).getSelectedRows()) {
                    if (buffer.length() > 0) {
                        buffer.append("\n");
                    }
                    buffer.append(row.getVisualNumber() + 1);
                }
                ResultSetUtils.copyToClipboard(buffer.toString());
                break;
            }
        case IWorkbenchCommandConstants.EDIT_COPY:
            ResultSetUtils.copyToClipboard(presentation.copySelectionToString(new ResultSetCopySettings(false, false, false, true, null, null, DBDDisplayFormat.EDIT)));
            break;
        case IWorkbenchCommandConstants.EDIT_PASTE:
        case CoreCommands.CMD_PASTE_SPECIAL:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).pasteFromClipboard(actionId.equals(CoreCommands.CMD_PASTE_SPECIAL));
            }
            break;
        case IWorkbenchCommandConstants.EDIT_CUT:
            ResultSetUtils.copyToClipboard(presentation.copySelectionToString(new ResultSetCopySettings(false, false, true, true, 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:
            FindReplaceAction action = new FindReplaceAction(DBeaverActivator.getCoreResourceBundle(), "Editor.FindReplace.", HandlerUtil.getActiveShell(event), rsv.getAdapter(IFindReplaceTarget.class));
            action.run();
            break;
        case CMD_NAVIGATE_LINK:
            final ResultSetRow row = rsv.getCurrentRow();
            final DBDAttributeBinding attr = rsv.getActivePresentation().getCurrentAttribute();
            if (row != null && attr != null) {
                new AbstractJob("Navigate association") {

                    @Override
                    protected IStatus run(DBRProgressMonitor monitor) {
                        try {
                            rsv.navigateAssociation(monitor, attr, row, 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(HandlerUtil.getActiveShell(event), "Go to Row", "Enter row number (1.." + rowCount + ")", String.valueOf(currentRow == null ? 1 : currentRow.getVisualNumber() + 1), new IInputValidator() {

                    @Override
                    public String isValid(String 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;
            }
    }
    return null;
}
Also used : DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) FindReplaceAction(org.eclipse.ui.texteditor.FindReplaceAction) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) ArrayList(java.util.ArrayList) List(java.util.List) InvocationTargetException(java.lang.reflect.InvocationTargetException) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) ViewSQLDialog(org.jkiss.dbeaver.ui.dialogs.sql.ViewSQLDialog) ExecutionEvent(org.eclipse.core.commands.ExecutionEvent) Event(org.eclipse.swt.widgets.Event) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) Collection(java.util.Collection) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) IFindReplaceTarget(org.eclipse.jface.text.IFindReplaceTarget) IInputValidator(org.eclipse.jface.dialogs.IInputValidator) Nullable(org.jkiss.code.Nullable)

Aggregations

IStatus (org.eclipse.core.runtime.IStatus)270 Status (org.eclipse.core.runtime.Status)118 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)62 CoreException (org.eclipse.core.runtime.CoreException)49 ArrayList (java.util.ArrayList)40 ITask (com.cubrid.common.core.task.ITask)37 TaskJobExecutor (com.cubrid.common.ui.spi.progress.TaskJobExecutor)29 File (java.io.File)27 InvocationTargetException (java.lang.reflect.InvocationTargetException)25 IOException (java.io.IOException)24 List (java.util.List)21 IFile (org.eclipse.core.resources.IFile)20 Job (org.eclipse.core.runtime.jobs.Job)20 IStructuredSelection (org.eclipse.jface.viewers.IStructuredSelection)19 IResource (org.eclipse.core.resources.IResource)18 IPath (org.eclipse.core.runtime.IPath)18 IJobChangeEvent (org.eclipse.core.runtime.jobs.IJobChangeEvent)17 CommonTaskJobExec (com.cubrid.common.ui.spi.progress.CommonTaskJobExec)14 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)14 GridLayout (org.eclipse.swt.layout.GridLayout)14