Search in sources :

Example 16 with DBECommandContext

use of org.jkiss.dbeaver.model.edit.DBECommandContext in project dbeaver by dbeaver.

the class TabbedFolderPageForm method updateEditButtonsState.

private void updateEditButtonsState() {
    if (saveButton == null || saveButton.isDisposed()) {
        return;
    }
    DBECommandContext commandContext = input.getCommandContext();
    boolean isDirty = commandContext != null && commandContext.isDirty();
    saveButton.setEnabled(isDirty);
    revertButton.setEnabled(isDirty);
    scriptButton.setEnabled(isDirty);
}
Also used : DBECommandContext(org.jkiss.dbeaver.model.edit.DBECommandContext)

Example 17 with DBECommandContext

use of org.jkiss.dbeaver.model.edit.DBECommandContext in project dbeaver by dbeaver.

the class TabbedFolderPageForm method createControl.

@Override
public void createControl(Composite parent) {
    this.boldFont = UIUtils.makeBoldFont(parent.getFont());
    // ScrolledComposite scrolled = new ScrolledComposite(parent, SWT.V_SCROLL);
    // scrolled.setLayout(new GridLayout(1, false));
    propertiesGroup = new Composite(parent, SWT.NONE);
    // CSSUtils.setCSSClass(propertiesGroup, DBStyles.COLORED_BY_CONNECTION_TYPE);
    curPropertySource = input.getPropertySource();
    DBECommandContext commandContext = input.getCommandContext();
    if (commandContext != null) {
        commandContext.addCommandListener(new DBECommandAdapter() {

            @Override
            public void onCommandChange(DBECommand<?> command) {
                UIUtils.asyncExec(() -> {
                    updateEditButtonsState();
                    if (command instanceof DBECommandProperty) {
                        // We need to exclude current prop from update
                        // Simple value compare on update is not enough because value can be transformed (e.g. uppercased)
                        // and it will differ from the value in edit control
                        Object propId = ((DBECommandProperty<?>) command).getHandler().getId();
                        updateOtherPropertyValues(propId);
                    }
                });
            }

            @Override
            public void onSave() {
                UIUtils.asyncExec(() -> updateEditButtonsState());
            }

            @Override
            public void onReset() {
                UIUtils.asyncExec(() -> {
                    refreshProperties();
                    updateEditButtonsState();
                });
            }
        });
    }
    propertiesGroup.addDisposeListener(e -> dispose());
    refreshProperties();
}
Also used : DBECommandProperty(org.jkiss.dbeaver.model.edit.prop.DBECommandProperty) DBECommandContext(org.jkiss.dbeaver.model.edit.DBECommandContext) DBECommandAdapter(org.jkiss.dbeaver.model.impl.edit.DBECommandAdapter) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBPNamedObject(org.jkiss.dbeaver.model.DBPNamedObject)

Example 18 with DBECommandContext

use of org.jkiss.dbeaver.model.edit.DBECommandContext in project dbeaver by serge-rider.

the class EntityEditor method saveCommandContext.

private boolean saveCommandContext(final DBRProgressMonitor monitor) {
    int previewResult = IDialogConstants.PROCEED_ID;
    if (DBeaverCore.getGlobalPreferenceStore().getBoolean(DBeaverPreferences.NAVIGATOR_SHOW_SQL_PREVIEW)) {
        monitor.beginTask(CoreMessages.editors_entity_monitor_preview_changes, 1);
        previewResult = showChanges(true);
        monitor.done();
    }
    if (previewResult != IDialogConstants.PROCEED_ID) {
        return true;
    }
    monitor.beginTask("Save entity", 1);
    Throwable error = null;
    final DBECommandContext commandContext = getCommandContext();
    if (commandContext == null) {
        log.warn("Null command context");
        return true;
    }
    try {
        commandContext.saveChanges(monitor);
    } catch (DBException e) {
        error = e;
    }
    if (getDatabaseObject() instanceof DBPStatefulObject) {
        try {
            ((DBPStatefulObject) getDatabaseObject()).refreshObjectState(monitor);
        } catch (DBCException e) {
            // Just report an error
            log.error(e);
        }
    }
    if (error == null) {
        // Refresh underlying node
        // It'll refresh database object and all it's descendants
        // So we'll get actual data from database
        final DBNDatabaseNode treeNode = getEditorInput().getNavigatorNode();
        try {
            DBeaverUI.runInProgressService(new DBRRunnableWithProgress() {

                @Override
                public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    try {
                        treeNode.refreshNode(monitor, DBNEvent.FORCE_REFRESH);
                    } catch (DBException e) {
                        throw new InvocationTargetException(e);
                    }
                }
            });
        } catch (InvocationTargetException e) {
            error = e.getTargetException();
        } catch (InterruptedException e) {
        // ok
        }
    }
    monitor.done();
    if (error == null) {
        return true;
    } else {
        // Try to handle error in nested editors
        final Throwable vError = error;
        DBeaverUI.syncExec(new Runnable() {

            @Override
            public void run() {
                final IErrorVisualizer errorVisualizer = getAdapter(IErrorVisualizer.class);
                if (errorVisualizer != null) {
                    errorVisualizer.visualizeError(monitor, vError);
                }
            }
        });
        // Show error dialog
        DBeaverUI.asyncExec(new Runnable() {

            @Override
            public void run() {
                UIUtils.showErrorDialog(getSite().getShell(), "Can't save '" + getDatabaseObject().getName() + "'", null, vError);
            }
        });
        return false;
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBCException(org.jkiss.dbeaver.model.exec.DBCException) Point(org.eclipse.swt.graphics.Point) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBECommandContext(org.jkiss.dbeaver.model.edit.DBECommandContext) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)

