Пример #1
0
  /** Tests the specified instance. */
  @Test
  public void test() {
    final StringBuilder sb = new StringBuilder();
    int fail = 0;

    for (final Object[] qu : queries) {
      final boolean correct = qu.length == 3;
      final String query = qu[correct ? 2 : 1].toString();
      final Value cmp = correct ? (Value) qu[1] : null;

      final QueryProcessor qp = new QueryProcessor(query, context);
      try {
        final Value val = qp.value();
        if (!correct || !new DeepCompare().equal(val, cmp)) {
          sb.append("[" + qu[0] + "] " + query);
          String s = correct && cmp.size() != 1 ? "#" + cmp.size() : "";
          sb.append("\n[E" + s + "] ");
          if (correct) {
            final String cp = cmp.toString();
            sb.append('\'');
            sb.append(cp.length() > 1000 ? cp.substring(0, 1000) + "..." : cp);
            sb.append('\'');
          } else {
            sb.append("error");
          }
          final TokenBuilder types = new TokenBuilder();
          for (final Item it : val) types.add(it.type.toString()).add(" ");
          s = val.size() == 1 ? "" : "#" + val.size();
          sb.append("\n[F" + s + "] '" + val + "', " + types + details() + '\n');
          ++fail;
        }
      } catch (final Exception ex) {
        final String msg = ex.getMessage();
        if (correct || msg == null || msg.contains("mailman")) {
          final String cp = correct && cmp.data() != null ? cmp.toString() : "()";
          sb.append(
              "["
                  + qu[0]
                  + "] "
                  + query
                  + "\n[E] "
                  + cp
                  + "\n[F] "
                  + (msg == null ? Util.className(ex) : msg.replaceAll("\r\n?|\n", " "))
                  + ' '
                  + details()
                  + '\n');
          ex.printStackTrace();
          ++fail;
        }
      } finally {
        qp.close();
      }
    }
    if (fail != 0) fail(fail + " Errors. [E] = expected, [F] = found:\n" + sb.toString().trim());
  }
Пример #2
0
  /**
   * Computes the number of results.
   *
   * @param qc query context (may be @code null)
   * @return number of results
   */
  private long size(final QueryContext qc) {
    final Value rt = initial(qc);
    // skip computation if value is not a document node
    if (rt == null || rt.type != NodeType.DOC) return -1;
    final Data data = rt.data();
    // skip computation if no database instance is available, is out-of-date or
    // if context does not contain all database nodes
    if (data == null || !data.meta.uptodate || data.resources.docs().size() != rt.size()) return -1;

    ArrayList<PathNode> nodes = data.paths.root();
    long m = 1;
    final int sl = steps.length;
    for (int s = 0; s < sl; s++) {
      final Step curr = axisStep(s);
      if (curr != null) {
        nodes = curr.nodes(nodes, data);
        if (nodes == null) return -1;
      } else if (s + 1 == sl) {
        m = steps[s].size();
      } else {
        // stop if a non-axis step is not placed last
        return -1;
      }
    }

    long sz = 0;
    for (final PathNode pn : nodes) sz += pn.stats.count;
    return sz * m;
  }
Пример #3
0
 /**
  * Checks the response to an HTTP request.
  *
  * @param v query result
  * @param itemsCount expected number of items
  * @param expStatus expected status
  */
 private static void checkResponse(final Value v, final int itemsCount, final int expStatus) {
   assertEquals(itemsCount, v.size());
   assertTrue(v.itemAt(0) instanceof FElem);
   final FElem response = (FElem) v.itemAt(0);
   assertNotNull(response.attributes());
   if (!eq(response.attribute(STATUS), token(expStatus))) {
     fail("Expected: " + expStatus + "\nFound: " + response);
   }
 }
Пример #4
0
 /**
  * Returns the root of the current context or {@code null}.
  *
  * @param ctx query context
  * @return root
  */
 final Value root(final QueryContext ctx) {
   final Value v = ctx != null ? ctx.value : null;
   // no root specified: return context, if it does not reference a document
   // as e.g. happens in //a(b|c)
   if (root == null) return v == null || v.type != NodeType.DOC ? v : null;
   // root is value: return root
   if (root.isValue()) return (Value) root;
   // no root reference, no context: return null
   if (!(root instanceof Root) || v == null) return null;
   // return context sequence or root of current context
   return v.size() == 1 ? Root.root(v) : v;
 }
