Type Declarations
Some expressions, namely FLWORs, quantified expressions, and global variable declarations, allow the use of a type declaration to force the static type of an expression. A type declaration uses the keyword as, followed by a sequence type. The sequence types used in these expressions follow the syntax described in Chapter 11.
Type Declarations in FLWORs
Sequence types can be used in the for and let clauses of FLWORs to declare the type of variable being bound. In this case, the type declaration appears immediately after the variable name, as in Example 14-6.
Example 14-6. A FLWOR with a type declaration
for $prod as element(*,ProductType) in doc("catalog.xml")/catalog/*
order by $prod/name
return $prod/nameThe sequence type element(*,ProductType) is specified as the type of the variable $prod. Without the type declaration, this query might raise a type error using a processor that implements static typing, if the schema allows the possibility of catalog having children that don't themselves have name children. The type declaration serves as a way of telling the processor, "I know that all the children of catalog will be valid elements of type ProductType, which all have name children, so don't raise a static error. If it turns out I'm wrong, you can raise a dynamic error later."
With the type declaration, this error checking is postponed to evaluation time. When the query is evaluated, if the value of $prod does not have the type ProductType, a type error is raised. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access