Search in sources :

Example 1 with DBSCatalog

use of org.jkiss.dbeaver.model.struct.rdb.DBSCatalog in project dbeaver by serge-rider.

the class DatabaseTransferConsumer method generateTargetTableDDL.

public static String generateTargetTableDDL(DBRProgressMonitor monitor, DBPDataSource dataSource, DBSObjectContainer schema, DatabaseMappingContainer containerMapping) throws DBException {
    monitor.subTask("Create table " + containerMapping.getTargetName());
    StringBuilder sql = new StringBuilder(500);
    if (!(dataSource instanceof SQLDataSource)) {
        throw new DBException("Data source doesn't support SQL");
    }
    SQLDataSource targetDataSource = (SQLDataSource) dataSource;
    String tableName = DBObjectNameCaseTransformer.transformName(targetDataSource, containerMapping.getTargetName());
    containerMapping.setTargetName(tableName);
    sql.append("CREATE TABLE ");
    if (schema instanceof DBSSchema || schema instanceof DBSCatalog) {
        sql.append(DBUtils.getQuotedIdentifier(schema));
        sql.append(targetDataSource.getSQLDialect().getCatalogSeparator());
    }
    sql.append(DBUtils.getQuotedIdentifier(targetDataSource, tableName)).append("(\n");
    Map<DBSAttributeBase, DatabaseMappingAttribute> mappedAttrs = new HashMap<>();
    for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
        if (attr.getMappingType() != DatabaseMappingType.create) {
            continue;
        }
        if (!mappedAttrs.isEmpty())
            sql.append(",\n");
        appendAttributeClause(dataSource, sql, attr);
        mappedAttrs.put(attr.getSource(), attr);
    }
    if (containerMapping.getSource() instanceof DBSEntity) {
        // Make primary key
        Collection<? extends DBSEntityAttribute> identifier = DBUtils.getBestTableIdentifier(monitor, (DBSEntity) containerMapping.getSource());
        if (!CommonUtils.isEmpty(identifier)) {
            boolean idMapped = true;
            for (DBSEntityAttribute idAttr : identifier) {
                if (!mappedAttrs.containsKey(idAttr)) {
                    idMapped = false;
                    break;
                }
            }
            if (idMapped) {
                sql.append(",\nPRIMARY KEY (");
                boolean hasAttr = false;
                for (DBSEntityAttribute idAttr : identifier) {
                    DatabaseMappingAttribute mappedAttr = mappedAttrs.get(idAttr);
                    if (hasAttr)
                        sql.append(",");
                    sql.append(mappedAttr.getTargetName());
                    hasAttr = true;
                }
                sql.append(")\n");
            }
        }
    }
    sql.append(")");
    return sql.toString();
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBSCatalog(org.jkiss.dbeaver.model.struct.rdb.DBSCatalog) SQLDataSource(org.jkiss.dbeaver.model.sql.SQLDataSource) DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema)

Example 2 with DBSCatalog

use of org.jkiss.dbeaver.model.struct.rdb.DBSCatalog in project dbeaver by dbeaver.

the class ExasolCreateForeignKeyDialog method createSchemaSelector.

