Search in sources :

Example 6 with SQLWordPartDetector

use of org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector in project dbeaver by serge-rider.

the class SQLCompletionProcessor method computeCompletionProposals.

@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    IDocument document = editor.getDocument();
    if (document == null) {
        return new ICompletionProposal[0];
    }
    final SQLCompletionRequest request = new SQLCompletionRequest(editor.getCompletionContext(), document, documentOffset, editor.extractQueryAtPos(documentOffset), simpleMode);
    SQLWordPartDetector wordDetector = request.getWordDetector();
    try {
        // Check that word start position is in default partition (#5994)
        String contentType = TextUtilities.getContentType(document, SQLParserPartitions.SQL_PARTITIONING, wordDetector.getStartOffset(), true);
        if (contentType == null || (!IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) && !SQLParserPartitions.CONTENT_TYPE_SQL_QUOTED.equals(contentType))) {
            return new ICompletionProposal[0];
        }
    } catch (BadLocationException e) {
        log.debug(e);
        return new ICompletionProposal[0];
    }
    if (lookupTemplates) {
        return makeTemplateProposals(viewer, request);
    }
    try {
        String commandPrefix = editor.getSyntaxManager().getControlCommandPrefix();
        if (wordDetector.getStartOffset() >= commandPrefix.length() && viewer.getDocument().get(wordDetector.getStartOffset() - commandPrefix.length(), commandPrefix.length()).equals(commandPrefix)) {
            return makeCommandProposals(request, request.getWordPart());
        }
    } catch (BadLocationException e) {
        log.debug(e);
    }
    SQLCompletionAnalyzer analyzer = new SQLCompletionAnalyzer(request);
    DBPDataSource dataSource = editor.getDataSource();
    if (request.getWordPart() != null) {
        if (dataSource != null) {
            ProposalSearchJob searchJob = new ProposalSearchJob(analyzer);
            searchJob.schedule();
            // Wait until job finished
            UIUtils.waitJobCompletion(searchJob);
        }
    }
    List<SQLCompletionProposalBase> proposals = analyzer.getProposals();
    List<ICompletionProposal> result = new ArrayList<>();
    for (SQLCompletionProposalBase cp : proposals) {
        if (cp instanceof ICompletionProposal) {
            result.add((ICompletionProposal) cp);
        }
    }
    return ArrayUtils.toArray(ICompletionProposal.class, result);
}
Also used : SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) SQLCompletionProposalBase(org.jkiss.dbeaver.model.sql.completion.SQLCompletionProposalBase) ArrayList(java.util.ArrayList) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLCompletionRequest(org.jkiss.dbeaver.model.sql.completion.SQLCompletionRequest) SQLCompletionAnalyzer(org.jkiss.dbeaver.model.sql.completion.SQLCompletionAnalyzer)

Example 7 with SQLWordPartDetector

use of org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector in project dbeaver by serge-rider.

the class SQLCompletionAnalyzer method makeProposalsFromChildren.

