Search in sources :

Example 36 with DBRProgressMonitor

use of org.jkiss.dbeaver.model.runtime.DBRProgressMonitor in project dbeaver by serge-rider.

the class GenericStructureAssistant method findProceduresByMask.

private void findProceduresByMask(JDBCSession session, GenericCatalog catalog, GenericSchema schema, String procNameMask, int maxResults, List<DBSObjectReference> objects) throws SQLException, DBException {
    final GenericMetaObject procObject = getDataSource().getMetaObject(GenericConstants.OBJECT_PROCEDURE);
    DBRProgressMonitor monitor = session.getProgressMonitor();
    try (JDBCResultSet dbResult = session.getMetaData().getProcedures(catalog == null ? null : catalog.getName(), schema == null ? null : schema.getName(), procNameMask)) {
        while (dbResult.next()) {
            if (monitor.isCanceled()) {
                break;
            }
            String catalogName = GenericUtils.safeGetStringTrimmed(procObject, dbResult, JDBCConstants.PROCEDURE_CAT);
            String schemaName = GenericUtils.safeGetStringTrimmed(procObject, dbResult, JDBCConstants.PROCEDURE_SCHEM);
            String procName = GenericUtils.safeGetStringTrimmed(procObject, dbResult, JDBCConstants.PROCEDURE_NAME);
            String uniqueName = GenericUtils.safeGetStringTrimmed(procObject, dbResult, JDBCConstants.SPECIFIC_NAME);
            if (CommonUtils.isEmpty(procName)) {
                continue;
            }
            if (CommonUtils.isEmpty(uniqueName)) {
                uniqueName = procName;
            }
            objects.add(new ProcedureReference(findContainer(session.getProgressMonitor(), catalog, schema, catalogName, schemaName), catalogName, procName, uniqueName));
            if (objects.size() >= maxResults) {
                break;
            }
        }
    }
}
Also used : GenericMetaObject(org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaObject) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 37 with DBRProgressMonitor

use of org.jkiss.dbeaver.model.runtime.DBRProgressMonitor in project dbeaver by serge-rider.

the class GenericStructureAssistant method findTablesByMask.

private void findTablesByMask(JDBCSession session, GenericCatalog catalog, GenericSchema schema, String tableNameMask, int maxResults, List<DBSObjectReference> objects) throws SQLException, DBException {
    final GenericMetaObject tableObject = getDataSource().getMetaObject(GenericConstants.OBJECT_TABLE);
    final DBRProgressMonitor monitor = session.getProgressMonitor();
    try (JDBCResultSet dbResult = session.getMetaData().getTables(catalog == null ? null : catalog.getName(), schema == null ? null : schema.getName(), tableNameMask, null)) {
        while (dbResult.next()) {
            if (monitor.isCanceled()) {
                break;
            }
            String catalogName = GenericUtils.safeGetStringTrimmed(tableObject, dbResult, JDBCConstants.TABLE_CAT);
            String schemaName = GenericUtils.safeGetStringTrimmed(tableObject, dbResult, JDBCConstants.TABLE_SCHEM);
            String tableName = GenericUtils.safeGetStringTrimmed(tableObject, dbResult, JDBCConstants.TABLE_NAME);
            if (CommonUtils.isEmpty(tableName)) {
                continue;
            }
            objects.add(new TableReference(findContainer(session.getProgressMonitor(), catalog, schema, catalogName, schemaName), tableName, GenericUtils.safeGetString(tableObject, dbResult, JDBCConstants.REMARKS)));
            if (objects.size() >= maxResults) {
                break;
            }
        }
    }
}
Also used : GenericMetaObject(org.jkiss.dbeaver.ext.generic.model.meta.GenericMetaObject) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 38 with DBRProgressMonitor

use of org.jkiss.dbeaver.model.runtime.DBRProgressMonitor in project dbeaver by serge-rider.

the class ResultSetUtils method bindAttributes.

