Beispiel #1
0
 public static Combo createEncodingCombo(Composite parent, String curCharset) {
   if (curCharset == null) {
     curCharset = GeneralUtils.getDefaultFileEncoding();
   }
   Combo encodingCombo = new Combo(parent, SWT.DROP_DOWN);
   encodingCombo.setVisibleItemCount(30);
   SortedMap<String, Charset> charsetMap = Charset.availableCharsets();
   int index = 0;
   int defIndex = -1;
   for (String csName : charsetMap.keySet()) {
     Charset charset = charsetMap.get(csName);
     encodingCombo.add(charset.displayName());
     if (charset.displayName().equalsIgnoreCase(curCharset)) {
       defIndex = index;
     }
     if (defIndex < 0) {
       for (String alias : charset.aliases()) {
         if (alias.equalsIgnoreCase(curCharset)) {
           defIndex = index;
         }
       }
     }
     index++;
   }
   if (defIndex >= 0) {
     encodingCombo.select(defIndex);
   } else {
     log.warn("Charset '" + curCharset + "' is not recognized"); // $NON-NLS-1$ //$NON-NLS-2$
   }
   return encodingCombo;
 }
Beispiel #2
0
 /**
  * Eclipse hack. Disables/enabled all key bindings in specified site's part. Works only if host
  * editor is extender of AbstractTextEditor Uses reflection because setActionActivation is private
  * method TODO: find better way to disable key bindings or prioritize event handling to widgets
  *
  * @param partSite workbench part site
  * @param enable enable or disable
  */
 @Deprecated
 public static void enableHostEditorKeyBindings(IWorkbenchPartSite partSite, boolean enable) {
   IWorkbenchPart part = partSite.getPart();
   if (part instanceof AbstractTextEditor) {
     AbstractTextEditor hostEditor = (AbstractTextEditor) part;
     if (hostEditor instanceof BaseTextEditor) {
       StyledText textWidget = ((BaseTextEditor) hostEditor).getTextViewer().getTextWidget();
       if (textWidget == null || textWidget.isDisposed()) {
         return;
       }
     }
     try {
       Method activatorMethod =
           AbstractTextEditor.class.getDeclaredMethod("setActionActivation", Boolean.TYPE);
       activatorMethod.setAccessible(true);
       activatorMethod.invoke(hostEditor, enable);
     } catch (Throwable e) {
       if (e instanceof InvocationTargetException) {
         e = ((InvocationTargetException) e).getTargetException();
       }
       log.warn("Can't disable text editor action activations", e);
     }
     // hostEditor.getEditorSite().getActionBarContributor().setActiveEditor(hostEditor);
   }
 }
 @Override
 public void contributeProperties(
     @NotNull DBPPropertyManager propertySource, @NotNull IValueController controller) {
   super.contributeProperties(propertySource, controller);
   try {
     Object value = controller.getValue();
     if (value instanceof DBDContent) {
       propertySource.addProperty(
           PROP_CATEGORY_CONTENT,
           "content_type", //$NON-NLS-1$
           CoreMessages.model_jdbc_content_type,
           ((DBDContent) value).getContentType());
       final long contentLength = ((DBDContent) value).getContentLength();
       if (contentLength >= 0) {
         propertySource.addProperty(
             PROP_CATEGORY_CONTENT,
             "content_length", //$NON-NLS-1$
             CoreMessages.model_jdbc_content_length,
             contentLength);
       }
     }
   } catch (Exception e) {
     log.warn("Can't extract CONTENT value information", e); // $NON-NLS-1$
   }
 }
 @Override
 public void fetchRow(DBCSession session, DBCResultSet resultSet) throws DBCException {
   Object[] row = new Object[columnsCount];
   for (int i = 0; i < columnsCount; i++) {
     try {
       row[i] =
           metaColumns[i]
               .getValueHandler()
               .fetchValueObject(
                   session,
                   resultSet,
                   metaColumns[i].getAttribute(),
                   metaColumns[i].getOrdinalPosition());
     } catch (DBCException e) {
       // Do not reports the same error multiple times
       // There are a lot of error could occur during result set fetch
       // We report certain error only once
       List<DBCException> errorList = errors.get(metaColumns[i].getMetaAttribute());
       if (errorList == null) {
         errorList = new ArrayList<>();
         errors.put(metaColumns[i].getMetaAttribute(), errorList);
       }
       if (!errorList.contains(e)) {
         log.warn("Can't read column '" + metaColumns[i].getName() + "' value", e);
         errorList.add(e);
       }
     }
   }
   rows.add(row);
 }
  @Override
  protected ElementInfo createElementInfo(Object element) throws CoreException {
    if (element instanceof IEditorInput) {

      IEditorInput input = (IEditorInput) element;
      IStorage storage = EditorUtils.getStorageFromInput(input);
      if (storage instanceof IFile) {
        IFile file = (IFile) storage;
        try {
          refreshFile(file);
        } catch (CoreException x) {
          log.warn("Can't refresh file", x);
        }

        IDocument d;
        IStatus s = null;

        try {
          d = createDocument(element);
        } catch (CoreException x) {
          log.warn("Can't create document", x);
          s = x.getStatus();
          d = createEmptyDocument();
        }

        // Set the initial line delimiter
        String initialLineDelimiter = GeneralUtils.getDefaultLineSeparator();
        if (initialLineDelimiter != null) {
          ((IDocumentExtension4) d).setInitialLineDelimiter(initialLineDelimiter);
        }

        IAnnotationModel m = createAnnotationModel(element);
        FileSynchronizer f = new FileSynchronizer(input);
        f.install();

        FileInfo info = new FileInfo(d, m, f);
        info.modificationStamp = computeModificationStamp(file);
        info.fStatus = s;

        return info;
      }
    }

    return super.createElementInfo(element);
  }
 private boolean matchesContentType(IResultSetContext context) {
   String documentType = context.getDocumentContentType();
   if (contentTypes.isEmpty() || CommonUtils.isEmpty(documentType)) {
     return false;
   }
   for (MimeType mimeType : contentTypes) {
     try {
       if (mimeType.match(documentType)) {
         return true;
       }
     } catch (MimeTypeParseException e) {
       log.warn("Bad document content type: " + documentType, e);
     }
   }
   return false;
 }
