Search in sources :

Example 76 with DBEPersistAction

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

the class DBStructUtils method generateObjectDDL.

public static String generateObjectDDL(@NotNull DBRProgressMonitor monitor, @NotNull DBSObject object, Map<String, Object> options, boolean addComments) throws DBException {
    final DBERegistry editorsRegistry = object.getDataSource().getContainer().getPlatform().getEditorsRegistry();
    final SQLObjectEditor entityEditor = editorsRegistry.getObjectManager(object.getClass(), SQLObjectEditor.class);
    if (entityEditor != null) {
        SQLObjectEditor.ObjectCreateCommand createCommand = entityEditor.makeCreateCommand(object, options);
        DBEPersistAction[] ddlActions = createCommand.getPersistActions(monitor, DBUtils.getDefaultContext(object, true), options);
        return SQLUtils.generateScript(object.getDataSource(), ddlActions, addComments);
    }
    log.debug("Object editor not found for " + object.getClass().getName());
    return SQLUtils.generateCommentLine(object.getDataSource(), "Can't generate DDL: object editor not found for " + object.getClass().getName());
}
Also used : DBERegistry(org.jkiss.dbeaver.model.edit.DBERegistry) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) SQLObjectEditor(org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor)

Example 77 with DBEPersistAction

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

the class NavigatorHandlerObjectBase method showScript.

protected static boolean showScript(IWorkbenchWindow workbenchWindow, DBECommandContext commandContext, Map<String, Object> options, String dialogTitle) {
    Collection<? extends DBECommand> commands = commandContext.getFinalCommands();
    StringBuilder script = new StringBuilder();
    try {
        UIUtils.runInProgressService(monitor -> {
            try {
                for (DBECommand command : commands) {
                    DBEPersistAction[] persistActions = command.getPersistActions(monitor, commandContext.getExecutionContext(), options);
                    script.append(SQLUtils.generateScript(commandContext.getExecutionContext().getDataSource(), persistActions, false));
                    if (script.length() == 0) {
                        script.append(SQLUtils.generateComments(commandContext.getExecutionContext().getDataSource(), persistActions, false));
                    }
                }
            } catch (DBException e) {
                throw new InvocationTargetException(e);
            }
        });
    } catch (InvocationTargetException e) {
        DBWorkbench.getPlatformUI().showError("Script generation error", "Error generating alter script", e.getTargetException());
    } catch (InterruptedException e) {
        return false;
    }
    if (script.length() > 0) {
        UIServiceSQL serviceSQL = DBWorkbench.getService(UIServiceSQL.class);
        if (serviceSQL != null) {
            return serviceSQL.openSQLViewer(commandContext.getExecutionContext(), dialogTitle, UIIcon.SQL_PREVIEW, script.toString(), true, false) == IDialogConstants.PROCEED_ID;
        }
    } else {
        return UIUtils.confirmAction(workbenchWindow.getShell(), dialogTitle, "No SQL script available.\nAre you sure you want to proceed?");
    }
    return false;
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBECommand(org.jkiss.dbeaver.model.edit.DBECommand) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) UIServiceSQL(org.jkiss.dbeaver.runtime.ui.UIServiceSQL) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 78 with DBEPersistAction

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

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 79 with DBEPersistAction

use of org.jkiss.dbeaver.model.edit.DBEPersistAction in project dbeaver by dbeaver.

the class MySQLCommandChangeUser method getPersistActions.

@Override
public DBEPersistAction[] getPersistActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, Map<String, Object> options) {
    List<DBEPersistAction> actions = new ArrayList<>();
    boolean newUser = !getObject().isPersisted();
    if (newUser) {
        actions.add(new // $NON-NLS-2$
        SQLDatabasePersistAction(// $NON-NLS-2$
        MySQLUIMessages.edit_command_change_user_action_create_new_user, // $NON-NLS-2$
        "CREATE USER " + getObject().getFullName()) {

            @Override
            public void afterExecute(DBCSession session, Throwable error) {
                if (error == null) {
                    getObject().setPersisted(true);
                }
            }
        });
    }
    boolean hasSet;
    final MySQLDataSource dataSource = getObject().getDataSource();
    if (MySQLUtils.isAlterUSerSupported(dataSource)) {
        StringBuilder script = new StringBuilder();
        if (generateAlterScript(script)) {
            actions.add(new SQLDatabasePersistAction(MySQLUIMessages.edit_command_change_user_action_update_user_record, script.toString()));
        }
    } else {
        String updateSQL = generateUpdateScript();
        if (updateSQL != null) {
            actions.add(new SQLDatabasePersistAction(MySQLUIMessages.edit_command_change_user_action_update_user_record, updateSQL));
        }
        updateSQL = generatePasswordSet();
        if (updateSQL != null) {
            actions.add(new SQLDatabasePersistAction(MySQLUIMessages.edit_command_change_user_action_update_user_record, updateSQL));
        }
    }
    return actions.toArray(new DBEPersistAction[0]);
}
Also used : MySQLDataSource(org.jkiss.dbeaver.ext.mysql.model.MySQLDataSource) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) ArrayList(java.util.ArrayList) SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction) DBCSession(org.jkiss.dbeaver.model.exec.DBCSession)

