Search in sources :

Example 1 with DBRProgressListener

use of org.jkiss.dbeaver.model.runtime.DBRProgressListener in project dbeaver by serge-rider.

the class SQLEditor method processQueries.

private void processQueries(@NotNull final List<SQLQuery> queries, final boolean newTab, final boolean export, final boolean checkSession) {
    if (queries.isEmpty()) {
        // Nothing to process
        return;
    }
    final DBPDataSourceContainer container = getDataSourceContainer();
    if (checkSession) {
        try {
            DBRProgressListener connectListener = new DBRProgressListener() {

                @Override
                public void onTaskFinished(IStatus status) {
                    if (!status.isOK() || container == null || !container.isConnected()) {
                        UIUtils.showErrorDialog(getSite().getShell(), CoreMessages.editors_sql_error_cant_obtain_session, null, status);
                        return;
                    }
                    // Make a small pause to let all UI connection listeners to finish
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    // it's ok
                    }
                    DBeaverUI.syncExec(new Runnable() {

                        @Override
                        public void run() {
                            processQueries(queries, newTab, export, false);
                        }
                    });
                }
            };
            if (!checkSession(connectListener)) {
                return;
            }
        } catch (DBException ex) {
            ResultSetViewer viewer = getActiveResultSetViewer();
            if (viewer != null) {
                viewer.setStatus(ex.getMessage(), DBPMessageType.ERROR);
            }
            UIUtils.showErrorDialog(getSite().getShell(), CoreMessages.editors_sql_error_cant_obtain_session, ex.getMessage());
            return;
        }
    }
    if (sashForm.getMaximizedControl() != null) {
        sashForm.setMaximizedControl(null);
    }
    // Save editor
    if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_EXECUTE) && isDirty()) {
        doSave(new NullProgressMonitor());
    }
    final boolean isSingleQuery = (queries.size() == 1);
    if (!newTab || !isSingleQuery) {
        // We don't need new tab or we are executing a script - so close all extra tabs
        closeExtraResultTabs(null);
    }
    if (newTab) {
        // Execute each query in a new tab
        for (int i = 0; i < queries.size(); i++) {
            SQLQuery query = queries.get(i);
            QueryProcessor queryProcessor = (i == 0 && !isSingleQuery ? curQueryProcessor : createQueryProcessor(queries.size() == 1));
            queryProcessor.processQueries(Collections.singletonList(query), true, export);
        }
    } else {
        // Use current tab.
        // If current tab was pinned then use first tab
        final QueryResultsContainer firstResults = curQueryProcessor.getFirstResults();
        if (firstResults.isPinned()) {
            curQueryProcessor = queryProcessors.get(0);
        }
        closeExtraResultTabs(curQueryProcessor);
        if (firstResults.tabItem != null) {
            resultTabs.setSelection(firstResults.tabItem);
        }
        curQueryProcessor.processQueries(queries, false, export);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) Point(org.eclipse.swt.graphics.Point) ResultSetViewer(org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer)

Example 2 with DBRProgressListener

use of org.jkiss.dbeaver.model.runtime.DBRProgressListener in project dbeaver by dbeaver.

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);
    }
    DBeaverUI.asyncExec(new Runnable() {

        @Override
        public void run() {
            loadState();
        }
    });
}
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) SashForm(org.eclipse.swt.custom.SashForm) GridData(org.eclipse.swt.layout.GridData)

Example 3 with DBRProgressListener

use of org.jkiss.dbeaver.model.runtime.DBRProgressListener in project dbeaver by dbeaver.

the class SQLEditor method processQueries.

