| 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.query; |
| 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.Expression; |
| 14 | import net.sf.saxon.expr.ExpressionOwner; |
| 15 | import net.sf.saxon.expr.PackageData; |
| 16 | import net.sf.saxon.expr.XPathContextMajor; |
| 17 | import net.sf.saxon.expr.instruct.Executable; |
| 18 | import net.sf.saxon.expr.instruct.GlobalContextRequirement; |
| 19 | import net.sf.saxon.expr.instruct.GlobalVariable; |
| 20 | import net.sf.saxon.expr.instruct.SlotManager; |
| 21 | import net.sf.saxon.expr.parser.*; |
| 22 | import net.sf.saxon.lib.SerializerFactory; |
| 23 | import net.sf.saxon.lib.TraceListener; |
| 24 | import net.sf.saxon.lib.UnfailingErrorListener; |
| 25 | import net.sf.saxon.om.*; |
| 26 | import net.sf.saxon.serialize.SerializationProperties; |
| 27 | import net.sf.saxon.trace.ExpressionPresenter; |
| 28 | import net.sf.saxon.trans.SaxonErrorCode; |
| 29 | import net.sf.saxon.trans.XPathException; |
| 30 | import net.sf.saxon.tree.iter.ManualIterator; |
| 31 | import net.sf.saxon.type.AnyItemType; |
| 32 | import net.sf.saxon.type.ItemType; |
| 33 | |
| 34 | import javax.xml.transform.Result; |
| 35 | import javax.xml.transform.Source; |
| 36 | import javax.xml.transform.TransformerException; |
| 37 | import javax.xml.transform.stream.StreamResult; |
| 38 | import java.io.OutputStream; |
| 39 | import java.util.*; |
| 40 | |
| 41 | /** |
| 42 | * XQueryExpression represents a compiled query. This object is immutable and thread-safe, |
| 43 | * the same compiled query may be executed many times in series or in parallel. The object |
| 44 | * can be created only by using the compileQuery method of the QueryProcessor class. |
| 45 | * <p>Various methods are provided for evaluating the query, with different options for |
| 46 | * delivery of the results.</p> |
| 47 | */ |
| 48 | public class XQueryExpression implements Location, ExpressionOwner { |
| 49 | |
| 50 | protected Expression expression; |
| 51 | protected SlotManager stackFrameMap; |
| 52 | protected Executable executable; |
| 53 | protected QueryModule mainModule; |
| 54 | |
| 55 | |
| 56 | /** |
| 57 | * The constructor is protected, to ensure that instances can only be |
| 58 | * created using the compileQuery() methods of StaticQueryContext |
| 59 | * @param exp an expression to be wrapped as an XQueryExpression |
| 60 | * @param mainModule the static context of the main module |
| 61 | * @param streaming true if streamed execution is requested |
| 62 | * @throws XPathException if an error occurs |
| 63 | */ |
| 64 | |
| 65 | public XQueryExpression(Expression exp, QueryModule mainModule, boolean streaming) |
| 66 | throws XPathException { |
| 67 | Executable exec = mainModule.getExecutable(); |
| 68 | Configuration config = mainModule.getConfiguration(); |
| 69 | stackFrameMap = config.makeSlotManager(); |
| 70 | executable = exec; |
| 71 | this.mainModule = mainModule; |
| 72 | exp.setRetainedStaticContext(mainModule.makeRetainedStaticContext()); |
| 73 | try { |
| 74 | ExpressionVisitor visitor = ExpressionVisitor.make(mainModule); |
| 75 | Optimizer optimizer = visitor.obtainOptimizer(); |
| 76 | visitor.setOptimizeForStreaming(streaming); |
| 77 | exp = exp.simplify(); |
| 78 | exp.checkForUpdatingSubexpressions(); |
| 79 | GlobalContextRequirement contextReq = exec.getGlobalContextRequirement(); |
| 80 | ItemType req = contextReq == null ? AnyItemType.getInstance() : contextReq.getRequiredItemType(); |
| 81 | ContextItemStaticInfo cit = config.makeContextItemStaticInfo(req, true); |
| 82 | Expression e2 = exp.typeCheck(visitor, cit); |
| 83 | if (e2 != exp) { |
| 84 | e2.setRetainedStaticContext(exp.getRetainedStaticContext()); |
| 85 | e2.setParentExpression(null); |
| 86 | exp = e2; |
| 87 | } |
| 88 | if (optimizer.isOptionSet(OptimizerOptions.MISCELLANEOUS)) { |
| 89 | e2 = exp.optimize(visitor, cit); |
| 90 | if (e2 != exp) { |
| 91 | e2.setRetainedStaticContext(exp.getRetainedStaticContext()); |
| 92 | e2.setParentExpression(null); |
| 93 | exp = e2; |
| 94 | } |
| 95 | } |
| 96 | if (optimizer.isOptionSet(OptimizerOptions.LOOP_LIFTING)) { |
| 97 | e2 = LoopLifter.process(exp, visitor, cit); |
| 98 | if (e2 != exp) { |
| 99 | e2.setRetainedStaticContext(exp.getRetainedStaticContext()); |
| 100 | e2.setParentExpression(null); |
| 101 | exp = e2; |
| 102 | } |
| 103 | } |
| 104 | } catch (XPathException err) { |
| 105 | //err.printStackTrace(); |
| 106 | mainModule.reportStaticError(err); |
| 107 | throw err; |
| 108 | } |
| 109 | ExpressionTool.allocateSlots(exp, 0, stackFrameMap); |
| 110 | ExpressionTool.computeEvaluationModesForUserFunctionCalls(exp); |
| 111 | for (GlobalVariable var : getPackageData().getGlobalVariableList()) { |
| 112 | Expression top = var.getSelectExpression(); |
| 113 | if (top != null) { |
| 114 | ExpressionTool.computeEvaluationModesForUserFunctionCalls(top); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | expression = exp; |
| 119 | executable.setConfiguration(config); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Get the expression wrapped in this XQueryExpression object |
| 124 | * |
| 125 | * @return the underlying expression |
| 126 | */ |
| 127 | |
| 128 | public Expression getExpression() { |
| 129 | return expression; |
| 130 | } |
| 131 | |
| 132 | /** |
| 133 | * Get data about the unit of compilation (XQuery module, XSLT package) to which this |
| 134 | * container belongs |
| 135 | */ |
| 136 | public PackageData getPackageData() { |
| 137 | return mainModule.getPackageData(); |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Get the Configuration to which this Container belongs |
| 142 | * |
| 143 | * @return the Configuration |
| 144 | */ |
| 145 | public Configuration getConfiguration() { |
| 146 | return mainModule.getConfiguration(); |
| 147 | } |
| 148 | |
| 149 | /** |
| 150 | * Ask whether this query uses the context item |
| 151 | * |
| 152 | * @return true if the context item is referenced either in the query body or in the initializer |
| 153 | * of any global variable |
| 154 | */ |
| 155 | |
| 156 | public boolean usesContextItem() { |
| 157 | if (ExpressionTool.dependsOnFocus(expression)) { |
| 158 | return true; |
| 159 | } |
| 160 | List<GlobalVariable> map = getPackageData().getGlobalVariableList(); |
| 161 | if (map != null) { |
| 162 | for (GlobalVariable var : map) { |
| 163 | Expression select = var.getSelectExpression(); |
| 164 | if (select != null && ExpressionTool.dependsOnFocus(select)) { |
| 165 | return true; |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | return false; |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * Ask whether this is an update query |
| 174 | * |
| 175 | * @return true if the body of the query is an updating expression |
| 176 | * (as defined by the XQuery Update specification). Note that a query can use Update syntax |
| 177 | * (notably the copy-modify syntax) without being an updating expression. |
| 178 | */ |
| 179 | |
| 180 | public boolean isUpdateQuery() { |
| 181 | return false; |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * Get the stack frame map used for the outermost level of this query |
| 186 | * |
| 187 | * @return the stack frame map |
| 188 | */ |
| 189 | |
| 190 | public SlotManager getStackFrameMap() { |
| 191 | return stackFrameMap; |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Output the path map of the query for diagnostics |
| 196 | */ |
| 197 | |
| 198 | public void explainPathMap() { |
| 199 | // No action (requires Saxon-EE) |
| 200 | } |
| 201 | |
| 202 | /** |
| 203 | * Get the static context in which this expression was compiled. This is essentially an internal |
| 204 | * copy of the original user-created StaticQueryContext object, augmented with information obtained |
| 205 | * from the query prolog of the main query module, and with information about functions and variables |
| 206 | * imported from other library modules. The user-created StaticQueryContext object is not modified |
| 207 | * by Saxon, whereas the QueryModule object includes additional information found in the query prolog. |
| 208 | * |
| 209 | * @return the QueryModule object representing the static context of the main module of the query. |
| 210 | * This is available for inspection, but must not be modified or reused by the application. |
| 211 | */ |
| 212 | public QueryModule getMainModule() { |
| 213 | return mainModule; |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Get a list containing the names of the external variables in the query. |
| 218 | * <p><i>Changed in Saxon 9.0 to return an array of StructuredQName objects rather than |
| 219 | * integer fingerprints.</i></p> |
| 220 | * |
| 221 | * @return an array of StructuredQName objects, representing the names of external variables defined |
| 222 | * in the query |
| 223 | */ |
| 224 | |
| 225 | /*@NotNull*/ |
| 226 | public StructuredQName[] getExternalVariableNames() { |
| 227 | List list = stackFrameMap.getVariableMap(); |
| 228 | StructuredQName[] names = new StructuredQName[stackFrameMap.getNumberOfVariables()]; |
| 229 | for (int i = 0; i < names.length; i++) { |
| 230 | names[i] = (StructuredQName) list.get(i); |
| 231 | } |
| 232 | return names; |
| 233 | } |
| 234 | |
| 235 | /** |
| 236 | * Execute a the compiled Query, returning the results as a List of objects |
| 237 | * obtained by converting the items in the query result to the nearest appropriate |
| 238 | * Java type |
| 239 | * |
| 240 | * @param env Provides the dynamic query evaluation context |
| 241 | * @return The results of the expression, as a List. The List represents the sequence |
| 242 | * of items returned by the expression. Each item in the list will either be an |
| 243 | * object representing a node, or an object representing an atomic value. |
| 244 | * For the types of Java object that may be returned, see the description of the |
| 245 | * {@link net.sf.saxon.xpath.XPathEvaluator#evaluate} method |
| 246 | * of class XPathProcessor |
| 247 | * @throws XPathException if a dynamic error occurs during query evaluation |
| 248 | */ |
| 249 | |
| 250 | /*@NotNull*/ |
| 251 | public List<Object> evaluate(/*@NotNull*/ DynamicQueryContext env) throws XPathException { |
| 252 | if (isUpdateQuery()) { |
| 253 | throw new XPathException("Cannot call evaluate() on an updating query"); |
| 254 | } |
| 255 | ArrayList<Object> list = new ArrayList<>(100); |
| 256 | iterator(env).forEachOrFail(item -> list.add(SequenceTool.convertToJava(item))); |
| 257 | return list; |
| 258 | } |
| 259 | |
| 260 | /** |
| 261 | * Execute the compiled Query, returning the first item in the result. |
| 262 | * This is useful where it is known that the expression will only return |
| 263 | * a singleton value (for example, a single node, or a boolean). |
| 264 | * |
| 265 | * @param env Provides the dynamic query evaluation context |
| 266 | * @return The first item in the sequence returned by the expression. If the expression |
| 267 | * returns an empty sequence, this method returns null. Otherwise, it returns the first |
| 268 | * item in the result sequence, represented as a Java object using the same mapping as for |
| 269 | * the {@link XQueryExpression#evaluate} method |
| 270 | * @throws XPathException if evaluation fails with a dynamic error |
| 271 | */ |
| 272 | |
| 273 | /*@Nullable*/ |
| 274 | public Object evaluateSingle(/*@NotNull*/ DynamicQueryContext env) throws XPathException { |
| 275 | if (isUpdateQuery()) { |
| 276 | throw new XPathException("Cannot call evaluateSingle() on an updating query"); |
| 277 | } |
| 278 | SequenceIterator iterator = iterator(env); |
| 279 | Item item = iterator.next(); |
| 280 | if (item == null) { |
| 281 | return null; |
| 282 | } |
| 283 | return SequenceTool.convertToJava(item); |
| 284 | } |
| 285 | |
| 286 | /** |
| 287 | * Get an iterator over the results of the expression. This returns results without |
| 288 | * any conversion of the returned items to "native" Java classes. The iterator will |
| 289 | * deliver a sequence of Item objects, each item being either a NodeInfo (representing |
| 290 | * a node) or an AtomicValue (representing an atomic value). |
| 291 | * <p>To get the results of the query in the form of an XML document in which each |
| 292 | * item is wrapped by an element indicating its type, use:</p> |
| 293 | * <p><code>QueryResult.wrap(iterator(env))</code></p> |
| 294 | * <p>To serialize the results to a file, use the QueryResult.serialize() method.</p> |
| 295 | * |
| 296 | * @param env Provides the dynamic query evaluation context |
| 297 | * @return an iterator over the results of the query. The class SequenceIterator |
| 298 | * is modeled on the standard Java Iterator class, but has extra functionality |
| 299 | * and can throw exceptions when errors occur. |
| 300 | * @throws XPathException if a dynamic error occurs in evaluating the query. Some |
| 301 | * dynamic errors will not be reported by this method, but will only be reported |
| 302 | * when the individual items of the result are accessed using the returned iterator. |
| 303 | */ |
| 304 | |
| 305 | /*@NotNull*/ |
| 306 | public SequenceIterator<?> iterator(/*@NotNull*/ DynamicQueryContext env) throws XPathException { |
| 307 | if (isUpdateQuery()) { |
| 308 | throw new XPathException("Cannot call iterator() on an updating query"); |
| 309 | } |
| 310 | if (!env.getConfiguration().isCompatible(getExecutable().getConfiguration())) { |
| 311 | throw new XPathException("The query must be compiled and executed under the same Configuration", SaxonErrorCode.SXXP0004); |
| 312 | } |
| 313 | Controller controller = newController(env); |
| 314 | |
| 315 | try { |
| 316 | Item contextItem = controller.getGlobalContextItem(); |
| 317 | if (contextItem instanceof NodeInfo && ((NodeInfo)contextItem).getTreeInfo().isTyped() && !getExecutable().isSchemaAware()) { |
| 318 | throw new XPathException("A typed input document can only be used with a schema-aware query"); |
| 319 | } |
| 320 | |
| 321 | XPathContextMajor context = initialContext(env, controller); |
| 322 | |
| 323 | // In tracing/debugging mode, evaluate all the global variables first |
| 324 | if (controller.getTraceListener() != null) { |
| 325 | controller.preEvaluateGlobals(context); |
| 326 | } |
| 327 | |
| 328 | context.openStackFrame(stackFrameMap); |
| 329 | |
| 330 | SequenceIterator<?> iterator = expression.iterate(context); |
| 331 | if ((iterator.getProperties() & SequenceIterator.GROUNDED) != 0) { |
| 332 | return iterator; |
| 333 | } else { |
| 334 | return new ErrorReportingIterator<>(iterator, controller.getErrorListener()); |
| 335 | } |
| 336 | } catch (XPathException err) { |
| 337 | TransformerException terr = err; |
| 338 | while (terr.getException() instanceof TransformerException) { |
| 339 | terr = (TransformerException) terr.getException(); |
| 340 | } |
| 341 | XPathException de = XPathException.makeXPathException(terr); |
| 342 | controller.reportFatalError(de); |
| 343 | throw de; |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Run the query, sending the results directly to a JAXP Result object. This way of executing |
| 349 | * the query is most efficient in the case of queries that produce a single document (or parentless |
| 350 | * element) as their output, because it avoids constructing the result tree in memory: instead, |
| 351 | * it is piped straight to the serializer. |
| 352 | * |
| 353 | * <p>If the output method specified in the outputProperties, or declared in the query itself, is |
| 354 | * one of XML, HTML, XHTML, or TEXT, or if it is defaulted to XML, then the query is implicitly |
| 355 | * wrapped in a document node constructor to implement the "sequence normalization" phase described |
| 356 | * in the Serialization specification. If the output method is JSON or ADAPTIVE then this phase |
| 357 | * is skipped and the items produced by the query are piped straight into the serializer.</p> |
| 358 | * |
| 359 | * @param env the dynamic query context |
| 360 | * @param result the destination for the results of the query. The query is effectively wrapped |
| 361 | * in a document{} constructor, so that the items in the result are concatenated to form a single |
| 362 | * document; this is then written to the requested Result destination, which may be (for example) |
| 363 | * a DOMResult, a SAXResult, or a StreamResult |
| 364 | * @param outputProperties Supplies serialization properties, in JAXP format, if the result is to |
| 365 | * be serialized. This parameter can be defaulted to null. |
| 366 | * @throws XPathException if the query fails. |
| 367 | */ |
| 368 | |
| 369 | public void run(/*@NotNull*/ DynamicQueryContext env, Result result, Properties outputProperties) throws XPathException { |
| 370 | if (isUpdateQuery()) { |
| 371 | throw new XPathException("Cannot call run() on an updating query"); |
| 372 | } |
| 373 | if (!env.getConfiguration().isCompatible(getExecutable().getConfiguration())) { |
| 374 | throw new XPathException("The query must be compiled and executed under the same Configuration", SaxonErrorCode.SXXP0004); |
| 375 | } |
| 376 | Item contextItem = env.getContextItem(); |
| 377 | if (contextItem instanceof NodeInfo && ((NodeInfo) contextItem).getTreeInfo().isTyped() && !getExecutable().isSchemaAware()) { |
| 378 | throw new XPathException("A typed input document can only be used with a schema-aware query"); |
| 379 | } |
| 380 | Controller controller = newController(env); |
| 381 | if (result instanceof Receiver) { |
| 382 | ((Receiver)result).getPipelineConfiguration().setController(controller); |
| 383 | } |
| 384 | |
| 385 | Properties actualProperties = validateOutputProperties(controller, outputProperties); |
| 386 | |
| 387 | //controller.defineGlobalParameters(); |
| 388 | |
| 389 | XPathContextMajor context = initialContext(env, controller); |
| 390 | |
| 391 | // In tracing/debugging mode, evaluate all the global variables first |
| 392 | TraceListener tracer = controller.getTraceListener(); |
| 393 | if (tracer != null) { |
| 394 | controller.preEvaluateGlobals(context); |
| 395 | //tracer.open(controller); |
| 396 | } |
| 397 | |
| 398 | context.openStackFrame(stackFrameMap); |
| 399 | |
| 400 | boolean mustClose = result instanceof StreamResult && ((StreamResult) result).getOutputStream() == null; |
| 401 | Receiver out; |
| 402 | if (result instanceof Receiver) { |
| 403 | out = (Receiver)result; |
| 404 | } else { |
| 405 | SerializerFactory sf = context.getConfiguration().getSerializerFactory(); |
| 406 | PipelineConfiguration pipe = controller.makePipelineConfiguration(); |
| 407 | pipe.setHostLanguage(Configuration.XQUERY); |
| 408 | out = sf.getReceiver(result, new SerializationProperties(actualProperties), pipe); |
| 409 | |
| 410 | // String itemSeparator = actualProperties.getProperty(SaxonOutputKeys.ITEM_SEPARATOR); |
| 411 | // if (out instanceof ComplexContentOutputter && itemSeparator != null) { |
| 412 | // out = new SequenceNormalizer(out, itemSeparator); |
| 413 | // context.setReceiver(out); |
| 414 | // } |
| 415 | } |
| 416 | |
| 417 | NamespaceReducer nr = new NamespaceReducer(out); |
| 418 | out = new ComplexContentOutputter(nr); |
| 419 | |
| 420 | context.setReceiver(out); |
| 421 | out.open(); |
| 422 | |
| 423 | // Run the query |
| 424 | try { |
| 425 | expression.process(context); |
| 426 | } catch (XPathException err) { |
| 427 | controller.reportFatalError(err); |
| 428 | throw err; |
| 429 | } finally { |
| 430 | try { |
| 431 | if (tracer != null) { |
| 432 | tracer.close(); |
| 433 | } |
| 434 | out.close(); |
| 435 | } catch (XPathException e) { |
| 436 | e.printStackTrace(); |
| 437 | } |
| 438 | } |
| 439 | if (result instanceof StreamResult) { |
| 440 | closeStreamIfNecessary((StreamResult) result, mustClose); |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | protected void closeStreamIfNecessary(StreamResult result, boolean mustClose) throws XPathException { |
| 445 | if (mustClose) { |
| 446 | OutputStream os = result.getOutputStream(); |
| 447 | if (os != null) { |
| 448 | try { |
| 449 | os.close(); |
| 450 | } catch (java.io.IOException err) { |
| 451 | throw new XPathException(err); |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | /** |
| 458 | * Run the query in streaming mode, assuming it has been compiled for streaming. |
| 459 | * This requires Saxon-EE. |
| 460 | * @param dynamicEnv the dynamic execution context |
| 461 | * @param source the input document, as a SAXSource or StreamSource |
| 462 | * @param result the destination for the query results |
| 463 | * @param outputProperties serialization options for the query result |
| 464 | * @throws XPathException if streamed evaluation of the query fails |
| 465 | */ |
| 466 | |
| 467 | public void runStreamed(DynamicQueryContext dynamicEnv, Source source, Result result, Properties outputProperties) throws XPathException { |
| 468 | throw new XPathException("Streaming requires Saxon-EE"); |
| 469 | } |
| 470 | |
| 471 | /** |
| 472 | * Validate the serialization properties requested; any problems result in warnings being output |
| 473 | * @param controller The query controller |
| 474 | * @param outputProperties the requested serialization properties (may be null) |
| 475 | * @return the properties after validation and normalization |
| 476 | */ |
| 477 | |
| 478 | protected Properties validateOutputProperties(Controller controller, /*@Nullable*/ Properties outputProperties) { |
| 479 | // Validate the serialization properties requested |
| 480 | |
| 481 | Properties baseProperties = controller.getExecutable().getPrimarySerializationProperties().getProperties(); |
| 482 | SerializerFactory sf = controller.getConfiguration().getSerializerFactory(); |
| 483 | if (outputProperties != null) { |
| 484 | Enumeration iter = outputProperties.propertyNames(); |
| 485 | while (iter.hasMoreElements()) { |
| 486 | String key = (String) iter.nextElement(); |
| 487 | String value = outputProperties.getProperty(key); |
| 488 | try { |
| 489 | value = sf.checkOutputProperty(key, value); |
| 490 | baseProperties.setProperty(key, value); |
| 491 | } catch (XPathException dynamicError) { |
| 492 | outputProperties.remove(key); |
| 493 | controller.getErrorListener().warning(dynamicError); |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | if (baseProperties.getProperty("method") == null) { |
| 498 | // XQuery forces the default method to XML, unlike XSLT where it depends on the contents of the result tree |
| 499 | baseProperties.setProperty("method", "xml"); |
| 500 | } |
| 501 | return baseProperties; |
| 502 | } |
| 503 | |
| 504 | /** |
| 505 | * Run the query in pull mode. From Saxon 9.8 this method is identical to {@link #run(DynamicQueryContext, Result, Properties)} |
| 506 | * |
| 507 | * @param dynamicEnv the dynamic context for query evaluation |
| 508 | * @param destination the Receiver to accept the query results *usually a serializer) |
| 509 | * @throws XPathException if a dynamic error occurs during the evaluation |
| 510 | * @deprecated since 9.8. |
| 511 | */ |
| 512 | |
| 513 | public void pull(/*@NotNull*/ DynamicQueryContext dynamicEnv, /*@NotNull*/ Result destination, Properties outputProperties) throws XPathException { |
| 514 | run(dynamicEnv, destination, outputProperties); |
| 515 | } |
| 516 | |
| 517 | /** |
| 518 | * Run the query in pull mode. From Saxon 9.8 this method is identical to {@link #run(DynamicQueryContext, Result, Properties)} |
| 519 | * (supplying the default serialization properties from the configuration as the third argument) |
| 520 | * @param dynamicEnv the dynamic context for query evaluation |
| 521 | * @param destination the Receiver to accept the query results *usually a serializer) |
| 522 | * @throws XPathException if a dynamic error occurs during the evaluation |
| 523 | * @deprecated since 9.8. |
| 524 | */ |
| 525 | |
| 526 | public void pull(DynamicQueryContext dynamicEnv, SequenceReceiver destination) throws XPathException { |
| 527 | run(dynamicEnv, destination, getConfiguration().getDefaultSerializationProperties()); |
| 528 | } |
| 529 | |
| 530 | /** |
| 531 | * Run an updating query |
| 532 | * |
| 533 | * @param dynamicEnv the dynamic context for query execution |
| 534 | * @return a set of nodes representing the roots of trees that have been modified as a result |
| 535 | * of executing the update. Note that this method will never modify persistent data on disk; it returns |
| 536 | * the root nodes of the affected documents (which will often be document nodes whose document-uri can |
| 537 | * be ascertained), and it is the caller's responsibility to decide what to do with them. |
| 538 | * <p>On completion of this method it is generally unsafe to rely on the contents or relationships |
| 539 | * of NodeInfo objects that were obtained before the updating query was run. Such objects may or may not |
| 540 | * reflect the results of the update operations. This is especially true in the case of nodes that |
| 541 | * are part of a subtree that has been deleted (detached from its parent). Instead, the new updated |
| 542 | * tree should be accessed by navigation from the root nodes returned by this method.</p> |
| 543 | * @throws XPathException if evaluation of the update query fails, or it this is not an updating query |
| 544 | */ |
| 545 | |
| 546 | /*@NotNull*/ |
| 547 | public Set<MutableNodeInfo> runUpdate(/*@NotNull*/ DynamicQueryContext dynamicEnv) throws XPathException { |
| 548 | throw new XPathException("Calling runUpdate() on a non-updating query"); |
| 549 | } |
| 550 | |
| 551 | /** |
| 552 | * Run an updating query, writing back eligible updated node to persistent storage. |
| 553 | * <p>A node is eligible to be written back to disk if it is present in the document pool, |
| 554 | * which generally means that it was originally read using the doc() or collection() function.</p> |
| 555 | * <p>On completion of this method it is generally unsafe to rely on the contents or relationships |
| 556 | * of NodeInfo objects that were obtained before the updating query was run. Such objects may or may not |
| 557 | * reflect the results of the update operations. This is especially true in the case of nodes that |
| 558 | * are part of a subtree that has been deleted (detached from its parent). Instead, the new updated |
| 559 | * tree should be accessed by navigation from the root nodes returned by this method.</p> |
| 560 | * <p>If one or more eligible updated nodes cannot be written back to disk, perhaps because the URI |
| 561 | * identifies a non-updatable location, then an exception is thrown. In this case it is undefined</p> |
| 562 | * |
| 563 | * @param dynamicEnv the dynamic context for query execution |
| 564 | * @param agent a callback class that is called to process each document updated by the query |
| 565 | * @throws XPathException if evaluation of the update query fails, or it this is not an updating query |
| 566 | */ |
| 567 | |
| 568 | public void runUpdate(/*@NotNull*/ DynamicQueryContext dynamicEnv, /*@NotNull*/ UpdateAgent agent) throws XPathException { |
| 569 | throw new XPathException("Calling runUpdate() on a non-updating query"); |
| 570 | } |
| 571 | |
| 572 | |
| 573 | protected XPathContextMajor initialContext(DynamicQueryContext dynamicEnv, Controller controller) throws XPathException { |
| 574 | |
| 575 | Item<?> contextItem = controller.getGlobalContextItem(); |
| 576 | XPathContextMajor context = controller.newXPathContext(); |
| 577 | |
| 578 | if (contextItem != null) { |
| 579 | ManualIterator<Item<?>> single = new ManualIterator<>(contextItem); |
| 580 | context.setCurrentIterator(single); |
| 581 | controller.setGlobalContextItem(contextItem); |
| 582 | } |
| 583 | return context; |
| 584 | } |
| 585 | |
| 586 | /** |
| 587 | * Get a controller that can be used to execute functions in this compiled query. |
| 588 | * Functions in the query module can be found using {@link QueryModule#getUserDefinedFunction}. |
| 589 | * They can then be called directly from the Java application using {@link net.sf.saxon.expr.instruct.UserFunction#call} |
| 590 | * The same Controller can be used for a series of function calls. Note that the Controller should only be used |
| 591 | * in a single thread. |
| 592 | * @param env the dynamic context for evaluation |
| 593 | * @return a newly constructed Controller |
| 594 | * @throws XPathException if evaluation fails with a dynamic error |
| 595 | */ |
| 596 | |
| 597 | /*@NotNull*/ |
| 598 | public Controller newController(DynamicQueryContext env) throws XPathException { |
| 599 | Controller controller = new Controller(executable.getConfiguration(), executable); |
| 600 | env.initializeController(controller); |
| 601 | //controller.getBindery(getPackageData()).allocateGlobals(executable.getGlobalVariableMap()); |
| 602 | return controller; |
| 603 | } |
| 604 | |
| 605 | /** |
| 606 | * Diagnostic method: display a representation of the compiled query on the |
| 607 | * selected output stream. |
| 608 | * |
| 609 | * @param out an ExpressionPresenter to which the XML representation of the compiled query |
| 610 | * will be sent |
| 611 | */ |
| 612 | |
| 613 | public void explain(/*@NotNull*/ ExpressionPresenter out) throws XPathException { |
| 614 | out.startElement("query"); |
| 615 | mainModule.getKeyManager().exportKeys(out, null); |
| 616 | getExecutable().explainGlobalVariables(out); |
| 617 | mainModule.explainGlobalFunctions(out); |
| 618 | out.startElement("body"); |
| 619 | expression.export(out); |
| 620 | out.endElement(); |
| 621 | out.endElement(); |
| 622 | out.close(); |
| 623 | } |
| 624 | |
| 625 | /** |
| 626 | * Get the Executable (representing a complete stylesheet or query) of which this Container forms part |
| 627 | * @return the Executable |
| 628 | */ |
| 629 | |
| 630 | public Executable getExecutable() { |
| 631 | return executable; |
| 632 | } |
| 633 | |
| 634 | /** |
| 635 | * Indicate that document projection is or is not allowed |
| 636 | * |
| 637 | * @param allowed true if projection is allowed |
| 638 | */ |
| 639 | |
| 640 | public void setAllowDocumentProjection(boolean allowed) { |
| 641 | if (allowed) { |
| 642 | throw new UnsupportedOperationException("Document projection requires Saxon-EE"); |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | /** |
| 647 | * Ask whether document projection is allowed |
| 648 | * |
| 649 | * @return true if document projection is allowed |
| 650 | */ |
| 651 | |
| 652 | public boolean isDocumentProjectionAllowed() { |
| 653 | return false; |
| 654 | } |
| 655 | |
| 656 | /** |
| 657 | * Return the public identifier for the current document event. |
| 658 | * <p>The return value is the public identifier of the document |
| 659 | * entity or of the external parsed entity in which the markup that |
| 660 | * triggered the event appears.</p> |
| 661 | * |
| 662 | * @return A string containing the public identifier, or |
| 663 | * null if none is available. |
| 664 | * @see #getSystemId |
| 665 | */ |
| 666 | /*@Nullable*/ |
| 667 | public String getPublicId() { |
| 668 | return null; |
| 669 | } |
| 670 | |
| 671 | /** |
| 672 | * Return the system identifier for the current document event. |
| 673 | * <p>The return value is the system identifier of the document |
| 674 | * entity or of the external parsed entity in which the markup that |
| 675 | * triggered the event appears.</p> |
| 676 | * <p>If the system identifier is a URL, the parser must resolve it |
| 677 | * fully before passing it to the application.</p> |
| 678 | * |
| 679 | * @return A string containing the system identifier, or null |
| 680 | * if none is available. |
| 681 | * @see #getPublicId |
| 682 | */ |
| 683 | /*@Nullable*/ |
| 684 | public String getSystemId() { |
| 685 | return mainModule.getSystemId(); |
| 686 | } |
| 687 | |
| 688 | /** |
| 689 | * Return the line number where the current document event ends. |
| 690 | * <p><strong>Warning:</strong> The return value from the method |
| 691 | * is intended only as an approximation for the sake of error |
| 692 | * reporting; it is not intended to provide sufficient information |
| 693 | * to edit the character content of the original XML document.</p> |
| 694 | * <p>The return value is an approximation of the line number |
| 695 | * in the document entity or external parsed entity where the |
| 696 | * markup that triggered the event appears.</p> |
| 697 | * |
| 698 | * @return The line number, or -1 if none is available. |
| 699 | * @see #getColumnNumber |
| 700 | */ |
| 701 | public int getLineNumber() { |
| 702 | return -1; |
| 703 | } |
| 704 | |
| 705 | /** |
| 706 | * Return the character position where the current document event ends. |
| 707 | * <p><strong>Warning:</strong> The return value from the method |
| 708 | * is intended only as an approximation for the sake of error |
| 709 | * reporting; it is not intended to provide sufficient information |
| 710 | * to edit the character content of the original XML document.</p> |
| 711 | * <p>The return value is an approximation of the column number |
| 712 | * in the document entity or external parsed entity where the |
| 713 | * markup that triggered the event appears.</p> |
| 714 | * |
| 715 | * @return The column number, or -1 if none is available. |
| 716 | * @see #getLineNumber |
| 717 | */ |
| 718 | public int getColumnNumber() { |
| 719 | return -1; |
| 720 | } |
| 721 | |
| 722 | /** |
| 723 | * Get an immutable copy of this Location object. By default Location objects may be mutable, so they |
| 724 | * should not be saved for later use. The result of this operation holds the same location information, |
| 725 | * but in an immutable form. |
| 726 | */ |
| 727 | public Location saveLocation() { |
| 728 | return this; |
| 729 | } |
| 730 | |
| 731 | /** |
| 732 | * Get the host language (XSLT, XQuery, XPath) used to implement the code in this container |
| 733 | * |
| 734 | * @return typically {@link net.sf.saxon.Configuration#XSLT} or {@link net.sf.saxon.Configuration#XQUERY} |
| 735 | */ |
| 736 | |
| 737 | public int getHostLanguage() { |
| 738 | return Configuration.XQUERY; |
| 739 | } |
| 740 | |
| 741 | public void setChildExpression(Expression expr) { |
| 742 | expression = expr; |
| 743 | } |
| 744 | |
| 745 | /** |
| 746 | * ErrorReportingIterator is an iterator that wraps a base iterator and reports |
| 747 | * any exceptions that are raised to the ErrorListener |
| 748 | */ |
| 749 | |
| 750 | private class ErrorReportingIterator<T extends Item<?>> implements SequenceIterator<T> { |
| 751 | private SequenceIterator<T> base; |
| 752 | private UnfailingErrorListener listener; |
| 753 | |
| 754 | public ErrorReportingIterator(SequenceIterator<T> base, UnfailingErrorListener listener) { |
| 755 | this.base = base; |
| 756 | this.listener = listener; |
| 757 | } |
| 758 | |
| 759 | /*@Nullable*/ |
| 760 | public T next() throws XPathException { |
| 761 | try { |
| 762 | return base.next(); |
| 763 | } catch (XPathException e1) { |
| 764 | e1.maybeSetLocation(expression.getLocation()); |
| 765 | listener.fatalError(e1); |
| 766 | e1.setHasBeenReported(true); |
| 767 | throw e1; |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | public void close() { |
| 772 | base.close(); |
| 773 | } |
| 774 | |
| 775 | /** |
| 776 | * Get properties of this iterator, as a bit-significant integer. |
| 777 | * |
| 778 | * @return the properties of this iterator. This will be some combination of |
| 779 | * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER}, |
| 780 | * and {@link #LOOKAHEAD}. It is always |
| 781 | * acceptable to return the value zero, indicating that there are no known special properties. |
| 782 | * It is acceptable for the properties of the iterator to change depending on its state. |
| 783 | */ |
| 784 | |
| 785 | public int getProperties() { |
| 786 | return 0; |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | } |
| 791 |