Module 6 XQuery - Stanford Universityweb.stanford.edu/class/cs345b/slides/XMLDB-M6-Stanford.pdf ·...

39
Module 6 Module 6 XQuery XQuery

Transcript of Module 6 XQuery - Stanford Universityweb.stanford.edu/class/cs345b/slides/XMLDB-M6-Stanford.pdf ·...

Module 6Module 6

XQueryXQuery

01/31/07 2

XML queriesXML queries An XQuery basic structure:An XQuery basic structure:

a a prologprolog + an + an expressionexpression Role of the prolog:Role of the prolog:

Populate the context where the expression is compiled Populate the context where the expression is compiled and evaluatedand evaluated

Prologue contains:Prologue contains: namespace definitionsnamespace definitions schema importsschema imports default element and function namespacedefault element and function namespace function definitionsfunction definitions collations declarationscollations declarations function library importsfunction library imports global and external variables definitionsglobal and external variables definitions etcetc

01/31/07 3

XQuery expressionsXQuery expressionsXQuery Expr :=XQuery Expr :=Constants | Variable | FunctionCalls | PathExpr |Constants | Variable | FunctionCalls | PathExpr |

ComparisonExpr | ArithmeticExpr | LogicExpr |ComparisonExpr | ArithmeticExpr | LogicExpr |

FLWRExpr | ConditionalExpr | QuantifiedExpr |FLWRExpr | ConditionalExpr | QuantifiedExpr |

TypeSwitchExpr | InstanceofExpr | CastExpr |TypeSwitchExpr | InstanceofExpr | CastExpr |

UnionExpr | IntersectExceptExpr |UnionExpr | IntersectExceptExpr |

ConstructorExpr | ValidateExprConstructorExpr | ValidateExpr

Expressions can be nested with full generality !Expressions can be nested with full generality !

Functional programming heritage (ML, Haskell, Lisp)Functional programming heritage (ML, Haskell, Lisp)

01/31/07 4

ConstantsConstantsXQuery grammar has built-in support for:XQuery grammar has built-in support for:

Strings:Strings: “125.0” or ‘125.0’“125.0” or ‘125.0’ Integers:Integers: 150150 Decimal:Decimal: 125.0125.0 Double:Double: 125.e2125.e2

19 other 19 other atomic typesatomic types available via XML Schema available via XML Schema Values can be constructed Values can be constructed

with constructors in F&O doc: with constructors in F&O doc: fn:true(), fn:date(“2002-5-20”)fn:true(), fn:date(“2002-5-20”) by castingby casting by schema validationby schema validation

01/31/07 5

VariablesVariables $ + Qname (e.g. $x, $ns:foo)$ + Qname (e.g. $x, $ns:foo) bound, not assignedbound, not assigned XQuery does not allow variable assignmentXQuery does not allow variable assignment created by created by letlet, , forfor, , some/every, typeswitch some/every, typeswitch

expressions, function parametersexpressions, function parameters example:example:

let $x := ( 1, 2, 3 )let $x := ( 1, 2, 3 )return count($x)return count($x)

above scoping ends at conclusion of above scoping ends at conclusion of return return expressionexpression

01/31/07 6

A built-in function samplerA built-in function sampler fn:document(xs:anyURI)=> document?fn:document(xs:anyURI)=> document? fn:empty(item*) => booleanfn:empty(item*) => boolean fn:index-of(item*, item) => xs:unsignedInt?fn:index-of(item*, item) => xs:unsignedInt? fn:distinct-values(item*) => item*fn:distinct-values(item*) => item* fn:distinct-nodes(node*) => node*fn:distinct-nodes(node*) => node* fn:union(node*, node*) => node*fn:union(node*, node*) => node* fn:except(node*, node*) => node*fn:except(node*, node*) => node* fn:string-length(xs:string?) => xs:integer?fn:string-length(xs:string?) => xs:integer? fn:contains(xs:string, xs:string) => xs:booleanfn:contains(xs:string, xs:string) => xs:boolean fn:true() => xs:booleanfn:true() => xs:boolean fn:date(xs:string) => xs:datefn:date(xs:string) => xs:date fn:add-date(xs:date, xs:duration) => xs:datefn:add-date(xs:date, xs:duration) => xs:date

