Search in sources :

Example 1 with SQLWordPartDetector

use of org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector 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 2 with SQLWordPartDetector

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

the class SQLContextInformer method searchInformation.

public void searchInformation(IRegion region) {
    ITextViewer textViewer = editor.getTextViewer();
    final DBCExecutionContext executionContext = editor.getExecutionContext();
    if (region == null || textViewer == null || executionContext == null) {
        return;
    }
    IDocument document = textViewer.getDocument();
    if (document == null) {
        return;
    }
    SQLWordPartDetector wordDetector = new SQLWordPartDetector(document, syntaxManager, region.getOffset());
    wordRegion = wordDetector.detectIdentifier(document, region);
    if (wordRegion.word.length() == 0) {
        return;
    }
    String fullName = wordRegion.identifier;
    String tableName = wordRegion.word;
    boolean caseSensitive = false;
    if (wordDetector.isQuoted(tableName)) {
        tableName = DBUtils.getUnQuotedIdentifier(tableName, syntaxManager.getIdentifierQuoteStrings());
        caseSensitive = true;
    }
    String[] containerNames = null;
    if (!CommonUtils.equalObjects(fullName, tableName)) {
        int divPos = fullName.indexOf(syntaxManager.getStructSeparator());
        if (divPos != -1) {
            String[] parts = wordDetector.splitIdentifier(fullName);
            tableName = parts[parts.length - 1];
            containerNames = ArrayUtils.remove(String.class, parts, parts.length - 1);
            for (int i = 0; i < containerNames.length; i++) {
                if (wordDetector.isQuoted(containerNames[i])) {
                    containerNames[i] = DBUtils.getUnQuotedIdentifier(containerNames[i], syntaxManager.getIdentifierQuoteStrings());
                }
                containerNames[i] = DBObjectNameCaseTransformer.transformName(editor.getDataSource(), containerNames[i]);
            }
            if (wordDetector.isQuoted(tableName)) {
                tableName = DBUtils.getUnQuotedIdentifier(tableName, syntaxManager.getIdentifierQuoteStrings());
            }
        } else {
            // Full name could be quoted
            if (wordDetector.isQuoted(fullName)) {
                String unquotedName = DBUtils.getUnQuotedIdentifier(tableName, syntaxManager.getIdentifierQuoteStrings());
                if (unquotedName.equals(tableName)) {
                    caseSensitive = true;
                }
            }
        }
    }
    final SQLDialect dialect = syntaxManager.getDialect();
    keywordType = dialect.getKeywordType(fullName);
    if (keywordType == DBPKeywordType.KEYWORD && region.getLength() > 1) {
        // It is a keyword = let's use whole selection
        try {
            fullName = document.get(region.getOffset(), region.getLength());
        } catch (BadLocationException e) {
            log.warn(e);
        }
    }
    keywords = new String[] { fullName };
    if (keywordType == DBPKeywordType.KEYWORD || keywordType == DBPKeywordType.FUNCTION) {
        // Skip keywords
        return;
    }
    final Map<String, ObjectLookupCache> contextCache = getLinksCache();
    if (contextCache == null) {
        return;
    }
    ObjectLookupCache tlc = contextCache.get(fullName);
    if (tlc == null) {
        // Start new word finder job
        tlc = new ObjectLookupCache();
        contextCache.put(fullName, tlc);
        DBSStructureAssistant structureAssistant = DBUtils.getAdapter(DBSStructureAssistant.class, editor.getDataSource());
        TablesFinderJob job = new TablesFinderJob(executionContext, structureAssistant, containerNames, tableName, caseSensitive, tlc);
        job.schedule();
    }
    if (tlc.loading) {
        // Wait for 1000ms maximum
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                // interrupted - just go further
                break;
            }
            if (!tlc.loading) {
                break;
            }
            Display.getCurrent().readAndDispatch();
        }
    }
    if (!tlc.loading) {
        synchronized (this) {
            objectReferences = tlc.references;
        }
    }
}
Also used : SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector) DBCExecutionContext(org.jkiss.dbeaver.model.exec.DBCExecutionContext) ITextViewer(org.eclipse.jface.text.ITextViewer) SQLDialect(org.jkiss.dbeaver.model.sql.SQLDialect) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 3 with SQLWordPartDetector

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

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 4 with SQLWordPartDetector

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

the class SQLCompletionAnalyzer method makeJoinColumnProposals.

private boolean makeJoinColumnProposals(DBSObjectContainer sc, DBSEntity leftTable) {
    SQLWordPartDetector joinTableDetector = new SQLWordPartDetector(request.getDocument(), request.getContext().getSyntaxManager(), request.getWordDetector().getStartOffset(), 2);
    List<String> prevWords = joinTableDetector.getPrevWords();
    if (!CommonUtils.isEmpty(prevWords)) {
        DBPDataSource dataSource = request.getContext().getDataSource();
        SQLDialect sqlDialect = dataSource.getSQLDialect();
        String rightTableName = prevWords.get(0);
        String[] allNames = SQLUtils.splitFullIdentifier(rightTableName, sqlDialect.getCatalogSeparator(), sqlDialect.getIdentifierQuoteStrings(), false);
        DBSObject rightTable = SQLSearchUtils.findObjectByFQN(monitor, sc, request.getContext().getExecutionContext(), Arrays.asList(allNames), !request.isSimpleMode(), request.getWordDetector());
        if (rightTable instanceof DBSEntity) {
            try {
                String joinCriteria = SQLUtils.generateTableJoin(monitor, leftTable, DBUtils.getQuotedIdentifier(leftTable), (DBSEntity) rightTable, DBUtils.getQuotedIdentifier(rightTable));
                proposals.add(createCompletionProposal(request, joinCriteria, joinCriteria, DBPKeywordType.OTHER, "Join condition"));
                return true;
            } catch (DBException e) {
                log.error("Error generating join condition", e);
            }
        }
    }
    return false;
}
Also used : DBException(org.jkiss.dbeaver.DBException) SQLWordPartDetector(org.jkiss.dbeaver.model.sql.parser.SQLWordPartDetector)

Example 5 with SQLWordPartDetector

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

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)

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