Search in sources :

Example 41 with DBPDataSource

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

the class JDBCCallableStatementImpl method findProcedure.

private static DBSProcedure findProcedure(DBCSession session, String queryString) throws DBException {
    DBPDataSource dataSource = session.getDataSource();
    if (!CommonUtils.isEmpty(queryString)) {
        Matcher matcher = EXEC_PATTERN.matcher(queryString);
        if (matcher.find()) {
            String procName = matcher.group(1);
            char divChar = dataSource.getSQLDialect().getStructSeparator();
            if (procName.indexOf(divChar) != -1) {
                return findProcedureByNames(session, procName.split("\\" + divChar));
            } else {
                return findProcedureByNames(session, procName);
            }
        }
    }
    return null;
}
Also used : Matcher(java.util.regex.Matcher) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource)

Example 42 with DBPDataSource

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

the class AbstractObjectReference method getFullyQualifiedName.

@NotNull
@Override
public String getFullyQualifiedName(DBPEvaluationContext context) {
    if (extraInfo != null) {
        return extraInfo;
    }
    String fqName;
    DBPDataSource dataSource = container.getDataSource();
    if (container == dataSource) {
        // In case if there are no schemas/catalogs supported
        // and data source is a root container
        fqName = DBUtils.getQuotedIdentifier(dataSource, name);
    } else {
        fqName = DBUtils.getFullQualifiedName(dataSource, container, this);
    }
    return fqName;
}
Also used : DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) NotNull(org.jkiss.code.NotNull)

Example 43 with DBPDataSource

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

the class AbstractJob method runBlockCanceler.

private void runBlockCanceler() {
    final List<DBRBlockingObject> activeBlocks = new ArrayList<>(CommonUtils.safeList(progressMonitor.getActiveBlocks()));
    if (activeBlocks.isEmpty()) {
        // Nothing to cancel
        return;
    }
    final DBRBlockingObject lastBlock = activeBlocks.remove(activeBlocks.size() - 1);
    try {
        new JobCanceler(lastBlock).schedule();
    } catch (Exception e) {
        // If this happens during shutdown and job manager is not active
        log.debug(e);
    }
    if (!activeBlocks.isEmpty()) {
        DBPPreferenceStore preferenceStore;
        if (activeBlocks.get(0) instanceof DBCSession) {
            DBPDataSource dataSource = ((DBCSession) activeBlocks.get(0)).getDataSource();
            if (dataSource == null) {
                return;
            }
            preferenceStore = dataSource.getContainer().getPreferenceStore();
        } else {
            preferenceStore = ModelPreferences.getPreferences();
        }
        int cancelCheckTimeout = preferenceStore.getInt(ModelPreferences.EXECUTE_CANCEL_CHECK_TIMEOUT);
        if (cancelCheckTimeout > 0) {
            // There are other blocks. If last one can't be canceled then try others
            Job cancelChecker = new // $NON-N LS-1$
            Job(// $NON-N LS-1$
            "Cancel checker block") {

                {
                    setSystem(true);
                    setUser(false);
                }

                @Override
                protected IStatus run(IProgressMonitor monitor) {
                    if (!finished) {
                        DBRBlockingObject nextBlock = activeBlocks.remove(activeBlocks.size() - 1);
                        new JobCanceler(nextBlock).schedule();
                        if (!activeBlocks.isEmpty()) {
                            schedule(cancelCheckTimeout);
                        }
                    }
                    return Status.OK_STATUS;
                }
            };
            cancelChecker.schedule(cancelCheckTimeout);
        }
    }
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ArrayList(java.util.ArrayList) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) Job(org.eclipse.core.runtime.jobs.Job) DBPPreferenceStore(org.jkiss.dbeaver.model.preferences.DBPPreferenceStore) DBException(org.jkiss.dbeaver.DBException) DBCSession(org.jkiss.dbeaver.model.exec.DBCSession)

Example 44 with DBPDataSource

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

the class SQLCompletionProposal method validate.