private void makeProposalsFromChildren(DBPObject parent, @Nullable String startPart, boolean addFirst, Map<String, Object> params) throws DBException {
    if (request.getQueryType() == SQLCompletionRequest.QueryType.EXEC) {
        return;
    }
    if (parent instanceof DBSAlias) {
        DBSObject realParent = ((DBSAlias) parent).getTargetObject(monitor);
        if (realParent == null) {
            log.debug("Can't get synonym target object");
        } else {
            parent = realParent;
        }
    }
    SQLWordPartDetector wordDetector = request.getWordDetector();
    if (startPart != null) {
        startPart = wordDetector.removeQuotes(startPart).toUpperCase(Locale.ENGLISH);
        int divPos = startPart.lastIndexOf(request.getContext().getSyntaxManager().getStructSeparator());
        if (divPos != -1) {
            startPart = startPart.substring(divPos + 1);
        }
    }
    DBPDataSource dataSource = request.getContext().getDataSource();
    Collection<? extends DBSObject> children = null;
    if (parent instanceof DBSObjectContainer) {
        children = ((DBSObjectContainer) parent).getChildren(monitor);
    } else if (parent instanceof DBSEntity) {
        children = ((DBSEntity) parent).getAttributes(monitor);
    }
    if (children != null && !children.isEmpty()) {
        // boolean isJoin = SQLConstants.KEYWORD_JOIN.equals(request.wordDetector.getPrevKeyWord());
        List<DBSObject> matchedObjects = new ArrayList<>();
        final Map<String, Integer> scoredMatches = new HashMap<>();
        boolean simpleMode = request.isSimpleMode();
        boolean allObjects = !simpleMode && ALL_COLUMNS_PATTERN.equals(startPart);
        String objPrefix = null;
        if (allObjects) {
            if (!CommonUtils.isEmpty(wordDetector.getPrevWords())) {
                String prevWord = wordDetector.getPrevWords().get(0);
                if (prevWord.length() > 0 && prevWord.charAt(prevWord.length() - 1) == request.getContext().getSyntaxManager().getStructSeparator()) {
                    objPrefix = prevWord;
                }
            }
        }
        StringBuilder combinedMatch = new StringBuilder();
        for (DBSObject child : children) {
            if (DBUtils.isHiddenObject(child)) {
                // Skip hidden
                continue;
            }
            if (DBUtils.isVirtualObject(child)) {
                makeProposalsFromChildren(child, startPart, addFirst, Collections.emptyMap());
                continue;
            }
            if (allObjects) {
                if (combinedMatch.length() > 0) {
                    combinedMatch.append(", ");
                    if (objPrefix != null)
                        combinedMatch.append(objPrefix);
                }
                combinedMatch.append(DBUtils.getQuotedIdentifier(child));
            } else {
                if (dataSource != null && !request.getContext().isSearchInsideNames()) {
                    // startsWith
                    if (CommonUtils.isEmpty(startPart) || CommonUtils.startsWithIgnoreCase(child.getName(), startPart)) {
                        matchedObjects.add(child);
                    }
                } else {
                    // Use fuzzy search for contains
                    int score = CommonUtils.isEmpty(startPart) ? 1 : TextUtils.fuzzyScore(child.getName(), startPart);
                    if (score > 0) {
                        matchedObjects.add(child);
                        scoredMatches.put(child.getName(), score);
                    }
                }
            }
        }
        if (combinedMatch.length() > 0) {
            String replaceString = combinedMatch.toString();
            proposals.add(createCompletionProposal(request, replaceString, replaceString, DBPKeywordType.OTHER, "All objects"));
        } else if (!matchedObjects.isEmpty()) {
            if (startPart == null || scoredMatches.isEmpty()) {
                if (dataSource != null && request.getContext().isSortAlphabetically()) {
                    matchedObjects.sort(DBUtils.nameComparatorIgnoreCase());
                }
            } else {
                matchedObjects.sort((o1, o2) -> {
                    int score1 = scoredMatches.get(o1.getName());
                    int score2 = scoredMatches.get(o2.getName());
                    if (score1 == score2) {
                        if (o1 instanceof DBSAttributeBase) {
                            return ((DBSAttributeBase) o1).getOrdinalPosition() - ((DBSAttributeBase) o2).getOrdinalPosition();
                        }
                        return o1.getName().compareToIgnoreCase(o2.getName());
                    }
                    return score2 - score1;
                });
            }
            List<SQLCompletionProposalBase> childProposals = new ArrayList<>(matchedObjects.size());
            for (DBSObject child : matchedObjects) {
                SQLCompletionProposalBase proposal = makeProposalsFromObject(child, !(parent instanceof DBPDataSource), params);
                if (!scoredMatches.isEmpty()) {
                    int proposalScore = scoredMatches.get(child.getName());
                    proposal.setProposalScore(proposalScore);
                }
                childProposals.add(proposal);
            }
            if (addFirst) {
                // Add proposals in the beginning (because the most strict identifiers have to be first)
                proposals.addAll(0, childProposals);
            } else {
                proposals.addAll(childProposals);
            }
        }
    }
}
Also used : DBCSession(org.jkiss.dbeaver.model.exec.DBCSession) java.util(java.util) DBNNode(org.jkiss.dbeaver.model.navigator.DBNNode) Nullable(org.jkiss.code.Nullable) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) NotNull(org.jkiss.code.NotNull) DBDLabelValuePair(org.jkiss.dbeaver.model.data.DBDLabelValuePair) RelationalObjectType(org.jkiss.dbeaver.model.impl.struct.RelationalObjectType) DBNUtils(org.jkiss.dbeaver.model.navigator.DBNUtils) Matcher(java.util.regex.Matcher) Log(org.jkiss.dbeaver.Log) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) org.jkiss.dbeaver.model(org.jkiss.dbeaver.model) DBRRunnableParametrized(org.jkiss.dbeaver.model.runtime.DBRRunnableParametrized) CommonUtils(org.jkiss.utils.CommonUtils) org.jkiss.dbeaver.model.struct(org.jkiss.dbeaver.model.struct) PatternSyntaxException(java.util.regex.PatternSyntaxException) Table(net.sf.jsqlparser.schema.Table) DBObjectNameCaseTransformer(org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer) ArrayUtils(org.jkiss.utils.ArrayUtils) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBCExecutionPurpose(org.jkiss.dbeaver.model.exec.DBCExecutionPurpose) TextUtils(org.jkiss.dbeaver.model.text.TextUtils) DBException(org.jkiss.dbeaver.DBException) Statement(net.sf.jsqlparser.statement.Statement) Pattern(java.util.regex.Pattern) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) TablesNamesFinder(net.sf.jsqlparser.util.TablesNamesFinder) org.jkiss.dbeaver.model.sql(org.jkiss.dbeaver.model.sql) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector)