private void createSchemaSelector(Composite tableGroup) throws DBException {
    // Here is a trick - we need to find schema/catalog container node and list its children
    DBNDatabaseNode schemaContainerNode = null;
    for (DBNNode node = ownerTableNode.getParentNode(); node != null; node = node.getParentNode()) {
        if (node instanceof DBNDatabaseNode) {
            DBSObject nodeObject = ((DBNDatabaseNode) node).getObject();
            if (nodeObject instanceof DBSSchema || nodeObject instanceof DBSCatalog) {
                if (node.getParentNode() instanceof DBNDatabaseNode) {
                    schemaContainerNode = (DBNDatabaseNode) node.getParentNode();
                    break;
                }
            }
        }
    }
    if (schemaContainerNode != null) {
        ILabelProvider labelProvider = new LabelProvider() {

            @Override
            public Image getImage(Object element) {
                return DBeaverIcons.getImage(((DBNDatabaseNode) element).getNodeIcon());
            }

            @Override
            public String getText(Object element) {
                return ((DBNDatabaseNode) element).getNodeName();
            }
        };
        boolean isSchema = (ownTable.getParentObject() instanceof DBSSchema);
        DBPDataSourceInfo dsInfo = ownTable.getDataSource().getInfo();
        UIUtils.createControlLabel(tableGroup, isSchema ? dsInfo.getSchemaTerm() : dsInfo.getCatalogTerm());
        final CSmartCombo<DBNDatabaseNode> schemaCombo = new CSmartCombo<>(tableGroup, SWT.BORDER, labelProvider);
        schemaCombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
        DBNDatabaseNode selectedNode = null;
        for (DBNNode node : schemaContainerNode.getChildren(new VoidProgressMonitor())) {
            if (node instanceof DBNDatabaseNode && ((DBNDatabaseNode) node).getObject() instanceof DBSObjectContainer) {
                schemaCombo.addItem((DBNDatabaseNode) node);
                if (((DBNDatabaseNode) node).getObject() == ownTable.getParentObject()) {
                    selectedNode = (DBNDatabaseNode) node;
                }
            }
        }
        if (selectedNode != null) {
            schemaCombo.select(selectedNode);
        }
        schemaCombo.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                // Here is another trick
                // We need to find table container node
                // This node is a child of schema node and has the same meta as our original table parent node
                DBNDatabaseNode newContainerNode = null;
                DBXTreeNode tableContainerMeta = ((DBNDatabaseNode) ownerTableNode.getParentNode()).getMeta();
                DBNDatabaseNode schemaNode = schemaCombo.getSelectedItem();
                if (schemaNode.getMeta() == tableContainerMeta) {
                    newContainerNode = schemaNode;
                } else {
                    try {
                        for (DBNNode child : schemaNode.getChildren(new VoidProgressMonitor())) {
                            if (child instanceof DBNDatabaseNode && ((DBNDatabaseNode) child).getMeta() == tableContainerMeta) {
                                newContainerNode = (DBNDatabaseNode) child;
                                break;
                            }
                        }
                    } catch (DBException e1) {
                        log.debug(e1);
                    // Shouldn't be here
                    }
                }
                if (newContainerNode != null) {
                    tableList.setRootNode(newContainerNode);
                    tableList.loadData();
                }
            }
        });
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBSCatalog(org.jkiss.dbeaver.model.struct.rdb.DBSCatalog) DBNNode(org.jkiss.dbeaver.model.navigator.DBNNode) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) ILabelProvider(org.eclipse.jface.viewers.ILabelProvider) DBPDataSourceInfo(org.jkiss.dbeaver.model.DBPDataSourceInfo) DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBXTreeNode(org.jkiss.dbeaver.model.navigator.meta.DBXTreeNode) CSmartCombo(org.jkiss.dbeaver.ui.controls.CSmartCombo) GridData(org.eclipse.swt.layout.GridData) DBSObjectContainer(org.jkiss.dbeaver.model.struct.DBSObjectContainer) SelectionEvent(org.eclipse.swt.events.SelectionEvent) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) VoidProgressMonitor(org.jkiss.dbeaver.model.runtime.VoidProgressMonitor) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode) ILabelProvider(org.eclipse.jface.viewers.ILabelProvider) LabelProvider(org.eclipse.jface.viewers.LabelProvider)

Example 3 with DBSCatalog

use of org.jkiss.dbeaver.model.struct.rdb.DBSCatalog in project dbeaver by serge-rider.

the class SQLScriptExecuteHandler method runScripts.

