@Override
  public void execute() throws TranslatorException {

    LogManager.logTrace(
        LogConstants.CTX_CONNECTOR,
        "ObjectExecution command:",
        query.toString(),
        "using connection:",
        connection.getClass().getName()); // $NON-NLS-1$ //$NON-NLS-2$

    String nameInSource =
        getNameInSource(((NamedTable) query.getFrom().get(0)).getMetadataObject());

    List<Object> results = factory.search(query, nameInSource, connection, executionContext);

    if (results != null && results.size() > 0) {
      LogManager.logDetail(
          LogConstants.CTX_CONNECTOR,
          "ObjectExecution number of returned objects is :",
          results.size()); // $NON-NLS-1$

    } else {
      LogManager.logDetail(
          LogConstants.CTX_CONNECTOR,
          "ObjectExecution number of objects returned is : 0"); //$NON-NLS-1$

      results = Collections.emptyList();
    }

    this.resultsIt = results.iterator();
  }
Exemple #2
0
  public static boolean visit(
      In obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder)
      throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IN criteria."); // $NON-NLS-1$

    Expression lhs = obj.getLeftExpression();

    Column mdIDElement = ((ColumnReference) lhs).getMetadataObject();

    List<Expression> rhsList = obj.getRightExpressions();
    boolean createdQuery = false;
    for (Expression expr : rhsList) {

      if (expr instanceof Literal) {
        Literal literal = (Literal) expr;

        // add these as OR queries
        createEqualsQuery(
            mdIDElement,
            escapeReservedChars(literal.getValue()),
            false,
            false,
            junction,
            queryBuilder);
        createdQuery = true;
      } else {
        String msg =
            ObjectPlugin.Util.getString(
                "LuceneSearch.Unsupported_expression", //$NON-NLS-1$
                new Object[] {expr, "IN"}); // $NON-NLS-1$
        throw new TranslatorException(msg);
      }
    }
    return createdQuery;
  }
Exemple #3
0
  public static boolean visit(
      Like obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder)
      throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing LIKE criteria."); // $NON-NLS-1$

    Expression lhs = obj.getLeftExpression();
    Expression rhs = obj.getRightExpression();

    Column c = null;
    Expression literalExp = null;
    if (lhs instanceof ColumnReference) {
      c = ((ColumnReference) lhs).getMetadataObject();
      literalExp = rhs;
    } else {
      c = ((ColumnReference) rhs).getMetadataObject();
      literalExp = lhs;
    }

    String value = null;
    if (literalExp instanceof Literal) {

      value = (String) escapeReservedChars(((Literal) literalExp).getValue());
      createLikeQuery(
          c, value.replaceAll("%", ""), junction, queryBuilder); // "*" //$NON-NLS-1$ //$NON-NLS-2$
    } else {
      final String msg =
          ObjectPlugin.Util.getString(
              "LuceneSearch.Unsupported_expression", //$NON-NLS-1$
              new Object[] {literalExp.toString(), "LIKE"}); // $NON-NLS-1$
      throw new TranslatorException(msg);
    }

    return true;
  }
Exemple #4
0
  public static List<Object> performSearch(
      Select command, Class<?> type, String cacheName, CacheContainerWrapper cache)
      throws TranslatorException {

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Using Lucene Searching."); // $NON-NLS-1$

    // Map<?, ?> cache,
    SearchManager searchManager = Search.getSearchManager((Cache<?, ?>) cache.getCache(cacheName));

    QueryBuilder queryBuilder = searchManager.buildQueryBuilderForClass(type).get();

    BooleanJunction<BooleanJunction> junction = queryBuilder.bool();
    boolean createdQueries = buildQueryFromWhereClause(command.getWhere(), junction, queryBuilder);

    Query query = null;
    if (createdQueries) {
      query = junction.createQuery();
    } else {
      query = queryBuilder.all().createQuery();
    }

    CacheQuery cacheQuery = searchManager.getQuery(query, type); // rootNodeType

    List<Object> results = cacheQuery.list();
    if (results == null || results.isEmpty()) {
      return Collections.emptyList();
    }

    return results;
  }
