Search in sources :

Example 11 with DataSourceDescriptor

use of org.jkiss.dbeaver.registry.DataSourceDescriptor 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 12 with DataSourceDescriptor

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

the class PendingTransactionsDialog method loadContexts.

private void loadContexts(boolean showAllContexts) {
    contextTree.removeAll();
    // Load all open context
    for (DataSourceDescriptor dataSource : DataSourceRegistry.getAllDataSources()) {
        if (!dataSource.isConnected() || dataSource.getDataSource() == null) {
            continue;
        }
        DBCExecutionContext[] allContexts = dataSource.getDataSource().getAllContexts();
        if (ArrayUtils.isEmpty(allContexts)) {
            continue;
        }
        List<DBCExecutionContext> txnContexts = new ArrayList<>();
        for (DBCExecutionContext context : allContexts) {
            if (showAllContexts || QMUtils.isTransactionActive(context)) {
                txnContexts.add(context);
            }
        }
        if (txnContexts.isEmpty()) {
            continue;
        }
        TreeItem dsItem = new TreeItem(contextTree, SWT.NONE);
        dsItem.setText(dataSource.getName());
        dsItem.setImage(DBeaverIcons.getImage(dataSource.getObjectImage()));
        dsItem.setData(dataSource);
        for (DBCExecutionContext context : txnContexts) {
            QMTransactionState txnState = QMUtils.getTransactionState(context);
            TreeItem contextItem = new TreeItem(dsItem, SWT.NONE);
            contextItem.setText(0, context.getContextName());
            String stateString = String.valueOf(txnState.getUpdateCount()) + "/" + String.valueOf(txnState.getExecuteCount());
            contextItem.setText(1, stateString);
            contextItem.setData(context);
        }
        dsItem.setExpanded(true);
    }
    UIUtils.packColumns(contextTree);
}
Also used : ArrayList(java.util.ArrayList) QMTransactionState(org.jkiss.dbeaver.model.qm.QMTransactionState) DataSourceDescriptor(org.jkiss.dbeaver.registry.DataSourceDescriptor)

Example 13 with DataSourceDescriptor

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

the class DataSourceHandler method disconnectDataSource.

public static void disconnectDataSource(DBPDataSourceContainer dataSourceContainer, @Nullable final Runnable onFinish) {
    // Save users
    for (DBPDataSourceUser user : dataSourceContainer.getUsers()) {
        if (user instanceof ISaveablePart) {
            if (!SaveChangesHandler.validateAndSave(VoidProgressMonitor.INSTANCE, (ISaveablePart) user)) {
                return;
            }
        }
    }
    if (!checkAndCloseActiveTransaction(dataSourceContainer)) {
        return;
    }
    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 DisconnectJob disconnectJob = new DisconnectJob(dataSourceDescriptor);
        disconnectJob.addJobChangeListener(new JobChangeAdapter() {

            @Override
            public void done(IJobChangeEvent event) {
                IStatus result = disconnectJob.getConnectStatus();
                if (onFinish != null) {
                    onFinish.run();
                } else if (!result.isOK()) {
                    UIUtils.showErrorDialog(null, disconnectJob.getName(), null, result);
                }
            }
        });
        // Run in UI thread to update actions (some Eclipse magic)
        DBeaverUI.asyncExec(new Runnable() {

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

Example 14 with DataSourceDescriptor

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

the class GenericConnectionPage method createEmbeddedDatabase.

private void createEmbeddedDatabase() {
    String paramCreate = CommonUtils.toString(site.getDriver().getDriverParameter(GenericConstants.PARAM_CREATE_URL_PARAM));
    DataSourceDescriptor dataSource = (DataSourceDescriptor) site.getActiveDataSource();
    final DataSourceDescriptor testDataSource = new DataSourceDescriptor(site.getDataSourceRegistry(), dataSource.getId(), dataSource.getDriver(), new DBPConnectionConfiguration(dataSource.getConnectionConfiguration()));
    saveSettings(testDataSource);
    DBPConnectionConfiguration cfg = testDataSource.getConnectionConfiguration();
    cfg.setUrl(cfg.getUrl() + paramCreate);
    String databaseName = cfg.getDatabaseName();
    testDataSource.setName(databaseName);
    if (!UIUtils.confirmAction(getShell(), "Create Database", "Are you sure you want to create database '" + databaseName + "'?")) {
        testDataSource.dispose();
        return;
    }
    try {
        site.getRunnableContext().run(true, true, new DBRRunnableWithProgress() {

            @Override
            public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    createEmbeddedDatabase(monitor, testDataSource);
                } catch (DBException e1) {
                    throw new InvocationTargetException(e1);
                }
            }
        });
        MessageDialog.openInformation(getShell(), "Database Create", "Database '" + databaseName + "' created!");
    } catch (InvocationTargetException e1) {
        UIUtils.showErrorDialog(getShell(), "Create database", "Error creating database", e1.getTargetException());
    } catch (InterruptedException e1) {
    // Just ignore
    }
}
Also used : DBPConnectionConfiguration(org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration) DBException(org.jkiss.dbeaver.DBException) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) InvocationTargetException(java.lang.reflect.InvocationTargetException) DataSourceDescriptor(org.jkiss.dbeaver.registry.DataSourceDescriptor)

Example 15 with DataSourceDescriptor

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

the class ConnectionPageGeneral method configureEvents.

private void configureEvents() {
    DataSourceDescriptor dataSource = getActiveDataSource();
    EditShellCommandsDialog dialog = new EditShellCommandsDialog(getShell(), dataSource);
    if (dialog.open() == IDialogConstants.OK_ID) {
        eventsButton.setFont(getFont());
        for (DBPConnectionEventType eventType : dataSource.getConnectionConfiguration().getDeclaredEvents()) {
            if (dataSource.getConnectionConfiguration().getEvent(eventType).isEnabled()) {
                eventsButton.setFont(boldFont);
                break;
            }
        }
    }
}
Also used : DBPConnectionEventType(org.jkiss.dbeaver.model.connection.DBPConnectionEventType) DataSourceDescriptor(org.jkiss.dbeaver.registry.DataSourceDescriptor)

Aggregations

DataSourceDescriptor (org.jkiss.dbeaver.registry.DataSourceDescriptor)21 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 DBException (org.jkiss.dbeaver.DBException)4 DBPConnectionConfiguration (org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration)4 DriverDescriptor (org.jkiss.dbeaver.registry.driver.DriverDescriptor)4 IStatus (org.eclipse.core.runtime.IStatus)2 IJobChangeEvent (org.eclipse.core.runtime.jobs.IJobChangeEvent)2 JobChangeAdapter (org.eclipse.core.runtime.jobs.JobChangeAdapter)2 ModifyEvent (org.eclipse.swt.events.ModifyEvent)2 ModifyListener (org.eclipse.swt.events.ModifyListener)2 SelectionAdapter (org.eclipse.swt.events.SelectionAdapter)2 SelectionEvent (org.eclipse.swt.events.SelectionEvent)2 GridData (org.eclipse.swt.layout.GridData)2 GridLayout (org.eclipse.swt.layout.GridLayout)2 Composite (org.eclipse.swt.widgets.Composite)2 Control (org.eclipse.swt.widgets.Control)2 DBPConnectionEventType (org.jkiss.dbeaver.model.connection.DBPConnectionEventType)2 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)2 DBRRunnableWithProgress (org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress)2 DBSObjectContainer (org.jkiss.dbeaver.model.struct.DBSObjectContainer)2