Search in sources :

Example 1 with DataSourceRegistry

use of org.jkiss.dbeaver.registry.DataSourceRegistry in project dbeaver by serge-rider.

the class DiagramLoader method load.

public static void load(DBRProgressMonitor monitor, IProject project, DiagramPart diagramPart, InputStream in) throws IOException, XMLException, DBException {
    monitor.beginTask("Parse diagram", 1);
    final EntityDiagram diagram = diagramPart.getDiagram();
    final DataSourceRegistry dsRegistry = DBeaverCore.getInstance().getProjectRegistry().getDataSourceRegistry(project);
    if (dsRegistry == null) {
        throw new DBException("Cannot find datasource registry for project '" + project.getName() + "'");
    }
    final Document document = XMLUtils.parseDocument(in);
    final Element diagramElem = document.getDocumentElement();
    monitor.done();
    // Check version
    final String diagramVersion = diagramElem.getAttribute(ATTR_VERSION);
    if (CommonUtils.isEmpty(diagramVersion)) {
        throw new DBException("Diagram version not found");
    }
    if (!diagramVersion.equals(String.valueOf(ERD_VERSION_1))) {
        throw new DBException("Unsupported diagram version: " + diagramVersion);
    }
    List<TableLoadInfo> tableInfos = new ArrayList<>();
    List<RelationLoadInfo> relInfos = new ArrayList<>();
    Map<String, TableLoadInfo> tableMap = new HashMap<>();
    final Element entitiesElem = XMLUtils.getChildElement(diagramElem, TAG_ENTITIES);
    if (entitiesElem != null) {
        // Parse data source
        for (Element dsElem : XMLUtils.getChildElementList(entitiesElem, TAG_DATA_SOURCE)) {
            String dsId = dsElem.getAttribute(ATTR_ID);
            if (CommonUtils.isEmpty(dsId)) {
                log.warn("Missing datasource ID");
                continue;
            }
            // Get connected datasource
            final DataSourceDescriptor dataSourceContainer = dsRegistry.getDataSource(dsId);
            if (dataSourceContainer == null) {
                log.warn("Datasource '" + dsId + "' not found");
                continue;
            }
            if (!dataSourceContainer.isConnected()) {
                monitor.subTask("Connect to '" + dataSourceContainer.getName() + "'");
                try {
                    dataSourceContainer.connect(monitor, true, true);
                } catch (DBException e) {
                    diagram.addErrorMessage("Can't connect to '" + dataSourceContainer.getName() + "': " + e.getMessage());
                    continue;
                }
            }
            final DBPDataSource dataSource = dataSourceContainer.getDataSource();
            if (!(dataSource instanceof DBSObjectContainer)) {
                diagram.addErrorMessage("Datasource '" + dataSourceContainer.getName() + "' entities cannot be loaded - no entity container found");
                continue;
            }
            DBSObjectContainer rootContainer = (DBSObjectContainer) dataSource;
            // Parse entities
            Collection<Element> entityElemList = XMLUtils.getChildElementList(dsElem, TAG_ENTITY);
            monitor.beginTask("Parse entities", entityElemList.size());
            for (Element entityElem : entityElemList) {
                String tableId = entityElem.getAttribute(ATTR_ID);
                String tableName = entityElem.getAttribute(ATTR_NAME);
                monitor.subTask("Load " + tableName);
                List<String> path = new ArrayList<>();
                for (Element pathElem : XMLUtils.getChildElementList(entityElem, TAG_PATH)) {
                    path.add(0, pathElem.getAttribute(ATTR_NAME));
                }
                DBSObjectContainer container = rootContainer;
                for (String conName : path) {
                    final DBSObject child = container.getChild(monitor, conName);
                    if (child == null) {
                        diagram.addErrorMessage("Object '" + conName + "' not found within '" + container.getName() + "'");
                        container = null;
                        break;
                    }
                    if (child instanceof DBSObjectContainer) {
                        container = (DBSObjectContainer) child;
                    } else {
                        diagram.addErrorMessage("Object '" + child.getName() + "' is not a container");
                        container = null;
                        break;
                    }
                }
                if (container == null) {
                    continue;
                }
                final DBSObject child = container.getChild(monitor, tableName);
                if (!(child instanceof DBSEntity)) {
                    diagram.addErrorMessage("Cannot find table '" + tableName + "' in '" + container.getName() + "'");
                    continue;
                }
                String locX = entityElem.getAttribute(ATTR_X);
                String locY = entityElem.getAttribute(ATTR_Y);
                DBSEntity table = (DBSEntity) child;
                Rectangle bounds = new Rectangle();
                if (CommonUtils.isEmpty(locX) || CommonUtils.isEmpty(locY)) {
                    diagram.setNeedsAutoLayout(true);
                } else {
                    bounds.x = Integer.parseInt(locX);
                    bounds.y = Integer.parseInt(locY);
                }
                TableLoadInfo info = new TableLoadInfo(tableId, table, bounds);
                tableInfos.add(info);
                tableMap.put(info.objectId, info);
                monitor.worked(1);
            }
            monitor.done();
        }
    }
    final Element relationsElem = XMLUtils.getChildElement(diagramElem, TAG_RELATIONS);
    if (relationsElem != null) {
        // Parse relations
        Collection<Element> relElemList = XMLUtils.getChildElementList(relationsElem, TAG_RELATION);
        monitor.beginTask("Parse relations", relElemList.size());
        for (Element relElem : relElemList) {
            String relName = relElem.getAttribute(ATTR_NAME);
            monitor.subTask("Load " + relName);
            String relType = relElem.getAttribute(ATTR_TYPE);
            String pkRefId = relElem.getAttribute(ATTR_PK_REF);
            String fkRefId = relElem.getAttribute(ATTR_FK_REF);
            if (CommonUtils.isEmpty(relName) || CommonUtils.isEmpty(pkRefId) || CommonUtils.isEmpty(fkRefId)) {
                log.warn("Missing relation ID");
                continue;
            }
            TableLoadInfo pkTable = tableMap.get(pkRefId);
            TableLoadInfo fkTable = tableMap.get(fkRefId);
            if (pkTable == null || fkTable == null) {
                log.debug("PK (" + pkRefId + ") or FK (" + fkRefId + ") table(s) not found for relation " + relName);
                continue;
            }
            RelationLoadInfo relationLoadInfo = new RelationLoadInfo(relName, relType, pkTable, fkTable);
            relInfos.add(relationLoadInfo);
            // Load columns (present only in logical relations)
            for (Element columnElem : XMLUtils.getChildElementList(relElem, TAG_COLUMN)) {
                String name = columnElem.getAttribute(ATTR_NAME);
                String refName = columnElem.getAttribute(ATTR_REF_NAME);
                relationLoadInfo.columns.put(name, refName);
            }
            // Load bends
            for (Element bendElem : XMLUtils.getChildElementList(relElem, TAG_BEND)) {
                String type = bendElem.getAttribute(ATTR_TYPE);
                if (!BEND_RELATIVE.equals(type)) {
                    String locX = bendElem.getAttribute(ATTR_X);
                    String locY = bendElem.getAttribute(ATTR_Y);
                    if (!CommonUtils.isEmpty(locX) && !CommonUtils.isEmpty(locY)) {
                        relationLoadInfo.bends.add(new Point(Integer.parseInt(locX), Integer.parseInt(locY)));
                    }
                }
            }
            monitor.worked(1);
        }
        monitor.done();
    }
    // Load notes
    final Element notesElem = XMLUtils.getChildElement(diagramElem, TAG_NOTES);
    if (notesElem != null) {
        // Parse relations
        Collection<Element> noteElemList = XMLUtils.getChildElementList(notesElem, TAG_NOTE);
        monitor.beginTask("Parse notes", noteElemList.size());
        for (Element noteElem : noteElemList) {
            final String noteText = XMLUtils.getElementBody(noteElem);
            ERDNote note = new ERDNote(noteText);
            diagram.addNote(note, false);
            String locX = noteElem.getAttribute(ATTR_X);
            String locY = noteElem.getAttribute(ATTR_Y);
            String locW = noteElem.getAttribute(ATTR_W);
            String locH = noteElem.getAttribute(ATTR_H);
            if (!CommonUtils.isEmpty(locX) && !CommonUtils.isEmpty(locY) && !CommonUtils.isEmpty(locW) && !CommonUtils.isEmpty(locH)) {
                Rectangle bounds = new Rectangle(Integer.parseInt(locX), Integer.parseInt(locY), Integer.parseInt(locW), Integer.parseInt(locH));
                diagram.addInitBounds(note, bounds);
            }
        }
    }
    // Fill entities
    List<DBSEntity> tableList = new ArrayList<>();
    for (TableLoadInfo info : tableInfos) {
        tableList.add(info.table);
    }
    diagram.fillTables(monitor, tableList, null);
    // Set initial bounds
    for (TableLoadInfo info : tableInfos) {
        final ERDEntity erdEntity = diagram.getERDTable(info.table);
        if (erdEntity != null) {
            diagram.addInitBounds(erdEntity, info.bounds);
        }
    }
    // Add logical relations
    for (RelationLoadInfo info : relInfos) {
        if (info.type.equals(ERDConstants.CONSTRAINT_LOGICAL_FK.getId())) {
            final ERDEntity sourceEntity = diagram.getERDTable(info.pkTable.table);
            final ERDEntity targetEntity = diagram.getERDTable(info.fkTable.table);
            if (sourceEntity != null && targetEntity != null) {
                new ERDAssociation(targetEntity, sourceEntity, false);
            }
        }
    }
    // Set relations' bends
    for (RelationLoadInfo info : relInfos) {
        if (!CommonUtils.isEmpty(info.bends)) {
            final ERDEntity sourceEntity = diagram.getERDTable(info.pkTable.table);
            if (sourceEntity == null) {
                log.warn("Source table " + info.pkTable.table.getName() + " not found");
                continue;
            }
            final ERDEntity targetEntity = diagram.getERDTable(info.fkTable.table);
            if (targetEntity == null) {
                log.warn("Target table " + info.pkTable.table.getName() + " not found");
                continue;
            }
            diagram.addInitRelationBends(sourceEntity, targetEntity, info.name, info.bends);
        }
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) Element(org.w3c.dom.Element) Rectangle(org.eclipse.draw2d.geometry.Rectangle) Document(org.w3c.dom.Document) DataSourceRegistry(org.jkiss.dbeaver.registry.DataSourceRegistry) DataSourceDescriptor(org.jkiss.dbeaver.registry.DataSourceDescriptor) Point(org.eclipse.draw2d.geometry.Point)

Example 2 with DataSourceRegistry

use of org.jkiss.dbeaver.registry.DataSourceRegistry in project dbeaver by serge-rider.

the class EditorUtils method getFileDataSource.

@Nullable
public static DBPDataSourceContainer getFileDataSource(IFile file) {
    try {
        if (!file.exists()) {
            return null;
        }
        String projectId = file.getPersistentProperty(QN_PROJECT_ID);
        String dataSourceId = file.getPersistentProperty(QN_DATA_SOURCE_ID);
        if (dataSourceId != null) {
            IProject project = file.getProject();
            if (projectId != null) {
                final IProject fileProject = DBeaverCore.getInstance().getWorkspace().getRoot().getProject(projectId);
                if (fileProject != null && fileProject.exists()) {
                    project = fileProject;
                }
            }
            DataSourceRegistry dataSourceRegistry = DBeaverCore.getInstance().getProjectRegistry().getDataSourceRegistry(project);
            return dataSourceRegistry == null ? null : dataSourceRegistry.getDataSource(dataSourceId);
        } else {
            return null;
        }
    } catch (CoreException e) {
        log.error("Internal error while reading file property", e);
        return null;
    }
}
Also used : DataSourceRegistry(org.jkiss.dbeaver.registry.DataSourceRegistry) CoreException(org.eclipse.core.runtime.CoreException) IProject(org.eclipse.core.resources.IProject) Nullable(org.jkiss.code.Nullable)

Example 3 with DataSourceRegistry

use of org.jkiss.dbeaver.registry.DataSourceRegistry in project dbeaver by serge-rider.

the class DataSourceManagementToolbar method getAvailableDataSources.

private List<? extends DBPDataSourceContainer> getAvailableDataSources() {
    //Get project from active editor
    final IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
    if (activeEditor != null && activeEditor.getEditorInput() instanceof IFileEditorInput) {
        final IFile curFile = ((IFileEditorInput) activeEditor.getEditorInput()).getFile();
        if (curFile != null) {
            final DataSourceRegistry dsRegistry = DBeaverCore.getInstance().getProjectRegistry().getDataSourceRegistry(curFile.getProject());
            if (dsRegistry != null) {
                return dsRegistry.getDataSources();
            }
        }
    }
    final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
    if (dataSourceContainer != null) {
        return dataSourceContainer.getRegistry().getDataSources();
    } else {
        return DataSourceRegistry.getAllDataSources();
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) DataSourceRegistry(org.jkiss.dbeaver.registry.DataSourceRegistry) DBPDataSourceRegistry(org.jkiss.dbeaver.model.app.DBPDataSourceRegistry)

Example 4 with DataSourceRegistry

use of org.jkiss.dbeaver.registry.DataSourceRegistry in project dbeaver by serge-rider.

the class DataSourceManagementToolbar method createControl.

Control createControl(Composite parent) {
    workbenchWindow.addPageListener(pageListener);
    IWorkbenchPage activePage = workbenchWindow.getActivePage();
    if (activePage != null) {
        pageListener.pageOpened(activePage);
    }
    // Register as datasource listener in all datasources
    // We need it because at this moment there could be come already loaded registries (on startup)
    DataSourceProviderRegistry.getInstance().addDataSourceRegistryListener(DataSourceManagementToolbar.this);
    for (DataSourceRegistry registry : DataSourceRegistry.getAllRegistries()) {
        handleRegistryLoad(registry);
    }
    Composite comboGroup = new Composite(parent, SWT.NONE);
    RowLayout layout = new RowLayout(SWT.HORIZONTAL);
    layout.marginTop = 0;
    layout.marginBottom = 0;
    layout.marginWidth = 5;
    layout.marginHeight = 0;
    comboGroup.setLayout(layout);
    final int fontHeight = UIUtils.getFontHeight(parent);
    int comboWidth = fontHeight * 20;
    connectionCombo = new CSmartCombo<>(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER, new ConnectionLabelProvider());
    RowData rd = new RowData();
    rd.width = comboWidth;
    connectionCombo.setLayoutData(rd);
    connectionCombo.setVisibleItemCount(15);
    connectionCombo.setWidthHint(comboWidth);
    connectionCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_datasource_tooltip);
    connectionCombo.addItem(null);
    connectionCombo.select(0);
    connectionCombo.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            changeDataSourceSelection();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }
    });
    connectionCombo.setTableFilter(new CSmartCombo.TableFilter<DBPDataSourceContainer>() {

        boolean enabled = false;

        @Override
        public String getFilterLabel() {
            return "Connected";
        }

        @Override
        public String getDefaultLabel() {
            return "All";
        }

        @Override
        public boolean isEnabled() {
            return enabled;
        }

        @Override
        public boolean setEnabled(boolean enabled) {
            this.enabled = enabled;
            return enabled;
        }

        @Override
        public boolean filter(DBPDataSourceContainer item) {
            return item != null && item.isConnected();
        }
    });
    comboWidth = fontHeight * 16;
    databaseCombo = new CSmartCombo<>(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER, new DatabaseLabelProvider());
    rd = new RowData();
    rd.width = comboWidth;
    databaseCombo.setLayoutData(rd);
    databaseCombo.setVisibleItemCount(15);
    databaseCombo.setWidthHint(comboWidth);
    databaseCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_database_tooltip);
    databaseCombo.addItem(null);
    databaseCombo.select(0);
    databaseCombo.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            changeDataBaseSelection();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }
    });
    resultSetSize = new Text(comboGroup, SWT.BORDER);
    resultSetSize.setTextLimit(10);
    rd = new RowData();
    rd.width = fontHeight * 4;
    resultSetSize.setLayoutData(rd);
    resultSetSize.setToolTipText(CoreMessages.toolbar_datasource_selector_resultset_segment_size);
    final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
    if (dataSourceContainer != null) {
        resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS)));
    }
    //resultSetSize.setDigits(7);
    resultSetSize.addVerifyListener(UIUtils.getIntegerVerifyListener(Locale.getDefault()));
    resultSetSize.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {
        }

        @Override
        public void focusLost(FocusEvent e) {
            changeResultSetSize();
        }
    });
    comboGroup.addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            DataSourceManagementToolbar.this.dispose();
        }
    });
    DBeaverUI.asyncExec(new Runnable() {

        @Override
        public void run() {
            if (workbenchWindow != null && workbenchWindow.getActivePage() != null) {
                setActivePart(workbenchWindow.getActivePage().getActivePart());
            }
        }
    });
    return comboGroup;
}
Also used : Composite(org.eclipse.swt.widgets.Composite) Text(org.eclipse.swt.widgets.Text) RowData(org.eclipse.swt.layout.RowData) DataSourceRegistry(org.jkiss.dbeaver.registry.DataSourceRegistry) DBPDataSourceRegistry(org.jkiss.dbeaver.model.app.DBPDataSourceRegistry) CSmartCombo(org.jkiss.dbeaver.ui.controls.CSmartCombo) RowLayout(org.eclipse.swt.layout.RowLayout)