Example 80 with DBEPersistAction

use of org.jkiss.dbeaver.model.edit.DBEPersistAction in project dbeaver by dbeaver.

the class SQLTableManager method addStructObjectCreateActions.

@Override
protected void addStructObjectCreateActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, StructCreateCommand command, Map<String, Object> options) throws DBException {
    final OBJECT_TYPE table = command.getObject();
    final NestedObjectCommand tableProps = command.getObjectCommands().get(table);
    if (tableProps == null) {
        // $NON-NLS-1$
        log.warn("Object change command not found");
        return;
    }
    final String tableName = DBUtils.getEntityScriptName(table, options);
    final String slComment = SQLUtils.getDialectFromObject(table).getSingleLineComments()[0];
    final String lineSeparator = GeneralUtils.getDefaultLineSeparator();
    StringBuilder createQuery = new StringBuilder(100);
    createQuery.append(beginCreateTableStatement(monitor, table, tableName, options));
    boolean hasNestedDeclarations = false;
    final Collection<NestedObjectCommand> orderedCommands = getNestedOrderedCommands(command);
    for (NestedObjectCommand nestedCommand : orderedCommands) {
        if (nestedCommand.getObject() == table) {
            continue;
        }
        if (excludeFromDDL(nestedCommand, orderedCommands)) {
            continue;
        }
        final String nestedDeclaration = nestedCommand.getNestedDeclaration(monitor, table, options);
        if (!CommonUtils.isEmpty(nestedDeclaration)) {
            // Insert nested declaration
            if (hasNestedDeclarations) {
                // Check for embedded comment
                int lastLFPos = createQuery.lastIndexOf(lineSeparator);
                int lastCommentPos = createQuery.lastIndexOf(slComment);
                if (lastCommentPos != -1) {
                    while (lastCommentPos > 0 && Character.isWhitespace(createQuery.charAt(lastCommentPos - 1))) {
                        lastCommentPos--;
                    }
                }
                if (lastCommentPos < 0 || lastCommentPos < lastLFPos) {
                    // $NON-NLS-1$
                    createQuery.append(",");
                } else {
                    // $NON-NLS-1$
                    createQuery.insert(lastCommentPos, ",");
                }
                createQuery.append(lineSeparator);
            }
            if (!hasNestedDeclarations && !hasAttrDeclarations(table)) {
                // $NON-NLS-1$
                createQuery.append("(\n\t").append(nestedDeclaration);
            } else {
                // $NON-NLS-1$
                createQuery.append("\t").append(nestedDeclaration);
            }
            hasNestedDeclarations = true;
        } else {
            // This command should be executed separately
            final DBEPersistAction[] nestedActions = nestedCommand.getPersistActions(monitor, executionContext, options);
            if (nestedActions != null) {
                Collections.addAll(actions, nestedActions);
            }
        }
    }
    if (hasAttrDeclarations(table) || hasNestedDeclarations) {
        createQuery.append(lineSeparator);
        // $NON-NLS-1$
        createQuery.append(")");
    }
    appendTableModifiers(monitor, table, tableProps, createQuery, false);
    actions.add(0, new SQLDatabasePersistAction(ModelMessages.model_jdbc_create_new_table, createQuery.toString()));
}
Also used : DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) SQLDatabasePersistAction(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction)

Aggregations

DBEPersistAction (org.jkiss.dbeaver.model.edit.DBEPersistAction)94 SQLDatabasePersistAction (org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction)44 DBException (org.jkiss.dbeaver.DBException)24 InvocationTargetException (java.lang.reflect.InvocationTargetException)16 ArrayList (java.util.ArrayList)14 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)10 UIServiceSQL (org.jkiss.dbeaver.runtime.ui.UIServiceSQL)10 DBERegistry (org.jkiss.dbeaver.model.edit.DBERegistry)8 OracleObjectPersistAction (org.jkiss.dbeaver.ext.oracle.model.OracleObjectPersistAction)6 DBPEvent (org.jkiss.dbeaver.model.DBPEvent)6 DBECommand (org.jkiss.dbeaver.model.edit.DBECommand)6 DBECommandContext (org.jkiss.dbeaver.model.edit.DBECommandContext)6 DBCException (org.jkiss.dbeaver.model.exec.DBCException)6 DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)6 DBCStatement (org.jkiss.dbeaver.model.exec.DBCStatement)6 SQLDatabasePersistActionComment (org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment)6 SQLObjectEditor (org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor)6 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)6 DBSObjectState (org.jkiss.dbeaver.model.struct.DBSObjectState)6 SQLException (java.sql.SQLException)4