Search in sources :

Example 71 with DBCExecutionContext

use of org.jkiss.dbeaver.model.exec.DBCExecutionContext in project dbeaver by serge-rider.

the class PendingTransactionsDialog method loadContexts.

private void loadContexts(boolean showAllContexts) {
    contextTree.removeAll();
    // Load all open context
    for (DBPDataSourceContainer dataSource : DataSourceRegistry.getAllDataSources()) {
        if (!dataSource.isConnected() || dataSource.getDataSource() == null) {
            continue;
        }
        for (DBSInstance instance : dataSource.getDataSource().getAvailableInstances()) {
            DBCExecutionContext[] allContexts = instance.getAllContexts();
            if (ArrayUtils.isEmpty(allContexts)) {
                continue;
            }
            List<DBCExecutionContext> txnContexts = new ArrayList<>();
            for (DBCExecutionContext context : allContexts) {
                if (showAllContexts || QMUtils.isTransactionActive(context, false)) {
                    txnContexts.add(context);
                }
            }
            if (txnContexts.isEmpty()) {
                continue;
            }
            TreeItem dsItem = new TreeItem(contextTree, SWT.NONE);
            dsItem.setText(dataSource.getName());
            dsItem.setImage(DBeaverIcons.getImage(dataSource.getDriver().getIcon()));
            dsItem.setData(dataSource);
            for (DBCExecutionContext context : txnContexts) {
                QMTransactionState txnState = QMUtils.getTransactionState(context);
                TreeItem contextItem = new TreeItem(dsItem, SWT.NONE);
                contextItem.setText(0, context.getContextName());
                String stateString = String.valueOf(txnState.getUpdateCount()) + "/" + String.valueOf(txnState.getExecuteCount());
                contextItem.setText(1, stateString);
                contextItem.setData(context);
            }
            dsItem.setExpanded(true);
        }
    }
    UIUtils.asyncExec(new Runnable() {

        @Override
        public void run() {
            UIUtils.packColumns(contextTree);
        }
    });
}
Also used : DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) DBSInstance(org.jkiss.dbeaver.model.struct.DBSInstance) ArrayList(java.util.ArrayList) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer) QMTransactionState(org.jkiss.dbeaver.model.qm.QMTransactionState)

Example 72 with DBCExecutionContext

use of org.jkiss.dbeaver.model.exec.DBCExecutionContext in project dbeaver by serge-rider.

the class DataSourceInvalidateHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    DBCExecutionContext context = getActiveExecutionContext(event, false);
    if (context != null) {
        invalidateDataSource(context.getDataSource());
    } else {
        IEditorPart editor = HandlerUtil.getActiveEditor(event);
        if (editor instanceof IDataSourceContainerProviderEx) {
            // Try to set the same container.
            // It should trigger connection instantiation if for some reason it was lost (SQLEditor specific?)
            DBPDataSourceContainer dsContainer = ((IDataSourceContainerProviderEx) editor).getDataSourceContainer();
            if (dsContainer != null) {
                ((IDataSourceContainerProviderEx) editor).setDataSourceContainer(null);
                ((IDataSourceContainerProviderEx) editor).setDataSourceContainer(dsContainer);
            }
        }
    }
    return null;
}
Also used : DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) IEditorPart(org.eclipse.ui.IEditorPart) IDataSourceContainerProviderEx(org.jkiss.dbeaver.model.IDataSourceContainerProviderEx) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer)

Example 73 with DBCExecutionContext

use of org.jkiss.dbeaver.model.exec.DBCExecutionContext in project dbeaver by serge-rider.

