Search in sources :

Example 6 with DBSSchema

use of org.jkiss.dbeaver.model.struct.rdb.DBSSchema 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 7 with DBSSchema

use of org.jkiss.dbeaver.model.struct.rdb.DBSSchema 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 8 with DBSSchema

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

the class ModelPropertyTester method test.

@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
    if (!(receiver instanceof DBSObject)) {
        return false;
    }
    Display display = Display.getCurrent();
    if (display == null) {
        return false;
    }
    switch(property) {
        case PROP_CHILD_OF_TYPE:
            {
                {
                    DBSObject object = (DBSObject) receiver;
                    if (object instanceof DBSObjectContainer) {
                        if (expectedValue instanceof String) {
                            try {
                                Class<?> expectedChildClass = Class.forName((String) expectedValue);
                                Class<? extends DBSObject> childType = ((DBSObjectContainer) object).getPrimaryChildType(null);
                                return expectedChildClass.isAssignableFrom(childType);
                            } catch (Exception e) {
                                return false;
                            }
                        }
                    }
                }
                return false;
            }
        case PROP_IS_TABLE_CONTAINER:
            {
                DBSObject object = DBUtils.getPublicObject((DBSObject) receiver);
                if (object instanceof DBNContainer) {
                    Object valueObject = ((DBNContainer) object).getValueObject();
                    if (valueObject instanceof DBSObject) {
                        object = (DBSObject) valueObject;
                    }
                }
                if (object instanceof DBSSchema) {
                    return true;
                }
                if (object instanceof DBSObjectContainer) {
                    try {
                        Class<? extends DBSObject> primaryChildType = ((DBSObjectContainer) object).getPrimaryChildType(null);
                        if (DBSDataContainer.class.isAssignableFrom(primaryChildType)) {
                            return true;
                        }
                    } catch (DBException e) {
                        log.debug(e);
                    }
                }
                return false;
            }
    }
    return false;
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBNContainer(org.jkiss.dbeaver.model.navigator.DBNContainer) DBException(org.jkiss.dbeaver.DBException) DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBSObjectContainer(org.jkiss.dbeaver.model.struct.DBSObjectContainer) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBSDataContainer(org.jkiss.dbeaver.model.struct.DBSDataContainer) Display(org.eclipse.swt.widgets.Display)

Example 9 with DBSSchema

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

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(DBUtils.getQuotedIdentifier(dataSource, 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 10 with DBSSchema

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

the class DatabaseTransferConsumer method createTargetDatabaseObjects.

private boolean createTargetDatabaseObjects(DBRProgressMonitor monitor, DBSObject dbObject) throws DBException {
    try (DBCSession session = DBUtils.openMetaSession(monitor, dbObject, "Create target metadata")) {
        // We may need to change active catalog to create target object in the proper location
        DBSCatalog oldCatalog = null;
        DBSSchema oldSchema = null;
        DBSCatalog catalog = dbObject instanceof DBSSchema ? DBUtils.getParentOfType(DBSCatalog.class, dbObject) : null;
        if (catalog != null) {
            DBCExecutionContextDefaults contextDefaults = session.getExecutionContext().getContextDefaults();
            if (contextDefaults != null && contextDefaults.supportsCatalogChange() && contextDefaults.getDefaultCatalog() != catalog) {
                oldCatalog = contextDefaults.getDefaultCatalog();
                try {
                    contextDefaults.setDefaultCatalog(monitor, catalog, (DBSSchema) dbObject);
                } catch (DBCException e) {
                    log.debug(e);
                }
            }
        }
        try {
            switch(containerMapping.getMappingType()) {
                case create:
                    createTargetTable(session, containerMapping);
                    return true;
                case existing:
                    boolean hasNewObjects = false;
                    if (!(containerMapping.getTarget() instanceof DBSDocumentContainer)) {
                        for (DatabaseMappingAttribute attr : containerMapping.getAttributeMappings(monitor)) {
                            if (attr.getMappingType() == DatabaseMappingType.create) {
                                createTargetAttribute(session, attr);
                                hasNewObjects = true;
                            }
                        }
                    }
                    return hasNewObjects;
                default:
                    return false;
            }
        } finally {
            if (oldCatalog != null) {
                // Revert to old catalog
                try {
                    session.getExecutionContext().getContextDefaults().setDefaultCatalog(monitor, oldCatalog, oldSchema);
                } catch (DBCException e) {
                    log.debug(e);
                }
            }
        }
    }
}
Also used : DBSSchema(org.jkiss.dbeaver.model.struct.rdb.DBSSchema) DBSCatalog(org.jkiss.dbeaver.model.struct.rdb.DBSCatalog)

Aggregations

DBSSchema (org.jkiss.dbeaver.model.struct.rdb.DBSSchema)14 DBSCatalog (org.jkiss.dbeaver.model.struct.rdb.DBSCatalog)12 DBException (org.jkiss.dbeaver.DBException)7 DBCExecutionContextDefaults (org.jkiss.dbeaver.model.exec.DBCExecutionContextDefaults)7 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)7 DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)4 DBSObjectContainer (org.jkiss.dbeaver.model.struct.DBSObjectContainer)4 DBPDataSourceContainer (org.jkiss.dbeaver.model.DBPDataSourceContainer)2 DBCException (org.jkiss.dbeaver.model.exec.DBCException)2 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)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 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