private void runScripts(DBRProgressMonitor monitor, DBTTask task, SQLScriptExecuteSettings settings, Log log, PrintStream logStream) throws DBException {
    List<DBPDataSourceContainer> dataSources = settings.getDataSources();
    for (String filePath : settings.getScriptFiles()) {
        IFile sqlFile = SQLScriptExecuteSettings.getWorkspaceFile(filePath);
        try (InputStream sqlStream = sqlFile.getContents(true)) {
            try (Reader fileReader = new InputStreamReader(sqlStream, sqlFile.getCharset())) {
                String sqlScriptContent = IOUtils.readToString(fileReader);
                try {
                    for (DBPDataSourceContainer dataSourceContainer : dataSources) {
                        if (!dataSourceContainer.isConnected()) {
                            dataSourceContainer.connect(monitor, true, true);
                        }
                        DBPDataSource dataSource = dataSourceContainer.getDataSource();
                        if (dataSource == null) {
                            throw new DBException("Can't obtain data source connection");
                        }
                        DBCExecutionContext executionContext = dataSource.getDefaultInstance().getDefaultContext(monitor, false);
                        log.debug("> Execute script [" + filePath + "] in [" + dataSourceContainer.getName() + "]");
                        DBCExecutionContextDefaults contextDefaults = executionContext.getContextDefaults();
                        if (contextDefaults != null) {
                            DBSCatalog defaultCatalog = contextDefaults.getDefaultCatalog();
                            if (defaultCatalog != null) {
                                log.debug("> Default catalog: " + defaultCatalog.getName());
                            }
                            DBSSchema defaultSchema = contextDefaults.getDefaultSchema();
                            if (defaultSchema != null) {
                                log.debug("> Default schema: " + defaultSchema.getName());
                            }
                        }
                        processScript(monitor, task, settings, executionContext, filePath, sqlScriptContent, log, logStream);
                    }
                } catch (Exception e) {
                    throw new InvocationTargetException(e);
                }
            }
        } catch (Throwable e) {
            Throwable error = e instanceof InvocationTargetException ? ((InvocationTargetException) e).getTargetException() : e;
            throw new DBException("Error executing script '" + filePath + "'", error);
        }
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBCExecutionContextDefaults(org.jkiss.dbeaver.model.exec.DBCExecutionContextDefaults) IFile(org.eclipse.core.resources.IFile) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) DBSCatalog(org.jkiss.dbeaver.model.struct.rdb.DBSCatalog) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBException(org.jkiss.dbeaver.DBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer)

Example 4 with DBSCatalog

use of org.jkiss.dbeaver.model.struct.rdb.DBSCatalog in project dbeaver by serge-rider.

the class DatabaseTransferUtils method generateTargetTableDDL.

public static DBEPersistAction[] generateTargetTableDDL(DBRProgressMonitor monitor, DBCExecutionContext executionContext, DBSObjectContainer schema, DatabaseMappingContainer containerMapping) throws DBException {
    if (containerMapping.getMappingType() == DatabaseMappingType.skip) {
        return new DBEPersistAction[0];
    }
    monitor.subTask("Create table '" + containerMapping.getTargetName() + "'");
    if (USE_STRUCT_DDL) {
        DBEPersistAction[] ddl = generateStructTableDDL(monitor, executionContext, schema, containerMapping);
        if (ddl != null) {
            return ddl;
        }
    }
    // Struct doesn't work (no proper object managers?)
    // Try plain SQL mode
    DBPDataSource dataSource = executionContext.getDataSource();
    StringBuilder sql = new StringBuilder(500);
    String tableName = DBObjectNameCaseTransformer.transformName(dataSource, containerMapping.getTargetName());
    containerMapping.setTargetName(tableName);
    List<DBEPersistAction> actions = new ArrayList<>();
    if (containerMapping.getMappingType() == DatabaseMappingType.create) {
        sql.append("CREATE TABLE ");
        if (schema instanceof DBSSchema || schema instanceof DBSCatalog) {
            sql.append(DBUtils.getQuotedIdentifier(schema));
            sql.append(dataSource.getSQLDialect().getCatalogSeparator());
        }
        sql.append(DBUtils.getQuotedIdentifier(dataSource, tableName)).append("(\n");
        Map<DBSAttributeBase, DatabaseMappingAttribute> mappedAttrs = new HashMap<>();
        for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
            if (attr.getMappingType() != DatabaseMappingType.create) {
                continue;
            }
            if (!mappedAttrs.isEmpty())
                sql.append(",\n");
            sql.append("\t");
            appendAttributeClause(dataSource, sql, attr);
            mappedAttrs.put(attr.getSource(), attr);
        }
        if (containerMapping.getSource() instanceof DBSEntity) {
            // Make primary key
            Collection<? extends DBSEntityAttribute> identifier = DBUtils.getBestTableIdentifier(monitor, (DBSEntity) containerMapping.getSource());
            if (!CommonUtils.isEmpty(identifier)) {
                boolean idMapped = true;
                for (DBSEntityAttribute idAttr : identifier) {
                    if (!mappedAttrs.containsKey(idAttr)) {
                        idMapped = false;
                        break;
                    }
                }
                if (idMapped) {
                    sql.append(",\n\tPRIMARY KEY (");
                    boolean hasAttr = false;
                    for (DBSEntityAttribute idAttr : identifier) {
                        DatabaseMappingAttribute mappedAttr = mappedAttrs.get(idAttr);
                        if (hasAttr)
                            sql.append(",");
                        sql.append(DBUtils.getQuotedIdentifier(dataSource, mappedAttr.getTargetName()));
                        hasAttr = true;
                    }
                    sql.append(")\n");
                }
            }
        }
        sql.append(")");
        actions.add(new SQLDatabasePersistAction("Table DDL", sql.toString()));
    } else {
        for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
            if (attr.getMappingType() == DatabaseMappingType.create) {
                actions.add(generateTargetAttributeDDL(dataSource, attr));
            }
        }
    }
    return actions.toArray(new DBEPersistAction[0]);
}
Also used : DBSCatalog(org.jkiss.dbeaver.model.struct.rdb.DBSCatalog) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction) DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema)