Example 19 with DBECommandContext

use of org.jkiss.dbeaver.model.edit.DBECommandContext in project dbeaver by serge-rider.

the class PostgreFDWConfigWizard method generateScript.

List<DBEPersistAction> generateScript(DBRProgressMonitor monitor) throws DBException {
    PostgreDatabase database = getDatabase();
    PostgreDataSource curDataSource = database.getDataSource();
    List<DBEPersistAction> actions = new ArrayList<>();
    PostgreFDWConfigWizard.FDWInfo selectedFDW = getSelectedFDW();
    PropertySourceCustom propertySource = getFdwPropertySource();
    Map<String, Object> propValues = propertySource.getPropertiesWithDefaults();
    String serverId = getFdwServerId();
    actions.add(new SQLDatabasePersistActionComment(curDataSource, "CREATE EXTENSION " + selectedFDW.getId()));
    {
        StringBuilder script = new StringBuilder();
        script.append("CREATE SERVER ").append(serverId).append("\n\tFOREIGN DATA WRAPPER ").append(selectedFDW.getId()).append("\n\tOPTIONS(");
        boolean firstProp = true;
        for (Map.Entry<String, Object> pe : propValues.entrySet()) {
            String propName = CommonUtils.toString(pe.getKey());
            String propValue = CommonUtils.toString(pe.getValue());
            if (CommonUtils.isEmpty(propName) || CommonUtils.isEmpty(propValue)) {
                continue;
            }
            if (!firstProp)
                script.append(", ");
            script.append(propName).append(" '").append(propValue).append("'");
            firstProp = false;
        }
        script.append(")");
        actions.add(new SQLDatabasePersistAction("Create extension", script.toString()));
    }
    actions.add(new SQLDatabasePersistAction("CREATE USER MAPPING FOR CURRENT_USER SERVER " + serverId));
    // Now tables
    DBECommandContext commandContext = new SimpleCommandContext(getExecutionContext(), false);
    try {
        PostgreFDWConfigWizard.FDWInfo fdwInfo = getSelectedFDW();
        Map<String, Object> options = new HashMap<>();
        options.put(SQLObjectEditor.OPTION_SKIP_CONFIGURATION, true);
        PostgreForeignTableManager tableManager = new PostgreForeignTableManager();
        PostgreTableColumnManager columnManager = new PostgreTableColumnManager();
        for (DBNDatabaseNode tableNode : getSelectedEntities()) {
            DBSEntity entity = (DBSEntity) tableNode.getObject();
            PostgreTableForeign pgTable = (PostgreTableForeign) tableManager.createNewObject(monitor, commandContext, getSelectedSchema(), null, options);
            if (pgTable == null) {
                log.error("Internal error while creating new table");
                continue;
            }
            pgTable.setName(entity.getName());
            pgTable.setForeignServerName(serverId);
            pgTable.setForeignOptions(new String[0]);
            for (DBSEntityAttribute attr : CommonUtils.safeCollection(entity.getAttributes(monitor))) {
                // Cache data types
                PostgreSchema catalogSchema = database.getCatalogSchema(monitor);
                if (catalogSchema != null) {
                    catalogSchema.getDataTypes(monitor);
                }
                String defTypeName = DBStructUtils.mapTargetDataType(database, attr, true);
                String plainTargetTypeName = SQLUtils.stripColumnTypeModifiers(defTypeName);
                PostgreDataType dataType = database.getDataType(monitor, plainTargetTypeName);
                if (dataType == null) {
                    log.error("Data type '" + plainTargetTypeName + "' not found. Skip column mapping.");
                    continue;
                }
                PostgreTableColumn newColumn = columnManager.createNewObject(monitor, commandContext, pgTable, null, options);
                assert newColumn != null;
                newColumn.setName(attr.getName());
                newColumn.setDataType(dataType);
            }
            DBEPersistAction[] tableDDL = tableManager.getTableDDL(monitor, pgTable, options);
            Collections.addAll(actions, tableDDL);
        }
    } finally {
        commandContext.resetChanges(true);
    }
    // CREATE SERVER clickhouse_svr FOREIGN DATA WRAPPER clickhousedb_fdw OPTIONS(dbname 'default', driver '/usr/local/lib/odbc/libclickhouseodbc.so', host '46.101.202.143');
    return actions;
}
Also used : SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction) DBECommandContext(org.jkiss.dbeaver.model.edit.DBECommandContext) PostgreForeignTableManager(org.jkiss.dbeaver.ext.postgresql.edit.PostgreForeignTableManager) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode) SQLDatabasePersistActionComment(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment) PostgreTableColumnManager(org.jkiss.dbeaver.ext.postgresql.edit.PostgreTableColumnManager) PropertySourceCustom(org.jkiss.dbeaver.runtime.properties.PropertySourceCustom) SimpleCommandContext(org.jkiss.dbeaver.ui.editors.SimpleCommandContext) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) DBSEntityAttribute(org.jkiss.dbeaver.model.struct.DBSEntityAttribute) DBSEntity(org.jkiss.dbeaver.model.struct.DBSEntity)

