net.sf.saxon.query

Class XQueryExpression

public class XQueryExpression extends Object implements Container

XQueryExpression represents a compiled query. This object is immutable and thread-safe, the same compiled query may be executed many times in series or in parallel. The object can be created only by using the compileQuery method of the QueryProcessor class.

Various methods are provided for evaluating the query, with different options for delivery of the results.

Constructor Summary
protected XQueryExpression(Expression exp, Executable exec, QueryModule mainModule, Configuration config)
The constructor is protected, to ensure that instances can only be created using the compileQuery() methods of StaticQueryContext
Method Summary
Listevaluate(DynamicQueryContext env)
Execute a the compiled Query, returning the results as a List.
ObjectevaluateSingle(DynamicQueryContext env)
Execute the compiled Query, returning the first item in the result.
voidexplain(ExpressionPresenter out)
Diagnostic method: display a representation of the compiled query on the selected output stream.
intgetColumnNumber()
Return the character position where the current document event ends.
intgetContainerGranularity()
Get the granularity of the container.
ExecutablegetExecutable()
Get the Executable (representing a complete stylesheet or query) of which this Container forms part
ExpressiongetExpression()
Get the expression wrapped in this XQueryExpression object
StructuredQName[]getExternalVariableNames()
Get a list containing the names of the external variables in the query.
intgetHostLanguage()
Get the host language (XSLT, XQuery, XPath) used to implement the code in this container
intgetLineNumber()
Return the line number where the current document event ends.
LocationProvidergetLocationProvider()
Get the LocationProvider allowing location identifiers to be resolved.
PathMapgetPathMap()
Get the path map for the query expression
StringgetPublicId()
Return the public identifier for the current document event.
SlotManagergetStackFrameMap()
Get the stack frame map used for the outermost level of this query
QueryModulegetStaticContext()
Get the static context in which this expression was compiled.
StringgetSystemId()
Return the system identifier for the current document event.
booleanisDocumentProjectionAllowed()
Ask whether document projection is allowed
booleanisUpdateQuery()
Ask whether this is an update query
EventIteratoriterateEvents(Controller controller, DynamicQueryContext dynamicEnv)
Run the query returning the results as an EventIterator
SequenceIteratoriterator(DynamicQueryContext env)
Get an iterator over the results of the expression.
ControllernewController()
Get a controller that can be used to execute functions in this compiled query.
voidpull(DynamicQueryContext dynamicEnv, Result destination, Properties outputProperties)
Run the query in pull mode.
voidrun(DynamicQueryContext env, Result result, Properties outputProperties)
Run the query, sending the results directly to a JAXP Result object.
SetrunUpdate(DynamicQueryContext dynamicEnv)
Run an updating query
voidrunUpdate(DynamicQueryContext dynamicEnv, UpdateAgent agent)
Run an updating query, writing back eligible updated node to persistent storage.
voidsetAllowDocumentProjection(boolean allowed)
Indicate that document projection is or is not allowed
booleanusesContextItem()
Ask whether this query uses the context item

Constructor Detail

XQueryExpression

protected XQueryExpression(Expression exp, Executable exec, QueryModule mainModule, Configuration config)
The constructor is protected, to ensure that instances can only be created using the compileQuery() methods of StaticQueryContext

Parameters: exp an expression to be wrapped as an XQueryExpression exec the executable mainModule the static context of the main module config the configuration

Throws: XPathException if an error occurs

Method Detail

evaluate

public List evaluate(DynamicQueryContext env)
Execute a the compiled Query, returning the results as a List.

Parameters: env Provides the dynamic query evaluation context

Returns: The results of the expression, as a List. The List represents the sequence of items returned by the expression. Each item in the list will either be an object representing a node, or an object representing an atomic value. For the types of Java object that may be returned, see the description of the evaluate method of class XPathProcessor

evaluateSingle

public Object evaluateSingle(DynamicQueryContext env)
Execute the compiled Query, returning the first item in the result. This is useful where it is known that the expression will only return a singleton value (for example, a single node, or a boolean).

Parameters: env Provides the dynamic query evaluation context

Returns: The first item in the sequence returned by the expression. If the expression returns an empty sequence, this method returns null. Otherwise, it returns the first item in the result sequence, represented as a Java object using the same mapping as for the evaluate method