Example 5 with DBSCatalog

use of org.jkiss.dbeaver.model.struct.rdb.DBSCatalog in project dbeaver by serge-rider.

the class SelectActiveSchemaHandler method updateElement.

@Override
public void updateElement(UIElement element, Map parameters) {
    if ("true".equals(parameters.get("noCustomLabel"))) {
        return;
    }
    IWorkbenchWindow workbenchWindow = element.getServiceLocator().getService(IWorkbenchWindow.class);
    if (workbenchWindow == null || workbenchWindow.getActivePage() == null) {
        return;
    }
    IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
    if (activeEditor == null) {
        return;
    }
    String schemaName = "< N/A >";
    DBIcon schemaIcon = DBIcon.TREE_SCHEMA;
    String schemaTooltip = UINavigatorMessages.toolbar_datasource_selector_combo_database_tooltip;
    DBPDataSourceContainer dataSource = DataSourceToolbarUtils.getCurrentDataSource(workbenchWindow);
    if (dataSource != null && dataSource.isConnected()) {
        // schemaName = "<no schema>";
        IEditorInput editorInput = activeEditor.getEditorInput();
        if (editorInput instanceof IDatabaseEditorInput) {
            if (editorInput instanceof DatabaseLazyEditorInput) {
                activeEditor.addPropertyListener(new IPropertyListener() {

                    @Override
                    public void propertyChanged(Object source, int propId) {
                        if (EntityEditor.PROP_TITLE == propId) {
                            DataSourceToolbarUtils.updateCommandsUI();
                            activeEditor.removePropertyListener(this);
                        }
                    }
                });
            }
            DBCExecutionContext executionContext = ((IDatabaseEditorInput) editorInput).getExecutionContext();
            if (executionContext != null) {
                DBSObject schemaObject = DBUtils.getSelectedObject(executionContext);
                if (schemaObject != null && DBUtils.getPublicObjectContainer(schemaObject) != dataSource) {
                    DBSObject schemaParent = schemaObject.getParentObject();
                    if (schemaParent instanceof DBSObjectContainer && !(schemaParent instanceof DBPDataSource)) {
                        schemaName = schemaObject.getName() + "@" + schemaParent.getName();
                    } else {
                        schemaName = schemaObject.getName();
                    }
                }
            }
        } else {
            DBCExecutionContext executionContext = getExecutionContextFromPart(activeEditor);
            DBCExecutionContextDefaults contextDefaults = null;
            if (executionContext != null) {
                contextDefaults = executionContext.getContextDefaults();
            }
            if (contextDefaults != null) {
                DBSCatalog defaultCatalog = contextDefaults.getDefaultCatalog();
                DBSSchema defaultSchema = contextDefaults.getDefaultSchema();
                if (defaultCatalog != null && (defaultSchema != null || contextDefaults.supportsSchemaChange())) {
                    schemaName = defaultSchema == null ? "?" : defaultSchema.getName() + "@" + defaultCatalog.getName();
                    schemaIcon = DBIcon.TREE_SCHEMA;
                } else if (defaultCatalog != null) {
                    schemaName = defaultCatalog.getName();
                    schemaIcon = DBIcon.TREE_DATABASE;
                } else if (defaultSchema != null) {
                    schemaName = defaultSchema.getName();
                    schemaIcon = DBIcon.TREE_SCHEMA;
                }
            }
        }
    }
    element.setText(schemaName);
    element.setIcon(DBeaverIcons.getImageDescriptor(schemaIcon));
    element.setTooltip(schemaTooltip);
}
Also used : IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) DBCExecutionContextDefaults(org.jkiss.dbeaver.model.exec.DBCExecutionContextDefaults) DatabaseLazyEditorInput(org.jkiss.dbeaver.ui.editors.DatabaseLazyEditorInput) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) DBSCatalog(org.jkiss.dbeaver.model.struct.rdb.DBSCatalog) IEditorPart(org.eclipse.ui.IEditorPart) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) IPropertyListener(org.eclipse.ui.IPropertyListener) IDatabaseEditorInput(org.jkiss.dbeaver.ui.editors.IDatabaseEditorInput) DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBSObjectContainer(org.jkiss.dbeaver.model.struct.DBSObjectContainer) DBIcon(org.jkiss.dbeaver.model.DBIcon) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer) IEditorInput(org.eclipse.ui.IEditorInput)