Example 20 with DBECommandContext

use of org.jkiss.dbeaver.model.edit.DBECommandContext in project dbeaver by serge-rider.

the class EntityEditor method createPages.

@Override
protected void createPages() {
    super.createPages();
    final IDatabaseEditorInput editorInput = getEditorInput();
    if (editorInput instanceof DatabaseLazyEditorInput) {
        try {
            addPage(new ProgressEditorPart(this), editorInput);
            setPageText(0, "Initializing ...");
            Image tabImage = DBeaverIcons.getImage(UIIcon.REFRESH);
            setPageImage(0, tabImage);
            setActivePage(0);
            ((CTabFolder) getContainer()).setTabHeight(tabImage.getBounds().height + 2);
        } catch (PartInitException e) {
            log.error(e);
        }
        return;
    } else if (editorInput instanceof ErrorEditorInput) {
        ErrorEditorInput errorInput = (ErrorEditorInput) editorInput;
        try {
            addPage(new ErrorEditorPartEx(errorInput.getError()), errorInput);
            setPageImage(0, UIUtils.getShardImage(ISharedImages.IMG_OBJS_ERROR_TSK));
            setPageText(0, "Error");
            setActivePage(0);
        } catch (PartInitException e) {
            log.error(e);
        }
        return;
    }
    // Command listener
    commandListener = new DBECommandAdapter() {

        @Override
        public void onCommandChange(DBECommand<?> command) {
            UIUtils.syncExec(() -> firePropertyChange(IEditorPart.PROP_DIRTY));
        }
    };
    DBECommandContext commandContext = getCommandContext();
    if (commandContext != null) {
        commandContext.addCommandListener(commandListener);
    }
    // Property listener
    addPropertyListener((source, propId) -> {
        if (propId == IEditorPart.PROP_DIRTY) {
            EntityEditorPropertyTester.firePropertyChange(EntityEditorPropertyTester.PROP_DIRTY);
            EntityEditorPropertyTester.firePropertyChange(EntityEditorPropertyTester.PROP_CAN_UNDO);
            EntityEditorPropertyTester.firePropertyChange(EntityEditorPropertyTester.PROP_CAN_REDO);
        }
    });
    DBSObject databaseObject = editorInput.getDatabaseObject();
    EditorDefaults editorDefaults = null;
    if (databaseObject == null) {
        // Weird
        log.debug("Null database object in EntityEditor");
    } else {
        synchronized (defaultPageMap) {
            editorDefaults = defaultPageMap.get(databaseObject.getClass().getName());
        }
        EntityEditorsRegistry editorsRegistry = EntityEditorsRegistry.getInstance();
        // Add object editor page
        EntityEditorDescriptor defaultEditor = editorsRegistry.getMainEntityEditor(databaseObject, this);
        hasPropertiesEditor = false;
        if (defaultEditor != null) {
            hasPropertiesEditor = addEditorTab(defaultEditor);
        }
        if (hasPropertiesEditor) {
            DBNNode node = editorInput.getNavigatorNode();
            int propEditorIndex = getPageCount() - 1;
            setPageText(propEditorIndex, UINavigatorMessages.editors_entity_properties_text);
            setPageToolTip(propEditorIndex, node.getNodeType() + UINavigatorMessages.editors_entity_properties_tooltip_suffix);
            setPageImage(propEditorIndex, DBeaverIcons.getImage(node.getNodeIconDefault()));
        }
    }
    // Add contributed pages
    addContributions(EntityEditorDescriptor.POSITION_PROPS);
    addContributions(EntityEditorDescriptor.POSITION_START);
    addContributions(EntityEditorDescriptor.POSITION_MIDDLE);
    // Add contributed pages
    addContributions(EntityEditorDescriptor.POSITION_END);
    String defPageId = editorInput.getDefaultPageId();
    String defFolderId = editorInput.getDefaultFolderId();
    if (defPageId == null && editorDefaults != null) {
        defPageId = editorDefaults.pageId;
    }
    if (defPageId != null) {
        IEditorPart defEditorPage = editorMap.get(defPageId);
        if (defEditorPage != null) {
            setActiveEditor(defEditorPage);
        }
    } else {
        setActiveEditor(getEditor(0));
    }
    this.activeEditor = getActiveEditor();
    if (activeEditor instanceof ITabbedFolderContainer) {
        if (defFolderId == null && editorDefaults != null) {
            defFolderId = editorDefaults.folderId;
        }
        if (defFolderId != null) {
            String folderId = defFolderId;
            UIUtils.asyncExec(() -> {
                ((ITabbedFolderContainer) activeEditor).switchFolder(folderId);
            });
        }
    }
    UIUtils.setHelp(getContainer(), IHelpContextIds.CTX_ENTITY_EDITOR);
}
Also used : CTabFolder(org.eclipse.swt.custom.CTabFolder) Image(org.eclipse.swt.graphics.Image) Point(org.eclipse.swt.graphics.Point) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) ITabbedFolderContainer(org.jkiss.dbeaver.ui.controls.folders.ITabbedFolderContainer) DBECommandContext(org.jkiss.dbeaver.model.edit.DBECommandContext) DBECommandAdapter(org.jkiss.dbeaver.model.impl.edit.DBECommandAdapter)