private void processQueries(@NotNull final List<SQLScriptElement> queries, final boolean newTab, final boolean export, final boolean checkSession, @Nullable final SQLQueryListener queryListener) {
    if (queries.isEmpty()) {
        // Nothing to process
        return;
    }
    final DBPDataSourceContainer container = getDataSourceContainer();
    if (checkSession) {
        try {
            DBRProgressListener connectListener = status -> {
                if (!status.isOK() || container == null || !container.isConnected()) {
                    DBUserInterface.getInstance().showError(CoreMessages.editors_sql_error_cant_obtain_session, null, status);
                    return;
                }
                updateExecutionContext(new Runnable() {

                    @Override
                    public void run() {
                        DBeaverUI.syncExec(() -> processQueries(queries, newTab, export, false, queryListener));
                    }
                });
            };
            if (!checkSession(connectListener)) {
                return;
            }
        } catch (DBException ex) {
            ResultSetViewer viewer = getActiveResultSetViewer();
            if (viewer != null) {
                viewer.setStatus(ex.getMessage(), DBPMessageType.ERROR);
            }
            DBUserInterface.getInstance().showError(CoreMessages.editors_sql_error_cant_obtain_session, ex.getMessage());
            return;
        }
    }
    if (dataSourceContainer == null) {
        return;
    }
    final boolean isSingleQuery = (queries.size() == 1);
    if (isSingleQuery && queries.get(0) instanceof SQLQuery) {
        SQLQuery query = (SQLQuery) queries.get(0);
        if (query.isDeleteUpdateDangerous()) {
            String targetName = "multiple tables";
            if (query.getSingleSource() != null) {
                targetName = query.getSingleSource().getEntityName();
            }
            if (ConfirmationDialog.showConfirmDialogEx(getSite().getShell(), DBeaverPreferences.CONFIRM_DANGER_SQL, ConfirmationDialog.CONFIRM, ConfirmationDialog.WARNING, query.getType().name(), targetName) != IDialogConstants.OK_ID) {
                return;
            }
        }
    } else if (newTab && queries.size() > MAX_PARALLEL_QUERIES_NO_WARN) {
        if (ConfirmationDialog.showConfirmDialogEx(getSite().getShell(), DBeaverPreferences.CONFIRM_MASS_PARALLEL_SQL, ConfirmationDialog.CONFIRM, ConfirmationDialog.WARNING, queries.size()) != IDialogConstants.OK_ID) {
            return;
        }
    }
    if (sashForm.getMaximizedControl() != null) {
        sashForm.setMaximizedControl(null);
    }
    // Save editor
    if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_EXECUTE) && isDirty()) {
        doSave(new NullProgressMonitor());
    }
    if (!newTab || !isSingleQuery) {
        // We don't need new tab or we are executing a script - so close all extra tabs
        closeExtraResultTabs(null);
    }
    if (newTab) {
        // Execute each query in a new tab
        for (int i = 0; i < queries.size(); i++) {
            SQLScriptElement query = queries.get(i);
            QueryProcessor queryProcessor = (i == 0 && !isSingleQuery ? curQueryProcessor : createQueryProcessor(queries.size() == 1));
            queryProcessor.processQueries(Collections.singletonList(query), true, export, getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESULT_SET_CLOSE_ON_ERROR), queryListener);
        }
    } else {
        // Use current tab.
        // If current tab was pinned then use first tab
        final QueryResultsContainer firstResults = curQueryProcessor.getFirstResults();
        if (firstResults.isPinned()) {
            curQueryProcessor = queryProcessors.get(0);
        }
        closeExtraResultTabs(curQueryProcessor);
        if (firstResults.tabItem != null) {
            // Do not switch tab if Output tab is active
            CTabItem selectedTab = resultTabs.getSelection();
            if (selectedTab == null || selectedTab.getData() != outputViewer) {
                resultTabs.setSelection(firstResults.tabItem);
            }
        }
        curQueryProcessor.processQueries(queries, false, export, false, queryListener);
    }
}
Also used : StringEditorInput(org.jkiss.dbeaver.ui.editors.StringEditorInput) IResultSetListener(org.jkiss.dbeaver.ui.controls.resultset.IResultSetListener) org.eclipse.jface.action(org.eclipse.jface.action) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) CompoundContributionItem(org.eclipse.ui.actions.CompoundContributionItem) SashForm(org.eclipse.swt.custom.SashForm) org.jkiss.dbeaver.ui(org.jkiss.dbeaver.ui) StyledText(org.eclipse.swt.custom.StyledText) DefaultRangeIndicator(org.eclipse.ui.texteditor.DefaultRangeIndicator) SQLQueryListener(org.jkiss.dbeaver.runtime.sql.SQLQueryListener) SQLQueryJob(org.jkiss.dbeaver.runtime.sql.SQLQueryJob) SQLResultsView(org.jkiss.dbeaver.ui.views.SQLResultsView) org.eclipse.jface.text(org.eclipse.jface.text) DBCPlanStyle(org.jkiss.dbeaver.model.exec.plan.DBCPlanStyle) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) DBDDataFilter(org.jkiss.dbeaver.model.data.DBDDataFilter) Point(org.eclipse.swt.graphics.Point) SQLLogPanel(org.jkiss.dbeaver.ui.editors.sql.log.SQLLogPanel) QMUtils(org.jkiss.dbeaver.model.qm.QMUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResultSetViewer(org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer) IOUtils(org.jkiss.utils.IOUtils) DBSObjectSelector(org.jkiss.dbeaver.model.struct.DBSObjectSelector) ScriptPositionColumn(org.jkiss.dbeaver.ui.editors.text.ScriptPositionColumn) URI(java.net.URI) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) RulerColumnDescriptor(org.eclipse.ui.texteditor.rulers.RulerColumnDescriptor) SQLResultsConsumer(org.jkiss.dbeaver.runtime.sql.SQLResultsConsumer) EFS(org.eclipse.core.filesystem.EFS) ExplainPlanViewer(org.jkiss.dbeaver.ui.views.plan.ExplainPlanViewer) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) DBPPreferenceListener(org.jkiss.dbeaver.model.preferences.DBPPreferenceListener) GeneralUtils(org.jkiss.dbeaver.utils.GeneralUtils) CommonUtils(org.jkiss.utils.CommonUtils) IFileState(org.eclipse.core.resources.IFileState) DBCPlan(org.jkiss.dbeaver.model.exec.plan.DBCPlan) DatabaseTransferProducer(org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer) CTabFolder(org.eclipse.swt.custom.CTabFolder) DBCQueryPlanner(org.jkiss.dbeaver.model.exec.plan.DBCQueryPlanner) DBeaverPreferences(org.jkiss.dbeaver.DBeaverPreferences) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) IDataTransferProducer(org.jkiss.dbeaver.tools.transfer.IDataTransferProducer) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent) MouseEvent(org.eclipse.swt.events.MouseEvent) List(java.util.List) RuntimeUtils(org.jkiss.dbeaver.utils.RuntimeUtils) DBException(org.jkiss.dbeaver.DBException) SWT(org.eclipse.swt.SWT) ITextEditorActionConstants(org.eclipse.ui.texteditor.ITextEditorActionConstants) DatabaseEditorUtils(org.jkiss.dbeaver.ui.editors.DatabaseEditorUtils) DefaultServerOutputReader(org.jkiss.dbeaver.model.impl.DefaultServerOutputReader) PrefUtils(org.jkiss.dbeaver.utils.PrefUtils) MouseAdapter(org.eclipse.swt.events.MouseAdapter) IColumnSupport(org.eclipse.ui.texteditor.rulers.IColumnSupport) java.util(java.util) EnterNameDialog(org.jkiss.dbeaver.ui.dialogs.EnterNameDialog) DBPPreferenceStore(org.jkiss.dbeaver.model.preferences.DBPPreferenceStore) DBUserInterface(org.jkiss.dbeaver.runtime.ui.DBUserInterface) Image(org.eclipse.swt.graphics.Image) Nullable(org.jkiss.code.Nullable) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DataTransferWizard(org.jkiss.dbeaver.tools.transfer.wizard.DataTransferWizard) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) NotNull(org.jkiss.code.NotNull) EditorUtils(org.jkiss.dbeaver.ui.editors.EditorUtils) DataSourceHandler(org.jkiss.dbeaver.ui.actions.datasource.DataSourceHandler) IProject(org.eclipse.core.resources.IProject) INonPersistentEditorInput(org.jkiss.dbeaver.ui.editors.INonPersistentEditorInput) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) IResultSetContainer(org.jkiss.dbeaver.ui.controls.resultset.IResultSetContainer) IFile(org.eclipse.core.resources.IFile) GridData(org.eclipse.swt.layout.GridData) SQLQueryTransformerCount(org.jkiss.dbeaver.model.impl.sql.SQLQueryTransformerCount) RulerColumnRegistry(org.eclipse.ui.texteditor.rulers.RulerColumnRegistry) ModelPreferences(org.jkiss.dbeaver.ModelPreferences) DBDDataReceiver(org.jkiss.dbeaver.model.data.DBDDataReceiver) IFileStore(org.eclipse.core.filesystem.IFileStore) JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) org.jkiss.dbeaver.model(org.jkiss.dbeaver.model) Job(org.eclipse.core.runtime.jobs.Job) org.jkiss.dbeaver.model.exec(org.jkiss.dbeaver.model.exec) org.eclipse.swt.widgets(org.eclipse.swt.widgets) ArrayUtils(org.jkiss.utils.ArrayUtils) CTabItem(org.eclipse.swt.custom.CTabItem) org.eclipse.ui(org.eclipse.ui) FileStoreEditorInput(org.eclipse.ui.ide.FileStoreEditorInput) org.jkiss.dbeaver.core(org.jkiss.dbeaver.core) org.eclipse.core.runtime(org.eclipse.core.runtime) DBSDataContainer(org.jkiss.dbeaver.model.struct.DBSDataContainer) java.io(java.io) ActiveWizardDialog(org.jkiss.dbeaver.ui.dialogs.ActiveWizardDialog) SelectionEvent(org.eclipse.swt.events.SelectionEvent) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) ConfirmationDialog(org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog) org.jkiss.dbeaver.model.sql(org.jkiss.dbeaver.model.sql) DBException(org.jkiss.dbeaver.DBException) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) CTabItem(org.eclipse.swt.custom.CTabItem) Point(org.eclipse.swt.graphics.Point) ResultSetViewer(org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer)