@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
    if (event == null) {
        return false;
    }
    SQLSyntaxManager syntaxManager = getContext().getSyntaxManager();
    DBPDataSource dataSource = getContext().getDataSource();
    final SQLWordPartDetector wordDetector = new SQLWordPartDetector(document, syntaxManager, offset);
    String wordPart = wordDetector.getWordPart();
    int divPos = wordPart.lastIndexOf(syntaxManager.getStructSeparator());
    if (divPos != -1) {
        if (divPos == wordPart.length() - 1) {
            // It is valid only if full word matches (it should be the only proposal)
            if (replacementString.equals(wordPart.substring(0, divPos))) {
                {
                    // Call completion popup again
                    UIUtils.asyncExec(() -> {
                        IEditorPart activeEditor = UIUtils.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
                        if (activeEditor != null) {
                            ITextViewer textViewer = activeEditor.getAdapter(ITextViewer.class);
                            if (textViewer != null) {
                                textViewer.getTextOperationTarget().doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
                            }
                        }
                    });
                }
            }
            return false;
        }
        wordPart = wordPart.substring(divPos + 1);
    }
    String wordLower = wordPart.toLowerCase(Locale.ENGLISH);
    if (!CommonUtils.isEmpty(wordPart)) {
        boolean matchContains = dataSource != null && dataSource.getContainer().getPreferenceStore().getBoolean(SQLPreferenceConstants.PROPOSALS_MATCH_CONTAINS);
        boolean matched;
        if (getObject() == null || !matchContains) {
            // For keywords use strict matching
            matched = (matchContains ? replacementFull.contains(wordLower) : replacementFull.startsWith(wordLower)) && (CommonUtils.isEmpty(event.getText()) || replacementFull.contains(event.getText().toLowerCase(Locale.ENGLISH))) || (this.replacementLast != null && this.replacementLast.startsWith(wordLower));
        } else {
            // For objects use fuzzy matching
            int score = TextUtils.fuzzyScore(replacementFull, wordLower);
            matched = (score > 0 && (CommonUtils.isEmpty(event.getText()) || TextUtils.fuzzyScore(replacementFull, event.getText()) > 0)) || (this.replacementLast != null && TextUtils.fuzzyScore(this.replacementLast, wordLower) > 0);
            if (matched) {
                setProposalScore(score);
            }
        }
        if (matched) {
            setPosition(wordDetector);
            return true;
        }
    } else if (divPos != -1) {
        // Most likely it is a column name after an alias - all columns are valid
        if (getObject() != null) {
            return true;
        }
    }
    return false;
}
Also used : SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) SQLSyntaxManager(org.jkiss.dbeaver.model.sql.SQLSyntaxManager) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) StyledString(org.eclipse.jface.viewers.StyledString) IEditorPart(org.eclipse.ui.IEditorPart) Point(org.eclipse.swt.graphics.Point) ITextViewer(org.eclipse.jface.text.ITextViewer)

Example 45 with DBPDataSource

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

the class DBExecUtils method bindAttributes.