Beispiel #7
0
 public static CellEditor createCellEditor(
     Composite parent, Object object, DBPPropertyDescriptor property) {
   // List
   if (property instanceof IPropertyValueListProvider) {
     final IPropertyValueListProvider listProvider = (IPropertyValueListProvider) property;
     final Object[] items = listProvider.getPossibleValues(object);
     if (!ArrayUtils.isEmpty(items)) {
       final String[] strings = new String[items.length];
       for (int i = 0, itemsLength = items.length; i < itemsLength; i++) {
         strings[i] =
             items[i] instanceof DBPNamedObject
                 ? ((DBPNamedObject) items[i]).getName()
                 : CommonUtils.toString(items[i]);
       }
       final CustomComboBoxCellEditor editor =
           new CustomComboBoxCellEditor(
               parent,
               strings,
               SWT.DROP_DOWN | (listProvider.allowCustomValue() ? SWT.NONE : SWT.READ_ONLY));
       return editor;
     }
   }
   Class<?> propertyType = property.getDataType();
   if (propertyType == null || CharSequence.class.isAssignableFrom(propertyType)) {
     return new CustomTextCellEditor(parent);
   } else if (BeanUtils.isNumericType(propertyType)) {
     return new CustomNumberCellEditor(parent, propertyType);
   } else if (BeanUtils.isBooleanType(propertyType)) {
     return new CustomCheckboxCellEditor(parent);
     // return new CheckboxCellEditor(parent);
   } else if (propertyType.isEnum()) {
     final Object[] enumConstants = propertyType.getEnumConstants();
     final String[] strings = new String[enumConstants.length];
     for (int i = 0, itemsLength = enumConstants.length; i < itemsLength; i++) {
       strings[i] = ((Enum) enumConstants[i]).name();
     }
     return new CustomComboBoxCellEditor(parent, strings, SWT.DROP_DOWN | SWT.READ_ONLY);
   } else {
     log.warn("Unsupported property type: " + propertyType.getName());
     return null;
   }
 }
  protected ResultSetPresentationDescriptor(IConfigurationElement config) {
    super(config);

    this.id = config.getAttribute(RegistryConstants.ATTR_ID);
    this.label = config.getAttribute(RegistryConstants.ATTR_LABEL);
    this.description = config.getAttribute(RegistryConstants.ATTR_DESCRIPTION);
    this.presentationType = new ObjectType(config.getAttribute(RegistryConstants.ATTR_CLASS));
    this.icon = iconToImage(config.getAttribute(RegistryConstants.ATTR_ICON));
    this.order = CommonUtils.toInt(config.getAttribute(RegistryConstants.ATTR_ORDER));

    for (IConfigurationElement typeCfg : config.getChildren(CONTENT_TYPE)) {
      String type = typeCfg.getAttribute(RegistryConstants.ATTR_TYPE);
      try {
        MimeType contentType = new MimeType(type);
        contentTypes.add(contentType);
      } catch (MimeTypeParseException e) {
        log.warn("Invalid content type: " + type, e);
      }
    }
  }
  /**
   * This method returns a list of completion proposals as ICompletionProposal objects. The
   * proposals are based on the word at the offset in the document where the cursor is positioned.
   * In this implementation, we find the word at the document offset and compare it to our list of
   * SQL reserved words. The list is a subset, of those words that match what the user has entered.
   * For example, the text or proposes the SQL keywords OR and ORDER. The list is returned as an
   * array of completion proposals.
   *
   * @see
   *     org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(ITextViewer,
   *     int)
   */
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    this.documentOffset = documentOffset;
    this.activeQuery = null;

    this.wordDetector =
        new SQLWordPartDetector(viewer.getDocument(), editor.getSyntaxManager(), documentOffset);
    final String wordPart = wordDetector.getWordPart();

    if (lookupTemplates) {
      return makeTemplateProposals(viewer, documentOffset, wordPart);
    }

    final List<SQLCompletionProposal> proposals = new ArrayList<>();
    QueryType queryType = null;
    {
      final String prevKeyWord = wordDetector.getPrevKeyWord();
      if (!CommonUtils.isEmpty(prevKeyWord)) {
        if (editor.getSyntaxManager().getDialect().isEntityQueryWord(prevKeyWord)) {
          queryType = QueryType.TABLE;
        } else if (editor.getSyntaxManager().getDialect().isAttributeQueryWord(prevKeyWord)) {
          queryType = QueryType.COLUMN;
        }
      }
    }
    if (queryType != null) {
      if (editor.getDataSource() != null) {
        try {
          final QueryType qt = queryType;
          DBeaverUI.runInProgressService(
              new DBRRunnableWithProgress() {
                @Override
                public void run(DBRProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  monitor.beginTask("Seeking for completion proposals", 1);
                  try {
                    monitor.subTask("Make structure proposals");
                    makeStructureProposals(monitor, proposals, wordPart, qt);
                  } finally {
                    monitor.done();
                  }
                }
              });
        } catch (InvocationTargetException e) {
          log.warn("Error while seeking for structure proposals", e.getTargetException());
        } catch (InterruptedException e) {
          // interrupted - do nothing
        }
      }
    }

    if (proposals.isEmpty() || !wordPart.isEmpty()) {
      // Keyword assist
      List<String> matchedKeywords =
          editor.getSyntaxManager().getDialect().getMatchedKeywords(wordPart);
      for (String keyWord : matchedKeywords) {
        DBPKeywordType keywordType = editor.getSyntaxManager().getDialect().getKeywordType(keyWord);
        if (keywordType != null) {
          proposals.add(
              createCompletionProposal(
                  keyWord, keyWord, keyWord + " (" + keywordType.name() + ")", null, false, null));
        }
      }
    }

    // Remove duplications
    for (int i = 0; i < proposals.size(); i++) {
      SQLCompletionProposal proposal = proposals.get(i);
      for (int j = i + 1; j < proposals.size(); ) {
        SQLCompletionProposal proposal2 = proposals.get(j);
        if (proposal.getDisplayString().equals(proposal2.getDisplayString())) {
          proposals.remove(j);
        } else {
          j++;
        }
      }
    }
    DBSObject selectedObject = getSelectedObject(editor.getDataSource());
    boolean hideDups =
        getPreferences().getBoolean(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS)
            && selectedObject != null;
    if (hideDups) {
      for (int i = 0; i < proposals.size(); i++) {
        SQLCompletionProposal proposal = proposals.get(i);
        for (int j = 0; j < proposals.size(); ) {
          SQLCompletionProposal proposal2 = proposals.get(j);
          if (i != j
              && proposal.hasStructObject()
              && proposal2.hasStructObject()
              && CommonUtils.equalObjects(
                  proposal.getObject().getName(), proposal2.getObject().getName())
              && proposal.getObjectContainer() == selectedObject) {
            proposals.remove(j);
          } else {
            j++;
          }
        }
      }
    }

    if (hideDups) {
      // Remove duplicates from non-active schema

      if (selectedObject instanceof DBSObjectContainer) {
        // List<ICompletionProposal>
      }
    }
    return proposals.toArray(new ICompletionProposal[proposals.size()]);
  }