Aggregations

DBSCatalog (org.jkiss.dbeaver.model.struct.rdb.DBSCatalog)12 DBSSchema (org.jkiss.dbeaver.model.struct.rdb.DBSSchema)12 DBCExecutionContextDefaults (org.jkiss.dbeaver.model.exec.DBCExecutionContextDefaults)6 DBException (org.jkiss.dbeaver.DBException)5 DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)5 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)5 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 DBPDataSourceContainer (org.jkiss.dbeaver.model.DBPDataSourceContainer)2 DBCException (org.jkiss.dbeaver.model.exec.DBCException)2 DBNNode (org.jkiss.dbeaver.model.navigator.DBNNode)2 VoidProgressMonitor (org.jkiss.dbeaver.model.runtime.VoidProgressMonitor)2 SQLDataSource (org.jkiss.dbeaver.model.sql.SQLDataSource)2 DBSObjectContainer (org.jkiss.dbeaver.model.struct.DBSObjectContainer)2 ExecutionException (org.eclipse.core.commands.ExecutionException)1 IFile (org.eclipse.core.resources.IFile)1 ILabelProvider (org.eclipse.jface.viewers.ILabelProvider)1 LabelProvider (org.eclipse.jface.viewers.LabelProvider)1 SelectionAdapter (org.eclipse.swt.events.SelectionAdapter)1 SelectionEvent (org.eclipse.swt.events.SelectionEvent)1