XQuery 3.0: An XML Query Language /**/ /* from xsl:query.xsl (C) */ code { font-family: monospace; }
div.constraint, div.issue, div.note, div.notice { margin-left: 2em; }
div.issue p.title { margin-left: -2em; }
ol.enumar { list-style-type: decimal; } ol.enumla { list-style-type: lower-alpha; } ol.enumlr { list-style-type: lower-roman; } ol.enumua { list-style-type: upper-alpha; } ol.enumur { list-style-type: upper-roman; }
li p { margin-top: 0.3em; margin-bottom: 0.3em; }
sup small { font-style: italic; color: #8F8F8F; } /* from xsl:query.xsl (D) */ div.exampleInner pre { margin-left: 1em; margin-top: 0em; margin-bottom: 0em} div.exampleOuter {border: 4px double gray; margin: 0em; padding: 0em} div.exampleInner { background-color: #d5dee3; border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; border-bottom-width: 4px; border-bottom-style: double; border-bottom-color: #d3d3d3; padding: 4px; margin: 0em } div.exampleWrapper { margin: 4px } div.exampleHeader { font-weight: bold; margin: 4px}
div.issue { border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1pt; margin-bottom: 20pt; }
th.issue-toc-head { border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1pt; }
/* from xsl-query.xsl (B) */ table.small { font-size: x-small; } a.judgment:visited, a.judgment:link { font-family: sans-serif; color: black; text-decoration: none } a.processing:visited, a.processing:link { color: black; text-decoration: none } a.env:visited, a.env:link { color: black; text-decoration: none } .advisement { border-color: orange; border-style: none solid; background: #fec; color: black; padding: .5em; border-width: .5em; page-break-inside: avoid; margin: 1em auto; } /**/ Status Update (6 April 2021): Feedback, comments, error reports on this specification should be sent via GitHub https://github.com/w3c/qtspecs/issues [email protected] This version: http://www.w3.org/TR/2014/REC-xquery-30-20140408/ Latest version of XQuery 3.0: http://www.w3.org/TR/xquery-30/ Previous version of XQuery 3.0: http://www.w3.org/TR/2013/PR-xquery-30-20131022/ http://www.w3.org/TR/2013/WD-xquery-30-20130723/ http://www.w3.org/TR/2013/CR-xquery-30-20130108/ http://www.w3.org/TR/2011/WD-xquery-30-20111213/ http://www.w3.org/TR/2011/WD-xquery-30-20110614/ http://www.w3.org/TR/2009/WD-xquery-11-20091215/ http://www.w3.org/TR/2008/WD-xquery-11-20081203/ http://www.w3.org/TR/2008/WD-xquery-11-20080711/ Most recent version of XQuery 3: http://www.w3.org/TR/xquery-3/ Most recent Recommendation of XQuery: http://www.w3.org/TR/2010/REC-xquery-20101214/ Editors: Jonathan Robie, EMC Corporation <[email protected]> Don Chamberlin <[email protected]> Michael Dyck, Invited Expert <[email protected]> John Snelson <[email protected]> Please check the errata See also translations This document is also available in these non-normative formats: XML Change markings relative to previous edition Copyright W3C ® MIT ERCIM Keio Beihang liability trademark document use XML is a versatile markup language, capable of labeling the information content of diverse data sources including structured and semi-structured documents, relational databases, and object repositories. A query language that uses the structure of XML intelligently can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware. This specification describes a query language called XQuery, which is designed to be broadly applicable across many types of XML data sources. XQuery 3.0 is an extended version of the XQuery 1.0 Recommendation published on 23 January 2007. A list of changes made since XQuery 1.0 can be found in J Change Log group by 3.10.7 Group By Clause tumbling window sliding window 3.10.4 Window Clause count 3.10.6 Count Clause allowing empty 3.10.2 For Clause try catch 3.15 Try/Catch Expressions Dynamic function call 3.2.2 Dynamic Function Call Inline function expression 3.1.7 Inline Function Expressions Private functions ( 4.18 Function Declaration Switch expressions ( 3.13 Switch Expression Computed namespace constructors ( 3.9.3.7 Computed Namespace Constructors Output declarations ( 2.2.4 Serialization Annotations ( 4.15 Annotations Function assertions function tests A string concatenation operator ( 3.6 String Concatenation Expressions A mapping operator ( 3.17 Simple map operator (!) This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index This is one document in a set of six documents that have been progressed to Recommendation together (XQuery 3.0, XQueryX 3.0, XPath 3.0, Data Model 3.0, Functions and Operators 3.0, and Serialization 3.0). This is a Recommendation XML Query Working Group XML Activity This Recommendation of XQuery 3.0 represents the second version of a previous W3C Recommendation A Test Suite has been created for this document. Implementors are encouraged to run this test suite and report their results. The Test Suite can be found at http://dev.w3.org/2011/QT3-test-suite/ implementation report This document incorporates minor changes made against the Proposed Recommendation Proposed Recommendation J Change Log Please report errors in this document using W3C's public Bugzilla system http://www.w3.org/XML/2005/04/qt-bugzilla [email protected] http://lists.w3.org/Archives/Public/public-qt-comments/ This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web. This document was produced by a group operating under the 5 February 2004 W3C Patent Policy public list of any patent disclosures Essential Claim(s) section 6 of the W3C Patent Policy 1 Introduction Basics Module Context and Expression Context Static Context Dynamic Context Processing Model Data Model Generation Schema Import Processing Expression Processing Static Analysis Phase Dynamic Evaluation Phase Serialization Consistency Constraints Error Handling Kinds of Errors Identifying and Reporting Errors Handling Dynamic Errors Errors and Optimization Concepts Document Order Atomization Effective Boolean Value Input Sources URI Literals Resolving a Relative URI Reference Types Predefined Schema Types Namespace-sensitive Types Typed Value and String Value SequenceType Syntax SequenceType Matching Matching a SequenceType and a Value Matching an ItemType and an Item Element Test Schema Element Test Attribute Test Schema Attribute Test Function Test SequenceType Subtype Relationships The judgement subtype(A, B) The judgement subtype-itemtype(Ai, Bi) The judgement subtype-assertions(AnnotationsA, AnnotationsB) xs:error Comments Expressions Primary Expressions Literals Variable References Parenthesized Expressions Context Item Expression Static Function Calls Evaluating Static and Dynamic Function Calls Function Conversion Rules Function Coercion Named Function References Inline Function Expressions Postfix Expressions Filter Expressions Dynamic Function Call Path Expressions Relative Path Expressions Path operator (/) Steps Axes Node Tests Predicates within Steps Unabbreviated Syntax Abbreviated Syntax Sequence Expressions Constructing Sequences Combining Node Sequences Arithmetic Expressions String Concatenation Expressions Comparison Expressions Value Comparisons General Comparisons Node Comparisons Logical Expressions Constructors Direct Element Constructors Attributes Namespace Declaration Attributes Content Boundary Whitespace Other Direct Constructors Computed Constructors Computed Element Constructors Computed Attribute Constructors Document Node Constructors Text Node Constructors Computed Processing Instruction Constructors Computed Comment Constructors Computed Namespace Constructors In-scope Namespaces of a Constructed Element FLWOR Expressions Variable Bindings For Clause Let Clause Window Clause Tumbling Windows Sliding Windows Effects of Window Clauses on the Tuple Stream Where Clause Count Clause Group By Clause Order By Clause Return Clause Ordered and Unordered Expressions Conditional Expressions Switch Expression Quantified Expressions Try/Catch Expressions Expressions on SequenceTypes Instance Of Typeswitch Cast Castable Constructor Functions Treat Simple map operator (!) Validate Expressions Extension Expressions Modules and Prologs Version Declaration Module Declaration Boundary-space Declaration Default Collation Declaration Base URI Declaration Construction Declaration Ordering Mode Declaration Empty Order Declaration Copy-Namespaces Declaration Decimal Format Declaration Schema Import Module Import The Target Namespace of a Module Multiple Modules with the same Target Namespace Location URIs Cycles Namespace Declaration Default Namespace Declaration Annotations Variable Declaration Context Item Declaration Function Declaration Option Declaration Conformance Minimal Conformance Optional Features Schema Aware Feature Typed Data Feature Static Typing Feature Module Feature Serialization Feature Higher-Order Function Feature Data Model Conformance Syntax Extensions A XQuery 3.0 Grammar EBNF Notation Extra-grammatical Constraints Grammar Notes Lexical structure Terminal Symbols Terminal Delimitation End-of-Line Handling XML 1.0 End-of-Line Handling XML 1.1 End-of-Line Handling Whitespace Rules Default Whitespace Handling Explicit Whitespace Handling Reserved Function Names Precedence Order (Non-Normative) Type Promotion and Operator Mapping Type Promotion Operator Mapping Context Components Static Context Components Dynamic Context Components Implementation-Defined Items References Normative References Non-normative References Background Material Error Conditions The application/xquery Media Type Introduction Registration of MIME Media Type application/xquery Interoperability Considerations Applications Using this Media Type File Extensions Intended Usage Author/Change Controller Encoding Considerations Recognizing XQuery Files Charset Default Rules Security Considerations Glossary Example Applications Joins Queries on Sequence Recursive Transformations Selecting Distinct Combinations Change Log Incompatibilities Changes introduced during the Proposed Recommendation period: Substantive Changes Editorial Changes Changes introduced during the Candidate Recommendation period: Substantive Changes Editorial Changes Resolutions that are no longer relevant. Changes introduced in the Candidate Recommendation Substantive Changes Editorial Changes Changes introduced in prior Working Drafts Substantive Changes Editorial Changes As increasing amounts of information are stored, exchanged, and presented using XML, the ability to intelligently query XML data sources becomes increasingly important. One of the great strengths of XML is its flexibility in representing many different kinds of information from diverse sources. To exploit this flexibility, an XML query language must provide features for retrieving and interpreting information from these diverse sources. XQuery is designed to meet the requirements identified by the W3C XML Query Working Group [XQuery 3.0 Requirements] [XML Query Use Cases] [Quilt] [XML Path Language (XPath) Version 1.0] [XQL] [XML-QL] [SQL] [ODMG] [ Definition data model [XQuery and XPath Data Model (XDM) 3.0] XQuery Version 3.0 is an extension of XPath Version 3.0. In general, any expression that is syntactically valid and executes successfully in both XPath 3.0 and XQuery 3.0 will return the same result in both languages. There are a few exceptions to this rule: Because XQuery expands predefined entity references character references "&" & & If XPath 1.0 compatibility mode is enabled, XPath behaves differently from XQuery in a number of ways, which are discussed in [XML Path Language (XPath) 3.0] Because these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency, and the editors of these specifications work together closely. XQuery 3.0 also depends on and is closely related to the following specifications: [XQuery and XPath Data Model (XDM) 3.0] The type system of XQuery 3.0 is based on XML Schema. It is implementation-defined whether the type system is based on [XML Schema 1.0] [XML Schema 1.1] The built-in function library and the operators supported by XQuery 3.0 are defined in [XQuery and XPath Functions and Operators 3.0] XQuery also has an XML-based syntax, which [XQueryX 3.0] [ Definition XQuery 3.0 Processor Definition XQuery 1.0 Processor [ Definition XPath 3.0 Processor Definition XPath 2.0 Processor Definition XPath 1.0 Processor This document specifies a grammar for XQuery 3.0, using the same basic EBNF notation used in [XML 1.0] A.2 Lexical structure queries A XQuery 3.0 Grammar In the grammar productions in this document, named symbols are underlined and literal text is enclosed in double quotes. For example, the following productions describe the syntax of a static FunctionCall ::= EQName ArgumentList ArgumentList ::= "(" ( Argument Argument The productions should be read as follows: A static EQName ArgumentList This document normatively defines the static and dynamic semantics of XQuery 3.0. In this document, examples and material labeled as "Note" are provided for explanatory purposes and are not normative. Certain aspects of language processing are described in this specification as implementation-defined implementation-dependent [ Definition Implementation-defined [ Definition Implementation-dependent The basic building block of XQuery 3.0 is the expression [Unicode] implementation-defined (However, unlike a pure functional language, it does not allow variable substitution if the variable declaration contains construction of new nodes.) Note: This specification contains no assumptions or requirements regarding the character set encoding of strings of [Unicode] Like XML, XQuery 3.0 is a case-sensitive language. Keywords in XQuery 3.0 use lower-case characters and are not reserved—that is, names in XQuery 3.0 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in A.3 Reserved Function Names [ Definition data model value sequence Definition sequence items Definition item atomic value node function DM30 Definition atomic value atomic type [XML Schema 1.0] [XML Schema 1.1] Definition node node kinds [XQuery and XPath Data Model (XDM) 3.0] node identity typed value string value name typed value string value xs:string name xs:QName [ Definition singleton Definition empty sequence [ Definition XDM instance value sequence items data model In the XQuery 3.0 grammar, most names are specified using the EQName lexical QNames EQName ::= QName URIQualifiedName QName ::= [http://www.w3.org/TR/REC-xml-names/#NT-QName] Names NCName ::= [http://www.w3.org/TR/REC-xml-names/#NT-NCName] Names URILiteral ::= StringLiteral URIQualifiedName ::= BracedURILiteral NCName BracedURILiteral ::= "Q" "{" ( PredefinedEntityRef CharRef Names in XQuery 3.0 can be bound to namespaces, and are based on the syntax and semantics defined in [XML Names] Definition lexical QName [http://www.w3.org/TR/REC-xml-names/#NT-QName] lexical QName lexical QName expanded QName statically known namespaces lexical QName [ Definition expanded QName expanded QNames The EQName QName URIQualifiedName xs:anyURI [XML Schema 1.0] [XML Schema 1.1] static error err:XQST0070 namespace URI http://www.w3.org/2000/xmlns/ Here are some examples of EQName pi lexical QName math:pi lexical QName Q{http://www.w3.org/2005/xpath-functions/math}pi BracedURILiteral lexical QName Certain namespace prefixes are predeclared by XQuery and bound to fixed namespace URIs. These namespace prefixes are as follows: xml = http://www.w3.org/XML/1998/namespace xs = http://www.w3.org/2001/XMLSchema xsi = http://www.w3.org/2001/XMLSchema-instance fn = http://www.w3.org/2005/xpath-functions local = http://www.w3.org/2005/xquery-local-functions 4.18 Function Declaration In addition to the prefixes in the above list, this document uses the prefix err http://www.w3.org/2005/xqt-errors 2.3.2 Identifying and Reporting Errors http://www.w3.org/2012/xquery which is reserved for use in this specification. It is currently used for annotations and option declarations that are defined by the XML Query Working Group. Element nodes have a property called in-scope namespaces Definition in-scope namespaces Note: In [XML Path Language (XPath) Version 1.0] namespace nodes namespace axis [XML Path Language (XPath) 3.0] However, where other specifications such as [XSLT and XQuery Serialization 3.0] in-scope-prefixes($e) ! namespace {namespace-uri-for-prefix($e,.)} {.} [ Definition URI [RFC3986] [RFC3987] IRI Note: In most contexts, processors are not required to raise errors if a URI is not lexically valid according to [RFC3986] [RFC3987] 2.4.5 URI Literals and 3.9.1.2 Namespace Declaration Attributes Module Context and [ Definition expression context [ Definition module context QueryBody This information is organized into two categories called the static context dynamic context [ Definition static context static error The individual components of the static context described Rules governing the initialization and alteration C.1 Static Context Components [ Definition XPath 1.0 compatibility mode. This component must be set by all host languages that include XPath 3.0 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false [ Definition Statically known namespaces. mapping from prefix to namespace URI that defines xs:anyURI [XML Schema 1.0] [XML Schema 1.1] in-scope namespaces statically known namespaces Some namespaces are predefined; additional namespaces can be added to the statically known namespaces by namespace declarations schema imports module imports Prolog module declaration namespace declaration attributes direct element constructors [ Definition Default element/type namespace. absent DM30 xs:anyURI [XML Schema 1.0] [XML Schema 1.1] [ Definition Default function namespace. absent DM30 xs:anyURI [XML Schema 1.0] [XML Schema 1.1] [ Definition In-scope schema definitions. static analysis [ Definition In-scope schema types. expanded QName named type implementation-dependent anonymous type 2.5.1 Predefined Schema Types If the Schema Aware Feature [ Definition In-scope element declarations. expanded QName implementation-dependent If the Schema Aware Feature substitution group [ Definition Substitution groups [XML Schema 1.0] [XML Schema 1.1] head element [ Definition In-scope attribute declarations. expanded QName implementation-dependent If the Schema Aware Feature [ Definition In-scope variables. mapping from expanded QName expanded QName static type Variable declarations in a Prolog in-scope variables An expression that binds a variable extends the in-scope variables inline function expression or user-defined function in-scope variables function parameters The static type of a variable may either be declared in a query or inferred by static type inference as discussed in 2.2.3.1 Static Analysis Phase [ Definition Context item static type. static type [ Definition Statically known function signatures. function signature DM30 statically known functions static function call named function reference expanded QName signature DM30 and annotations The statically known [XQuery and XPath Functions and Operators 3.0] functions declared in the current module (see 4.18 Function Declaration 4.12 Module Import constructor functions 3.16.5 Constructor Functions C.1 Static Context Components It is a static error err:XQST0034 expanded QName [ Definition Statically known collations. implementation-defined mapping from URI to collation. queries and Definition collation [XQuery and XPath Functions and Operators 3.0] [ Definition Default collation. statically known collations xs:string xs:anyURI [ Definition Construction mode. preserve xs:anyType strip xs:untyped xs:untyped xs:untypedAtomic [ Definition Ordering mode. ordered unordered expressions, as discussed in 3.11 Ordered and Unordered Expressions [ Definition Default order for empty sequences. NaN order by 3.10.8 Order By Clause greatest least [ Definition Boundary-space policy. boundary whitespace direct element constructors 3.9.1.4 Boundary Whitespace preserve strip [ Definition Copy-namespaces mode. 3.9.1 Direct Element Constructors preserve no-preserve inherit no-inherit [ Definition Static Base URI. relative URIs both during static analysis and during dynamic evaluation. All expressions within a module have the same static base URI. The Static Base URI can be set using a base URI declaration fn:static-base-uri fn:doc 2.4.6 Resolving a Relative URI Reference If the value of the Static Base URI is based on the location of the query module (in the terminology of [RFC3986] may import module fn:doc [ Definition Statically known documents. fn:doc static type fn:doc fn:doc statically known documents static type fn:doc document-node()? Note: The purpose of the statically known documents statically known documents fn:doc [ Definition Statically known collections. fn:collection fn:collection fn:collection statically known collections static type fn:collection node()* Note: The purpose of the statically known collections statically known collections fn:collection [ Definition Statically known default collection type. fn:collection statically known default collection type node()* [ Definition Statically known decimal formats. a mapping from QName to decimal format, with one default format that has no visible name. fn:format-number() Each decimal format contains three sets of properties, which fn:format-number The following attributes specify characters used to format the number per se: [ Definition decimal-separator [ Definition grouping-separator [ Definition percent [ Definition per-mille [ Definition zero-digit The following attributes control the interpretation of characters in the picture string supplied to the format-number function. In each case the value must be a single character. [ Definition digit-sign [ Definition pattern-separator The following attributes specify characters or strings that may appear in the result of formatting the number: [ Definition infinity [ Definition NaN [ Definition minus-sign [ Definition dynamic context dynamic context is absent DM30 dynamic error err:XPDY0002 The individual components of the dynamic context described Rules governing the initialization and alteration of these components can be found in C.2 Dynamic Context Components The dynamic context static context [ Definition dynamic context focus If any component in the focus is defined, all components of the focus are defined. Definition singleton focus Certain language constructs, notably the path operator E1/E2 the simple mapping operator predicate E1[E2] E2 E1 E2 E2 inner focus E1 outer focus E2 [ Definition context item item Definition context node . E1/E2 E1[E2] E1 E2 [ Definition initial context item [ Definition context position fn:position() E1/E2 E1[E2] E2 E1 [ Definition context size fn:last() E1/E2 E1[E2] E2 E1 [ Definition Variable values mapping from expanded QName expanded QNames in-scope variables static context expanded QName dynamic type [ Definition Named functions function DM30 statically known function signatures 2.2.5 Consistency Constraints [ Definition Current dateTime. implementation-dependent a query fn:current-dateTime a query [ Definition Implicit timezone. implementation-defined xs:dayTimeDuration [XML Schema 1.0] [XML Schema 1.1] [ Definition Default language. fn:format-date fn:format-integer xs:language [ Definition Default calendar. fn:format-date fn:format-dateTime [ Definition Default place. fn:format-date fn:format-dateTime [ Definition Available documents. data model fn:doc statically known documents If there are one or more URIs in available documents D D Note: This means that given a document node $N fn:doc(fn:document-uri($N)) is $N true fn:document-uri($N) [ Definition Available text resources fn:unparsed-text statically known documents [ Definition Available node collections. fn:collection statically known collections For every document node D available node collections D U available documents U D Note: This means that for any document node $N fn:collection fn:doc(fn:document-uri($N)) is $N true fn:document-uri($N) fn:doc fn:collection fn:doc fn:collection fn:doc [ Definition Default node collection. fn:collection default collection [ Definition Available resource collections. fn:uri-collection Note: An implementation may fn:uri-collection(X)!fn:doc(.) fn:collection(X) fn:uri-collection fn:collection fn:collection [ Definition Default resource collection. fn:uri-collection default resource collection [ Definition Environment variables. mapping from names to values. implementation-defined implementation-defined may Note: A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other operating systems) appropriate to the process in which the query is initiated XQuery 3.0 is defined in terms of the data model expression context Figure 1: Processing Model Overview Figure 1 provides a schematic overview of the processing steps that are discussed in detail below. Some of these steps are completely outside the domain of XQuery 3.0; in Figure 1, these are depicted outside the line that represents the boundaries of the language, an area labeled external processing XDM instance 2.2.1 Data Model Generation 2.2.2 Schema Import Processing (see 2.2.4 Serialization query processing domain 2.2.3 Expression Processing query 2.2.5 Consistency Constraints Before a query XDM instance XDM instance A document may be parsed using an XML parser that generates an XML Information Set [XML Infoset] [XML Schema 1.0] [XML Schema 1.1] Post-Schema Validation Infoset The Information Set or PSVI may be transformed into an XDM instance [XQuery and XPath Data Model (XDM) 3.0] The above steps provide an example of how an XDM instance data model [ Definition XDM instance type annotation described [XQuery and XPath Data Model (XDM) 3.0] reference to an XML Schema type. The type-name type annotation XDM instance Section 3.3 Construction from a PSVI DM30 The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is given the type annotation xs:untypedAtomic The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The type annotation xs:untyped xs:anyType xs:untyped xs:untyped xs:anyType type annotation The in-scope schema definitions static context 2.2.5 Consistency Constraints XQuery 3.0 defines two phases of processing called the static analysis phase dynamic evaluation phase static errors dynamic errors type errors dynamic errors type errors 2.3.1 Kinds of Errors Within each phase, an implementation is free to use any strategy or algorithm whose result conforms to the specifications in this document. [ Definition static analysis phase static context static analysis phase During the static analysis phase, the query operation tree static error err:XPST0003 static context The static context prolog Schema Aware Feature in-scope schema definitions Module Feature static context operation tree static context static error err:XPST0008 err:XPST0017 2.5.5.3 Element Test 2.5.5.5 Attribute Test The operation tree normalized atomization Effective Boolean Values During the static analysis phase static type Definition static type Examples of inferred static types might be: For the expression concat(a,b) xs:string For the expression $a = $v xs:boolean For the expression $s[exp] $s $s The inferred static type of the expression data($x) $x $x element(*, xs:integer) data($x) xs:integer In XQuery 1.0 and XPath 2.0, rules for static type inferencing were published normatively in [XQuery 1.0 and XPath 2.0 Formal Semantics] Every kind of expression also imposes requirements on the type of its operands. For example, with the expression substring($a, $b, $c) $a xs:string xs:string $b $c xs:double If the Static Typing Feature is in effect, a processor must raise a type error during static analysis if the inferred static type of an expression is not subsumed by the required type of the context where the expression is used. For example, the call of substring above would cause a type error if the inferred static type of $a xs:integer xs:anyAtomicType If the Static Typing Feature is not in effect, a processor may raise a type error during static analysis only if the inferred static type of an expression has no overlap (intersection) with the required type: so for the first argument of substring, the processor may raise an error if the inferred type is xs:integer xs:anyAtomicType [ Definition dynamic evaluation phase static analysis phase The dynamic evaluation phase can occur only if no errors were detected during the static analysis phase Static Typing Feature type errors The dynamic evaluation phase depends on the operation tree dynamic context static context dynamic context [ Definition dynamic type static type xs:integer* xs:integer If an operand of an expression is found to have a dynamic type type error err:XPTY0004 Even though static typing can catch many type errors dynamic error static type xs:untypedAtomic static error numeric dynamic error When the Static Typing Feature type error static type type error [ Definition Serialization XDM instance , as described in [XSLT and XQuery Serialization 3.0] Note: This definition of serialization is the definition used in this specification. Any form of serialization that is not based on [XSLT and XQuery Serialization 3.0] An XQuery implementation is not required to provide a serialization interface. For example, an implementation may provide only a DOM interface (see [Document Object Model] [XSLT and XQuery Serialization 3.0] serialization parameters C.1 Static Context Components If an implementation does not support one of these parameters, it must ignore it without raising an error. [ Definition output declaration Except for parameter-document Section B Schema for Serialization Parameters SER30 use-character-maps The following example illustrates the use of declaration options. declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "xml"; declare option output:encoding "iso-8859-1"; declare option output:indent "yes"; declare option output:parameter-document "file:///home/me/serialization-parameters.xml"; An output declaration err:XQST0108 library module err:XQST0110 static error err:XQST0109 http://www.w3.org/2010/xslt-xquery-serialization C.1 Static Context Components parameter-document or if the name of an output declaration is use-character-maps method "xml" implementation-defined If the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization parameter-document err:XQST0119 output:parameter-document If a processor is performing serialization, the XDM instance identified by an output:parameter-document Section 3.1 Setting Serialization Parameters by Means of a Data Model Instance SER30 err:XQST0115 http://www.w3.org/2010/xslt-xquery-serialization A serialization parameter that is not applicable to the chosen output method must be ignored, except that if its value is not a valid value for that parameter, an error may be raised. A processor that is performing serialization must raise a serialization error if the values of any serialization parameters that it supports A processor that is not performing serialization may report errors if any serialization parameters are incorrect, or may ignore such parameters. Specifying serialization parameters in a query does not by itself demand that the output be serialized. It merely defines the desired form of the serialized output for use in situations where the processor has been asked to perform serialization. Note: The data model in-scope namespaces [XML Names 1.1] [XML Names 1.1] In order for XQuery 3.0 to be well defined, the input XDM instance static context dynamic context a query For every node that has a type annotation, if that type annotation is found in the in-scope schema definitions type annotation Every element name, attribute name, or schema type name referenced in in-scope variables statically known in-scope schema definitions ElementTest AttributeTest Any reference to a global element, attribute, or type name in the in-scope schema definitions in-scope schema definitions For each mapping of a string to a document node in available documents statically known documents 2.5.5 SequenceType Matching For each mapping of a string to a sequence of nodes in available node collections statically known collections 2.5.5 SequenceType Matching The sequence of nodes in the default collection statically known default collection type 2.5.5 SequenceType Matching The value of the context item context item static type 2.5.5 SequenceType Matching For each (variable, type) pair in in-scope variables variable values 2.5.5 SequenceType Matching For each variable declared as external, if the variable declaration does not include a VarDefaultValue For each variable declared as external for which the external environment provides a value: If the variable declaration includes a declared type, the value provided by the external environment must match the declared type, using the matching rules in 2.5.5 SequenceType Matching For each function declared as external: the function's implementation DM30 2.5.5 SequenceType Matching implementation-defined For a given query, define a participating ISSD in-scope schema definitions In this context, equivalence means that validating an instance against type T T In the statically known namespaces xml http://www.w3.org/XML/1998/namespace xml xmlns http://www.w3.org/2000/xmlns/ For each (expanded QName, arity) -> FunctionTest statically known function signatures (expanded QName, arity) -> function named functions signature DM30 FunctionTest As described in 2.2.3 Expression Processing static analysis phase dynamic evaluation phase [ Definition can , and is not a type error, static error static error [ Definition dynamic error [ Definition type error type error static type type error dynamic type The outcome of the static analysis phase type errors static errors dynamic errors dynamic evaluation phase type error dynamic error If more than one error is present, or if an error condition comes within the scope of more than one error defined in this specification, then any non-empty subset of these errors may be reported. During the static analysis phase Static Typing Feature static type () data(()) empty-sequence() static error err:XPST0005 in-scope schema definitions Independently of whether the Static Typing Feature static analysis phase a QueryBody dynamic error type error static analysis phase An implementation can raise a dynamic error for a QueryBody error() The following example contains a type error, which can be reported statically even if the implementation can not prove that the expression will actually be evaluated. if (empty($arg)) then "cat" * 2 else 0 [ Definition static errors dynamic errors type errors warnings static analysis phase dynamic evaluation phase implementation-defined In addition to the errors defined in this specification, an implementation may raise a dynamic error An error must be raised if such a limitation is exceeded [ err:XPDY0130 Note: Any limits on primitives defined by the XML and XSD specifications that differ from what these specifications state are implementation-defined 5.3 Data Model Conformance err:XPDY0130 The errors defined in this specification are identified by QNames that have the form err:XXYYnnnn err http://www.w3.org/2005/xqt-errors err XX XP XQ YY ST DY TY nnnn Note: The namespace URI for XPath and XQuery errors is not expected to change from one version of XQuery The method by which an XQuery 3.0 processor reports error information to the external environment is implementation-defined An error can be represented by a URI reference that is derived from the error QName as follows: an error with namespace URI NS LP NS # LP err:XPST0017 http://www.w3.org/2005/xqt-errors#XPST0017 Note: Along with a code identifying an error, implementations may wish to return additional information, such as the location of the error or the processing phase in which it was detected. If an implementation chooses to do so, then the mechanism that it uses to return this information is implementation-defined Except as noted in this document, if any operand of an expression raises a dynamic error dynamic error (see 2.3.4 Errors and Optimization expr1 and expr2 false false If more than one operand of an expression raises an error, the implementation may choose which error is raised by the expression. For example, in this expression: ($x div $y) + xs:decimal($z) both the sub-expressions ($x div $y) xs:decimal($z) + [ Definition error values . XQuery 3.0 provides standard error handling via Section 3.15 Try/Catch Expressions XQ30 A dynamic error may be raised by a built-in function div xs:decimal [XQuery and XPath Functions and Operators 3.0] A dynamic error can also be raised explicitly by calling the fn:error always a dynamic [XQuery and XPath Functions and Operators 3.0] app fn:error(xs:QName("app:err057"), "Unexpected value", fn:string($v)) Because different implementations may choose to evaluate or optimize an expression in different ways, certain aspects of raising dynamic errors implementation-dependent An implementation is always free to evaluate the operands of an operator in any order. In some cases, a processor can determine the result of an expression without accessing all the data that would be implied by the formal expression semantics. For example, the formal description of filter expressions $s[1] $s position()=1 $s //book[author eq 'Berners-Lee'] book author The extent to which a processor may optimize its access to data, at the cost of not raising errors, is defined by the following rules. Consider an expression Q E E Q V V E There is an exception to this rule: If a processor evaluates an operand E E $e eq 0 $e $e true $e These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands E1 E2 The rules cascade: if A B B C B C A B The effect of these rules is that the processor is free to stop examining further items in a sequence as soon as it can establish that further items would not affect the result except possibly by causing an error. For example, the processor may return true S1 = S2 Another consequence of these rules is that where none of the items in a sequence contributes to the result of an expression, the processor is not obliged to evaluate any part of the sequence. Again, however, the processor cannot dispense with a required cardinality check: if an empty sequence is not permitted in the relevant context, then the processor must ensure that the operand is not an empty sequence. Examples: If an implementation can find (for example, by using an index) that at least one item returned by $expr1 47 true some $expr1 some $x in $expr1 satisfies $x = 47 In the following example, if an implementation can find (for example, by using an index) the product id 47 path expression product id //product[id = 47] For a variety of reasons, including optimization, implementations may rewrite expressions into a different form. There are a number of rules that limit the extent of this freedom: Other than the raising or not raising of errors, the result of evaluating a rewritten expression must conform to the semantics defined in this specification for the original expression. Note: This allows an implementation to return a result in cases where the original expression would have raised an error, or to raise an error in cases where the original expression would have returned a result. The main cases where this is likely to arise in practice are (a) where a rewrite changes the order of evaluation, such that a subexpression causing an error is evaluated when the expression is written one way and is not evaluated when the expression is written a different way, and (b) where intermediate results of the evaluation cause overflow or other out-of-range conditions. Note: This rule does not mean that the result of the expression will always be the same in non-error cases as if it had not been rewritten, because there are many cases where the result of an expression is to some degree implementation-dependent implementation-defined Conditional and typeswitch expressions must not raise a dynamic error in respect of subexpressions occurring in a branch that is not selected, and must not return the value delivered by a branch unless that branch is selected. Thus, the following example must not raise a dynamic error if the document abc.xml if (doc-available('abc.xml')) then doc('abc.xml') else () As stated earlier, an expression must not be rewritten to dispense with a required cardinality check: for example, string-length(//title) Expressions must not be rewritten in such a way as to create or remove static errors. The static errors in this specification are defined for the original expression, and must be preserved if the expression is rewritten. Expression rewrite is illustrated by the following examples. Consider the expression //part[color eq "Red"] //part[color = "Red"][color eq "Red"] = eq Parts that have exactly one color that is Red are returned. If some part has color Red together with some other color, an error is raised. The existence of some part that has no color Red but has multiple non-Red colors does not trigger an error. The expression in the following example cannot raise a casting error if it is evaluated exactly as written (i.e., left to right). Since neither predicate depends on the context position, an implementation might choose to reorder the predicates to achieve better performance (for example, by taking advantage of an index). This reordering could cause the expression to raise an error. $N[@x castable as xs:date][xs:date(@x) gt xs:date("2000-01-01")] To avoid unexpected errors caused by expression rewrite, tests that are designed to prevent dynamic errors should be expressed using conditional or typeswitch $N[if (@x castable as xs:date) then xs:date(@x) gt xs:date("2000-01-01") else false()] This section explains some concepts that are important to the processing of XQuery 3.0 expressions. An ordering called document order query trees [XQuery and XPath Data Model (XDM) 3.0] implementation-dependent Definition document order Definition stable query implementation-dependent Definition reverse document order Within a tree, document order satisfies the following constraints: The root node is the first node. Every node occurs before all of its children and descendants. Attribute nodes immediately follow the element node with which they are associated. The relative order of attribute nodes is stable but implementation-dependent The relative order of siblings is the order in which they occur in the children Children and descendants occur before following siblings. The relative order of nodes in distinct trees is stable but implementation-dependent The semantics of some XQuery 3.0 operators depend on a process called atomization type error Definition Atomization fn:data [XQuery and XPath Functions and Operators 3.0] The semantics of fn:data fn:data If the item is an atomic value, it is returned. If the item is a node, its typed value If the item is a function DM30 Atomization is used in processing the following types of expressions: Arithmetic expressions Comparison expressions Function calls and returns Cast expressions Constructor expressions for various kinds of nodes order by group by Switch expressions Under certain circumstances (listed below), it is necessary to find the effective boolean value Definition effective boolean value fn:boolean [XQuery and XPath Functions and Operators 3.0] The dynamic semantics of fn:boolean If its operand is an empty sequence, fn:boolean false If its operand is a sequence whose first item is a node, fn:boolean true If its operand is a singleton xs:boolean xs:boolean fn:boolean If its operand is a singleton xs:string xs:anyURI xs:untypedAtomic fn:boolean false true If its operand is a singleton numeric fn:boolean false NaN true In all other cases, fn:boolean Note: The effective boolean value implementation-dependent ordering mode unordered The effective boolean value Logical expressions ( and or The fn:not The where Certain types of predicates a[b] Conditional expressions ( if Quantified expressions ( some every WindowStartCondition WindowEndCondition window Note: The definition of effective boolean value not xs:boolean cast xs:boolean XQuery 3.0 has a set of functions that provide access to input data. These functions are of particular importance because they provide a way in which an expression can reference a document or a collection of documents. The input functions are described informally here; they are defined in [XQuery and XPath Functions and Operators 3.0] An expression can access input data either by calling one of the input functions or by referencing some part of the dynamic context variable context item The input functions supported by XQuery 3.0 are as follows: The fn:doc available documents fn:doc data model dynamic error The fn:unparsed-text dynamic error The fn:environment-variable fn:available-environment-variables The fn:collection available node collections fn:collection dynamic error fn:collection("http://example.org")//customer customer http://example.org The fn:collection default collection implementation-dependent The fn:uri-collection xs:anyURI The fn:uri-collection default resource collection These input functions are all specified in [XQuery and XPath Functions and Operators 3.0] XQuery 3.0 requires a statically known, valid URI in a URILiteral BracedURILiteral static error err:XQST0046 a URI Literal or neither an absolute URI nor a relative URI As in a string literal, any predefined entity reference & character reference • EscapeQuot EscapeApos "" predefined entity reference character reference Note: The xs:anyURI [RFC3987] Whitespace is normalized using the whitespace normalization rules of fn:normalize-space Whitespace normalization is done after the expansion of character references 
 A Braced URI Literal or URI Literal is not subjected to percent-encoding or decoding as defined in [RFC3986] [ Definition resolve a relative URI $rel $base fn:resolve-uri($rel, $base) Any process that attempts to resolve URI The type system of XQuery 3.0 is based on [XML Schema 1.0] [XML Schema 1.1] [ Definition sequence type SequenceType sequence type [ Definition schema type [XML Schema 1.0] [XML Schema 1.1] [XML Schema 1.0] [XML Schema 1.1] xs:NOTATION xs:anyAtomicType complex type simple type list types union types atomic types [XML Schema 1.0] [XML Schema 1.1] [ Definition generalized atomic type pure union type [ Definition pure union type {variety} union {facets} {variety} list {variety} union {facets} Note: The definition of pure union type Note: The current (second) edition of XML Schema 1.0 contains an error in respect of the substitutability of a union type by one of its members: it fails to recognize that this is unsafe if the union is derived by restriction from another union. This problem is fixed in XSD 1.1, but the effect of the resolution is that an atomic value labeled with an atomic type cannot be treated as being substitutable for a union type without explicit validation. This specification therefore allows union types to be used as item types only if they are defined directly as the union of a number of atomic types. Generalized atomic types sequence type schema type xs:integer my:hatsize sequence type schema type The schema types defined in [XQuery and XPath Data Model (XDM) 3.0] The in-scope schema types static context http://www.w3.org/2001/XMLSchema xs [XML Schema 1.0] [XML Schema 1.1] [XQuery and XPath Data Model (XDM) 3.0] xs [XQuery and XPath Data Model (XDM) 3.0] [ Definition xs:untyped type annotation skip xs:untyped [ Definition xs:untypedAtomic skip data model type annotation xs:untypedAtomic xs:untypedAtomic [ Definition xs:dayTimeDuration xs:duration xs:dayTimeDuration [ Definition xs:yearMonthDuration xs:duration xs:yearMonthDuration [ Definition xs:anyAtomicType xs:anySimpleType xs:decimal xs:string xs:anyAtomicType Note: xs:anyAtomicType XDM instance [ Definition xs:error [XML Schema 1.1] 2.5.4 SequenceType Syntax The relationships among the schema types in the xs [XQuery and XPath Functions and Operators 3.0] Figure 2: Hierarchy of Schema Types used in XQuery 3.0. [ Definition namespace-sensitive xs:QName xs:NOTATION xs:QName xs:NOTATION It is not possible to preserve the type of a namespace-sensitive namespace-sensitive casting to a namespace-sensitive type error [err:FONS0004] Every node has a typed value string value , except for nodes whose value is absent DM30 Definition typed value fn:data Definition string value fn:string fn:data fn:string [XQuery and XPath Functions and Operators 3.0] An implementation may store both the typed value string value xs:integer 30 30 0030 The typed value string value type annotation If the node was created by mapping from an Infoset or PSVI, see rules in [XQuery and XPath Data Model (XDM) 3.0] If the node was created by an XQuery node constructor, see rules in 3.9.1 Direct Element Constructors 3.9.3.1 Computed Element Constructors 3.9.3.2 Computed Attribute Constructors If the node was created by a validate 3.18 Validate Expressions As a convenience to the reader, the relationship between typed value string value For text and document nodes, the typed value of the node is the same as its string value, as an instance of the type xs:untypedAtomic document order The typed value of a comment or processing instruction node is the same as its string value. It is an instance of the type xs:string The typed value of an attribute node with the type annotation xs:anySimpleType xs:untypedAtomic xs:untypedAtomic [XML Schema 1.0] [XML Schema 1.1] Example: A1 is an attribute having string value "3.14E-2" xs:double xs:double 3.14E-2 Example: A2 is an attribute with type annotation xs:IDREFS xs:IDREF bar baz faz bar baz faz xs:IDREF xs:IDREFS generalized atomic type xs:IDREF For an element node, the relationship between typed value and string value depends on the node's type annotation If the type annotation is xs:untyped xs:anySimpleType xs:anyType xs:untypedAtomic nilled true Example: E1 is an element node having type annotation xs:untyped 1999-05-31 1999-05-31 xs:untypedAtomic Example: E2 is an element node with the type annotation formula H subscript 2 O H2O xs:untypedAtomic If the type annotation denotes a simple type or a complex type with simple content, then the typed value of the node is derived from its string value and its type annotation in a way that is consistent with schema validation. However, if the nilled true Example: E3 is an element node with the type annotation cost xs:decimal 74.95 74.95 xs:decimal Example: E4 is an element node with the type annotation hatsizelist hatsize xs:integer 7 8 9 7 8 9 hatsize Example: E5 is an element node with the type annotation my:integer-or-string xs:integer xs:string 47 47 xs:integer xs:integer Note: If an implementation stores only the string value of a node, and the type annotation of the node is a union type, the implementation must be able to deliver the typed value of the node as an instance of the appropriate member type. If the type annotation denotes a complex type with empty content, then the typed value of the node is the empty sequence and its string value is the zero-length string. If the type annotation denotes a complex type with element-only content, then the typed value of the node is absent DM30 fn:data type error [err:FOTY0012] Example: E6 is an element node with the type annotation weather element-only temperature precipitation absent DM30 fn:data Whenever it is necessary to refer to a type in an XQuery 3.0 expression, the SequenceType SequenceType ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator ItemType ::= KindTest FunctionTest AtomicOrUnionType ParenthesizedItemType OccurrenceIndicator ::= "?" | "*" | "+" AtomicOrUnionType ::= EQName KindTest ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest NamespaceNodeTest AnyKindTest DocumentTest ::= "document-node" "(" ( ElementTest SchemaElementTest ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName SchemaElementTest ::= "schema-element" "(" ElementDeclaration ElementDeclaration ::= ElementName AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration AttributeDeclaration ::= AttributeName ElementNameOrWildcard ::= ElementName ElementName ::= EQName AttribNameOrWildcard ::= AttributeName AttributeName ::= EQName TypeName ::= EQName PITest ::= "processing-instruction" "(" ( NCName StringLiteral CommentTest ::= "comment" "(" ")" NamespaceNodeTest ::= "namespace-node" "(" ")" TextTest ::= "text" "(" ")" AnyKindTest ::= "node" "(" ")" FunctionTest ::= Annotation AnyFunctionTest TypedFunctionTest AnyFunctionTest ::= "function" "(" "*" ")" TypedFunctionTest ::= "function" "(" ( SequenceType SequenceType SequenceType ParenthesizedItemType ::= "(" ItemType With the exception of the special type empty-sequence() sequence type item type cardinality item() node types element() generalized atomic types xs:integer Lexical QNames sequence type statically known namespaces default element/type namespace eq Item types representing element and attribute nodes may specify the required type annotations schema type element(*, us:address) us:address The occurrence indicators '+', '*', and '?' bind to the last ItemType SequenceType occurrence-indicators Here are some examples of sequence types xs:date xs:date attribute()? element() element(po:shipto, po:address) po:shipto po:address po:address element(*, po:address) po:address po:address element(customer) customer schema-element(customer) customer customer customer in-scope element declarations node()* item()+ items function(*) function DM30 function(node()) as xs:string* function DM30 (function(node()) as xs:string)* functions DM30 [ Definition SequenceType matching dynamic type sequence type instance of true dynamic type sequence type false An XQuery 3.0 implementation must be able to determine relationships among the types in type annotations in an XDM instance in-scope schema definitions An XQuery 3.0 implementation must be able to determine relationships among the types in ISSDs used in different modules of the same query. [ Definition dynamic type subtype substitution xs:integer xs:decimal xs:integer The definition of SequenceType matching derives-from( AT ET ) AT ET type error err:XPTY0004 This function is defined as follows: derives-from( AT ET ) err:XPTY0004 ET the in-scope schema definitions derives-from( AT ET ) true if any of the following conditions applies: AT ET ET AT ET AT There is a type MT derives-from( AT MT ) derives-from( MT ET ) Otherwise, derives-from( AT ET ) false The rules for SequenceType matching The sequence type empty-sequence() An ItemType OccurrenceIndicator ItemType 2.5.5.2 Matching an ItemType and an Item An ItemType OccurrenceIndicator OccurrenceIndicator ItemType An OccurrenceIndicator ? * + As a consequence of these rules, any sequence type OccurrenceIndicator * ? An ItemType AtomicOrUnionType AtomicOrUnionType AT derives-from( AT, AtomicOrUnionType ) true The name of an AtomicOrUnionType statically known namespaces default element/type namespace expanded QName AtomicOrUnionType generalized atomic type in-scope schema types static error err:XPST0051 Example: The ItemType xs:decimal xs:decimal shoesize shoesize xs:decimal Example: Suppose ItemType dress-size xs:decimal xs:strings ItemType dress-size Note: The names of non-atomic types such as xs:IDREFS generalized atomic type xs:IDREF+ item() item Example: item() 1 <a/> fn:concat#3 node() text() processing-instruction() processing-instruction( N ) fn:normalize-space(N) fn:normalize-space(N) err:XPTY0004 Example: processing-instruction(xml-stylesheet) xml-stylesheet For backward compatibility with XPath 1.0, the PITarget of a processing instruction may also be expressed as a string literal, as in this example: processing-instruction("xml-stylesheet") If the specified PITarget is not a syntactically valid NCName, a type error is raised [ err:XPTY0004 comment() namespace-node() document-node() document-node( E ) E ElementTest SchemaElementTest 2.5.5.3 Element Test 2.5.5.4 Schema Element Test Example: document-node(element(book)) element(book) A ParenthesizedItemType ItemType An ItemType ElementTest SchemaElementTest AttributeTest SchemaAttributeTest FunctionTest ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName ElementNameOrWildcard ::= ElementName ElementName ::= EQName TypeName ::= EQName An ElementTest type annotation The ElementName TypeName ElementTest statically known namespaces default element/type namespace ElementName in-scope element declarations TypeName in-scope schema types err:XPST0008 substitution groups ElementTest An ElementTest element() element(*) element( ElementName ) ElementName nilled Example: element(person) person element( ElementName , TypeName ) ElementName derives-from( AT TypeName ) true AT nilled false Example: element(person, surgeon) person surgeon surgeon element( ElementName TypeName ?) ElementName derives-from( AT TypeName ) true AT nilled true false Example: element(person, surgeon?) person surgeon surgeon element(*, TypeName ) derives-from( AT TypeName ) true AT nilled false Example: element(*, surgeon) surgeon surgeon element(*, TypeName ?) derives-from( AT TypeName ) true AT nilled true false Example: element(*, surgeon?) surgeon surgeon SchemaElementTest ::= "schema-element" "(" ElementDeclaration ElementDeclaration ::= ElementName ElementName ::= EQName A SchemaElementTest in-scope element declarations The ElementName SchemaElementTest statically known namespaces default element/type namespace ElementName SchemaElementTest in-scope element declarations static error err:XPST0008 A SchemaElementTest Either: The name N ElementName The name N ElementName Note: The term "actual substitution group" is defined in [XML Schema 1.1] H P H P P H The schema element declaration named N derives-from( AT, ET ) AT ET N If the schema element declaration named N Example: The SchemaElementTest schema-element(customer) in the following two situations: customer is a top-level element declaration in the in-scope element declarations; the name of the candidate node is customer; the element declaration of customer is not abstract; the type annotation of the candidate node is the same as or derived from the schema type declared in the customer element declaration; and either the candidate node is not nilled, or customer is declared to be nillable. customer is a top-level element declaration in the in-scope element declarations; the name of the candidate node is client; client is an actual (non-abstract and non-blocked) member of the substitution group of customer; the type annotation of the candidate node is the same as or derived from the schema type declared for the client element; and either the candidate node is not nilled, or client is declared to be nillable. AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName AttribNameOrWildcard ::= AttributeName AttributeName ::= EQName TypeName ::= EQName An AttributeTest type annotation The AttributeName TypeName AttributeTest statically known namespaces AttributeName TypeName default element/type namespace AttributeName in-scope attribute declarations TypeName in-scope schema types err:XPST0008 An AttributeTest attribute() attribute(*) attribute( AttributeName ) AttributeName Example: attribute(price) price attribute( AttributeName TypeName ) AttributeName derives-from( AT TypeName ) true AT Example: attribute(price, currency) price currency currency attribute(*, TypeName ) derives-from( AT TypeName ) true AT Example: attribute(*, currency) currency currency SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration AttributeDeclaration ::= AttributeName AttributeName ::= EQName A SchemaAttributeTest in-scope attribute declarations The AttributeName SchemaAttributeTest statically known namespaces AttributeName AttributeName SchemaAttributeTest in-scope attribute declarations static error err:XPST0008 A SchemaAttributeTest The name of the candidate node matches the specified AttributeName derives-from( AT, ET ) true AT ET AttributeName in-scope attribute declarations Example: The SchemaAttributeTest schema-attribute(color) color in-scope attribute declarations color color FunctionTest ::= Annotation AnyFunctionTest TypedFunctionTest AnyFunctionTest ::= "function" "(" "*" ")" TypedFunctionTest ::= "function" "(" ( SequenceType SequenceType SequenceType A FunctionTest function DM30 function signature DM30 and annotations (see 4.15 Annotations AnyFunctionTest TypedFunctionTest function DM30 Section 2.8.1 Functions DM30 subtype TypedFunctionTest Here are some examples of FunctionTest function(*) function DM30 %assertion function(*) function DM30 %assertion function(int, int) as int function DM30 function(int, int) as int %assertion function(int, int) as int function DM30 function(int, int) as int %assertion [ Definition function assertion 4.15 Annotations Implementations are free to define their own function assertions, whose behavior is completely implementation-defined. Implementations may also provide a way for users to create their own function assertions. An implementation may raise implementation-defined errors or warnings for function assertions, e.g. if the parameters are not correct for a given assertion. If a function assertion is not recognized by an implementation, it is ignored, and has no effect on the semantics of the function test. Note: An implementation is free to raise warnings for function assertions that it does not recognize. Note: Although function assertions use the same syntax as annotations, they are not directly related to annotations. If an implementation defines the annotation blue blue blue blue Implementations must not define function assertions in the following reserved namespaces; it is an error for users to create function assertions in the following reserved namespaces [ err:XQST0045 http://www.w3.org/XML/1998/namespace http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2005/xpath-functions http://www.w3.org/2005/xpath-functions/math http://www.w3.org/2012/xquery Given two sequence types Definition sequence type A subtype B subtype(A, B) subtype(A, B) V (V instance of A) (V instance of B) subtype(A, B) The judgement subtype(A, B) sequence type A subtype B A empty-sequence() , xs:error ItemType Ai B empty-sequence() , xs:error ItemType Bi subtype(A, B) subtype-itemtype(Ai, Bi) 2.5.6.2 The judgement subtype-itemtype(Ai, Bi) Sequence type B empty-sequence() Bi? Bi* Bi Bi+ xs:error Sequence type A empty-sequence() true true true false false false Ai? false subtype-itemtype(Ai, Bi) subtype-itemtype(Ai, Bi) false false false Ai* false false subtype-itemtype(Ai, Bi) false false false Ai false subtype-itemtype(Ai, Bi) subtype-itemtype(Ai, Bi) subtype-itemtype(Ai, Bi) subtype-itemtype(Ai, Bi) false Ai+ false false subtype-itemtype(Ai, Bi) false subtype-itemtype(Ai, Bi) false xs:error true true true true true true xs:error+ xs:error xs:error? xs:error* empty-sequence() subtype-itemtype(Ai, Bi) The judgement subtype-itemtype(Ai, Bi) ItemType Ai subtype Bi Ai Bi Ai Bi AtomicOrUnionTypes derives-from(Ai, Bi) true Ai t Ai subtype-itemType(t, Bi) Ai xs:error Bi generalized atomic type Bi item() Bi node() Ai KindTest Bi text() Ai text() Bi comment() Ai comment() Bi namespace-node() Ai namespace-node() Bi processing-instruction() Ai processing-instruction() processing-instruction(N) Bi processing-instruction(Bn) Ai processing-instruction(Bn) Bi document-node() Ai document-node() document-node(E) ElementTest Bi document-node(Be) Ai document-node(Ae) subtype-itemtype(Ae, Be) Bi element() element(*) Ai ElementTest Bi element(Bn) element(Bn, xs:anyType?) expanded QName An expanded QName Bn Ai element(An) element(An, T?) Bi element(Bn, Bt) expanded QName An expanded QName Bn Ai element(An, At) derives-from(At, Bt) true Bi element(Bn, Bt?) expanded QName An expanded QName Bn Ai element(An, At) element(An, At?) derives-from(At, Bt) true Bi element(*, Bt) Ai element(*, At) element(N, At) derives-from(At, Bt) true Bi element(*, Bt?) Ai element(*, At) element(*, At?) element(N, At) element(N, At?) derives-from(At, Bt) true Bi schema-element(Bn) Ai schema-element(An) An Bn Note: The fact that P Q P Q Q P Bi attribute() attribute(*) Ai AttributeTest Bi attribute(Bn) attribute(Bn, xs:anyType) expanded QName An expanded QName Bn Ai attribute(An) attribute(An, T) Bi attribute(Bn, Bt) expanded QName An expanded QName Bn Ai attribute(An, At) derives-from(At, Bt) true Bi attribute(*, Bt) Ai attribute(*, At) attribute(N, At) derives-from(At, Bt) true Bi schema-attribute(Bn) expanded QName An expanded QName Bn Ai schema-attribute(An) Bi [AnnotationsB] , Ai FunctionTest [AnnotationsA] subtype-assertions(AnnotationsA, AnnotationsB) , where [AnnotationsB] [AnnotationsA] Bi AnnotationsB Ai AnnotationsA [AnnotationsB] [AnnotationsA] N M subtype(Ar, Br) I N subtype(Ba_I, Aa_I) ; and subtype-assertions(AnnotationsA, AnnotationsB) Note: Function return types are covariant because this rule invokes subtype(Ar, Br) for return types. Function arguments are contravariant because this rule invokes subtype(Ba_I, Aa_I) for arguments. subtype-assertions(AnnotationsA, AnnotationsB) The judgement subtype-assertions(AnnotationsA, AnnotationsB) AnnotationsA AnnotationsB AnnotationsA AnnotationsB function subtype-assertions() The following examples are some possible ways to define subtype-assertions() local AnnotationsA is %local:inline It has no influence on the outcome of subtype-assertions() AnnotationsA is %local:deterministic AnnotationsB is %local:nondeterministic Since deterministic functions are a subset of nondeterministic functions, subtype-assertions() AnnotationsA contains %local:nondeterministic AnnotationsB is empty. If FunctionTests without the %local:nondeterministic subtype-assertions() The type xs:error xs:error A cast to xs:error xs:error xs:error xs:error+ xs:error xs:error? xs:error* Comment ::= "(:" ( CommentContents Comment CommentContents ::= ( Char Comments may be used to provide information relevant to programmers who read a query, either in the Prolog Query Body query Comments are strings, delimited by the symbols (: :) A comment may be used anywhere ignorable whitespace A.2.4.1 Default Whitespace Handling The following is an example of a comment: (: Houston, we have a problem :) This section discusses each of the basic kinds of expression. Each kind of expression has a name such as PathExpr The order in which expressions are discussed in this document does not reflect the order of operator precedence. In general, this document introduces the simplest kinds of expressions first, followed by more complex expressions. For the complete grammar, see Appendix [ A XQuery 3.0 Grammar [ Definition query modules Query Body Expr Expr ::= ExprSingle ExprSingle ExprSingle ::= FLWORExpr QuantifiedExpr SwitchExpr TypeswitchExpr IfExpr TryCatchExpr OrExpr The XQuery 3.0 operator that has lowest precedence is the comma operator Expr ExprSingle ExprSingle comma operator ExprSingle The symbol ExprSingle ExprSingle After the comma, the expressions that have next lowest precedence are FLWORExpr QuantifiedExpr SwitchExpr TypeswitchExpr IfExpr TryCatchExpr OrExpr [ Definition Primary expressions constructors, Constructors are described in 3.9 Constructors PrimaryExpr ::= Literal VarRef ParenthesizedExpr ContextItemExpr FunctionCall OrderedExpr UnorderedExpr Constructor FunctionItemExpr FunctionItemExpr ::= NamedFunctionRef InlineFunctionExpr [ Definition literal Literal ::= NumericLiteral StringLiteral NumericLiteral ::= IntegerLiteral DecimalLiteral DoubleLiteral IntegerLiteral ::= Digits DecimalLiteral ::= ("." Digits Digits DoubleLiteral ::= (("." Digits Digits Digits StringLiteral ::= ('"' ( PredefinedEntityRef CharRef EscapeQuot PredefinedEntityRef CharRef EscapeApos PredefinedEntityRef ::= "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";" EscapeQuot ::= '""' EscapeApos ::= "''" Digits ::= [0-9]+ The value of a numeric literal . e E xs:integer . e E xs:decimal e E xs:double xs:untypedAtomic Section 18.2 Casting from xs:string and xs:untypedAtomic FO30 The value of a string literal xs:string A string literal may contain a predefined entity reference Definition predefined entity reference Entity Reference Character Represented < < > > & & " " ' ' A string literal may also contain a character reference Definition character reference [Unicode] € implementation-defined [XML 1.0] [XML 1.1] static error err:XQST0090 Here are some examples of literal expressions: "12.5" 12 xs:integer 12.5 xs:decimal 125E2 xs:double "He said, ""I don't like it.""" "Ben & Jerry's" xs:string Ben & Jerry's "€99.50" xs:string €99.50 The xs:boolean true false built-in functions fn:true() fn:false() Values of other atomic types can be constructed by calling the constructor function [XQuery and XPath Functions and Operators 3.0] xs:integer("12") xs:date("2001-08-25") xs:date xs:dayTimeDuration("PT5H") xs:dayTimeDuration Constructor functions can also be used to create special values that have no literal representation, as in the following examples: xs:float("NaN") xs:double("INF") Constructor functions are available for all Generalized atomic types my:dt xs:date xs:time xs:dateTime my:dt("2011-01-10") xs:date It is also possible to construct values of various types by using a cast 9 cast as hatsize 9 hatsize VarRef ::= "$" VarName VarName ::= EQName [ Definition variable reference Two variable references are equivalent if their expanded QNames eq Every variable reference must match a name in the in-scope variables Every variable binding has a static scope. The scope defines where references to the variable can validly occur. It is a static error err:XPST0008 static context except where it is occluded by another binding that uses the same name within that scope A reference to a variable that was declared external err:XPDY0002 At evaluation time, the value of a variable reference is the value to which the relevant variable is bound. ParenthesizedExpr ::= "(" Expr Parentheses may be used to override the precedence rules. For example, the expression (2 + 4) * 5 (2 + 4) 2 + 4 * 5 Empty parentheses are used to denote an empty sequence, as described in 3.4.1 Constructing Sequences ContextItemExpr ::= "." A context item expression context item fn:doc("bib.xml")/books/book[fn:count(./author)>1] (1 to 100)[. mod 5 eq 0] If the context item absent DM30 err:XPDY0002 Static [ Definition built-in functions [XQuery and XPath Functions and Operators 3.0] Additional functions may be declared in a Prolog library module static context FunctionCall ::= EQName ArgumentList ArgumentList ::= "(" ( Argument Argument Argument ::= ExprSingle ArgumentPlaceholder ArgumentPlaceholder ::= "?" [ Definition static Definition argument expression static is a lexical QName default function namespace. If the expanded QName static function signature static context static error err:XPST0017 [ Definition static or dynamic partial function application Evaluation of function calls is described in 3.1.5.1 Evaluating Static and Dynamic Function Calls Since the arguments of a function call are separated by commas, any argument expression comma operator static my:three-argument-function(1, 2, 3) static my:two-argument-function((1, 2), 3) static my:two-argument-function(1, ()) static my:one-argument-function((1, 2, 3)) static my:one-argument-function(( )) static my:zero-argument-function( ) static Static and Dynamic When a static or dynamic function call FC a static context SC DC [ Definition Argument ArgumentList arity The function to be called or partially applied (call it F If FC FC EQName FC ArgumentList named functions DC F If FC FC SC DC ArgumentList F err:XPTY0004 [ Definition Argument expressions with respect to DC argument values implementation-dependent Each argument value is converted to the corresponding parameter type in F function conversion rules resulting in a converted argument value The remainder depends on whether or not FC partial function application If FC [ Definition fixed position ArgumentList ArgumentPlaceholder A new (as the value of FC Section 2.8.1 Functions DM30 name Absent. parameter names F signature The signature of F implementation The implementation of F , associated with the same contexts as in F F SC DC nonlocal variable bindings The nonlocal variable bindings of F If FC If F implementation-dependent F using the contexts it is associated with in F F SC DC The result is either an instance of F FC Errors raised by built-in functions are defined in [XQuery and XPath Functions and Operators 3.0] Errors raised by external functions are implementation-defined 2.2.5 Consistency Constraints If F FunctionBody The FunctionBody module FunctionBody The focus absent DM30 In the variable values When this is done, converted dynamic type $p xs:decimal xs:integer xs:decimal call dynamic type $p xs:integer F's nonlocal variable bindings are also added to the variable values The value returned by evaluating the function body is then converted to the declared return type of F function conversion rules FC As with argument values, F xs:decimal xs:integer [ Definition function conversion rules or a return value parameter or return. sequence type If the expected type is a sequence of a generalized atomic type * + ? Atomization Each item in the atomic sequence that is of type xs:untypedAtomic generalized built-in functions numeric xs:untypedAtomic xs:double If the item is of type xs:untypedAtomic namespace-sensitive type error err:XPTY0117 For each numeric promoted B.1 Type Promotion For each item of type xs:anyURI promoted B.1 Type Promotion If the expected type is a TypedFunctionTest * + ? function coercion If, after the above conversions, the resulting value does not match the expected type according to the rules for SequenceType Matching type error err:XPTY0004 If the function call takes place in a module module in-scope schema definitions SequenceType Matching Function coercion is a transformation applied to functions DM30 function conversion rules Definition Function coercion function DM30 Function coercion is only defined to operate on functions DM30 F and an expected function type proceeds as follows: If F err:XPTY0004 Section 2.8.1 Functions DM30 name F parameter names F signature Annotations F TypedFunctionTest implementation In effect, a FunctionBody F nonlocal variable bindings An empty mapping. If the result of invoking the new function would necessarily result in a type error, that error may be raised during function coercion. It is implementation dependent whether this happens or not. These rules have the following consequences: SequenceType matching of the function's arguments and result are delayed until that function is invoked. The function conversion rules applied to the function's arguments and result are defined by the SequenceType it has most recently been coerced to. Additional function conversion rules could apply when the wrapped function is invoked. If an implementation has static type information about a function, that can be used to type check the function's argument and return types during static analysis. For instance, consider the following query: declare function local:filter($s as item()*, $p as function(xs:string) as xs:boolean) as item()* { $s[$p(.)] };
let $f := function($a) { starts-with($a, "E") } return local:filter(("Ethel", "Enid", "Gertrude"), $f) The function $f function(item()*) as item()* local:filter() The function conversion rules result in applying function coercion to $f function(xs:string) as xs:boolean $p is matched against the SequenceType of function(xs:string) as xs:boolean When $p is invoked inside the predicate, function conversion and SequenceType matching rules are applied to the context item argument, resulting in an xs:string $f is invoked with the xs:string xs:boolean $p applies function conversion rules to the result sequence from $f, which already matches its declared return type of xs:boolean The xs:boolean Note: Although the semantics of function coercion are specified in terms of wrapping the functions, static typing will often be able to reduce the number of places where this is actually necessary. Named Function References NamedFunctionRef ::= EQName IntegerLiteral EQName ::= QName URIQualifiedName [ Definition named function reference denotes named function Definition named function query expanded If the EQName is a lexical QName If the expanded QName named function reference err:XPST0017 The value of a NamedFunctionRef named functions Furthermore, if the function referenced by a NamedFunctionRef NamedFunctionRef NamedFunctionRef Certain functions in the [XQuery and XPath Functions and Operators 3.0] named function references Note: The above way of modeling polymorphic functions is semantically backwards compatible with XQuery 1.0 The following are examples of named function references fn:abs#1 fn:concat#5 local:myfunc#2 Expression InlineFunctionExpr ::= Annotation ParamList SequenceType FunctionBody [ Definition inline function expression function DM30 expression If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted from an inline function expression, its default result type is item()*. The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error [ err:XQST0039 An inline function expression expression static error err:XQST0125 expression %public %private The static context for the function body is inherited from the location of the inline function expression, with the exception of the static type of the context item which is initially absent DM30 The variables in scope for the function body include all variables representing the function parameters, as well as all variables that are in scope for the inline function expression. Note: Function parameter names can mask variables that would otherwise be in scope for the function body. The result of an inline function expression Section 2.8.1 Functions DM30 name Absent. parameter names InlineFunctionExpr ParamList signature A FunctionTest Annotation SequenceType InlineFunctionExpr implementation The InlineFunctionExpr FunctionBody nonlocal variable bindings For each nonlocal variable, a binding of it to its value in the variable values InlineFunctionExpr The following are examples of some inline function expression This example creates a function that takes no arguments and returns a sequence of the first 6 primes: function() as xs:integer+ { 2, 3, 5, 7, 11, 13 } This example creates a function that takes two xs:double arguments and returns their product: function($a as xs:double, $b as xs:double) as xs:double { $a * $b } This example creates a function that returns its item()* argument: function($a) { $a } This example creates a sequence of functions each of which returns a different node from the default collection. collection()/(let $a := . return function() { $a }) PostfixExpr ::= PrimaryExpr Predicate ArgumentList Predicate ::= "[" Expr ArgumentList ::= "(" ( Argument Argument [ Definition E1[E2] filter expression E1 3.2.1 Filter Expressions An expression (other than a raw EQName) followed by an argument list in parentheses (that is, E1(E2, E3, ...) dynamic function call E1 E2 E3 ... calls 3.2.2 Dynamic Function Call PostfixExpr ::= PrimaryExpr Predicate ArgumentList Predicate ::= "[" Expr A filter expression consists of a base expression followed by a predicate, which is an expression written in square brackets. The result of the filter expression consists of the items returned by the base expression, filtered by applying the predicate to each item in turn. The ordering of the items returned by a filter expression is the same as their order in the result of the primary expression. Note: Where the expression before the square brackets is a ReverseStep ForwardStep AxisStep 3.3.3 Predicates within Steps Here are some examples of filter expressions: Given a sequence of products in a variable, return only those products whose price is greater than 100. $products[price gt 100] List all the integers from 1 to 100 that are divisible by 5. (See 3.4.1 Constructing Sequences to (1 to 100)[. mod 5 eq 0] The result of the following expression is the integer 25: (21 to 29)[5] The following example returns the fifth through ninth items in the sequence bound to variable $orders $orders[fn:position() = (5 to 9)] The following example illustrates the use of a filter expression as a step path expression $book $book/(chapter | appendix)[fn:last()] For each item in the input sequence, the predicate expression is evaluated using an inner focus For each item in the input sequence, the result of the predicate expression is coerced to an xs:boolean predicate truth value true false The predicate truth value is derived by applying the following rules, in order: If the value of the predicate expression is a singleton numeric numeric true eq context position false Definition numeric predicate Note: In a region of a query where ordering mode unordered implementation-dependent 3.11 Ordered and Unordered Expressions Otherwise, the predicate truth value is the effective boolean value Call PostfixExpr ::= PrimaryExpr Predicate ArgumentList ArgumentList ::= "(" ( Argument Argument Argument ::= ExprSingle ArgumentPlaceholder ArgumentPlaceholder ::= "?" [ Definition dynamic function call base expression argument expressions A dynamic function call is evaluated as described in 3.1.5.1 Evaluating Static and Dynamic Function Calls The following are examples of some dynamic function calls This example invokes the function contained in $f, passing the arguments 2 and 3: $f(2, 3) This example fetches the second item from sequence $f, treats it as a function and invokes it, passing an xs:string $f[2]("Hi there") This example invokes the function $f passing no arguments, and filters the result with a positional predicate: $f()[2] PathExpr ::= ("/" RelativePathExpr RelativePathExpr RelativePathExpr RelativePathExpr ::= StepExpr StepExpr [ Definition path expression steps / // / // / // A path expression consisting of a single step is evaluated as described in 3.3.2 Steps A " / (fn:root(self::node()) treat as document-node()) / / type error err:XPTY0020 dynamic error err:XPDY0050 A " // (fn:root(self::node()) treat as document-node()) // err:XPST0003 type error err:XPTY0020 dynamic error err:XPDY0050 Note: The descendants of a node do not include attribute nodes. RelativePathExpr ::= StepExpr StepExpr Relative path expressions are binary operators on step expressions, which are named E1 E2 Each non-initial occurrence of " // 3.3.5 Abbreviated Syntax / E1 context item E2 E2 The following example illustrates the use of relative path expressions. child::div1/child::para Selects the para div1 para div1 Note: Since each step in a path provides context nodes for the following step, in effect, only the last step in a path is allowed to return a sequence of non-nodes. Note: The " / /* * / * leading-lone-slash /* / * /*5 / * 5 / (/) * 5 4 + / * 5 4 + (/) * 5 4 + / / Similarly, in the expression / union /* (/) union /* / The path operator "/" is used to build expressions for locating nodes within trees. Its left-hand side expression must return a sequence of nodes. The operator Each operation E1/E2 E1 S type error err:XPTY0019 S S S E2 2.1.2 Dynamic Context E2 If every evaluation of E2 If ordering mode is ordered, the resulting node sequence is returned in document order implementation-dependent If every evaluation of E2 If ordering mode ordered E2 implementation-dependent If the multiple evaluations of E2 type error err:XPTY0018 Note: The semantics of the path operator can also be defined using the simple mapping operator as follows (forming the union with an empty sequence ($R | ()) E1/E2 ::= let $R := E1!E2 return if (every $r in $R satisfies $r instance of node()) then ($R|()) else if (every $r in $R satisfies not($r instance of node())) then $R else error() StepExpr ::= PostfixExpr AxisStep AxisStep ::= ( ReverseStep ForwardStep PredicateList ForwardStep ::= ( ForwardAxis NodeTest AbbrevForwardStep ReverseStep ::= ( ReverseAxis NodeTest AbbrevReverseStep PredicateList ::= Predicate [ Definition step path expression predicates axis step 3.2 Postfix Expressions [ Definition axis step axis node test type annotation type error err:XPTY0020 If ordering mode ordered document order implementation-dependent forward step reverse step predicates In the abbreviated syntax 3.3.5 Abbreviated Syntax The unabbreviated syntax for an axis step consists of the axis name and node test separated by a double colon. The result of the step consists of the nodes reachable from the context node via the specified axis that have the node kind, name, and/or type annotation child::para para child para 3.3.2.1 Axes 3.3.2.2 Node Tests 3.3.4 Unabbreviated Syntax 3.3.5 Abbreviated Syntax ForwardAxis ::= ("child" "::") ReverseAxis ::= ("parent" "::") XQuery supports the following axes: The child dm:children [XQuery and XPath Data Model (XDM) 3.0] Note: Only document nodes and element nodes have children. If the context node is any other kind of node, or if the context node is an empty document or element node, then the child axis is an empty sequence. The children of a document node or element node may be element, processing instruction, comment, or text nodes. Attribute and document nodes can never appear as children. the descendant the parent dm:parent [XQuery and XPath Data Model (XDM) 3.0] Note: An attribute node may have an element node as its parent, even though the attribute node is not a child of the element node. the ancestor Note: The ancestor axis includes the root node of the tree in which the context node is found, unless the context node is the root node. the following-sibling document order following-sibling the preceding-sibling document order preceding-sibling the following document order the preceding document order the attribute dm:attributes [XQuery and XPath Data Model (XDM) 3.0] the self the descendant-or-self the ancestor-or-self Axes can be categorized as forward axes reverse axes document order document order The parent ancestor ancestor-or-self preceding preceding-sibling ancestor descendant following preceding self [ Definition principal node kind For the attribute axis, the principal node kind is attribute. For all other axes, the principal node kind is element. [ Definition node test type annotation step NodeTest ::= KindTest NameTest NameTest ::= EQName Wildcard Wildcard ::= "*" NCName NCName BracedURILiteral EQName ::= QName URIQualifiedName [ Definition name test kind principal node kind expanded QName eq expanded QName child::para para para attribute::abc:href abc:href If the EQName is a lexical QName expanded QName statically known namespaces static error err:XPST0081 principal node kind default element/type namespace A name test is not satisfied by an element node whose name does not match the expanded QName substitution group A node test * principal node kind child::* attribute::* A node test can have the form NCName:* lexical QName statically known namespaces static context static error err:XPST0081 principal node kind expanded QName A node test can contain a BracedURILiteral, e.g. Q{http://example.com/msg}* A node test can also have the form *:NCName principal node kind [ Definition kind test type annotation 2.5.4 SequenceType Syntax 2.5.5 SequenceType Matching node test node() text() comment() namespace-node() element() schema-element(person) person substitution group person person in-scope element declarations element(person) person element(person, surgeon) person surgeon surgeon element(*, surgeon) surgeon surgeon attribute() attribute(price) price attribute(*, xs:decimal) xs:decimal xs:decimal document-node() document-node(element(book)) kind test element(book) AxisStep ::= ( ReverseStep ForwardStep PredicateList PredicateList ::= Predicate Predicate ::= "[" Expr A predicate within a Step has similar syntax and semantics to a predicate within a filter expression For the purpose of evaluating the context position within a predicate, the input sequence is considered to be sorted as follows: into document order if the predicate is in a forward-axis step, into reverse document order if the predicate is in a reverse-axis step, or in its original order if the predicate is not in a step. Here are some examples of axis steps This example selects the second chapter child::chapter[2] This example selects all the descendants of the context node that are elements named "toy" color "red" descendant::toy[attribute::color = "red"] This example selects all the employee secretary assistant child::employee[secretary][assistant] Note: When using predicates reverse axis reverse document order preceding::foo[1] foo reverse document order axis step (preceding::foo)[1] foo document order (preceding::foo) primary expression ancestor::*[1] ancestor (ancestor::*)[1] The fact that a reverse-axis step assigns context positions in reverse document order for the purpose of evaluating predicates does not alter the fact that the final result of the step (when in ordered mode) This section provides a number of examples of path expressions in which the axis is explicitly specified in each step unabbreviated syntax abbreviated syntax 3.3.5 Abbreviated Syntax child::para para child::* child::text() child::node() attribute::name name attribute::* parent::node() descendant::para para ancestor::div div ancestor-or-self::div div div descendant-or-self::para para para self::para para child::chapter/descendant::para para chapter child::*/child::para para / /descendant::para para /descendant::list/child::member member list child::para[fn:position() = 1] para child::para[fn:position() = fn:last()] para child::para[fn:position() = fn:last()-1] para child::para[fn:position() > 1] para para following-sibling::chapter[fn:position() = 1] chapter preceding-sibling::chapter[fn:position() = 1] chapter /descendant::figure[fn:position() = 42] figure /child::book/child::chapter[fn:position() = 5]/child::section[fn:position() = 2] section chapter book child::para[attribute::type eq "warning"] para type warning child::para[attribute::type eq 'warning'][fn:position() = 5] para type warning child::para[fn:position() = 5][attribute::type eq "warning"] para type warning child::chapter[child::title = 'Introduction'] chapter title typed value Introduction child::chapter[child::title] chapter title child::*[self::chapter or self::appendix] chapter appendix child::*[self::chapter or self::appendix][fn:position() = fn:last()] chapter appendix AbbrevForwardStep ::= "@"? NodeTest AbbrevReverseStep ::= ".." The abbreviated syntax permits the following abbreviations: The attribute axis attribute:: @ para[@type="warning"] child::para[attribute::type="warning"] para type warning If the axis name is omitted from an axis step child NodeTest AttributeTest SchemaAttributeTest attribute NodeTest is a NamespaceNodeTest err:XQST0134 Note: In an implementation that does not support the namespace axis, an attempt to access it always raises an error. Thus, an XQuery implementation will always raise an error in this case, since XQuery does not support the namespace axis. The namespace axis is deprecated as of For example, the path expression section/para child::section/child::para section/@id child::section/attribute::id section/attribute(id) child::section/attribute::attribute(id) node test Each non-initial occurrence of // /descendant-or-self::node()/ div1//para child::div1/descendant-or-self::node()/child::para para div1 Note: The path expression //para[1] not /descendant::para[1] para para para A step consisting of .. parent::node() ../title parent::node()/child::title title Note: The expression . context item expression primary expression 3.1.4 Context Item Expression Here are some examples of path expressions that use the abbreviated syntax: para para * text() @name name @* para[1] para para[fn:last()] para */para para /book/chapter[5]/section[2] section chapter book chapter//para para chapter //para para para //@version version //list/member member list .//para para .. ../@lang lang para[@type="warning"] para type warning para[@type="warning"][5] para type warning para[5][@type="warning"] para type warning chapter[title="Introduction"] chapter title typed value Introduction chapter[title] chapter title employee[@secretary and @assistant] employee secretary assistant book/(chapter|appendix)/section section chapter appendix book If E E/. document order XQuery 3.0 supports operators to construct, filter, and combine sequences items 1 (2, 3) ( ) (1, 2, 3) Expr ::= ExprSingle ExprSingle RangeExpr ::= AdditiveExpr AdditiveExpr [ Definition comma operator A sequence may contain duplicate items Note: In places where the grammar calls for ExprSingle Here are some examples of expressions that construct sequences: The result of this expression is a sequence of five integers: (10, 1, 2, 3, 4) This expression combines four sequences of length one, two, zero, and two, respectively, into a single sequence of length five. The result of this expression is the sequence 10, 1, 2, 3, 4 (10, (1, 2), (), (3, 4)) The result of this expression is a sequence containing all salary bonus (salary, bonus) Assuming that $price 10.50 10.50, 10.50 ($price, $price) A range expression to xs:integer? This example uses a range expression as one operand in constructing a sequence. It evaluates to the sequence 10, 1, 2, 3, 4 (10, 1 to 4) This example constructs a sequence of length one containing the single integer 10 10 to 10 The result of this example is a sequence of length zero. 15 to 10 This example uses the fn:reverse 15, 14, 13, 12, 11, 10 fn:reverse(10 to 15) UnionExpr ::= IntersectExceptExpr IntersectExceptExpr IntersectExceptExpr ::= InstanceofExpr InstanceofExpr XQuery 3.0 provides the following operators for combining sequences of nodes: The union | The intersect The except All these operators eliminate duplicate nodes from their result sequences based on node identity. If ordering mode ordered document order implementation-dependent If an operand of union intersect except type error err:XPTY0004 If an IntersectExceptExpr contains more than two InstanceofExprs, they are grouped from left to right. With a UnionExpr, it makes no difference how operands are grouped, the results are the same. Here are some examples of expressions that combine sequences. Assume the existence of three element nodes that we will refer to by symbolic names A, B, and C. Assume that ordering mode ordered $seq1 $seq2 $seq3 $seq1 $seq2 $seq3 Then: $seq1 union $seq2 $seq2 union $seq3 $seq1 intersect $seq2 $seq2 intersect $seq3 $seq1 except $seq2 $seq2 except $seq3 In addition to the sequence operators described here, [XQuery and XPath Functions and Operators 3.0] XQuery 3.0 provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms. AdditiveExpr ::= MultiplicativeExpr MultiplicativeExpr MultiplicativeExpr ::= UnionExpr UnionExpr UnaryExpr ::= ("-" | "+")* ValueExpr ValueExpr ::= ValidateExpr ExtensionExpr SimpleMapExpr A subtraction operator must be preceded by whitespace if it could otherwise be interpreted as part of the previous token. For example, a-b a - b a -b A.2.4 Whitespace Rules If an AdditiveExpr contains more than two MultiplicativeExprs, they are grouped from left to right. So, for instance, A - B + C - D is equivalent to ((A - B) + C) - D Similarly, the operands of a MultiplicativeExpr are grouped from left to right. The first step in evaluating an arithmetic expression is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent Each Atomization atomized operand If the atomized operand is an empty sequence, the result of the arithmetic expression is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error. If the atomized operand is a sequence of length greater than one, a type error err:XPTY0004 If the atomized operand is of type xs:untypedAtomic xs:double dynamic error After evaluation of the operands, if the types of the operands are a valid combination for the given arithmetic operator, the operator is applied to the operands, resulting in an atomic value or a dynamic error B.2 Operator Mapping operator functions [XQuery and XPath Functions and Operators 3.0] If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in B.2 Operator Mapping type error err:XPTY0004 XQuery 3.0 supports two division operators named div idiv numeric [XQuery and XPath Functions and Operators 3.0] $arg1 idiv $arg2 ($arg1 div $arg2) cast as xs:integer? Here are some examples of arithmetic expressions: The first expression below returns the xs:decimal -1.5 xs:integer -1 -3 div 2 -3 idiv 2 Subtraction of two date values results in a value of type xs:dayTimeDuration $emp/hiredate - $emp/birthdate This example illustrates the difference between a subtraction operator and a hyphen: $unit-price - $unit-discount Unary operators have higher precedence than binary operators, subject of course to the use of parentheses. Therefore, the following two examples have different meanings: -$bellcost + $whistlecost -($bellcost + $whistlecost) Note: Multiple consecutive unary arithmetic operators are permitted by XQuery 3.0 for compatibility with [XML Path Language (XPath) Version 1.0] StringConcatExpr ::= RangeExpr RangeExpr String concatenation expressions allow the string representations of values to be concatenated. In XQuery 3.0, $a || $b fn:concat($a, $b) concatenate "con" || "cat" || "enate" Comparison expressions allow two values to be compared. XQuery 3.0 provides three kinds of comparison expressions, called value comparisons, general comparisons, and node comparisons. ComparisonExpr ::= StringConcatExpr ValueComp GeneralComp NodeComp StringConcatExpr ValueComp ::= "eq" | "ne" | "lt" | "le" | "gt" | "ge" GeneralComp ::= "=" | "!=" | "<" | "<=" | ">" | ">=" NodeComp ::= "is" | "<<" | ">>" The value comparison operators are eq ne lt le gt ge The first step in evaluating a value comparison is to evaluate its operands. The order in which the operands are evaluated is implementation-dependent Atomization atomized operand If the atomized operand is an empty sequence, the result of the value comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error. If the atomized operand is a sequence of length greater than one, a type error err:XPTY0004 If the atomized operand is of type xs:untypedAtomic xs:string Note: The purpose of this rule is to make value comparisons transitive. Users should be aware that the general comparison operators have a different rule for casting of xs:untypedAtomic xs:integer xs:float xs:float xs:integer Next, if possible, the two operands are converted to their least common type by a combination of type promotion subtype substitution hatsize xs:integer shoesize xs:float xs:float Finally, if the types of the operands are a valid combination for the given operator, the operator is applied to the operands. The combinations of atomic types that are accepted by the various value comparison operators, and their respective result types, are listed in B.2 Operator Mapping operator functions [XQuery and XPath Functions and Operators 3.0] Informally, if both atomized operands consist of exactly one atomic value, then the result of the comparison is true false If the types of the operands, after evaluation, are not a valid combination for the given operator, according to the rules in B.2 Operator Mapping type error err:XPTY0004 Here are some examples of value comparisons: The following comparison atomizes the node(s) that are returned by the expression $book/author xs:string xs:untypedAtomic type error err:XPTY0004 $book1/author eq "Kennedy" The following path expression weight weight //product[weight gt 100] The following comparisons are true because, in each case, the two constructed nodes have the same value after atomization, even though they have different identities and/or names: <a>5</a> eq <a>5</a> <a>5</a> eq <b>5</b> The following comparison is true if my:hatsize my:shoesize numeric my:hatsize(5) eq my:shoesize(5) The following comparison is true. The eq fn:QName("http://example.com/ns1", "this:color") eq fn:QName("http://example.com/ns1", "that:color") The general comparison operators are = != < <= > >= true false A Atomization The result of the comparison is true magnitude relationship false magnitude relationship cast Note: The purpose of these rules is to preserve compatibility with XPath 1.0, in which (for example) x < 17 x xs:untypedAtomic If both atomic values are instances of xs:untypedAtomic xs:string If exactly one of the atomic values is an instance of xs:untypedAtomic If T is a numeric type or is derived from a numeric type, then V is cast to xs:double If T is xs:dayTimeDuration xs:dayTimeDuration xs:dayTimeDuration If T is xs:yearMonthDuration xs:yearMonthDuration xs:yearMonthDuration In all other cases, V is cast to the primitive base type of T. Note: The special treatment of the duration types is required to avoid errors that may arise when comparing the primitive type xs:duration After performing the conversions described above, the atomic values are compared using one of the value comparison operators eq ne lt le gt ge = != < <= > >= magnitude relationship true When evaluating a general comparison in which either operand is a sequence of items, an implementation may return true magnitude relationship dynamic error Here are some examples of general comparisons: The following comparison is true if the typed value author $book1 xs:string xs:untypedAtomic $book1/author = "Kennedy" The following example contains three general comparisons. The value of the first two comparisons is true false (1, 2) = (2, 3) (2, 3) = (3, 4) (1, 2) = (3, 4) The following example contains two general comparisons, both of which are true = != (1, 2) = (2, 3) (1, 2) != (2, 3) Suppose that $a $b $c xs:untypedAtomic string values 1 2 2.0 ($a, $b) = ($c, 3.0) false $b $c ($a, $b) = ($c, 2.0) true $b 2.0 Node comparisons are used to compare two nodes, by their identity or by their document order The operands of a node comparison are evaluated in implementation-dependent If either operand is an empty sequence, the result of the comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error. Each operand must be either a single node or an empty sequence; otherwise a type error err:XPTY0004 A comparison with the is true false [XQuery and XPath Data Model (XDM) 3.0] A comparison with the << true document order false A comparison with the >> true document order false Here are some examples of node comparisons: The following comparison is true only if the left and right sides each evaluate to exactly the same single node: /books/book[isbn="1558604820"] is /books/book[call="QA76.9 C3845"] The following comparison is false because each constructed node has its own identity: <a>5</a> is <a>5</a> The following comparison is true only if the node identified by the left side occurs before the node identified by the right side in document order: /transactions/purchase[parcel="28-451"] << /transactions/sale[parcel="33-870"] A logical expression and-expression or-expression true false OrExpr ::= AndExpr AndExpr AndExpr ::= ComparisonExpr ComparisonExpr The first step in evaluating a logical expression is to find the effective boolean value 2.4.3 Effective Boolean Value The value of an and-expression is determined by the effective boolean values (EBV's) of its operands, as shown in the following table: AND: EBV 2 true EBV 2 false error in EBV 2 EBV 1 true true false error EBV 1 false false false either false error in EBV 1 error either false error The value of an or-expression is determined by the effective boolean values (EBV's) of its operands, as shown in the following table: OR: EBV 2 true EBV 2 false error in EBV 2 EBV 1 true true true either true EBV 1 false true false error error in EBV 1 either true error error The order in which the operands of a logical expression are evaluated is implementation-dependent true false Here are some examples of logical expressions: The following expressions return true 1 eq 1 and 2 eq 2 1 eq 1 or 2 eq 3 The following expression may return either false dynamic error 1 eq 2 and 3 idiv 0 = 1 The following expression may return either true dynamic error 1 eq 1 or 3 idiv 0 = 1 The following expression must raise a dynamic error 1 eq 1 and 3 idiv 0 = 1 In addition to and- and or-expressions, XQuery 3.0 provides a function named fn:not fn:not [XQuery and XPath Functions and Operators 3.0] fn:not effective boolean value true false false true fn:not XQuery provides constructors that can create XML structures within a query. Constructors are provided for element, attribute, document, text, comment, and processing instruction nodes. Two kinds of constructors are provided: direct constructors computed constructors Constructor ::= DirectConstructor ComputedConstructor DirectConstructor ::= DirElemConstructor DirCommentConstructor DirPIConstructor DirElemConstructor ::= "<" QName DirAttributeList DirElemContent QName S DirElemContent ::= DirectConstructor CDataSection CommonContent ElementContentChar ElementContentChar ::= ( Char CommonContent ::= PredefinedEntityRef CharRef EnclosedExpr CDataSection ::= "<![CDATA[" CDataSectionContents CDataSectionContents ::= ( Char DirAttributeList ::= ( S QName S S DirAttributeValue DirAttributeValue ::= ('"' ( EscapeQuot QuotAttrValueContent EscapeApos AposAttrValueContent QuotAttrValueContent ::= QuotAttrContentChar CommonContent AposAttrValueContent ::= AposAttrContentChar CommonContent QuotAttrContentChar ::= ( Char AposAttrContentChar ::= ( Char EscapeQuot ::= '""' EscapeApos ::= "''" EnclosedExpr ::= "{" Expr This section contains a conceptual description of the semantics of various kinds of constructor expressions. An XQuery implementation is free to use any implementation technique that produces the same result as the processing steps described in this section. An element constructor Definition direct element constructor book <book isbn="isbn-0060229357"> <title>Harold and the Purple Crayon</title> <author> <first>Crockett</first> <last>Johnson</last> </author> </book> If the element name in a direct element constructor has a namespace prefix, the namespace prefix is resolved to a namespace URI using the statically known namespaces default element/type namespace namespace declaration attributes lexical QName [XQuery and XPath Data Model (XDM) 3.0] expanded QName node-name In a direct element constructor, the name used in the end tag must exactly match the name used in the corresponding start tag, including its prefix or absence of a prefix [ err:XQST0118 In a direct element constructor, curly braces { } delimit enclosed expressions <example> <p> Here is a query. </p> <eg> $b/title </eg> <p> Here is the result of the query. </p> <eg>{ $b/title }</eg> </example> The above query might generate the following result (whitespace has been added for readability to this result and other result examples in this document): <example> <p> Here is a query. </p> <eg> $b/title </eg> <p> Here is the result of the query. </p> <eg><title>Harold and the Purple Crayon</title></eg> </example> Since XQuery uses curly braces to denote enclosed expressions, some convention is needed to denote a curly brace used as an ordinary character. For this purpose, a pair of identical curly brace characters within the content of an element or attribute are interpreted by XQuery as a single curly brace character (that is, the pair " {{ { }} } character references { } { } static error err:XPST0003 The result of an element constructor is a new element node, with its own node identity. All the attribute and descendant nodes of the new element node are also new nodes with their own identities, even if they are copies of existing nodes. The start tag of a direct element constructor may contain one or more attributes. As in XML, each attribute is specified by a name and a value. In a direct element constructor, the name of each attribute is specified by a constant lexical QName Each attribute in a direct element constructor creates a new attribute node, with its own node identity, whose parent is the constructed element node. However, note that namespace declaration attributes 3.9.1.2 Namespace Declaration Attributes If an attribute name has a namespace prefix, the prefix is resolved to a namespace URI using the statically known namespaces namespace declaration attributes lexical QName [XQuery and XPath Data Model (XDM) 3.0] expanded QName node-name If the attributes in a direct element constructor do not have distinct expanded QNames node-name static error err:XQST0040 Conceptually, an attribute (other than a namespace declaration attribute) in a direct element constructor is processed by the following steps: Each consecutive sequence of literal characters in the attribute content is processed as a string literal containing those characters, with the following exceptions: Each occurrence of two consecutive { { Each occurrence of two consecutive } } Each occurrence of EscapeQuot " Each occurrence of EscapeApos ' Attribute value normalization is then applied to normalize whitespace and expand character references predefined entity references The rules for attribute value normalization are the rules from Section 3.3.3 of [XML 1.0] or Section 3.3.3 of [XML 1.1] (it is implementation-defined which version is used). The rules are applied as though the type of the attribute were CDATA (leading and trailing whitespace characters are not stripped.) Each enclosed expression is converted to a string as follows: Atomization If the result of atomization is an empty sequence, the result is the zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string. The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. Adjacent strings resulting from the above steps are concatenated with no intervening blanks. The resulting string becomes the string-value type annotation xs:untypedAtomic typed-value string-value xs:untypedAtomic The parent If the attribute name is xml:id xml:id [XML ID] xs:ID xml:id dynamic error err:XQDY0091 If the attribute name is xml:id is-id true is-id false is-idrefs false Example: <shoe size="7"/> The string value of the size 7 Example: <shoe size="{7}"/> The string value of the size 7 Example: <shoe size="{()}"/> The string value of the size Example: <chapter ref="[{1, 5 to 7, 9}]"/> The string value of the ref [1 5 6 7 9] Example: <shoe size="As big as {$hat/@size}"/> The string value of the size As big as $hat/@size The names of a constructed element and its attributes may be lexical QNames namespace prefixes Prolog namespace declaration attributes static error err:XPST0081 [ Definition namespace declaration attribute default element/type namespace xmlns xmlns err:XQST0071 The value of the namespace declaration attribute (a DirAttributeValue DirAttributeValue EnclosedExpr err:XQST0022 3.9.1.1 Attributes err:XQST0046 neither an absolute URI nor a relative URI If the prefix of the attribute name is xmlns statically known namespaces in-scope namespaces [XML Names 1.1] in-scope namespaces statically known namespaces [XML Names 1.1] err:XQST0085 implementation-defined [XML Names] [XML Names 1.1] If the name of the namespace declaration attribute is xmlns default element/type namespace in-scope namespaces default element/type namespace absent DM30 in-scope namespaces It is a static error err:XQST0070 Bind the prefix xml http://www.w3.org/XML/1998/namespace Bind a prefix other than xml http://www.w3.org/XML/1998/namespace Bind the prefix xmlns Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/ A namespace declaration attribute does not cause an attribute node to be created. The following examples illustrate namespace declaration attributes: In this element constructor, a namespace declaration attribute is used to set the default element/type namespace http://example.org/animals <cat xmlns = "http://example.org/animals"> <breed>Persian</breed> </cat> In this element constructor, namespace declaration attributes are used to bind the namespace prefixes metric english <box xmlns:metric = "http://example.org/metric/units" xmlns:english = "http://example.org/english/units"> <height> <metric:meters>3</metric:meters> </height> <width> <english:feet>6</english:feet> </width> <depth> <english:inches>18</english:inches> </depth> </box> The part of a direct element constructor between the start tag and the end tag is called the content ElementContentChar CDataSections predefined entity references Conceptually, the content of an element constructor is processed as follows: The content is evaluated to produce a sequence of nodes called the content sequence If the boundary-space policy static context strip boundary whitespace 3.9.1.4 Boundary Whitespace Predefined entity references character references 3.1.1 Literals CDataSection < & ]]> Each consecutive sequence of literal characters evaluates to a single text node containing the characters. Each nested direct constructor is evaluated according to the rules in 3.9.1 Direct Element Constructors 3.9.2 Other Direct Constructors The parent The base-uri xml:base base-uri resolved (if it is relative) base-uri Enclosed expressions are evaluated as follows: If an enclosed expression returns a function DM30 err:XQTY0105 For each adjacent sequence of one or more atomic values returned by an enclosed expression, a new text node is constructed, containing the result of casting each atomic value to a string, with a single space character inserted between adjacent values. Note: The insertion of blank characters between adjacent values applies even if one or both of the values is a zero-length string. For each node returned by an enclosed expression, a new copy is made of the given node and all nodes that have the given node as an ancestor, collectively referred to as copied nodes Each copied node receives a new node identity. The parent children attributes parent If construction mode static context strip If the copied node is an element node, its type annotation xs:untyped nilled is-id is-idrefs false If the copied node is an attribute node, its type-name xs:untypedAtomic is-idrefs false is-id true xml:id false The string-value typed-value string-value xs:untypedAtomic Note: Implementations that store only the typed value On the other hand, if construction mode static context preserve type-name nilled string-value typed-value is-id is-idrefs The in-scope-namespaces If copy-namespaces mode preserve copy-namespaces mode no-preserve If copy-namespaces mode inherit copy-namespaces mode no-inherit An enclosed expression in the content of an element constructor may cause one or more existing nodes to be copied. Type error [ err:XQTY0086 An element node is copied, and the typed value namespace-sensitive construction mode preserve copy-namespaces mode no-preserve An attribute node is copied but its parent element node is not copied, and the typed value namespace-sensitive construction mode preserve Note: The rationale for error [ err:XQTY0086 When an element or processing instruction node is copied, its base-uri xml:base base-uri resolved (if it is relative) base-uri All other properties of the copied nodes are preserved. If the content sequence contains a document node, the document node is replaced in the content sequence by its children. Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence. If the content sequence contains an attribute node or a namespace node following a node that is not an attribute node or a namespace node, a type error err:XQTY0024 The properties of the newly constructed element node are determined as follows: node-name expanded QName 3.9.1 Direct Element Constructors parent attributes 3.9.1.1 Attributes implementation-dependent parent node-name dynamic error err:XQDY0025 xml:space preserve default err:XQDY0092 children parent base-uri If the constructed node has an attribute named xml:base resolved (if it is relative) Static Base URI 2.4.6 Resolving a Relative URI Reference Otherwise, the Static Base URI in-scope-namespaces 3.9.1.2 Namespace Declaration Attributes 3.9.4 In-scope Namespaces of a Constructed Element The nilled false The string-value string-value The typed-value string-value xs:untypedAtomic If construction mode static context strip type-name xs:untyped preserve type-name xs:anyType The is-id is-idrefs false Example: <a>{1}</a> The constructed element node has one child, a text node containing the value " 1 Example: <a>{1, 2, 3}</a> The constructed element node has one child, a text node containing the value " 1 2 3 Example: <c>{1}{2}{3}</c> The constructed element node has one child, a text node containing the value " 123 Example: <b>{1, "2", "3"}</b> The constructed element node has one child, a text node containing the value " 1 2 3 Example: <fact>I saw 8 cats.</fact> The constructed element node has one child, a text node containing the value " I saw 8 cats. Example: <fact>I saw {5 + 3} cats.</fact> The constructed element node has one child, a text node containing the value " I saw 8 cats. Example: <fact>I saw <howmany>{5 + 3}</howmany> cats.</fact> The constructed element node has three children: a text node containing " I saw howmany cats. 8 In a direct element constructor, whitespace characters may appear in the content of the constructed element. In some cases, enclosed expressions and/or nested elements may be separated only by whitespace characters. For example, in the expression below, the end-tag </title> <author> <book isbn="isbn-0060229357"> <title>Harold and the Purple Crayon</title> <author> <first>Crockett</first> <last>Johnson</last> </author> </book> [ Definition Boundary whitespace direct element constructor DirectConstructor EnclosedExpr character references   CDataSections The boundary-space policy static context strip preserve Example: <cat> <breed>{$b}</breed> <color>{$c}</color> </cat> The constructed cat breed color strip Example: <a> {"abc"} </a> If boundary-space policy is strip <a>abc</a> preserve <a> abc </a> Example: <a> z {"abc"}</a> Since the whitespace surrounding the z <a> z abc</a> Example: <a> {"abc"}</a> This example is equivalent to <a> abc</a> character reference Example: <a>{" "}</a> This example constructs an element containing two space characters, regardless of the boundary-space policy, because whitespace inside an enclosed expression is never considered to be boundary whitespace. Note: Element constructors treat attributes named xml:space xml:space XQuery allows an expression to generate a processing instruction node or a comment node. This can be accomplished by using a direct processing instruction constructor direct comment constructor DirPIConstructor ::= "<?" PITarget S DirPIContents DirPIContents ::= ( Char DirCommentConstructor ::= "<!--" DirCommentContents DirCommentContents ::= (( Char Char A direct processing instruction constructor creates a processing instruction node whose target PITarget content DirPIContents base-uri parent The PITarget DirPIContents ?> The following example illustrates a direct processing instruction constructor: <?format role="output" ?> A direct comment constructor creates a comment node whose content DirCommentContents parent The DirCommentContents The following example illustrates a direct comment constructor: <!-- Tags are ignored in the following section --> Note: A direct comment constructor is different from a comment comment ComputedConstructor ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompNamespaceConstructor CompTextConstructor CompCommentConstructor CompPIConstructor An alternative way to create nodes is by using a computed constructor element attribute document text processing-instruction comment namespace For those kinds of nodes that have names (element, attribute, and processing instruction nodes), the keyword that specifies the node kind is followed by the name of the node to be created. This name may be specified either as an EQName or as an expression enclosed in braces. [ Definition name expression [ Definition content expression The following example illustrates the use of computed element and attribute constructors in a simple case where the names of the constructed nodes are constants. This example generates exactly the same result as the first example in 3.9.1 Direct Element Constructors element book { attribute isbn {"isbn-0060229357" }, element title { "Harold and the Purple Crayon"}, element author { element first { "Crockett" }, element last {"Johnson" } } } CompElemConstructor ::= "element" ( EQName Expr ContentExpr EQName ::= QName URIQualifiedName ContentExpr ::= Expr [ Definition computed element constructor If the keyword element expanded QName BracedURILiteral lexical QName statically known namespaces lexical QName default element/type namespace expanded QName node-name static error err:XPST0081 If the keyword element name expression Atomization name expression xs:QName xs:string xs:untypedAtomic type error err:XPTY0004 If the atomized value of the name expression xs:QName expanded QName node-name If the atomized value of the name expression xs:string xs:untypedAtomic expanded QName resolved to a namespace URI statically known namespaces default element/type namespace expanded QName node-name name expression expanded QName dynamic error err:XQDY0074 A dynamic error err:XQDY0096 Its namespace prefix is xmlns Its namespace URI is http://www.w3.org/2000/xmlns/ Its namespace prefix is xml http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace The content expression direct element constructor 3.9.1.3 Content content sequence content expression Processing of the computed element constructor proceeds as follows: If the content sequence contains a document node, the document node is replaced in the content sequence by its children. Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence. If the content sequence contains an attribute node or a namespace node following a node that is not an attribute node or a namespace node, a type error err:XQTY0024 The properties of the newly constructed element node are determined as follows: node-name expanded QName lexical QName name expression parent attributes implementation-dependent parent node-name dynamic error err:XQDY0025 xml:space preserve default err:XQDY0092 children parent base-uri If the constructed node has an attribute named xml:base resolved (if it is relative) Static Base URI 2.4.6 Resolving a Relative URI Reference Otherwise, the Static Base URI in-scope-namespaces 3.9.4 In-scope Namespaces of a Constructed Element The nilled false The string-value The typed-value string-value xs:untypedAtomic If construction mode static context strip type-name xs:untyped preserve type-name xs:anyType The is-id is-idrefs false A computed element constructor might be used to make a modified copy of an existing element. For example, if the variable $e numeric $e $e element {fn:node-name($e)} {$e/@*, 2 * fn:data($e)} In this example, if $e let $e := <length units="inches">{5}</length> <length units="inches">10</length> Note: The static type fn:node-name($e) xs:QName? Static Typing Feature fn:node-name($e) fn:exactly-one(fn:node-name($e)) Static Typing Feature $e One important purpose of computed constructors is to allow the name of a node to be computed. We will illustrate this feature by an expression that translates the name of an element from one language to another. Suppose that the variable $dict dictionary entry <entry word="address"> <variant xml:lang="de">Adresse</variant> <variant xml:lang="it">indirizzo</variant> </entry> Suppose further that the variable $e <address>123 Roosevelt Ave. Flushing, NY 11368</address> Then the following expression generates a new element in which the name of $e $e element element {$dict/entry[@word=name($e)]/variant[@xml:lang="it"]} {$e/@*, $e/node()} The result of this expression is as follows: <indirizzo>123 Roosevelt Ave. Flushing, NY 11368</indirizzo> Note: As in the previous example, if the Static Typing Feature fn:exactly-one Additional examples of computed element constructors can be found in I.3 Recursive Transformations CompAttrConstructor ::= "attribute" ( EQName Expr Expr EQName ::= QName URIQualifiedName A computed attribute constructor creates a new attribute node, with its own node identity. Attributes have no default namespace. The rules that expand attribute names create an implementation-dependent If the keyword attribute expanded QName If the EQName has a BracedURILiteral expanded QName implementation-dependent If the EQName is a lexical QName statically known namespaces If the EQName is a lexical QName The resulting expanded QName node-name static error err:XPST0081 If the keyword attribute name expression Atomization name expression atomization xs:QName xs:string xs:untypedAtomic type error err:XPTY0004 If the atomized value of the name expression xs:QName If the expanded QName implementation-dependent The resulting expanded QName node-name If the atomized value of the name expression xs:string xs:untypedAtomic expanded QName statically known namespaces expanded QName node-name name expression expanded QName dynamic error err:XQDY0074 A dynamic error err:XQDY0044 Its namespace prefix is xmlns It has no namespace prefix and its local name is xmlns Its namespace URI is http://www.w3.org/2000/xmlns/ Its namespace prefix is xml http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace The content expression Atomization content expression content expression If the result of atomization is an empty sequence, the value of the attribute is the zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string. The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the string-value type annotation type-name xs:untypedAtomic typed-value string-value xs:untypedAtomic The parent If the attribute name is xml:id xml:id [XML ID] xs:ID xml:id dynamic error err:XQDY0091 If the attribute name is xml:id is-id true is-id false is-idrefs false If the attribute name is xml:space preserve default err:XQDY0092 Example: attribute size {4 + 3} The string value size 7 xs:untypedAtomic Example: attribute { if ($sex = "M") then "husband" else "wife" } { <a>Hello</a>, 1 to 3, <b>Goodbye</b> } The name of the constructed attribute is either husband wife string value Hello 1 2 3 Goodbye CompDocConstructor ::= "document" "{" Expr All document node constructors are computed constructors. The result of a document node constructor is a new document node, with its own node identity. A document node constructor is useful when the result of a query is to be a document in its own right. The following example illustrates a query that returns an XML document containing a root element named author-list document { <author-list> {fn:doc("bib.xml")/bib/book/author} </author-list> } The content expression direct element constructor 3.9.1.3 Content content sequence If the content sequence contains a document node, the document node is replaced in the content sequence by its children. Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence. If the content sequence contains an attribute node, a type error err:XPTY0004 If the content sequence contains a namespace node, a type error err:XPTY0004 The properties of the newly constructed document node are determined as follows: base-uri set to the Static Base URI children parent The unparsed-entities document-uri The string-value The typed-value string-value xs:untypedAtomic No validation is performed on the constructed document node. The [XML 1.0] CompTextConstructor ::= "text" "{" Expr All text node constructors are computed constructors. The result of a text node constructor is a new text node, with its own node identity. The content expression Atomization content expression If the result of atomization is an empty sequence, no text node is constructed. Otherwise, each atomic value in the atomized sequence is cast into a string. The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the content The parent Note: It is possible for a text node constructor to construct a text node containing a zero-length string. However, if used in the content of a constructed element or document node, such a text node will be deleted or merged with another text node. The following example illustrates a text node constructor: text {"Hello"} CompPIConstructor ::= "processing-instruction" ( NCName Expr Expr A computed processing instruction constructor ( CompPIConstructor If the keyword processing-instruction target processing-instruction name expression Atomization name expression atomization xs:NCName xs:string xs:untypedAtomic type error err:XPTY0004 If the atomized value of the name expression xs:string xs:untypedAtomic xs:NCName xs:NCName dynamic error err:XQDY0041 The resulting NCName is then used as the target dynamic error XML err:XQDY0064 The content expression Atomization content expression content expression If the result of atomization is an empty sequence, it is replaced by a zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string. If any of the resulting strings contains the string " ?> dynamic error err:XQDY0026 The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. Leading whitespace is removed from the resulting string. The resulting string then becomes the content The remaining properties of the new processing instruction node are determined as follows: The parent The base-uri The following example illustrates a computed processing instruction constructor: let $target := "audio-output", $content := "beep" return processing-instruction {$target} {$content} The processing instruction node constructed by this example might be serialized as follows: <?audio-output beep?> CompCommentConstructor ::= "comment" "{" Expr A computed comment constructor ( CompCommentConstructor content expression Atomization content expression If the result of atomization is an empty sequence, it is replaced by a zero-length string. Otherwise, each atomic value in the atomized sequence is cast into a string. The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the content It is a dynamic error err:XQDY0072 content expression The parent The following example illustrates a computed comment constructor: let $homebase := "Houston" return comment {fn:concat($homebase, ", we have a problem.")} The comment node constructed by this example might be serialized as follows: <!--Houston, we have a problem.--> CompNamespaceConstructor ::= "namespace" ( Prefix PrefixExpr URIExpr PrefixExpr ::= Expr URIExpr ::= Expr A computed namespace constructor creates a new namespace node, with its own node identity. The parent of the newly created namespace node is empty. If the constructor specifies a Prefix If the constructor specifies a PrefixExpr Atomization PrefixExpr If the result of atomization xs:string xs:untypedAtomic If the result is castable to xs:NCName If the result is the empty sequence or a zero-length xs:string xs:untypedAtomic Otherwise, a dynamic error is raised [ err:XQDY0074 If the result of atomization is not an empty sequence or a single atomic value of type xs:string xs:untypedAtomic err:XPTY0004 The URIExpr xs:anyURI URI An implementation may raise a dynamic error [ err:XQDY0074 URIExpr xs:anyURI An error [ err:XQDY0101 Bind the prefix xml http://www.w3.org/XML/1998/namespace Bind a prefix other than xml http://www.w3.org/XML/1998/namespace Bind the prefix xmlns Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/ Bind any prefix (including the empty prefix) to a zero-length namespace URI. By itself, a computed namespace constructor has no effect on in-scope namespaces, but if an element constructor's content sequence contains a namespace node, the namespace binding it represents is added to the element's in-scope namespaces A computed namespace constructor has no effect on the statically known namespaces. Note: The newly created namespace node has all properties defined for a namespace node in the data model. Like all nodes, it has identity. Like all nodes which do not share a common parent, the relative order of these nodes is implementation dependent. As defined in the data model, the name of the node is the prefix, and the string value of the node is the URI. Examples: A computed namespace constructor with a prefix: namespace a {"http://a.example.com" } A computed namespace constructor with a prefix expression: namespace {"a"} {"http://a.example.com" } A computed namespace constructor with an empty prefix: namespace { "" } {"http://a.example.com" } Computed namespace constructors are generally used to add to the in-scope namespaces of elements created with element constructors: <age xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> { namespace xs {"http://www.w3.org/2001/XMLSchema"}, attribute xsi:type {"xs:integer"}, 23 }</age> In the above example, note that the xsi xs Computed namespace constructors have no effect on the statically known namespaces. If the prefix a is not already defined in the statically known namespaces, the following expression results in a static error [ err:XPST0081 <a:form> { namespace a { "http://a.example.com" } } </a:form> An element node constructed by a direct or computed element constructor has an in-scope namespaces namespace bindings 2.2.4 Serialization fn:name in-scope namespaces statically known namespaces A namespace binding is created for each namespace declared in the current element constructor by a namespace declaration attribute A namespace binding is created for each namespace node in the content sequence of the current element constructor. A namespace binding is created for each namespace that is declared in a namespace declaration attribute direct element constructor A namespace binding is always created to bind the prefix xml http://www.w3.org/XML/1998/namespace For each prefix used in the name of the constructed element or in the names of its attributes, a namespace binding must exist. If a namespace binding does not already exist for one of these prefixes, a new namespace binding is created for it. If this would result in a conflict, because it would require two different bindings of the same prefix, then the prefix used in the node name is changed to an arbitrary implementation-dependent Note: Copy-namespaces mode In an element constructor, if two or more namespace bindings in the in-scope bindings would have the same prefix, then an error is raised if they have different URIs [ err:XQDY0102 If the name of an element in an element constructor is in no namespace, creating a default namespace for that element using a computed namespace constructor is an error [ err:XQDY0102 element e { namespace {''} {'u'} } The following query illustrates the in-scope namespaces of a constructed element: declare namespace p="http://example.com/ns/p"; declare namespace q="http://example.com/ns/q"; declare namespace f="http://example.com/ns/f";
<p:a q:b="{f:func(2)}" xmlns:r="http://example.com/ns/r"/> The in-scope namespaces p:a p = "http://example.com/ns/p" q = "http://example.com/ns/q" r = "http://example.com/ns/r" xml = "http://www.w3.org/XML/1998/namespace" The namespace bindings for p q r="http://example.com/ns/r" namespace declaration attribute No namespace binding corresponding to f="http://example.com/ns/f" f statically known namespaces Note that the following constructed element, if nested within a validate <p xsi:type="xs:integer">3</p> The constructed element will have namespace bindings for the prefixes xsi xml xs namespace declaration attribute <p xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:integer">3</p> XQuery provides a versatile expression called a FLWOR expression that may contain multiple clauses. The FLWOR expression can be used for many purposes, including iterating over sequences, joining multiple documents, and performing grouping and aggregation. The name FLWOR, pronounced "flower", is suggested by the keywords for let where order by return The complete syntax of a FLWOR expression is shown here, and relevant parts of the syntax are repeated in subsequent sections of this document. FLWORExpr ::= InitialClause IntermediateClause ReturnClause InitialClause ::= ForClause LetClause WindowClause IntermediateClause ::= InitialClause WhereClause GroupByClause OrderByClause CountClause ForClause ::= "for" ForBinding ForBinding ForBinding ::= "$" VarName TypeDeclaration AllowingEmpty PositionalVar ExprSingle LetClause ::= "let" LetBinding LetBinding LetBinding ::= "$" VarName TypeDeclaration ExprSingle TypeDeclaration ::= "as" SequenceType AllowingEmpty ::= "allowing" "empty" PositionalVar ::= "at" "$" VarName WindowClause ::= "for" ( TumblingWindowClause SlidingWindowClause TumblingWindowClause ::= "tumbling" "window" "$" VarName TypeDeclaration ExprSingle WindowStartCondition WindowEndCondition SlidingWindowClause ::= "sliding" "window" "$" VarName TypeDeclaration ExprSingle WindowStartCondition WindowEndCondition WindowStartCondition ::= "start" WindowVars ExprSingle WindowEndCondition ::= "only"? "end" WindowVars ExprSingle WindowVars ::= ("$" CurrentItem PositionalVar PreviousItem NextItem CurrentItem ::= EQName PreviousItem ::= EQName NextItem ::= EQName CountClause ::= "count" "$" VarName WhereClause ::= "where" ExprSingle GroupByClause ::= "group" "by" GroupingSpecList GroupingSpecList ::= GroupingSpec GroupingSpec GroupingSpec ::= GroupingVariable TypeDeclaration ExprSingle URILiteral GroupingVariable ::= "$" VarName OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList OrderSpecList ::= OrderSpec OrderSpec OrderSpec ::= ExprSingle OrderModifier OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral ReturnClause ::= "return" ExprSingle The semantics of FLWOR expressions are based on a concept called a tuple stream Definition tuple stream tuples Definition tuple XDM instance static types $x $y $z ($x = 1003, $y = "Fred", $z = <age>21</age>) ($x = 1017, $y = "Mary", $z = <age>35</age>) ($x = 1020, $y = "Bill", $z = <age>18</age>) ($x = 1024, $y = "John", $z = <age>29</age>) Note: In this section, tuple streams are represented as shown in the above example. Each tuple is on a separate line and is enclosed in parentheses, and the variable bindings inside each tuple are separated by commas. This notation does not represent XQuery syntax, but is simply a representation of a tuple stream for the purpose of defining the semantics of FLWOR expressions. Tuples and tuple streams are not part of the data model Conceptually, the first between the first clause and the return clause return XDM instance XDM instances The initial clause in a FLWOR expression may be a for let or window for let window count where group by order by return The following clauses in FLWOR expressions bind values to variables: for let window count group by The binding of variables for for let and count the binding of variables in group by 3.10.7 Group By Clause window 3.10.4 Window Clause The scope of a bound variable includes all subexpressions of the containing FLWOR that appear after the variable binding. The scope does not include the expression to which the variable is bound. The following code fragment, containing two let let $x := 47, $y := f($x) let $z := g($x, $y) A given variable may be bound more than once in a FLWOR expression, or even within one clause of a FLWOR expression. In such a case, each new binding occludes the previous one, which becomes inaccessible in the remainder of the FLWOR expression. [ Definition type declaration as 2.5.4 SequenceType Syntax SequenceType matching type error err:XPTY0004 let type error $salary let $salary as xs:decimal := "cat" [ Definition for window in binding sequence for window for window ForClause ::= "for" ForBinding ForBinding ForBinding ::= "$" VarName TypeDeclaration AllowingEmpty PositionalVar ExprSingle TypeDeclaration ::= "as" SequenceType AllowingEmpty ::= "allowing" "empty" PositionalVar ::= "at" "$" VarName A for for If a for for for Example: The clause for $x in $expr1, $y in $expr2 is semantically equivalent to: for $x in $expr1 for $y in $expr2 In the remainder of this section, we define the semantics of a for in binding sequence If a single-variable for binding sequence ordering mode ordered binding sequence implementation-dependent If the binding sequence allowing empty allowing empty allowing empty The following examples illustrates tuple streams that are generated by initial for Initial clause: for $x in (100, 200, 300) or (equivalently): for $x allowing empty in (100, 200, 300) Output tuple stream: ($x = 100) ($x = 200) ($x = 300) Initial clause: for $x in () Output tuple stream contains no tuples. Initial clause: for $x allowing empty in () Output tuple stream: ($x = ()) [ Definition positional variable at for binding sequence binding sequence binding sequence allowing empty xs:integer expanded QName expanded QName err:XQST0089 The following examples illustrate how a positional variable would have affected the results of the previous examples that generated tuples: Initial clause: for $x at $i in (100, 200, 300) Output tuple stream: ($x = 100, $i = 1) ($x = 200, $i = 2) ($x = 300, $i = 3) Initial clause: for $x allowing empty at $i in () Output tuple stream: ($x = (), $i = 0) If a single-variable for binding sequence binding sequence Note: Although the binding sequence binding sequence binding sequence For a given input tuple, if the binding sequence for allowing empty allowing empty allowing empty If the new variable introduced by a for positional variable for positional variable binding sequence positional variable binding sequence positional variable binding sequence binding sequence allowing empty positional variable If ordering mode ordered binding sequence implementation-dependent The following examples illustrates the effects of intermediate for Input tuple stream: ($x = 1) ($x = 2) ($x = 3) ($x = 4) Intermediate for for $y in ($x to 3) Output tuple stream (assuming ordering mode ordered ($x = 1, $y = 1) ($x = 1, $y = 2) ($x = 1, $y = 3) ($x = 2, $y = 2) ($x = 2, $y = 3) ($x = 3, $y = 3) Note: In this example, there is no output tuple that corresponds to the input tuple ($x = 4) for binding sequence $y This example shows how the previous example would have been affected by a positional variable for $y at $j in ($x to 3) Output tuple stream (assuming ordering mode ordered ($x = 1, $y = 1, $j = 1) ($x = 1, $y = 2, $j = 2) ($x = 1, $y = 3, $j = 3) ($x = 2, $y = 2, $j = 1) ($x = 2, $y = 3, $j = 2) ($x = 3, $y = 3, $j = 1) This example shows how the previous example would have been affected by allowing empty allowing empty ($x = 4) binding sequence $y allowing empty for for $y allowing empty at $j in ($x to 3) Output tuple stream (assuming ordering mode ordered ($x = 1, $y = 1, $j = 1) ($x = 1, $y = 2, $j = 2) ($x = 1, $y = 3, $j = 3) ($x = 2, $y = 2, $j = 1) ($x = 2, $y = 3, $j = 2) ($x = 3, $y = 3, $j = 1) ($x = 4, $y = (), $j = 0) This example shows how a for for for for for for $x in (1, 2, 3, 4), $y in ($x to 3) Output tuple stream (assuming ordering mode ordered ($x = 1, $y = 1) ($x = 1, $y = 2) ($x = 1, $y = 3) ($x = 2, $y = 2) ($x = 2, $y = 3) ($x = 3, $y = 3) In the above examples, if ordering mode unordered positional variables implementation-dependent A for type declarations as type declarations 3.10.1 Variable Bindings LetClause ::= "let" LetBinding LetBinding LetBinding ::= "$" VarName TypeDeclaration ExprSingle TypeDeclaration ::= "as" SequenceType The purpose of a let If a let let let $x := $expr1, $y := $expr2 is semantically equivalent to the following sequence of clauses: let $x := $expr1 let $y := $expr2 In the remainder of this section, we define the semantics of a let V E If a single-variable let V E let V E If a single-variable let V V E let The number of tuples in the output tuple stream of an intermediate let V V V A let type declarations as 3.10.1 Variable Bindings The following code fragment illustrates how a for let for $d let $e $d for $d in fn:doc("depts.xml")/depts/deptno let $e := fn:doc("emps.xml")/emps/emp[deptno eq $d] WindowClause ::= "for" ( TumblingWindowClause SlidingWindowClause TumblingWindowClause ::= "tumbling" "window" "$" VarName TypeDeclaration ExprSingle WindowStartCondition WindowEndCondition SlidingWindowClause ::= "sliding" "window" "$" VarName TypeDeclaration ExprSingle WindowStartCondition WindowEndCondition WindowStartCondition ::= "start" WindowVars ExprSingle WindowEndCondition ::= "only"? "end" WindowVars ExprSingle WindowVars ::= ("$" CurrentItem PositionalVar PreviousItem NextItem CurrentItem ::= EQName PositionalVar ::= "at" "$" VarName PreviousItem ::= EQName NextItem ::= EQName Like a for window binding sequence window Definition window binding sequence Window-variable: binding sequence Start-item: Start-item-position: binding sequence Start-item-position positional variable xs:integer Start-previous-item: binding sequence Start-next-item: binding sequence End-item: End-item-position: binding sequence End-item-position positional variable xs:integer End-previous-item: binding sequence End-next-item: binding sequence All variables in a window static error err:XQST0103 The following is an example of a window $w $s $spos $sprev $snext $e $epos $eprev $enext window for tumbling window $w in (2, 4, 6, 8, 10) start $s at $spos previous $sprev next $snext when true() end $e at $epos previous $eprev next $enext when true() Windows are created by iterating over the items in the binding sequence WindowStartCondition WindowEndCondition effective boolean value when true WindowStartCondition 3.10.4.1 Tumbling Windows 3.10.4.2 Sliding Windows binding sequence WindowEndCondition 3.10.4.1 Tumbling Windows 3.10.4.2 Sliding Windows binding sequence binding sequence WindowEndCondition only only end binding sequence In the above example, the WindowStartCondition WindowEndCondition true item binding sequence WindowStartCondition WindowEndCondition WindowStartCondition binding sequence start $s previous $sprev next $snext when $s > $sprev and $s > $snext The scoping rules for the variables bound by a window In the when WindowStartCondition start-item, start-item-position, start-previous-item, start-next-item. In the when WindowEndCondition start-item, start-item-position, start-previous-item, start-next-item, end-item, end-item-position, end-previous-item, end-next-item. In the clauses of the FLWOR expression that follow the window window window-variable In a window tumbling sliding If the window type is tumbling binding sequence binding sequence binding sequence (unless the sequence contains the same item more than once) end start binding sequence binding sequence The following examples illustrate the use of tumbling windows. Show non-overlapping windows of three items. for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when fn:true() only end at $e when $e - $s eq 2 return <window>{ $w }</window> Result of the above query: <window>2 4 6</window> <window>8 10 12</window> Show averages of non-overlapping three-item windows. for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when fn:true() only end at $e when $e - $s eq 2 return avg($w) Result of the above query: 4 10 Show first and last items in each window of three items. for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) start $first at $s when fn:true() only end $last at $e when $e - $s eq 2 return <window>{ $first, $last }</window> Result of the above query: <window>2 6</window> <window>8 12</window> Show non-overlapping windows of up to three items (illustrates end only for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when fn:true() end at $e when $e - $s eq 2 return <window>{ $w }</window> Result of the above query: <window>2 4 6</window> <window>8 10 12</window> <window>14</window> Show non-overlapping windows of up to three items (illustrates use of start end for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when $s mod 3 = 1 return <window>{ $w }</window> Result of the above query: <window>2 4 6</window> <window>8 10 12</window> <window>14</window> Show non-overlapping sequences starting with a number divisible by 3. for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) start $first when $first mod 3 = 0 return <window>{ $w }</window> Result of the above query: <window>6 8 10</window> <window>12 14</window> If the window type is sliding window binding sequence WindowStartCondition binding sequence The following examples illustrate the use of sliding windows. Show windows of three items. for sliding window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when fn:true() only end at $e when $e - $s eq 2 return <window>{ $w }</window> Result of the above query: <window>2 4 6</window> <window>4 6 8</window> <window>6 8 10</window> <window>8 10 12</window> <window>10 12 14</window> Show moving averages of three items. for sliding window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when fn:true() only end at $e when $e - $s eq 2 return avg($w) Result of the above query: 4 6 8 10 12 Show overlapping windows of up to three items (illustrates end only for sliding window $w in (2, 4, 6, 8, 10, 12, 14) start at $s when fn:true() end at $e when $e - $s eq 2 return <window>{ $w }</window> Result of the above query: <window>2 4 6</window> <window>4 6 8</window> <window>6 8 10</window> <window>8 10 12</window> <window>10 12 14</window> <window>12 14</window> <window>14</window> The effects of a window for 3.10.4 Window Clause window If the window ordering mode ordered binding sequence implementation-dependent If a window T N T N T window T ordering mode ordered binding sequence ordering mode unordered implementation-dependent The following example illustrates a window price xs:decimal <stock> <closing> <date>2008-01-01</date> <price>105</price> </closing> <closing> <date>2008-01-02</date> <price>101</price> </closing> <closing> <date>2008-01-03</date> <price>102</price> </closing> <closing> <date>2008-01-04</date> <price>103</price> </closing> <closing> <date>2008-01-05</date> <price>102</price> </closing> <closing> <date>2008-01-06</date> <price>104</price> </closing> </stock> A user wishes to find "run-ups," which are defined as sequences of dates that begin with a "low" and end with a "high" price (that is, the stock price begins to rise on the first day of the run-up, and continues to rise or remain even through the last day of the run-up.) The following query uses a tumbling window to find run-ups in the input data: for tumbling window $w in //closing start $first next $second when $first/price < $second/price end $last next $beyond when $last/price > $beyond/price return <run-up> <start-date>{fn:data($first/date)}</start-date> <start-price>{fn:data($first/price)}</start-price> <end-date>{fn:data($last/date)}</end-date> <end-price>{fn:data($last/price)}</end-price> </run-up> For our sample input data, this tumbling window $w $first $second $last $beyond return <run-up> <start-date>2008-01-02</start-date> <start-price>101</start-price> <end-date>2008-01-04</end-date> <end-price>103</end-price> </run-up> <run-up> <start-date>2008-01-05</start-date> <start-price>102</start-price> <end-date>2008-01-06</end-date> <end-price>104</end-price> </run-up> The following example illustrates a window price xs:decimal <stocks> <closing> <symbol>ABC</symbol> <date>2008-01-01</date> <price>105</price> </closing> <closing> <symbol>DEF</symbol> <date>2008-01-01</date> <price>057</price> </closing> <closing> <symbol>ABC</symbol> <date>2008-01-02</date> <price>101</price> </closing> <closing> <symbol>DEF</symbol> <date>2008-01-02</date> <price>054</price> </closing> <closing> <symbol>ABC</symbol> <date>2008-01-03</date> <price>102</price> </closing> <closing> <symbol>DEF</symbol> <date>2008-01-03</date> <price>056</price> </closing> <closing> <symbol>ABC</symbol> <date>2008-01-04</date> <price>103</price> </closing> <closing> <symbol>DEF</symbol> <date>2008-01-04</date> <price>052</price> </closing> <closing> <symbol>ABC</symbol> <date>2008-01-05</date> <price>101</price> </closing> <closing> <symbol>DEF</symbol> <date>2008-01-05</date> <price>055</price> </closing> <closing> <symbol>ABC</symbol> <date>2008-01-06</date> <price>104</price> </closing> <closing> <symbol>DEF</symbol> <date>2008-01-06</date> <price>059</price> </closing> </stocks> As in the previous example, we want to find "run-ups," which are defined as sequences of dates that begin with a "low" and end with a "high" price for a specific company. In this example, however, the input data consists of stock prices for multiple companies. Therefore it is necessary to isolate the stock prices of each company before forming windows. This can be accomplished by an initial for let window for $symbol in fn:distinct-values(//symbol) let $closings := //closing[symbol = $symbol] for tumbling window $w in $closings start $first next $second when $first/price < $second/price end $last next $beyond when $last/price > $beyond/price return <run-up symbol="{$symbol}"> <start-date>{fn:data($first/date)}</start-date> <start-price>{fn:data($first/price)}</start-price> <end-date>{fn:data($last/date)}</end-date> <end-price>{fn:data($last/price)}</end-price> </run-up> Note: In the above example, the for let for $closings in //closing let $symbol := $closings/symbol group by $symbol The group by 3.10.7 Group By Clause The for let $symbol $closings closing $symbol $closings closing The window $symbol $closings $w $first $second $last $beyond return <run-up symbol="ABC"> <start-date>2008-01-02</start-date> <start-price>101</start-price> <end-date>2008-01-04</end-date> <end-price>103</end-price> </run-up> <run-up symbol="ABC"> <start-date>2008-01-05</start-date> <start-price>101</start-price> <end-date>2008-01-06</end-date> <end-price>104</end-price> </run-up> <run-up symbol="DEF"> <start-date>2008-01-02</start-date> <start-price>054</start-price> <end-date>2008-01-03</end-date> <end-price>056</end-price> </run-up> <run-up symbol="DEF"> <start-date>2008-01-04</start-date> <start-price>052</start-price> <end-date>2008-01-06</end-date> <end-price>059</end-price> </run-up> WhereClause ::= "where" ExprSingle A where where where-expression effective boolean value true Examples: This example illustrates the effect of a where Input tuple stream: ($a = 5, $b = 11) ($a = 91, $b = 42) ($a = 17, $b = 30) ($a = 85, $b = 63) where where $a > $b Output tuple stream: ($a = 91, $b = 42) ($a = 85, $b = 63) The following query illustrates how a where positional variable for $x at $i in $inputvalues where $i mod 100 = 0 return $x CountClause ::= "count" "$" VarName The purpose of a count count The output tuple stream of a count The following examples illustrate uses of the count This example illustrates the effect of a count Input tuple stream: ($name = "Bob", $age = 21) ($name = "Carol", $age = 19) ($name = "Ted", $age = 20) ($name = "Alice", $age = 22) count count $counter Output tuple stream: ($name = "Bob", $age = 21, $counter = 1) ($name = "Carol", $age = 19, $counter = 2) ($name = "Ted", $age = 20, $counter = 3) ($name = "Alice", $age = 22, $counter = 4) This example illustrates how a counter might be used to filter the result of a query. The query ranks products in order by decreasing sales, and returns the three products with the highest sales. Assume that the variable $products product name sales for $p in $products order by $p/sales descending count $rank where $rank <= 3 return <product rank="{$rank}"> {$p/name, $p/sales} </product> The result of this query has the following structure: <product rank="1"> <name>Toaster</name> <sales>968</sales> </product> <product rank="2"> <name>Blender</name> <sales>520</sales> </product> <product rank="3"> <name>Can Opener</name> <sales>475</sales> </product> GroupByClause ::= "group" "by" GroupingSpecList GroupingSpecList ::= GroupingSpec GroupingSpec GroupingSpec ::= GroupingVariable TypeDeclaration ExprSingle URILiteral GroupingVariable ::= "$" VarName A group by that have equivalent grouping keys pre-grouping tuples post-grouping tuples The group by In the post-grouping tuple for a group, each grouping key is represented by a variable that was specified in a GroupingSpec The number of post-grouping tuples is less than or equal to the number of pre-grouping tuples A group by grouping specifications Definition grouping variable eq expanded QNames static error err:XQST0094 let let group by $g1, $g2 := $expr1, $g3 := $expr2 collation "Spanish" is semantically equivalent to the following sequence of clauses: let $g2 := $expr1 let $g3 := $expr2 group by $g1, $g2, $g3 collation "Spanish" The process of group formation proceeds as follows: [ Definition grouping variable grouping key grouping keys atomizing grouping variables grouping variable type error err:XPTY0004 If a type declaration is present and the resulting atomized value is not an instance of the specified type, a type error err:XPTY0004 The input tuple stream is partitioned into groups of tuples whose grouping keys are equivalent Definition T1 T2 equivalent grouping keys GV GV T1 GV T2 fn:deep-equal A B C A eq B B eq C A ne C Section 14.2.1 fn:distinct-values FO30 Note: The atomized grouping key will always be either an empty sequence or a single atomic value. Defining equivalence by reference to the fn:deep-equal NaN NaN eq The appropriate collation for comparing two grouping keys is the collation specified in the pertinent GroupingSpec resolved to an absolute URI Static Base URI err:XQST0076 Each group of tuples produced by the above process results in one post-grouping tuple. The pre-grouping tuples from which the group is derived have equivalent grouping keys equivalent grouping variable the corresponding grouping key In the post-grouping tuple generated for a given group, each non-grouping variable is bound to a sequence containing the concatenated values of that variable in all the pre-grouping tuples that were assigned to that group. If ordering mode ordered implementation-dependent Note: This behavior may be surprising to SQL programmers, since SQL reduces the equivalent of a non-grouping variable to one representative value. Consider the following query: let $x := 64000 for $c in //customer where $c/salary > $x group by $d := $c/department return <department name="{$d}"> Number of employees earning more than ${$x} is {count($c)} </department> If there are three qualifying customers in the sales department this evaluates to: <department name="sales"> Number of employees earning more than $64000 64000 64000 is 3 </department> In XQuery, each group is a sequence of items that match the group by criteria—in a tree-structured language like XQuery, this is convenient, because further structures can be built based on the items in this sequence. Because there are three items in the group, $x fn:distinct-values() let $x := 64000 for $c in //customer let $d := $c/department where $c/salary > $x group by $d return <department name="{$d}"> Number of employees earning more than ${distinct-values($x)} is {count($c)} </department> Note: In general, the static type static type The order in which tuples appear in the post-grouping tuple stream is implementation-dependent Note: An order by order by order by group by A group by group by Examples: This example illustrates the effect of a group by Input tuple stream: ($storeno = <storeno>S101</storeno>, $itemno = <itemno>P78395</itemno>) ($storeno = <storeno>S102</storeno>, $itemno = <itemno>P94738</itemno>) ($storeno = <storeno>S101</storeno>, $itemno = <itemno>P41653</itemno>) ($storeno = <storeno>S102</storeno>, $itemno = <itemno>P70421</itemno>) group by group by $storeno Output tuple stream: ($storeno = S101, $itemno = (<itemno>P78395</itemno>, <itemno>P41653</itemno>)) ($storeno = S102, $itemno = (<itemno>P94738</itemno>, <itemno>P70421</itemno>)) This example and the ones that follow are based on two separate sequences of elements, named $sales $products $sales <sales> <storeno>S101</storeno> <itemno>P78395</itemno> <qty>125</qty> </sales> We also assume that the variable $products <product> <itemno>P78395</itemno> <price>25.00</price> <category>Men's Wear</category> </product> The simplest kind of grouping query has a single grouping variable for $s in $sales let $storeno := $s/storeno group by $storeno return <store number="{$storeno}" total-qty="{sum($s/qty)}"/> The result of this query is a sequence of elements with the following structure: <store number="S101" total-qty="1550" /> <store number="S102" total-qty="2125" /> In a more realistic example, a user might be interested in the total revenue generated by each store for each product category. Revenue depends on both the quantity sold of various items and the price of each item. The following query joins the two input sequences and groups the resulting tuples by two grouping variables for $s in $sales, $p in $products[itemno = $s/itemno] let $revenue := $s/qty * $p/price group by $storeno := $s/storeno, $category := $p/category return <summary storeno="{$storeno}" category="{$category}" revenue="{sum($revenue)}"/> The result of this query is a sequence of elements with the following structure: <summary storeno="S101" category="Men's Wear" revenue="10185"/> <summary storeno="S101" category="Stationery" revenue="4520"/> <summary storeno="S102" category="Men's Wear" revenue="9750"/> <summary storeno="S102" category="Appliances" revenue="22650"/> <summary storeno="S102" category="Jewelry" revenue="30750"/> The result of the previous example was a "flat" list of elements. A user might prefer the query result to be presented in the form of a hierarchical report, grouped primarily by store (in order by store number) and secondarily by product category. Within each store, the user might want to see only those product categories whose total revenue exceeds $10,000, presented in descending order by their total revenue. This report is generated by the following query: for $s1 in $sales let $storeno := $s1/storeno group by $storeno order by $storeno return <store storeno="{$storeno}"> {for $s2 in $s1, $p in $products[itemno = $s2/itemno] let $category := $p/category, $revenue := $s2/qty * $p/price group by $category let $group-revenue := sum($revenue) where $group-revenue > 10000 order by $group-revenue descending return <category name="{$category}" revenue="{$group-revenue}"/> } </store> The result of this example query has the following structure: <store storeno="S101"> <category name="Men's Wear" revenue="10185"/> </store> <store storeno="S102"> <category name="Jewelry" revenue="30750"/> <category name="Appliances" revenue="22650"/> </store> The following example illustrates how to avoid a possible pitfall in writing grouping queries. In each post-grouping tuple, all variables except for the grouping variable are bound to sequences of items derived from all the pre-grouping tuples from which the group was formed. For instance, in the following query, $high-price let $high-price := 1000 for $p in $products[price > $high-price] let $category := $p/category group by $category return <category name="{$category}"> {fn:count($p)} products have price greater than {$high-price}. </category> If three products in the "Men's Wear" category have prices greater than 1000, the result of this query might look (in part) like this: <category name="Men's Wear"> 3 products have price greater than 1000 1000 1000. </category> The repetition of "1000" in this query result is due to the fact that $high-price grouping variable $high-price let $high-price := 1000 return for $p in $products[price > $high-price] let $category := $p/category group by $category return <category name="{$category}"> {fn:count($p)} products have price greater than {$high-price}. </category> The result of the revised query might contain the following element: <category name="Men's Wear"> 3 products have price greater than 1000. </category> OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList OrderSpecList ::= OrderSpec OrderSpec OrderSpec ::= ExprSingle OrderModifier OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral The purpose of an order by order by An order by orderspecs collation xs:string xs:anyURI default collation resolved to an absolute URI Static Base URI statically known collations err:XQST0076 The process of evaluating and comparing the orderspecs is based on the following rules: Atomization type error err:XPTY0004 If the value of an orderspec has the dynamic type xs:untypedAtomic xs:string Note: Consistently treating untyped values as strings enables the sorting process to begin without complete knowledge of the types of all the values to be sorted. All the non-empty orderspec values must be convertible to a common type by subtype substitution type promotion gt gt type error err:XPTY0004 Example: The orderspec values include a value of type hatsize xs:integer shoesize xs:decimal xs:decimal Example: The orderspec values include a value of type xs:string xs:anyURI xs:string For the purpose of determining their relative position in the ordering sequence, the greater-than W V When the orderspec specifies empty least If V W W greater-than V If V NaN W NaN W greater-than V If a specific collation C V W xs:string xs:string subtype substitution type promotion If fn:compare(V, W, C) W greater-than V W greater-than V If none of the above rules apply, then: If W gt V W greater-than V W greater-than V When the orderspec specifies empty greatest If W V W greater-than V If W NaN V NaN W greater-than V If a specific collation C V W xs:string xs:string subtype substitution type promotion If fn:compare(V, W, C) W greater-than V W greater-than V If none of the above rules apply, then: If W gt V W greater-than V W greater-than V When the orderspec specifies neither empty least empty greatest default order for empty sequences static context empty least empty greatest If T1 T2 V1 V2 greater-than If V1 greater-than V2: descending T1 T2 T2 T1 If V2 greater-than V1 descending T2 T1 T1 T2 If neither V1 V2 greater-than T1 T2 If stable T1 T2 If stable T1 T2 implementation-dependent Note: If two orderspecs return the special floating-point values positive and negative zero, neither of these values is greater-than +0.0 gt -0.0 -0.0 gt +0.0 false Examples: This example illustrates the effect of an order by stable Input tuple stream: ($license = "PFQ519", $make = "Ford", $value = 16500) ($license = "HAJ865", $make = "Honda", $value = 22750) ($license = "NKV473", $make = "Ford", $value = 21650) ($license = "RCM922", $make = "Dodge", $value = 11400) ($license = "ZBX240", $make = "Ford", $value = 16500) ($license = "KLM030", $make = "Dodge", $value = () ) order by stable order by $make, $value descending empty least Output tuple stream: ($license = "RCM922", $make = "Dodge", $value = 11400) ($license = "KLM030", $make = "Dodge", $value = () ) ($license = "NKV473", $make = "Ford", $value = 21650) ($license = "PFQ519", $make = "Ford", $value = 16500) ($license = "ZBX240", $make = "Ford", $value = 16500) ($license = "HAJ865", $make = "Honda", $value = 22750) The following example shows how an order by for $e in $employees order by $e/salary descending return $e/name Note: Since the order by path expression $books/book[price < 100] for $b in $books/book[price < 100] order by $b/title return $b ReturnClause ::= "return" ExprSingle The return return comma operator The following example illustrates a FLWOR expression containing several clauses. The for depts.xml $d $d let $e emps.xml deptno $d $e $d $e where order by return big-dept for $d in fn:doc("depts.xml")//dept let $e := fn:doc("emps.xml")//emp[deptno eq $d/deptno] where fn:count($e) >= 10 order by fn:avg($e/salary) descending return <big-dept> { $d/deptno, <headcount>{fn:count($e)}</headcount>, <avgsal>{fn:avg($e/salary)}</avgsal> } </big-dept> Notes: The order in which items appear in the result of a FLWOR expression depends on the ordering of the input tuple stream to the return order by ordering mode for $d in fn:doc("depts.xml")//dept order by $d/deptno for $e in fn:doc("emps.xml")//emp[deptno eq $d/deptno] return <assignment> {$d/deptno, $e/name} </assignment> The result of this query is a sequence of assignment deptno name deptno order by ordering mode ordered assignment deptno name emps.xml implementation-dependent Parentheses are helpful in return $j let $i := 5, $j := 20 * $i return $i, $j Parentheses can be used to bring $j return let $i := 5, $j := 20 * $i return ($i, $j) OrderedExpr ::= "ordered" "{" Expr UnorderedExpr ::= "unordered" "{" Expr The purpose of ordered unordered ordering mode static context ordered unordered unordered Ordering mode path expressions / // axis step union intersect except fn:id fn:element-with-id fn:idref ordered union intersect except fn:id fn:idref document order implementation-dependent 3.10.2 For Clause 3.10.4.3 Effects of Window Clauses on the Tuple Stream 3.10.7 Group By Clause Note: In a region of a query where ordering mode is unordered implementation-dependent fn:position fn:last fn:index-of fn:insert-before fn:remove fn:reverse fn:subsequence The functions fn:boolean fn:not implementation-dependent unordered 2.4.3 Effective Boolean Value path expression numeric predicates implementation-dependent (//a/b)[5] b document order implementation-dependent b Note: The fn:id fn:idref [XQuery and XPath Functions and Operators 3.0] document order unordered The use of an unordered parts.xml suppliers.xml unordered document order parts.xml document order suppliers.xml suppliers.xml parts.xml unordered unordered { for $p in fn:doc("parts.xml")/parts/part[color = "Red"], $s in fn:doc("suppliers.xml")/suppliers/supplier where $p/suppno = $s/suppno return <ps> { $p/partno, $s/suppno } </ps> } In addition to ordered unordered fn:unordered implementation-defined fn:unordered fn:unordered unordered ordering mode XQuery 3.0 supports a conditional expression based on the keywords if then else IfExpr ::= "if" "(" Expr ExprSingle ExprSingle The expression following the if test expression then else then-expression else-expression The first step in processing a conditional expression is to find the effective boolean value 2.4.3 Effective Boolean Value The value of a conditional expression is defined as follows: If the effective boolean value of the test expression is true false Conditional expressions have a special rule for propagating dynamic errors true false dynamic errors Here are some examples of conditional expressions: In this example, the test expression is a comparison expression: if ($widget1/unit-cost < $widget2/unit-cost) then $widget1 else $widget2 In this example, the test expression tests for the existence of an attribute named discounted if ($part/@discounted) then $part/wholesale else $part/retail SwitchExpr ::= "switch" "(" Expr SwitchCaseClause ExprSingle SwitchCaseClause ::= ("case" SwitchCaseOperand ExprSingle SwitchCaseOperand ::= ExprSingle The switch expression In a switch switch switch operand expression switch case case operand expressions default The first step in evaluating a switch expression is to apply atomization to the value of the switch operand expression. If the result is a sequence of length greater than one, a type error is raised [ err:XPTY0004 The resulting value is matched against each SwitchCaseOperand The SwitchCaseOperand The resulting value is atomized. If the atomized sequence has length greater than one, a type error is raised [ err:XPTY0004 The atomized value of the switch operand expression is compared with the atomized value of the SwitchCaseOperand fn:deep-equal [ Definition effective case Switch expressions have rules regarding the propagation of dynamic errors that take precedence over the general rules given in 2.3.4 Errors and Optimization The following example shows how a switch expression might be used: switch ($animal) case "Cow" return "Moo" case "Cat" return "Meow" case "Duck" return "Quack" default return "What's that odd noise?" Quantified expressions support existential and universal quantification. The value of a quantified expression is always true false QuantifiedExpr ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle TypeDeclaration ::= "as" SequenceType A quantified expression quantifier some every satisfies effective boolean value 2.4.3 Effective Boolean Value If the quantifier is some true effective boolean value true false false If the quantifier is every true effective boolean value true false true The scope of a variable bound in a quantified expression comprises all subexpressions of the quantified expression that appear after the variable binding. The scope does not include the expression to which the variable is bound. Each variable bound in an in-clause of a quantified expression may have an optional type declaration SequenceType matching type error err:XPTY0004 The order in which test expressions are evaluated for the various binding tuples is implementation-dependent some true effective boolean value true dynamic error every false effective boolean value false dynamic error Here are some examples of quantified expressions: This expression is true part discounted every $part in /parts/part satisfies $part/@discounted This expression is true employee some $emp in /emps/employee satisfies ($emp/bonus > 0.25 * $emp/salary) In the following examples, each quantified expression evaluates its test expression over nine tuples of variable bindings, formed from the Cartesian product of the sequences (1, 2, 3) (2, 3, 4) some true every false some $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4 every $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4 This quantified expression may either return true type error true type error some $x in (1, 2, "cat") satisfies $x * 2 = 4 This quantified expression may either return false type error false type error every $x in (1, 2, "cat") satisfies $x * 2 = 4 This quantified expression contains a type declaration Static Typing Feature type error static analysis phase true type error dynamic evaluation phase some $x as xs:integer in (1, 2, "cat") satisfies $x * 2 = 4 The try/catch expression provides error handling for dynamic errors and type errors raised during dynamic evaluation, including errors raised by the XQuery implementation and errors explicitly raised in a query using the fn:error() TryCatchExpr ::= TryClause CatchClause TryClause ::= "try" "{" TryTargetExpr TryTargetExpr ::= Expr CatchClause ::= "catch" CatchErrorList Expr CatchErrorList ::= NameTest NameTest A try/catch expression catches dynamic errors type errors try If the target expression raises a dynamic error or a type error, the result of the try/catch expression is obtained by evaluating the first catch If no catch clause "matches" the error value, then the try/catch expression raises the error that was raised by the target expression. catch err:FOER0000 catch err:FOER0000 | err:FOER0001 err:FOER0000 catch err:* *:FOER0000 * Within the scope of the catch Variable Type Value err:code xs:QName The error code err:description xs:string ? A description of the error condition; an empty sequence if no description is available (for example, if the error err:value item()* Value associated with the error. For an error raised by calling the error err:module xs:string? The URI (or system ID) of the module containing the expression err:line-number xs:integer? The line number within the stylesheet module of the instruction where the error occurred, or an empty sequence if the information is not available. The value may err:column-number xs:integer? The column number within the stylesheet module of the instruction where the error occurred, or an empty sequence if the information is not available. The value may err:additional item()* Implementation-defined Try/catch expressions have a special rule for propagating dynamic errors. The try/catch expression ignores any dynamic errors encountered in catch clauses other than the first catch clause that matches an error raised by the try clause, and these catch clause expressions need not be evaluated. Static errors are not caught by the try/catch expression. If a function call occurs within a try try try Note: The presence of a try/catch expression does not prevent an implementation from using a lazy evaluation strategy, nor does it prevent an optimizer performing expression rewrites. However, if the evaluation of an expression inside a try/catch is rewritten or deferred in this way, it must take its try/catch context with it. Similarly, expressions that were written outside the try/catch expression may be evaluated inside the try/catch, but only if they retain their original try/catch behavior. The presence of a try/catch does not change the rules that allow the processor to evaluate expressions in such a way that may avoid the detection of some errors. Here are some examples of try/catch expressions. A try/catch expression without a CatchErrorList catches any error: try { $x cast as xs:integer } catch * { 0 } The CatchErrorList in this try/catch expression specifies that only err:FORG0001 try { $x cast as xs:integer } catch err:FORG0001 { 0 } The CatchErrorList in this try/catch expression specifies that errors err:FORG0001 err:XPTY0004 try { $x cast as xs:integer } catch err:FORG0001 | err:XPTY0004 { 0 } Note: In some implementations, err:XPTY0004 This try/catch expression shows how to return information about the error using implicitly defined error variables. Since the CatchErrorList is a wildcard, it catches any error: try { fn:error(fn:QName('http://www.w3.org/2005/xqt-errors', 'err:FOER0000')) } catch * { $err:code, $err:value, " module: ", $err:module, "(", $err:line-number, ",", $err:column-number, ")" } Errors raised by using the result of a try/catch expression are not caught, since they are outside the scope of the try declare function local:thrice($x as xs:integer) as xs:integer { 3*$x };
local:thrice(try { "oops" } catch * { 3 } ) In this example, the try block succeeds, returning the string "oops", which is not a valid argument to the function. In addition to their use in function parameters and results, sequence types instance of typeswitch cast castable treat InstanceofExpr ::= TreatExpr SequenceType The boolean operator instance of true SequenceType SequenceType matching false 5 instance of xs:integer This example returns true 5 instance of xs:decimal This example returns true xs:integer xs:decimal <a>{5}</a> instance of xs:integer This example returns false (5, 6) instance of xs:integer+ This example returns true . instance of element() This example returns true false absent DM30 dynamic error err:XPDY0002 TypeswitchExpr ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle CaseClause ::= "case" ("$" VarName SequenceTypeUnion ExprSingle SequenceTypeUnion ::= SequenceType SequenceType The typeswitch dynamic type In a typeswitch typeswitch operand expression typeswitch case default Each case SequenceType return Definition effective case typeswitch case SequenceType SequenceTypeUnion case SequenceType matching typeswitch return SequenceType case typeswitch return default In a case default return case default case static type SequenceType SequenceTypeUnion default case default The scope of a variable binding in a case default case default typeswitch A special rule applies to propagation of dynamic errors typeswitch typeswitch case effective case default effective case effective case The following example shows how a typeswitch dynamic type typeswitch($customer/billing-address) case $a as element(*, USAddress) return $a/state case $a as element(*, CanadaAddress) return $a/province case $a as element(*, JapanAddress) return $a/prefecture default return "unknown" The following example shows a union of sequence types in a single case: typeswitch($customer/billing-address) case $a as element(*, USAddress) | element(*, AustraliaAddress) | element(*, MexicoAddress) return $a/state case $a as element(*, CanadaAddress) return $a/province case $a as element(*, JapanAddress) return $a/prefecture default return "unknown" CastExpr ::= UnaryExpr SingleType SingleType ::= SimpleTypeName AtomicOrUnionType ::= EQName Occasionally it is necessary to convert a value to a specific datatype. For this purpose, XQuery 3.0 provides a cast cast input expression target type atomized value of the input type The SimpleTypeName must be the name of a type defined in the in-scope schema types it must be a simple type err:XQST0052 xs:NOTATION , xs:anySimpleType xs:anyAtomicType err:XPST0080 ? is a lexical QName that default element/type namespace Casting a node to xs:QName can cause surprises because it uses of casting to xs:QName fn:QName The semantics of the cast The input expression is evaluated. The result of the first step is atomized If the result of atomization is a sequence of more than one atomic value, a type error err:XPTY0004 If the result of atomization is an empty sequence: If ? cast If ? type error err:XPTY0004 If the result of atomization is a single atomic value, the result of the cast expression depends on the input type and the target type. In general, the cast expression attempts to create a new value of the target type based on the input value. Only certain combinations of input type and target type are supported. A summary of the rules are listed below—the normative definition of these rules is given in [XQuery and XPath Functions and Operators 3.0] in-scope schema definitions implementation-dependent cast Section 18.1 Casting from primitive types to primitive types FO30 schema types xs:string xs:decimal [XQuery and XPath Functions and Operators 3.0] cast shoesize xs:integer shoesize xs:integer cast xs:string xs:untypedAtomic [XML Schema 1.0] [XML Schema 1.1] dynamic error [XQuery and XPath Functions and Operators 3.0] cast xs:string xs:untypedAtomic [XML Schema 1.0] [XML Schema 1.1] The effect of casting a string S T S T If the target type is namespace-sensitive cast xs:string dynamic type If a primitive type P1 can be cast into a primitive type P2, then any type derived by restriction from P1 can be cast into any type derived by restriction from P2, provided that the facets of the target type are satisfied. First the input value is cast to P1 using rule (b) above. Next, the value of type P1 is cast to the type P2, using rule (a) above. Finally, the value of type P2 is cast to the target type, using rule (d) above. For any combination of input type and target type that is not in the above list, a cast type error err:XPTY0004 If casting from the input type to the target type is supported but nevertheless it is not possible to cast the input value into the value space of the target type, a dynamic error "2003-02-31" cast as xs:date dynamic error CastableExpr ::= CastExpr SingleType SingleType ::= SimpleTypeName XQuery 3.0 provides an expression that tests whether a given value is castable into a given target type. The SimpleTypeName must be the name of a type defined in the in-scope schema types simple err:XQST0052 xs:NOTATION xs:anySimpleType xs:anyAtomicType err:XPST0080 ? The expression E castable as T true E T cast false E castable castable predicate if ($x castable as hatsize) then $x cast as hatsize else if ($x castable as IQ) then $x cast as IQ else $x cast as xs:string For every generalized atomic type in-scope schema types xs:NOTATION xs:anyAtomicType constructor function T T($arg as xs:anyAtomicType?) as T? [ Definition constructor function T($arg) (($arg) cast as T?) The following examples illustrate the use of constructor functions: This example is equivalent to ("2000-01-01" cast as xs:date?) xs:date("2000-01-01") This example is equivalent to (($floatvalue * 0.2E-5) cast as xs:decimal?) xs:decimal($floatvalue * 0.2E-5) This example returns an xs:dayTimeDuration ("P21D" cast as xs:dayTimeDuration?) xs:dayTimeDuration("P21D") If usa:zipcode in-scope schema types ("12345" cast as usa:zipcode?) usa:zipcode("12345") Note: An instance of an atomic type that is not in a namespace can be constructed in either of the following ways: By using a cast default element/type namespace absent DM30 (See 4.14 Default Namespace Declaration default element/type namespace 17 cast as apple By using a constructor function, if the default function namespace absent DM30 (See 4.14 Default Namespace Declaration default function namespace apple(17) TreatExpr ::= CastableExpr SequenceType XQuery 3.0 provides an expression called treat static type Like cast treat SequenceType cast treat dynamic type treat The semantics of expr1 treat as type1 During static analysis: The static type treat type1 type1 During expression evaluation: If expr1 type1 SequenceType matching treat expr1 dynamic error err:XPDY0050 expr1 treat Example: $myaddress treat as element(*, USAddress) The static type $myaddress element(*, Address) element(*, USAddress) $myaddress element(*, USAddress) SequenceType matching dynamic error err:XPDY0050 ! SimpleMapExpr ::= PathExpr PathExpr The simple map operator " ! Each operation E1!E2 E1 S S S S E2 dynamic context E2 E2 E2 Simple map operators have functionality similar to 3.3.1.1 Path operator (/) Operator Path operator ( E1 / E2 Simple map operator ( E1 ! E2 E1 Any sequence of nodes Any sequence of items E2 Either a sequence of nodes or a sequence of non-node items A sequence of items Additional processing Duplicate elimination and document ordering Simple sequence concatenation The following examples illustrate the use of simple map operators combined with path expressions. child::div1 / child::para / string() ! concat("id-", .) Selects the para div1 para div1 "id-" $emp ! (@first, @middle, @last) Returns the values of the attributes first middle last $emp / $docs ! ( //employee) Returns all the employees within all the documents identified by the variable docs, in document order within each document, but retaining the order of documents. avg( //employee / salary ! translate(., '$', '') ! number(.)) Returns the average salary of the employees, having converted the salary to a number by removing any $ ! / / ValidateExpr ::= "validate" ( ValidationMode TypeName Expr ValidationMode ::= "lax" | "strict" A validate in-scope schema definitions [XML Schema 1.0] [XML Schema 1.1] validate type error err:XQTY0030 validate operand node A validate type annotation A validate validation mode validation mode (applicable when no type name is provided) strict A validate TypeName in-scope schema definitions static error err:XQST0104 The result of a validate If the operand node is a document node, its children must consist of exactly one element node and zero or more comment and processing instruction nodes, in any order; otherwise, a dynamic error err:XQDY0061 The operand node is converted to an XML Information Set ( [XML Infoset] [XQuery and XPath Data Model (XDM) 3.0] type annotations Validity assessment is carried out on the root element information item of the resulting Infoset, using the in-scope schema definitions If a type name is provided, and the type name is xs:untyped xs:untyped xs:untypedAtomic xs:untypedAtomic err:XPTY0004 [XML Schema 1.0] [XML Schema 1.1] When no type name is provided: If validation mode strict in-scope element declarations [XML Schema 1.0] [XML Schema 1.1] dynamic error err:XQDY0084 If validation mode lax [XML Schema 1.0] [XML Schema 1.1] If validation mode lax xsi:type [XML Schema 1.0] [XML Schema 1.1] validate If the operand node is an element node, the validation rules named "Validation Root Valid (ID/IDREF)" are not applied. This means that document-level constraints relating to uniqueness and referential integrity are not enforced. There is no check that the document contains unparsed entities whose names match the values of nodes of type xs:ENTITY xs:ENTITIES Note: Validity assessment is affected by the presence or absence of xsi:type The outcome of the validation expression depends on the validity If the validity valid validation mode lax validity notKnown XDM instance [XQuery and XPath Data Model (XDM) 3.0] validate Otherwise, a dynamic error err:XQDY0027 Note: The effect of these rules is as follows, where the validated element If validation mode strict If validation mode lax validation mode lax xsi:type xsi:type If a type name is specified in the validate expression, no attempt is made to locate an element declaration matching the name of the validated element; the element can have any name, and its content is validated against the named type. Note: During conversion of the PSVI into an XDM instance notKnown type annotation xs:anyType notKnown type annotation xs:untypedAtomic Section 3.3.1.1 Element and Attribute Node Types DM30 [ Definition extension expression implementation-defined ExtensionExpr ::= Pragma Expr Pragma ::= "(#" S EQName S PragmaContents PragmaContents ::= ( Char An extension expression consists of one or more pragmas Definition pragma (# #) implementation-defined #) lexical QName statically known namespaces err:XPST0081 Note: Since there is no default namespace for pragmas, a pragma's EQName must provide a BracedURILiteral Each implementation recognizes an implementation-defined If the namespace URI of a pragma's expanded QName ExtensionExpr ExtensionExpr static error err:XQST0079 If an implementation recognizes the namespace of one or more pragmas in an ExtensionExpr ExtensionExpr implementation-defined expanded QName It is a static error err:XQST0013 If an implementation recognizes a pragma, it must report any static errors in the following expression even if it will not evaluate that expression (however, static type errors are raised only if the Static Typing Feature Note: The following examples illustrate three ways in which extension expressions might be used. A pragma can be used to furnish a hint for how to evaluate the following expression, without actually changing the result. For example: declare namespace exq = "http://example.org/XQueryImplementation"; (# exq:use-index #) { $bib/book/author[name='Berners-Lee'] } An implementation that recognizes the exq:use-index A pragma might be used to modify the semantics of the following expression in ways that would not (in the absence of the pragma) be conformant with this specification. For example, a pragma might be used to permit comparison of xs:duration A pragma might contain syntactic constructs that are evaluated in place of the following expression. In this case, the following expression itself (if it is present) provides a fallback for use by implementations that do not recognize the pragma. For example: declare namespace exq = "http://example.org/XQueryImplementation"; for $x in (# exq:distinct //city by @country #) { //city[not(@country = preceding::city/@country)] } return f:show-city($x) Here an implementation that recognizes the pragma will return the result of evaluating the proprietary syntax exq:distinct //city by @country //city[not(@country = preceding::city/@country)] static error Module ::= VersionDecl LibraryModule MainModule MainModule ::= Prolog QueryBody LibraryModule ::= ModuleDecl Prolog Prolog ::= (( DefaultNamespaceDecl Setter NamespaceDecl Import Separator ContextItemDecl AnnotatedDecl OptionDecl Separator Setter ::= BoundarySpaceDecl DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl DecimalFormatDecl Import ::= SchemaImport ModuleImport Separator ::= ";" QueryBody ::= Expr A query can be assembled from one or more fragments called modules Definition module Module static analysis phase 2.2.3 Expression Processing main module library module [ Definition main module Prolog Query Body Query Body It is evaluated with respect to the static and dynamic contexts of the main module in which it is found, and its value is the result of the query. [ Definition Query Body library module module declaration Prolog The XQuery syntax does not allow a module module declaration Query Body [ Definition Prolog module The first part of the Prolog consists of setters, imports, namespace declarations, and default namespace declarations. [ Definition Setters lexical QNames Definition The target namespace The second part of the Prolog consists of declarations of variables, functions, and options. These declarations appear at the end of the Prolog because they may be affected by declarations and imports in the first part of the Prolog. [ Definition Query Body 3 Expressions VersionDecl ::= "xquery" (("encoding" StringLiteral StringLiteral StringLiteral Separator [ Definition version declaration module XQuery 1.0 processor XQuery 3.0 processor Process the module using the specification of the XQuery version identified in the version declaration. Process the module using the specification of XQuery 3.0. Note: An implementation may issue a warning in this case. Raise a static error [ err:XQST0031 A processor may raise an error [ err:XQST0034 Note: In general, this should be done only if a processor is not able to evaluate such a query. [ Definition encoding declaration encoding EncName [XML 1.0] err:XQST0087 UTF-8 UTF-16 US-ASCII The handling of an encoding declaration is implementation-dependent a priori If a version declaration is present, no Comment Comment implementation-dependent ; an implementation may raise an implementation-dependent static error, or ignore the comment Note: The effect of a Comment before the end of a version declaration is implementation-dependent because it may suppress query processing by interfering with detection of the encoding declaration. The following examples illustrate version declarations: xquery version "1.0"; xquery version "3.0" encoding "utf-8"; ModuleDecl ::= "module" "namespace" NCName URILiteral Separator [ Definition module declaration module library module module URILiteral err:XQST0088 target namespace static error err:XQST0048 The (prefix,URI) pair is added to the set of statically known namespaces The namespace prefix specified in a module declaration must not be xml xmlns err:XQST0070 schema import namespace declaration module import err:XQST0033 Any module module import static context dynamic context The following is an example of a module declaration: module namespace gis = "http://example.org/gis-functions"; BoundarySpaceDecl ::= "declare" "boundary-space" ("preserve" | "strip") [ Definition boundary-space declaration boundary-space policy static context boundary whitespace preserve strip 3.9.1.4 Boundary Whitespace The following example illustrates a boundary-space declaration: declare boundary-space preserve; If a Prolog contains more than one boundary-space declaration, a static error err:XQST0068 DefaultCollationDecl ::= "declare" "default" "collation" URILiteral [ Definition default collation declaration default collation static context gt fn:compare gt fn:compare gt If neither the implementation nor the Prolog specifies a default collation, the Unicode codepoint collation ( http://www.w3.org/2005/xpath-functions/collation/codepoint The following example illustrates a default collation declaration: declare default collation "http://example.org/languages/Icelandic"; If a default collation declaration specifies a collation by a relative URI, that relative URI is resolved to an absolute URI Static Base URI statically known collations static error err:XQST0038 BaseURIDecl ::= "declare" "base-uri" URILiteral [ Definition base URI declaration Static Base URI Static Base URI For example, the Static Base URI module import fn:doc Note: As discussed in the definition of Static Base URI The following is an example of a base URI declaration: declare base-uri "http://example.org"; If a Prolog contains more than one base URI declaration, a static error err:XQST0032 In the terminology of [RFC3986] Static Base URI [RFC3986] ../data/ file:///C:/temp/queries/query.xq Static Base URI file:///C:/temp/data/ It is not intrinsically an error if this process fails to establish an absolute base URI; however, the Static Base URI absent DM30 err:XPST0001 Static Base URI absent DM30 resolve a relative URI reference err:XPST0001 ConstructionDecl ::= "declare" "construction" ("strip" | "preserve") [ Definition construction declaration construction mode static context preserve xs:anyType strip xs:untyped xs:untyped xs:untypedAtomic The following example illustrates a construction declaration: declare construction strip; If a Prolog specifies more than one construction declaration, a static error err:XQST0067 OrderingModeDecl ::= "declare" "ordering" ("ordered" | "unordered") [ Definition ordering mode declaration ordering mode static context module Prolog Query Body ordered unordered The following example illustrates an ordering mode declaration: declare ordering unordered; If a Prolog contains more than one ordering mode declaration, a static error err:XQST0065 EmptyOrderDecl ::= "declare" "default" "order" "empty" ("greatest" | "least") [ Definition empty order declaration default order for empty sequences static context, NaN order by order by empty greatest empty least The following example illustrates an empty order declaration: declare default order empty least; If a Prolog contains more than one empty order declaration, a static error err:XQST0069 Note: It is important to distinguish an empty order declaration ordering mode declaration empty order declaration order by order by ordering mode declaration order by CopyNamespacesDecl ::= "declare" "copy-namespaces" PreserveMode InheritMode PreserveMode ::= "preserve" | "no-preserve" InheritMode ::= "inherit" | "no-inherit" [ Definition copy-namespaces declaration copy-namespaces mode static context 3.9.1 Direct Element Constructors The following example illustrates a copy-namespaces declaration: declare copy-namespaces preserve, no-inherit; If a Prolog contains more than one copy-namespaces declaration, a static error err:XQST0055 DecimalFormatDecl ::= "declare" (("decimal-format" EQName DFPropertyName StringLiteral DFPropertyName ::= "decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" [ Definition decimal format declaration statically known decimal formats fn:format-number() [XQuery and XPath Functions and Operators 3.0] fn:format-number() statically known decimal formats It is a static error err:XQST0111 static error err:XQST0114 static error statically known decimal formats err:XQST0097 static error err:XQST0098 decimal-separator-sign grouping-separator percent-sign per-mille-sign zero-digit digit-sign pattern-separator-sign The following query formats numbers using two different decimal format declarations: declare decimal-format local:de decimal-separator = "," grouping-separator = "."; declare decimal-format local:en decimal-separator = "." grouping-separator = ",";
let $numbers := (1234.567, 789, 1234567.765) for $i in $numbers return ( format-number($i, "#.###,##", "local:de"), format-number($i, "#,###.##", "local:en") ) The output of this query is: 1.234,57 1,234.57 789 789 1.234.567,76 1,234,567.76 SchemaImport ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral SchemaPrefix ::= ("namespace" NCName [ Definition schema import in-scope schema definitions For each named simple type constructor function target namespace adding the (prefix, URI) pair to the statically known namespaces default element/type namespace The namespace prefix specified in a schema import must not be xml xmlns err:XQST0070 module import namespace declaration module declaration err:XQST0033 The first URILiteral at A schema import that specifies a zero-length string as target namespace is considered to import a schema that has no target namespace. Such a schema import must not bind a namespace prefix [ err:XQST0057 It is a static error err:XQST0058 Prolog static error err:XQST0059 static error err:XQST0035 http://www.w3.org/2001/XMLSchema xs in-scope schema types. It is a static error err:XQST0012 [XML Schema 1.0] [XML Schema 1.1] The following example imports a schema, specifying both its target namespace and its location, and binding the prefix soap import schema namespace soap="http://www.w3.org/2003/05/soap-envelope" at "http://www.w3.org/2003/05/soap-envelope/"; The following example imports a schema by specifying only its target namespace, and makes it the default element/type namespace: import schema default element namespace "http://example.org/abc"; The following example imports a schema that has no target namespace, providing a location hint, and sets the default element/type namespace to "no namespace" so that the definitions in the imported schema can be referenced: import schema default element namespace "" at "http://example.org/xyz.xsd"; The following example imports a schema that has no target namespace and sets the default element/type namespace to "no namespace". Since no location hint is provided, it is up to the implementation to find the schema to be imported. import schema default element namespace ""; ModuleImport ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral [ Definition module import public variable declarations and public function declarations library modules statically known in-scope variables module target namespace implementation-defined adding the (prefix, URI) pair to the statically known namespaces If a module A B A in-scope schema definitions statically known function signatures B A variable values named functions B B The following example illustrates a module import: import module namespace gis="http://example.org/gis-functions"; If a query imports the same module via multiple paths, only one instance of the module is imported. Because only one instance of a module is imported, there is only one instance of each variable declared in a module 's prolog A module may import its own target namespace (this is interpreted as importing an implementation-defined The namespace prefix specified in a module import must not be xml xmlns err:XQST0070 schema import namespace declaration module declaration err:XQST0033 The first URILiteral err:XQST0088 at implementation-defined It is a static error err:XQST0047 Prolog static error err:XQST0059 static error two or more variables declared or imported by a module expanded QNames eq err:XQST0049 Each module static context module import in-scope schema definitions statically known namespaces A module import does not import schema definitions from the imported module. In the following query, the type geometry:triangle is not defined, even if it is known in the imported module, so the variable declaration raises an error [ err:XPST0051 (: Error - geometry:triangle is not defined :) import module namespace geo = "http://example.org/geo-functions"; declare variable $t as geometry:triangle := geo:make-triangle();
$t Without the type declaration for the variable, the variable declaration succeeds: import module namespace geo = "http://example.org/geo-functions"; declare variable $t := geo:make-triangle();
$t Importing the schema that defines the type of the variable, the variable declaration succeeds: import schema namespace geometry = "http://example.org/geo-schema-declarations"; import module namespace geo = "http://example.org/geo-functions"; declare variable $t as geometry:triangle := geo:make-triangle();
$t The Target Namespace of a Module The target namespace of a module To maximize interoperability, query authors should use a string that is a valid absolute IRI. Implementions must accept any string of Unicode characters. target namespace Implementations may provide mechanisms allowing the target namespace Similarly, implementations may perform syntactic transformations on the target namespace target namespace target namespace As with other namespace URIs, it is common practice to use target namespace The specifications allow, and some users might consider it good practice, for the target namespace Target Namespace Several different modules with the same target namespace module contexts target namespace the in their module contexts If one module contains an "import module" declaration with the target namespace M in the contexts of target namespace M The term "location URIs" refers to the URIs in the "at" clause of an "import module" declaration. Products should (by default or at user option) take account of all the location URIs in an "import module" declaration, treating each location URI as a reference to a module with the specified target namespace When the same absolutized location URI is used more than once, either in the same "import module" declaration or in different "import module" declarations within the same query, a single copy of the resource containing the module is loaded. When different absolutized location URIs are used, each results in a single module being loaded, unless the implementation is able to determine that the different URIs are references to the same resource. No error due to duplicate variable or functions names should arise from the same module being imported more than once, so long as the absolute location URI is the same in each case. Implementations must report a static error if a location URI cannot be resolved after all available recovery strategies have been exhausted. Implementations must resolve cycles in the import graph, target namespace and ensure that each module is imported only once NamespaceDecl ::= "declare" "namespace" NCName URILiteral [ Definition namespace declaration statically known namespaces namespace declaration attribute direct element constructor If the URILiteral part of a namespace declaration is a zero-length string, any existing namespace binding for the given prefix is removed from the statically known namespaces local The following query illustrates a namespace declaration: declare namespace foo = "http://example.org"; <foo:bar> Lentils </foo:bar> In the query result, the newly created node is in the namespace associated with the namespace URI http://example.org The namespace prefix specified in a namespace declaration must not be xml xmlns err:XQST0070 http://www.w3.org/XML/1998/namespace http://www.w3.org/2000/xmlns/ err:XQST0070 module import schema import module declaration err:XQST0033 It is a static error err:XPST0081 lexical QName statically known namespaces XQuery has several predeclared namespace prefixes that are present in the statically known namespaces namespace declarations Prolog namespace declaration attributes xml xml err:XQST0070 xml = http://www.w3.org/XML/1998/namespace xs = http://www.w3.org/2001/XMLSchema xsi = http://www.w3.org/2001/XMLSchema-instance fn = http://www.w3.org/2005/xpath-functions local = http://www.w3.org/2005/xquery-local-functions 4.18 Function Declaration Additional predeclared namespace prefixes may be added to the statically known namespaces When element or attribute names are compared, they are considered identical if the local parts and namespace URIs match on a codepoint basis. Namespace prefixes need not be identical for two names to match, as illustrated by the following example: declare namespace xx = "http://example.org";
let $i := <foo:bar xmlns:foo = "http://example.org"> <foo:bing> Lentils </foo:bing> </foo:bar> return $i/xx:bing Although the namespace prefixes xx foo http://example.org xx:bing foo:bing <foo:bing xmlns:foo = "http://example.org"> Lentils </foo:bing> DefaultNamespaceDecl ::= "declare" "default" ("element" | "function") "namespace" URILiteral Default namespace declarations Prolog The namespace URI specified in a default namespace declaration must not be http://www.w3.org/XML/1998/namespace http://www.w3.org/2000/xmlns/ err:XQST0070 The following kinds of default namespace declarations are supported: A default element/type namespace declaration default element/type namespace static context Prolog err:XQST0066 URILiteral default element/type namespace absent DM30 declare default element namespace "http://example.org/names"; A default element/type namespace declaration may be overridden by a namespace declaration attribute direct element constructor If no default element/type namespace declaration is present, unprefixed element and type names are in no namespace (however, an implementation may define a different default as specified in C.1 Static Context Components A default function namespace declaration static default function namespace static context Prolog err:XQST0066 absent DM30 If no default function namespace declaration is present, the default function namespace is the namespace of XPath/XQuery functions, http://www.w3.org/2005/xpath-functions C.1 Static Context Components The following example illustrates the declaration of a default function namespace: declare default function namespace "http://www.w3.org/2005/xpath-functions/math"; The effect of declaring a default function namespace is that all functions in the default function namespace, including implicitly-declared constructor functions static constructor functions err:XPST0017 Note: Only constructor functions Unprefixed attribute names and variable names are in no namespace. AnnotatedDecl ::= "declare" Annotation VarDecl FunctionDecl InlineFunctionExpr ::= Annotation ParamList SequenceType FunctionBody Annotation ::= "%" EQName Literal Literal XQuery uses annotations to declare properties associated with functions (inline or declared in the prolog) %public or %private 4.18 Function Declaration Annotations are (QName, value) lexical QName the name is in the http://www.w3.org/2012/xquery Implementations may define further annotations, whose behaviour is implementation-defined. For instance, if the eg eg:sequential err:XQST0045 http://www.w3.org/XML/1998/namespace http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2005/xpath-functions http://www.w3.org/2005/xpath-functions/math http://www.w3.org/2012/xquery An annotation can provide values explicitly using a parenthesized list of literals %java:method("java.lang.Math.sin") java:method java.lang.Math.sin AnnotatedDecl ::= "declare" Annotation VarDecl FunctionDecl Annotation ::= "%" EQName Literal Literal VarDecl ::= "variable" "$" VarName TypeDeclaration VarValue VarDefaultValue VarName ::= EQName TypeDeclaration ::= "as" SequenceType VarValue ::= ExprSingle VarDefaultValue ::= ExprSingle A variable declaration static type in-scope variables variable values Note: A variable declaration variable binding During static analysis, a variable declaration causes a pair (expanded QName N, type T) in-scope variables VarName static error err:XQST0049 All variable names declared in a library module must (when expanded) be in the target namespace of the library module [ err:XQST0048 %private %public Definition private variable %private module import in-scope variables Definition public variable %private module import in-scope variables Using %public %private static error err:XQST0116 if a variable declaration contains both a %private %public %private %public Variable names that have no namespace prefix are in no namespace. Variable declarations that have no namespace prefix may appear only in a main module. Here are some examples of variable declarations: The following declaration specifies both the type and the value of a variable. This declaration causes the type xs:integer $x static context 7 $x dynamic context declare variable $x as xs:integer := 7; The following declaration specifies a value but not a type. The static type $x xs:decimal declare variable $x := 7.5; The following declaration specifies a type but not a value. The keyword external $x dynamic context xs:integer type error declare variable $x as xs:integer external; The following declaration specifies neither a type nor a value. It simply declares that the query depends on the existence of a variable named $x $x item()* dynamic context $x declare variable $x external; The following declaration, which might appear in a library module, declares a variable whose name includes a namespace prefix: declare variable $sasl:username as xs:string := "[email protected]"; This is an example of an external variable declaration that provides a VarDefaultValue declare variable $x as xs:integer external := 47; The syntax for variable declarations allows annotations, but XQuery 3.0 does not define annotations that apply to variable declarations. An implementation can provide annotations it needs. For instance, an implemenation that supports volatile external variables might allow them to be declared using an annotation: declare %eg:volatile variable $time as xs:time external; The type of the declared variable is as follows: If TypeDeclaration SequenceType TypeDeclaration If the Static Typing Feature is in effect and VarValue VarValue Note: Type inference might not be computable until after the check for circular dependencies, described below, is complete. Otherwise, item()* [ Definition VarValue VarDefaultValue initializing expression. In a module's dynamic context, a variable value (or the context item) may depend on Definition depends on In the following example, the value of variable $a depends on $b local:f() declare variable $a := local:f(); declare variable $b := 1; declare function local:f() { $b }; A directed graph can be built with all variable values and the context item as nodes, and with the depend on err:XQDY0054 During query evaluation, each variable declaration causes a pair (expanded QName N, value V) variable values VarName If VarValue VarValue If external if a value is provided for the variable by the external environment, then V is that value. The means by which typed values of external variables are provided by the external environment is implementation-defined. if no value is provided for the variable by the external environment, and VarDefaultValue VarDefaultValue If no value is provided for the variable by the external environment, and VarDefaultValue dynamic error err:XPDY0002 It is implementation-dependent whether this error is raised if the evaluation of the query does not reference the value of the variable. In all cases the value V must match the type T according to the rules for SequenceType matching; otherwise a type error err:XPTY0004 If VarValue VarDefaultValue the static and dynamic contexts for the evaluation are the current module's static and dynamic context. ContextItemDecl ::= "declare" "context" "item" ("as" ItemType VarValue VarDefaultValue A context item declaration allows a query to specify the static type initial context item Only the main module can set the value of the initial context item must be external, and VarValue VarDefaultValue err:XQST0113 In every module that does not contain a context item declaration, the effect is as if the declaration declare context item as item() external; appeared in that module. During static analysis, the context item declaration has the effect of setting the context item static type T ItemType item() If a module contains more than one context item declaration, a static error is raised [ err:XQST0099 The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog. During query evaluation, a singleton focus QueryBody If VarValue VarValue If external if a value is provided for the context item by the external environment, then that value. The means by which an external value is provided by the external environment is implementation-defined. if no value is provided for the context item by the external environment, and VarDefaultValue then the result of evaluating VarDefaultValue In all cases where the context item has a value, that value must match the type T err:XPTY0004 If VarValue VarDefaultValue Here are some examples of context item declarations. Declare the type of the context item: declare namespace env="http://www.w3.org/2003/05/soap-envelope"; declare context item as element(env:Envelope) external; Declare a default context item, which is a system log in a default location. If the system log is in a different location, it can be specified in the external environment: declare context item as element(sys:log) external := doc("/var/xlogs/sysevent.xml")/sys:log; In addition to the built-in functions described in [XQuery and XPath Functions and Operators 3.0] 2.5 Types statically known and the named functions module AnnotatedDecl ::= "declare" Annotation VarDecl FunctionDecl Annotation ::= "%" EQName Literal Literal FunctionDecl ::= "function" EQName ParamList SequenceType FunctionBody ParamList ::= Param Param Param ::= "$" EQName TypeDeclaration FunctionBody ::= EnclosedExpr TypeDeclaration ::= "as" SequenceType A function declaration specifies whether a function is user-defined external [ Definition User defined functions function body static context Prolog Its in-scope variables context item static type absent DM30 [ Definition External functions [XQuery and XPath Functions and Operators 3.0] external A function declaration may use the %private %public Definition private function %private module import statically known Definition public function without a %private module import statically known Using %public %private static error err:XQST0106 if a function declaration contains both a %private %public %private %public An XQuery implementation may provide a facility whereby external functions can be implemented using a host programming language, but it is not required to do so. If such a facility is provided, the protocols by which parameters are passed to an external function, and the result of the function is returned to the invoking query, are implementation-defined [XQuery and XPath Data Model (XDM) 3.0] xs:anyAtomicType An implementation can define annotations, in its own namespace, to support functionality beyond the scope of this specification. For instance, an implementation that supports external Java functions might use an annotation to associate a Java function with an XQuery external function: declare %java:method("java.lang.StrictMath.copySign") function smath:copySign($magnitude, $sign) external; Every declared err:XQST0060 default function namespace library module target namespace err:XQST0048 static error err:XQST0045 http://www.w3.org/XML/1998/namespace http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2005/xpath-functions http://www.w3.org/2005/xpath-functions/math http://www.w3.org/2012/xquery In order to allow main modules to declare functions for local use within the module without defining a new namespace, XQuery predefines the namespace prefix local http://www.w3.org/2005/xquery-local-functions If a function parameter is declared using a name but no type, its default type is item()* item()* The parameters of a function declaration are considered to be variables whose scope is the function body. It is an static error err:XQST0039 sequence type A FunctionDecl name EQName FunctionDecl statically known namespaces default function namespace parameter names EQName ParamList statically known namespaces signature FunctionTest SequenceType FunctionDecl ParamList Annotation FunctionDecl implementation FunctionDecl FunctionBody nonlocal variable bindings Empty. The following example illustrates the declaration and use of a local function that accepts a sequence of employee dept Using a function, prepare a summary of employees that are located in Denver. declare function local:summary($emps as element(employee)*) as element(dept)* { for $d in fn:distinct-values($emps/deptno) let $e := $emps[deptno = $d] return <dept> <deptno>{$d}</deptno> <headcount> {fn:count($e)} </headcount> <payroll> {fn:sum($e/salary)} </payroll> </dept> };
local:summary(fn:doc("acme_corp.xml")//employee[location = "Denver"]) A function declaration may be recursive—that is, it may reference itself. Mutually recursive functions, whose bodies reference each other, are also allowed. The following example declares a recursive function that computes the maximum depth of a node hierarchy, and calls the function to find the maximum depth of a particular document. The function local:depth empty max Find the maximum depth of the document named partlist.xml declare function local:depth($e as node()) as xs:integer { (: A node with no children has depth 1 :) (: Otherwise, add 1 to max depth of children :) if (fn:empty($e/*)) then 1 else fn:max(for $c in $e/* return local:depth($c)) + 1 };
local:depth(fn:doc("partlist.xml")) [ Definition option declaration OptionDecl ::= "declare" "option" EQName StringLiteral Typically, a particular option will be recognized by some implementations and not by others. The syntax is designed so that option declarations can be successfully parsed by all implementations. If the EQName of an option is a lexical QName statically known namespaces err:XPST0081 If the EQName of an option does not have a prefix, the expanded QName http://www.w3.org/2012/xquery , which is reserved for option declarations defined by the XQuery family of specifications XQuery does not currently define declaration options in this namespace. Each implementation recognizes the http://www.w3.org/2012/xquery implementation-defined and an implementation-defined set of option names defined in those namespaces Otherwise, the effect of the option declaration, including its error behavior, is implementation-defined Implementations may impose rules on where particular option declarations may appear relative to variable declarations and function declarations, and the interpretation of an option declaration may depend on its position. An option declaration must not be used to change the syntax accepted by the processor, or to suppress the detection of static errors implementation-defined The following examples illustrate several possible uses for option declarations: This option declaration might be used to specify how comments in source documents returned by the fn:doc() declare option exq:strip-comments "true"; This option declaration might be used to associate a namespace used in function names with a Java class: declare namespace smath = "http://example.org/MathLibrary"; declare option exq:java-class "smath = java.lang.StrictMath"; This section defines the conformance criteria for an XQuery processor. In this section, the following terms are used to indicate the requirement levels defined in [RFC 2119] Definition MUST Definition MUST NOT Definition MAY Definition SHOULD An XQuery processor that claims to conform to this specification MUST 5.1 Minimal Conformance MAY 5.2 Optional Features An implementation that claims Minimal Conformance MUST provide An implementation of everything 5.2 Optional Features MUST 5.2 Optional Features A definition of every item specified to be implementation-defined provided implementation-defined D Implementation-Defined Items Note: Implementations are not required to define items specified to be implementation-dependent An implementation of [XQuery and XPath Data Model (XDM) 3.0] 5.3 Data Model Conformance implementation-defined provided An implementation of [XQuery and XPath Functions and Operators 3.0] implementation-defined function or provided The features discussed in this section are optional. An implementation MAY The description of each feature mentions any errors that may occur if a query relies on a feature that is not present. [ Definition Schema Aware Feature schema import validate 3.18 Validate Expressions If an XQuery implementation does not provide MUST err:XQST0009 MUST err:XQST0075 validate If an implementation provides the Schema Aware Feature, it MUST 5.2.4 Typed Data Feature [ Definition Typed Data Feature xs:untyped xs:untypedAtomic If an XQuery implementation does not provide the Typed Data Feature, it MUST The XDM has the type xs:untyped xs:untypedAtomic Elements constructed by the query always have the type xs:untyped xs:untypedAtomic construction mode = strip [ Definition Static Typing Feature type errors static analysis phase If an implementation provide Static Typing Feature MUST If an implementation does not provide Static Typing Feature MAY MAY [ Definition The Module Feature Module Import library modules An provide MUST static error err:XQST0016 module declaration module import module declaration library module library module Note: In the absence of the Module Feature, each query consists of a single main module [ Definition The Serialization Feature 2.2.4 Serialization provide MUST 2.2.4 Serialization An implementation MAY The means by which serialization is invoked is implementation-defined If an error is raised during the serialization process as specified in [XSLT and XQuery Serialization 3.0] an MUST An provide MUST NOT output declaration MUST fn:serialize MAY fn:serialize Section 14.9.3 fn:serialize FO30 an provide MAY Note: Some implementations return query results without serialization. For instance, an implementation might provide results via an XML API or a binary representation such as a persistent DOM. [ Definition Higher Order Function Feature An implementation that does not provide the Higher-Order Function Feature MUST err:XQST0129 FunctionTest dynamic function call named function reference inline function expression partial function application MAY err:XPTY0004 If an implementation provides the Higher-Order Function Feature, then it must provide fn:function-lookup fn:function-name fn:function-arity fn:for-each fn:filter fn:fold-left fn:fold-right fn:for-each-pair static error err:XPST0017 All XQuery implementations process data represented in the data model [XQuery and XPath Data Model (XDM) 3.0] Support for normative construction from an infoset. An MAY Section 3.2 Construction from an Infoset DM30 XDM instance Support for normative construction from a PSVI. An MAY Section 3.3 Construction from a PSVI DM30 XDM instance Support for versions of XML and XSD. [XQuery and XPath Data Model (XDM) 3.0] Note: For suggestions on processing XML 1.1 documents with XSD 1.0 [XML 1.1 and Schema 1.0] Ranges of data values. implementation-defined For the xs:decimal totalDigits For the types xs:date xs:time xs:dateTime xs:gYear xs:gYearMonth For the xs:duration type For the xs:yearMonthDuration For the xs:dayTimeDuration For the types xs:string xs:hexBinary xs:base64Binary xs:QName xs:anyURI xs:NOTATION The limits listed above need not be fixed, but may depend on environmental factors such as system resources. For example, the length of a value of type xs:string Note: For discussion of errors due to implementation-dependent 2.3.1 Kinds of Errors Any syntactic extensions to XQuery are implementation-defined implementation-defined The grammar of XQuery 3.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] All named symbols have a name that begins with an uppercase letter. It adds a notation for referring to productions in external specs. Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols. A 'xgc:' prefix is an extra-grammatical constraint, the details of which are explained in A.1.2 Extra-grammatical Constraints A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.2.4 Whitespace Rules A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.2.1 Terminal Symbols The EBNF notation is described in more detail in A.1.1 Notation To increase readability, the EBNF in the main body of this document omits some of these notational features. This appendix is the normative version of the EBNF. Module ::= VersionDecl LibraryModule MainModule VersionDecl ::= "xquery" (("encoding" StringLiteral StringLiteral StringLiteral Separator MainModule ::= Prolog QueryBody LibraryModule ::= ModuleDecl Prolog ModuleDecl ::= "module" "namespace" NCName URILiteral Separator Prolog ::= (( DefaultNamespaceDecl Setter NamespaceDecl Import Separator ContextItemDecl AnnotatedDecl OptionDecl Separator Separator ::= ";" Setter ::= BoundarySpaceDecl DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl DecimalFormatDecl BoundarySpaceDecl ::= "declare" "boundary-space" ("preserve" | "strip") DefaultCollationDecl ::= "declare" "default" "collation" URILiteral BaseURIDecl ::= "declare" "base-uri" URILiteral ConstructionDecl ::= "declare" "construction" ("strip" | "preserve") OrderingModeDecl ::= "declare" "ordering" ("ordered" | "unordered") EmptyOrderDecl ::= "declare" "default" "order" "empty" ("greatest" | "least") CopyNamespacesDecl ::= "declare" "copy-namespaces" PreserveMode InheritMode PreserveMode ::= "preserve" | "no-preserve" InheritMode ::= "inherit" | "no-inherit" DecimalFormatDecl ::= "declare" (("decimal-format" EQName DFPropertyName StringLiteral DFPropertyName ::= "decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" Import ::= SchemaImport ModuleImport SchemaImport ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral SchemaPrefix ::= ("namespace" NCName ModuleImport ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral NamespaceDecl ::= "declare" "namespace" NCName URILiteral DefaultNamespaceDecl ::= "declare" "default" ("element" | "function") "namespace" URILiteral AnnotatedDecl ::= "declare" Annotation VarDecl FunctionDecl Annotation ::= "%" EQName Literal Literal VarDecl ::= "variable" "$" VarName TypeDeclaration VarValue VarDefaultValue VarValue ::= ExprSingle VarDefaultValue ::= ExprSingle ContextItemDecl ::= "declare" "context" "item" ("as" ItemType VarValue VarDefaultValue FunctionDecl ::= "function" EQName ParamList SequenceType FunctionBody /* xgc: reserved-function-names ParamList ::= Param Param Param ::= "$" EQName TypeDeclaration FunctionBody ::= EnclosedExpr EnclosedExpr ::= "{" Expr OptionDecl ::= "declare" "option" EQName StringLiteral QueryBody ::= Expr Expr ::= ExprSingle ExprSingle ExprSingle ::= FLWORExpr QuantifiedExpr SwitchExpr TypeswitchExpr IfExpr TryCatchExpr OrExpr FLWORExpr ::= InitialClause IntermediateClause ReturnClause InitialClause ::= ForClause LetClause WindowClause IntermediateClause ::= InitialClause WhereClause GroupByClause OrderByClause CountClause ForClause ::= "for" ForBinding ForBinding ForBinding ::= "$" VarName TypeDeclaration AllowingEmpty PositionalVar ExprSingle AllowingEmpty ::= "allowing" "empty" PositionalVar ::= "at" "$" VarName LetClause ::= "let" LetBinding LetBinding LetBinding ::= "$" VarName TypeDeclaration ExprSingle WindowClause ::= "for" ( TumblingWindowClause SlidingWindowClause TumblingWindowClause ::= "tumbling" "window" "$" VarName TypeDeclaration ExprSingle WindowStartCondition WindowEndCondition SlidingWindowClause ::= "sliding" "window" "$" VarName TypeDeclaration ExprSingle WindowStartCondition WindowEndCondition WindowStartCondition ::= "start" WindowVars ExprSingle WindowEndCondition ::= "only"? "end" WindowVars ExprSingle WindowVars ::= ("$" CurrentItem PositionalVar PreviousItem NextItem CurrentItem ::= EQName PreviousItem ::= EQName NextItem ::= EQName CountClause ::= "count" "$" VarName WhereClause ::= "where" ExprSingle GroupByClause ::= "group" "by" GroupingSpecList GroupingSpecList ::= GroupingSpec GroupingSpec GroupingSpec ::= GroupingVariable TypeDeclaration ExprSingle URILiteral GroupingVariable ::= "$" VarName OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList OrderSpecList ::= OrderSpec OrderSpec OrderSpec ::= ExprSingle OrderModifier OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral ReturnClause ::= "return" ExprSingle QuantifiedExpr ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle SwitchExpr ::= "switch" "(" Expr SwitchCaseClause ExprSingle SwitchCaseClause ::= ("case" SwitchCaseOperand ExprSingle SwitchCaseOperand ::= ExprSingle TypeswitchExpr ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle CaseClause ::= "case" ("$" VarName SequenceTypeUnion ExprSingle SequenceTypeUnion ::= SequenceType SequenceType IfExpr ::= "if" "(" Expr ExprSingle ExprSingle TryCatchExpr ::= TryClause CatchClause TryClause ::= "try" "{" TryTargetExpr TryTargetExpr ::= Expr CatchClause ::= "catch" CatchErrorList Expr CatchErrorList ::= NameTest NameTest OrExpr ::= AndExpr AndExpr AndExpr ::= ComparisonExpr ComparisonExpr ComparisonExpr ::= StringConcatExpr ValueComp GeneralComp NodeComp StringConcatExpr StringConcatExpr ::= RangeExpr RangeExpr RangeExpr ::= AdditiveExpr AdditiveExpr AdditiveExpr ::= MultiplicativeExpr MultiplicativeExpr MultiplicativeExpr ::= UnionExpr UnionExpr UnionExpr ::= IntersectExceptExpr IntersectExceptExpr IntersectExceptExpr ::= InstanceofExpr InstanceofExpr InstanceofExpr ::= TreatExpr SequenceType TreatExpr ::= CastableExpr SequenceType CastableExpr ::= CastExpr SingleType CastExpr ::= UnaryExpr SingleType UnaryExpr ::= ("-" | "+")* ValueExpr ValueExpr ::= ValidateExpr ExtensionExpr SimpleMapExpr GeneralComp ::= "=" | "!=" | "<" | "<=" | ">" | ">=" ValueComp ::= "eq" | "ne" | "lt" | "le" | "gt" | "ge" NodeComp ::= "is" | "<<" | ">>" ValidateExpr ::= "validate" ( ValidationMode TypeName Expr ValidationMode ::= "lax" | "strict" ExtensionExpr ::= Pragma Expr Pragma ::= "(#" S EQName S PragmaContents /* ws: explicit PragmaContents ::= ( Char SimpleMapExpr ::= PathExpr PathExpr PathExpr ::= ("/" RelativePathExpr RelativePathExpr RelativePathExpr /* xgc: leading-lone-slash RelativePathExpr ::= StepExpr StepExpr StepExpr ::= PostfixExpr AxisStep AxisStep ::= ( ReverseStep ForwardStep PredicateList ForwardStep ::= ( ForwardAxis NodeTest AbbrevForwardStep ForwardAxis ::= ("child" "::") AbbrevForwardStep ::= "@"? NodeTest ReverseStep ::= ( ReverseAxis NodeTest AbbrevReverseStep ReverseAxis ::= ("parent" "::") AbbrevReverseStep ::= ".." NodeTest ::= KindTest NameTest NameTest ::= EQName Wildcard Wildcard ::= "*" NCName NCName BracedURILiteral /* ws: explicit PostfixExpr ::= PrimaryExpr Predicate ArgumentList ArgumentList ::= "(" ( Argument Argument PredicateList ::= Predicate Predicate ::= "[" Expr PrimaryExpr ::= Literal VarRef ParenthesizedExpr ContextItemExpr FunctionCall OrderedExpr UnorderedExpr Constructor FunctionItemExpr Literal ::= NumericLiteral StringLiteral NumericLiteral ::= IntegerLiteral DecimalLiteral DoubleLiteral VarRef ::= "$" VarName VarName ::= EQName ParenthesizedExpr ::= "(" Expr ContextItemExpr ::= "." OrderedExpr ::= "ordered" "{" Expr UnorderedExpr ::= "unordered" "{" Expr FunctionCall ::= EQName ArgumentList /* xgc: reserved-function-names /* gn: parens Argument ::= ExprSingle ArgumentPlaceholder ArgumentPlaceholder ::= "?" Constructor ::= DirectConstructor ComputedConstructor DirectConstructor ::= DirElemConstructor DirCommentConstructor DirPIConstructor DirElemConstructor ::= "<" QName DirAttributeList DirElemContent QName S /* ws: explicit DirAttributeList ::= ( S QName S S DirAttributeValue /* ws: explicit DirAttributeValue ::= ('"' ( EscapeQuot QuotAttrValueContent EscapeApos AposAttrValueContent /* ws: explicit QuotAttrValueContent ::= QuotAttrContentChar CommonContent AposAttrValueContent ::= AposAttrContentChar CommonContent DirElemContent ::= DirectConstructor CDataSection CommonContent ElementContentChar CommonContent ::= PredefinedEntityRef CharRef EnclosedExpr DirCommentConstructor ::= "<!--" DirCommentContents /* ws: explicit DirCommentContents ::= (( Char Char /* ws: explicit DirPIConstructor ::= "<?" PITarget S DirPIContents /* ws: explicit DirPIContents ::= ( Char /* ws: explicit CDataSection ::= "<![CDATA[" CDataSectionContents /* ws: explicit CDataSectionContents ::= ( Char /* ws: explicit ComputedConstructor ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompNamespaceConstructor CompTextConstructor CompCommentConstructor CompPIConstructor CompDocConstructor ::= "document" "{" Expr CompElemConstructor ::= "element" ( EQName Expr ContentExpr ContentExpr ::= Expr CompAttrConstructor ::= "attribute" ( EQName Expr Expr CompNamespaceConstructor ::= "namespace" ( Prefix PrefixExpr URIExpr Prefix ::= NCName PrefixExpr ::= Expr URIExpr ::= Expr CompTextConstructor ::= "text" "{" Expr CompCommentConstructor ::= "comment" "{" Expr CompPIConstructor ::= "processing-instruction" ( NCName Expr Expr FunctionItemExpr ::= NamedFunctionRef InlineFunctionExpr NamedFunctionRef ::= EQName IntegerLiteral /* xgc: reserved-function-names InlineFunctionExpr ::= Annotation ParamList SequenceType FunctionBody SingleType ::= SimpleTypeName TypeDeclaration ::= "as" SequenceType SequenceType ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator OccurrenceIndicator ::= "?" | "*" | "+" /* xgc: occurrence-indicators ItemType ::= KindTest FunctionTest AtomicOrUnionType ParenthesizedItemType AtomicOrUnionType ::= EQName KindTest ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest NamespaceNodeTest AnyKindTest AnyKindTest ::= "node" "(" ")" DocumentTest ::= "document-node" "(" ( ElementTest SchemaElementTest TextTest ::= "text" "(" ")" CommentTest ::= "comment" "(" ")" NamespaceNodeTest ::= "namespace-node" "(" ")" PITest ::= "processing-instruction" "(" ( NCName StringLiteral AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName AttribNameOrWildcard ::= AttributeName SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration AttributeDeclaration ::= AttributeName ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName ElementNameOrWildcard ::= ElementName SchemaElementTest ::= "schema-element" "(" ElementDeclaration ElementDeclaration ::= ElementName AttributeName ::= EQName ElementName ::= EQName SimpleTypeName ::= TypeName TypeName ::= EQName FunctionTest ::= Annotation AnyFunctionTest TypedFunctionTest AnyFunctionTest ::= "function" "(" "*" ")" TypedFunctionTest ::= "function" "(" ( SequenceType SequenceType SequenceType ParenthesizedItemType ::= "(" ItemType URILiteral ::= StringLiteral EQName ::= QName URIQualifiedName The following definitions will be helpful in defining precisely this exposition. [ Definition symbol symbol ::= expression ] [ Definition terminal [a-zA-Z] matches any Char [abc] matches any Char [^abc] matches any Char "string" matches the sequence of characters that appear inside the double quotes. 'string' matches the sequence of characters that appear inside the single quotes. [http://www.w3.org/TR/REC-example/#NT-Example] matches any string matched by the production defined in the external specification as per the provided reference. Patterns (including the above constructs) can be combined with grammatical operators to form more complex patterns, matching more complex sets of character strings. In the examples that follow, A and B represent (sub-)patterns. (A) A A? matches A A A B matches A B A B | C D (A B) | (C D) A | B matches A B A - B matches any string that matches A B A+ matches one or more occurrences of A A+ | B+ (A+) | (B+) A* matches zero or more occurrences of A A* | B* (A*) | (B*) This section contains constraints on the EBNF productions, which are required to parse syntactically valid sentences. The notes below are referenced from the right side of the production, with the notation: /* xgc: <id> */ Constraint: leading-lone-slash A single slash may appear either as a complete path expression or as the first part of a path expression in which it is followed by a RelativePathExpr * union NameTest , and the < DirectConstructor / * 5 / * / Therefore to reduce the need for lookahead, if the token immediately following a slash can form the start of a RelativePathExpr PathExpr A single slash may be used as the left-hand argument of an operator by parenthesizing it: (/) * 5 5 * / Constraint: xml-version The version of XML and XML Names (e.g. [XML 1.0] [XML Names] [XML 1.1] [XML Names 1.1] implementation-defined A.2.4.1 Default Whitespace Handling prefix : localname lexical QName XML 1.0 and XML 1.1 differ in their handling of C0 control characters (specifically #x1 through #x1F, excluding #x9, #xA, and #xD) and C1 control characters (#x7F through #x9F). In XML 1.0, these C0 characters are prohibited, and the C1 characters are permitted. In XML 1.1, both sets of control characters are permitted, but only if written as character references. It is RECOMMENDED that implementations should follow the XML 1.1 rules in this respect; however, for backwards compatibility with XQuery 1.0 Note: Direct use of C1 control characters often suggests a character encoding error, such as using encoding CP-1252 and mislabeling it as iso-8859-1. Constraint: reserved-function-names Unprefixed function names spelled the same way as language keywords could make the language harder to recognize. For instance, if(foo) FunctionCall IfExpr A.3 Reserved Function Names A function named "if" can be called by binding its namespace to a prefix and using the prefixed form: "library:if(foo)" instead of "if(foo)". Constraint: occurrence-indicators As written, the grammar in A XQuery 3.0 Grammar SequenceType ItemType SequenceType Thus, 4 treat as item() + - 5 (4 treat as item()+) - 5 (4 treat as item()) + -5 SequenceType function () as xs:string * function () as (xs:string *) (function () as xs:string) * This rule has as a consequence that certain forms which would otherwise be syntactically valid and unambiguous are not recognized: in "4 treat as item() + 5", the "+" is taken as an OccurrenceIndicator This section contains general notes on the EBNF productions, which may be helpful in understanding how to interpret and implement the EBNF. These notes are not normative. The notes below are referenced from the right side of the production, with the notation: /* gn: <id> */ Note: Look-ahead is required to distinguish FunctionCall Pragma Comment address (: this may be empty :) for (: whom the bell :) $tolls in 3 return $tolls Comments are allowed everywhere that ignorable whitespace Comment A.2.4.1 Default Whitespace Handling Note that comments are not allowed in direct constructor content, though they are allowed in nested EnclosedExprs A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment. Note: Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero. Some illustrative examples: (: commenting out a (: comment :) may be confusing, but often helpful :) "this is just a string :)" (: "this is just a string :)" :) "this is another string (:" (: "this is another string (:" :) for (: set up loop :) $i in $x return $i 5 instance (: strange place for a comment :) of xs:integer <eg (: an example:)>{$i//title}</eg> <eg> (: an example:) </eg> The terminal symbols assumed by the grammar above are described in this section. Quoted strings appearing in production rules are terminal symbols. Other terminal symbols are defined in A.2.1 Terminal Symbols Some productions are defined by reference to the XML and XML Names specifications (e.g. [XML 1.0] [XML Names] [XML 1.1] [XML Names 1.1] It is implementation-defined When tokenizing, the longest possible match that is consistent with the EBNF All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName A.3 Reserved Function Names IntegerLiteral ::= Digits DecimalLiteral ::= ("." Digits Digits /* ws: explicit DoubleLiteral ::= (("." Digits Digits Digits /* ws: explicit StringLiteral ::= ('"' ( PredefinedEntityRef CharRef EscapeQuot PredefinedEntityRef CharRef EscapeApos /* ws: explicit URIQualifiedName ::= BracedURILiteral NCName /* ws: explicit BracedURILiteral ::= "Q" "{" ( PredefinedEntityRef CharRef /* ws: explicit PredefinedEntityRef ::= "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";" /* ws: explicit EscapeQuot ::= '""' EscapeApos ::= "''" ElementContentChar ::= ( Char QuotAttrContentChar ::= ( Char AposAttrContentChar ::= ( Char Comment ::= "(:" ( CommentContents Comment /* ws: explicit /* gn: comments PITarget ::= [http://www.w3.org/TR/REC-xml#NT-PITarget] XML /* xgc: xml-version CharRef ::= [http://www.w3.org/TR/REC-xml#NT-CharRef] XML /* xgc: xml-version QName ::= [http://www.w3.org/TR/REC-xml-names/#NT-QName] Names /* xgc: xml-version NCName ::= [http://www.w3.org/TR/REC-xml-names/#NT-NCName] Names /* xgc: xml-version S ::= [http://www.w3.org/TR/REC-xml#NT-S] XML /* xgc: xml-version Char ::= [http://www.w3.org/TR/REC-xml#NT-Char] XML /* xgc: xml-version The following symbols are used only in the definition of terminal symbols; they are not terminal symbols in the grammar of A.1 EBNF Digits ::= [0-9]+ CommentContents ::= ( Char XQuery 3.0 expressions consist of terminal symbols symbol separators Terminal symbols that are not used exclusively in /* ws: explicit */ [ Definition delimiting terminal symbols S StringLiteral BracedURILiteral [ Definition non-delimiting terminal symbols IntegerLiteral URIQualifiedName NCName DecimalLiteral DoubleLiteral QName [ Definition Whitespace Comments symbol separators /* ws: explicit */ /* xgc: xml-version */ It is customary to separate consecutive terminal symbols by whitespace Comments symbol separator Prior to parsing, the XQuery 3.0 processor must normalize all line breaks. The rules for line breaking follow the rules of [XML 1.0] [XML 1.1] For [XML 1.0] the two-character sequence #xD #xA any #xD character that is not immediately followed by #xA. For [XML 1.1] the two-character sequence #xD #xA the two-character sequence #xD #x85 the single character #x85 the single character #x2028 any #xD character that is not immediately followed by #xA or #x85. The characters #x85 and #x2028 cannot be reliably recognized and translated until the VersionDecl [ Definition whitespace [http://www.w3.org/TR/REC-xml/#NT-S] [ Definition Ignorable whitespace whitespace terminals ws:explicit A.2.4.2 Explicit Whitespace Handling of a module terminals Comments foo- foo foo -foo foo - foo foo(: This is a comment :)- foo foo - foo foo-foo 10div 3 10 div3 10div3 Explicit whitespace notation is specified with the EBNF productions, when it is different from the default rules, using the notation shown below. This notation is not inherited. In other words, if an EBNF rule is marked as /* ws: explicit */, the notation does not automatically apply to all the 'child' EBNF productions of that rule. /* ws: explicit */ means that the EBNF notation explicitly notates, with S whitespace characters A.2.4.1 Default Whitespace Handling Comments For example, whitespace is not freely allowed by the direct constructor productions, but is specified explicitly in the grammar, in order to be more consistent with XML. The following names are not allowed as function names in an unprefixed form because expression syntax takes precedence. attribute comment document-node element empty-sequence function if item namespace-node node processing-instruction schema-attribute schema-element switch text typeswitch The grammar in A.1 EBNF # Operator Associativity 1 , (comma) either 2 FLWOR some, every switch typeswitch try if NA 3 or either 4 and either 5 eq, ne, lt, le, gt, ge =, !=, <, <=, >, >= is, <<, >> NA 6 || left-to-right 7 to NA 8 +, - (binary) left-to-right 9 *, div, idiv, mod left-to-right 10 union, | either 11 intersect, except left-to-right 12 instance of NA 13 treat as NA 14 castable as NA 15 cast as NA 16 -, + (unary) right-to-left 17 ! left-to-right 18 /, // left-to-right 19 [ ] left-to-right In the "Associativity" column, "either" indicates that all the operators at that level have the associative property (i.e., (A op B) op C A op (B op C) Note: Parentheses can be used to override the operator precedence in the usual way. Square brackets in an expression such as A[B] serve two roles: they act as an operator causing B to be evaluated once for each item in the value of A, and they act as parentheses enclosing the expression B. Curly braces in an expression such as validate{E} or ordered{E} perform a similar bracketing role to the parentheses in a function call, but with the difference in most cases that E is an Expr rather than ExprSingle, meaning that it can use the comma operator. [ Definition Type promotion 3.1.5.1 Evaluating Static and Dynamic Function Calls , order by 3.10.8 Order By Clause B.2 Operator Mapping Numeric type promotion: A value of type xs:float xs:float xs:double xs:double A value of type xs:decimal xs:decimal xs:float xs:double URI type promotion: A value of type xs:anyURI xs:anyURI xs:string xs:string Note: Since xs:anyURI xs:string default collation xs:anyURI default collation xs:anyURI Note that type promotion subtype substitution A function that expects a parameter $p xs:float xs:decimal type promotion $p instance of xs:decimal false A function that expects a parameter $p xs:decimal xs:integer subtype substitution $p instance of xs:integer true The operator mapping tables in this section list the combinations of types for which the various operators of XQuery 3.0 are defined. [ Definition operator function [XQuery and XPath Functions and Operators 3.0] [XQuery and XPath Functions and Operators 3.0] The and or If an operator in the operator mapping tables expects an operand of type ET AT AT ET type promotion subtype substitution gt xs:date xs:boolean gt xs:date xs:boolean [ Definition numeric xs:integer xs:decimal xs:float xs:double numeric + Operator First operand type Second operand type Result type + xs:integer xs:integer xs:integer + xs:decimal xs:decimal xs:decimal + xs:float xs:float xs:float + xs:double xs:double xs:double A numeric operator may be validly applied to an operand of type AT AT type promotion subtype substitution (xs:integer, xs:decimal, xs:float, xs:double) subtype substitution type promotion hatsize xs:integer shoesize xs:float + hatsize shoesize xs:float + hatsize xs:integer [ Definition Gregorian xs:gYearMonth xs:gYear xs:gMonthDay xs:gDay xs:gMonth xs:gDay xs:gDay Binary Operators Operator Type(A) Type(B) Function Result type A + B numeric numeric op:numeric-add(A, B) numeric A + B xs:date xs:yearMonthDuration op:add-yearMonthDuration-to-date(A, B) xs:date A + B xs:yearMonthDuration xs:date op:add-yearMonthDuration-to-date(B, A) xs:date A + B xs:date xs:dayTimeDuration op:add-dayTimeDuration-to-date(A, B) xs:date A + B xs:dayTimeDuration xs:date op:add-dayTimeDuration-to-date(B, A) xs:date A + B xs:time xs:dayTimeDuration op:add-dayTimeDuration-to-time(A, B) xs:time A + B xs:dayTimeDuration xs:time op:add-dayTimeDuration-to-time(B, A) xs:time A + B xs:dateTime xs:yearMonthDuration op:add-yearMonthDuration-to-dateTime(A, B) xs:dateTime A + B xs:yearMonthDuration xs:dateTime op:add-yearMonthDuration-to-dateTime(B, A) xs:dateTime A + B xs:dateTime xs:dayTimeDuration op:add-dayTimeDuration-to-dateTime(A, B) xs:dateTime A + B xs:dayTimeDuration xs:dateTime op:add-dayTimeDuration-to-dateTime(B, A) xs:dateTime A + B xs:yearMonthDuration xs:yearMonthDuration op:add-yearMonthDurations(A, B) xs:yearMonthDuration A + B xs:dayTimeDuration xs:dayTimeDuration op:add-dayTimeDurations(A, B) xs:dayTimeDuration A - B numeric numeric op:numeric-subtract(A, B) numeric A - B xs:date xs:date op:subtract-dates(A, B) xs:dayTimeDuration A - B xs:date xs:yearMonthDuration op:subtract-yearMonthDuration-from-date(A, B) xs:date A - B xs:date xs:dayTimeDuration op:subtract-dayTimeDuration-from-date(A, B) xs:date A - B xs:time xs:time op:subtract-times(A, B) xs:dayTimeDuration A - B xs:time xs:dayTimeDuration op:subtract-dayTimeDuration-from-time(A, B) xs:time A - B xs:dateTime xs:dateTime op:subtract-dateTimes(A, B) xs:dayTimeDuration A - B xs:dateTime xs:yearMonthDuration op:subtract-yearMonthDuration-from-dateTime(A, B) xs:dateTime A - B xs:dateTime xs:dayTimeDuration op:subtract-dayTimeDuration-from-dateTime(A, B) xs:dateTime A - B xs:yearMonthDuration xs:yearMonthDuration op:subtract-yearMonthDurations(A, B) xs:yearMonthDuration A - B xs:dayTimeDuration xs:dayTimeDuration op:subtract-dayTimeDurations(A, B) xs:dayTimeDuration A * B numeric numeric op:numeric-multiply(A, B) numeric A * B xs:yearMonthDuration numeric op:multiply-yearMonthDuration(A, B) xs:yearMonthDuration A * B numeric xs:yearMonthDuration op:multiply-yearMonthDuration(B, A) xs:yearMonthDuration A * B xs:dayTimeDuration numeric op:multiply-dayTimeDuration(A, B) xs:dayTimeDuration A * B numeric xs:dayTimeDuration op:multiply-dayTimeDuration(B, A) xs:dayTimeDuration A idiv B numeric numeric op:numeric-integer-divide(A, B) xs:integer A div B numeric numeric op:numeric-divide(A, B) numeric; but xs:decimal if both operands are xs:integer A div B xs:yearMonthDuration numeric op:divide-yearMonthDuration(A, B) xs:yearMonthDuration A div B xs:dayTimeDuration numeric op:divide-dayTimeDuration(A, B) xs:dayTimeDuration A div B xs:yearMonthDuration xs:yearMonthDuration op:divide-yearMonthDuration-by-yearMonthDuration (A, B) xs:decimal A div B xs:dayTimeDuration xs:dayTimeDuration op:divide-dayTimeDuration-by-dayTimeDuration (A, B) xs:decimal A mod B numeric numeric op:numeric-mod(A, B) numeric A eq B numeric numeric op:numeric-equal(A, B) xs:boolean A eq B xs:boolean xs:boolean op:boolean-equal(A, B) xs:boolean A eq B xs:string xs:string op:numeric-equal(fn:compare(A, B), 0) xs:boolean A eq B xs:date xs:date op:date-equal(A, B) xs:boolean A eq B xs:time xs:time op:time-equal(A, B) xs:boolean A eq B xs:dateTime xs:dateTime op:dateTime-equal(A, B) xs:boolean A eq B xs:duration xs:duration op:duration-equal(A, B) xs:boolean A eq B Gregorian Gregorian op:gYear-equal(A, B) etc. xs:boolean A eq B xs:hexBinary xs:hexBinary op:hexBinary-equal(A, B) xs:boolean A eq B xs:base64Binary xs:base64Binary op:base64Binary-equal(A, B) xs:boolean A eq B xs:anyURI xs:anyURI op:numeric-equal(fn:compare(A, B), 0) xs:boolean A eq B xs:QName xs:QName op:QName-equal(A, B) xs:boolean A eq B xs:NOTATION xs:NOTATION op:NOTATION-equal(A, B) xs:boolean A ne B numeric numeric fn:not(op:numeric-equal(A, B)) xs:boolean A ne B xs:boolean xs:boolean fn:not(op:boolean-equal(A, B)) xs:boolean A ne B xs:string xs:string fn:not(op:numeric-equal(fn:compare(A, B), 0)) xs:boolean A ne B xs:date xs:date fn:not(op:date-equal(A, B)) xs:boolean A ne B xs:time xs:time fn:not(op:time-equal(A, B)) xs:boolean A ne B xs:dateTime xs:dateTime fn:not(op:dateTime-equal(A, B)) xs:boolean A ne B xs:duration xs:duration fn:not(op:duration-equal(A, B)) xs:boolean A ne B Gregorian Gregorian fn:not(op:gYear-equal(A, B)) etc. xs:boolean A ne B xs:hexBinary xs:hexBinary fn:not(op:hexBinary-equal(A, B)) xs:boolean A ne B xs:base64Binary xs:base64Binary fn:not(op:base64Binary-equal(A, B)) xs:boolean A ne B xs:anyURI xs:anyURI fn:not(op:numeric-equal(fn:compare(A, B), 0)) xs:boolean A ne B xs:QName xs:QName fn:not(op:QName-equal(A, B)) xs:boolean A ne B xs:NOTATION xs:NOTATION fn:not(op:NOTATION-equal(A, B)) xs:boolean A gt B numeric numeric op:numeric-greater-than(A, B) xs:boolean A gt B xs:boolean xs:boolean op:boolean-greater-than(A, B) xs:boolean A gt B xs:string xs:string op:numeric-greater-than(fn:compare(A, B), 0) xs:boolean A gt B xs:date xs:date op:date-greater-than(A, B) xs:boolean A gt B xs:time xs:time op:time-greater-than(A, B) xs:boolean A gt B xs:dateTime xs:dateTime op:dateTime-greater-than(A, B) xs:boolean A gt B xs:yearMonthDuration xs:yearMonthDuration op:yearMonthDuration-greater-than(A, B) xs:boolean A gt B xs:dayTimeDuration xs:dayTimeDuration op:dayTimeDuration-greater-than(A, B) xs:boolean A gt B xs:anyURI xs:anyURI op:numeric-greater-than(fn:compare(A, B), 0) xs:boolean A lt B numeric numeric op:numeric-less-than(A, B) xs:boolean A lt B xs:boolean xs:boolean op:boolean-less-than(A, B) xs:boolean A lt B xs:string xs:string op:numeric-less-than(fn:compare(A, B), 0) xs:boolean A lt B xs:date xs:date op:date-less-than(A, B) xs:boolean A lt B xs:time xs:time op:time-less-than(A, B) xs:boolean A lt B xs:dateTime xs:dateTime op:dateTime-less-than(A, B) xs:boolean A lt B xs:yearMonthDuration xs:yearMonthDuration op:yearMonthDuration-less-than(A, B) xs:boolean A lt B xs:dayTimeDuration xs:dayTimeDuration op:dayTimeDuration-less-than(A, B) xs:boolean A lt B xs:anyURI xs:anyURI op:numeric-less-than(fn:compare(A, B), 0) xs:boolean A ge B numeric numeric op:numeric-greater-than(A, B) or op:numeric-equal(A, B) xs:boolean A ge B xs:boolean xs:boolean fn:not(op:boolean-less-than(A, B)) xs:boolean A ge B xs:string xs:string op:numeric-greater-than(fn:compare(A, B), -1) xs:boolean A ge B xs:date xs:date fn:not(op:date-less-than(A, B)) xs:boolean A ge B xs:time xs:time fn:not(op:time-less-than(A, B)) xs:boolean A ge B xs:dateTime xs:dateTime fn:not(op:dateTime-less-than(A, B)) xs:boolean A ge B xs:yearMonthDuration xs:yearMonthDuration fn:not(op:yearMonthDuration-less-than(A, B)) xs:boolean A ge B xs:dayTimeDuration xs:dayTimeDuration fn:not(op:dayTimeDuration-less-than(A, B)) xs:boolean A ge B xs:anyURI xs:anyURI op:numeric-greater-than(fn:compare(A, B), -1) xs:boolean A le B numeric numeric op:numeric-less-than(A, B) or op:numeric-equal(A, B) xs:boolean A le B xs:boolean xs:boolean fn:not(op:boolean-greater-than(A, B)) xs:boolean A le B xs:string xs:string op:numeric-less-than(fn:compare(A, B), 1) xs:boolean A le B xs:date xs:date fn:not(op:date-greater-than(A, B)) xs:boolean A le B xs:time xs:time fn:not(op:time-greater-than(A, B)) xs:boolean A le B xs:dateTime xs:dateTime fn:not(op:dateTime-greater-than(A, B)) xs:boolean A le B xs:yearMonthDuration xs:yearMonthDuration fn:not(op:yearMonthDuration-greater-than(A, B)) xs:boolean A le B xs:dayTimeDuration xs:dayTimeDuration fn:not(op:dayTimeDuration-greater-than(A, B)) xs:boolean A le B xs:anyURI xs:anyURI op:numeric-less-than(fn:compare(A, B), 1) xs:boolean A is B node() node() op:is-same-node(A, B) xs:boolean A << B node() node() op:node-before(A, B) xs:boolean A >> B node() node() op:node-after(A, B) xs:boolean A union B node()* node()* op:union(A, B) node()* A | B node()* node()* op:union(A, B) node()* A intersect B node()* node()* op:intersect(A, B) node()* A except B node()* node()* op:except(A, B) node()* A to B xs:integer xs:integer op:to(A, B) xs:integer* A , B item()* item()* op:concatenate(A, B) item()* A || B xs:anyAtomicType xs:anyAtomicType fn:concat(A, B) xs:string Unary Operators Operator Operand type Function Result type + A numeric op:numeric-unary-plus(A) numeric - A numeric op:numeric-unary-minus(A) numeric The tables in this section describe how values are assigned to the various components of the static context and dynamic context, and to the parameters that control the serialization process. The following table describes the components of the static context Default initial value: Can be overwritten or augmented by implementation: implementation-defined implementation-defined Can be overwritten or augmented by prolog: Can be overwritten or augmented by expressions: Consistency Rules: 2.2.5 Consistency Constraints Static Context Components Component Default initial value Can be overwritten or augmented by implementation? Can be overwritten or augmented by prolog? Can be overwritten or augmented by expressions? Consistency rules Statically known namespaces fn xml xs xsi local overwriteable and augmentable (except for xml overwriteable and augmentable by 4.13 Namespace Declaration overwriteable and augmentable by element constructor Only one namespace can be assigned to a given prefix per lexical scope. Default element/type namespace no namespace overwriteable overwriteable by 4.14 Default Namespace Declaration overwriteable by element constructor Only one default namespace per lexical scope. In-scope variables none augmentable overwriteable and augmentable by 4.16 Variable Declaration 3.1.7 Inline Function Expressions 4.12 Module Import overwriteable and augmentable by variable-binding expressions Only one definition per variable per lexical scope. Context item static type item() overwriteable overwriteable by 4.17 Context Item Declaration overwriteable by expresssions that set the context item None. Ordering mode ordered overwriteable overwriteable by 4.7 Ordering Mode Declaration overwriteable by expression Value must be ordered unordered Default function namespace fn overwriteable (not recommended) overwriteable by 4.14 Default Namespace Declaration no None. In-scope schema types built-in types in xs augmentable augmentable by 4.11 Schema Import no Only one definition per global or local type. In-scope element declarations none augmentable augmentable by 4.11 Schema Import no Only one definition per global or local element name. In-scope attribute declarations none augmentable augmentable by 4.11 Schema Import no Only one definition per global or local attribute name. Statically known functions in fn generalized atomic types augmentable augmentable by 4.12 Module Import 4.18 Function Declaration 4.11 Schema Import no Each function must have a unique expanded QName Default collation Unicode codepoint collation overwriteable overwriteable by 4.4 Default Collation Declaration no None. Construction mode preserve overwriteable overwriteable by 4.6 Construction Declaration no Value must be preserve strip Default order for empty sequences implementation-defined overwriteable overwriteable by 4.8 Empty Order Declaration no Value must be greatest least Boundary-space policy strip overwriteable overwriteable by 4.3 Boundary-space Declaration no Value must be preserve strip Copy-namespaces mode inherit, preserve overwriteable overwriteable by 4.9 Copy-Namespaces Declaration no Value consists of inherit no-inherit preserve no-preserve Static Base URI See rules in 4.5 Base URI Declaration overwriteable overwriteable by 4.5 Base URI Declaration no Value must be a valid lexical representation of the type xs:anyURI. Statically known decimal formats the default (unnamed) decimal format, which has an implementation-dependent value augmentable augmentable, using decimal format declarations no each QName uniquely identifies a decimal format Statically known documents none augmentable no no None. Statically known collections none augmentable no no None. Statically known default collection type node()* overwriteable no no None. Statically known collations only the default collation augmentable no no Each URI uniquely identifies a collation. XPath 1.0 Compatibility Mode false no no no Must be false Serialization Parameters byte-order-mark implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 cdata-section-elements empty overwriteable and augmentable overwriteable by prolog no Section 3 Serialization Parameters SER30 doctype-public none overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 doctype-system none overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 encoding implementation-defined choice between "utf-8" and "utf-16" overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 escape-uri-attributes (not applicable when method = xml) overwriteable and augmentable overwriteable by prolog no Section 3 Serialization Parameters SER30 html-version implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 include-content-type (not applicable when method = xml) overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 indent no overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 item-separator implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 media-type implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 method xml overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 normalization-form implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 omit-xml-declaration implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 standalone implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 suppress-indentation empty overwriteable and augmentable overwriteable by prolog no Section 3 Serialization Parameters SER30 undeclare-prefixes no overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 use-character-maps empty overwriteable and augmentable overwriteable by prolog no Section 3 Serialization Parameters SER30 version implementation-defined overwriteable overwriteable by prolog no Section 3 Serialization Parameters SER30 The following table describes the components of the dynamic context Default initial value: Can be overwritten or augmented by implementation: implementation-defined implementation-defined Can be overwritten or augmented by prolog: Can be overwritten or augmented by expressions: Consistency Rules: 2.2.5 Consistency Constraints Dynamic Context Components Component Default initial value Can be overwritten or augmented by implementation? Can be overwritten or augmented by prolog? Can be overwritten or augmented by expressions? Consistency rules Context item the initial context item overwriteable no, but the initial context item 4.17 Context Item Declaration overwritten during evaluation of path expressions and predicates The query body and the prolog of every module in a query share the same initial context item Context position 1 if the initial context item overwriteable no overwritten during evaluation of path expressions and predicates If context item is defined, context position must be >0 and <= context size; else context position is absent DM30 Context size 1 if the initial context item overwriteable no overwritten during evaluation of path expressions and predicates If context item is defined, context size must be >0; else context size is absent DM30 Variable values none augmentable overwriteable and augmentable by 4.16 Variable Declaration 3.1.7 Inline Function Expressions 4.12 Module Import overwriteable and augmentable by variable-binding expressions Names and values must be consistent with in-scope variables. Named functions functions in fn generalized atomic types augmentable augmentable by 4.18 Function Declaration 4.12 Module Import 4.11 Schema Import no Must be consistent with statically known Current dateTime none must be initialized by implementation no no Must include a timezone. Remains constant during evaluation of a query. Implicit timezone none must be initialized by implementation no no Remains constant during evaluation of a query. Available documents none must be initialized by implementation no no None Available text resources none must be initialized by implementation no no None Available node collections none must be initialized by implementation no no None Default node collection none overwriteable no no None Available resource collections none must be initialized by implementation no no None Default resource collection none overwriteable no no None The following items in this specification are implementation-defined The version of Unicode that is used to construct expressions. The statically-known collations The implicit timezone The circumstances in which warnings The method by which errors are reported to the external processing environment. Which version of XML and XML Names (e.g. [XML 1.0] [XML Names] [XML 1.1] [XML Names 1.1] [XML Schema 1.0] [XML Schema 1.1] How XDM instances are created from sources other than an Infoset or PSVI. Any components of the static context dynamic context The default handling of empty sequences returned by an ordering key (orderspec) in an order by empty least empty greatest The names and semantics of any extension expressions pragmas The names and semantics of any option declarations Protocols (if any) by which parameters can be passed to an external function, and the result of the function can returned to the invoking query. The process by which the specific modules to be imported by a module import Module Feature The means by which serialization is invoked, if the Serialization Feature The default values for the byte-order-mark encoding media-type normalization-form omit-xml-declaration standalone version Serialization Feature The result of an unsuccessful call to an external function (for example, if the function implementation cannot be found or does not return a value of the declared type). Limits on ranges of values for various data types, as enumerated in 5.3 Data Model Conformance Syntactic extensions to XQuery, including both their syntax and semantics, as discussed in 5.4 Syntax Extensions Whether the type system is based on [XML Schema 1.0] [XML Schema 1.1] The signatures of functions provided by the implementation or via an implementation-defined API (see 2.1.1 Static Context Any environment variables Any rules used for static typing (see 2.2.3.1 Static Analysis Phase Any serialization parameters provided by the implementation (see 2.2.4 Serialization The means by which the location hint for a serialization parameter document identifies the corresponding XDM instance (see 2.2.4 Serialization What error, if any, is returned if an external function's implementation does not return the declared result type (see 2.2.5 Consistency Constraints Any annotations defined by the implementation, and their associated behavior (see 4.15 Annotations Any function asertions The effect of function assertions understood by the implementation on 2.5.6.3 The judgement subtype-assertions(AnnotationsA, AnnotationsB) Any implementation-defined variables defined by the implementation. (see 3.1.2 Variable References The ordering associated with fn:unordered 3.11 Ordered and Unordered Expressions Any additional information provided for try/catch via the err:additional 3.15 Try/Catch Expressions The default boundary-space policy (see 4.3 Boundary-space Declaration The default collation (see 4.4 Default Collation Declaration The default base URI (see 4.5 Base URI Declaration Note: Additional implementation-defined [XQuery and XPath Data Model (XDM) 3.0] [XQuery and XPath Functions and Operators 3.0] S. Bradner. Key Words for use in RFCs to Indicate Requirement Levels. http://www.ietf.org/rfc/rfc2119.txt T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax http://www.ietf.org/rfc/rfc3986.txt M. Duerst and M. Suignard. Internationalized Resource Identifiers (IRIs) http://www.ietf.org/rfc/rfc3987.txt ISO (International Organization for Standardization). ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS) http://www.iso.org The Unicode Consortium. The Unicode Standard http://www.unicode.org/standard/versions/ implementation-defined World Wide Web Consortium. Extensible Markup Language (XML) 1.0. http://www.w3.org/TR/REC-xml/ implementation-defined World Wide Web Consortium. Extensible Markup Language (XML) 1.1. http://www.w3.org/TR/xml11/ World Wide Web Consortium. XML Base. http://www.w3.org/TR/xmlbase/ World Wide Web Consortium. Namespaces in XML. http://www.w3.org/TR/REC-xml-names/ World Wide Web Consortium. Namespaces in XML 1.1. http://www.w3.org/TR/xml-names11/ World Wide Web Consortium. xml:id Version 1.0. http://www.w3.org/TR/xml-id/ World Wide Web Consortium. XML Schema, Parts 0, 1, and 2 (Second Edition) http://www.w3.org/TR/xmlschema-0/ http://www.w3.org/TR/xmlschema-1/ http://www.w3.org/TR/xmlschema-2/ World Wide Web Consortium. XML Schema, Parts 1, and 2 http://www.w3.org/TR/xmlschema11-1/ http://www.w3.org/TR/xmlschema11-2/ XQuery and XPath Data Model (XDM) 3.0 latest version XQuery and XPath Functions and Operators 3.0 latest version XSLT and XQuery Serialization 3.0 latest version XQuery 3.0 Requirements latest version XML Path Language (XPath) 3.0 latest version XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition) et. al. latest version XQueryX 3.0 latest version XSL Transformations (XSLT) Version 3.0 latest version World Wide Web Consortium. Document Object Model (DOM) Level 3 Core Specification. http://www.w3.org/TR/DOM-Level-3-Core/ World Wide Web Consortium. XML Information Set. http://www.w3.org/TR/xml-infoset/ XML Path Language (XPath) Version 1.0 latest version XML Path Language (XPath) 2.0 (Second Edition) et. al. latest version World Wide Web Consortium. XML Pointer Language (XPointer). http://www.w3.org/TR/WD-xptr World Wide Web Consortium. XML Query Use Cases http://www.w3.org/TR/xquery-use-cases/ World Wide Web Consortium. Processing XML 1.1 Documents with XML Schema 1.0 Processors http://www.w3.org/TR/xml11schema10/ Internet Engineering Task Force (IETF). Uniform Resource Locators (URL) http://www.ietf.org/rfc/rfc1738.txt Rick Cattell et al. The Object Database Standard: ODMG-93, Release 1.2 Don Chamberlin, Jonathan Robie, and Daniela Florescu. Quilt: an XML Query Language for Heterogeneous Data Sources Lecture Notes in Computer Science Alin Deutsch, Mary Fernandez, Daniela Florescu, Alon Levy, and Dan Suciu. A Query Language for XML International Organization for Standardization (ISO). Information Technology — Database Language SQL J. Robie, J. Lapp, D. Schach. XML Query Language (XQL) http://www.w3.org/TandS/QL/QL98/pp/xql.html World Wide Web Consortium. Character Model for the World Wide Web. http://www.w3.org/TR/charmod/ XSL Transformations (XSLT) Version 1.0 latest version Queries from the XQuery 1.0 Use Cases, presented in a single file. See http://www.w3.org/2010/12/xquery-30-use-cases/xquery-30-use-case-queries.txt Queries from this document, presented in a single file. See http://www.w3.org/2013/01/xquery-30-use-cases/xquery-30-example-queries.txt It is a static error static context is absent DM30 It is a dynamic error dynamic context is absent DM30 It is a static error A.1 EBNF It is a type error static analysis phase static type dynamic evaluation phase dynamic type 2.5.5 SequenceType Matching During the analysis phase, it is a static error static type () data(()) empty-sequence() It is a static error static context ElementTest AttributeTest An implementation that does not support the Schema Aware Feature must raise a static error It is a static error [XML Schema 1.0] [XML Schema 1.1] It is a static error An implementation that does not support the Module Feature raises a static error module declaration module import It is a static error expanded QName static function signature static context It is a type error It is a type error E1 E1/E2 It is a type error It is a static error namespace declaration attribute contains an EnclosedExpr It is a type error It is a dynamic error It is a dynamic error ?> In a validate expression, it is a dynamic error valid strict valid notKnown lax It is a type error validate It is a static error A static error base URI declaration It is a static error It is a static error or imported by a module same expanded QNames eq It is a static error It is a static error default collation declaration statically known collations It is a static error a function declaration or an inline function expression It is a static error expanded QNames It is a dynamic error xs:NCName It is a dynamic error Its namespace prefix is xmlns It has no namespace prefix and its local name is xmlns Its namespace URI is http://www.w3.org/2000/xmlns/ Its namespace prefix is xml http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace It is a static error the name of a function annotation or http://www.w3.org/XML/1998/namespace, http://www.w3.org/2001/XMLSchema, http://www.w3.org/2001/XMLSchema-instance, http://www.w3.org/2005/xpath-functions http://www.w3.org/2005/xpath-functions/math http://www.w3.org/2012/xquery An implementation MAY static error a URILiteral BracedURILiteral neither an absolute URI nor a relative URI It is a static error It is a static error It is a static error module expanded QNames eq It is a dynamic error dynamic type treat sequence type treat / // / // treat as document-node() It is a static error expanded QName AtomicOrUnionType SequenceType in-scope schema types generalized atomic type The type must be the name of a type defined in the in-scope schema types {variety} simple It is a dynamic error It is a static error copy-namespaces declaration It is a static error It is a static error It is a static error It is a static error expanded QName It is a dynamic error It is a dynamic error A static error ordering mode declaration A static error A static error construction declaration A static error boundary-space declaration A static error empty order declaration A static error xml xmlns or a default namespace declaration, The prefix xml http://www.w3.org/XML/1998/namespace A prefix other than xml http://www.w3.org/XML/1998/namespace The prefix xmlns A prefix other than xmlns http://www.w3.org/2000/xmlns/ A static error It is a dynamic error It is a dynamic error expanded QName statically known namespaces An implementation that does not support the Validation Feature must raise a static error validate It is a static error collation order by statically known collations It is a static error pragma It is a static error cast castable xs:NOTATION xs:anySimpleType xs:anyAtomicType It is a static error a query statically known namespaces It is a dynamic error validate in-scope element declarations strict It is a static error [XML Names 1.1] It is a type error namespace-sensitive construction mode preserve copy-namespaces mode no-preserve It is a static error EncName [XML 1.0] It is a static error module import module declaration It is a static error for window expanded QNames It is a static error character reference An implementation MAY dynamic error xml:id [XML ID] xml:id An implementation MAY dynamic error xml:space preserve default The name of each grouping variable must be equal (by the eq expanded QNames It is a dynamic error if Its namespace prefix is xmlns Its namespace URI is http://www.w3.org/2000/xmlns/ Its namespace prefix is xml http://www.w3.org/XML/1998/namespace Its namespace prefix is other than xml http://www.w3.org/XML/1998/namespace It is a static error for a decimal-format to specify a value that is not valid for a given property, as described in statically known decimal formats It is a static error if, for any named or unnamed decimal format, the properties representing characters used in a picture string do not each have distinct values. These properties are decimal-separator-sign grouping-separator percent-sign per-mille-sign zero-digit digit-sign pattern-separator-sign No module An error is raised if a computed namespace constructor attempts to do any of the following: Bind the prefix xml http://www.w3.org/XML/1998/namespace Bind a prefix other than xml http://www.w3.org/XML/1998/namespace Bind the prefix xmlns Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/ Bind any prefix (including the empty prefix) to a zero-length namespace URI. In an element constructor, if two or more namespace bindings in the in-scope bindings would have the same prefix, then an error is raised if they have different URIs; if they would have the same prefix and URI, duplicate bindings are ignored. If the name of an element in an element constructor is in no namespace, creating a default namespace for that element using a computed namespace constructor is an error. All variables in a window A TypeName validate in-scope schema definitions It is a type error It is a static error %private %public It is a static error output declaration library module It is a static error http://www.w3.org/2010/xslt-xquery-serialization C.1 Static Context Components or if the name of an output declaration is use-character-maps It is a static error output declaration It is a static error Specifying a VarValue VarDefaultValue static error It is a static error It is a static error It is a static error if a variable declaration contains both a %private %public %private %public In a cast expression, if an item is of type xs:untypedAtomic namespace-sensitive type error err:XPTY0117 In a direct element constructor, the name used in the end tag must exactly match the name used in the corresponding start tag, including its prefix or absence of a prefix. It is a static error if the implementation is not able to process the value of an output:parameter-document It is a static error expression %public %private An implementation that does not provide the Higher-Order Function Feature MUST err:XQST0129 FunctionTest dynamic function call named function reference inline function expression partial function application An implementation-defined limit has been exceeded. It is a static error err:XPST0133 http://www.w3.org/2000/xmlns/ XQuery 3.0 does not support the namespace axis. application/xquery This Appendix specifies the media type for XQuery Version 1.0. XQuery is a language for querying over collections of data from XML data sources, as specified in the main body of this document. This media type is being submitted to the IESG (Internet Engineering Steering Group) for review, approval, and registration with IANA (Internet Assigned Numbers Authority.) This document, found at http://www.w3.org/TR/xquery/ application/xquery This document was prepared by members of the W3C XML Query Working Group. Please send comments to [email protected], a public mailing list with archives at http://lists.w3.org/Archives/Public/public-qt-comments application/xquery MIME media type name: application MIME subtype name: xquery Required parameters: none Optional parameters: none The syntax of XQuery is expressed in Unicode but may be written with any Unicode-compatible character encoding, including UTF-8 or UTF-16, or transported as US-ASCII or ISO-8859-1 with Unicode characters outside the range of the given encoding represented using an XML-style ෝ None known. The public XQuery Web page This new media type is being registered to allow for deployment of XQuery on the World Wide Web. The most common file extensions in use for XQuery are .xq .xquery The appropriate Macintosh file type code is TEXT The intended usage of this media type is for interchange of XQuery expressions. XQuery was produced by, and is maintained by, the World Wide Web Consortium's XML Query Working Group. The W3C has change control over this specification. For use with transports that are not 8-bit clean, quoted-printable encoding is recommended since the XQuery syntax itself uses the US-ASCII-compatible subset of Unicode. An XQuery document may contain an encoding declaration version declaration xquery version "1.0" encoding "utf-8"; An XQuery file may have the string xquery version "V.V" "V.V" "1.0" XQuery documents use the Unicode character set and, by default, the UTF-8 encoding. Queries written in XQuery may cause arbitrary URIs or IRIs to be dereferenced. Therefore, the security issues of [RFC3987] file: [XQuery and XPath Functions and Operators 3.0] fn:doc() fn:doc-available() XQuery is a full declarative programming language, and supports user-defined functions, external function libraries (modules) referenced by URI, and system-specific "native" functions. Arbitrary recursion is possible, as is arbitrarily large memory usage, and implementations may place limits on CPU and memory usage, as well as restricting access to system-defined functions. The XML Query Working group is working on a facility to allow XQuery expressions to create and update persistent data. Untrusted queries should not be given write access to data. Furthermore, because the XQuery language permits extensions, it is possible that application/xquery In the operator mapping tables, the term Gregorian xs:gYearMonth xs:gYear xs:gMonthDay xs:gDay xs:gMonth NaN A Prolog module SequenceType matching dynamic type sequence type Static Base URI. relative URIs both during static analysis and during dynamic evaluation. Within this specification, the term URI [RFC3986] [RFC3987] IRI The term XDM instance value sequence items data model An XPath 1.0 Processor XPath 1.0 compatibility mode. This component must be set by all host languages that include XPath 3.0 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false An XPath 2.0 Processor An XPath 3.0 Processor An XQuery 1.0 Processor An XQuery 3.0 Processor An argument to a function call is either an argument expression Argument expressions with respect to DC argument values The number of Argument ArgumentList arity An atomic value atomic type [XML Schema 1.0] [XML Schema 1.1] Atomization fn:data [XQuery and XPath Functions and Operators 3.0] Available documents. data model fn:doc Available node collections. fn:collection Available resource collections. fn:uri-collection Available text resources fn:unparsed-text An axis step axis node test type annotation A base URI declaration Static Base URI Static Base URI In a for window in binding sequence Boundary whitespace direct element constructor DirectConstructor EnclosedExpr character references   CDataSections A boundary-space declaration boundary-space policy static context boundary whitespace Boundary-space policy. boundary whitespace direct element constructors 3.9.1.4 Boundary Whitespace The built-in functions [XQuery and XPath Functions and Operators 3.0] A character reference [Unicode] A collation [XQuery and XPath Functions and Operators 3.0] One way to construct a sequence is by using the comma operator A computed element constructor A construction declaration construction mode static context Construction mode. preserve xs:anyType strip xs:untyped xs:untyped xs:untypedAtomic The constructor function T($arg) (($arg) cast as T?) The final part of a computed constructor is an expression enclosed in braces, called the content expression The context item item Context item static type. static type When the context item is a node, it can also be referred to as the context node The context position The context size A copy-namespaces declaration copy-namespaces mode static context Copy-namespaces mode. 3.9.1 Direct Element Constructors preserve no-preserve inherit no-inherit Current dateTime. implementation-dependent a query fn:current-dateTime a query XQuery 3.0 operates on the abstract, logical structure of an XML document, rather than its surface syntax. This logical structure, known as the data model [XQuery and XPath Data Model (XDM) 3.0] A decimal format declaration statically known decimal formats fn:format-number() decimal-separator Default calendar. fn:format-date fn:format-dateTime Default collation. statically known collations xs:string xs:anyURI A default collation declaration default collation static context Default element/type namespace. absent DM30 Default function namespace. absent DM30 Default language. fn:format-date fn:format-integer xs:language Default node collection. fn:collection Default order for empty sequences. NaN order by 3.10.8 Order By Clause Default place. fn:format-date fn:format-dateTime Default resource collection. fn:uri-collection The delimiting terminal symbols S StringLiteral BracedURILiteral A variable value (or the context item) depends on digit-sign A direct element constructor Informally, document order The dynamic context A dynamic error The dynamic evaluation phase A dynamic function call base expression argument expressions A dynamic type static type xs:integer* xs:integer The effective boolean value fn:boolean [XQuery and XPath Functions and Operators 3.0] The effective case The effective case typeswitch case SequenceType SequenceTypeUnion case SequenceType matching An empty order declaration default order for empty sequences static context, NaN order by A sequence containing zero items is called an empty sequence If present, a version declaration may optionally include an encoding declaration encoding EncName [XML 1.0] err:XQST0087 UTF-8 UTF-16 US-ASCII Environment variables. mapping from names to values. implementation-defined implementation-defined may Two tuples T1 T2 equivalent grouping keys GV GV T1 GV T2 fn:deep-equal In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values An expanded QName The expression context An extension expression implementation-defined External functions An expression followed by a predicate (that is, E1[E2] filter expression E1 In a partial function application, a fixed position ArgumentList ArgumentPlaceholder The first three components of the dynamic context focus A function assertion 4.15 Annotations Function coercion function DM30 The function conversion rules or a return value parameter or return. A generalized atomic type pure union type The atomized value of a grouping variable grouping key Each grouping specification specifies one grouping variable grouping-separator The Higher Order Function Feature Ignorable whitespace whitespace terminals ws:explicit A.2.4.2 Explicit Whitespace Handling Implementation-dependent Implementation-defined Implicit timezone. implementation-defined xs:dayTimeDuration [XML Schema 1.0] [XML Schema 1.1] In-scope attribute declarations. expanded QName implementation-dependent If the Schema Aware Feature In-scope element declarations. expanded QName implementation-dependent If the Schema Aware Feature The in-scope namespaces In-scope schema definitions. static analysis In-scope schema types. expanded QName named type implementation-dependent anonymous type 2.5.1 Predefined Schema Types If the Schema Aware Feature In-scope variables. mapping from expanded QName expanded QName static type infinity The initial context item If a variable declaration includes an expression ( VarValue VarDefaultValue initializing expression. An inline function expression function DM30 An item atomic value node function DM30 An alternative form of a node test called a kind test type annotation A lexical QName [http://www.w3.org/TR/REC-xml-names/#NT-QName] A module that does not contain a Query Body library module module declaration Prolog A literal A main module Prolog Query Body MAY minus-sign A module Module static analysis phase 2.2.3 Expression Processing main module library module The module context A module declaration module library module module URILiteral The Module Feature Module Import library modules A module import public variable declarations and public function declarations library modules statically known in-scope variables module MUST MUST NOT When an expression is used to specify the name of a constructed node, that expression is called the name expression A node test that consists only of an EQName or a Wildcard is called a name test A named function query expanded A named function reference denotes named function Named functions function DM30 A namespace declaration statically known namespaces A namespace declaration attribute default element/type namespace The namespace-sensitive xs:QName xs:NOTATION xs:QName xs:NOTATION A node node kinds [XQuery and XPath Data Model (XDM) 3.0] A node test type annotation step The non-delimiting terminal symbols IntegerLiteral URIQualifiedName NCName DecimalLiteral DoubleLiteral QName When referring to a type, the term numeric xs:integer xs:decimal xs:float xs:double A predicate whose predicate expression returns a numeric type is called a numeric predicate For each operator and valid combination of operand types, the operator mapping tables specify a result type and an operator function An option declaration Ordering mode. ordered unordered expressions, as discussed in 3.11 Ordered and Unordered Expressions An ordering mode declaration ordering mode static context An output declaration A static or dynamic partial function application A path expression steps / // / // pattern-separator per-mille percent A positional variable at A pragma (# #) implementation-defined A predefined entity reference Primary expressions constructors, Every axis has a principal node kind A private variable %private module import in-scope variables A private function %private module import statically known A public function without a %private module import statically known A public variable %private module import in-scope variables Using %public %private static error err:XQST0116 if a variable declaration contains both a %private %public %private %public A pure union type {variety} union {facets} {variety} list {variety} union {facets} A query modules The Query Body To resolve a relative URI $rel $base fn:resolve-uri($rel, $base) The node ordering that is the reverse of document order is called reverse document order The Schema Aware Feature schema import validate 3.18 Validate Expressions A schema import in-scope schema definitions For each named simple type constructor function A schema type [XML Schema 1.0] [XML Schema 1.1] [XML Schema 1.0] [XML Schema 1.1] A sequence items A sequence type SequenceType sequence type Serialization XDM instance , as described in [XSLT and XQuery Serialization 3.0] The Serialization Feature 2.2.4 Serialization Setters SHOULD A sequence containing exactly one item is called a singleton A singleton focus Document order is stable query implementation-dependent The Static Typing Feature type errors static analysis phase The static analysis phase static context static analysis phase The static context An error that can , and is not a type error, static error A static The static type Statically known decimal formats. a mapping from QName to decimal format, with one default format that has no visible name. fn:format-number() Statically known collections. fn:collection fn:collection Statically known documents. fn:doc static type fn:doc Statically known collations. implementation-defined mapping from URI to collation. queries and Statically known default collection type. fn:collection Statically known function signatures. function signature DM30 Statically known namespaces. mapping from prefix to namespace URI that defines A step path expression predicates axis step The string value fn:string Substitution groups [XML Schema 1.0] [XML Schema 1.1] head element A sequence type A subtype B subtype(A, B) The use of a value whose dynamic type subtype substitution Each rule in the grammar defines one symbol symbol ::= expression Whitespace Comments symbol separators /* ws: explicit */ /* xgc: xml-version */ The target namespace A terminal A tuple XDM instance A tuple stream tuples Each element node and attribute node in an XDM instance type annotation described [XQuery and XPath Data Model (XDM) 3.0] reference to an XML Schema type. A variable binding may be accompanied by a type declaration as 2.5.4 SequenceType Syntax A type error type error static type type error dynamic type Under certain circumstances, an atomic value can be promoted from one type to another. Type promotion 3.1.5.1 Evaluating Static and Dynamic Function Calls , order by 3.10.8 Order By Clause B.2 Operator Mapping The Typed Data Feature xs:untyped xs:untypedAtomic The typed value fn:data User defined functions function body In the data model value sequence A variable reference Variable values mapping from expanded QName expanded QNames in-scope variables static context expanded QName dynamic type A version declaration module In addition to static errors dynamic errors type errors warnings static analysis phase dynamic evaluation phase implementation-defined A whitespace [http://www.w3.org/TR/REC-xml/#NT-S] A window binding sequence xs:anyAtomicType xs:anySimpleType xs:decimal xs:string xs:anyAtomicType xs:dayTimeDuration xs:duration xs:dayTimeDuration xs:error [XML Schema 1.1] 2.5.4 SequenceType Syntax xs:untyped type annotation skip xs:untypedAtomic xs:yearMonthDuration xs:duration xs:yearMonthDuration zero-digit This section contains examples of several important classes of queries that can be expressed using XQuery. The applications described here include joins across multiple data sources, grouping and aggregation, queries based on sequential relationships, recursive transformations, and selection of distinct combinations of values. Note: This section needs to be rewritten in light of the new features of XQuery 3.0, which can significantly simplify some of these queries. Joins, which combine data from multiple sources into a single result, are a very important type of query. In this section we will illustrate how several types of joins can be expressed in XQuery. We will base our examples on the following three documents: A document named parts.xml part part partno description A document named suppliers.xml supplier supplier suppno suppname A document named catalog.xml item partno suppno price A conventional ("inner") join returns information from two or more related sources, as illustrated by the following example, which combines information from three documents. The example generates a "descriptive catalog" derived from the catalog document, but containing part descriptions instead of part numbers and supplier names instead of supplier numbers. The new catalog is ordered alphabetically by part description and secondarily by supplier name. <descriptive-catalog> { for $i in fn:doc("catalog.xml")/items/item, $p in fn:doc("parts.xml")/parts/part[partno = $i/partno], $s in fn:doc("suppliers.xml")/suppliers /supplier[suppno = $i/suppno] order by $p/description, $s/suppname return <item> { $p/description, $s/suppname, $i/price } </item> } </descriptive-catalog> The previous query returns information only about parts that have suppliers and suppliers that have parts. An outer join left outer join The following query demonstrates a left outer join. It returns names of all the suppliers in alphabetic order, including those that supply no parts. In the result, each supplier element contains the descriptions of all the parts it supplies, in alphabetic order. for $s in fn:doc("suppliers.xml")/suppliers/supplier order by $s/suppname return <supplier> { $s/suppname, for $i in fn:doc("catalog.xml")/items/item [suppno = $s/suppno], $p in fn:doc("parts.xml")/parts/part [partno = $i/partno] order by $p/description return $p/description } </supplier> The previous query preserves information about suppliers that supply no parts. Another type of join, called a full outer join supplier part part <master-list> { for $s in fn:doc("suppliers.xml")/suppliers/supplier order by $s/suppname return <supplier> { $s/suppname, for $i in fn:doc("catalog.xml")/items/item [suppno = $s/suppno], $p in fn:doc("parts.xml")/parts/part [partno = $i/partno] order by $p/description return <part> { $p/description, $i/price } </part> } </supplier> , (: parts that have no supplier :) <orphan-parts> { for $p in fn:doc("parts.xml")/parts/part where fn:empty(fn:doc("catalog.xml")/items/item [partno = $p/partno] ) order by $p/description return $p/description } </orphan-parts> } </master-list> The previous query uses an element constructor to enclose its output inside a master-list supplier orphan-parts XQuery uses the << >> procedure incision instrument action anesthesia The following query returns all the action incision let $proc := /report/procedure[1] for $i in $proc//action where $i >> ($proc//incision)[1] and $i << ($proc//incision)[2] return $i It is worth noting here that document order is defined in such a way that a node is considered to precede its descendants in document order. In the surgical report, an action incision instrument >> $i >> ($proc//incision)[1] instrument incision For some queries, it may be helpful to declare a function that can test whether a node precedes another node without being its ancestor. The following function returns true false declare function local:precedes($a as node(), $b as node()) as boolean { $a << $b and fn:empty($a//node() intersect $b) }; Similarly, a local:follows declare function local:follows($a as node(), $b as node()) as boolean { $a >> $b and fn:empty($b//node() intersect $a) }; Using the local:precedes instrument instrument incision let $proc := /report/procedure[1] for $i in $proc//instrument where local:precedes(($proc//incision)[1], $i) and local:precedes($i, ($proc//incision)[2]) return $i The following query reports incisions for which no prior anesthesia was recorded in the surgical report. Since an anesthesia incision << local:precedes for $proc in /report/procedure where some $i in $proc//incision satisfies fn:empty($proc//anesthesia[. << $i]) return $proc In some documents, particular sequences of elements may indicate a logical hierarchy. This is most commonly true of HTML. The following query returns the introduction of an XHTML document, wrapping it in a div h2 h2 h1 let $intro := //h2[text()="Introduction"], $next-h := //(h1|h2)[. >> $intro][1] return <div> { $intro, if (fn:empty($next-h)) then //node()[. >> $intro] else //node()[. >> $intro and . << $next-h] } </div> Note that the above query makes explicit the hierarchy that was implicit in the original document. In this example, we assume that the h2 Occasionally it is necessary to scan over a hierarchy of elements, applying some transformation at each level of the hierarchy. In XQuery this can be accomplished by defining a recursive function. In this section we will present two examples of such recursive functions. Suppose that we need to compute a table of contents for a given document by scanning over the document, retaining only elements named section title section section title title declare function local:sections-and-titles($n as node()) as node()? { if (fn:local-name($n) = "section") then element { fn:local-name($n) } { for $c in $n/* return local:sections-and-titles($c) } else if (fn:local-name($n) = "title") then $n else ( ) }; The "skeleton" of a given document, containing only its sections and titles, can then be obtained by invoking the local:sections-and-titles local:sections-and-titles(fn:doc("cookbook.xml")) As another example of a recursive transformation, suppose that we wish to scan over a document, transforming every attribute named color color size size $e declare function local:swizzle($n as node()) as node() { typeswitch($n) case $a as attribute(color) return element color { fn:string($a) } case $es as element(size) return attribute size { fn:string($es) } case $e as element() return element { fn:local-name($e) } { for $c in ($e/@* except $e/@color, (: attr -> attr :) $e/size, (: elem -> attr :) $e/@color, (: attr -> elem :) $e/node() except $e/size ) (: elem -> elem :) return local:swizzle($c) } case $d as document-node() return document { for $c in $d/* return local:swizzle($c) } default return $n }; The transformation can be applied to a whole document by invoking the local:swizzle local:swizzle(fn:doc("plans.xml")) It is sometimes necessary to search through a set of data to find all the distinct combinations of a given list of properties. For example, an input data set might consist of a large set of order <order> <date>2003-10-15</date> <product>Dress Shirt</product> <size>M</size> <color>Blue</color> <supplier>Fashion Trends</supplier> <quantity>50</quantity> </order> From this data set, a user might wish to find all the distinct combinations of product size color order option for $p in fn:distinct-values(/orders/order/product), $s in fn:distinct-values(/orders/order/size), $c in fn:distinct-values(/orders/order/color) order by $p, $s, $c return if (fn:exists(/orders/order[product eq $p and size eq $s and color eq $c])) then <option> <product>{$p}</product> <size>{$s}</size> <color>{$c}</color> </option> else () This appendix lists the changes that have been made to this specification since the first The following names are now reserved, and cannot appear as function names (see A.3 Reserved Function Names function namespace-node switch Code written for XQuery 1.0 processors may assume that every item is either a node or an atomic value. This is no longer true, since XQuery 3.0 introduces function items. Thus, an XQuery 1.0 function that declares a parameter as an item() No substantive changes were made during the Proposed Recommendation period. Clarified wording of FLWOR expression in introductory text. Resolves Bug 24221 The following substantive changes have been made. Removed require-feature() prohibit-feature() Added the 5.2.4 Typed Data Feature Bug 20828 Added entry to J.1 Incompatibilities function namespace-node switch Bug 20902 Added entry to J.1 Incompatibilities https://lists.w3.org/Archives/Member/w3c-xsl-query/2013Feb/0050.htm (member only) Fixed text for castable. Resolves Bug 21664 Added error code [ err:XPDY0130 Bug 21413 Changed fn:map fn:for-each fn:map-pairs fn:for-each-pair Bug 21128 Implementations must recognize options declared in the XQuery specification. Resolves Bug 20540 Adopted new definition of derives-from(AT, ET). Resolves Bug 20643 If the NodeTest in an axis step is a NamespaceNodeTest then a static error is raised. Resolves Bug 20736 A try/catch expression catches dynamic errors and type errors raised by the evaluation of the target expression of the try clause. Previously, the text referred to expressions lexically contained within the try clause. Resolves Bug 18877 Added support for xs:error Bug 20634 If any component in the focus is defined, all components of the focus are defined. Resolves Bug 21011 Defined validate type xs:untyped xs:untyped xs:untypedAtomic xs:untypedAtomic xs:untypedAtomic Bug 21011 Changed XPTY0117 to FONS0004 in section 2.5.2, changed text of [ err:XPTY0117 Bug 21893 Explicitly stated that no catch clause "matches" the error value, a the try/catch expression raises the error that was raised by the target expression. Resolves Bug 21666 Changed "When tokenizing, the longest possible match that is valid in the current context is used." to "When tokenizing, the longest possible match consistent with the EBNF is used." Decided in Teleconference #541 2013-05-21. If the name of an element in a computed element constructor is in no namespace, creating a default namespace for that element using a computed namespace constructor is an error. Resolves Bug 22032 Added an exception for subtype(Ai*, Bi?) when Ai is a pure union type with no member types, as in xs:error. Resolves Bug 20862 Modified definition of statically known decimal formats in context. Resolves Bug 19365 A processor must not raise errors for serialization parameters that it does not support. "A processor that is performing serialization must raise a serialization error if the values of any serialization parameters that it supports Changed the second rule of 2.5.6.2 The judgement subtype-itemtype(Ai, Bi) 2.5.6.2 The judgement subtype-itemtype(Ai, Bi) Bug 20632 Removed the paragraph that said no published version of XML Schema references the XML 1.1 specifications, since this is no longer true. Modified 2.5.6 SequenceType Subtype Relationships xs:error Bug 22552 Improved Step 5.b.ii.A in 3.1.5.1 Evaluating Static and Dynamic Function Calls The following items were changed in earlier drafts, but were erroneously omitted in previous change logs. Added support for unions of types in 3.16.2 Typeswitch A cycle in the definition of a module's dynamic context components, for example because of a cycle in variable declarations, is now a dynamic error [ err:XQDY0054 The following are some of the editorial changes that have been made. Deleted unused error, checked for consistency of errors. Resolves Bug 20837 Added an example to show how to copy "unused" namespaces from one node to another using in-scope-prefixes($e) ! namespace {namespace-uri-for-prefix($e,.)} {.} Bug 21025 Restored normative status of FunctionTest semantics - see 2.5.5.7 Function Test Bug 19341 Added entry for || A.4 Precedence Order (Non-Normative) Deleted note on the converse relationship from 2.5.6 SequenceType Subtype Relationships Removed statement that implied the XQuery 3.0 requirements include a requirement for an XML-based representation. The following are changes that have been decided, but are no longer relevant because of our decision to remove require-feature prohibit-feature Resolution of the following bugs, all related to require/prohibit feature, has not yet been implemented in this document: Bug 21130 Bug 19597 Bug 21717 Reworked require-feature prohibit-feature Bug 19602 Clarified meaning of vendor extensions, added definition of named feature, simplified require-feature prohibit-feature Bug 19670 The following substantive changes have been made. Pure union types (formerly known as restricted union types) are now permitted in AtomicOrUnionTypes. Resolves Bug 13399 Adopted the XML restriction that control characters #x1 to #x1F and 0x7F to 0x9F cannot appear in unescaped form in an XQuery. Resolves Bug 14921 Added available text resources to the static context, as part of the resolution of Bug 14932 Changed error XQST0046 for URI literals so that it is no longer dependent on the lexical space of xs:anyURI - the error is now raised if the value of a URILiteral or a BracedURILiteral is of nonzero length and is neither an absolute URI nor a relative URI. Resolves Bug 15675 All function annotations are carried through function coercion. Resolves Bug 15690 Clarified and extended rules for casting. Resolves Bug 15807 Modified the scope of grouping variables. Resolves Bug 15728 Abandoned the special casting rule that prevented atomization for namespace sensitive types. Resolves Bug 16089 The split of base URI into static base URI and dynamic base URI has been reverted ; instead there is simply a note giving implementations freedom to handle base URI as needed in the case where compiled queries are deployed remotely from the source code Bug 17595 A grouping variable is bound to an atomized value. See decision in Teleconference #497 Minutes (member only) Changed the syntax of EQName to avoid conflicts with potential JSON syntax extensions in future versions. Resolves Bug 15399 Relaxed rules that required inputs, outputs, and query modules to all use the same versions of XML, XML Names, and XML Schemas for names, characters, attribute value normalization, line-breaks, etc. Resolves Bug 15966 Function items are now supported for context-dependent functions if they depend only on the static context. Resolves Bug 15912 Removed error XPDY0229. Resolves Bug 16681 The default namespace for both options and annotations is now http://www.w3.org/2012/xquery Bug 16199 Changed precedence of simple map operator, reorganized text accordingly. Resolves Bug 16197 Integrated proposals on static and dynamic context from http://lists.w3.org/Archives/Member/w3c-xsl-query/2012May/0118.html 14656 14375 15791 Clarified errors for variable declarations and function declarations that have both %private %public Bug 16104 Bug 19077 Renamed annotation assertions to function assertions, clarified that an unrecognized assertion has no effect on processing and that an assertion always restricts the set of matched functions (and never extends them). Resolves Bug 17474 If there is a Comment before the end of a Version Declaration, an implementation must either raise an implementation-defined static error or ignore the commment. Decided in Montreal Face-to-Face, see https://lists.w3.org/Archives/Member/w3c-xsl-query/2012Jul/0081.html The namespace URI specified in a default namespace declaration must not be http://www.w3.org/XML/1998/namespace http://www.w3.org/2000/xmlns/ Bug 14930 Combined the Schema Validation Feature and the Schema Import Feature into one feature, the Schema Aware Feature (see 5.2.3 Schema Aware Feature Bug 11585 The serialization feature (see 5.2.7 Serialization Feature Using %public %private Higher order functions are now an optional feature. Decided in teleconference #519, 2012-09-18. If the type name is xs:untyped validate type xs:untyped { $x } $x Changed rules for whitespace in URI Literals and Braced URI Literals in 2.4.5 URI Literals Serialization parameter names are defined by the element names in the schema in the serialization spec. Error XQST0109 is also raised if the name of an output declaration is use-character-maps An implementation may raise a dynamic error [ err:XQDY0074 URIExpr xs:anyURI Bug 15675 Updated the appendix of implementation-defined items. In E castable as T E castable false 3.16.4 Castable Adopted rewording of 2.5.5.4 Schema Element Test Bug 10207 Corrected rule #17 of 2.5.6.2 The judgement subtype-itemtype(Ai, Bi) Bug 19425 Added error [ err:XPST0133 http://www.w3.org/2000/xmlns/ Bug 19658 Allow an XQuery implementation to process an XQuery 1.0 query according to either the XQuery 1.0 specification or the XQuery 3.0 specification. See 4.1 Version Declaration Bug 19671 All modules share the same initial context item Bug 19267 Added row for statically known decimal formats to C.2 Dynamic Context Components Bug 19365 In 4.18 Function Declaration Bug 15791 In 4.18 Function Declaration Updated J.1 Incompatibilities function namespace-node switch Ai is a subtype of Bi if Ai and Bi are both pure union types, and every type t in the transitive membership of Ai is also in the transitive membership of Bi. Resolves Bug 19504 Added html-version item-separator Bug 20267 Implementations must raise an error if limits are exceeded. Resolves Bug 20310 The following are some of the editorial changes that have been made. Introduced the concept of singleton focus, borrowed from XSLT, and used it to clarify context declaration. Resolves Bug 15789 Reworked much of the prose re functions, to increase clarity and better accommodate dynamic function calls and partial function applications. Renamed "Module URI" to "the target namespace of a module". Resolves Bug 14368 Eliminated the undefined term "global variable". Resolves Bug 14369 Simplified Conformance language. Consistently use "provides a feature" instead of using both "provides" and "supports". Reduce redundant use of the term "conforms to". Consistently use "absent" for properties with no value in both static and dynamic context. More consistent use of terminology for raising an error, eliminating other terms (signal, report, raise, throw) that have been used in various versions of this specification over the years. Improved the definition of static error Editorial rewrite of the description of document order. Corrected several places where EQNames, QNames, and expanded QNames were conflated. Simplified 3.1.2 Variable References Improved the definition of node test Removed definition for "depends on a function", which is no longer used. Removed a dangling note describing an obsolete error for context-sensitive functions in 3.1.6 Named Function References Fixed headings in Appendix C that implied that it describes static and dynamic contexts only for modules. Resolves Bug 20350 The following substantive changes have been made in prior Working Drafts. Applied all XQuery 2ed errata Added group by 3.10.7 Group By Clause Added tumbling window sliding window 3.10.4 Window Clause Added count 3.10.6 Count Clause Added allowing empty 3.10.2 For Clause Added 3.15 Try/Catch Expressions Added named function references 3.1.6 Named Function References Added inline function expression 3.1.7 Inline Function Expressions Added dynamic function call 3.2.2 Dynamic Function Call Added 3.1.5.3 Function Coercion Added 2.5.6 SequenceType Subtype Relationships Added private functions ( 4.18 Function Declaration Added switch expressions ( 3.13 Switch Expression Added computed namespace constructors ( 3.9.3.7 Computed Namespace Constructors Added output declarations ( 2.2.4 Serialization Added annotations ( 4.15 Annotations Simplified BNF for FLWOR expressions, changed description of semantics so that each clause is understood as accepting a tuple stream as input, acting on that tuple stream, and producing a tuple stream as output. Modified validate expressions type Extended variable declarations Added 4.17 Context Item Declaration Modified 4.1 Version Declaration Added 4.10 Decimal Format Declaration fn:format-number() Relaxed constraints on module imports in 4.12 Module Import Modified 4.16 Variable Declaration Removed obsolete Latin-1, using ISO-8859-1 instead. Resolves Bug 7797 Changed conformance section to make full-axis support mandatory. Added note saying the Working Group has not yet decided which XQuery 3.0 features are optional. Added normative rules for resolving module URIs to 4.12 Module Import Clarified type information available to derives-from() 2.5.5 SequenceType Matching Bug 6513, Comment #21 Modified derives-from() 2.5.5 SequenceType Matching Bug 7749 Added function assertions function tests Removed section on static typing extensions. Added support for literal URLs in names, using EQNames Added support for XML Schema 1.1. Added support for union types in function arguments. Allowed serialization options to be specified as an XDM instance using output declarations. See 2.2.4 Serialization Bug 9302 Allowed implementations to ignore errors in non-matching case operands. Resolves Bug 9252 Required validation to check the values of nodes of type xs:NOTATION. Resolves Bug 9816 Clarified wording on conflicts between function signatures and constructor functions in statically known Fixed an editorial error in which the wrong error was reported for duplicate decimal formats. Resolves Bug 10271 Added error for duplicate property declarations within a single decimal format declaration. Resolves Bug 10272 Specified consistency constraints for types and values of default values for external variables. Resolves Bug 10407 Added missing consistency constraints for statically known namespaces to 2.2.5 Consistency Constraints xmlns http://www.w3.org/2000/xmlns/ Bug 10700 The prefixes math err out Bug 10681 Forbid the namespace URI "http://www.w3.org/2000/xmlns/" in constructed namespace nodes. Resolves Bug 10728 Corrected definition of group by: 1. We now that no two items with different grouping keys are deep equal to each other, 2. We now handle a non-transitivity edge case. Resolves Bug 10733 Corrected a bug in XQuery Second Edition involving consecutive ' or " characters in attribute content. Resolves Bug 10989 Adopted rules for abstract elements in substitution groups: abstract elements do not appear in substitution groups, block attributes must be taken into account when building the substitution groups. Resolves Bug 10207 Changed the rules for static detection of dynamic and type errors in 2.3.1 Kinds of Errors Clarified that implementation-defined annotations must not be in any of the following namespaces: http://www.w3.org/XML/1998/namespace http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema-instance Prohibited implementations from defining annotations or annotations assertions in reserved namespaces, changing to MUST NOT http://www.w3.org/2005/xpath-functions http://www.w3.org/2005/xpath-functions/math Bug 10865 Prohibited the xmlns Bug 10869 Prohibited user defined functions from being declared in the math namespace. Resolves Bug 10883 Defined the behavior of "depends on" in the presence of function items. Resolves Bug 10885 Removed default values from annotations. Resolves Bug 11014 Added missing semantics for EQNames with URILiterals. Resolves Bug 10857 Added support for private variables. Resolves Bug 10875 Added support for casting to union types. Resolves Bug 7860 Eliminated err:XQST0036 - implementations must be able to determine whether a type in the schemas of one module is derived from a type in the schemas of another module. Resolves Bug 12173 Prohibited reserved namespaces in annotations (in addition to annotation assertions). Resolves Bug 11538 Required implementations to resolve cycles in module imports, ensuring that a given module is imported only once. Resolves Bug 10863 In try/catch expressions, only the first catch clause the matches an error needs to be evaluated. Resolves Bug 11171 Allowed a URILiteral Wildcard How XDM instances are created from sources other than an Infoset or PSVI is implementation-defined. Resolves Bug 12208 Clarified use of Static Base URI, Dynamic Base URI per Bug 11561#c6 Added err:XQST0118 for start tag / end tag name mismatches. Resolves Bug 11609 Adds errors for casts to namepace sensitive types in cast and function conversion rules. Resolves Bug 11964 Specified use of "unknown" types, including types from documents and types from other modules. Eliminated err:XQST0036. Resolves Bug 11095 Introduced Generalized atomic types Added string concatenation operator "con" || "cat" || "enate" Clarified that conformance to the data model or functions and operators requires a definition of every item specified to be implementation-defined, unless that item is part of an optional feature that is not supported by the implementation. Added prohibit-feature require-feature Implemented simple mapping operator proposal using "!" operator. Resolves Bug 12951 Inline function expression Bug 12909 Changed the ordering of rules in namespace constructors. Resolves Bug 12649 Changed rules for matching substitution groups. Resolves Bug 10065 Eliminated redundant errors for duplicate variables in window clauses. Resolves Bug 13680 Changed XQTY0102 to a dynamic error. Resolves Bug 13289 A namespace constructor must have a namespace URI of length > 0. Resolves Bug 12738 Functions and annotations For a partial function application, a failure in the function conversion rules MUST raise a type error. Function item coercion is required to raise a type error if there's a mismatch in the number of parameters (expected vs actual). Resolves Bug 14350 In the triggers for err:XPST0112, broaden the class of functions that can't be referenced by partial function applications and named function references, from "focus-dependent" to "context-dependent built-in". Added default language, calendar, and place to the dynamic context. Resolves Bug 14995 Changed namespace handling in option declarations to provide a default namespace. Expanded definition of XPST0080 so that casting to xs:anySimpleType is also an error. Resolves Bug 19090 The following are some of the editorial changes that have been made. Add Note to group-by section on unexpected replication of LET-bindings after grouping. Advises users to use a separate FLWOR to bind the expression, and a nested FLWOR for grouping, like this: let $x := 47 return for $e in //emps group by $d := $e/dept return f($d, $x) Changed introductory text on the relationship between XQuery and XPath to list the cases where a syntactically valid query can return different results in the two languages - see https://www.w3.org/Bugs/Public/show_bug.cgi?id=7163. Introduced definitions of scope, global scope, module scope, lexical scope, and dynamic scope to C Context Components Fixed names of op:hexBinary-equal op:base64Binary-equal B.2 Operator Mapping Bug 7048 Clarified overwriteability of the context item static type, resolving Bug 8875 Added a definion for resolving a relative URI. Bug 10571 Provided a definition for matching a ParenthesizedItemType ParenthesizedItemType ItemType Clarified that defaults are used for missing properties of decimal formats. If a given property is not declared, the default values specified in statically known decimal formats are used. Resolves Bug 10858 Clarified semantics of decimal formats in which all properties are defaulted. If a format declares no properties, default values are used for all properties. Resolves Bug 10273 Eliminated the vestigial term user declared function user-defined function Bug 10466 Added fn:unparsed-text fn:uri-collection fn:get-environment-variable Bug 10503 Changed terminology for properties with no value, particularly in the case of namespace URIs, using the Data Model's new term absent DM30 Bug 10683 Clarified that in-scope variables are augmented by inline function expression Bug 10686 Corrected several editorial errors involving static context for statically known namespaces. Resolves Bug 10689 Pulled FunctionTest out into it's own SequenceType matching sub-section. Clarified which default namespace to use throughout. Resolves Bug 10705 Replaced the term "evaluation order" for describing parentheses. New description: "Parentheses may be used to override the precedence rules". Resolves Bug 10716 Added functions to the definitions of item, XDM. Resolves Bug 10679 Eliminated erroneous reference to [err:XPST0081]. Resolves Bug 10680 Added a note to the introduction, specifying that in most contexts, processors are not required to raise errors if a URI is not lexically valid according to [RFC3986] and [RFC3987]. Resolves Bug 10682 Made editorial corrections governing the prefix expression for computed namespace nodes. Resolves Bug 10727 Removed the word "legal", which is no longer used in this specification, replacing with more precise terminology. Modified definition of public/private functions to make the presence or absence of a %private annotation part of the definition. Resolves Bug 10874 Fixed an incorrect group by Bug 10980 Corrected an example in I.1 Joins http://lists.w3.org/Archives/Public/public-qt-comments/2010Nov/0036.html Clarified rules on ItemType Subtype Judgement for functions: annotations in these rules are optional, the rules apply even if no annotations are present; return types are covariant, function arguments are contravariant. Modified description of attribute constructors when the name contains a URILiteral. Clarified that "Evaluating Function Calls" section applies to dynamic function call Bug 10574 Clarified use of 'URILiteral':NCName as a name in element/attribute construction. Resolves Bug 10857 Clarified relationship of conformance to XDM, F&O conformance items. Resolves Bug 13073 Eliminated the phrase "query module", which was not well-defined. Added example for decimal format declaration. Resolves Bug 10859 Clarified contributions of schema import, module import and module declaration to the statically known namespaces. Resolves Bug 8265 Renamed LiteralFunctionItem as NamedFunctionRef. ( 3.1.6 Named Function References Removed the concept of "scope" defined in Appendix C. Resolves Bug 10368 Changed the definition of subtype subtype(A, B)