Example 8 with SQLWordPartDetector

use of org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector in project dbeaver by serge-rider.

the class SQLCompletionAnalyzer method runAnalyzer.

private void runAnalyzer() throws DBException {
    String searchPrefix = request.getWordPart();
    request.setQueryType(null);
    SQLWordPartDetector wordDetector = request.getWordDetector();
    SQLSyntaxManager syntaxManager = request.getContext().getSyntaxManager();
    String prevKeyWord = wordDetector.getPrevKeyWord();
    boolean isPrevWordEmpty = CommonUtils.isEmpty(wordDetector.getPrevWords());
    String prevDelimiter = wordDetector.getPrevDelimiter();
    {
        if (!CommonUtils.isEmpty(prevKeyWord)) {
            if (syntaxManager.getDialect().isEntityQueryWord(prevKeyWord)) {
                // TODO: its an ugly hack. Need a better way
                if (SQLConstants.KEYWORD_DELETE.equals(prevKeyWord)) {
                    request.setQueryType(null);
                } else if (SQLConstants.KEYWORD_INTO.equals(prevKeyWord) && !isPrevWordEmpty && ("(".equals(prevDelimiter) || ",".equals(prevDelimiter))) {
                    request.setQueryType(SQLCompletionRequest.QueryType.COLUMN);
                } else if (SQLConstants.KEYWORD_INTO.equals(prevKeyWord) && !isPrevWordEmpty && ("(*".equals(prevDelimiter) || "{*".equals(prevDelimiter) || "[*".equals(prevDelimiter))) {
                    wordDetector.shiftOffset(-SQLCompletionAnalyzer.ALL_COLUMNS_PATTERN.length());
                    searchPrefix = SQLCompletionAnalyzer.ALL_COLUMNS_PATTERN;
                    request.setQueryType(SQLCompletionRequest.QueryType.COLUMN);
                } else if (SQLConstants.KEYWORD_JOIN.equals(prevKeyWord)) {
                    request.setQueryType(SQLCompletionRequest.QueryType.JOIN);
                } else {
                    if (!isPrevWordEmpty && CommonUtils.isEmpty(prevDelimiter)) {
                        // Seems to be table alias
                        return;
                    }
                    request.setQueryType(SQLCompletionRequest.QueryType.TABLE);
                }
            } else if (syntaxManager.getDialect().isAttributeQueryWord(prevKeyWord)) {
                request.setQueryType(SQLCompletionRequest.QueryType.COLUMN);
                if (!request.isSimpleMode() && CommonUtils.isEmpty(request.getWordPart()) && prevDelimiter.equals(SQLCompletionAnalyzer.ALL_COLUMNS_PATTERN)) {
                    wordDetector.shiftOffset(-SQLCompletionAnalyzer.ALL_COLUMNS_PATTERN.length());
                    searchPrefix = SQLCompletionAnalyzer.ALL_COLUMNS_PATTERN;
                }
            } else if (SQLUtils.isExecQuery(syntaxManager.getDialect(), prevKeyWord)) {
                request.setQueryType(SQLCompletionRequest.QueryType.EXEC);
            }
        }
    }
    request.setWordPart(searchPrefix);
    DBPDataSource dataSource = request.getContext().getDataSource();
    if (dataSource == null) {
        return;
    }
    String wordPart = request.getWordPart();
    boolean emptyWord = wordPart.length() == 0;
    SQLCompletionRequest.QueryType queryType = request.getQueryType();
    Map<String, Object> parameters = new LinkedHashMap<>();
    List<String> prevWords = wordDetector.getPrevWords();
    String previousWord = "";
    if (!CommonUtils.isEmpty(prevWords)) {
        previousWord = prevWords.get(0).toUpperCase(Locale.ENGLISH);
    }
    if (!CommonUtils.isEmpty(prevWords) && (SQLConstants.KEYWORD_PROCEDURE.equals(previousWord) || SQLConstants.KEYWORD_FUNCTION.equals(previousWord))) {
        parameters.put(SQLCompletionProposalBase.PARAM_EXEC, false);
    } else {
        parameters.put(SQLCompletionProposalBase.PARAM_EXEC, true);
    }
    if (queryType != null) {
        // or get list of root database objects
        if (emptyWord) {
            // Get root objects
            DBPObject rootObject = null;
            if (queryType == SQLCompletionRequest.QueryType.COLUMN && dataSource instanceof DBSObjectContainer) {
                // Try to detect current table
                rootObject = getTableFromAlias((DBSObjectContainer) dataSource, null, true);
                if (rootObject instanceof DBSEntity) {
                    switch(prevKeyWord) {
                        case SQLConstants.KEYWORD_ON:
                            // Join?
                            if (makeJoinColumnProposals((DBSObjectContainer) dataSource, (DBSEntity) rootObject)) {
                                return;
                            }
                        // Fall-thru
                        case SQLConstants.KEYWORD_WHERE:
                        case SQLConstants.KEYWORD_AND:
                        case SQLConstants.KEYWORD_OR:
                            if (!request.isSimpleMode()) {
                                boolean waitsForValue = rootObject instanceof DBSEntity && !CommonUtils.isEmpty(prevWords) && !CommonUtils.isEmpty(prevDelimiter) && !prevDelimiter.endsWith(")");
                                if (waitsForValue) {
                                    makeProposalsFromAttributeValues(dataSource, wordDetector, (DBSEntity) rootObject);
                                }
                            }
                            break;
                    }
                }
            } else if (dataSource instanceof DBSObjectContainer) {
                // Try to get from active object
                DBSObject selectedObject = DBUtils.getActiveInstanceObject(request.getContext().getExecutionContext());
                if (selectedObject != null) {
                    makeProposalsFromChildren(selectedObject, null, false, parameters);
                    rootObject = DBUtils.getPublicObject(selectedObject.getParentObject());
                } else {
                    rootObject = dataSource;
                }
            }
            if (rootObject != null) {
                makeProposalsFromChildren(rootObject, null, false, parameters);
            }
            if (queryType == SQLCompletionRequest.QueryType.JOIN && !proposals.isEmpty() && dataSource instanceof DBSObjectContainer) {
                // Filter out non-joinable tables
                DBSObject leftTable = getTableFromAlias((DBSObjectContainer) dataSource, null, true);
                if (leftTable instanceof DBSEntity) {
                    filterNonJoinableProposals((DBSEntity) leftTable);
                }
            }
        } else {
            DBSObject rootObject = null;
            if (queryType == SQLCompletionRequest.QueryType.COLUMN && dataSource instanceof DBSObjectContainer) {
                // Part of column name
                // Try to get from active object
                DBSObjectContainer sc = (DBSObjectContainer) dataSource;
                DBSObject selectedObject = DBUtils.getActiveInstanceObject(request.getContext().getExecutionContext());
                if (selectedObject instanceof DBSObjectContainer) {
                    sc = (DBSObjectContainer) selectedObject;
                }
                SQLDialect sqlDialect = request.getContext().getDataSource().getSQLDialect();
                String tableAlias = null;
                if (ALL_COLUMNS_PATTERN.equals(wordPart)) {
                    if (!isPrevWordEmpty) {
                        if (!prevKeyWord.equalsIgnoreCase("INTO")) {
                            String prevWord = wordDetector.getPrevWords().get(0);
                            if (prevWord.contains(sqlDialect.getCatalogSeparator())) {
                                int divPos = prevWord.lastIndexOf(sqlDialect.getCatalogSeparator());
                                tableAlias = prevWord.substring(0, divPos);
                            }
                        }
                    }
                }
                if (tableAlias == null) {
                    int divPos = wordPart.lastIndexOf(syntaxManager.getStructSeparator());
                    tableAlias = divPos == -1 ? null : wordPart.substring(0, divPos);
                }
                if (tableAlias == null && !CommonUtils.isEmpty(wordPart)) {
                    // May be an incomplete table alias. Try to find such table
                    rootObject = getTableFromAlias(sc, wordPart, false);
                    if (rootObject != null) {
                        // Found alias - no proposals
                        searchFinished = true;
                        return;
                    }
                }
                rootObject = getTableFromAlias(sc, tableAlias, false);
                if (rootObject == null && tableAlias != null) {
                    // Maybe alias ss a table name
                    String[] allNames = SQLUtils.splitFullIdentifier(tableAlias, sqlDialect.getCatalogSeparator(), sqlDialect.getIdentifierQuoteStrings(), false);
                    rootObject = SQLSearchUtils.findObjectByFQN(monitor, sc, request.getContext().getExecutionContext(), Arrays.asList(allNames), !request.isSimpleMode(), wordDetector);
                }
            }
            if (rootObject != null) {
                makeProposalsFromChildren(rootObject, wordPart, false, parameters);
            } else {
                // Get root object or objects from active database (if any)
                if (queryType != SQLCompletionRequest.QueryType.COLUMN && queryType != SQLCompletionRequest.QueryType.EXEC) {
                    makeDataSourceProposals();
                }
            }
        }
        if (!request.isSimpleMode() && (queryType == SQLCompletionRequest.QueryType.EXEC || (queryType == SQLCompletionRequest.QueryType.COLUMN && request.getContext().isSearchProcedures())) && dataSource instanceof DBSObjectContainer) {
            makeProceduresProposals(dataSource, wordPart, true);
        }
    } else {
        if (!request.isSimpleMode() && !CommonUtils.isEmpty(prevWords)) {
            if (SQLConstants.KEYWORD_PROCEDURE.equals(previousWord) || SQLConstants.KEYWORD_FUNCTION.equals(previousWord)) {
                makeProceduresProposals(dataSource, wordPart, false);
            }
        // may be useful in the future for procedures autocomplete
        /*if (SQLConstants.BLOCK_BEGIN.equalsIgnoreCase(prevWords.get(0))) {
                    makeProceduresProposals(dataSource, wordPart, true);
                }*/
        }
    }
    if (!emptyWord) {
        makeProposalsFromQueryParts();
    }
    // Final filtering
    if (!searchFinished) {
        List<String> matchedKeywords = Collections.emptyList();
        Set<String> allowedKeywords = null;
        SQLDialect sqlDialect = request.getContext().getDataSource().getSQLDialect();
        if (CommonUtils.isEmpty(prevKeyWord)) {
            allowedKeywords = new HashSet<>();
            Collections.addAll(allowedKeywords, sqlDialect.getQueryKeywords());
            Collections.addAll(allowedKeywords, sqlDialect.getDMLKeywords());
            Collections.addAll(allowedKeywords, sqlDialect.getDDLKeywords());
            Collections.addAll(allowedKeywords, sqlDialect.getExecuteKeywords());
        } else if (ArrayUtils.contains(sqlDialect.getQueryKeywords(), prevKeyWord.toUpperCase(Locale.ENGLISH))) {
            // SELECT ..
            // Limit with FROM if we already have some expression
            String delimiter = wordDetector.getPrevDelimiter();
            if (!isPrevWordEmpty && (CommonUtils.isEmpty(delimiter) || delimiter.endsWith(")"))) {
                // last expression ends with space or with ")"
                allowedKeywords = new HashSet<>();
                allowedKeywords.add(SQLConstants.KEYWORD_FROM);
                if (CommonUtils.isEmpty(request.getWordPart())) {
                    matchedKeywords = Arrays.asList(SQLConstants.KEYWORD_FROM);
                }
            }
        } else if (sqlDialect.isEntityQueryWord(prevKeyWord)) {
            allowedKeywords = new HashSet<>();
            if (SQLConstants.KEYWORD_DELETE.equals(prevKeyWord)) {
                allowedKeywords.add(SQLConstants.KEYWORD_FROM);
            } else {
                allowedKeywords.add(SQLConstants.KEYWORD_WHERE);
            }
        }
        if (!CommonUtils.isEmpty(request.getWordPart())) {
            // Keyword assist
            matchedKeywords = syntaxManager.getDialect().getMatchedKeywords(request.getWordPart());
            if (!request.isSimpleMode()) {
                // Sort using fuzzy match
                matchedKeywords.sort(Comparator.comparingInt(o -> TextUtils.fuzzyScore(o, request.getWordPart())));
            }
        }
        for (String keyWord : matchedKeywords) {
            DBPKeywordType keywordType = syntaxManager.getDialect().getKeywordType(keyWord);
            if (keywordType != null) {
                if (keywordType == DBPKeywordType.TYPE) {
                    continue;
                }
                if (request.getQueryType() == SQLCompletionRequest.QueryType.COLUMN && !(keywordType == DBPKeywordType.FUNCTION || keywordType == DBPKeywordType.KEYWORD || keywordType == DBPKeywordType.OTHER)) {
                    continue;
                }
                if (allowedKeywords != null && !allowedKeywords.contains(keyWord)) {
                    continue;
                }
                proposals.add(SQLCompletionAnalyzer.createCompletionProposal(request, keyWord, keyWord, keywordType, null, false, null, Collections.emptyMap()));
            }
        }
    }
    filterProposals(dataSource);
}
Also used : DBCSession(org.jkiss.dbeaver.model.exec.DBCSession) java.util(java.util) DBNNode(org.jkiss.dbeaver.model.navigator.DBNNode) Nullable(org.jkiss.code.Nullable) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) NotNull(org.jkiss.code.NotNull) DBDLabelValuePair(org.jkiss.dbeaver.model.data.DBDLabelValuePair) RelationalObjectType(org.jkiss.dbeaver.model.impl.struct.RelationalObjectType) DBNUtils(org.jkiss.dbeaver.model.navigator.DBNUtils) Matcher(java.util.regex.Matcher) Log(org.jkiss.dbeaver.Log) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) org.jkiss.dbeaver.model(org.jkiss.dbeaver.model) DBRRunnableParametrized(org.jkiss.dbeaver.model.runtime.DBRRunnableParametrized) CommonUtils(org.jkiss.utils.CommonUtils) org.jkiss.dbeaver.model.struct(org.jkiss.dbeaver.model.struct) PatternSyntaxException(java.util.regex.PatternSyntaxException) Table(net.sf.jsqlparser.schema.Table) DBObjectNameCaseTransformer(org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer) ArrayUtils(org.jkiss.utils.ArrayUtils) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBCExecutionPurpose(org.jkiss.dbeaver.model.exec.DBCExecutionPurpose) TextUtils(org.jkiss.dbeaver.model.text.TextUtils) DBException(org.jkiss.dbeaver.DBException) Statement(net.sf.jsqlparser.statement.Statement) Pattern(java.util.regex.Pattern) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) TablesNamesFinder(net.sf.jsqlparser.util.TablesNamesFinder) org.jkiss.dbeaver.model.sql(org.jkiss.dbeaver.model.sql) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector)

