Download presentation
Presentation is loading. Please wait.
1
Static Typing in XQuery Based on Xquery from the Experts [Katz], chap 4 Presented by Iris Rudner
2
Intro Xquery implementations must support dynamic typing, and may support static typing. Objective: How to use the Xquery type system to write type-safe queries, how to understand and resolve type errors and how to work around the type system when necessary.
3
The Benefits of Static Typing Can help by detecting common type errors during static analysis instead of being discovered only when the program is run. A type error occurs when the type of an expression is not compatible with the type required by the context in which the expression is used.
4
Static typing is conservative. For example: expression of type element(surgeon) | element(plumber) in a context requiring element(surgeon) Static typing allows to detect all type errors. Cannot detect errors such as divide-by-zero or array-bounds-overflow. The Benefits of Static Typing (cont.)
5
An Xquery Programming Scenario XML Schema for the Relational Auction Data: http://example.com.auctionhttp://www.w3.org/2001/XMLSchema
7
… etc.
8
Relational Auction (partial) Data in XML: Tom Jones B Red Bicycle 1999-01-05 1999-01-20 40 45 1999-01-11
9
The desired output is an XHTML document that can be rendered by a browser :
10
XML Schema for XHTML: <xs:schema targetNamespace="http://www.w3.org/2001/xhtml" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns = "http://www.w3.org/2001/xhtml">
11
XML Schema for XHTML – cont. : …
12
Xquery: [1] default element namespace = "http://www.example.com/auction" [2] declare namespace x = "http://www.w3.org/1999/xhtml" [3] define variable $base := xs:anyURI("http://www.example.com/auction/") [4] define function makeURI ($resource as xs:string) as xs:anyURI { [5] xs:anyURI(fn:concat(xs:string($base), $resource)) [6] } [7] let $auction := $input/auction [8] return [9] [10] [11] Auctions [12] [13] [14] Item Name [15] Seller [16] Last Bid [17] Closes On [18] [19] { [20] for $article in $auction/articles/article[start_date <= date()]
13
Xquery – cont. : [21] let $last_bid := $auction/bids/bid[articleno/@idref = $article/@id][last()] [22] return [23] [24] [25] { data($article/anme) } [26] [27] [28] { [29] fn:data($auction/users/user[@id = $article//@idref]/name) [30] } [31] [32] { fn:data($last_bid/amount) } [33] { fn:data($last_bid/date) } [34] [35] } [36] [37] [38]
14
Debugging Why is the table such a mess ???
15
[12] … [13] [14] Item Name ….. [18] … [22] return [23] [24] [25] {data($article/anme) } [26] [27] [28] { [29] fn:data($auction/users/user[@id = $article//@idref]/name) [30] } [31] [32] { fn:data($last_bid/amount) } [33] { fn:data($last_bid/date) } [34] [35] } …. A closer look at the query: tr and td tags are inverted
16
Debugging – cont. Where are the Item Names ???
17
[25] {data($article/anme) } should be: [25] {data($article/name) } Debugging – cont.
18
Are we done ???
19
Debugging – cont. … [28] … Xquery – link to seller’s details : Lets see which descendants of article has an idref attribute …
20
XML Schema: … xs:anyType possibly: Line [28]: Run-time type error. Argument to function ‘makeURI’ contains more than one value.
21
Debugging – cont. correction: [28] It took us 4 cycles of debugging by running the query and then changing the query…
22
Validation It is important to validate the formats of the input and output documents. To enable validation – explicitly import the schemas of the input and output, and explicitly validate the input data. No need to explicitly validate the output data, because element constructors validate the elements they create.
23
Validation – cont. [1] import schema default element namespace = "http://www.example.com/auction“ at “auction.xsd” [2] import schema namespace x = "http://www.w3.org/1999/xhtml" at “xhtml.xsd” [2a] default validation strict … [7] let $auction := validate { $input } The query will raise a run-time error of the input document does not conform to the auction schema or if the output document does not conform to the XHTML schema. Requires a declaration for the element
24
When running our query we get the error message: Validation error: Missing ‘x:head’ element in x:html element. Lets look at the XHTML schema: … … Whereas the query: … [9] [10] ….
26
Validation – cont. How would validation affect our earlier debugging cycles? Detects the inverted tr and td tags. Fails to detect the misspelled element name. Fails to detect the error which occurs for input data in which description elements contain idref attributes.
27
Static Typing Validation detects the presence of certain types of error in the format of the data. Static typing guarantees their absence. It can spot errors during static analysis rather than at run-time. It can detect many errors at once. Not dependant on the input.
28
Static Typing Line [10]: Element ‘x:body: encountered where element ‘x:head’ expected. Line [13]: Element ‘x:td: encountered where element ‘x:tr’ expected. Line [23]: Element ‘x:td: encountered where element ‘x:tr’ expected. Line [25]: Expression ‘$article/anme’ is always empty. Line [28]: Argument to function ‘makeURI’ has actual type (attribute(@idref) | attribute(@idref, xs:anySimpleType) )+ instead of expected type ‘xs:string’. The result of static typing our query:
29
Getting Started with Types Coming up: How the type system assigns a type to different kinds of expressions. Including: literals & operators, variables, function calls, conditionals, paths, FLWORs and element constructors.
30
XML Schema and Xquery types Xquery’s type system is based on XML Schema. But, it is simpler and more concise, for the sake of type checking. More on the relationship between XML Schema and Xquery’s type system in the following lecture (chap 5).
31
XML Schema and Xquery types XML Schema – global element: formal type notation: define element user of type User define element rating of type xs:string In XML Schema, element declarations may be global, at the top level, or local, nested within a type declaration.
32
XML Schema and Xquery types – cont. XML Schema – local elements, unnamed types & complex types: <xs:element name="first“ type="xs:string“ minOccurs="0"/> formal type notation: define type User { attribute id of type xs:ID, element name of type AnonymousType1, element rating ? } define type AnonymousType1{ element first of type xs:string ?, element last of type xs:string }
33
XML Schema and Xquery types – cont. XML Schema – simple type: formal type notation: define type IntegerList {xs:integer + } In the formal type notation: List types are formed using ?, + & *. Union types are formed using the choice operator |.
34
XML Schema – the NewUser type derived by restriction of the type User : formal type notation – type declarations for NewUser : define type NewUser restricts User { attribute id of type xs:ID, element name of type AnonymousType2, element rating } define type AnonymousType2 { element first of type xs:string, element last of type xs:string } define element newuser of type NewUser
35
XML Schema and Xquery types – cont. define function user-name($user as element(*,user)) as xs:string {…} Can be applied to either a user or newuser element: All types are derived from xs:anyType. All simple types are derived from xs:anySimpleType.
36
Values Xquery expression evaluates to a value in the Xquery data model. Every Value is a sequence of individual items. An item is either an atomic value or a node. Every atomic value, element node and attribute node has an associated Xquery type. The process of XML Schema validation specifies how elements and attributes are labeled with types.
37
Values – cont. XML input document: Mary Doe A Xquery values representation: element user of type User { attribute id of type xs:ID { “U02” }, element name of type AnonymousType1{ element first of type xs:string {“Mary”}, element last of type xs:string {“Doe”}, }, element rating of type xs:string { “A” } } If we apply fn:data to the first element, we get the value xs:string(“Mary”).
38
Relating Values and Types Types are used ay analysis time and at evaluation time. At evaluation time, the value of a query depends upon the types that label values. It’s possible to refer to type labels explicitly: //element(*, x:Block.type) Both evaluation and type assignment proceed bottom-up.
39
Literals and Operators How does the static type system assigns types to expressions? Literals: “hello” has type xs:string 42 has type xs:integer 42.00 has type xs:decimal4.2e1 has type xs:double arithmetic operations: 42 + 69 has type xs: integer 42 + 69.00 has type xs: decimal order of promotion: xs:integer -> xs:decimal ->xs:float -> xs:double
40
Variables let $z := 1+2 return $z+$z has type xs:integer let $x as xs:integer := 1+2 return $x+$x has type xs:integer Implicit: Explicit: let $x := xs:double(1+2) return $x+$x has type xs:double let $x as xs:decimal := 1+2 return $x+$x has type xs: decimal let $x as xs:double := 1+2 return $x+$x is a static type error xs:integer is not a subtype of xs:double
41
Functions function call: fn:concat(“http://www.example.com/auction/”, “1001”) has type xs:string function signature: fn:concat( $op1 as xs:string ?, $op2 as xs:string ? ) as xs:string fn:concat( (), “1001”) has type xs:string The argument type must derive from the required type or can be promoted to it: fn:concat(10e1, “1001”) is a static type error
42
unlike arithmetic operators, there’s no notion of promotion: Conditionals if ($x<$y) then 3 else 4 has type xs:integer if ($x<$y) then “three” else 4.00 has type ( xs:string | xs:decimal ) if ($x<$y) then 4.2e1 else 69 has type ( xs:double | xs:integer ) unless arithmetic is performed on an operand expression of type ‘union’: (if ($x<$y) then 4.2e1 else 69) + 0.5 has type ( xs:double | xs:decimal )
43
Path Expressions $auction/articles has type element(articles) $auction/articles/article has type element(articles)+ $auction/itesm/article is a static type error (has type empty()) assume $auction has type element(auction) : $auction/(articles | users) has type ( element(articles) | element(users) )+ $auction/(articles | users) doesn’t have type ( element(users), element(articles) )
44
Predicates $auction/articles/article[start_date <= date()] has type element(article)* $auction/articles/article[@id = $id] has type element(article)* exactly-one($auction/articles/article[@id = $id]) has type element(article) zero-or-one($auction/articles/article[@id = $id]) has type element(article)? one-or-more($auction/articles/article[@id = $id]) has type element(article)+
45
FLWOR Expressions for $article in $articles return $article/end_date - $article/start_date has type xdt:dayTimeDuration+ assume $articles has type element(article)+ : for $article in $articles[start_date <= current_date()] return $article/end_date - $article/start_date has type xdt:dayTimeDuration*
46
Element Construction Objective: how to construct data. Simplest way – include literal XML data in a query : Red Bycicle 1999-01-05 1999-01-20 40 has type element(article) At evaluation time, the element is constructed and then validated.
47
Element Construction – cont. Using computed data in a constructor: define function bargain ($a as element(article)) as element(article) { { $a/@id, $a/name, $a/seller, { fn:current-date() } { fn:current-date() + ($a/end_date - $a/start_date) } { $a/reserve_price * 0.80 } } has type element(article)
48
Element Construction – cont. Using computed data in a constructor – bad example: define function bargain ($a as element(article)) as element(article){ { $a/name, $a/seller, { fn:current-date() } { $a/end_date - $a/start_date } { $a/reserve_price * 0.80 } } the type system detects 2 errors. no id attribute type expected for end_date element is xs:date. the type of the expression is xs:dayTimeDuration.
49
Validation Context let $first := "Mary", $last := "Doe", $rating := "A“ return { if (fn:string-length($first) > 10) then () else { $first } } { $last } { if ($rating > "C") then () else { $rating } } validated in global context validated in user context validated in user/name context validation context specified by lexical scope of constructors:
50
Validation Context – cont. let $first := validate context user/name { Mary }, $last := validate context user/name { Doe }, $rating := validate context user { A } return { if (fn:string-length($first) > 10) then () else $first,$last } if ($rating > "C") then () else $rating } validation context specified explicitly in validate expression: the first, last & rating elements are no longer lexically nested within the user and name elements => validation context must be explicitly given.
51
Conclusions What have we seen? The benefits of static typing. How Xquery infers the type for each expression during static analysis. Common errors that can be detected by static typing, including misspelled names in path expressions and constructors.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.