explain

public void explain(ExpressionPresenter out)
Diagnostic method: display a representation of the compiled query on the selected output stream.

Parameters: out an ExpressionPresenter to which the XML representation of the compiled query will be sent

getColumnNumber

public int getColumnNumber()
Return the character position where the current document event ends.

Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

The return value is an approximation of the column number in the document entity or external parsed entity where the markup that triggered the event appears.

Returns: The column number, or -1 if none is available.

See Also: XQueryExpression

getContainerGranularity

public int getContainerGranularity()
Get the granularity of the container.

Returns: 0 for a temporary container created during parsing; 1 for a container that operates at the level of an XPath expression; 2 for a container at the level of a global function or template

getExecutable

public Executable getExecutable()
Get the Executable (representing a complete stylesheet or query) of which this Container forms part

getExpression

public Expression getExpression()
Get the expression wrapped in this XQueryExpression object

Returns: the underlying expression

getExternalVariableNames

public StructuredQName[] getExternalVariableNames()
Get a list containing the names of the external variables in the query.

Changed in Saxon 9.0 to return an array of StructuredQName objects rather than integer fingerprints.

Returns: an array of StructuredQName objects, representing the names of external variables defined in the query

getHostLanguage

public int getHostLanguage()
Get the host language (XSLT, XQuery, XPath) used to implement the code in this container

Returns: typically XSLT or XQUERY

getLineNumber

public int getLineNumber()
Return the line number where the current document event ends.

Warning: The return value from the method is intended only as an approximation for the sake of error reporting; it is not intended to provide sufficient information to edit the character content of the original XML document.

The return value is an approximation of the line number in the document entity or external parsed entity where the markup that triggered the event appears.

Returns: The line number, or -1 if none is available.

See Also: XQueryExpression

getLocationProvider

public LocationProvider getLocationProvider()
Get the LocationProvider allowing location identifiers to be resolved.

getPathMap

public PathMap getPathMap()
Get the path map for the query expression

Returns: the path map (which is constructed if this has not already been done)

getPublicId

public String getPublicId()
Return the public identifier for the current document event.

The return value is the public identifier of the document entity or of the external parsed entity in which the markup that triggered the event appears.

Returns: A string containing the public identifier, or null if none is available.

See Also: XQueryExpression

getStackFrameMap

public SlotManager getStackFrameMap()
Get the stack frame map used for the outermost level of this query

Returns: the stack frame map

getStaticContext

public QueryModule getStaticContext()
Get the static context in which this expression was compiled. This is essentially an internal copy of the original user-created StaticQueryContext object, augmented with information obtained from the query prolog of the main query module, and with information about functions and variables imported from other library modules. The user-created StaticQueryContext object is not modified by Saxon, whereas the QueryModule object includes additional information found in the query prolog.

Returns: the QueryModule object representing the static context of the main module of the query. This is available for inspection, but must not be modified or reused by the application.

getSystemId

public String getSystemId()
Return the system identifier for the current document event.

The return value is the system identifier of the document entity or of the external parsed entity in which the markup that triggered the event appears.

If the system identifier is a URL, the parser must resolve it fully before passing it to the application.

Returns: A string containing the system identifier, or null if none is available.

See Also: XQueryExpression

isDocumentProjectionAllowed

public boolean isDocumentProjectionAllowed()
Ask whether document projection is allowed

Returns: true if document projection is allowed

isUpdateQuery

public boolean isUpdateQuery()
Ask whether this is an update query

Returns: true if the body of the query is an updating expression (as defined by the XQuery Update specification). Note that a query can use Update syntax (notably the copy-modify syntax) without being an updating expression.

iterateEvents

public EventIterator iterateEvents(Controller controller, DynamicQueryContext dynamicEnv)
Run the query returning the results as an EventIterator

Parameters: controller The Controller used to run the query dynamicEnv the XQuery dynamic context for evaluating the query

Returns: an EventIterator representing the results of the query as a sequence of events

iterator

public SequenceIterator iterator(DynamicQueryContext env)
Get an iterator over the results of the expression. This returns results without any conversion of the returned items to "native" Java classes. The iterator will deliver a sequence of Item objects, each item being either a NodeInfo (representing a node) or an AtomicValue (representing an atomic value).