the class DataSourceAutoCommitHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    DBCExecutionContext context = getActiveExecutionContext(event, true);
    if (context != null) {
        DBCTransactionManager txnManager = DBUtils.getTransactionManager(context);
        if (txnManager != null) {
            try {
                final DBPDataSourceContainer container = context.getDataSource().getContainer();
                boolean newAutocommit = !container.isDefaultAutoCommit();
                if (context.isConnected()) {
                    // Get flag from connection
                    newAutocommit = !txnManager.isAutoCommit();
                }
                boolean autoCommit = newAutocommit;
                new AbstractJob("Set auto-commit") {

                    @Override
                    protected IStatus run(DBRProgressMonitor monitor) {
                        monitor.beginTask("Change connection auto-commit to " + autoCommit, 1);
                        try {
                            monitor.subTask("Change context '" + context.getContextName() + "' auto-commit state");
                            txnManager.setAutoCommit(monitor, autoCommit);
                        } catch (Exception e) {
                            return GeneralUtils.makeExceptionStatus(e);
                        } finally {
                            monitor.done();
                        }
                        return Status.OK_STATUS;
                    }
                }.schedule();
            } catch (DBException e) {
                DBWorkbench.getPlatformUI().showError("Auto-Commit", "Error while toggle auto-commit", e);
            }
        }
    }
    return null;
}
Also used : AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer) DBCException(org.jkiss.dbeaver.model.exec.DBCException) ExecutionException(org.eclipse.core.commands.ExecutionException) DBException(org.jkiss.dbeaver.DBException) DBCTransactionManager(org.jkiss.dbeaver.model.exec.DBCTransactionManager)

Example 74 with DBCExecutionContext

use of org.jkiss.dbeaver.model.exec.DBCExecutionContext in project dbeaver by serge-rider.

the class DataImporterCSV method runImport.

@Override
public void runImport(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource streamDataSource, @NotNull InputStream inputStream, @NotNull IDataTransferConsumer consumer) throws DBException {
    IStreamDataImporterSite site = getSite();
    StreamEntityMapping entityMapping = site.getSourceObject();
    Map<String, Object> properties = site.getProcessorProperties();
    HeaderPosition headerPosition = getHeaderPosition(properties);
    boolean emptyStringNull = CommonUtils.getBoolean(properties.get(PROP_EMPTY_STRING_NULL), false);
    String nullValueMark = CommonUtils.toString(properties.get(PROP_NULL_STRING));
    DBCExecutionContext context = streamDataSource.getDefaultInstance().getDefaultContext(monitor, false);
    try (DBCSession producerSession = context.openSession(monitor, DBCExecutionPurpose.UTIL, "Transfer stream data")) {
        LocalStatement localStatement = new LocalStatement(producerSession, "SELECT * FROM Stream");
        StreamTransferResultSet resultSet = new StreamTransferResultSet(producerSession, localStatement, entityMapping);
        consumer.fetchStart(producerSession, resultSet, -1, -1);
        applyTransformHints(resultSet, consumer, properties, PROP_TIMESTAMP_FORMAT, PROP_TIMESTAMP_ZONE);
        try (Reader reader = openStreamReader(inputStream, properties)) {
            try (CSVReader csvReader = openCSVReader(reader, properties)) {
                int maxRows = site.getSettings().getMaxRows();
                int targetAttrSize = entityMapping.getStreamColumns().size();
                boolean headerRead = false;
                for (int lineNum = 0; ; ) {
                    if (monitor.isCanceled()) {
                        break;
                    }
                    String[] line = csvReader.readNext();
                    if (line == null) {
                        break;
                    }
                    if (line.length == 0) {
                        continue;
                    }
                    if (headerPosition != HeaderPosition.none && !headerRead) {
                        // First line is a header
                        headerRead = true;
                        continue;
                    }
                    if (maxRows > 0 && lineNum >= maxRows) {
                        break;
                    }
                    if (line.length < targetAttrSize) {
                        // Stream row may be shorter than header
                        String[] newLine = new String[targetAttrSize];
                        System.arraycopy(line, 0, newLine, 0, line.length);
                        for (int i = line.length; i < targetAttrSize; i++) {
                            newLine[i] = null;
                        }
                        line = newLine;
                    }
                    if (emptyStringNull) {
                        for (int i = 0; i < line.length; i++) {
                            if ("".equals(line[i])) {
                                line[i] = null;
                            }
                        }
                    }
                    if (!CommonUtils.isEmpty(nullValueMark)) {
                        for (int i = 0; i < line.length; i++) {
                            if (nullValueMark.equals(line[i])) {
                                line[i] = null;
                            }
                        }
                    }
                    resultSet.setStreamRow(line);
                    consumer.fetchRow(producerSession, resultSet);
                    lineNum++;
                    if (lineNum % 1000 == 0) {
                        monitor.subTask(String.valueOf(lineNum) + " rows processed");
                    }
                }
            }
        } catch (IOException e) {
            throw new DBException("IO error reading CSV", e);
        } finally {
            try {
                consumer.fetchEnd(producerSession, resultSet);
            } finally {
                consumer.close();
            }
        }
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) LocalStatement(org.jkiss.dbeaver.model.impl.local.LocalStatement) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) CSVReader(au.com.bytecode.opencsv.CSVReader) CSVReader(au.com.bytecode.opencsv.CSVReader) DBCSession(org.jkiss.dbeaver.model.exec.DBCSession)