See Functions and Operators W3C specificationSee Functions and Operators W3C specification

01/31/07 7

AtomizationAtomization fn:data(item*) -> fn:data(item*) -> xs:anyAtomicType* Extracting the “value” of a node, or returning Extracting the “value” of a node, or returning

the atomic valuethe atomic value fn:data(<a>001</a>)fn:data(<a>001</a>)

(“001”, xs:untypedAtomic)(“001”, xs:untypedAtomic) fn:data(validate {<a xsi:type=“xs:integer”>001</a>}) fn:data(validate {<a xsi:type=“xs:integer”>001</a>})

(1, xs:integer)(1, xs:integer) Implicitly applied:

••Arithmetic expressionsArithmetic expressions••Comparison expressionsComparison expressions••Function calls and returnsFunction calls and returns••Cast expressionsCast expressions••Constructor expressions for various kinds of nodesConstructor expressions for various kinds of nodes••order byorder by clauses in FLWOR expressions clauses in FLWOR expressions

01/31/07 8

Constructing sequencesConstructing sequences(1, 2, 2, 3, 3, <a/>, <b/>)(1, 2, 2, 3, 3, <a/>, <b/>)

““,” is the sequence concatenation operator,” is the sequence concatenation operator Nested sequences are flattened:Nested sequences are flattened:

(1, 2, 2, (3, 3)) => (1, 2, 2, 3,3)(1, 2, 2, (3, 3)) => (1, 2, 2, 3,3)

range expressions:range expressions: (1 to 3) => (1, 2,3) (1 to 3) => (1, 2,3)

01/31/07 9

Combining sequencesCombining sequences Union, Intersect, ExceptUnion, Intersect, Except Work only for sequences of nodes, not atomic valuesWork only for sequences of nodes, not atomic values Eliminate duplicates and reorder to document orderEliminate duplicates and reorder to document order

$x := <a/>, $y := <b/>, $z := <c/>$x := <a/>, $y := <b/>, $z := <c/>

($x, $y) union ($y, $z) => (<a/>, <b/>, ($x, $y) union ($y, $z) => (<a/>, <b/>, <c/>)<c/>)

F&O specification provides other functions & F&O specification provides other functions & operators; eg. operators; eg. fn:distinct-values()fn:distinct-values() and and fn:distinct-nodes()fn:distinct-nodes() particularly useful particularly useful

01/31/07 10

Arithmetic expressionsArithmetic expressions1 + 41 + 4 $a div 5$a div 55 div 65 div 6 $b mod 10$b mod 101 - (4 * 8.5)1 - (4 * 8.5) -55.5-55.5

<a>42</a> + 1 <a>baz</a> + 1 <a>42</a> + 1 <a>baz</a> + 1 validate {<a xsi:type=“xs:integer”>42</a> }+ 1validate {<a xsi:type=“xs:integer”>42</a> }+ 1 validate {<a xsi:type=“xs:string”>42</a> }+ 1validate {<a xsi:type=“xs:string”>42</a> }+ 1

Apply the following rules:Apply the following rules: atomizeatomize all operands. if either operand is (), => () all operands. if either operand is (), => () if an operand is untyped, cast to if an operand is untyped, cast to xs:double xs:double (if unable, => (if unable, => error)error) if the operand types differ but can be if the operand types differ but can be promotedpromoted to common type, do so to common type, do so

(e.g.: (e.g.: xs:integerxs:integer can be promoted to can be promoted to xs:doublexs:double)) if operator is consistent w/ types, apply it; result is either atomic if operator is consistent w/ types, apply it; result is either atomic

value or value or errorerror if type is not consistent, throw type exceptionif type is not consistent, throw type exception

01/31/07 11

Logical expressionsLogical expressions expr1 expr1 andand expr2 expr2 expr1 expr1 oror expr2 expr2 fn:notfn:not() as a function() as a function

