The World Wide Web Consortium (W3C) defines a set of language features and functions for XQuery. The BEA AquaLogic Data Services Platform XQuery engine fully supports these language features with one exception (modules) and also supports a robust subset of functions and adds a number of implementation-specific functions and language keywords.
This chapter describes the function and language implementation and extensions in the XQuery engine.
The chapter includes the following topics:
AquaLogic Data Services Platform supports the W3C Working Draft “XQuery 1.0 and XPath 2.0 Functions and Operators” dated 23 July 2004 (http://www.w3.org/TR/2004/WD-xpath-functions-
20040723/). In addition, AquaLogic Data Services Platform supports a number of functions that are enhancements to the XQuery specification, which you can recognize by their extended function prefix fn-bea:
. For example, the full XQuery notation for an extended function is: fn-bea:function_name.
This section describes the BEA XQuery function extensions, and contains the following topics:
Table 2-1 provides an overview of the BEA XQuery function extensions.
Returns either the full result of the primary expression, or the full result of the alternate expression in cases when the primary XQuery expression fails.
|
||
AquaLogic Data Services Platform (ALDSP) uses the role-base security policies of the underlying WebLogic platform to control access to data resources. A security policy is a condition that must be met for a secured resource to be accessed. If the outcome of condition evaluation is false — given the policy, requested resource, and user context — access to the resource is blocked and associated data is not returned.
Once the security policies have been configured using the AquaLogic Data Services Platform Console, you can use the security function extensions described in this section to determine:
This section describes the following AquaLogic Data Services Platform access control function extensions to the BEA implementation of XQuery:
The fn-bea:is-access-allowed
function checks whether a user associated with the current request context can access the specified resource, which is denoted by a resource name and a data service identifier. The function has the following signature:
fn-bea:is-access-allowed($resource as xs:string, $data\service as xs:string) as xs:boolean
where $resource
is the name of the resource, and $dataservice
is the resource identifier.
This function makes a call to the WebLogic security framework to check access for the specified resource. An example is shown below.
if (fn-bea:is-access-allowed("CustomerProfile/ssn",
"ld:DataServices/CustomerProfile.ds"))
then fn:true()
The fn-bea:is-user-in-group
function checks whether the current user is in the specified group. This function analyzes the WebLogic authenticated subject for appropriate group membership.
This function has the following signature:
fn-bea:is-user-in-group($group as xs:string) as xs:boolean
where $group
is the group to test against the current user.
Note: | This operation is not automatically authenticated. |
The fn-bea:is-user-in-role
function checks whether the current user is in the specified global role. This function obtains a list of roles from the WebLogic security framework.
The function has the following signature:
fn-bea:is-user-in-role($role as xs:string) as xs:boolean
where $role
is the role to test against the current user.
Note: | This operation is not automatically authenticated. |
The fn-bea:userid()
function returns the identifier of the user making the request for the protected resource.
The function has the following signature:
This section describes the following duration, date, and time function extensions to the BEA implementation of XQuery:
The fn-bea:date-from-dateTime()
function converts a dateTime
to a date
, and returns the date part of the dateTime
value.
The function has the following signature:
fn-bea:date-from-dateTime($dateTime as xs:dateTime?) as xs:date?
where $dateTime
is the date and time.
The fn-bea:date-from-string-with-format
function returns a new date
value from a string source value according to the specified pattern.
The function has the following signature:
fn-bea:date-from-string-with-format($format as xs:string?, $dateString as xs:string?) as xs:date?
where $format
is the pattern and $dateString
is the date. For more information about specifying patterns, see Date and Time Patterns.
fn-bea:date-from-string-with-format("yyyy-MM-dd G", "2005-06-22 AD")
returns the specified date in the current time zone.fn-bea:date-from-string-with-format("yyyy-MM-dd", "2002-July-22")
generates an error because the date string does not match the specified format.fn-bea:date-from-string-with-format(“yyyy-MMM-dd”, “2005-JUL-22”)
returns the specified date in the current time zone.
The fn-bea:date-to-string-with-format
function returns a date string with the specified pattern.
The function has the following signature:
fn-bea:date-to-string-with-format($format as xs:string?, $date as xs:date?) as xs:string?
where $format
is the pattern and $date
is the date. For more information about specifying patterns, see Date and Time Patterns.
The fn-bea:dateTime-from-string-with-format
function returns a new dateTime
value from a string source value according to the specified pattern.
The function has the following signature:
fn-bea:dateTime-from-string-with-format($format as xs:string?, $dateTimeString as xs:string?) as xs:dateTime?
where $format
is the pattern and $dateTimeString
is the date and time. For more information about specifying patterns, see Date and Time Patterns.
fn-bea:dateTime-from-string-with-format("yyyy-MM-dd G", "2005-06-22 AD")
returns the specified date, 12:00:00AM in the current time zone.fn-bea:dateTime-from-string-with-format("yyyy-MM-dd 'at' hh:mm", "2005-06-22 at 11:04")
returns the specified date, 11:04:00AM in the current time zone.fn-bea:dateTime-from-string-with-format("yyyy-MM-dd", "2005-July-22")
generates an error because the date string does not match the specified format.fn-bea:dateTime-from-string-with-format(“yyyy-MMM-dd”, “2005-JUL-22”)
returns 12:00:00AM in the current time zone.
The fn-bea:dateTime-to-string-with-format
function returns a date and time string with the specified pattern.
The function has the following signature:
fn-bea:dateTime-to-string-with-format($format as xs:string?, $dateTime as xs:dateTime?) as xs:string?
where $format
is the pattern and $dateTime
is the date and time. For more information about specifying patterns, see Date and Time Patterns.
The fn-bea:time-from-dateTime
function returns the time from a dateTime
value.
The function has the following signature:
fn-bea:time-from-dateTime($dateTime as xs:dateTime?) as xs:time?
where $dateTime
is the date and time.
The fn-bea:time-from-string-with-format
function returns a new time value from a string source value according to the specified pattern.
The function has the following signature:
fn-bea:time-from-string-with-format($format as xs:string?, $timeString as xs:string?) as xs:time?
where $format
is the pattern and $timeString
is the time. For more information about specifying patterns, see Date and Time Patterns.
The fn-bea:time-to-string-with-format
function returns a time string with the specified pattern.
The function has the following signature:
fn-bea:time-to-string-with-format($format as xs:string?, $time as xs:time?) as xs:string?
where $format
is the pattern and $time
is the time. For more information about specifying patterns, see Date and Time Patterns.
You can construct date and time patterns using standard Java class symbols. Table 2-2 outlines the pattern symbols you can use.
Repeat each symbol to match the maximum number of characters required to represent the actual value. For example, to represent 4 July 2002, the pattern is d MMMM yyyy. To represent 12:43 PM, the pattern is hh:mm a.
This section describes the following AquaLogic Data Services Platform execution control function extensions to the BEA implementation of XQuery:
The fn-bea:async
function evaluates an XQuery expression asynchronously, using a buffer to control data flow between threads of execution.
The function has the following signature:
fn-bea:async($expression as item()*) as item()*
where $expression
is the XQuery expression to evaluate asynchronously.
The fn-bea:async
function enables asynchronous execution of Web services to reduce problems caused by the latency of these services.
Note: | Asynchronous web services do not propagate the transaction context to other threads, regardless of the transaction settings. Asynchronous operations are likewise unable to start new transactions. |
In the following example, CUSTOMER
is a database table while the getCreditScore
functions are Web services offered by two credit rating agencies.
for $cust in db:CUSTOMER()
where $cust/ID eq $param
return
let $score1:= fn-bea:async(exper:getCreditScore($cust/SSN), 2),
$score2:= fn-bea:async(equi:getCreditScore($cust/SSN), 2)
return
if (fn:abs($score1 - $score2) < $threshold)
then fn:avg(($score1, $score2))
else fn:max(($score1, $score2))
The fn-bea:fence
function enables you to define optimization boundaries, dividing queries into islands within which optimizations should occur while preventing optimizations across boundaries. You might consider using the fn-bea:fence
function when building a query incrementally.
The function has the following signature:
fn-bea:fence($expression as item()*) as item()*
where $expression
is the input expression.
The fn-bea:fence
function is a pass-through function that does not change the input stream, but indicates to the optimizer that global rewritings should not occur across itself. Specifically, the fn-bea:fence
function stops the following rewritings: view unfolding, loop unrolling, constant folding, and Boolean optimizations.
The timeout functions return either of the following:
Timeout functions are designed to be highly configurable. In the case of an error condition, the function can return either a single $alt
expression or it can return more detailed information as $timeout
and $failure
.
The difference between the two functions fn-bea-timeout( )
and fn-bea-timeout-with-label( )
is that the latter returns $label
along with other auditing information when an error condition is encountered.
The fn-bea:timeout( )
function has the following signature:
fn-bea:timeout($seq as item()*,
$millisec as xs:integer,
$timeout as item()*,
$failure as item()*) as item()*
where $seq
is the primary XQuery expression to evaluate, $millisec
is the timeout value in milliseconds, $timeout
is returned if the evaluation of $seq
takes more than $millis
milliseconds to execute. $failure
is returned if the evaluation of $seq
raises an error.
Alternatively, you can replace the $timeout
and $failure
parameters with a single $alt
parameter. The result of $alt
will then be returned if a timeout or other error occurs.
The fn-bea:timeout-with-label( )
function has the following signature:
fn-bea:timeout-with-label($seq as item()*,
$millisec as xs:integer,
$timeout as item()*
$failure as item(),
$label as xs:string) as item()*
where $label
represents information provided to the audit record.
Both functions return the result of evaluating $seq
if the evaluation of $seq
:
If an error does occur or the millisecond limit is exceeded, the alternate expression is returned along with the audit record.
If the evaluation of $millis
or $alt
raises an error, the error is reported in the usual way. That is, neither of the functions attempts to handle the returned error.
If — for a specific instance of one of these functions in a query — the evaluation of $seq
raises an error or “times out”, all subsequent evaluations of this instance during the same query evaluation will return $timeout
and $failure
(or $alt
). No attempt to re-evaluate $seq
is made in such a case.
You can use the timeout functions in the following ways:
Note that the timeout functions immediately return the alternative expression in cases when accessing the data source causes an error.
Here is an example where $param
is a external parameter:
for $cust in db:CUSTOMER()
where $cust/ID eq $param
return
fn-bea:timeout(exper:getCreditScore($cust/SSN), 200,
fn-bea:timeout(equi:getCreditScore($cust/SSN), 200,
fn:error()
)
)
The fn:bea:fail-over
and fn:bea:fail-over-with-label
functions return the result of evaluating $seq if the evaluation of $seq does not raise an exception. If it does raise an exception, $alt is returned. Both functions are polymorphic and their static return type is the union of the static types of $seq
and $alt
.
The functions have the following signatures:
fn-bea:fail-over($seq as item()*,
$alt as item()*) as item()*
fn-bea:fail-over-with-label($seq as item()*,
$alt as item()*,
$label as xs:string) as item()*
If $alt
is returned the audit record contains:
If the evaluation of $seq
raises an exception, all subsequent evaluations of this instance during the same query evaluation will return $alt
. No attempt to re-evaluate $seq
is made. If the evaluation of $alt raises an exception, it is simply reported. No attempt is made to handle the error.
The fn:bea:fail-over-retry
and fn:bea:fail-over-retry-with-label
functions return the result of evaluating $seq if the evaluation of $seq does not raise an exception. If it does raise an exception, $alt is returned.
In contrast to the fn:bea:fail-over
and fn:bea:fail-over-with-label
functions, however, the fn:bea:fail-over-retry
and fn:bea:fail-over-retry-with-label
functions re-evaluate $seq for each subsequent evaluation even if the evaluation of $seq raises an error.
The fn:bea:fail-over-retry
and fn:bea:fail-over-retry-with-label
functions have the following signatures:
fn-bea:fail-over-retry($seq as item()*,
$alt as item()*) as item()*
fn-bea:fail-over-retry-with-label($seq as item()*,
$alt as item()*,
$label as xs:string) as item()*
The fn-bea:fail-over( )
functions can be used in two ways:
This section describes the following numeric function extensions to the BEA implementation of XQuery:
The fn-bea:format-number
function converts a double to a string using the specified format pattern.
The function has the following signature:
fn-bea:format-number($number as xs:double, $pattern as xs:string) as xs:string
where $number
represents the double number to be converted to a string, and $pattern
represents the pattern string. The format of this pattern is specified by the JDK 1.5.0 DecimalFormat
class. (For information on DecimalFormat and other JDK 1.5.0 Java classes see:
http://java.sun.com/j2se/1.5.0.)
The fn-bea:decimal-round
function returns a decimal value rounded to the specified precision (scale) or to the nearest whole number.
The function has the following signatures:
fn-bea:decimal-round($value as xs:decimal?, $scale as xs:integer?) as xs:decimal?
fn-bea:decimal-round($value as xs:decimal?) as xs:decimal?
where $value
is the decimal value to round and $scale
is the precision with which to round the decimal input. A scale value of 1 rounds the input to tenths, a scale value of 2 rounds it to hundreths, and so on.
The fn-bea:decimal-truncate
function returns a decimal value truncated to the specified precision (scale) or to the nearest whole number.
The function has the following signatures:
fn-bea:decimal-truncate($value as xs:decimal?, $scale as xs:integer?) as xs:decimal?
fn-bea:decimal-truncate($value as xs:decimal?) as xs:decimal?
where $value
is the decimal value to truncate and $scale
is the precision with which to truncate the decimal input. A scale value of 1 truncates the input to tenths, a scale value of 2 truncates it to hundreths, and so on.
This section describes the following function extensions to the BEA implementation of XQuery:
The fn-bea:get-property
function enables you to write data services that can change behavior based on external influence. This is an implicit way to parameterize functions.
The function first checks whether the property has been defined using the AquaLogic Data Services Console. If so, it returns this value as a string. In cases when the property is not defined, the function returns the default value.
The function has the following signature:
fn-bea:get-property($propertyName as xs:string, $defaultValue as xs:string) as xs:string
where $propertyName
is the name of the property, and $defaultValue
is the default value returned by the function.
The fn-bea:inlinedXML
function parses textual XML and returns an instance of the XQuery 1.0 Data Model.
The function has the following signature:
fn-bea:inlinedXML($text as xs:string) as node()*
where $text
is the textual XML to parse.
The fn-bea:rename
function renames an element or a sequence of elements.
The function has the following signature:
fn-bea:rename($oldelements as element()*, $newname as element()) as element()*)
where $oldelements
is the sequence of elements to rename, and $newname
is an element from which the new name and type are extracted.
For each element in the original sequence, the fn-bea:rename function returns a new element with the following:
for $c in CUSTOMER()
return
<CUSTOMER>
{fn-bea:rename($c/FIRST_NAME, <FNAME/>)}
{fn-bea:rename($c/LAST_NAME, <LNAME/>)}
</CUSTOMER>
In the above, if CUSTOMER()
returns:
<CUST><FIRST_NAME>John</FIRST_NAME><LAST_NAME>Jones</LAST_NAME></CUST>
<CUSTOMER><FNAME>John</FNAME><LNAME>Jones</LNAME></CUSTOMER>
This section describes the following QName function extensions to the BEA implementation of XQuery:
The fn-bea:QName-from-string
function creates an xs:QName
and uses the value of $param
as its local name without a namespace.
The function has the following signature:
fn-bea:QName-from-string($name as xs:string) as xs:QName
where $name
is the local name.
This section describes the following sequence function extensions to the BEA implementation of XQuery:
The fn-bea:interleave
function interleaves the specified arguments. The function has the following signature:
fn-bea:interleave($item1 as item()*, $item2 as xdt:anyAtomicType) as item()*
where $item1
and $item2
are the items to interleave.
For example, fn-bea:interleave((<a/>, <b/>, </c>), " ")
returns the following sequence:
This section describes the following string function extensions to the BEA implementation of XQuery:
The fn-bea:match
function returns a list of two integers specifying the characters in the string input that match the input regular expression (or an empty list, if none found). When the function returns a match, the first integer represents the index of (the position of) the first character of the matching substring and the second integer represents the number of matching characters. The function has the following signature:
fn-bea:match($source as xs:string?, $regularExp as xs:string?) as xs:int*
where $source
is the input string and $regularExp
uses is the regular expression.
Regular expression use standard java.util.regex.Pattern
class patterns. Currently the following link to regular expression constructs is valid:
The fn-bea:sql-like
function tests whether a string contains the specified pattern. Typically, you can use this function as a condition for a query, similar to the SQL LIKE operator used in a predicate of SQL queries. The function returns TRUE if the pattern is matched in the source expression; otherwise the function returns FALSE.
The function has the following signatures:
fn-bea:sql-like($source as xs:string?, $pattern as xs:string?, $escape as xs:string?) as xs:boolean?
fn-bea:sql-like($source as xs:string?, $pattern as xs:string?) as xs:boolean?
where $source is the string to search, $pattern is the pattern specified using the syntax of the SQL LIKE clause, and $escape is the character to use to escape a wildcard character in the pattern.
You can use the following wildcard characters to specify the pattern:
You can include the “%” or “_” character in the pattern by specifying an escape character and preceding the “%” or “_” character in the pattern with this character. The function then reads the character literally, instead of interpreting it as a special pattern-matching character.
The $escape character has to be exactly one character in length and cannot be either the percent (“%”) or underscore (“_”) character.
fn-bea:sql-like($RTL_CUSTOMER.ADDRESS_1/FIRST_NAME,"H%","\")
returns TRUE
for all FIRST_NAME
elements in $RTL_CUSTOMER.ADDRESS
that start with the character H
.fn-bea:sql-like($RTL_CUSTOMER.ADDRESS_1/FIRST_NAME,"_a%","\")
returns TRUE
for all FIRST_NAME
elements in $RTL_CUSTOMER.ADDRESS
that start with any character and have a second character of the letter a
.fn-bea:sql-like($RTL_CUSTOMER.ADDRESS_1/FIRST_NAME,"H\%%","\")
returns TRUE
for all FIRST_NAME
elements in $RTL_CUSTOMER.ADDRESS
that start with the characters H%
.
The fn-bea:trim
function removes the leading and trailing white space.
The function has the following signature:
fn-bea:trim($source as xs:string?) as xs:string?
where $source
is the string to trim. In cases when $source
is an empty sequence, the function returns an empty sequence. AquaLogic Data Services Platform generates an error when the parameter is not a string.
The fn-bea:trim-left
function removes the leading white space.
The function has the following signature:
fn-bea:trim-left($input as xs:string?) as xs:string?
where $input
is the string to trim.
The fn-bea:trim-right
function removes the trailing white space.
This function has the following signature:
fn-bea:trim-right($input as xs:string?) as xs:string?
where $input
is the string to trim.
The fn-bea:pad-left
functions add padding characters to the left of a string to create a fixed-length string. There are two variations of the function:
If the input string exceeds the requested length, only a substring as long as the length is returned.
The function has the following signature:
fn-bea:pad-left($str as xs:string?, $size as xs:integer?) as xs:string?
where string ($str
) is returned with a specified number ($size
) of characters (ASCII 32) prepended to the left of the string. The result is a string of length $size. It consists of $str prepended with $size - fn:length($str) space characters.
fn-bea:pad-left(“abcd”, 6)
prepends spaces to the string up to the maximum 6 specified. The returned string is: “ abcd”
.fn-bea:pad-left(“abcd”, 2)
returns only “ab”
because characters are only prepended to the complete string. In addition, only the first two characters are returned since that is the setting of $size
.This function has the following signature:
fn-bea:pad-left($str as xs:string?, $size as xs:integer?, $pad as xs:string?) as xs:string?
where string ($str
) is returned with an arbitrary number ($size
) of prepended characters with the pad string ($pad
) replicated as many times as necessary.
fn-bea:pad-left(“abcd”, 6, “01”)
prepends a pad string to the string up to the maximum 6 specified. The returned string is: “01abcd”
.fn-bea:pad-left(“abcd”, 2, “01”)
returns only “ab”
because characters are only prepended to a complete string. In addition, only the first two characters are returned since that is the setting of $size
.fn-bea:pad-left(“abc”, 6, “01”)
returns “010abc”
. Note that the prepended string is returned completely once and then partially up to the length ($size) specified.
The fn-bea:pad-right
functions add padding characters to the right of a string to create a fixed-length string. There are two variations of the function:
If the input string exceeds the requested length, only a substring as long as the length is returned.
The function has the following signature:
fn-bea:pad-right($str as xs:string?, $size as xs:integer?) as xs:string?
where string ($str
) is returned with a specified number ($size
) of characters (ASCII 32) appended to the string. The result is a string of length $size. It consists of $str appended with $size - fn:length($str) space characters.
fn-bea:pad-right(“abcd”, 6)
appends spaces to the string up to the maximum 6 specified. The returned string is: “abcd ”
.fn-bea:pad-right(“abcd”, 2)
returns only “ab”
because characters are only appended to a complete string. In addition, only the first two characters are returned since that is the setting of $size
.This function has the following signature:
fn-bea:pad-right($str as xs:string?, $size as xs:integer?, $pad as xs:string?) as xs:string?
where string ($str
) is returned with an arbitrary number ($size
) of appended characters with the pad string ($pad
) replicated as many times as necessary.
fn-bea:pad-right(“abcd”, 6, “01”)
prepends a pad string to the string up to the maximum 6 specified. The returned string is: “abcd01”
.fn-bea:pad-right(“abcd”, 2, “01”)
returns only “ab”
because characters are only appended to a complete string. In addition, only the first two characters are returned since that is the setting of $size
.fn-bea:pad-right(“abc”, 6, “01”)
returns only “abc010”
. Note that the appended string is returned completely once and then partially up to the length ($size) specified.AquaLogic Data Services Platform includes functions to support the Extended XQuery Data Model (XXDM). The XXDM represents instances of the XQuery Data Model (XDM) along with information about changes to the instances.
This section describes functions that you can use to convert XXDM instances to XDM instances.
Note: | ALDSP 3.2 offers several new XQuery functions for manipulating and applying changes to XML element instances. See “Introducing Mutators for Updates” in the ALDSP 3.2 New Features Supplement |
The fn-bea:current-value function returns an XDM instance representing the current value of the specified argument (discarding information about applied changes).
The function has the following signature:
fn-bea:current-value($changed as changed-element()) as element()?
where $changed
is the XXDM instance.
The fn-bea:old-value function returns an XDM instance representing the value of the specified argument prior to modification.
The function has the following signature:
fn-bea:old-value($changed as changed-element()) as element()?
where $changed
is the XXDM instance.
Both the fn-bea:current-value and fn-bea:old-value functions are polymorphic.
The following function returns the salary difference for a customer before and after modification.
declare function salaryDifference($cus as changed-element
(cus:customer)) as xs:decimal {
fn:data(fn-bea:get-current-value($cus)/salary - fn:data(fn-
bea:get-old-value($cus)/salary)
}
The function does this by accessing the current and old versions of the customer element, extracting the salaries, and subtracting to determine the difference.
The following functions from the XQuery 1.0 specification are not supported in current BEA XQuery engine implementation:
This section describes BEA-specific implementation details related to functions and operators.
This section describes the BEA XQuery language implementation, and contains the following topics:
The AquaLogic Data Services Platform conforms to the W3C Working Draft “XQuery 1.0: An XML Query Language” dated 23 July 2004 (http://www.w3.org/TR/2004/WD-xquery-20040723/), with these exceptions:
Beyond compliance with the specification, BEA AquaLogic Data Services Platform’s XQuery language implementation (the AquaLogic Data Services Platform XQuery engine) extends the XQuery language via the following:
BEA offers a group by clause extension to standard FLWOR expressions. The following EBNF shows the syntax of the general FLWGDOR:
flwgdorExpression := (forClause | letClause) (forClause
| letClause
| whereClause
| groupbyClause
| orderbyClause)* returnClause
groupbyClause := "group" [variable "as" variable] "by" (expression
["as" variable]) ("," (expression ["as" variable]))*
The remaining clauses referenced in the EBNF fragment follow the standard definition, as presented in the XQuery specification.
As an example, consider the problem of grouping books by year, without losing books that do not have a year attribute. Using standard XQuery, you would need to perform a self-join with the result of the fn:distinct-values() function, concatenating the result of the self-join with the result for books without a year attribute.
The following illustrates an XQuery expression that can be used to accomplish this:
let $books := document("bib.xml")/bib/book return (
for $year in fn:distinct-values($books/@year)
return
<g>
<year>{ $year }</year>
<titles>{ $books[@year eq $year]/title }</titles>
</g>,
<g>
<year/>
<titles>{ $books[fn:empty(@year)]/title }
</g>
)
Using the BEA group by
extension function, you could write the same query as follows:
for $book in document("bib.xml")/bib/book
group $book as $partition by $book/@year as $year
return
<g>
<year>{ $year }</year>
<titles>{ $partition/title }</titles>
</g>
The following tables (Table 2-4 and Table 2-5) show book bindings before and after the group by clause is applied.
The FLWGOR expression conceptually builds a sequence of binding tuples, where the size of the tuple is the number of variables in scope at that point in the FLWGOR. In the example, the tuple at the group by
clause consists of a single variable binding $book
which binds to each book in the bib.xml
document, one book at a time (see Table 2-4).
The group by
creates a new sequence of binding tuples with each output tuple containing variables defined in the group by
clause. After the group by
, all variables there were previously in-scope go out of scope.
In the example, the output tuple from the group by
clause is of size two with the variable bindings being for $year
and $partition
(see Table 2-5).
The number of output tuples is equal to the number of unique group by value bindings. In the above example, this is the number of unique book/@year
values: 2. The variable introduced in the group
clause ($partition
in the example above) binds to the sequence of all matching input values.
This extension enables external consumers of XML generated by XQuery to have certain empty elements and attributes omitted. You can specify this using optional indicators, instead of employing computed constructors, conditional statements, and custom functions.
For example, consider the following query:
<a><b>{()}</b><c foo="{()}"/></a>,
The extension enables the following to be returned:
<a><c/></a>
<a><b/><c foo=""/></a>
The extension uses the optional indicator '?' with direct element and attribute constructors. This means that in the following you could change the production DirElemConstructor
to the following:
[94] DirElemConstructor ::= "<" QName "?"? DirAttributeList
("/>" | (">" DirElemContent* "</" QName S? ">")) /* ws: explicit */
Likewise, you could change the DirAttributeList
to the following:
[95] DirAttributeList ::= (S (QName "?"? S? "=" S?
DirAttributeValue)?)*
When ? is present, elements with no children and attributes with the value "" are omitted. The query in the example could then be written as:
<a><b?>{()}</b><c foo?="{()}"/></a>
which produces the following result:
<a><c/></a>
In another example, consider the case of constructing a new customer element with different tags. One requirement is that you do not want a phone element in the resulting customer when the phone number does not exist in the original customer. Using standard XQuery, you would have to write:
for $cust in CUSTOMER()
return
<customer>
<id>{ fn:data($cust/C_ID) }</id>
{
if (fn:exists($cust/PHONE))
then <phone>{ fn:data($cust/PHONE) }</phone>
else ()
}
...
</customer>
Using the optional element constructor, you could instead write the following:
for $cust in CUSTOMER()
return
<customer>
<id>{ fn:data($cust/C_ID) }</id>
<phone?>{ fn:data($cust/PHONE) }</phone>
...
</customer>
Similarly, when you want the resulting customer element to use attributes instead of elements, you would need to employ computed attribute constructors using standard XQuery, as illustrated by the following:
for $cust in CUSTOMER()
return
<customer
id="{ fn:data($cust/C_ID) }"
{
if (fn:exists($cust/PHONE))
then attribute { "phone" } { fn:data($cust/PHONE) }
else ()
}
...
/>
Using the optional attribute constructor, the query becomes:
for $cust in CUSTOMER()
return
<customer
id="{ fn:data($cust/C_ID) }"
phone?="{ fn:data($cust/PHONE) }"
...
/>
This section describes the BEA-specific implementation details related to XQuery language processing.