Example 5 with DataSourceRegistry

use of org.jkiss.dbeaver.registry.DataSourceRegistry in project dbeaver by serge-rider.

the class OpenHandler method getCurrentConnection.

@Nullable
private static DBPDataSourceContainer getCurrentConnection(ExecutionEvent event) {
    DBPDataSourceContainer dataSourceContainer = getDataSourceContainer(event, false);
    final ProjectRegistry projectRegistry = DBeaverCore.getInstance().getProjectRegistry();
    IProject project = dataSourceContainer != null ? dataSourceContainer.getRegistry().getProject() : projectRegistry.getActiveProject();
    if (dataSourceContainer == null) {
        final DataSourceRegistry dataSourceRegistry = projectRegistry.getDataSourceRegistry(project);
        if (dataSourceRegistry == null) {
            return null;
        }
        if (dataSourceRegistry.getDataSources().size() == 1) {
            dataSourceContainer = dataSourceRegistry.getDataSources().get(0);
        } else if (!dataSourceRegistry.getDataSources().isEmpty()) {
            dataSourceContainer = SelectDataSourceDialog.selectDataSource(HandlerUtil.getActiveShell(event), project);
        }
    }
    return dataSourceContainer;
}
Also used : DataSourceRegistry(org.jkiss.dbeaver.registry.DataSourceRegistry) ProjectRegistry(org.jkiss.dbeaver.registry.ProjectRegistry) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer) IProject(org.eclipse.core.resources.IProject) Nullable(org.jkiss.code.Nullable)