Example 9 with SQLWordPartDetector

use of org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector in project dbeaver by dbeaver.

the class ResultSetFilterPanel method getProposals.

@Override
public IContentProposal[] getProposals(String contents, int position) {
    if (!viewer.getPreferenceStore().getBoolean(ResultSetPreferences.RESULT_SET_FILTER_AUTO_COMPLETE_PROPOSIAL)) {
        return null;
    }
    SQLSyntaxManager syntaxManager = new SQLSyntaxManager();
    DBPDataSource dataSource = viewer.getDataSource();
    if (dataSource != null) {
        syntaxManager.init(dataSource);
    }
    SQLWordPartDetector wordDetector = new SQLWordPartDetector(new Document(contents), syntaxManager, position);
    String word = wordDetector.getFullWord();
    final List<IContentProposal> proposals = new ArrayList<>();
    if (CommonUtils.isEmptyTrimmed(word))
        word = contents;
    word = word.toLowerCase(Locale.ENGLISH);
    String attrName = word;
    final DBRRunnableWithProgress reader = monitor -> {
        DBDAttributeBinding[] attributes = viewer.getModel().getAttributes();
        for (DBDAttributeBinding attribute : attributes) {
            if (attribute.isCustom()) {
                continue;
            }
            final String name = DBUtils.getUnQuotedIdentifier(attribute.getDataSource(), attribute.getName());
            if (CommonUtils.isEmpty(attrName) || name.toLowerCase(Locale.ENGLISH).startsWith(attrName)) {
                final String content = DBUtils.getQuotedIdentifier(attribute) + " ";
                proposals.add(new ContentProposalExt(content, attribute.getName(), DBInfoUtils.makeObjectDescription(monitor, attribute.getAttribute(), false), content.length(), DBValueFormatting.getObjectImage(attribute)));
            }
        }
    };
    SystemJob searchJob = new SystemJob("Extract attribute proposals", reader);
    searchJob.schedule();
    UIUtils.waitJobCompletion(searchJob);
    String[] filterKeywords = { SQLConstants.KEYWORD_AND, SQLConstants.KEYWORD_OR, SQLConstants.KEYWORD_IS, SQLConstants.KEYWORD_NOT, SQLConstants.KEYWORD_NULL };
    for (String kw : filterKeywords) {
        if (attrName.isEmpty() || kw.startsWith(attrName.toUpperCase())) {
            if (dataSource != null) {
                kw = dataSource.getSQLDialect().storesUnquotedCase().transform(kw);
            }
            proposals.add(new ContentProposal(kw + " ", kw + ": SQL expression keyword"));
        }
    }
    return proposals.toArray(new IContentProposal[0]);
}
Also used : ResultSetHandlerMain(org.jkiss.dbeaver.ui.controls.resultset.handler.ResultSetHandlerMain) org.jkiss.dbeaver.ui(org.jkiss.dbeaver.ui) StyledText(org.eclipse.swt.custom.StyledText) IWorkbenchCommandConstants(org.eclipse.ui.IWorkbenchCommandConstants) DBDDataFilter(org.jkiss.dbeaver.model.data.DBDDataFilter) ContentProposal(org.eclipse.jface.fieldassist.ContentProposal) Matcher(java.util.regex.Matcher) PartInitException(org.eclipse.ui.PartInitException) Locale(java.util.Locale) ContentProposalAdapter(org.eclipse.jface.fieldassist.ContentProposalAdapter) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) SystemJob(org.jkiss.dbeaver.model.runtime.SystemJob) IAdaptable(org.eclipse.core.runtime.IAdaptable) CommonUtils(org.jkiss.utils.CommonUtils) org.eclipse.swt.graphics(org.eclipse.swt.graphics) DBDAttributeConstraint(org.jkiss.dbeaver.model.data.DBDAttributeConstraint) StyledTextUtils(org.jkiss.dbeaver.ui.controls.StyledTextUtils) Collection(java.util.Collection) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) DBStyles(org.jkiss.dbeaver.ui.css.DBStyles) ContentAssistUtils(org.jkiss.dbeaver.ui.contentassist.ContentAssistUtils) List(java.util.List) DBException(org.jkiss.dbeaver.DBException) SWT(org.eclipse.swt.SWT) SQLSyntaxManager(org.jkiss.dbeaver.model.sql.SQLSyntaxManager) SQLUtils(org.jkiss.dbeaver.model.sql.SQLUtils) Pattern(java.util.regex.Pattern) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) ContentProposalExt(org.jkiss.dbeaver.ui.contentassist.ContentProposalExt) DBWorkbench(org.jkiss.dbeaver.runtime.DBWorkbench) SQLConstants(org.jkiss.dbeaver.model.sql.SQLConstants) Nullable(org.jkiss.code.Nullable) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) NotNull(org.jkiss.code.NotNull) UIServiceSQL(org.jkiss.dbeaver.runtime.ui.UIServiceSQL) ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) Log(org.jkiss.dbeaver.Log) ResultSetMessages(org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages) GridData(org.eclipse.swt.layout.GridData) FillLayout(org.eclipse.swt.layout.FillLayout) org.jkiss.dbeaver.model(org.jkiss.dbeaver.model) DBSEntity(org.jkiss.dbeaver.model.struct.DBSEntity) org.eclipse.swt.events(org.eclipse.swt.events) IContentProposalProvider(org.eclipse.jface.fieldassist.IContentProposalProvider) IUndoManager(org.eclipse.jface.text.IUndoManager) TextEditorUtils(org.jkiss.dbeaver.ui.editors.TextEditorUtils) org.eclipse.swt.widgets(org.eclipse.swt.widgets) DBNDatabaseNode(org.jkiss.dbeaver.model.navigator.DBNDatabaseNode) TextViewerUndoManager(org.eclipse.jface.text.TextViewerUndoManager) CSSUtils(org.jkiss.dbeaver.ui.css.CSSUtils) TextViewer(org.eclipse.jface.text.TextViewer) DBSDataContainer(org.jkiss.dbeaver.model.struct.DBSDataContainer) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) GridLayout(org.eclipse.swt.layout.GridLayout) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) ContentProposalExt(org.jkiss.dbeaver.ui.contentassist.ContentProposalExt) ArrayList(java.util.ArrayList) Document(org.eclipse.jface.text.Document) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) SystemJob(org.jkiss.dbeaver.model.runtime.SystemJob) ContentProposal(org.eclipse.jface.fieldassist.ContentProposal) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) IContentProposal(org.eclipse.jface.fieldassist.IContentProposal) SQLSyntaxManager(org.jkiss.dbeaver.model.sql.SQLSyntaxManager) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress)