Exemple #5
0
 public void reset() {
   super.reset();
   if (evaluator != null) {
     evaluator.reset();
   }
   evaluatedParams = false;
   if (parentContext != null) {
     super.getContext().setVariableContext(parentContext);
   }
   createVariableContext();
   CommandContext cc = super.getContext();
   if (cc != null) {
     // create fresh local state
     setContext(cc.clone());
   }
   done = false;
   currentState = null;
   finalTupleSource = null;
   beginBatch = 1;
   batchRows = null;
   lastBatch = false;
   // reset program stack
   programs.clear();
   LogManager.logTrace(
       org.teiid.logging.LogConstants.CTX_DQP, "ProcedurePlan reset"); // $NON-NLS-1$
 }
 /** Set the standard request controls */
 private void setRequestControls(byte[] cookie) throws TranslatorException {
   List<Control> ctrl = new ArrayList<Control>();
   SortKey[] keys = searchDetails.getSortKeys();
   try {
     if (keys != null) {
       ctrl.add(new SortControl(keys, Control.NONCRITICAL));
     }
     if (this.executionFactory.usePagination()) {
       ctrl.add(
           new PagedResultsControl(
               this.executionContext.getBatchSize(), cookie, Control.CRITICAL));
     }
     if (!ctrl.isEmpty()) {
       this.ldapCtx.setRequestControls(ctrl.toArray(new Control[ctrl.size()]));
       LogManager.logTrace(
           LogConstants.CTX_CONNECTOR,
           "Sort/pagination controls were created successfully."); //$NON-NLS-1$
     }
   } catch (NamingException ne) {
     final String msg =
         LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError")
             + //$NON-NLS-1$
             " : "
             + ne.getExplanation(); // $NON-NLS-1$
     throw new TranslatorException(ne, msg);
   } catch (IOException e) {
     throw new TranslatorException(e);
   }
 }
Exemple #7
0
 public ResultsFuture<?> ping() throws InvalidSessionException, TeiidComponentException {
   // ping is double used to alert the aliveness of the client, as well as check the server
   // instance is
   // alive by socket server instance, so that they can be cached.
   String id = DQPWorkContext.getWorkContext().getSessionId();
   if (id != null) {
     this.service.pingServer(id);
   }
   LogManager.logTrace(LogConstants.CTX_SECURITY, "Ping", id); // $NON-NLS-1$
   return ResultsFuture.NULL_FUTURE;
 }
  public void resolveBlock(
      CreateProcedureCommand command,
      Block block,
      GroupContext originalExternalGroups,
      TempMetadataAdapter original)
      throws QueryResolverException, QueryMetadataException, TeiidComponentException {
    LogManager.logTrace(
        org.teiid.logging.LogConstants.CTX_QUERY_RESOLVER,
        new Object[] {"Resolving block", block}); // $NON-NLS-1$

    // create a new variable and metadata context for this block so that discovered metadata is not
    // visible else where
    TempMetadataStore store = original.getMetadataStore().clone();
    TempMetadataAdapter metadata = new TempMetadataAdapter(original.getMetadata(), store);
    GroupContext externalGroups = new GroupContext(originalExternalGroups, null);

    // create a new variables group for this block
    GroupSymbol variables =
        ProcedureContainerResolver.addScalarGroup(
            ProcedureReservedWords.VARIABLES, store, externalGroups, new LinkedList<Expression>());

    for (Statement statement : block.getStatements()) {
      resolveStatement(command, statement, externalGroups, variables, metadata);
    }

    if (block.getExceptionGroup() != null) {
      // create a new variable and metadata context for this block so that discovered metadata is
      // not visible else where
      store = original.getMetadataStore().clone();
      metadata = new TempMetadataAdapter(original.getMetadata(), store);
      externalGroups = new GroupContext(originalExternalGroups, null);

      // create a new variables group for this block
      variables =
          ProcedureContainerResolver.addScalarGroup(
              ProcedureReservedWords.VARIABLES,
              store,
              externalGroups,
              new LinkedList<Expression>());
      isValidGroup(metadata, block.getExceptionGroup());

      if (block.getExceptionStatements() != null) {
        ProcedureContainerResolver.addScalarGroup(
            block.getExceptionGroup(), store, externalGroups, exceptionGroup, false);
        for (Statement statement : block.getExceptionStatements()) {
          resolveStatement(command, statement, externalGroups, variables, metadata);
        }
      }
    }
  }
  @Override
  public void execute() throws TranslatorException {
    String sourceSQL = (String) this.arguments.get(0).getArgumentValue().getValue();
    List<Argument> parameters = this.arguments.subList(1, this.arguments.size());

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Source sql", sourceSQL); // $NON-NLS-1$
    int paramCount = parameters.size();

    try {
      Statement stmt;
      boolean hasResults = false;

      if (paramCount > 0) {
        PreparedStatement pstatement = getPreparedStatement(sourceSQL);
        for (int i = 0; i < paramCount; i++) {
          Argument arg = parameters.get(i);
          // TODO: if ParameterMetadata is supported we could use that type
          this.executionFactory.bindValue(
              pstatement,
              arg.getArgumentValue().getValue(),
              arg.getArgumentValue().getType(),
              i + 1);
        }
        stmt = pstatement;
        hasResults = pstatement.execute();
      } else {
        // TODO: when array support becomes more robust calling like "exec native('sql', ARRAY[])
        // could still be prepared
        stmt = getStatement();
        hasResults = stmt.execute(sourceSQL);
      }

      if (hasResults) {
        this.results = stmt.getResultSet();
        this.columnCount = this.results.getMetaData().getColumnCount();
      } else {
        this.updateCount = stmt.getUpdateCount();
      }
      addStatementWarnings();
    } catch (SQLException e) {
      throw new JDBCExecutionException(JDBCPlugin.Event.TEIID11008, e, sourceSQL);
    }
  }