public static void bindAttributes(@NotNull DBCSession session, @Nullable DBSEntity sourceEntity, @Nullable DBCResultSet resultSet, @NotNull DBDAttributeBinding[] bindings, @Nullable List<Object[]> rows) throws DBException {
    final DBRProgressMonitor monitor = session.getProgressMonitor();
    final DBPDataSource dataSource = session.getDataSource();
    boolean readMetaData = dataSource.getContainer().getPreferenceStore().getBoolean(ModelPreferences.RESULT_SET_READ_METADATA);
    if (!readMetaData && sourceEntity == null) {
        // Do not read metadata if source entity is not known
        return;
    }
    boolean readReferences = dataSource.getContainer().getPreferenceStore().getBoolean(ModelPreferences.RESULT_SET_READ_REFERENCES);
    final Map<DBCEntityMetaData, DBSEntity> entityBindingMap = new IdentityHashMap<>();
    monitor.beginTask("Discover resultset metadata", 3);
    try {
        SQLQuery sqlQuery = null;
        DBSEntity entity = null;
        if (sourceEntity != null) {
            entity = sourceEntity;
        } else if (resultSet != 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 = DBUtils.getEntityFromMetaData(monitor, session.getExecutionContext(), entityMeta);
                        if (entity != null) {
                            entityBindingMap.put(entityMeta, entity);
                        }
                    }
                }
            }
        }
        final Map<DBSEntity, DBDRowIdentifier> locatorMap = new IdentityHashMap<>();
        monitor.subTask("Discover attributes");
        for (DBDAttributeBinding binding : bindings) {
            monitor.subTask("Discover attribute '" + binding.getName() + "'");
            DBCAttributeMetaData attrMeta = binding.getMetaAttribute();
            if (attrMeta == null) {
                continue;
            }
            // 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 = DBUtils.getEntityFromMetaData(monitor, session.getExecutionContext(), 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 if (binding instanceof DBDAttributeBindingMeta) {
                DBDAttributeBindingMeta bindingMeta = (DBDAttributeBindingMeta) binding;
                DBDPseudoAttribute pseudoAttribute = DBUtils.getPseudoAttribute(attrEntity, attrMeta.getName());
                if (pseudoAttribute != null) {
                    bindingMeta.setPseudoAttribute(pseudoAttribute);
                }
                DBSEntityAttribute tableColumn;
                if (bindingMeta.getPseudoAttribute() != null) {
                    tableColumn = bindingMeta.getPseudoAttribute().createFakeAttribute(attrEntity, attrMeta);
                } else {
                    tableColumn = attrEntity.getAttribute(monitor, attrMeta.getName());
                }
                if (tableColumn != null && // - Database doesn't support column name collisions (default)
                (sourceEntity != null || bindingMeta.getMetaAttribute().getEntityMetaData() != null || !bindingMeta.getDataSource().getInfo().needsTableMetaForColumnResolution()) && bindingMeta.setEntityAttribute(tableColumn, ((sqlQuery == null || tableColumn.getTypeID() != attrMeta.getTypeID()) && rows != null))) {
                    // 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, 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 (DBDAttributeBinding binding : bindings) {
                if (!(binding instanceof DBDAttributeBindingMeta)) {
                    continue;
                }
                DBDAttributeBindingMeta bindingMeta = (DBDAttributeBindingMeta) binding;
                // monitor.subTask("Find attribute '" + binding.getName() + "' identifier");
                DBSEntityAttribute attr = binding.getEntityAttribute();
                if (attr == null) {
                    bindingMeta.setRowIdentifierStatus("No corresponding table column");
                    continue;
                }
                DBSEntity attrEntity = attr.getParentObject();
                if (attrEntity != null) {
                    DBDRowIdentifier rowIdentifier = locatorMap.get(attrEntity);
                    if (rowIdentifier == null) {
                        DBSEntityConstraint entityIdentifier = getBestIdentifier(monitor, attrEntity, bindings, readMetaData);
                        if (entityIdentifier != null) {
                            rowIdentifier = new DBDRowIdentifier(attrEntity, entityIdentifier);
                            locatorMap.put(attrEntity, rowIdentifier);
                        } else {
                            bindingMeta.setRowIdentifierStatus("Cannot determine unique row identifier");
                        }
                    }
                    bindingMeta.setRowIdentifier(rowIdentifier);
                }
            }
            monitor.worked(1);
        }
        if (readMetaData && readReferences && rows != null) {
            monitor.subTask("Read results metadata");
            // Read nested bindings
            for (DBDAttributeBinding binding : bindings) {
                binding.lateBinding(session, rows);
            }
        }
        /*
            monitor.subTask("Load transformers");
            // Load transformers
            for (DBDAttributeBinding binding : bindings) {
                binding.loadTransformers(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) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Aggregations

DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)118 DBException (org.jkiss.dbeaver.DBException)43 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)22 DBPDataSourceContainer (org.jkiss.dbeaver.model.DBPDataSourceContainer)14 JDBCStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement)12 SQLException (java.sql.SQLException)10 GridData (org.eclipse.swt.layout.GridData)10 IEditorPart (org.eclipse.ui.IEditorPart)10 JDBCResultSet (org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)10 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)10 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)10 InvocationTargetException (java.lang.reflect.InvocationTargetException)9 DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)9 ArrayList (java.util.ArrayList)8 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)8 IWorkbenchPart (org.eclipse.ui.IWorkbenchPart)7 SQLDataSource (org.jkiss.dbeaver.model.sql.SQLDataSource)7 ISelection (org.eclipse.jface.viewers.ISelection)6 Composite (org.eclipse.swt.widgets.Composite)5 VoidProgressMonitor (org.jkiss.dbeaver.model.runtime.VoidProgressMonitor)5