Aggregations

DataSourceRegistry (org.jkiss.dbeaver.registry.DataSourceRegistry)5 IProject (org.eclipse.core.resources.IProject)2 Nullable (org.jkiss.code.Nullable)2 DBPDataSourceRegistry (org.jkiss.dbeaver.model.app.DBPDataSourceRegistry)2 IFile (org.eclipse.core.resources.IFile)1 CoreException (org.eclipse.core.runtime.CoreException)1 Point (org.eclipse.draw2d.geometry.Point)1 Rectangle (org.eclipse.draw2d.geometry.Rectangle)1 RowData (org.eclipse.swt.layout.RowData)1 RowLayout (org.eclipse.swt.layout.RowLayout)1 Composite (org.eclipse.swt.widgets.Composite)1 Text (org.eclipse.swt.widgets.Text)1 DBException (org.jkiss.dbeaver.DBException)1 DBPDataSourceContainer (org.jkiss.dbeaver.model.DBPDataSourceContainer)1 DataSourceDescriptor (org.jkiss.dbeaver.registry.DataSourceDescriptor)1 ProjectRegistry (org.jkiss.dbeaver.registry.ProjectRegistry)1 CSmartCombo (org.jkiss.dbeaver.ui.controls.CSmartCombo)1 Document (org.w3c.dom.Document)1 Element (org.w3c.dom.Element)1