Exemple #10
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static FilterConditionContext visit(
      In obj, QueryBuilder queryBuilder, FilterConditionBeginContext fcbc)
      throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IN criteria."); // $NON-NLS-1$

    Expression lhs = obj.getLeftExpression();

    List<Expression> rhsList = obj.getRightExpressions();

    List v = new ArrayList(rhsList.size());
    // = Arrays.asList(1
    boolean createdQuery = false;
    for (Expression expr : rhsList) {

      if (expr instanceof Literal) {
        Literal literal = (Literal) expr;

        Object value = escapeReservedChars(literal.getValue());
        v.add(value);
        createdQuery = true;
      } else {
        throw new TranslatorException(
            InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25052, new Object[] {expr, "IN"}));
      }
    }

    if (createdQuery) {
      Column col = ((ColumnReference) lhs).getMetadataObject();

      if (fcbc == null) {
        if (obj.isNegated()) {
          return queryBuilder.not().having(col.getSourceName()).in(v);
        }
        return queryBuilder.having(col.getSourceName()).in(v);
      }
      if (obj.isNegated()) {
        return fcbc.not().having(col.getSourceName()).in(v);
      }
      return fcbc.having(col.getSourceName()).in(v);
    }
    return null;
  }
  @Override
  public void execute() throws TranslatorException {
    this.sourceSQL = (String) this.arguments.get(0).getArgumentValue().getValue();
    List<Argument> parameters = this.arguments.subList(1, this.arguments.size());

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Source sql", sourceSQL); // $NON-NLS-1$
    int paramCount = parameters.size();
    if (paramCount > 0) {
      throw new TranslatorException(
          SimpleDBPlugin.Event.TEIID24003, SimpleDBPlugin.Util.gs(SimpleDBPlugin.Event.TEIID24003));
    }

    if (!sourceSQL.toLowerCase().startsWith("select")) { // $NON-NLS-1$
      throw new TranslatorException(
          SimpleDBPlugin.Event.TEIID24002, SimpleDBPlugin.Util.gs(SimpleDBPlugin.Event.TEIID24002));
    }

    executeDirect(getSQL(), null);
  }
Exemple #12
0
  @SuppressWarnings("rawtypes")
  public static FilterConditionContext visit(
      IsNull obj, QueryBuilder queryBuilder, FilterConditionBeginContext fcbc) {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IsNull criteria."); // $NON-NLS-1$

    Expression exp = obj.getExpression();
    Column c = ((ColumnReference) exp).getMetadataObject();

    if (fcbc == null) {
      if (obj.isNegated()) {
        return queryBuilder.not().having(c.getSourceName()).isNull();
      }
      return queryBuilder.having(c.getSourceName()).isNull();
    }
    if (obj.isNegated()) {
      return fcbc.not().having(c.getSourceName()).isNull();
    }

    return fcbc.having(c.getSourceName()).isNull();
  }
Exemple #13
0
  @SuppressWarnings("rawtypes")
  public static FilterConditionContext visit(
      Like obj, QueryBuilder queryBuilder, FilterConditionBeginContext fcbc)
      throws TranslatorException {
    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing LIKE criteria."); // $NON-NLS-1$

    Expression lhs = obj.getLeftExpression();
    Expression rhs = obj.getRightExpression();

    Column c = null;
    Expression literalExp = null;
    if (lhs instanceof ColumnReference) {
      c = ((ColumnReference) lhs).getMetadataObject();
      literalExp = rhs;
    } else {
      c = ((ColumnReference) rhs).getMetadataObject();
      literalExp = lhs;
    }

    String value = null;
    if (literalExp instanceof Literal) {

      value = (String) escapeReservedChars(((Literal) literalExp).getValue());

      if (fcbc == null) {
        if (obj.isNegated()) {
          return queryBuilder.not().having(c.getSourceName()).like(value);
        }
        return queryBuilder.having(c.getSourceName()).like(value);
      }
      if (obj.isNegated()) {
        return fcbc.not().having(c.getSourceName()).like(value);
      }

      return fcbc.having(c.getSourceName()).like(value);
    }
    throw new TranslatorException(
        InfinispanPlugin.Util.gs(
            InfinispanPlugin.Event.TEIID25052, new Object[] {literalExp.toString(), "LIKE"}));
  }
  @Override
  public void start() throws TranslatorException {
    super.start();

    registerFunctionModifier(
        SourceSystemFunctions.UCASE, new AliasModifier("UpperCase")); // $NON-NLS-1$
    registerFunctionModifier(
        SourceSystemFunctions.LCASE, new AliasModifier("LowerCase")); // $NON-NLS-1$

    registerFunctionModifier(JCR_ISCHILDNODE, new IdentifierFunctionModifier());
    registerFunctionModifier(JCR_ISDESCENDANTNODE, new IdentifierFunctionModifier());
    registerFunctionModifier(JCR_ISSAMENODE, new IdentifierFunctionModifier());
    registerFunctionModifier(JCR_REFERENCE, new IdentifierFunctionModifier());
    registerFunctionModifier(JCR_CONTAINS, new IdentifierFunctionModifier());

    addPushDownFunction(JCR, JCR_ISCHILDNODE, BOOLEAN, STRING, STRING);
    addPushDownFunction(JCR, JCR_ISDESCENDANTNODE, BOOLEAN, STRING, STRING);
    addPushDownFunction(JCR, JCR_ISSAMENODE, BOOLEAN, STRING, STRING);
    addPushDownFunction(JCR, JCR_CONTAINS, BOOLEAN, STRING, STRING);
    addPushDownFunction(JCR, JCR_REFERENCE, BOOLEAN, STRING);

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "ModeShape Translator Started"); // $NON-NLS-1$
  }
  @Override
  public void execute() throws TranslatorException {

    // Log our command
    LogManager.logTrace(
        LogConstants.CTX_CONNECTOR, "Loopback executing command: " + command); // $NON-NLS-1$

    if (this.config.isThrowError()) {
      throw new TranslatorException("Failing because Error=true"); // $NON-NLS-1$
    }

    this.rowsNeeded = this.config.getRowCount();

    if (command instanceof QueryExpression) {
      QueryExpression queryCommand = (QueryExpression) command;
      if (queryCommand.getLimit() != null) {
        this.rowsNeeded = queryCommand.getLimit().getRowLimit();
      }
    }

    // Prepare for execution
    determineOutputTypes();
    generateRow();
  }