Example 75 with DBCExecutionContext

use of org.jkiss.dbeaver.model.exec.DBCExecutionContext in project dbeaver by serge-rider.

the class SQLTableManager method getTableDDL.

public DBEPersistAction[] getTableDDL(DBRProgressMonitor monitor, OBJECT_TYPE table, Map<String, Object> options) throws DBException {
    List<DBEPersistAction> actions = new ArrayList<>();
    final DBERegistry editorsRegistry = table.getDataSource().getContainer().getPlatform().getEditorsRegistry();
    SQLObjectEditor<DBSEntityAttribute, OBJECT_TYPE> tcm = getObjectEditor(editorsRegistry, DBSEntityAttribute.class);
    SQLObjectEditor<DBSEntityConstraint, OBJECT_TYPE> pkm = getObjectEditor(editorsRegistry, DBSEntityConstraint.class);
    SQLObjectEditor<DBSTableForeignKey, OBJECT_TYPE> fkm = getObjectEditor(editorsRegistry, DBSTableForeignKey.class);
    SQLObjectEditor<DBSTableIndex, OBJECT_TYPE> im = getObjectEditor(editorsRegistry, DBSTableIndex.class);
    DBCExecutionContext executionContext = DBUtils.getDefaultContext(table, true);
    if (CommonUtils.getOption(options, DBPScriptObject.OPTION_DDL_ONLY_FOREIGN_KEYS)) {
        if (fkm != null) {
            // Create only foreign keys
            try {
                for (DBSEntityAssociation foreignKey : CommonUtils.safeCollection(table.getAssociations(monitor))) {
                    if (!(foreignKey instanceof DBSTableForeignKey) || DBUtils.isHiddenObject(foreignKey) || DBUtils.isInheritedObject(foreignKey)) {
                        continue;
                    }
                    DBEPersistAction[] cmdActions = fkm.makeCreateCommand((DBSTableForeignKey) foreignKey, options).getPersistActions(monitor, executionContext, options);
                    if (cmdActions != null) {
                        Collections.addAll(actions, cmdActions);
                    }
                }
            } catch (DBException e) {
                // Ignore primary keys
                log.debug(e);
            }
        }
        return actions.toArray(new DBEPersistAction[0]);
    }
    if (isIncludeDropInDDL()) {
        actions.add(new SQLDatabasePersistActionComment(table.getDataSource(), "Drop table"));
        for (DBEPersistAction delAction : new ObjectDeleteCommand(table, ModelMessages.model_jdbc_delete_object).getPersistActions(monitor, executionContext, options)) {
            String script = delAction.getScript();
            String delimiter = SQLUtils.getScriptLineDelimiter(SQLUtils.getDialectFromObject(table));
            if (!script.endsWith(delimiter)) {
                script += delimiter;
            }
            actions.add(new SQLDatabasePersistActionComment(table.getDataSource(), script));
        }
    }
    StructCreateCommand command = makeCreateCommand(table, options);
    if (tcm != null) {
        // Aggregate nested column, constraint and index commands
        for (DBSEntityAttribute column : CommonUtils.safeCollection(table.getAttributes(monitor))) {
            if (DBUtils.isHiddenObject(column) || DBUtils.isInheritedObject(column)) {
                // Do not include hidden (pseudo?) and inherited columns in DDL
                continue;
            }
            command.aggregateCommand(tcm.makeCreateCommand(column, options));
        }
    }
    if (pkm != null) {
        try {
            for (DBSEntityConstraint constraint : CommonUtils.safeCollection(table.getConstraints(monitor))) {
                if (DBUtils.isHiddenObject(constraint) || DBUtils.isInheritedObject(constraint)) {
                    continue;
                }
                command.aggregateCommand(pkm.makeCreateCommand(constraint, options));
            }
        } catch (DBException e) {
            // Ignore primary keys
            log.debug(e);
        }
    }
    if (fkm != null && !CommonUtils.getOption(options, DBPScriptObject.OPTION_DDL_SKIP_FOREIGN_KEYS)) {
        try {
            for (DBSEntityAssociation foreignKey : CommonUtils.safeCollection(table.getAssociations(monitor))) {
                if (!(foreignKey instanceof DBSTableForeignKey) || DBUtils.isHiddenObject(foreignKey) || DBUtils.isInheritedObject(foreignKey)) {
                    continue;
                }
                command.aggregateCommand(fkm.makeCreateCommand((DBSTableForeignKey) foreignKey, options));
            }
        } catch (DBException e) {
            // Ignore primary keys
            log.debug(e);
        }
    }
    if (im != null && table instanceof DBSTable) {
        try {
            for (DBSTableIndex index : CommonUtils.safeCollection(((DBSTable) table).getIndexes(monitor))) {
                if (!isIncludeIndexInDDL(monitor, index)) {
                    continue;
                }
                command.aggregateCommand(im.makeCreateCommand(index, options));
            }
        } catch (DBException e) {
            // Ignore indexes
            log.debug(e);
        }
    }
    addExtraDDLCommands(monitor, table, options, command);
    Collections.addAll(actions, command.getPersistActions(monitor, executionContext, options));
    return actions.toArray(new DBEPersistAction[0]);
}
Also used : DBException(org.jkiss.dbeaver.DBException) SQLDatabasePersistActionComment(org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistActionComment) DBSTable(org.jkiss.dbeaver.model.struct.rdb.DBSTable) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) DBERegistry(org.jkiss.dbeaver.model.edit.DBERegistry) DBSTableIndex(org.jkiss.dbeaver.model.struct.rdb.DBSTableIndex) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) DBSTableForeignKey(org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKey)