public static void bindAttributes(DBCSession session, DBCResultSet resultSet, DBDAttributeBindingMeta[] bindings, List<Object[]> rows) throws DBException {
    final DBRProgressMonitor monitor = session.getProgressMonitor();
    final DBPDataSource dataSource = session.getDataSource();
    boolean readMetaData = dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_READ_METADATA);
    if (!readMetaData) {
        return;
    }
    boolean readReferences = dataSource.getContainer().getPreferenceStore().getBoolean(DBeaverPreferences.RESULT_SET_READ_REFERENCES);
    final Map<DBCEntityMetaData, DBSEntity> entityBindingMap = new IdentityHashMap<>();
    monitor.beginTask("Discover resultset metadata", 3);
    try {
        SQLQuery sqlQuery = null;
        DBSEntity entity = null;
        DBCStatement sourceStatement = resultSet.getSourceStatement();
        if (sourceStatement != null && sourceStatement.getStatementSource() != null) {
            DBCExecutionSource executionSource = sourceStatement.getStatementSource();
            monitor.subTask("Discover owner entity");
            DBSDataContainer dataContainer = executionSource.getDataContainer();
            if (dataContainer instanceof DBSEntity) {
                entity = (DBSEntity) dataContainer;
            }
            DBCEntityMetaData entityMeta = null;
            if (entity == null) {
                // Discover from entity metadata
                Object sourceDescriptor = executionSource.getSourceDescriptor();
                if (sourceDescriptor instanceof SQLQuery) {
                    sqlQuery = (SQLQuery) sourceDescriptor;
                    entityMeta = sqlQuery.getSingleSource();
                }
                if (entityMeta != null) {
                    entity = getEntityFromMetaData(monitor, dataSource, entityMeta);
                    if (entity != null) {
                        entityBindingMap.put(entityMeta, entity);
                    }
                }
            }
        }
        final Map<DBSEntity, DBDRowIdentifier> locatorMap = new IdentityHashMap<>();
        monitor.subTask("Discover attributes");
        for (DBDAttributeBindingMeta binding : bindings) {
            monitor.subTask("Discover attribute '" + binding.getName() + "'");
            DBCAttributeMetaData attrMeta = binding.getMetaAttribute();
            // We got table name and column name
            // To be editable we need this resultset contain set of columns from the same table
            // which construct any unique key
            DBSEntity attrEntity = null;
            final DBCEntityMetaData attrEntityMeta = attrMeta.getEntityMetaData();
            if (attrEntityMeta != null) {
                attrEntity = entityBindingMap.get(attrEntityMeta);
                if (attrEntity == null) {
                    if (entity != null && entity instanceof DBSTable && ((DBSTable) entity).isView()) {
                        // If this is a view then don't try to detect entity for each attribute
                        // MySQL returns source table name instead of view name. That's crazy.
                        attrEntity = entity;
                    } else {
                        attrEntity = getEntityFromMetaData(monitor, dataSource, attrEntityMeta);
                    }
                }
                if (attrEntity != null) {
                    entityBindingMap.put(attrEntityMeta, attrEntity);
                }
            }
            if (attrEntity == null) {
                attrEntity = entity;
            }
            if (attrEntity == null) {
                if (attrEntityMeta != null) {
                    log.debug("Table '" + DBUtils.getSimpleQualifiedName(attrEntityMeta.getCatalogName(), attrEntityMeta.getSchemaName(), attrEntityMeta.getEntityName()) + "' not found in metadata catalog");
                }
            } else {
                DBDPseudoAttribute pseudoAttribute = DBUtils.getPseudoAttribute(attrEntity, attrMeta.getName());
                if (pseudoAttribute != null) {
                    binding.setPseudoAttribute(pseudoAttribute);
                }
                DBSEntityAttribute tableColumn;
                if (binding.getPseudoAttribute() != null) {
                    tableColumn = binding.getPseudoAttribute().createFakeAttribute(attrEntity, attrMeta);
                } else {
                    tableColumn = attrEntity.getAttribute(monitor, attrMeta.getName());
                }
                if (sqlQuery != null) {
                    if (tableColumn != null && tableColumn.getTypeID() != attrMeta.getTypeID()) {
                        // There should be a better solution but for now let's just disable this too smart feature.
                        continue;
                    }
                /*
                        final SQLSelectItem selectItem = sqlQuery.getSelectItem(attrMeta.getName());
                        if (selectItem != null && !selectItem.isPlainColumn()) {
                            // It is not a column.
                            // It maybe an expression, function or anything else
                            continue;
                        }
*/
                }
                if (tableColumn != null && binding.setEntityAttribute(tableColumn)) {
                    // E.g. we fetched strings and found out that we should handle them as LOBs or enums.
                    try {
                        int pos = attrMeta.getOrdinalPosition();
                        for (Object[] row : rows) {
                            row[pos] = binding.getValueHandler().getValueFromObject(session, tableColumn, row[pos], false);
                        }
                    } catch (DBCException e) {
                        log.warn("Error resolving attribute '" + binding.getName() + "' values", e);
                    }
                }
            }
        }
        monitor.worked(1);
        // Init row identifiers
        monitor.subTask("Detect unique identifiers");
        for (DBDAttributeBindingMeta binding : bindings) {
            //monitor.subTask("Find attribute '" + binding.getName() + "' identifier");
            DBSEntityAttribute attr = binding.getEntityAttribute();
            if (attr == null) {
                continue;
            }
            DBSEntity attrEntity = attr.getParentObject();
            if (attrEntity != null) {
                DBDRowIdentifier rowIdentifier = locatorMap.get(attrEntity);
                if (rowIdentifier == null) {
                    DBSEntityReferrer entityIdentifier = getBestIdentifier(monitor, attrEntity, bindings);
                    if (entityIdentifier != null) {
                        rowIdentifier = new DBDRowIdentifier(attrEntity, entityIdentifier);
                        locatorMap.put(attrEntity, rowIdentifier);
                    }
                }
                binding.setRowIdentifier(rowIdentifier);
            }
        }
        monitor.worked(1);
        if (readReferences) {
            monitor.subTask("Late bindings");
            // Read nested bindings
            for (DBDAttributeBinding binding : bindings) {
                binding.lateBinding(session, rows);
            }
        }
        monitor.subTask("Complete metadata load");
        // Reload attributes in row identifiers
        for (DBDRowIdentifier rowIdentifier : locatorMap.values()) {
            rowIdentifier.reloadAttributes(monitor, bindings);
        }
    } finally {
        monitor.done();
    }
}
Also used : DBSTable(org.jkiss.dbeaver.model.struct.rdb.DBSTable) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) DBVEntityConstraint(org.jkiss.dbeaver.model.virtual.DBVEntityConstraint) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 39 with DBRProgressMonitor