Exemple #16
0
  @SuppressWarnings("rawtypes")
  public static FilterConditionContext visit(
      Comparison obj, QueryBuilder queryBuilder, FilterConditionBeginContext fcbc)
      throws TranslatorException {

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing Comparison criteria."); // $NON-NLS-1$
    Comparison.Operator op = obj.getOperator();

    Expression lhs = obj.getLeftExpression();
    Expression rhs = obj.getRightExpression();

    // joins between the objects in the same cache is not usable
    if ((lhs instanceof ColumnReference && rhs instanceof ColumnReference)
        || (lhs instanceof Literal && rhs instanceof Literal)) {
      return null;
    }

    Object value = null;
    Column mdIDElement = null;
    Literal literal = null;
    if (lhs instanceof ColumnReference) {

      mdIDElement = ((ColumnReference) lhs).getMetadataObject();
      literal = (Literal) rhs;
      value = literal.getValue();

    } else if (rhs instanceof ColumnReference) {
      mdIDElement = ((ColumnReference) rhs).getMetadataObject();
      literal = (Literal) lhs;
      value = literal.getValue();
    }

    if (value == null) {
      throw new TranslatorException(InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25051));
    }

    value = escapeReservedChars(value);
    switch (op) {
      case NE:
        if (fcbc == null) {
          return queryBuilder.not().having(mdIDElement.getSourceName()).eq(value);
        }
        return fcbc.not().having(mdIDElement.getSourceName()).eq(value);

      case EQ:
        if (fcbc == null) {
          return queryBuilder.having(mdIDElement.getSourceName()).eq(value);
        }
        return fcbc.having(mdIDElement.getSourceName()).eq(value);

      case GT:
        if (fcbc == null) {
          return queryBuilder.having(mdIDElement.getSourceName()).gt(value);
        }
        return fcbc.having(mdIDElement.getSourceName()).gt(value);

      case GE:
        if (fcbc == null) {
          return queryBuilder.having(mdIDElement.getSourceName()).gte(value);
        }
        return fcbc.having(mdIDElement.getSourceName()).gte(value);

      case LT:
        if (fcbc == null) {
          return queryBuilder.having(mdIDElement.getSourceName()).lt(value);
        }
        return fcbc.having(mdIDElement.getSourceName()).lt(value);

      case LE:
        if (fcbc == null) {
          return queryBuilder.having(mdIDElement.getSourceName()).lte(value);
        }
        return fcbc.having(mdIDElement.getSourceName()).lte(value);

      default:
        throw new TranslatorException(
            InfinispanPlugin.Util.gs(
                InfinispanPlugin.Event.TEIID25050, new Object[] {op, "NE, EQ, GT, GE, LT, LE"}));
    }
  }