return return true, false true, false Different from SQLDifferent from SQL

twotwo value logic, value logic, notnot three three value logic value logic Different from imperative languagesDifferent from imperative languages

andand, , oror are commutative in Xquery, but not in Java. are commutative in Xquery, but not in Java. if (($x castable as xs:integer) and (($x cast as xs:integer) eq 2) ) …..if (($x castable as xs:integer) and (($x cast as xs:integer) eq 2) ) …..

Non-deterministicNon-deterministicfalse and error => false false and error => false oror error ! (non-deterministically) error ! (non-deterministically)

• Rules:Rules: first compute the first compute the Boolean Effective Value (BEV)Boolean Effective Value (BEV) for each operand: for each operand:

if (), “”, NaN, 0, then return if (), “”, NaN, 0, then return falsefalse if the operand is of type xs:boolean, return it; if the operand is of type xs:boolean, return it; If operand is a sequence with first item a node, return trueIf operand is a sequence with first item a node, return true else raises an errorelse raises an error

then use standard two value Boolean logic on the two BEV's as appropriatethen use standard two value Boolean logic on the two BEV's as appropriate

01/31/07 12

ComparisonsComparisons

<<, >>testing relative position of one node vs. another (in document order)

Order

is, isnotfor testing identity of single nodes

Node

=, !=, <=, <, >, >=

Existential quantification + automatic type coercion

General

eq, ne, lt, le, gt, ge

for comparing single values

Value

01/31/07 13

Value and general Value and general comparisonscomparisons

<a>42</a> eq “42” true<a>42</a> eq “42” true <a>42</a> eq 42 error<a>42</a> eq 42 error <a>42</a> eq “42.0” false<a>42</a> eq “42.0” false <a>42</a> eq 42.0 error<a>42</a> eq 42.0 error <a>42</a> = 42 true<a>42</a> = 42 true <a>42</a> = 42.0 true<a>42</a> = 42.0 true <a>42</a> eq <b>42</b> true<a>42</a> eq <b>42</b> true <a>42</a> eq <b> 42</b> false<a>42</a> eq <b> 42</b> false <a>baz</a> eq 42 error<a>baz</a> eq 42 error () eq 42 ()() eq 42 () () = 42 false() = 42 false (<a>42</a>, <b>43</b>) = 42.0 true(<a>42</a>, <b>43</b>) = 42.0 true (<a>42</a>, <b>43</b>) = “42” true(<a>42</a>, <b>43</b>) = “42” true ns:shoesize(5) eq ns:hatsize(5) truens:shoesize(5) eq ns:hatsize(5) true (1,2) = (2,3) true(1,2) = (2,3) true

01/31/07 14

Algebraic properties of Algebraic properties of comparisonscomparisons

General comparisons not reflexive, transitiveGeneral comparisons not reflexive, transitive (1,3) = (1,2) (1,3) = (1,2) (but also !=, <, >, <=, >= !!!!!)(but also !=, <, >, <=, >= !!!!!) ReasonsReasons

implicit existential quantification, dynamic castsimplicit existential quantification, dynamic casts Negation rule does not holdNegation rule does not hold

fn:not($x = $y) is not equivalent to $x != $yfn:not($x = $y) is not equivalent to $x != $y General comparison not transitive, not reflexiveGeneral comparison not transitive, not reflexive Value comparisons are Value comparisons are almostalmost transitive transitive

Exception: Exception: xs:decimal due to the loss of precisionxs:decimal due to the loss of precision

Impact on grouping, hashing, indexing, caching !!!

01/31/07 15

XPath expressionsXPath expressions An expression that defines the set of nodes where the An expression that defines the set of nodes where the

navigation starts + a series of selection steps that explain how navigation starts + a series of selection steps that explain how to navigate into the XML treeto navigate into the XML tree

A step:A step: axisaxis ‘::’ ‘::’ nodeTestnodeTest