Пример #5
0
 /**
  * Returns a parameter.
  *
  * @param value value
  * @param name name
  * @param declared variable declaration flags
  * @return parameter
  * @throws QueryException HTTP exception
  */
 private RestXqParam param(final Value value, final QNm name, final boolean[] declared)
     throws QueryException {
   // [CG] RESTXQ: allow identical field names?
   final long vs = value.size();
   if (vs < 2) error(ANN_PARAMS, "%", name.string(), 2);
   // name of parameter
   final String key = toString(value.itemAt(0), name);
   // variable template
   final QNm qnm = checkVariable(toString(value.itemAt(1), name), declared);
   // default value
   final ValueBuilder vb = new ValueBuilder();
   for (int v = 2; v < vs; v++) vb.add(value.itemAt(v));
   return new RestXqParam(qnm, key, vb.value());
 }
Пример #6
0
  /**
   * Returns a document test. This test will be called by {@link AxisPath#index} if the context
   * value only consists of database nodes.
   *
   * @param rt root value
   * @return document test
   */
  static Test get(final Value rt) {
    // use simple test if database contains only one document
    final Data data = rt.data();
    if (data.meta.ndocs == 1) return Test.DOC;

    // adopt nodes from existing sequence
    if (rt instanceof DBNodeSeq) {
      final DBNodeSeq seq = (DBNodeSeq) rt;
      return seq.all() ? Test.DOC : new InvDocTest(new IntList(seq.pres()), data);
    }

    // loop through all documents and add pre values of documents
    // not more than 2^31 documents supported
    final IntList il = new IntList((int) rt.size());
    for (final Item it : rt) il.add(((DBNode) it).pre());
    return new InvDocTest(il, data);
  }
Пример #7
0
  @Override
  protected Expr opt(final CompileContext cc) throws QueryException {
    if (allAreValues() && exprs[0].size() < UNROLL_LIMIT) {
      // unroll the loop
      cc.info(QueryText.OPTUNROLL_X, this);
      final Value seq = (Value) exprs[0];
      final int len = (int) seq.size();

      // fn:for-each(...)
      final Expr[] results = new Expr[len];
      for (int i = 0; i < len; i++) {
        results[i] = new DynFuncCall(info, sc, exprs[1], seq.itemAt(i)).optimize(cc);
      }
      return new List(info, results).optimize(cc);
    }
    return this;
  }
Пример #8
0
  /**
   * Evaluates the specified query.
   *
   * @param query query
   * @return success flag
   */
  final boolean query(final String query) {
    final Performance p = new Performance();
    String error;
    if (exception != null) {
      error = Util.message(exception);
    } else {
      try {
        long hits = 0;
        final boolean run = options.get(MainOptions.RUNQUERY);
        final boolean serial = options.get(MainOptions.SERIALIZE);
        final int runs = Math.max(1, options.get(MainOptions.RUNS));
        for (int r = 0; r < runs; ++r) {
          // reuse existing processor instance
          if (r != 0) qp = null;
          qp(query, context);
          parse(p);
          if (r == 0) plan(false);

          qp.compile();
          info.compiling += p.time();
          if (r == 0) plan(true);
          if (!run) continue;

          final PrintOutput po = r == 0 && serial ? out : new NullOutput();
          try (final Serializer ser = qp.getSerializer(po)) {
            if (maxResults >= 0) {
              result = qp.cache(maxResults);
              info.evaluating += p.time();
              result.serialize(ser);
              hits = result.size();
            } else {
              hits = 0;
              final Iter ir = qp.iter();
              info.evaluating += p.time();
              for (Item it; (it = ir.next()) != null; ) {
                ser.serialize(it);
                ++hits;
                checkStop();
              }
            }
          }
          qp.close();
          info.serializing += p.time();
        }
        // dump some query info
        // out.flush();

        // remove string list if global locking is used and if query is updating
        if (soptions.get(StaticOptions.GLOBALLOCK) && qp.updating) {
          info.readLocked = null;
          info.writeLocked = null;
        }
        return info(info.toString(qp, out.size(), hits, options.get(MainOptions.QUERYINFO)));

      } catch (final QueryException | IOException ex) {
        exception = ex;
        error = Util.message(ex);
      } catch (final ProcException ex) {
        error = INTERRUPTED;
      } catch (final StackOverflowError ex) {
        Util.debug(ex);
        error = BASX_STACKOVERFLOW.desc;
      } catch (final RuntimeException ex) {
        extError("");
        Util.debug(info());
        throw ex;
      } finally {
        // close processor after exceptions
        if (qp != null) qp.close();
      }
    }
    return extError(error);
  }
Пример #9
0
  /**
   * Adds items to the specified list.
   *
   * @param value value
   * @param name name
   * @param list list to add values to
   * @throws QueryException HTTP exception
   */
  private void strings(final Value value, final QNm name, final StringList list)
      throws QueryException {

    final long vs = value.size();
    for (int v = 0; v < vs; v++) list.add(toString(value.itemAt(v), name));
  }