use of org.jkiss.dbeaver.model.runtime.DBRProgressMonitor in project dbeaver by serge-rider.

the class ReferenceValueEditor method createEditorSelector.

public boolean createEditorSelector(final Composite parent) {
    if (!(valueController instanceof IAttributeController) || valueController.isReadOnly()) {
        return false;
    }
    refConstraint = getEnumerableConstraint();
    if (refConstraint == null) {
        return false;
    }
    if (refConstraint instanceof DBSEntityAssociation) {
        final DBSEntityAssociation association = (DBSEntityAssociation) refConstraint;
        if (association.getReferencedConstraint() != null) {
            final DBSEntity refTable = association.getReferencedConstraint().getParentObject();
            Composite labelGroup = UIUtils.createPlaceholder(parent, 2);
            labelGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            Link dictLabel = UIUtils.createLink(labelGroup, NLS.bind(CoreMessages.dialog_value_view_label_dictionary, refTable.getName()), new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    // Open
                    final IWorkbenchWindow window = valueController.getValueSite().getWorkbenchWindow();
                    DBeaverUI.runInUI(window, new DBRRunnableWithProgress() {

                        @Override
                        public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                            DBNDatabaseNode tableNode = DBeaverCore.getInstance().getNavigatorModel().getNodeByObject(monitor, refTable, true);
                            if (tableNode != null) {
                                NavigatorHandlerObjectOpen.openEntityEditor(tableNode, DatabaseDataEditor.class.getName(), window);
                            }
                        }
                    });
                }
            });
            dictLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
            Link hintLabel = UIUtils.createLink(labelGroup, "(<a>Define Description</a>)", new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    EditDictionaryPage editDictionaryPage = new EditDictionaryPage("Dictionary structure", refTable);
                    if (editDictionaryPage.edit(parent.getShell())) {
                        loaderJob.schedule();
                    }
                }
            });
            hintLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_END));
        }
    }
    editorSelector = new Table(parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL);
    editorSelector.setLinesVisible(true);
    editorSelector.setHeaderVisible(true);
    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.heightHint = 150;
    //gd.widthHint = 300;
    //gd.grabExcessVerticalSpace = true;
    //gd.grabExcessHorizontalSpace = true;
    editorSelector.setLayoutData(gd);
    UIUtils.createTableColumn(editorSelector, SWT.LEFT, CoreMessages.dialog_value_view_column_value);
    UIUtils.createTableColumn(editorSelector, SWT.LEFT, CoreMessages.dialog_value_view_column_description);
    UIUtils.packColumns(editorSelector);
    editorSelector.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            TableItem[] selection = editorSelector.getSelection();
            if (selection != null && selection.length > 0) {
                Object value = selection[0].getData();
                //editorControl.setText(selection[0].getText());
                try {
                    valueEditor.primeEditorValue(value);
                } catch (DBException e1) {
                    log.error(e1);
                }
            }
        }
    });
    Control control = valueEditor.getControl();
    ModifyListener modifyListener = new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            Object curEditorValue;
            try {
                curEditorValue = valueEditor.extractEditorValue();
            } catch (DBException e1) {
                log.error(e1);
                return;
            }
            // Try to select current value in the table
            final String curTextValue = valueController.getValueHandler().getValueDisplayString(((IAttributeController) valueController).getBinding(), curEditorValue, DBDDisplayFormat.UI);
            boolean valueFound = false;
            for (TableItem item : editorSelector.getItems()) {
                if (item.getText(0).equals(curTextValue)) {
                    editorSelector.select(editorSelector.indexOf(item));
                    editorSelector.showItem(item);
                    valueFound = true;
                    break;
                }
            }
            if (!valueFound) {
                // Read dictionary
                if (loaderJob.getState() == Job.RUNNING) {
                    // Cancel it and create new one
                    loaderJob.cancel();
                    loaderJob = new SelectorLoaderJob();
                }
                loaderJob.setPattern(curEditorValue);
                if (loaderJob.getState() != Job.WAITING) {
                    loaderJob.schedule(100);
                }
            }
        }
    };
    if (control instanceof Text) {
        ((Text) control).addModifyListener(modifyListener);
    } else if (control instanceof StyledText) {
        ((StyledText) control).addModifyListener(modifyListener);
    }
    loaderJob = new SelectorLoaderJob();
    final Object curValue = valueController.getValue();
    if (curValue instanceof Number) {
        loaderJob.setPattern(curValue);
    }
    loaderJob.schedule(500);
    return true;
}
Also used : DBException(org.jkiss.dbeaver.DBException) ModifyListener(org.eclipse.swt.events.ModifyListener) EditDictionaryPage(org.jkiss.dbeaver.ui.editors.object.struct.EditDictionaryPage) IAttributeController(org.jkiss.dbeaver.ui.data.IAttributeController) ModifyEvent(org.eclipse.swt.events.ModifyEvent) SelectionEvent(org.eclipse.swt.events.SelectionEvent) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) DatabaseDataEditor(org.jkiss.dbeaver.ui.editors.data.DatabaseDataEditor) StyledText(org.eclipse.swt.custom.StyledText) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) StyledText(org.eclipse.swt.custom.StyledText) GridData(org.eclipse.swt.layout.GridData) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 40 with DBRProgressMonitor