Exemple #17
0
  private static FilterConditionContext buildQueryFromWhereClause(
      Condition criteria,
      @SuppressWarnings("rawtypes") QueryBuilder queryBuilder,
      FilterConditionBeginContext fcbc)
      throws TranslatorException {

    if (criteria == null) return null;
    FilterConditionContext fcc = null;

    if (criteria instanceof AndOr) {
      LogManager.logTrace(
          LogConstants.CTX_CONNECTOR, "Infinispan DSL Parsing compound criteria."); // $NON-NLS-1$
      AndOr crit = (AndOr) criteria;
      AndOr.Operator op = crit.getOperator();

      switch (op) {
        case AND:
          FilterConditionContext f_and =
              buildQueryFromWhereClause(crit.getLeftCondition(), queryBuilder, fcbc);
          FilterConditionBeginContext fcbca = null;
          if (f_and != null) {
            fcbca = f_and.and();
          }
          fcc = buildQueryFromWhereClause(crit.getRightCondition(), queryBuilder, fcbca);

          break;

        case OR:
          FilterConditionContext f_or =
              buildQueryFromWhereClause(crit.getLeftCondition(), queryBuilder, fcbc);
          FilterConditionBeginContext fcbcb = null;
          if (f_or != null) {
            fcbcb = f_or.or();
          }
          fcc = buildQueryFromWhereClause(crit.getRightCondition(), queryBuilder, fcbcb);

          break;

        default:
          throw new TranslatorException(
              InfinispanPlugin.Util.gs(
                  InfinispanPlugin.Event.TEIID25050, new Object[] {op, "And, Or"}));
      }

    } else if (criteria instanceof Comparison) {
      fcc = visit((Comparison) criteria, queryBuilder, fcbc);

    } else if (criteria instanceof Like) {
      fcc = visit((Like) criteria, queryBuilder, fcbc);

    } else if (criteria instanceof In) {
      fcc = visit((In) criteria, queryBuilder, fcbc);

    } else if (criteria instanceof IsNull) {
      fcc = visit((IsNull) criteria, queryBuilder, fcbc);
    } else if (criteria instanceof Not) {
      Condition c = ((Not) criteria).getCriteria();
      if (fcbc == null) {
        fcc = queryBuilder.not(buildQueryFromWhereClause(c, queryBuilder, fcbc));
      } else {
        fcc = fcbc.not(buildQueryFromWhereClause(c, queryBuilder, fcbc));
      }
    } else {
      throw new TranslatorException(
          InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25054, criteria.toString()));
    }
    return fcc;
  }
Exemple #18
0
  private static boolean buildQueryFromWhereClause(
      Condition criteria, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder)
      throws TranslatorException {
    boolean createdQueries = false;
    BooleanJunction<BooleanJunction> inUse = junction;

    if (criteria instanceof AndOr) {
      LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing compound criteria."); // $NON-NLS-1$
      AndOr crit = (AndOr) criteria;
      AndOr.Operator op = crit.getOperator();

      switch (op) {
        case AND:
          BooleanJunction<BooleanJunction> leftAnd = queryBuilder.bool();
          boolean andLeftHasQueries =
              buildQueryFromWhereClause(crit.getLeftCondition(), leftAnd, queryBuilder);

          BooleanJunction<BooleanJunction> rightAnd = queryBuilder.bool();
          boolean andRightHasQueries =
              buildQueryFromWhereClause(crit.getRightCondition(), rightAnd, queryBuilder);

          if (andLeftHasQueries && andRightHasQueries) {
            leftAnd.must(rightAnd.createQuery());
            inUse.should(leftAnd.createQuery());
          } else if (andLeftHasQueries) {

            inUse.should(leftAnd.createQuery());
          } else if (andRightHasQueries) {
            inUse.should(rightAnd.createQuery());
          }

          createdQueries = (andLeftHasQueries ? andLeftHasQueries : andRightHasQueries);

          break;

        case OR:
          boolean orLeftHasQueries =
              buildQueryFromWhereClause(crit.getLeftCondition(), inUse, queryBuilder);
          boolean orRightHasQueries =
              buildQueryFromWhereClause(crit.getRightCondition(), inUse, queryBuilder);

          createdQueries = (orLeftHasQueries ? orLeftHasQueries : orRightHasQueries);

          break;

        default:
          final String msg =
              ObjectPlugin.Util.getString(
                  "LuceneSearch.invalidOperator",
                  new Object[] {op, "And, Or"}); // $NON-NLS-1$ //$NON-NLS-2$
          throw new TranslatorException(msg);
      }

    } else if (criteria instanceof Comparison) {
      createdQueries = visit((Comparison) criteria, inUse, queryBuilder);

    } else if (criteria instanceof Exists) {
      LogManager.logTrace(
          LogConstants.CTX_CONNECTOR,
          "Parsing EXISTS criteria: NOT IMPLEMENTED YET"); //$NON-NLS-1$
      // TODO Exists should be supported in a future release.

    } else if (criteria instanceof Like) {
      createdQueries = visit((Like) criteria, inUse, queryBuilder);

    } else if (criteria instanceof In) {
      createdQueries = visit((In) criteria, inUse, queryBuilder);
    }
    // else if (criteria instanceof Not) {
    //			LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing NOT criteria."); //$NON-NLS-1$
    // isNegated = true;
    // filterList.addAll(getSearchFilterFromWhereClause(((Not)criteria).getCriteria(),
    // new LinkedList<String>()));
    // }

    return createdQueries;
  }