Beispiel #10
0
  private boolean executeSingleQuery(
      @NotNull DBCSession session, @NotNull SQLQuery sqlQuery, boolean fireEvents) {
    lastError = null;

    final String originalQueryText = sqlQuery.getQuery();
    DBCExecutionContext executionContext = getExecutionContext();
    SQLQueryResult curResult = new SQLQueryResult(sqlQuery);
    if (rsOffset > 0) {
      curResult.setRowOffset(rsOffset);
    }
    SQLQuery originalQuery = sqlQuery;
    long startTime = System.currentTimeMillis();

    if (fireEvents && listener != null) {
      // Notify query start
      listener.onStartQuery(sqlQuery);
    }

    try {
      // Prepare statement
      closeStatement();

      // Check and invalidate connection
      DBPDataSource dataSource = executionContext.getDataSource();
      if (!connectionInvalidated
          && dataSource
              .getContainer()
              .getPreferenceStore()
              .getBoolean(DBeaverPreferences.STATEMENT_INVALIDATE_BEFORE_EXECUTE)) {
        executionContext.invalidateContext(session.getProgressMonitor());
        connectionInvalidated = true;
      }

      try {
        // Modify query (filters + parameters)
        if (dataFilter != null && dataFilter.hasFilters() && dataSource instanceof SQLDataSource) {
          String filteredQueryText =
              ((SQLDataSource) dataSource)
                  .getSQLDialect()
                  .addFiltersToQuery(dataSource, originalQueryText, dataFilter);
          sqlQuery = new SQLQuery(filteredQueryText, sqlQuery.getOffset(), sqlQuery.getLength());
        }
      } catch (DBException e) {
        throw new DBCException("Can't apply query filter", e);
      }

      Boolean hasParameters = prepareStatementParameters(sqlQuery);
      if (hasParameters == null) {
        return false;
      }

      statistics.setQueryText(originalQueryText);

      startTime = System.currentTimeMillis();
      DBCExecutionSource source =
          new AbstractExecutionSource(
              dataContainer, executionContext, partSite.getPart(), sqlQuery);
      curStatement =
          DBUtils.prepareStatement(
              source,
              session,
              hasParameters ? DBCStatementType.QUERY : DBCStatementType.SCRIPT,
              sqlQuery,
              rsOffset,
              rsMaxRows);

      if (hasParameters) {
        bindStatementParameters(session, sqlQuery);
      }

      // Execute statement
      try {
        boolean hasResultSet = curStatement.executeStatement();
        curResult.setHasResultSet(hasResultSet);
        statistics.addExecuteTime(System.currentTimeMillis() - startTime);
        statistics.addStatementsCount();

        long updateCount = -1;
        while (hasResultSet || resultSetNumber == 0 || updateCount >= 0) {
          // Fetch data only if we have to fetch all results or if it is rs requested
          if (fetchResultSetNumber < 0 || fetchResultSetNumber == resultSetNumber) {
            if (hasResultSet && fetchResultSets) {
              DBDDataReceiver dataReceiver =
                  resultsConsumer.getDataReceiver(sqlQuery, resultSetNumber);
              if (dataReceiver != null) {
                hasResultSet =
                    fetchQueryData(
                        session, curStatement.openResultSet(), curResult, dataReceiver, true);
              }
            }
          }
          if (!hasResultSet) {
            try {
              updateCount = curStatement.getUpdateRowCount();
              if (updateCount >= 0) {
                curResult.setUpdateCount(updateCount);
                statistics.addRowsUpdated(updateCount);
              }
            } catch (DBCException e) {
              // In some cases we can't read update count
              // This is bad but we can live with it
              // Just print a warning
              log.warn("Can't obtain update count", e);
            }
          }
          if (hasResultSet && fetchResultSets) {
            resultSetNumber++;
            fetchResultSetNumber = resultSetNumber;
          }
          if (!hasResultSet && updateCount < 0) {
            // Nothing else to fetch
            break;
          }

          if (dataSource.getInfo().supportsMultipleResults()) {
            hasResultSet = curStatement.nextResults();
            updateCount = hasResultSet ? -1 : 0;
          } else {
            break;
          }
        }

        try {
          curResult.setWarnings(curStatement.getStatementWarnings());
        } catch (Throwable e) {
          log.warn("Can't read execution warnings", e);
        }
      } finally {
        // monitor.subTask("Close query");
        if (!keepStatementOpen()) {
          closeStatement();
        }

        // Release parameters
        releaseStatementParameters(sqlQuery);
      }
    } catch (Throwable ex) {
      if (!(ex instanceof DBException)) {
        log.error("Unexpected error while processing SQL", ex);
      }
      curResult.setError(ex);
      lastError = ex;
    } finally {
      curResult.setQueryTime(System.currentTimeMillis() - startTime);

      if (fireEvents && listener != null) {
        // Notify query end
        listener.onEndQuery(curResult);
      }
    }

    if (curResult.getError() != null && errorHandling != SQLScriptErrorHandling.IGNORE) {
      return false;
    }
    // Success
    lastGoodQuery = originalQuery;
    return true;
  }