Module 6 Module 6 XQuery XQuery XML queries XML queries An - - PowerPoint PPT Presentation

module 6 module 6 xquery xquery xml queries xml queries
SMART_READER_LITE
LIVE PREVIEW

Module 6 Module 6 XQuery XQuery XML queries XML queries An - - PowerPoint PPT Presentation

Module 6 Module 6 XQuery XQuery XML queries XML queries An XQuery basic structure: An XQuery basic structure: a a prolog prolog + an + an expression expression Role of the prolog: Role of the prolog: Populate the context


slide-1
SLIDE 1

Module 6 Module 6 XQuery XQuery

slide-2
SLIDE 2

01/31/07 2

XML queries XML queries

 An XQuery basic structure:

An XQuery basic structure:

a a prolog prolog + an + an expression expression

 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 evaluated and evaluated

 Prologue contains:

Prologue contains:

namespace definitions namespace definitions

schema imports schema imports

default element and function namespace default element and function namespace

function definitions function definitions

collations declarations collations declarations

function library imports function library imports

global and external variables definitions global and external variables definitions

 etc

etc

slide-3
SLIDE 3

01/31/07 3

XQuery expressions XQuery expressions

XQuery 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 | ValidateExpr ConstructorExpr | 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)

slide-4
SLIDE 4

01/31/07 4

Constants Constants

XQuery 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: 150 150

 Decimal:

Decimal: 125.0 125.0

 Double:

Double: 125.e2 125.e2

 19 other

19 other atomic types atomic 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 casting

by casting

 by schema validation

by schema validation

slide-5
SLIDE 5

01/31/07 5

Variables Variables

 $ + Qname (e.g. $x, $ns:foo)

$ + Qname (e.g. $x, $ns:foo)

 bound, not assigned

bound, not assigned

 XQuery does not allow variable assignment

XQuery does not allow variable assignment

 created by

created by let let, , for for, , some/every, typeswitch some/every, typeswitch expressions, function parameters expressions, 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 expression expression

slide-6
SLIDE 6

01/31/07 6

A built-in function sampler A built-in function sampler

 fn:document(xs:anyURI)=> document?

fn:document(xs:anyURI)=> document?

 fn:empty(item*) => boolean

fn: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:boolean

fn:contains(xs:string, xs:string) => xs:boolean

 fn:true() => xs:boolean

fn:true() => xs:boolean

 fn:date(xs:string) => xs:date

fn:date(xs:string) => xs:date

 fn:add-date(xs:date, xs:duration) => xs:date

fn:add-date(xs:date, xs:duration) => xs:date

See Functions and Operators W3C specification See Functions and Operators W3C specification

slide-7
SLIDE 7

01/31/07 7

Atomization Atomization

 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 value the 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 expressions

Arithmetic expressions

  • Comparison expressions

Comparison expressions

  • Function calls and returns

Function calls and returns

  • Cast expressions

Cast expressions

  • Constructor expressions for various kinds of nodes

Constructor expressions for various kinds of nodes

  • order by
  • rder by clauses in FLWOR expressions

clauses in FLWOR expressions

slide-8
SLIDE 8

01/31/07 8

Constructing sequences Constructing 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)

slide-9
SLIDE 9

01/31/07 9

Combining sequences Combining sequences

 Union, Intersect, Except

Union, Intersect, Except

 Work only for sequences of nodes, not atomic values

Work only for sequences of nodes, not atomic values

 Eliminate duplicates and reorder to document order

Eliminate 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 &

  • perators; eg.
  • perators; eg. fn:distinct-values()

fn:distinct-values() and and fn:distinct-nodes() fn:distinct-nodes() particularly useful particularly useful

slide-10
SLIDE 10

01/31/07 10

Arithmetic expressions Arithmetic expressions

1 + 4 1 + 4 $a div 5 $a div 5 5 div 6 5 div 6 $b mod 10 $b mod 10 1 - (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> }+ 1 validate {<a xsi:type=“xs:integer”>42</a> }+ 1

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

validate {<a xsi:type=“xs:string”>42</a> }+ 1  Apply the following rules:

Apply the following rules:

 atomize

