コード例 #1
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
 private void releaseStatementParameters(SQLQuery sqlStatement) {
   if (!CommonUtils.isEmpty(sqlStatement.getParameters())) {
     for (SQLQueryParameter param : sqlStatement.getParameters()) {
       if (param.isResolved()) {
         param.getValueHandler().releaseValueObject(param.getValue());
       }
     }
   }
 }
コード例 #2
0
  /**
   * This method is incomplete in that it does not implement logic to produce some context help
   * relevant to SQL. It just hard codes two strings to demonstrate the action
   *
   * @see
   *     org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(ITextViewer,
   *     int)
   */
  @Nullable
  @Override
  public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
    SQLQuery statementInfo = editor.extractQueryAtPos(documentOffset);
    if (statementInfo == null || CommonUtils.isEmpty(statementInfo.getQuery())) {
      return null;
    }

    IContextInformation[] result = new IContextInformation[1];
    result[0] = new ContextInformation(statementInfo.getQuery(), statementInfo.getQuery());
    return result;
  }
コード例 #3
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
 private void showExecutionResult(DBCSession session) throws DBCException {
   if (statistics.getStatementsCount() > 1 || resultSetNumber == 0) {
     SQLQuery query = new SQLQuery("", -1, -1);
     if (queries.size() == 1) {
       query.setQuery(queries.get(0).getQuery());
     }
     query.setData(STATS_RESULTS); // It will set tab name to "Stats"
     DBDDataReceiver dataReceiver = resultsConsumer.getDataReceiver(query, resultSetNumber);
     if (dataReceiver != null) {
       fetchExecutionResult(session, dataReceiver, query);
     }
   }
 }
コード例 #4
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
 private void fetchExecutionResult(
     @NotNull DBCSession session, @NotNull DBDDataReceiver dataReceiver, @NotNull SQLQuery query)
     throws DBCException {
   // Fetch fake result set
   // DBCStatement statsStatement;
   StatResultSet fakeResultSet = new StatResultSet(session, curStatement);
   SQLQueryResult resultInfo = new SQLQueryResult(query);
   if (statistics.getStatementsCount() > 1) {
     // Multiple statements - show script statistics
     fakeResultSet.addColumn("Queries", DBPDataKind.NUMERIC);
     fakeResultSet.addColumn("Updated Rows", DBPDataKind.NUMERIC);
     fakeResultSet.addColumn("Execute time", DBPDataKind.NUMERIC);
     fakeResultSet.addColumn("Fetch time", DBPDataKind.NUMERIC);
     fakeResultSet.addColumn("Total time", DBPDataKind.NUMERIC);
     fakeResultSet.addRow(
         statistics.getStatementsCount(),
         statistics.getRowsUpdated(),
         statistics.getExecuteTime(),
         statistics.getFetchTime(),
         statistics.getTotalTime());
     resultInfo.setResultSetName("Statistics");
   } else {
     // Single statement
     long updateCount = statistics.getRowsUpdated();
     if (updateCount >= 0) {
       fakeResultSet.addColumn("Query", DBPDataKind.STRING);
       fakeResultSet.addColumn("Updated Rows", DBPDataKind.NUMERIC);
       fakeResultSet.addRow(query.getQuery(), updateCount);
     } else {
       fakeResultSet.addColumn("Result", DBPDataKind.NUMERIC);
     }
     resultInfo.setResultSetName("Result");
   }
   fetchQueryData(session, fakeResultSet, resultInfo, dataReceiver, false);
 }
コード例 #5
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
 private Boolean prepareStatementParameters(SQLQuery sqlStatement) {
   // Bind parameters
   if (!CommonUtils.isEmpty(sqlStatement.getParameters())) {
     List<SQLQueryParameter> unresolvedParams = new ArrayList<>();
     for (SQLQueryParameter param : sqlStatement.getParameters()) {
       if (!param.isResolved()) {
         unresolvedParams.add(param);
       }
     }
     if (!CommonUtils.isEmpty(unresolvedParams)) {
       // Resolve parameters
       if (!fillStatementParameters(unresolvedParams)) {
         return null;
       }
     }
     // Set values for all parameters
     return true;
   }
   return false;
 }
コード例 #6
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
 public void extractData(DBCSession session) throws DBCException {
   statistics = new DBCStatistics();
   if (queries.size() != 1) {
     throw new DBCException("Invalid state of SQL Query job");
   }
   resultSetNumber = 0;
   SQLQuery query = queries.get(0);
   session.getProgressMonitor().beginTask(query.getQuery(), 1);
   try {
     boolean result = executeSingleQuery(session, query, true);
     if (!result && lastError != null) {
       if (lastError instanceof DBCException) {
         throw (DBCException) lastError;
       } else {
         throw new DBCException(lastError, getExecutionContext().getDataSource());
       }
     } else if (result) {
       showExecutionResult(session);
     }
   } finally {
     session.getProgressMonitor().done();
   }
 }
コード例 #7
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
 private void bindStatementParameters(DBCSession session, SQLQuery sqlStatement)
     throws DBCException {
   // Bind them
   for (SQLQueryParameter param : sqlStatement.getParameters()) {
     if (param.isResolved()) {
       // convert value to native form
       Object realValue =
           param.getValueHandler().getValueFromObject(session, param, param.getValue(), false);
       // bind
       param
           .getValueHandler()
           .bindValueObject(session, curStatement, param, param.getOrdinalPosition(), realValue);
     }
   }
 }
コード例 #8
0
ファイル: SQLQueryJob.java プロジェクト: ralic/dbeaver
  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;
  }