Axis control the navigation direction in the treeAxis control the navigation direction in the tree attribute, child, descendant, descendant-or-self, parent, selfattribute, child, descendant, descendant-or-self, parent, self The other Xpath 1.0 axes (The other Xpath 1.0 axes (following, following-sibling, preceding, following, following-sibling, preceding,

preceding-sibling, ancestor, ancestor-or-selfpreceding-sibling, ancestor, ancestor-or-self) are optional in XQuery) are optional in XQuery Node test by:Node test by:

Name Name (e.g. publisher, myNS:publisher, *: publisher, myNS:* , *:* )(e.g. publisher, myNS:publisher, *: publisher, myNS:* , *:* ) Kind of itemKind of item (e.g. node(), comment(), text() ) (e.g. node(), comment(), text() ) Type testType test (e.g. element(ns:PO, ns:PoType), attribute(*, xs:integer) (e.g. element(ns:PO, ns:PoType), attribute(*, xs:integer)

01/31/07 16

Examples of path expressionsExamples of path expressions document(“bibliography.xml”)/child::bibdocument(“bibliography.xml”)/child::bib $x/child::bib/child::book/attribute::year$x/child::bib/child::book/attribute::year $x/parent::*$x/parent::* $x/child::*/descendent::comment()$x/child::*/descendent::comment() $x/child::element(*, ns:PoType)$x/child::element(*, ns:PoType) $x/attribute::attribute(*, xs:integer)$x/attribute::attribute(*, xs:integer) $x/ancestors::document(schema-element(ns:PO))$x/ancestors::document(schema-element(ns:PO)) $x/(child::element(*, xs:date) | $x/(child::element(*, xs:date) |

attribute::attribute(*, xs:date)attribute::attribute(*, xs:date) $x/f(.)$x/f(.)

01/31/07 17

Xpath abbreviated syntaxXpath abbreviated syntax Axis can be missingAxis can be missing

By default the child axisBy default the child axis $x/$x/child::child::person -> $x/person person -> $x/person

Short-hands for common axesShort-hands for common axes Descendent-or-selfDescendent-or-self

$x/$x/descendant-or-self::*/child::descendant-or-self::*/child::comment()-> $xcomment()-> $x////comment()comment()

Parent Parent $x/$x/parent::*parent::* -> $x/ -> $x/....

AttributeAttribute$x/$x/attribute::attribute::year -> $x/year -> $x/@@yearyear

SelfSelf$x/$x/self::*self::* -> $x/ -> $x/..

01/31/07 18

Xpath filter predicatesXpath filter predicates Syntax:Syntax:

expression1 expression1 [ [ expression2expression2 ] ] [ ] is an overloaded operator[ ] is an overloaded operator Filtering by position (if numeric value) :Filtering by position (if numeric value) :

/book[3] /book[3] /book[3]/author[1] /book[3]/author[1] /book[3]/author[1 to 2] /book[3]/author[1 to 2]

Filtering by predicate :Filtering by predicate : //book [author/firstname = “ronald”]//book [author/firstname = “ronald”] //book [@price <25]//book [@price <25] //book [count(author [@gender=“female”] )>0 //book [count(author [@gender=“female”] )>0

Classical Xpath mistakeClassical Xpath mistake $x/a/b[1] means $x/a/(b[1]) and not ($x/a/b)[1]$x/a/b[1] means $x/a/(b[1]) and not ($x/a/b)[1]

01/31/07 19

Conditional expressions Conditional expressions

if ( $book/@year <1980 ) if ( $book/@year <1980 ) then “oldTitle”then “oldTitle”else “newTitle”else “newTitle”

Only one branch allowed to raise execution errorsOnly one branch allowed to raise execution errors Impacts scheduling and parallelizationImpacts scheduling and parallelization Else branch mandatoryElse branch mandatory

01/31/07 20

Local variable declarationLocal variable declaration

Syntax :Syntax : let let variablevariable := := expression1 expression1 return return expression2expression2

Example :Example :let $x :=document(“bib.xml”)/bib/book let $x :=document(“bib.xml”)/bib/book return count($x)return count($x)

Semantics :Semantics : bind the bind the variable variable to the result of the to the result of the expression1 expression1 add this binding to the current environmentadd this binding to the current environment evaluate and return evaluate and return expression2expression2

01/31/07 21

FLWFLW(O)(O)R expressionsR expressions Syntactic sugar that combines FOR, LET, IFSyntactic sugar that combines FOR, LET, IF

ExampleExample for $x in //bib/book /* similar to for $x in //bib/book /* similar to FROMFROM in SQL */ in SQL */ let $y := $x/author /* no analogy in SQL */let $y := $x/author /* no analogy in SQL */ where $x/title=“The politics of experience” where $x/title=“The politics of experience” /* similar to /* similar to WHEREWHERE in SQL */ in SQL */ return count($y) /* similarreturn count($y) /* similar to to SELECTSELECT in SQL in SQL */ */

FOR var IN expr

LET var := expr WHERE expr

RETURN expr

01/31/07 22

FLWR expression semantics FLWR expression semantics FLWR expression:FLWR expression:

for $x in //bib/bookfor $x in //bib/book let $y := $x/authorlet $y := $x/author where $x/title=“Ulysses”where $x/title=“Ulysses” return count($y)return count($y)

Equivalent to:Equivalent to: for $x in //bib/bookfor $x in //bib/book return (let $y := $x/authorreturn (let $y := $x/author return return if ($x/title=“Ulysses” )if ($x/title=“Ulysses” ) then count($y)then count($y) else ()else () ))

01/31/07 23

More FLWR expression More FLWR expression examplesexamples

SelectionsSelectionsfor $b in document("bib.xml")//book for $b in document("bib.xml")//book where $b/publisher = “Springer Verlag" and where $b/publisher = “Springer Verlag" and

$b/@year = "1998" $b/@year = "1998" return $b/titlereturn $b/title

JoinsJoinsfor $b in document("bib.xml")//book, for $b in document("bib.xml")//book,

$p in //publisher$p in //publisherwhere $b/publisher = $p/namewhere $b/publisher = $p/namereturn ( $b/title , $p/address)return ( $b/title , $p/address)

01/31/07 24

The “O” in FLWThe “O” in FLW(O)(O)R R expressionsexpressions

Syntactic sugar that combines FOR, LET, IFSyntactic sugar that combines FOR, LET, IF

SyntaxSyntax for $x in //bib/book /* similar to for $x in //bib/book /* similar to FROMFROM in SQL */ in SQL */ let $y := $x/author /* no analogy in SQL */let $y := $x/author /* no analogy in SQL */ [stable] order by ( [expr] [empty-handling ? Asc-vs-desc? Collation?] )+[stable] order by ( [expr] [empty-handling ? Asc-vs-desc? Collation?] )+/* similar to /* similar to ORDER-BYORDER-BY in SQL */ in SQL */ return count($y) /* similarreturn count($y) /* similar to to SELECTSELECT in SQL in SQL */ */

FOR var IN expr

LET var := expr WHERE expr

RETURN expr

01/31/07 25

Node constructorsNode constructors Constructing new nodes:

elements attributes documents processing instructions comments text

Side-effect operation Affects optimization optimization and expression rewriting expression rewriting

Element constructors create local scopes for namespaces Affects optimization optimization and expression rewriting expression rewriting

01/31/07 26

Element constructorsElement constructors A special kind of expression that creates (and A special kind of expression that creates (and

outputs) new elementsoutputs) new elements Equivalent of a Equivalent of a new Object()new Object() in Java in Java

Syntax that mimics exactly the XML syntaxSyntax that mimics exactly the XML syntax <a b=“24”>foo bar</a><a b=“24”>foo bar</a>

is a normal XQuery expression. is a normal XQuery expression. Fixed content vs. computed contentFixed content vs. computed content

<a>{<a>{some-expressionsome-expression}</a>}</a> <a> some fixed content {<a> some fixed content {some-expressionsome-expression} some more fixed } some more fixed

content</a>content</a>

01/31/07 27

Computed element Computed element constructorsconstructors

If even the name of the element is unknown at If even the name of the element is unknown at query time, use the other syntaxquery time, use the other syntax Non XML, but more generalNon XML, but more generalelement {element {name-name-expressionexpression} {} {content-content-expressionexpression} }

let $x := <a b=“1”>3</a>let $x := <a b=“1”>3</a>

return element {fn:node-name($e)} {$e/@*, 2 * return element {fn:node-name($e)} {$e/@*, 2 * fn:data($e)}fn:data($e)}

<a b=“1”>6</a><a b=“1”>6</a>

01/31/07 28

Other node constructorsOther node constructors Attribute constructors: direct (embedded inside Attribute constructors: direct (embedded inside

the element tags) and computedthe element tags) and computed <article date=“{<article date=“{fn:getCurrentDate()fn:getCurrentDate()}”/>}”/> attribute “date” {attribute “date” {fn:getCurrentDate()fn:getCurrentDate()}”}”

Document constructorDocument constructor document {document {expressionexpression}}

Text constructorsText constructors text {text {expressionexpression}}

Other constructors (comments, PI), but no NSOther constructors (comments, PI), but no NS

01/31/07 29

A more complex exampleA more complex example<<livreslivres>>

{for $x in fn:doc(“input.xml”)//book{for $x in fn:doc(“input.xml”)//bookwhere $x/year > 2000 and some $y in $x/author satisfies where $x/year > 2000 and some $y in $x/author satisfies

$y/address/country=“France” $y/address/country=“France”return return <<livrelivre anneeannee=“{$x/year}”>=“{$x/year}”>

<<titretitre>{$x/title/text()}</>{$x/title/text()}</titretitre>> { for $z in $x/( author | editor ){ for $z in $x/( author | editor )

return return if(fn:name($z)=“editor)if(fn:name($z)=“editor)then <then <editeurediteur>{$z/*}</>{$z/*}</editeurediteur>>

else <else <auteurauteur>{$z/*}</>{$z/*}</auteurauteur>> }}</</livrelivre>>}}</</livreslivres>>

01/31/07 30

Quantified expressionsQuantified expressions Universal and existential quantifiersUniversal and existential quantifiers Second order expressionsSecond order expressions

some some variablevariable in in expressionexpression satisfies satisfies expressionexpression every every variablevariable in in expressionexpression satisfies satisfies expressionexpression

Examples:Examples: some $x in //book satisfies $x/price <100some $x in //book satisfies $x/price <100 every $y in //(author | editor) satisfies every $y in //(author | editor) satisfies $y/address/city = “New York”$y/address/city = “New York”

01/31/07 31

Nested scopesNested scopesdeclare namespace declare namespace nsns=“uri1”=“uri1”

for for $x$x in fn:doc(“uri”)/ in fn:doc(“uri”)/nsns::aa

where where $x$x//nsns::b eq 3b eq 3return return

<result xmlns:<result xmlns:nsns=“uri2”>=“uri2”>{ for { for $x$x in fn:doc(“uri”)/ in fn:doc(“uri”)/nsns:a:a return return $x $x / / nsns:b }:b }

</result></result>

Local scopes impact optimization and rewriting !

01/31/07 32

Operators on datatypesOperators on datatypes expression expression instanceofinstanceof sequenceType sequenceType

returns true if its first operand is an instance of the type named in returns true if its first operand is an instance of the type named in its second operandits second operand

expression expression castable ascastable as singleType singleType returns true if first operand can be casted as the given sequence returns true if first operand can be casted as the given sequence

typetype expression expression cast ascast as singleType singleType

used to convert a value from one datatype to anotherused to convert a value from one datatype to another expression expression treat astreat as sequenceType sequenceType

treats an expr as if its datatype is a subtype of its static type (down treats an expr as if its datatype is a subtype of its static type (down cast)cast) typeswitchtypeswitch

case-like branching based on the type of an input expressioncase-like branching based on the type of an input expression

01/31/07 33

Schema validationSchema validation ExplicitExplicit syntax syntax

validate [validation mode] { expression }validate [validation mode] { expression } Validation mode: strict or laxValidation mode: strict or lax Semantics:Semantics:

Translate XML Data Model to InfosetTranslate XML Data Model to Infoset Apply XML Schema validationApply XML Schema validation Ignore identity constraints checksIgnore identity constraints checks Map resulting PSVI to a new XML Data Model instanceMap resulting PSVI to a new XML Data Model instance

It is not a side-effect operationIt is not a side-effect operation

01/31/07 34

Ignoring orderIgnoring order In the original application XML was totally orderedIn the original application XML was totally ordered

Xpath 1.0 preserves the document order through implicit expensive sorting Xpath 1.0 preserves the document order through implicit expensive sorting operations operations

In many cases the order is not semantically meaningfulIn many cases the order is not semantically meaningful The evaluation can be optimized if the order is not requiredThe evaluation can be optimized if the order is not required

OrderedOrdered { { exprexpr } and } and unorderedunordered { { exprexpr } } Affect : path expressions, FLWR without order clause, union, Affect : path expressions, FLWR without order clause, union,

intersect, exceptintersect, except Leads to non-determinismLeads to non-determinism Semantics of expressions is again context sensitiveSemantics of expressions is again context sensitive

let $x:= (//a)[1] unordered {(//a)[1]/b}let $x:= (//a)[1] unordered {(//a)[1]/b}return unordered {$x/b}return unordered {$x/b}

01/31/07 35

Functions in XQueryFunctions in XQuery In-place XQuery functionsIn-place XQuery functions

declare function ns:foo($x as xs:integer) as element()declare function ns:foo($x as xs:integer) as element(){ <a> {$x+1}</a> }{ <a> {$x+1}</a> } Can be recursive and mutually recursiveCan be recursive and mutually recursive

External functionsExternal functions

XQuery functions as database viewsdatabase views

01/31/07 36

How to pass “input” data How to pass “input” data to a query ?to a query ?

External variables (bound through an external API)External variables (bound through an external API)declare variable $x as xs:integer externaldeclare variable $x as xs:integer external

Current item (bound through an external API)Current item (bound through an external API) ..

External functions (bound through an external API)External functions (bound through an external API)declare function ora:sql($x as xs:string) as node()* externaldeclare function ora:sql($x as xs:string) as node()* external

Specific built-in functionsSpecific built-in functions fnfn:doc(:doc(uriuri), fn:collection(), fn:collection(uriuri))

01/31/07 38

Library modules (example)Library modules (example)

module namespace module namespace mod=“moduleURI”;mod=“moduleURI”;

declare namespace ns=“URI1”;declare namespace ns=“URI1”;define variable $mod:zero as define variable $mod:zero as

xs:integer {0}xs:integer {0}define function mod:add($x as define function mod:add($x as

xs:integer, $y as xs:integer)xs:integer, $y as xs:integer) as xs:integeras xs:integer{{

$x+$y$x+$y}}

import module namespace ns=“moduleURI”;ns:add(2, ns:zero)

Library module Importing module

01/31/07 39

XQuery implementationsXQuery implementations Relational databasesRelational databases

Oracle 10g, SQLServer 2005, DB2 ViperOracle 10g, SQLServer 2005, DB2 Viper MiddlewareMiddleware

Oracle, DataDirect, BEA WebLogicOracle, DataDirect, BEA WebLogic DataIntegrationDataIntegration

BEA AquaLogicBEA AquaLogic Commercial XML databaseCommercial XML database

MarkLogicMarkLogic Open source XML databasesOpen source XML databases

BerkeleyDB, eXist, SednaBerkeleyDB, eXist, Sedna Open source Xquery processor (no persistent store)Open source Xquery processor (no persistent store)

Saxon, MXQuery, ZorbaSaxon, MXQuery, Zorba XQuery editors, debuggersXQuery editors, debuggers

StylusStudio, oXygenStylusStudio, oXygen