Aggregations

DBECommandContext (org.jkiss.dbeaver.model.edit.DBECommandContext)33 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)12 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 DBException (org.jkiss.dbeaver.DBException)7 IUndoManager (org.eclipse.jface.text.IUndoManager)6 DBECommand (org.jkiss.dbeaver.model.edit.DBECommand)6 DBEPersistAction (org.jkiss.dbeaver.model.edit.DBEPersistAction)6 Point (org.eclipse.swt.graphics.Point)5 IEditorPart (org.eclipse.ui.IEditorPart)4 IWorkbenchWindow (org.eclipse.ui.IWorkbenchWindow)4 DBECommandAdapter (org.jkiss.dbeaver.model.impl.edit.DBECommandAdapter)4 EntityEditor (org.jkiss.dbeaver.ui.editors.entity.EntityEditor)4 DBCException (org.jkiss.dbeaver.model.exec.DBCException)3 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)3 CTabFolder (org.eclipse.swt.custom.CTabFolder)2 Image (org.eclipse.swt.graphics.Image)2 PostgreForeignTableManager (org.jkiss.dbeaver.ext.postgresql.edit.PostgreForeignTableManager)2 PostgreTableColumnManager (org.jkiss.dbeaver.ext.postgresql.edit.PostgreTableColumnManager)2 DBPNamedObject (org.jkiss.dbeaver.model.DBPNamedObject)2 DBEObjectMaker (org.jkiss.dbeaver.model.edit.DBEObjectMaker)2