Debian Codegraph @

net/sf/saxon/s9api/XQueryEvaluator.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.s9api;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.*;
13 import net.sf.saxon.expr.instruct.Executable;
14 import net.sf.saxon.expr.instruct.GlobalContextRequirement;
15 import net.sf.saxon.expr.instruct.UserFunction;
16 import net.sf.saxon.expr.parser.ExplicitLocation;
17 import net.sf.saxon.expr.parser.RoleDiagnostic;
18 import net.sf.saxon.lib.Logger;
19 import net.sf.saxon.lib.TraceListener;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.query.DynamicQueryContext;
22 import net.sf.saxon.query.XQueryExpression;
23 import net.sf.saxon.serialize.SerializationProperties;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.tree.tiny.TinyBuilder;
26 import net.sf.saxon.type.TypeHierarchy;
27
28 import javax.xml.transform.ErrorListener;
29 import javax.xml.transform.Source;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.URIResolver;
32 import javax.xml.transform.dom.DOMSource;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.Set;
36
37 /**
38 * An <code>XQueryEvaluator</code> represents a compiled and loaded query ready for execution.
39 * The <code>XQueryEvaluator</code> holds details of the dynamic evaluation context for the query.
40 * <p>An <code>XQueryEvaluator</code> must not be used concurrently in multiple threads.
41 * It is safe, however, to reuse the object within a single thread to run the same
42 * query several times. Running the query does not change the context
43 * that has been established.</p>
44 * <p>An <code>XQueryEvaluator</code> is always constructed by running the <code>Load</code>
45 * method of an {@link net.sf.saxon.s9api.XQueryExecutable}.</p>
46 * <p>An <code>XQueryEvaluator</code> is itself a <code>Iterable</code>. This makes it possible to
47 * evaluate the results in a for-each expression.</p>
48 * <p>An <code>XQueryEvaluator</code> is itself a <code>Destination</code>. This means it is possible to use
49 * one <code>XQueryEvaluator</code> as the destination to receive the results of another transformation,
50 * this providing a simple way for transformations to be chained into a pipeline. When the query is executed
51 * this way, {@link #setDestination(Destination)} must be called to provide a destination for the result of this query.</p>
52 * <p>As a {@code Destination}, an {@code XQueryEvaluator} performs <b>sequence normalization</b> as defined
53 * in the Serialization specification, including inserting item separators if required. The input to the
54 * query (the global context item) will therefore always be a single document node. This will always be built
55 * as a tree in memory, it will never be streamed.</p>
56 */
57 public class XQueryEvaluator extends AbstractDestination implements Iterable<XdmItem> {
58
59 private Processor processor;
60 private XQueryExpression expression;
61 private DynamicQueryContext context;
62 private Controller controller; // used only when making direct calls to global functions
63 private Destination destination;
64 private Set<XdmNode> updatedDocuments;
65 /*@Nullable*/ private Builder sourceTreeBuilder;
66
67 /**
68 * Protected constructor
69 *
70 * @param processor the Saxon processor
71 * @param expression the XQuery expression
72 */
73
74 protected XQueryEvaluator(Processor processor, XQueryExpression expression) {
75 this.processor = processor;
76 this.expression = expression;
77 this.context = new DynamicQueryContext(expression.getConfiguration());
78 }
79
80 /**
81 * Set the schema validation mode for the transformation. This indicates how source documents
82 * loaded specifically for this transformation will be handled. This applies to the
83 * principal source document if supplied as a SAXSource or StreamSource, and to all
84 * documents loaded during the transformation using the <code>doc()</code>, <code>document()</code>,
85 * or <code>collection()</code> functions.
86 *
87 * @param mode the validation mode. Passing null causes no change to the existing value.
88 * Passing <code>Validation.DEFAULT</code> resets to the initial value, which determines
89 * the validation requirements from the Saxon Configuration.
90 */
91
92 public void setSchemaValidationMode(ValidationMode mode) {
93 if (mode != null) {
94 context.setSchemaValidationMode(mode.getNumber());
95 }
96 }
97
98 /**
99 * Get the schema validation mode for the transformation. This indicates how source documents
100 * loaded specifically for this transformation will be handled. This applies to the
101 * principal source document if supplied as a SAXSource or StreamSource, and to all
102 * documents loaded during the transformation using the <code>doc()</code>, <code>document()</code>,
103 * or <code>collection()</code> functions.
104 *
105 * @return the validation mode.
106 */
107
108 public ValidationMode getSchemaValidationMode() {
109 return ValidationMode.get(context.getSchemaValidationMode());
110 }
111
112
113 /**
114 * Set the source document for the query.
115 * <p>If the source is an instance of {@link net.sf.saxon.om.NodeInfo}, the supplied node is used
116 * directly as the context node of the query.</p>
117 * <p>If the source is an instance of {@link javax.xml.transform.dom.DOMSource}, the DOM node identified
118 * by the DOMSource is wrapped as a Saxon node, and this is then used as the context item</p>
119 * <p>In all other cases a new Saxon tree is built, by calling
120 * {@link net.sf.saxon.s9api.DocumentBuilder#build(javax.xml.transform.Source)}, and the document
121 * node of this tree is then used as the context item for the query.</p>
122 *
123 * @param source the source document to act as the initial context item for the query.
124 */
125
126 public void setSource(Source source) throws SaxonApiException {
127 if (source instanceof NodeInfo) {
128 setContextItem(new XdmNode((NodeInfo) source));
129 } else if (source instanceof DOMSource) {
130 setContextItem(processor.newDocumentBuilder().wrap(source));
131 } else {
132 setContextItem(processor.newDocumentBuilder().build(source));
133 }
134 }
135
136 /**
137 * Set the initial context item for the query
138 *
139 * @param item the initial context item, or null if there is to be no initial context item
140 * @throws SaxonApiException if the query declares the context item and does not define
141 * it to be external
142 */
143
144 public void setContextItem(XdmItem item) throws SaxonApiException {
145 if (item != null) {
146 GlobalContextRequirement gcr = expression.getExecutable().getGlobalContextRequirement();
147 if (gcr != null && !gcr.isExternal()) {
148 throw new SaxonApiException("The context item for the query is not defined as external");
149 }
150 context.setContextItem(item.getUnderlyingValue());
151 }
152 }
153
154 /**
155 * Get the initial context item for the query, if one has been set
156 *
157 * @return the initial context item, or null if none has been set. This will not necessarily
158 * be the same object as was supplied, but it will be an XdmItem object that represents
159 * the same underlying node or atomic value.
160 */
161
162 public XdmItem getContextItem() {
163 Item<?> item = context.getContextItem();
164 if (item == null) {
165 return null;
166 }
167 return (XdmItem) XdmValue.wrap(item);
168 }
169
170 /**
171 * Set the value of external variable defined in the query
172 *
173 * @param name the name of the external variable, as a QName
174 * @param value the value of the external variable, or null to clear a previously set value
175 * @throws SaxonApiUncheckedException if the value is evaluated lazily, and evaluation fails
176 */
177
178 public void setExternalVariable(QName name, XdmValue value) {
179 try {
180 context.setParameter(name.getStructuredQName(),
181 value == null ? null : ((Sequence<?>) value.getUnderlyingValue()).materialize());
182 } catch (XPathException e) {
183 throw new SaxonApiUncheckedException(e);
184 }
185 }
186
187 /**
188 * Get the value that has been set for an external variable
189 *
190 * @param name the name of the external variable whose value is required
191 * @return the value that has been set for the external variable, or null if no value has been set
192 */
193
194 public XdmValue getExternalVariable(QName name) {
195 GroundedValue<?> oval = context.getParameter(name.getStructuredQName());
196 if (oval == null) {
197 return null;
198 }
199 return XdmValue.wrap(oval);
200 }
201
202 /**
203 * Set an object that will be used to resolve URIs used in
204 * fn:doc() and related functions.
205 *
206 * @param resolver An object that implements the URIResolver interface, or
207 * null.
208 */
209
210 public void setURIResolver(URIResolver resolver) {
211 context.setURIResolver(resolver);
212 }
213
214 /**
215 * Get the URI resolver.
216 *
217 * @return the user-supplied URI resolver if there is one, or the
218 * system-defined one otherwise
219 */
220
221 public URIResolver getURIResolver() {
222 return context.getURIResolver();
223 }
224
225 /**
226 * Set the error listener. The error listener receives reports of all run-time
227 * errors and can decide how to report them.
228 *
229 * @param listener the ErrorListener to be used
230 */
231
232 public void setErrorListener(ErrorListener listener) {
233 context.setErrorListener(listener);
234 }
235
236 /**
237 * Get the error listener.
238 *
239 * @return the ErrorListener in use
240 */
241
242 public ErrorListener getErrorListener() {
243 return context.getErrorListener();
244 }
245
246 /**
247 * Set a TraceListener which will receive messages relating to the evaluation of all expressions.
248 * This option has no effect unless the query was compiled to enable tracing.
249 *
250 * @param listener the TraceListener to use
251 */
252
253 public void setTraceListener(TraceListener listener) {
254 context.setTraceListener(listener);
255 }
256
257 /**
258 * Get the registered TraceListener, if any
259 *
260 * @return listener the TraceListener in use, or null if none has been set
261 */
262
263 public TraceListener getTraceListener() {
264 return context.getTraceListener();
265 }
266
267 /**
268 * Set the destination for output from the fn:trace() function.
269 * By default, the destination is System.err. If a TraceListener is in use,
270 * this is ignored, and the trace() output is sent to the TraceListener.
271 *
272 * @param stream the PrintStream to which trace output will be sent. If set to
273 * null, trace output is suppressed entirely. It is the caller's responsibility
274 * to close the stream after use.
275 * @since 9.1. Changed in 9.6 to use a Logger
276 */
277
278 public void setTraceFunctionDestination(Logger stream) {
279 context.setTraceFunctionDestination(stream);
280 }
281
282 /**
283 * Get the destination for output from the fn:trace() function.
284 *
285 * @return the PrintStream to which trace output will be sent. If no explicitly
286 * destination has been set, returns System.err. If the destination has been set
287 * to null to suppress trace output, returns null.
288 * @since 9.1. Changed in 9.6 to use a Logger
289 */
290
291 public Logger getTraceFunctionDestination() {
292 return context.getTraceFunctionDestination();
293 }
294
295 /**
296 * Set the destination to be used for the query results
297 *
298 * @param destination the destination to which the results of the query will be sent
299 */
300
301 public void setDestination(Destination destination) {
302 this.destination = destination;
303 }
304
305 /**
306 * Perform the query.
307 * <ul><li>In the case of a non-updating query, the results are sent to the
308 * registered Destination.</li>
309 * <li>In the case of an updating query, all updated documents will be available after query
310 * execution as the result of the {@link #getUpdatedDocuments} method.</li>
311 * </ul>
312 *
313 * @throws net.sf.saxon.s9api.SaxonApiException
314 * if any dynamic error occurs during the query
315 * @throws IllegalStateException if this is a non-updating query and no Destination has been
316 * supplied for the query results
317 */
318
319 public void run() throws SaxonApiException {
320 try {
321 if (expression.isUpdateQuery()) {
322 Set<MutableNodeInfo> docs = expression.runUpdate(context);
323 updatedDocuments = new HashSet<>();
324 for (MutableNodeInfo doc : docs) {
325 updatedDocuments.add(XdmNode.wrapItem(doc));
326 }
327 } else {
328 if (destination == null) {
329 throw new IllegalStateException("No destination supplied");
330 }
331 run(destination);
332 // Result receiver;
333 // if (destination instanceof Serializer) {
334 // //receiver = ((Serializer) destination).getResult();
335 // //context.set
336 // receiver = ((Serializer) destination).getReceiver(expression.getExecutable());
337 // } else {
338 // receiver = destination.getReceiver(expression.getConfiguration());
339 // }
340 // expression.run(context, receiver, null);
341 // destination.close();
342 }
343 } catch (TransformerException e) {
344 throw new SaxonApiException(e);
345 }
346 }
347
348 /**
349 * Perform the query, sending the results to a specified destination.
350 * <p>This method must not be used with an updating query.</p>
351 * <p>This method is designed for use with a query that produces a single node (typically
352 * a document node or element node) as its result. If the query produces multiple nodes,
353 * the effect depends on the kind of destination. For example, if the result is an
354 * <code>XdmDestination</code>, only the last of the nodes will be accessible.</p>
355 *
356 * @param destination The destination where the result document will be sent
357 * @throws net.sf.saxon.s9api.SaxonApiException
358 * if any dynamic error occurs during the query
359 * @throws IllegalStateException if this is an updating query
360 */
361
362 public void run(Destination destination) throws SaxonApiException {
363 if (expression.isUpdateQuery()) {
364 throw new IllegalStateException("Query is updating");
365 }
366 try {
367 Receiver out = getDestinationReceiver(destination);
368 expression.run(context, out, null);
369 destination.closeAndNotify();
370 } catch (TransformerException e) {
371 throw new SaxonApiException(e);
372 }
373 }
374
375 /**
376 * Perform the query in streaming mode, sending the results to a specified destination.
377 * <p>This method must not be used with an updating query.</p>
378 * <p>This method is designed for use with a query that produces a single node (typically
379 * a document node or element node) as its result. If the query produces multiple nodes,
380 * the effect depends on the kind of destination. For example, if the result is an
381 * <code>XdmDestination</code>, only the last of the nodes will be accessible.</p>
382 *
383 * @param source the input stream whose document node will act as the initial context item.
384 * Should be a SAXSource or StreamSource
385 * @param destination The destination where the result document will be sent
386 * @throws net.sf.saxon.s9api.SaxonApiException
387 * if any dynamic error occurs during the query
388 * @throws IllegalStateException if this is an updating query
389 */
390
391 public void runStreamed(Source source, Destination destination) throws SaxonApiException {
392 if (expression.isUpdateQuery()) {
393 throw new IllegalStateException("Query is updating; cannot run with streaming");
394 }
395 Configuration config = context.getConfiguration();
396 if (config.isTiming()) {
397 String systemId = source.getSystemId();
398 if (systemId == null) {
399 systemId = "";
400 }
401 config.getStandardErrorOutput().println("Processing streamed input " + systemId);
402 }
403 try {
404 SerializationProperties params = expression.getExecutable().getPrimarySerializationProperties();
405 Receiver receiver = destination.getReceiver(config.makePipelineConfiguration(), params);
406 expression.runStreamed(context, source, receiver, null);
407 } catch (TransformerException e) {
408 throw new SaxonApiException(e);
409 }
410 }
411
412
413 /**
414 * Perform the query, returning the results as an XdmValue. This method
415 * must not be used with an updating query
416 *
417 * @return an XdmValue representing the results of the query
418 * @throws SaxonApiException if the query fails with a dynamic error
419 * @throws IllegalStateException if this is an updating query
420 */
421
422 public XdmValue evaluate() throws SaxonApiException {
423 if (expression.isUpdateQuery()) {
424 throw new IllegalStateException("Query is updating");
425 }
426 try {
427 SequenceIterator<?> iter = expression.iterator(context);
428 return XdmValue.wrap(iter.materialize());
429 } catch (XPathException e) {
430 throw new SaxonApiException(e);
431 }
432 }
433
434 /**
435 * Evaluate the XQuery expression, returning the result as an <code>XdmItem</code> (that is,
436 * a single node or atomic value).
437 *
438 * @return an <code>XdmItem</code> representing the result of the query, or null if the query
439 * returns an empty sequence. If the expression returns a sequence of more than one item,
440 * any items after the first are ignored.
441 * @throws SaxonApiException if a dynamic error occurs during the query evaluation.
442 * @since 9.2
443 */
444
445
446 public XdmItem evaluateSingle() throws SaxonApiException {
447 try {
448 SequenceIterator<?> iter = expression.iterator(context);
449 Item<?> next = iter.next();
450 return next == null ? null : (XdmItem) XdmValue.wrap(next);
451 } catch (XPathException e) {
452 throw new SaxonApiException(e);
453 }
454 }
455
456 /**
457 * Evaluate the query, and return an iterator over its results.
458 * <p>This method must not be used with an updating query.</p>
459 *
460 * @return an Iterator&lt;XdmItem&gt;. The XdmSequenceIterator class is a standard Java Iterator with an additional close()
461 * method, which should be called to release resources if the client does not intend to read any more items
462 * from the iterator.
463 *
464 * @throws SaxonApiUncheckedException if a dynamic error is detected while constructing the iterator.
465 * It is also possible for an SaxonApiUncheckedException to be thrown by the hasNext() method of the
466 * returned iterator if a dynamic error occurs while evaluating the result sequence.
467 * @throws IllegalStateException if this is an updating query
468 * @since 9.5.1.5. Previously the method returned Iterator&lt;XdmItem&gt;; the signature changed in Saxon 9.5.1.5 for reasons
469 * described in bug 2016.
470 */
471
472 public XdmSequenceIterator<XdmItem> iterator() throws SaxonApiUncheckedException {
473 if (expression.isUpdateQuery()) {
474 throw new IllegalStateException("Query is updating");
475 }
476 try {
477 return new XdmSequenceIterator<>(expression.iterator(context));
478 } catch (XPathException e) {
479 throw new SaxonApiUncheckedException(e);
480 }
481 }
482
483 private Receiver getDestinationReceiver(Destination destination) throws SaxonApiException {
484 Executable exec = expression.getExecutable();
485 PipelineConfiguration pipe = expression.getConfiguration().makePipelineConfiguration();
486 Receiver out = destination.getReceiver(pipe, exec.getPrimarySerializationProperties());
487 if (Configuration.isAssertionsEnabled()) {
488 return new RegularSequenceChecker(out);
489 } else {
490 return out;
491 }
492 }
493
494 /**
495 * Return a Receiver which can be used to supply the principal source document for the transformation.
496 * This method is intended primarily for internal use, though it can also
497 * be called by a user application that wishes to feed events into the query engine.
498 * <p>Saxon calls this method to obtain a Receiver, to which it then sends
499 * a sequence of events representing the content of an XML document. This method is provided so that
500 * <code>XQueryEvaluator</code> implements <code>Destination</code>, allowing one transformation
501 * to receive the results of another in a pipeline.</p>
502 * <p>Note that when an <code>XQueryEvaluator</code> is used as a <code>Destination</code>, the initial
503 * context node set on that <code>XQueryEvaluator</code> (using {@link #setSource(javax.xml.transform.Source)}) is ignored.</p>
504 *
505 * @param pipe The Saxon configuration. This is supplied so that the destination can
506 * use information from the configuration (for example, a reference to the name pool)
507 * to construct or configure the returned Receiver.
508 * @param params the output serialization properties
509 * @return the Receiver to which events are to be sent.
510 * @throws SaxonApiException if the Receiver cannot be created
511 * @throws IllegalStateException if no Destination has been supplied
512 */
513
514 public Receiver getReceiver(PipelineConfiguration pipe, SerializationProperties params) throws SaxonApiException {
515 if (destination == null) {
516 throw new IllegalStateException("No destination has been supplied");
517 }
518 try {
519 if (controller == null) {
520 controller = expression.newController(context);
521 } else {
522 context.initializeController(controller);
523 }
524 } catch (XPathException e) {
525 throw new SaxonApiException(e);
526 }
527 sourceTreeBuilder = controller.makeBuilder();
528 if (sourceTreeBuilder instanceof TinyBuilder) {
529 ((TinyBuilder) sourceTreeBuilder).setStatistics(context.getConfiguration().getTreeStatistics().SOURCE_DOCUMENT_STATISTICS);
530 }
531 Receiver out = controller.makeStripper(sourceTreeBuilder);
532 SequenceNormalizer sn = params.makeSequenceNormalizer(out);
533 sn.onClose(() -> {
534 NodeInfo doc = sourceTreeBuilder.getCurrentRoot();
535 doc.getTreeInfo().setSpaceStrippingRule(controller.getSpaceStrippingRule());
536 setSource(doc);
537 sourceTreeBuilder = null;
538 if (doc == null) {
539 throw new SaxonApiException("No source document has been built by the previous pipeline stage");
540 }
541 run(destination);
542 destination.closeAndNotify();
543 });
544 return sn;
545 }
546
547 /**
548 * Close this destination, allowing resources to be released. Used when this <code>XQueryEvaluator</code> is acting
549 * as the destination of another transformation or query. Saxon calls this method when it has finished writing
550 * to the destination.
551 */
552
553 public void close() throws SaxonApiException {
554
555 }
556
557
558 /**
559 * After executing an updating query using the {@link #run()} method, iterate over the root
560 * nodes of the documents updated by the query.
561 * <p>The results remain available until a new query is executed. This method returns the results
562 * of the most recently executed query. It does not consume the results.</p>
563 *
564 * @return an iterator over the root nodes of documents (or other trees) that were updated by the query
565 * @since 9.1
566 */
567
568 public Iterator<XdmNode> getUpdatedDocuments() {
569 return updatedDocuments.iterator();
570 }
571
572 /**
573 * Call a global user-defined function in the compiled query.
574 * <p>If this is called more than once (to evaluate the same function repeatedly with different arguments,
575 * or to evaluate different functions) then the sequence of evaluations uses the same values of global
576 * variables including external variables (query parameters); the effect of any changes made to query parameters
577 * between calls is undefined.</p>
578 *
579 * @param function The name of the function to be called
580 * @param arguments The values of the arguments to be supplied to the function. If necessary
581 * these are converted to the required type by applying the function conversion rules.
582 * @return the result of the function call as an XdmValue.
583 * @throws SaxonApiException if no function has been defined with the given name and arity;
584 * or if any of the arguments does not match its required type according to the function
585 * signature; or if a dynamic error occurs in evaluating the function.
586 * @since 9.3. Changed in 9.6 to apply the function conversion rules to the supplied arguments.
587 */
588
589 public XdmValue callFunction(QName function, XdmValue[] arguments) throws SaxonApiException {
590 final UserFunction fn = expression.getMainModule().getUserDefinedFunction(
591 function.getNamespaceURI(), function.getLocalName(), arguments.length);
592 if (fn == null) {
593 throw new SaxonApiException("No function with name " + function.getClarkName() +
594 " and arity " + arguments.length + " has been declared in the query");
595 }
596 try {
597 if (controller == null) {
598 controller = expression.newController(context);
599 } else {
600 context.initializeController(controller);
601 }
602 Configuration config = processor.getUnderlyingConfiguration();
603 Sequence<?>[] vr = SequenceTool.makeSequenceArray(arguments.length);
604 for (int i = 0; i < arguments.length; i++) {
605 net.sf.saxon.value.SequenceType type = fn.getParameterDefinitions()[i].getRequiredType();
606 vr[i] = arguments[i].getUnderlyingValue();
607
608 TypeHierarchy th = config.getTypeHierarchy();
609 if (!type.matches(vr[i], th)) {
610 RoleDiagnostic role = new RoleDiagnostic(
611 RoleDiagnostic.FUNCTION, function.getStructuredQName().getDisplayName(), i);
612 vr[i] = th.applyFunctionConversionRules(vr[i], type, role, ExplicitLocation.UNKNOWN_LOCATION);
613 }
614 }
615 Sequence<?> result = fn.call(vr, controller);
616 return XdmValue.wrap(result);
617 } catch (XPathException e) {
618 throw new SaxonApiException(e);
619 }
620 }
621
622 /**
623 * Get the underlying dynamic context object. This provides an escape hatch to the underlying
624 * implementation classes, which contain methods that may change from one release to another.
625 *
626 * @return the underlying object representing the dynamic context for query execution
627 */
628
629 public DynamicQueryContext getUnderlyingQueryContext() {
630 return context;
631 }
632
633
634 }
635