use of org.jkiss.dbeaver.model.runtime.DBRProgressMonitor in project dbeaver by serge-rider.

the class SpreadsheetPresentation method navigateLink.

///////////////////////////////////////////////
// Links
public void navigateLink(@NotNull GridCell cell, final int state) {
    boolean recordMode = controller.isRecordMode();
    final DBDAttributeBinding attr = (DBDAttributeBinding) (recordMode ? cell.row : cell.col);
    final ResultSetRow row = (ResultSetRow) (recordMode ? cell.col : cell.row);
    Object value = controller.getModel().getCellValue(attr, row);
    if (DBUtils.isNullValue(value)) {
        log.warn("Can't navigate to NULL value");
        return;
    }
    if (!CommonUtils.isEmpty(attr.getReferrers())) {
        // Navigate association
        new AbstractJob("Navigate association") {

            @Override
            protected IStatus run(DBRProgressMonitor monitor) {
                try {
                    boolean ctrlPressed = (state & SWT.CTRL) == SWT.CTRL;
                    controller.navigateAssociation(monitor, attr, row, ctrlPressed);
                } catch (DBException e) {
                    return GeneralUtils.makeExceptionStatus(e);
                }
                return Status.OK_STATUS;
            }
        }.schedule();
    } else {
        // Navigate hyperlink
        String strValue = attr.getValueHandler().getValueDisplayString(attr, value, DBDDisplayFormat.UI);
        UIUtils.launchProgram(strValue);
    }
}
Also used : AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Aggregations

DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)79 DBException (org.jkiss.dbeaver.DBException)45 InvocationTargetException (java.lang.reflect.InvocationTargetException)36 DBRRunnableWithProgress (org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress)30 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)14 JDBCResultSet (org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)12 AbstractJob (org.jkiss.dbeaver.model.runtime.AbstractJob)12 JDBCPreparedStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement)10 AbstractObjectReference (org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference)10 ArrayList (java.util.ArrayList)8 IStatus (org.eclipse.core.runtime.IStatus)8 IJobChangeEvent (org.eclipse.core.runtime.jobs.IJobChangeEvent)6 JobChangeAdapter (org.eclipse.core.runtime.jobs.JobChangeAdapter)6 GridData (org.eclipse.swt.layout.GridData)6 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)6 List (java.util.List)5 NotNull (org.jkiss.code.NotNull)5 File (java.io.File)4 IOException (java.io.IOException)4 IFile (org.eclipse.core.resources.IFile)4