Debian Codegraph @

net/sf/saxon/s9api/XQueryCompiler.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.expr.parser.OptimizerOptions;
12 import net.sf.saxon.lib.ErrorGatherer;
13 import net.sf.saxon.lib.ModuleURIResolver;
14 import net.sf.saxon.lib.StringCollator;
15 import net.sf.saxon.pattern.NodeKindTest;
16 import net.sf.saxon.query.StaticQueryContext;
17 import net.sf.saxon.trans.XPathException;
18
19 import javax.xml.transform.ErrorListener;
20 import java.io.*;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.util.List;
24
25 /**
26 * An XQueryCompiler object allows XQuery 1.0 queries to be compiled. The compiler holds information that
27 * represents the static context for the compilation.
28 * <p>To construct an XQueryCompiler, use the factory method {@link Processor#newXQueryCompiler}.</p>
29 * <p>An XQueryCompiler may be used repeatedly to compile multiple queries. Any changes made to the
30 * XQueryCompiler (that is, to the static context) do not affect queries that have already been compiled.
31 * An XQueryCompiler may in principle be used concurrently in multiple threads, but in practice this
32 * is best avoided because all instances will share the same ErrorListener and it will therefore be
33 * difficult to establish which error messages are associated with each compilation.</p>
34 *
35 * @since 9.0
36 */
37
38 public class XQueryCompiler {
39
40 private Processor processor;
41 private StaticQueryContext env;
42 private ItemType requiredContextItemType;
43 private String encoding;
44
45 /**
46 * Protected constructor
47 *
48 * @param processor the Saxon Processor
49 */
50
51 protected XQueryCompiler(Processor processor) {
52 this.processor = processor;
53 this.env = processor.getUnderlyingConfiguration().newStaticQueryContext();
54 }
55
56 /**
57 * Get the Processor from which this XQueryCompiler was constructed
58 *
59 * @return the Processor to which this XQueryCompiler belongs
60 * @since 9.3
61 */
62
63 public Processor getProcessor() {
64 return processor;
65 }
66
67 /**
68 * Set the static base URI for the query
69 *
70 * @param baseURI the static base URI; or null to indicate that no base URI is available
71 */
72
73 public void setBaseURI(URI baseURI) {
74 if (baseURI == null) {
75 env.setBaseURI(null);
76 } else {
77 if (!baseURI.isAbsolute()) {
78 throw new IllegalArgumentException("Base URI must be an absolute URI: " + baseURI);
79 }
80 env.setBaseURI(baseURI.toString());
81 }
82 }
83
84 /**
85 * Get the static base URI for the query
86 *
87 * @return the static base URI
88 */
89
90 public URI getBaseURI() {
91 try {
92 return new URI(env.getBaseURI());
93 } catch (URISyntaxException err) {
94 throw new IllegalStateException(err);
95 }
96 }
97
98 /**
99 * Set the ErrorListener to be used during this query compilation episode
100 *
101 * @param listener The error listener to be used. This is notified of all errors detected during the
102 * compilation. Static errors (as defined in the XQuery specification) are notified
103 * to the {@link ErrorListener#fatalError(javax.xml.transform.TransformerException)} method.
104 * Warnings are notified to the {@link ErrorListener#warning(javax.xml.transform.TransformerException)}.
105 * Any exception thrown by these methods is ignored.
106 */
107
108 public void setErrorListener(ErrorListener listener) {
109 env.setErrorListener(listener);
110 }
111
112 /**
113 * Get the ErrorListener being used during this compilation episode
114 *
115 * @return listener The error listener in use. This is notified of all errors detected during the
116 * compilation. If no user-supplied ErrorListener has been set, returns the system-supplied
117 * ErrorListener.
118 */
119
120 public ErrorListener getErrorListener() {
121 return env.getErrorListener();
122 }
123
124 /**
125 * Set whether trace hooks are to be included in the compiled code. To use tracing, it is necessary
126 * both to compile the code with trace hooks included, and to supply a TraceListener at run-time
127 *
128 * @param option true if trace code is to be compiled in, false otherwise
129 */
130
131 public void setCompileWithTracing(boolean option) {
132 env.setCompileWithTracing(option);
133 }
134
135 /**
136 * Ask whether trace hooks are included in the compiled code.
137 *
138 * @return true if trace hooks are included, false if not.
139 */
140
141 public boolean isCompileWithTracing() {
142 return env.isCompileWithTracing();
143 }
144
145 /**
146 * Set a user-defined ModuleURIResolver for resolving URIs used in <code>import module</code>
147 * declarations in the XQuery prolog.
148 * This will override any ModuleURIResolver that was specified as part of the configuration.
149 *
150 * @param resolver the ModuleURIResolver to be used
151 */
152
153 public void setModuleURIResolver(ModuleURIResolver resolver) {
154 env.setModuleURIResolver(resolver);
155 }
156
157 /**
158 * Get the user-defined ModuleURIResolver for resolving URIs used in <code>import module</code>
159 * declarations in the XQuery prolog; returns null if none has been explicitly set either
160 * here or in the Saxon Configuration.
161 *
162 * @return the registered ModuleURIResolver
163 */
164
165 /*@Nullable*/
166 public ModuleURIResolver getModuleURIResolver() {
167 return env.getModuleURIResolver();
168 }
169
170 /**
171 * Set the encoding of the supplied query. This is ignored if the query is supplied
172 * in character form, that is, as a <code>String</code> or as a <code>Reader</code>. If no value
173 * is set, the query processor will attempt to infer the encoding, defaulting to UTF-8 if no
174 * information is available.
175 *
176 * @param encoding the encoding of the supplied query, for example "iso-8859-1"
177 * @since 9.1
178 */
179
180 public void setEncoding(String encoding) {
181 this.encoding = encoding;
182 }
183
184 /**
185 * Get the encoding previously set for the supplied query.
186 *
187 * @return the encoding previously set using {@link #setEncoding(String)}, or null
188 * if no value has been set. Note that this is not necessarily the actual encoding of the query.
189 * @since 9.2
190 */
191
192 public String getEncoding() {
193 return encoding;
194 }
195
196 /**
197 * Say whether the query is allowed to be updating. XQuery update syntax will be rejected
198 * during query compilation unless this flag is set. XQuery Update is supported only under Saxon-EE.
199 *
200 * @param updating true if the query is allowed to use the XQuery Update facility
201 * (requires Saxon-EE). If set to false, the query must not be an updating query. If set
202 * to true, it may be either an updating or a non-updating query.
203 * @throws UnsupportedOperationException if updating is requested and the Saxon Configuration does
204 * not support updating, either because it is not an EnterpriseConfiguration, or because no license
205 * key is available.
206 * @since 9.1
207 */
208
209 public void setUpdatingEnabled(boolean updating) {
210 if (updating && !env.getConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY)) {
211 throw new UnsupportedOperationException("XQuery Update is not supported in this Saxon Configuration");
212 }
213 env.setUpdatingEnabled(updating);
214 }
215
216 /**
217 * Ask whether the query is allowed to use XQuery Update syntax
218 *
219 * @return true if the query is allowed to use the XQuery Update facility. Note that this
220 * does not necessarily mean that the query is an updating query; but if the value is false,
221 * then it must definitely be non-updating.
222 * @since 9.1
223 */
224
225 public boolean isUpdatingEnabled() {
226 return env.isUpdatingEnabled();
227 }
228
229 /**
230 * Say that the query must be compiled to be schema-aware, even if it contains no
231 * "import schema" declarations. Normally a query is treated as schema-aware
232 * only if it contains one or more "import schema" declarations. If it is not schema-aware,
233 * then all input documents must be untyped (or xs:anyType), and validation of temporary nodes is disallowed
234 * (though validation of the final result tree is permitted). Setting the argument to true
235 * means that schema-aware code will be compiled regardless.
236 *
237 * @param schemaAware If true, the stylesheet will be compiled with schema-awareness
238 * enabled even if it contains no xsl:import-schema declarations. If false, the stylesheet
239 * is treated as schema-aware only if it contains one or more xsl:import-schema declarations.
240 * Note that setting the value to false does not disable use of an import-schema declaration.
241 * @since 9.2
242 */
243
244 public void setSchemaAware(boolean schemaAware) {
245 // We check this again more securely, but it's good to give the error as soon as possible
246 if (schemaAware && !processor.getUnderlyingConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY)) {
247 throw new UnsupportedOperationException("Schema-awareness requires a Saxon-EE license");
248 }
249 env.setSchemaAware(schemaAware);
250 }
251
252 /**
253 * Ask whether schema-awareness has been requested either by means of a call on
254 * {@link #setSchemaAware}
255 *
256 * @return true if schema-awareness has been requested
257 * @since 9.2
258 */
259
260 public boolean isSchemaAware() {
261 return env.isSchemaAware();
262 }
263
264 /**
265 * Say whether the query should be compiled and evaluated to use streaming.
266 * This affects subsequent calls on the compile() methods. This option requires
267 * Saxon-EE.
268 *
269 * @param option if true, the compiler will attempt to compile a query to be
270 * capable of executing in streaming mode. If the query cannot be streamed,
271 * a compile-time exception is reported. In streaming mode, the source
272 * document is supplied as a stream, and no tree is built in memory. The default
273 * is false.
274 * <p>
275 * <p>When setStreaming(true) is specified, this has the additional side-effect of setting the required
276 * context item type to "document-node()"
277 * @since 9.6
278 */
279
280 public void setStreaming(boolean option) {
281 env.setStreaming(option);
282 // We check this again more securely, but it's good to give the error as soon as possible
283 if (option && !processor.getUnderlyingConfiguration().isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XQUERY)) {
284 throw new UnsupportedOperationException("Streaming requires a Saxon-EE license");
285 }
286 if (option) {
287 setRequiredContextItemType(new ConstructedItemType(NodeKindTest.DOCUMENT, getProcessor()));
288 }
289 }
290
291 /**
292 * Ask whether the streaming option has been set, that is, whether
293 * subsequent calls on compile() will compile queries to be capable
294 * of executing in streaming mode.
295 *
296 * @return true if the streaming option has been set.
297 * @since 9.6
298 */
299
300 public boolean isStreaming() {
301 return env.isStreaming();
302 }
303
304 /**
305 * Say whether an XQuery 1.0, 3.0, or 3.1 processor is required.
306 *
307 * @param value Must be "3.1"; any other value is ignored with a warning.
308 * @since 9.2. The handling of different XQuery version numbers has changed in
309 * successive Saxon releases.
310 * @deprecated in 9.8; the only XQuery version supported is "3.1", and any other value is
311 * ignored with a warning.
312 */
313
314 public void setLanguageVersion(String value) {
315 if (!"3.1".equals(value)) {
316 env.getErrorListener().warning(new XPathException("XQuery version ignored: only \"3.1\" is recognized"));
317 }
318 env.setLanguageVersion(31);
319 }
320
321 /**
322 * Ask whether an XQuery 1.0 or XQuery 3.0 or XQuery 3.1 processor is being used
323 *
324 * @return always "3.1" in the current Saxon release.
325 * @since 9.2. From Saxon 9.8, only XQuery 3.1 is supported
326 */
327
328 public String getLanguageVersion() {
329 return "3.1";
330 }
331
332 /**
333 * Declare a namespace binding as part of the static context for queries compiled using this
334 * XQueryCompiler. This binding may be overridden by a binding that appears in the query prolog.
335 * The namespace binding will form part of the static context of the query, but it will not be copied
336 * into result trees unless the prefix is actually used in an element or attribute name.
337 *
338 * @param prefix The namespace prefix. If the value is a zero-length string, this method sets the default
339 * namespace for elements and types.
340 * @param uri The namespace URI. It is possible to specify a zero-length string to "undeclare" a namespace;
341 * in this case the prefix will not be available for use, except in the case where the prefix
342 * is also a zero length string, in which case the absence of a prefix implies that the name
343 * is in no namespace.
344 * @throws NullPointerException if either the prefix or uri is null.
345 * @throws IllegalArgumentException in the event of an invalid declaration of the XML namespace
346 */
347
348 public void declareNamespace(String prefix, String uri) {
349 env.declareNamespace(prefix, uri);
350 }
351
352 /**
353 * Declare the default collation
354 *
355 * @param uri the absolute URI of the default collation. This URI must have been bound to a collation
356 * using the method {@link Configuration#registerCollation(String, StringCollator)}, or it must be
357 * one that is recognized implicitly, such as a UCA collation
358 * @throws NullPointerException if the collation URI is null
359 * @throws IllegalStateException if the collation URI has not been registered, unless it is the standard
360 * Unicode codepoint collation which is registered implicitly
361 * @since 9.4
362 */
363
364 public void declareDefaultCollation(String uri) {
365 env.declareDefaultCollation(uri);
366 }
367
368
369 /**
370 * Declare the static type of the context item. If this type is declared, and if a context item
371 * is supplied when the query is invoked, then the context item must conform to this type (no
372 * type conversion will take place to force it into this type).
373 *
374 * @param type the required type of the context item
375 */
376
377 public void setRequiredContextItemType(ItemType type) {
378 requiredContextItemType = type;
379 env.setRequiredContextItemType(type.getUnderlyingItemType());
380 }
381
382 /**
383 * Get the required type of the context item. If no type has been explicitly declared for the context
384 * item, an instance of AnyItemType (representing the type item()) is returned.
385 *
386 * @return the required type of the context item
387 */
388
389 public ItemType getRequiredContextItemType() {
390 return requiredContextItemType;
391 }
392
393 /**
394 * Request fast compilation. Fast compilation will generally be achieved at the expense of run-time performance
395 * and quality of diagnostics. Fast compilation is a good trade-off if (a) the expression is known to be correct,
396 * and (b) once compiled, the expression is only executed once against a document of modest size.
397 * <p><i>The current implementation is equivalent to switching off all optimizations. Setting this option, however,
398 * indicates an intent rather than a mechanism, and the implementation details may change in future to reflect
399 * the intent.</i></p>
400 *
401 * @param fast set to true to request fast compilation; set to false to revert to the optimization options
402 * defined in the Configuration.
403 * @since 9.9
404 */
405
406 public void setFastCompilation(boolean fast) {
407 if (fast) {
408 env.setOptimizerOptions(new OptimizerOptions(0));
409 } else {
410 env.setOptimizerOptions(getProcessor().getUnderlyingConfiguration().getOptimizerOptions());
411 }
412 }
413
414 /**
415 * Ask if fast compilation has been enabled.
416 *
417 * @return true if fast compilation has been enabled
418 * @since 9.9
419 */
420
421 public boolean isFastCompilation() {
422 return env.getOptimizerOptions().getOptions() == 0;
423 }
424
425 /**
426 * Compile a library module supplied as a string. The code generated by compiling the library is available
427 * for importing by all subsequent compilations using the same XQueryCompiler; it is identified by an
428 * "import module" declaration that specifies the module URI of the library module. No module location
429 * hint is required, and if one is present, it is ignored.
430 * <p>The base URI of the query should be supplied by calling {@link #setBaseURI(java.net.URI)} </p>
431 * <p>Separate compilation of library modules is supported only under Saxon-EE</p>
432 *
433 * @param query the text of the query
434 * @throws SaxonApiException if the query compilation fails with a static error
435 * @since 9.2
436 */
437
438 public void compileLibrary(String query) throws SaxonApiException {
439 try {
440 env.compileLibrary(query);
441 } catch (XPathException e) {
442 throw new SaxonApiException(e);
443 }
444 }
445
446 /**
447 * Compile a library module supplied as a file. The code generated by compiling the library is available
448 * for importing by all subsequent compilations using the same XQueryCompiler; it is identified by an
449 * "import module" declaration that specifies the module URI of the library module. No module location
450 * hint is required, and if one is present, it is ignored.
451 * <p>The encoding of the input stream may be specified using {@link #setEncoding(String)};
452 * if this has not been set, the compiler determines the encoding from the version header of the
453 * query, and if that too is absent, it assumes UTF-8.</p>
454 * <p>Separate compilation of library modules is supported only under Saxon-EE</p>
455 *
456 * @param query the file containing the query. The URI corresponding to this file will be used as the
457 * base URI of the query, overriding any URI supplied using {@link #setBaseURI(java.net.URI)} (but not
458 * overriding any base URI specified within the query prolog)
459 * @throws SaxonApiException if the query compilation fails with a static error
460 * @throws IOException if the file does not exist or cannot be read
461 * @since 9.2
462 */
463
464 public void compileLibrary(File query) throws SaxonApiException, IOException {
465 try (FileInputStream stream = new FileInputStream(query)) {
466 String savedBaseUri = env.getBaseURI();
467 env.setBaseURI(query.toURI().toString());
468 env.compileLibrary(stream, encoding);
469 env.setBaseURI(savedBaseUri);
470 } catch (XPathException e) {
471 throw new SaxonApiException(e);
472 }
473 }
474
475 /**
476 * Compile a library module supplied as a Reader. The code generated by compiling the library is available
477 * for importing by all subsequent compilations using the same XQueryCompiler; it is identified by an
478 * "import module" declaration that specifies the module URI of the library module. No module location
479 * hint is required, and if one is present, it is ignored.
480 * <p>The base URI of the query should be supplied by calling {@link #setBaseURI(java.net.URI)} </p>
481 * <p>Separate compilation of library modules is supported only under Saxon-EE</p>
482 *
483 * @param query the text of the query
484 * @throws SaxonApiException if the query compilation fails with a static error
485 * @since 9.2
486 */
487
488 public void compileLibrary(Reader query) throws SaxonApiException {
489 try {
490 env.compileLibrary(query);
491 } catch (XPathException | IOException e) {
492 throw new SaxonApiException(e);
493 }
494 }
495
496 /**
497 * Compile a library module supplied as an InputStream. The code generated by compiling the library is available
498 * for importing by all subsequent compilations using the same XQueryCompiler; it is identified by an
499 * "import module" declaration that specifies the module URI of the library module. No module location
500 * hint is required, and if one is present, it is ignored.
501 * <p>The encoding of the input stream may be specified using {@link #setEncoding(String)};
502 * if this has not been set, the compiler determines the encoding from the version header of the
503 * query, and if that too is absent, it assumes UTF-8. </p>
504 * <p>The base URI of the query should be supplied by calling {@link #setBaseURI(java.net.URI)} </p>
505 * <p>Separate compilation of library modules is supported only under Saxon-EE</p>
506 *
507 * @param query the text of the query
508 * @throws SaxonApiException if the query compilation fails with a static error
509 * @since 9.2
510 */
511
512 public void compileLibrary(InputStream query) throws SaxonApiException {
513 try {
514 env.compileLibrary(query, encoding);
515 } catch (XPathException | IOException e) {
516 throw new SaxonApiException(e);
517 }
518 }
519
520 /**
521 * Compile a query supplied as a string.
522 * <p>The base URI of the query should be supplied by calling {@link #setBaseURI(java.net.URI)} </p>
523 * <p>If the query contains static errors, these will be notified to the registered {@link ErrorListener}.
524 * More than one static error may be reported. If any static errors have been reported, this method
525 * will exit with an exception, but the exception will only contain a summary message. The default
526 * {@link ErrorListener} writes details of each error to the <code>System.err</code> output stream.</p>
527 *
528 * @param query the text of the query
529 * @return an XQueryExecutable representing the compiled query
530 * @throws SaxonApiException if the query compilation fails with a static error
531 * @since 9.0
532 */
533
534 public XQueryExecutable compile(String query) throws SaxonApiException {
535 try {
536 return new XQueryExecutable(processor, env.compileQuery(query));
537 } catch (XPathException e) {
538 throw new SaxonApiException(e);
539 }
540 }
541
542 /**
543 * Compile a query supplied as a file
544 *
545 * @param query the file containing the query. The URI corresponding to this file will be used as the
546 * base URI of the query, overriding any URI supplied using {@link #setBaseURI(java.net.URI)} (but not
547 * overriding any base URI specified within the query prolog)
548 * @return an XQueryExecutable representing the compiled query
549 * @throws SaxonApiException if the query compilation fails with a static error
550 * @throws IOException if the file does not exist or cannot be read
551 * @since 9.1
552 */
553
554 public XQueryExecutable compile(File query) throws SaxonApiException, IOException {
555 try (FileInputStream stream = new FileInputStream(query)) {
556 String savedBaseUri = env.getBaseURI();
557 env.setBaseURI(query.toURI().toString());
558 XQueryExecutable exec =
559 new XQueryExecutable(processor, env.compileQuery(stream, encoding));
560 env.setBaseURI(savedBaseUri);
561 return exec;
562 } catch (XPathException e) {
563 throw new SaxonApiException(e);
564 }
565 }
566
567 /**
568 * Compile a query supplied as an InputStream
569 * <p>The base URI of the query should be supplied by calling {@link #setBaseURI(java.net.URI)} </p>
570 *
571 * @param query the input stream on which the query is supplied. This will be consumed by this method
572 * @return an XQueryExecutable representing the compiled query
573 * @throws SaxonApiException if the query compilation fails with a static error
574 * @since 9.1
575 */
576
577 public XQueryExecutable compile(InputStream query) throws SaxonApiException {
578 try {
579 return new XQueryExecutable(processor, env.compileQuery(query, encoding));
580 } catch (XPathException e) {
581 throw new SaxonApiException(e);
582 }
583 }
584
585 /**
586 * Compile a query supplied as a Reader
587 * <p>The base URI of the query should be supplied by calling {@link #setBaseURI(java.net.URI)} </p>
588 *
589 * @param query the input stream on which the query is supplied. This will be consumed by this method
590 * @return an XQueryExecutable representing the compiled query
591 * @throws SaxonApiException if the query compilation fails with a static error
592 * @throws IOException if the file does not exist or cannot be read
593 * @since 9.1
594 */
595
596 public XQueryExecutable compile(Reader query) throws SaxonApiException, IOException {
597 try {
598 return new XQueryExecutable(processor, env.compileQuery(query));
599 } catch (XPathException e) {
600 throw new SaxonApiException(e);
601 }
602 }
603
604 /**
605 * Get the underlying {@link net.sf.saxon.query.StaticQueryContext} object that maintains the static context
606 * information on behalf of this XQueryCompiler. This method provides an escape hatch to internal Saxon
607 * implementation objects that offer a finer and lower-level degree of control than the s9api classes and
608 * methods. Some of these classes and methods may change from release to release.
609 *
610 * @return the underlying StaticQueryContext object
611 * @since 9.2
612 */
613
614 public StaticQueryContext getUnderlyingStaticContext() {
615 return env;
616 }
617
618 /**
619 * List of errors. The caller should supply an empty list before calling Compile; the processor will then populate
620 * the list with error information obtained during the compilation. Each error will be included as an object of type StaticError.
621 * If no error list is supplied by the caller, error information will be written to the standard error stream.
622 * <p>By supplying a custom List with a user-written add() method, it is possible to intercept error conditions as they occur.</p>
623 * <p>Calling this method overwrites any previous call to {@link #setErrorListener}, as well as any
624 * previous call to {@code #setErrorList}.</p>
625 *
626 * @param errorList a (typically empty) list that will be populated with {@link StaticError} objects giving details
627 * of any static errors found in the query.
628 */
629 public void setErrorList(List<StaticError> errorList) {
630 env.setErrorListener(new ErrorGatherer(errorList));
631 }
632
633
634 }
635