atomize 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 promoted promoted to common type, do so to common type, do so (e.g.: (e.g.: xs:integer xs:integer can be promoted to can be promoted to xs:double xs: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 error error

 if type is not consistent, throw type exception

if type is not consistent, throw type exception

slide-11
SLIDE 11

01/31/07 11

Logical expressions Logical expressions

expr1

expr1 and and expr2 expr2 expr1 expr1 or

  • r expr2

expr2 fn:not fn:not() as a function () as a function

 return

return true, false true, false

 Different from SQL

Different from SQL

 two

two value logic, value logic, not not three three value logic value logic

 Different from imperative languages

Different from imperative languages

 and

and, , or

  • r 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-deterministic

Non-deterministic

false and error => false false and error => false or

  • r

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 false false

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 true

If operand is a sequence with first item a node, return true

 else raises an error

else raises an error

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

slide-12
SLIDE 12

01/31/07 12

Comparisons Comparisons

<<, >>

testing relative position

  • f one node vs. another

(in document order)

Order is, isnot

for testing identity of single nodes

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

Existential quantification + automatic type coercion

General eq, ne, lt, le, gt, ge

for comparing single values

Value

slide-13
SLIDE 13

01/31/07 13

Value and general Value and general comparisons comparisons

 <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) true

ns:shoesize(5) eq ns:hatsize(5) true

 (1,2) = (2,3) true

(1,2) = (2,3) true

slide-14
SLIDE 14

01/31/07 14

Algebraic properties of Algebraic properties of comparisons comparisons

 General comparisons not reflexive, transitive

General comparisons not reflexive, transitive

 (1,3) = (1,2)

(1,3) = (1,2) (but also !=, <, >, <=, >= !!!!!) (but also !=, <, >, <=, >= !!!!!)

 Reasons

Reasons

implicit existential quantification, dynamic casts implicit existential quantification, dynamic casts  Negation rule does not hold

Negation rule does not hold

 fn:not($x = $y) is not equivalent to $x != $y

fn:not($x = $y) is not equivalent to $x != $y

 General comparison not transitive, not reflexive

General comparison not transitive, not reflexive

 Value comparisons are

Value comparisons are almost almost transitive transitive

 Exception:

Exception:

 xs:decimal due to the loss of precision

xs:decimal due to the loss of precision

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

slide-15
SLIDE 15

01/31/07 15

XPath expressions XPath 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 tree to navigate into the XML tree

 A step:

A step:

 axis

axis ‘::’ ‘::’ nodeTest nodeTest

 Axis control the navigation direction in the tree

Axis control the navigation direction in the tree

 attribute, child, descendant, descendant-or-self, parent, self

attribute, 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-self preceding-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 item

Kind of item (e.g. node(), comment(), text() ) (e.g. node(), comment(), text() )

 Type test

Type test (e.g. element(ns:PO, ns:PoType), attribute(*, xs:integer) (e.g. element(ns:PO, ns:PoType), attribute(*, xs:integer)

slide-16
SLIDE 16

01/31/07 16

Examples of path expressions Examples of path expressions

 document(“bibliography.xml”)/child::bib

document(“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(.)

slide-17
SLIDE 17

01/31/07 17

Xpath abbreviated syntax Xpath abbreviated syntax

 Axis can be missing

Axis can be missing

 By default the child axis

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

 Short-hands for common axes

Short-hands for common axes

 Descendent-or-self

Descendent-or-self

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

 Parent

Parent

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

  • > $x/..

..

 Attribute

Attribute

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

 Self

Self

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

  • > $x/.

.

slide-18
SLIDE 18

01/31/07 18

Xpath filter predicates Xpath filter predicates

 Syntax:

Syntax:

expression1 expression1 [ [ expression2 expression2 ] ]

 [ ] 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 mistake

Classical 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]

slide-19
SLIDE 19

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 errors

Only one branch allowed to raise execution errors

 Impacts scheduling and parallelization

Impacts scheduling and parallelization

 Else branch mandatory

Else branch mandatory

slide-20
SLIDE 20

01/31/07 20

Local variable declaration Local variable declaration

 Syntax :

Syntax :

let

let variable variable := := expression1 expression1 return return expression2 expression2

 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 environment add this binding to the current environment

evaluate and return evaluate and return expression2 expression2

slide-21
SLIDE 21

01/31/07 21

FLW FLW(O) (O)R expressions R expressions

 Syntactic sugar that combines FOR, LET, IF

Syntactic sugar that combines FOR, LET, IF

 Example

Example

for $x in //bib/book /* similar to for $x in //bib/book /* similar to FROM FROM 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 WHERE WHERE in SQL */ in SQL */ return count($y) /* similar return count($y) /* similar

to

to SELECT SELECT in SQL in SQL */

*/ FOR var IN expr LET var := expr WHERE expr RETURN expr

slide-22
SLIDE 22

01/31/07 22

FLWR expression semantics FLWR expression semantics

 FLWR expression:

FLWR expression:

for $x in //bib/book for $x in //bib/book let $y := $x/author let $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/book for $x in //bib/book return (let $y := $x/author return (let $y := $x/author return return if ($x/title=“Ulysses” ) if ($x/title=“Ulysses” ) then count($y) then count($y) else () else () ) )

slide-23
SLIDE 23

01/31/07 23

More FLWR expression More FLWR expression examples examples

 Selections

Selections

for $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/title return $b/title

 Joins

Joins

for $b in document("bib.xml")//book, for $b in document("bib.xml")//book, $p in //publisher $p in //publisher where $b/publisher = $p/name where $b/publisher = $p/name return ( $b/title , $p/address) return ( $b/title , $p/address)

slide-24
SLIDE 24

01/31/07 24

The “O” in FLW The “O” in FLW(O) (O)R R expressions expressions

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

Syntax Syntax

for $x in //bib/book /* similar to for $x in //bib/book /* similar to FROM FROM 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-BY ORDER-BY in SQL */ in SQL */ return count($y) /* similar return count($y) /* similar

to

to SELECT SELECT in SQL in SQL */

*/

FOR var IN expr LET var := expr WHERE expr RETURN expr

slide-25
SLIDE 25

01/31/07 25

Node constructors Node constructors

 Constructing new nodes:  elements  attributes  documents  processing instructions  comments  text

 Side-effect operation

 Affects optimization

  • ptimization and expression rewriting

expression rewriting

 Element constructors create local scopes for

namespaces

 Affects optimization

  • ptimization and expression rewriting

expression rewriting

slide-26
SLIDE 26

01/31/07 26

Element constructors Element constructors

 A special kind of expression that creates (and

A special kind of expression that creates (and

  • utputs) new elements
  • utputs) new elements

 Equivalent of a

Equivalent of a new Object() new Object() in Java in Java

 Syntax that mimics exactly the XML syntax

Syntax 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 content

Fixed content vs. computed content

 <a>{

<a>{some-expression some-expression}</a> }</a>

 <a> some fixed content {

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

slide-27
SLIDE 27

01/31/07 27

Computed element Computed element constructors constructors

 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 syntax query time, use the other syntax

 Non XML, but more general

Non XML, but more general

element { element {name- name-expression expression} { } {content- content-expression expression} } 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>

slide-28
SLIDE 28

01/31/07 28

Other node constructors Other node constructors

 Attribute constructors: direct (embedded inside

Attribute constructors: direct (embedded inside the element tags) and computed the element tags) and computed

 <article date=“{

<article date=“{fn:getCurrentDate() fn:getCurrentDate()}”/> }”/>

 attribute “date” {

attribute “date” {fn:getCurrentDate() fn:getCurrentDate()}” }”

 Document constructor

Document constructor

 document {

document {expression expression} }

 Text constructors

Text constructors

 text {

text {expression expression} }

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

Other constructors (comments, PI), but no NS

slide-29
SLIDE 29

01/31/07 29

A more complex example A more complex example

< <livres livres> > {for $x in fn:doc(“input.xml”)//book {for $x in fn:doc(“input.xml”)//book where $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 < <livre livre annee annee=“{$x/year}”> =“{$x/year}”> < <titre titre>{$x/title/text()}</ >{$x/title/text()}</titre titre> > { 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 <editeur editeur>{$z/*}</ >{$z/*}</editeur editeur> > else < else <auteur auteur>{$z/*}</ >{$z/*}</auteur auteur> > } } </ </livre livre> > } } </ </livres livres> >

slide-30
SLIDE 30

01/31/07 30

Quantified expressions Quantified expressions

 Universal and existential quantifiers

Universal and existential quantifiers

 Second order expressions

Second order expressions

 some

some variable variable in in expression expression satisfies satisfies expression expression

 every

every variable variable in in expression expression satisfies satisfies expression expression

 Examples:

Examples:

 some $x in //book satisfies $x/price <100

some $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”

slide-31
SLIDE 31

01/31/07 31

Nested scopes Nested scopes

declare namespace declare namespace ns ns=“uri1” =“uri1” for for $x $x in fn:doc(“uri”)/ in fn:doc(“uri”)/ns ns: :a a where where $x

$x/ /ns ns: :b eq 3 b eq 3

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

</result> </result> Local scopes impact optimization and rewriting !

slide-32
SLIDE 32

01/31/07 32

Operators on datatypes Operators on datatypes

expression expression instanceof instanceof 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 operand its second operand expression expression castable as castable 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 type type expression expression cast as cast as singleType singleType

 used to convert a value from one datatype to another

used to convert a value from one datatype to another expression expression treat as treat 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) typeswitch typeswitch

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

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

slide-33
SLIDE 33

01/31/07 33

Schema validation Schema validation

 Explicit

Explicit syntax syntax

validate [validation mode] { expression } validate [validation mode] { expression }

 Validation mode: strict or lax

Validation mode: strict or lax

 Semantics:

Semantics:

 Translate XML Data Model to Infoset

Translate XML Data Model to Infoset

 Apply XML Schema validation

Apply XML Schema validation

 Ignore identity constraints checks

Ignore identity constraints checks

 Map resulting PSVI to a new XML Data Model instance

Map resulting PSVI to a new XML Data Model instance

 It is not a side-effect operation

It is not a side-effect operation

slide-34
SLIDE 34

01/31/07 34

Ignoring order Ignoring order

 In the original application XML was totally ordered

In 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

  • perations
  • perations

 In many cases the order is not semantically meaningful

In many cases the order is not semantically meaningful

 The evaluation can be optimized if the order is not required

The evaluation can be optimized if the order is not required

 Ordered

Ordered { { expr expr } and } and unordered unordered { { expr expr } }

 Affect : path expressions, FLWR without order clause, union,

Affect : path expressions, FLWR without order clause, union, intersect, except intersect, except

 Leads to non-determinism

Leads to non-determinism

 Semantics of expressions is again context sensitive

Semantics 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}

slide-35
SLIDE 35

01/31/07 35

Functions in XQuery Functions in XQuery

 In-place XQuery functions

In-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 recursive

Can be recursive and mutually recursive

 External functions

External functions

XQuery functions as database views database views

slide-36
SLIDE 36

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 external declare 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()* external declare function ora:sql($x as xs:string) as node()* external

 Specific built-in functions

Specific built-in functions

fn fn:doc(

:doc(uri uri), fn:collection( ), fn:collection(uri uri) )

slide-37
SLIDE 37

01/31/07 37

XQuery prolog XQuery prolog

Version Declaration Module Declaration Boundary-space Declaration Default Collation Declaration Base URI Declaration Construction Declaration Ordering Mode Declaration Empty Order Declaration Copy-Namespaces Declaration Schema Import Module Import Namespace Declaration Default Namespace Declaration Variable Declaration Variable Declaration Function Declaration Function Declaration

slide-38
SLIDE 38

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:integer as xs:integer { { $x+$y $x+$y } } import module namespace ns=“moduleURI”; ns:add(2, ns:zero)

Library module Importing module

slide-39
SLIDE 39

01/31/07 39

XQuery implementations XQuery implementations

 Relational databases

Relational databases

 Oracle 10g, SQLServer 2005, DB2 Viper

Oracle 10g, SQLServer 2005, DB2 Viper

 Middleware

Middleware

 Oracle, DataDirect, BEA WebLogic

Oracle, DataDirect, BEA WebLogic

 DataIntegration

DataIntegration

 BEA AquaLogic

BEA AquaLogic

 Commercial XML database

Commercial XML database

 MarkLogic

MarkLogic

 Open source XML databases

Open source XML databases

 BerkeleyDB, eXist, Sedna

BerkeleyDB, eXist, Sedna

 Open source Xquery processor (no persistent store)

Open source Xquery processor (no persistent store)

 Saxon, MXQuery, Zorba

Saxon, MXQuery, Zorba

 XQuery editors, debuggers

XQuery editors, debuggers

 StylusStudio, oXygen

StylusStudio, oXygen