To get the results of the query in the form of an XML document in which each item is wrapped by an element indicating its type, use:

QueryResult.wrap(iterator(env))

To serialize the results to a file, use the QueryResult.serialize() method.

Parameters: env Provides the dynamic query evaluation context

Returns: an iterator over the results of the query. The class SequenceIterator is modeled on the standard Java Iterator class, but has extra functionality and can throw exceptions when errors occur.

Throws: XPathException if a dynamic error occurs in evaluating the query. Some dynamic errors will not be reported by this method, but will only be reported when the individual items of the result are accessed using the returned iterator.

newController

public Controller newController()
Get a controller that can be used to execute functions in this compiled query. Functions in the query module can be found using QueryModule. They can then be called directly from the Java application using UserFunction The same Controller can be used for a series of function calls. Note that the Controller should only be used in a single thread.

Returns: a newly constructed Controller

pull

public void pull(DynamicQueryContext dynamicEnv, Result destination, Properties outputProperties)
Run the query in pull mode.

For maximum effect this method should be used when lazyConstructionMode has been set in the Configuration.

Note: this method usually has very similar performance to the XQueryExpression method (which does the same thing), but sometimes it is significantly slower. Therefore, the run() method is preferred.

Parameters: dynamicEnv the dynamic context for query evaluation destination the destination of the query results outputProperties the serialization parameters

See Also: Configuration

run

public void run(DynamicQueryContext env, Result result, Properties outputProperties)
Run the query, sending the results directly to a JAXP Result object. This way of executing the query is most efficient in the case of queries that produce a single document (or parentless element) as their output, because it avoids constructing the result tree in memory: instead, it is piped straight to the serializer.

Parameters: env the dynamic query context result the destination for the results of the query. The query is effectively wrapped in a document{} constructor, so that the items in the result are concatenated to form a single document; this is then written to the requested Result destination, which may be (for example) a DOMResult, a SAXResult, or a StreamResult outputProperties Supplies serialization properties, in JAXP format, if the result is to be serialized. This parameter can be defaulted to null.

Throws: XPathException if the query fails.

runUpdate

public Set runUpdate(DynamicQueryContext dynamicEnv)
Run an updating query

Parameters: dynamicEnv the dynamic context for query execution

Returns: a set of nodes representing the roots of trees that have been modified as a result of executing the update. Note that this method will never modify persistent data on disk; it returns the root nodes of the affected documents (which will often be document nodes whose document-uri can be ascertained), and it is the caller's responsibility to decide what to do with them.

On completion of this method it is generally unsafe to rely on the contents or relationships of NodeInfo objects that were obtained before the updating query was run. Such objects may or may not reflect the results of the update operations. This is especially true in the case of nodes that are part of a subtree that has been deleted (detached from its parent). Instead, the new updated tree should be accessed by navigation from the root nodes returned by this method.

Throws: XPathException if evaluation of the update query fails, or it this is not an updating query

runUpdate

public void runUpdate(DynamicQueryContext dynamicEnv, UpdateAgent agent)
Run an updating query, writing back eligible updated node to persistent storage.

A node is eligible to be written back to disk if it is present in the document pool, which generally means that it was originally read using the doc() or collection() function.

On completion of this method it is generally unsafe to rely on the contents or relationships of NodeInfo objects that were obtained before the updating query was run. Such objects may or may not reflect the results of the update operations. This is especially true in the case of nodes that are part of a subtree that has been deleted (detached from its parent). Instead, the new updated tree should be accessed by navigation from the root nodes returned by this method.

If one or more eligible updated nodes cannot be written back to disk, perhaps because the URI identifies a non-updatable location, then an exception is thrown. In this case it is undefined

Parameters: dynamicEnv the dynamic context for query execution

Throws: XPathException if evaluation of the update query fails, or it this is not an updating query

setAllowDocumentProjection

public void setAllowDocumentProjection(boolean allowed)
Indicate that document projection is or is not allowed

Parameters: allowed true if projection is allowed

usesContextItem

public boolean usesContextItem()
Ask whether this query uses the context item

Returns: true if the context item is referenced either in the query body or in the initializer of any global variable