Aggregations

DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)107 DBPDataSourceContainer (org.jkiss.dbeaver.model.DBPDataSourceContainer)27 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)22 DBException (org.jkiss.dbeaver.DBException)21 DBPContextProvider (org.jkiss.dbeaver.model.DBPContextProvider)20 InvocationTargetException (java.lang.reflect.InvocationTargetException)16 DBCExecutionContextDefaults (org.jkiss.dbeaver.model.exec.DBCExecutionContextDefaults)16 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)15 GridData (org.eclipse.swt.layout.GridData)12 IEditorPart (org.eclipse.ui.IEditorPart)12 DBCException (org.jkiss.dbeaver.model.exec.DBCException)12 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)12 ArrayList (java.util.ArrayList)10 Composite (org.eclipse.swt.widgets.Composite)10 DBSCatalog (org.jkiss.dbeaver.model.struct.rdb.DBSCatalog)10 DBSSchema (org.jkiss.dbeaver.model.struct.rdb.DBSSchema)10 SelectionAdapter (org.eclipse.swt.events.SelectionAdapter)8 SelectionEvent (org.eclipse.swt.events.SelectionEvent)8 IWorkbenchWindow (org.eclipse.ui.IWorkbenchWindow)8 NotNull (org.jkiss.code.NotNull)8