Search in sources :

Example 6 with SQLDatabasePersistActionComment

use of org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment in project dbeaver by dbeaver.

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 7 with SQLDatabasePersistActionComment

use of org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment in project dbeaver by dbeaver.

the class SQLToolExecuteHandler method executeTool.

private void executeTool(DBRProgressMonitor monitor, DBTTask task, SETTINGS settings, Log log, PrintStream outLog, DBTTaskExecutionListener listener) throws DBException, IOException {
    List<OBJECT_TYPE> objectList = settings.getObjectList();
    Exception lastError = null;
    listener.taskStarted(settings);
    try {
        monitor.beginTask("Execute tool '" + task.getType().getName() + "'", objectList.size());
        List<Throwable> warnings = settings.getWarnings();
        if (!warnings.isEmpty()) {
            Throwable throwable = warnings.get(0);
            throw new DBCException("Tool execution error: " + throwable.getMessage(), throwable);
        }
        for (OBJECT_TYPE object : objectList) {
            monitor.subTask("Process [" + DBUtils.getObjectFullName(object, DBPEvaluationContext.UI) + "]");
            try (DBCSession session = DBUtils.openUtilSession(monitor, object, "Execute " + task.getType().getName())) {
                List<DBEPersistAction> queries = new ArrayList<>();
                generateObjectQueries(session, settings, queries, object);
                DBCExecutionContext context = session.getExecutionContext();
                DBCTransactionManager txnManager = DBUtils.getTransactionManager(context);
                boolean isAutoCommitModeSwitchedOn = true;
                try {
                    if (isRunInAutoCommit() && txnManager != null && !txnManager.isAutoCommit()) {
                        isAutoCommitModeSwitchedOn = false;
                        txnManager.setAutoCommit(monitor, true);
                    }
                    for (DBEPersistAction action : queries) {
                        if (monitor.isCanceled()) {
                            break;
                        }
                        if (!CommonUtils.isEmpty(action.getTitle())) {
                            monitor.subTask(action.getTitle());
                        }
                        try {
                            if (action instanceof SQLDatabasePersistActionComment) {
                                continue;
                            }
                            String script = action.getScript();
                            if (!CommonUtils.isEmpty(script)) {
                                long startTime = System.currentTimeMillis();
                                try (final DBCStatement statement = session.prepareStatement(DBCStatementType.SCRIPT, script, false, false, false)) {
                                    long execTime = System.currentTimeMillis() - startTime;
                                    statement.executeStatement();
                                    if (listener instanceof SQLToolRunListener) {
                                        if (action.getType() != DBEPersistAction.ActionType.INITIALIZER && action.getType() != DBEPersistAction.ActionType.FINALIZER) {
                                            SQLToolStatisticsSimple statisticsSimple = new SQLToolStatisticsSimple(object, false);
                                            if (SQLToolExecuteHandler.this instanceof SQLToolRunStatisticsGenerator) {
                                                List<? extends SQLToolStatistics> executeStatistics = ((SQLToolRunStatisticsGenerator) SQLToolExecuteHandler.this).getExecuteStatistics(object, settings, action, session, statement);
                                                monitor.subTask("\tFinished in " + RuntimeUtils.formatExecutionTime(execTime));
                                                if (!CommonUtils.isEmpty(executeStatistics)) {
                                                    for (SQLToolStatistics stat : executeStatistics) {
                                                        stat.setExecutionTime(execTime);
                                                    }
                                                    ((SQLToolRunListener) listener).handleActionStatistics(object, action, session, executeStatistics);
                                                } else {
                                                    ((SQLToolRunListener) listener).handleActionStatistics(object, action, session, Collections.singletonList(statisticsSimple));
                                                }
                                            } else {
                                                ((SQLToolRunListener) listener).handleActionStatistics(object, action, session, Collections.singletonList(statisticsSimple));
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            lastError = e;
                            log.debug("Error executing query", e);
                            outLog.println("Error executing query\n" + e.getMessage());
                            if (listener instanceof SQLToolRunListener) {
                                SQLToolStatisticsSimple errorStat = new SQLToolStatisticsSimple(object, true);
                                errorStat.setStatusMessage(e.getMessage());
                                ((SQLToolRunListener) listener).handleActionStatistics(object, action, session, Collections.singletonList(errorStat));
                            }
                        } finally {
                            monitor.worked(1);
                        }
                    }
                } finally {
                    if (!isAutoCommitModeSwitchedOn) {
                        try {
                            txnManager.setAutoCommit(monitor, false);
                        } catch (DBCException e) {
                            log.debug("Cannot set auto-commit status", e);
                        }
                    }
                }
            }
            monitor.worked(1);
        }
    } catch (Exception e) {
        lastError = e;
        outLog.println("Process error\n" + e.getMessage());
    } finally {
        monitor.done();
    }
    listener.taskFinished(settings, lastError);
    outLog.println("Tool execution finished");
    outLog.flush();
}
Also used : SQLDatabasePersistActionComment(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBException(org.jkiss.dbeaver.DBException) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction)

Example 8 with SQLDatabasePersistActionComment

use of org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment in project dbeaver by dbeaver.

the class PostgreTableManagerBase method getTableGrantPermissionActions.

public static void getTableGrantPermissionActions(DBRProgressMonitor monitor, PostgreTableBase table, List<DBEPersistAction> actions, Map<String, Object> options) throws DBException {
    if (CommonUtils.getOption(options, PostgreConstants.OPTION_DDL_SHOW_PERMISSIONS)) {
        // Permissions
        Collection<PostgrePermission> permissions = table.getPermissions(monitor);
        if (!CommonUtils.isEmpty(permissions)) {
            actions.add(new SQLDatabasePersistActionComment(table.getDataSource(), "Permissions"));
            for (PostgrePermission permission : permissions) {
                if (permission.hasAllPrivileges(table)) {
                    Collections.addAll(actions, new PostgreCommandGrantPrivilege(permission.getOwner(), true, permission, PostgrePrivilegeType.ALL).getPersistActions(options));
                } else {
                    PostgreCommandGrantPrivilege grant = new PostgreCommandGrantPrivilege(permission.getOwner(), true, permission, permission.getPrivileges());
                    Collections.addAll(actions, grant.getPersistActions(options));
                }
            }
        }
    }
}
Also used : SQLDatabasePersistActionComment(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment)

Example 9 with SQLDatabasePersistActionComment

use of org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment 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 10 with SQLDatabasePersistActionComment

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

the class PostgreUtils method getObjectGrantPermissionActions.

public static void getObjectGrantPermissionActions(DBRProgressMonitor monitor, PostgrePrivilegeOwner object, List<DBEPersistAction> actions, Map<String, Object> options) throws DBException {
    if (object.isPersisted() && CommonUtils.getOption(options, DBPScriptObject.OPTION_INCLUDE_PERMISSIONS)) {
        DBCExecutionContext executionContext = DBUtils.getDefaultContext(object, true);
        actions.add(new SQLDatabasePersistActionComment(object.getDataSource(), "Permissions"));
        // Owner
        PostgreRole owner = object.getOwner(monitor);
        if (owner != null) {
            String alterScript = object.generateChangeOwnerQuery(DBUtils.getQuotedIdentifier(owner));
            if (!CommonUtils.isEmpty(alterScript)) {
                actions.add(new SQLDatabasePersistAction("Owner change", alterScript));
            }
        }
        // Permissions
        Collection<PostgrePrivilege> permissions = object.getPrivileges(monitor, true);
        if (!CommonUtils.isEmpty(permissions)) {
            for (PostgrePrivilege permission : permissions) {
                if (permission.hasAllPrivileges(object)) {
                    Collections.addAll(actions, new PostgreCommandGrantPrivilege(permission.getOwner(), true, object, permission, new PostgrePrivilegeType[] { PostgrePrivilegeType.ALL }).getPersistActions(monitor, executionContext, options));
                } else {
                    PostgreCommandGrantPrivilege grant = new PostgreCommandGrantPrivilege(permission.getOwner(), true, object, permission, permission.getPrivileges());
                    Collections.addAll(actions, grant.getPersistActions(monitor, executionContext, options));
                }
            }
        }
    }
}
Also used : PostgreCommandGrantPrivilege(org.jkiss.dbeaver.ext.postgresql.edit.PostgreCommandGrantPrivilege) SQLDatabasePersistActionComment(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment) SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction)

Aggregations

SQLDatabasePersistActionComment (org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment)14 DBException (org.jkiss.dbeaver.DBException)9 SQLDatabasePersistAction (org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction)9 DBEPersistAction (org.jkiss.dbeaver.model.edit.DBEPersistAction)6 DBSEntityAssociation (org.jkiss.dbeaver.model.struct.DBSEntityAssociation)3 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ArrayList (java.util.ArrayList)2 GenericTableBase (org.jkiss.dbeaver.ext.generic.model.GenericTableBase)2 GenericTableColumn (org.jkiss.dbeaver.ext.generic.model.GenericTableColumn)2 PostgreCommandGrantPrivilege (org.jkiss.dbeaver.ext.postgresql.edit.PostgreCommandGrantPrivilege)2 PostgreForeignTableManager (org.jkiss.dbeaver.ext.postgresql.edit.PostgreForeignTableManager)2 PostgreTableColumnManager (org.jkiss.dbeaver.ext.postgresql.edit.PostgreTableColumnManager)2 DBPScriptObject (org.jkiss.dbeaver.model.DBPScriptObject)2 DBECommandContext (org.jkiss.dbeaver.model.edit.DBECommandContext)2 DBERegistry (org.jkiss.dbeaver.model.edit.DBERegistry)2 DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)2 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)2 DBSEntity (org.jkiss.dbeaver.model.struct.DBSEntity)2 DBSEntityAttribute (org.jkiss.dbeaver.model.struct.DBSEntityAttribute)2