Exemple #19
0
  public static boolean visit(
      Comparison obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder)
      throws TranslatorException {

    LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing Comparison criteria."); // $NON-NLS-1$
    Comparison.Operator op = obj.getOperator();

    Expression lhs = obj.getLeftExpression();
    Expression rhs = obj.getRightExpression();

    // joins between the objects in the same cache is not usable
    if ((lhs instanceof ColumnReference && rhs instanceof ColumnReference)
        || (lhs instanceof Literal && rhs instanceof Literal)) {
      return false;
    }

    Object value = null;
    Column mdIDElement = null;
    Literal literal = null;
    if (lhs instanceof ColumnReference) {

      mdIDElement = ((ColumnReference) lhs).getMetadataObject();
      literal = (Literal) rhs;
      value = literal.getValue();

    } else if (rhs instanceof ColumnReference) {
      mdIDElement = ((ColumnReference) rhs).getMetadataObject();
      literal = (Literal) lhs;
      value = literal.getValue();
    }

    if (value == null) {
      final String msg =
          ObjectPlugin.Util.getString("LuceneSearch.unsupportedComparingByNull"); // $NON-NLS-1$
      throw new TranslatorException(msg);
    }

    value = escapeReservedChars(value);
    switch (op) {
      case NE:
        createEqualsQuery(mdIDElement, value, false, true, junction, queryBuilder);
        break;

      case EQ:
        createEqualsQuery(mdIDElement, value, true, false, junction, queryBuilder);
        break;

      case GT:
        createRangeAboveQuery(mdIDElement, value, junction, queryBuilder);
        break;

      case LT:
        createRangeBelowQuery(mdIDElement, value, junction, queryBuilder);
        break;

      default:
        final String msg =
            ObjectPlugin.Util.getString(
                "LuceneSearch.invalidOperator",
                new Object[] {op, "NE, EQ, GT, LT"}); // $NON-NLS-1$ //$NON-NLS-2$
        throw new TranslatorException(msg);
    }
    return true;
  }
  private void resolveStatement(
      CreateProcedureCommand command,
      Statement statement,
      GroupContext externalGroups,
      GroupSymbol variables,
      TempMetadataAdapter metadata)
      throws QueryResolverException, QueryMetadataException, TeiidComponentException {
    LogManager.logTrace(
        org.teiid.logging.LogConstants.CTX_QUERY_RESOLVER,
        new Object[] {"Resolving statement", statement}); // $NON-NLS-1$

    switch (statement.getType()) {
      case Statement.TYPE_IF:
        IfStatement ifStmt = (IfStatement) statement;
        Criteria ifCrit = ifStmt.getCondition();
        for (SubqueryContainer container :
            ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(ifCrit)) {
          resolveEmbeddedCommand(metadata, externalGroups, container.getCommand());
        }
        ResolverVisitor.resolveLanguageObject(ifCrit, null, externalGroups, metadata);
        resolveBlock(command, ifStmt.getIfBlock(), externalGroups, metadata);
        if (ifStmt.hasElseBlock()) {
          resolveBlock(command, ifStmt.getElseBlock(), externalGroups, metadata);
        }
        break;
      case Statement.TYPE_COMMAND:
        CommandStatement cmdStmt = (CommandStatement) statement;
        Command subCommand = cmdStmt.getCommand();

        TempMetadataStore discoveredMetadata =
            resolveEmbeddedCommand(metadata, externalGroups, subCommand);

        if (subCommand instanceof StoredProcedure) {
          StoredProcedure sp = (StoredProcedure) subCommand;
          for (SPParameter param : sp.getParameters()) {
            switch (param.getParameterType()) {
              case ParameterInfo.OUT:
              case ParameterInfo.RETURN_VALUE:
                if (param.getExpression() != null && !isAssignable(metadata, param)) {
                  throw new QueryResolverException(
                      QueryPlugin.Event.TEIID30121,
                      QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30121, param.getExpression()));
                }
                sp.setCallableStatement(true);
                break;
              case ParameterInfo.INOUT:
                if (!isAssignable(metadata, param)) {
                  continue;
                }
                sp.setCallableStatement(true);
                break;
            }
          }
        }

        if (discoveredMetadata != null) {
          metadata.getMetadataStore().getData().putAll(discoveredMetadata.getData());
        }

        // dynamic commands need to be updated as to their implicitly expected projected symbols
        if (subCommand instanceof DynamicCommand) {
          DynamicCommand dynCommand = (DynamicCommand) subCommand;

          if (dynCommand.getIntoGroup() == null && !dynCommand.isAsClauseSet()) {
            if ((command.getResultSetColumns() != null && command.getResultSetColumns().isEmpty())
                || !cmdStmt.isReturnable()
                || command.getResultSetColumns() == null) {
              // we're not interested in the resultset
              dynCommand.setAsColumns(Collections.EMPTY_LIST);
            } else {
              // should match the procedure
              dynCommand.setAsColumns(command.getResultSetColumns());
            }
          }
        }

        if (command.getResultSetColumns() == null
            && cmdStmt.isReturnable()
            && subCommand.returnsResultSet()
            && subCommand.getResultSetColumns() != null
            && !subCommand.getResultSetColumns().isEmpty()) {
          command.setResultSetColumns(subCommand.getResultSetColumns());
          if (command.getProjectedSymbols().isEmpty()) {
            command.setProjectedSymbols(subCommand.getResultSetColumns());
          }
        }

        break;
      case Statement.TYPE_ERROR:
      case Statement.TYPE_ASSIGNMENT:
      case Statement.TYPE_DECLARE:
      case Statement.TYPE_RETURN:
        ExpressionStatement exprStmt = (ExpressionStatement) statement;
        // first resolve the value.  this ensures the value cannot use the variable being defined
        if (exprStmt.getExpression() != null) {
          Expression expr = exprStmt.getExpression();
          for (SubqueryContainer container :
              ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(expr)) {
            resolveEmbeddedCommand(metadata, externalGroups, container.getCommand());
          }
          ResolverVisitor.resolveLanguageObject(expr, null, externalGroups, metadata);
        }

        // second resolve the variable
        switch (statement.getType()) {
          case Statement.TYPE_DECLARE:
            collectDeclareVariable(
                (DeclareStatement) statement, variables, metadata, externalGroups);
            break;
          case Statement.TYPE_ASSIGNMENT:
            AssignmentStatement assStmt = (AssignmentStatement) statement;
            ResolverVisitor.resolveLanguageObject(
                assStmt.getVariable(), null, externalGroups, metadata);
            if (!metadata.elementSupports(
                assStmt.getVariable().getMetadataID(), SupportConstants.Element.UPDATE)) {
              throw new QueryResolverException(
                  QueryPlugin.Event.TEIID30121,
                  QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30121, assStmt.getVariable()));
            }
            // don't allow variable assignments to be external
            assStmt.getVariable().setIsExternalReference(false);
            break;
          case Statement.TYPE_RETURN:
            ReturnStatement rs = (ReturnStatement) statement;
            if (rs.getExpression() != null) {
              if (command.getReturnVariable() == null) {
                throw new QueryResolverException(
                    QueryPlugin.Event.TEIID31125,
                    QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31125, rs));
              }
              rs.setVariable(command.getReturnVariable().clone());
            }
            // else - we don't currently require the use of return for backwards compatibility
            break;
        }

        // third ensure the type matches
        if (exprStmt.getExpression() != null) {
          Class<?> varType = exprStmt.getExpectedType();
          Class<?> exprType = exprStmt.getExpression().getType();
          if (exprType == null) {
            throw new QueryResolverException(
                QueryPlugin.Event.TEIID30123, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30123));
          }
          String varTypeName = DataTypeManager.getDataTypeName(varType);
          exprStmt.setExpression(
              ResolverUtil.convertExpression(exprStmt.getExpression(), varTypeName, metadata));
          if (statement.getType() == Statement.TYPE_ERROR) {
            ResolverVisitor.checkException(exprStmt.getExpression());
          }
        }
        break;
      case Statement.TYPE_WHILE:
        WhileStatement whileStmt = (WhileStatement) statement;
        Criteria whileCrit = whileStmt.getCondition();
        for (SubqueryContainer container :
            ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(whileCrit)) {
          resolveEmbeddedCommand(metadata, externalGroups, container.getCommand());
        }
        ResolverVisitor.resolveLanguageObject(whileCrit, null, externalGroups, metadata);
        resolveBlock(command, whileStmt.getBlock(), externalGroups, metadata);
        break;
      case Statement.TYPE_LOOP:
        LoopStatement loopStmt = (LoopStatement) statement;
        String groupName = loopStmt.getCursorName();

        isValidGroup(metadata, groupName);
        Command cmd = loopStmt.getCommand();
        resolveEmbeddedCommand(metadata, externalGroups, cmd);
        List<Expression> symbols = cmd.getProjectedSymbols();

        // add the loop cursor group into its own context
        TempMetadataStore store = metadata.getMetadataStore().clone();
        metadata = new TempMetadataAdapter(metadata.getMetadata(), store);
        externalGroups = new GroupContext(externalGroups, null);

        ProcedureContainerResolver.addScalarGroup(groupName, store, externalGroups, symbols, false);

        resolveBlock(command, loopStmt.getBlock(), externalGroups, metadata);
        break;
      case Statement.TYPE_COMPOUND:
        resolveBlock(command, (Block) statement, externalGroups, metadata);
        break;
    }
  }
