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());
}
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;
}
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();
}
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]);
}
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()));
}
Aggregations