Example 10 with SQLWordPartDetector

use of org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector in project dbeaver by dbeaver.

the class SQLCompletionProcessor method computeCompletionProposals.

@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    IDocument document = editor.getDocument();
    if (document == null) {
        return new ICompletionProposal[0];
    }
    final SQLCompletionRequest request = new SQLCompletionRequest(editor.getCompletionContext(), document, documentOffset, editor.extractQueryAtPos(documentOffset), simpleMode);
    SQLWordPartDetector wordDetector = request.getWordDetector();
    try {
        // Check that word start position is in default partition (#5994)
        String contentType = TextUtilities.getContentType(document, SQLParserPartitions.SQL_PARTITIONING, wordDetector.getStartOffset(), true);
        if (contentType == null || (!IDocument.DEFAULT_CONTENT_TYPE.equals(contentType) && !SQLParserPartitions.CONTENT_TYPE_SQL_QUOTED.equals(contentType))) {
            return new ICompletionProposal[0];
        }
    } catch (BadLocationException e) {
        log.debug(e);
        return new ICompletionProposal[0];
    }
    if (lookupTemplates) {
        return makeTemplateProposals(viewer, request);
    }
    try {
        String commandPrefix = editor.getSyntaxManager().getControlCommandPrefix();
        if (wordDetector.getStartOffset() >= commandPrefix.length() && viewer.getDocument().get(wordDetector.getStartOffset() - commandPrefix.length(), commandPrefix.length()).equals(commandPrefix)) {
            return makeCommandProposals(request, request.getWordPart());
        }
    } catch (BadLocationException e) {
        log.debug(e);
    }
    SQLCompletionAnalyzer analyzer = new SQLCompletionAnalyzer(request);
    DBPDataSource dataSource = editor.getDataSource();
    if (request.getWordPart() != null) {
        if (dataSource != null) {
            ProposalSearchJob searchJob = new ProposalSearchJob(analyzer);
            searchJob.schedule();
            // Wait until job finished
            UIUtils.waitJobCompletion(searchJob);
        }
    }
    List<SQLCompletionProposalBase> proposals = analyzer.getProposals();
    List<ICompletionProposal> result = new ArrayList<>();
    for (SQLCompletionProposalBase cp : proposals) {
        if (cp instanceof ICompletionProposal) {
            result.add((ICompletionProposal) cp);
        }
    }
    return ArrayUtils.toArray(ICompletionProposal.class, result);
}
Also used : SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) SQLCompletionProposalBase(org.jkiss.dbeaver.model.sql.completion.SQLCompletionProposalBase) ArrayList(java.util.ArrayList) DBPDataSource(org.jkiss.dbeaver.model.DBPDataSource) SQLCompletionRequest(org.jkiss.dbeaver.model.sql.completion.SQLCompletionRequest) SQLCompletionAnalyzer(org.jkiss.dbeaver.model.sql.completion.SQLCompletionAnalyzer)

Aggregations

SQLWordPartDetector (org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector)14 DBException (org.jkiss.dbeaver.DBException)8 DBCExecutionContext (org.jkiss.dbeaver.model.exec.DBCExecutionContext)8 Matcher (java.util.regex.Matcher)6 Pattern (java.util.regex.Pattern)6 NotNull (org.jkiss.code.NotNull)6 Nullable (org.jkiss.code.Nullable)6 Log (org.jkiss.dbeaver.Log)6 org.jkiss.dbeaver.model (org.jkiss.dbeaver.model)6 CommonUtils (org.jkiss.utils.CommonUtils)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 java.util (java.util)4 ArrayList (java.util.ArrayList)4 PatternSyntaxException (java.util.regex.PatternSyntaxException)4 Table (net.sf.jsqlparser.schema.Table)4 Statement (net.sf.jsqlparser.statement.Statement)4 TablesNamesFinder (net.sf.jsqlparser.util.TablesNamesFinder)4 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)4 DBDLabelValuePair (org.jkiss.dbeaver.model.data.DBDLabelValuePair)4 DBCExecutionPurpose (org.jkiss.dbeaver.model.exec.DBCExecutionPurpose)4