Example 4 with DBRProgressListener

use of org.jkiss.dbeaver.model.runtime.DBRProgressListener in project dbeaver by dbeaver.

the class BookmarksHandlerImpl method openResource.

@Override
public void openResource(@NotNull final IResource resource) throws CoreException, DBException {
    if (!(resource instanceof IFile)) {
        return;
    }
    final DBNProject projectNode = DBeaverCore.getInstance().getNavigatorModel().getRoot().getProject(resource.getProject());
    if (projectNode == null) {
        // $NON-NLS-2$
        throw new DBException("Can't find project node for '" + resource.getProject().getName() + "'");
    }
    final BookmarkStorage storage = new BookmarkStorage((IFile) resource, false);
    try {
        final DBPDataSourceContainer dataSourceContainer = projectNode.getDatabases().getDataSourceRegistry().getDataSource(storage.getDataSourceId());
        if (dataSourceContainer == null) {
            // $NON-NLS-2$
            throw new DBException("Can't find datasource '" + storage.getDataSourceId() + "'");
        }
        final DBNDataSource dsNode = (DBNDataSource) NavigatorUtils.getNodeByObject(dataSourceContainer);
        if (dsNode == null) {
            // $NON-NLS-2$
            throw new DBException("Can't find datasource node for '" + dataSourceContainer.getName() + "'");
        }
        dsNode.initializeNode(null, new DBRProgressListener() {

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

                        @Override
                        public void run() {
                            openNodeByPath(dsNode, (IFile) resource, storage);
                        }
                    });
                } else {
                    DBUserInterface.getInstance().showError("Open bookmark", "Can't open bookmark", status);
                }
            }
        });
    } finally {
        storage.dispose();
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) IFile(org.eclipse.core.resources.IFile) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer)