Exemple #21
0
  /**
   * Process the procedure, using the stack of Programs supplied by the ProcessorEnvironment. With
   * each pass through the loop, the current Program is gotten off the top of the stack, and the
   * current instruction is gotten from that program; each call to an instruction's process method
   * may alter the Program Stack and/or the current instruction pointer of a Program, so it's
   * important that this method's loop refer to the call stack of the ProcessorEnvironment each
   * time, and not cache things in local variables. If the current Program's current instruction is
   * null, then it's time to pop that Program off the stack.
   *
   * @return List a single tuple containing one Integer: the update count resulting from the
   *     procedure execution.
   */
  private TupleSource processProcedure()
      throws TeiidComponentException, TeiidProcessingException, BlockedException {

    // execute plan
    ProgramInstruction inst = null;

    while (!this.programs.empty()) {
      Program program = peek();
      inst = program.getCurrentInstruction();
      if (inst == null) {
        LogManager.logTrace(
            org.teiid.logging.LogConstants.CTX_DQP, "Finished program", program); // $NON-NLS-1$
        // look ahead to see if we need to process in place
        VariableContext vc = this.cursorStates.getParentContext();
        CursorState last = (CursorState) this.cursorStates.getValue(null);
        if (last != null) {
          if (last.resultsBuffer == null && (last.usesLocalTemp || !txnTupleSources.isEmpty())) {
            last.resultsBuffer =
                bufferMgr.createTupleBuffer(
                    last.processor.getOutputElements(),
                    getContext().getConnectionId(),
                    TupleSourceType.PROCESSOR);
            last.returning = true;
          }
          if (last.returning) {
            while (last.ts.hasNext()) {
              List<?> tuple = last.ts.nextTuple();
              last.resultsBuffer.addTuple(tuple);
            }
            last.resultsBuffer.close();
            last.ts = last.resultsBuffer.createIndexedTupleSource(true);
            last.returning = false;
          }
        }
        this.pop(true);
        continue;
      }
      try {
        if (inst instanceof RepeatedInstruction) {
          LogManager.logTrace(
              org.teiid.logging.LogConstants.CTX_DQP,
              "Executing repeated instruction",
              inst); //$NON-NLS-1$
          RepeatedInstruction loop = (RepeatedInstruction) inst;
          if (loop.testCondition(this)) {
            LogManager.logTrace(
                org.teiid.logging.LogConstants.CTX_DQP,
                "Passed condition, executing program " + loop.getNestedProgram()); // $NON-NLS-1$
            inst.process(this);
            this.push(loop.getNestedProgram());
            continue;
          }
          LogManager.logTrace(
              org.teiid.logging.LogConstants.CTX_DQP,
              "Exiting repeated instruction",
              inst); //$NON-NLS-1$
          loop.postInstruction(this);
        } else {
          LogManager.logTrace(
              org.teiid.logging.LogConstants.CTX_DQP, "Executing instruction", inst); // $NON-NLS-1$
          inst.process(this);
          this.evaluator.close();
        }
      } catch (RuntimeException e) {
        throw e;
      } catch (TeiidComponentException e) {
        throw e;
      } catch (Exception e) {
        // processing or teiidsqlexception
        boolean atomic = program.isAtomic();
        while (program.getExceptionGroup() == null) {
          this.pop(false);
          if (this.programs.empty()) {
            // reached the top without a handler, so throw
            if (e instanceof TeiidProcessingException) {
              throw (TeiidProcessingException) e;
            }
            throw new ProcedureErrorInstructionException(QueryPlugin.Event.TEIID30167, e);
          }
          program = peek();
          atomic |= program.isAtomic();
        }
        this.pop(false); // allow the current program to go out of scope
        if (atomic) {
          TransactionContext tc = this.getContext().getTransactionContext();
          if (tc != null && tc.getTransactionType() != Scope.NONE) {
            // a non-completing atomic block under a higher level transaction

            // this will not work correctly until we support
            // checkpoints/subtransactions
            try {
              tc.getTransaction().setRollbackOnly();
            } catch (IllegalStateException e1) {
              throw new TeiidComponentException(e1);
            } catch (SystemException e1) {
              throw new TeiidComponentException(e1);
            }
          }
        }
        if (program.getExceptionProgram() == null) {
          continue;
        }
        Program exceptionProgram = program.getExceptionProgram();
        this.push(exceptionProgram);
        TeiidSQLException tse = TeiidSQLException.create(e);
        GroupSymbol gs = new GroupSymbol(program.getExceptionGroup());
        this.currentVarContext.setValue(exceptionSymbol(gs, 0), tse.getSQLState());
        this.currentVarContext.setValue(exceptionSymbol(gs, 1), tse.getErrorCode());
        this.currentVarContext.setValue(exceptionSymbol(gs, 2), tse.getTeiidCode());
        this.currentVarContext.setValue(exceptionSymbol(gs, 3), tse);
        this.currentVarContext.setValue(exceptionSymbol(gs, 4), tse.getCause());
        continue;
      }
      program.incrementProgramCounter();
    }
    CursorState last = (CursorState) this.cursorStates.getValue(null);
    if (last == null) {
      return CollectionTupleSource.createNullTupleSource();
    }
    return last.ts;
  }