Example 5 with DBRProgressListener

use of org.jkiss.dbeaver.model.runtime.DBRProgressListener in project dbeaver by serge-rider.

the class SQLEditor method processQueries.

private boolean processQueries(@NotNull final List<SQLScriptElement> queries, final boolean forceScript, boolean newTab, final boolean export, final boolean checkSession, @Nullable final SQLQueryListener queryListener, @Nullable final SQLScriptContext context) {
    if (queries.isEmpty()) {
        // Nothing to process
        return false;
    }
    final DBPDataSourceContainer container = getDataSourceContainer();
    if (checkSession) {
        try {
            boolean finalNewTab = newTab;
            DBRProgressListener connectListener = status -> {
                if (!status.isOK() || container == null || !container.isConnected()) {
                    DBWorkbench.getPlatformUI().showError(SQLEditorMessages.editors_sql_error_cant_obtain_session, null, status);
                    return;
                }
                updateExecutionContext(() -> UIUtils.syncExec(() -> processQueries(queries, forceScript, finalNewTab, export, false, queryListener, context)));
            };
            if (!checkSession(connectListener)) {
                return false;
            }
        } catch (DBException ex) {
            ResultSetViewer viewer = getActiveResultSetViewer();
            if (viewer != null) {
                viewer.setStatus(ex.getMessage(), DBPMessageType.ERROR);
            }
            DBWorkbench.getPlatformUI().showError(SQLEditorMessages.editors_sql_error_cant_obtain_session, ex.getMessage());
            return false;
        }
    }
    if (dataSourceContainer == null) {
        return false;
    }
    if (!dataSourceContainer.hasModifyPermission(DBPDataSourcePermission.PERMISSION_EXECUTE_SCRIPTS)) {
        DBWorkbench.getPlatformUI().showError(SQLEditorMessages.editors_sql_error_cant_execute_query_title, "Query execution was restricted by connection configuration");
        return false;
    }
    SQLScriptContext scriptContext = context;
    if (scriptContext == null) {
        scriptContext = createScriptContext();
    }
    final boolean isSingleQuery = !forceScript && (queries.size() == 1);
    if (isSingleQuery && queries.get(0) instanceof SQLQuery) {
        SQLQuery query = (SQLQuery) queries.get(0);
        if (query.isDeleteUpdateDangerous()) {
            String targetName = "multiple tables";
            if (query.getSingleSource() != null) {
                targetName = query.getSingleSource().getEntityName();
            }
            if (ConfirmationDialog.showConfirmDialogEx(ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME), getSite().getShell(), SQLPreferenceConstants.CONFIRM_DANGER_SQL, ConfirmationDialog.CONFIRM, ConfirmationDialog.WARNING, query.getType().name(), targetName) != IDialogConstants.OK_ID) {
                return false;
            }
        }
    } else if (newTab && queries.size() > MAX_PARALLEL_QUERIES_NO_WARN) {
        if (ConfirmationDialog.showConfirmDialogEx(ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME), getSite().getShell(), SQLPreferenceConstants.CONFIRM_MASS_PARALLEL_SQL, ConfirmationDialog.CONFIRM, ConfirmationDialog.WARNING, queries.size()) != IDialogConstants.OK_ID) {
            return false;
        }
    }
    if (resultsSash.getMaximizedControl() != null) {
        resultsSash.setMaximizedControl(null);
    }
    // Save editor
    if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_EXECUTE) && isDirty()) {
        doSave(new NullProgressMonitor());
    }
    // Clear server console output
    if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.CLEAR_OUTPUT_BEFORE_EXECUTE)) {
        outputViewer.clearOutput();
    }
    if (!export) {
        // 2. The user is executing script that may open several result sets
        if (!newTab && !isSingleQuery) {
            int tabsClosed = closeExtraResultTabs(null, true, false);
            if (tabsClosed == IDialogConstants.CANCEL_ID) {
                return false;
            } else if (tabsClosed == IDialogConstants.NO_ID) {
                newTab = true;
            }
        }
        // 3. Or current query processor has running jobs
        if (newTab || queryProcessors.isEmpty() || curQueryProcessor.hasPinnedTabs() || curQueryProcessor.getRunningJobs() > 0) {
            boolean foundSuitableTab = false;
            // 2. The user is executing only single query
            if (!newTab && isSingleQuery) {
                for (QueryProcessor processor : queryProcessors) {
                    if (!processor.hasPinnedTabs() && processor.getRunningJobs() == 0) {
                        foundSuitableTab = true;
                        curQueryProcessor = processor;
                        break;
                    }
                }
            }
            // Just create a new query processor
            if (!foundSuitableTab) {
                createQueryProcessor(true, false);
            }
        }
        // if the user is executing only single query
        if (!newTab && isSingleQuery && curQueryProcessor.getResultContainers().size() > 1) {
            closeExtraResultTabs(curQueryProcessor, false, true);
        }
        CTabItem tabItem = curQueryProcessor.getFirstResults().getTabItem();
        if (tabItem != null) {
            // Do not switch tab if Output tab is active
            CTabItem selectedTab = resultTabs.getSelection();
            if (selectedTab == null || selectedTab.getData() != outputViewer.getControl()) {
                resultTabs.setSelection(tabItem);
            }
        }
    }
    return curQueryProcessor.processQueries(scriptContext, queries, forceScript, false, export, !export && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESULT_SET_CLOSE_ON_ERROR), queryListener);
}
Also used : StyledText(org.eclipse.swt.custom.StyledText) DBCPlanStyle(org.jkiss.dbeaver.model.exec.plan.DBCPlanStyle) IDialogConstants(org.eclipse.jface.dialogs.IDialogConstants) DBDDataFilter(org.jkiss.dbeaver.model.data.DBDDataFilter) Point(org.eclipse.swt.graphics.Point) DBNUtils(org.jkiss.dbeaver.model.navigator.DBNUtils) Matcher(java.util.regex.Matcher) ScriptPositionColumn(org.jkiss.dbeaver.ui.editors.text.ScriptPositionColumn) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) EFS(org.eclipse.core.filesystem.EFS) DatabaseTransferProducer(org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer) CTabFolder(org.eclipse.swt.custom.CTabFolder) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) ExplainPlanViewer(org.jkiss.dbeaver.ui.editors.sql.plan.ExplainPlanViewer) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) IDataTransferProducer(org.jkiss.dbeaver.tools.transfer.IDataTransferProducer) SQLQueryDataContainer(org.jkiss.dbeaver.model.sql.data.SQLQueryDataContainer) org.jkiss.dbeaver.ui.controls.resultset(org.jkiss.dbeaver.ui.controls.resultset) RuntimeUtils(org.jkiss.dbeaver.utils.RuntimeUtils) SWT(org.eclipse.swt.SWT) DefaultServerOutputReader(org.jkiss.dbeaver.model.impl.DefaultServerOutputReader) PrefUtils(org.jkiss.dbeaver.utils.PrefUtils) DBWorkbench(org.jkiss.dbeaver.runtime.DBWorkbench) IColumnSupport(org.eclipse.ui.texteditor.rulers.IColumnSupport) java.util(java.util) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) DBPPreferenceStore(org.jkiss.dbeaver.model.preferences.DBPPreferenceStore) SimpleDateFormat(java.text.SimpleDateFormat) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) NotNull(org.jkiss.code.NotNull) EditorUtils(org.jkiss.dbeaver.ui.editors.EditorUtils) INavigatorModelView(org.jkiss.dbeaver.ui.navigator.INavigatorModelView) IFile(org.eclipse.core.resources.IFile) ResultSetMessages(org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages) GridData(org.eclipse.swt.layout.GridData) RulerColumnRegistry(org.eclipse.ui.texteditor.rulers.RulerColumnRegistry) DBDDataReceiver(org.jkiss.dbeaver.model.data.DBDDataReceiver) org.jkiss.dbeaver.model(org.jkiss.dbeaver.model) org.eclipse.swt.events(org.eclipse.swt.events) SQLPresentationRegistry(org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationRegistry) org.eclipse.swt.widgets(org.eclipse.swt.widgets) DBSInstance(org.jkiss.dbeaver.model.struct.DBSInstance) UIServiceConnections(org.jkiss.dbeaver.runtime.ui.UIServiceConnections) SourceViewer(org.eclipse.jface.text.source.SourceViewer) org.eclipse.ui(org.eclipse.ui) FileStoreEditorInput(org.eclipse.ui.ide.FileStoreEditorInput) org.eclipse.core.runtime(org.eclipse.core.runtime) org.jkiss.dbeaver.model.sql(org.jkiss.dbeaver.model.sql) GridLayout(org.eclipse.swt.layout.GridLayout) StringEditorInput(org.jkiss.dbeaver.ui.editors.StringEditorInput) org.eclipse.jface.action(org.eclipse.jface.action) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) CompoundContributionItem(org.eclipse.ui.actions.CompoundContributionItem) org.jkiss.dbeaver.ui(org.jkiss.dbeaver.ui) DefaultRangeIndicator(org.eclipse.ui.texteditor.DefaultRangeIndicator) org.eclipse.jface.text(org.eclipse.jface.text) SQLLogPanel(org.jkiss.dbeaver.ui.editors.sql.log.SQLLogPanel) SQLPresentationPanelDescriptor(org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationPanelDescriptor) ModelMessages(org.jkiss.dbeaver.model.messages.ModelMessages) SQLPresentationDescriptor(org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationDescriptor) QMUtils(org.jkiss.dbeaver.model.qm.QMUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) URI(java.net.URI) RulerColumnDescriptor(org.eclipse.ui.texteditor.rulers.RulerColumnDescriptor) DBPProject(org.jkiss.dbeaver.model.app.DBPProject) SQLResultsConsumer(org.jkiss.dbeaver.runtime.sql.SQLResultsConsumer) DBCQueryPlannerConfiguration(org.jkiss.dbeaver.model.exec.plan.DBCQueryPlannerConfiguration) GeneralUtils(org.jkiss.dbeaver.utils.GeneralUtils) CommonUtils(org.jkiss.utils.CommonUtils) IFileState(org.eclipse.core.resources.IFileState) DBCPlan(org.jkiss.dbeaver.model.exec.plan.DBCPlan) NLS(org.eclipse.osgi.util.NLS) DBCQueryPlanner(org.jkiss.dbeaver.model.exec.plan.DBCQueryPlanner) org.jkiss.dbeaver.ui.controls(org.jkiss.dbeaver.ui.controls) SQLEditorMessages(org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages) DBStyles(org.jkiss.dbeaver.ui.css.DBStyles) List(java.util.List) DBException(org.jkiss.dbeaver.DBException) SQLNavigatorContext(org.jkiss.dbeaver.ui.editors.sql.handlers.SQLNavigatorContext) ITextEditorActionConstants(org.eclipse.ui.texteditor.ITextEditorActionConstants) DatabaseEditorUtils(org.jkiss.dbeaver.ui.editors.DatabaseEditorUtils) Pattern(java.util.regex.Pattern) EnterNameDialog(org.jkiss.dbeaver.ui.dialogs.EnterNameDialog) Image(org.eclipse.swt.graphics.Image) Nullable(org.jkiss.code.Nullable) INonPersistentEditorInput(org.jkiss.dbeaver.ui.editors.INonPersistentEditorInput) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) SQLQueryJob(org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob) SQLQueryTransformerCount(org.jkiss.dbeaver.model.impl.sql.SQLQueryTransformerCount) FillLayout(org.eclipse.swt.layout.FillLayout) ModelPreferences(org.jkiss.dbeaver.ModelPreferences) IFileStore(org.eclipse.core.filesystem.IFileStore) Job(org.eclipse.core.runtime.jobs.Job) org.jkiss.dbeaver.model.exec(org.jkiss.dbeaver.model.exec) ArrayUtils(org.jkiss.utils.ArrayUtils) DataSourceUtils(org.jkiss.dbeaver.registry.DataSourceUtils) CTabItem(org.eclipse.swt.custom.CTabItem) CSSUtils(org.jkiss.dbeaver.ui.css.CSSUtils) DataTransferWizard(org.jkiss.dbeaver.tools.transfer.ui.wizard.DataTransferWizard) DBSDataContainer(org.jkiss.dbeaver.model.struct.DBSDataContainer) java.io(java.io) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) ConfirmationDialog(org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog) DBException(org.jkiss.dbeaver.DBException) DBRProgressListener(org.jkiss.dbeaver.model.runtime.DBRProgressListener) CTabItem(org.eclipse.swt.custom.CTabItem) Point(org.eclipse.swt.graphics.Point)

Aggregations

DBRProgressListener (org.jkiss.dbeaver.model.runtime.DBRProgressListener)5 DBException (org.jkiss.dbeaver.DBException)4 IFile (org.eclipse.core.resources.IFile)3 Point (org.eclipse.swt.graphics.Point)3 GridData (org.eclipse.swt.layout.GridData)3 java.io (java.io)2 URI (java.net.URI)2 java.util (java.util)2 List (java.util.List)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 EFS (org.eclipse.core.filesystem.EFS)2 IFileStore (org.eclipse.core.filesystem.IFileStore)2 IFileState (org.eclipse.core.resources.IFileState)2 org.eclipse.core.runtime (org.eclipse.core.runtime)2 Job (org.eclipse.core.runtime.jobs.Job)2 org.eclipse.jface.action (org.eclipse.jface.action)2 IDialogConstants (org.eclipse.jface.dialogs.IDialogConstants)2 IPreferenceStore (org.eclipse.jface.preference.IPreferenceStore)2 org.eclipse.jface.text (org.eclipse.jface.text)2 ISelectionProvider (org.eclipse.jface.viewers.ISelectionProvider)2