Skip navigation.
Downloads | Product Documentation | Support

XQuery Developer's Guide

# BEA's XQuery Implementation

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

- BEA XQuery Function Implementation
- BEA XQuery Language Implementation

# BEA XQuery Function Implementation

Data Services Platform (DSP) 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, DSP 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:

- Function Overview
- Access Control Functions
- Duration, Date, and Time Functions
- Execution Control Functions
- Numeric Functions
- Other Functions
- QName Functions
- Sequence Functions
- String Functions
- Unsupported XQuery Functions
- Implementation-Specific Functions and Operators

## Function Overview

Table 2-1 provides an overview of the BEA XQuery function extensions.

Table 2-1 BEA XQuery Function Extensions

Category | Function | Description
Access Control Functions | fn-bea:is-access-allowed | Checks whether a user associated with the current request context can access the specified resource.
fn-bea:is-user-in-group | Checks whether the current user is in the specified group.
fn-bea:is-user-in-role | Checks whether the current user is in the specified role.
fn-bea:userid | Returns the identifier of the user making the request for the protected resource.
fn-bea:rename | Renames a sequence of elements.
Duration, Date, and Time Functions | fn-bea:date-from-dateTime | Returns the date part of a dateTime value.
fn-bea:date-from-string-with-format | Returns a new `date` value from a string source value according to the specified pattern.
fn-bea:date-to-string-with-format | Returns a date string with the specified pattern.
fn-bea:dateTime-from-string-with-format | Returns a new `dateTime` value from a string source value according to the specified pattern.
fn-bea:dateTime-to-string-with-format | Returns a date and time string with the specified pattern.
fn-bea:time-from-dateTime | Returns the time part of a dateTime value.
fn-bea:time-from-string-with-format | Returns a new time value from a string source value according to the specified pattern.
fn-bea:time-to-string-with-format | Returns a time string with the specified pattern.
Execution Control Functions | fn-bea:async | Evaluates an XQuery expression asynchronously, depositing the result of the evaluation into a buffer.
fn-bea:fence | Enables you to define optimization boundaries, dividing queries into islands within which optimizations should occur.
fn-bea:if-then-else | Accepts the value of a Boolean parameter to select one of two other input parameters.
fn-bea:timeout | Returns either the full result of the primary expression, or the full result of the alternate expression in cases when the primary XQuery expression times out.
Numeric Functions | fn-bea:decimal-round | Returns a decimal value rounded to the specified precision or whole number.
fn-bea:decimal-truncate | Returns a decimal value truncated to the specified precision or whole number.
Other Functions | fn-bea:get-property | Enables you to write data services that can change behavior based on external influence.
fn-bea:inlinedXML | Parses textual XML and returns an instance of the XQuery 1.0 Data Model.
fn-bea:format-number | Converts a double to a string using the specified format pattern.
QName Functions | fn-bea:QName-from-string | Creates an `xs:QName` and uses the value of specified argument as its local name without a namespace.
Sequence Functions | fn-bea:interleave | Interleaves items specified in the arguments.
String Functions | fn-bea:match | Returns a list of integers (either an empty list with 0 integers or a list with 2 integers) specifying which characters in the string input matches the input regular expression.
fn-bea:sql-like | Searches a string using a pattern, specified using the syntax of the SQL LIKE clause. The function optionally enables you to escape wildcards in the pattern.
fn-bea:trim | Removes the leading and trailing white space.
fn-bea:trim-left | Removes the leading white space.
fn-bea:trim-right | Removes the trailing white space.

## Access Control Functions

Data Services Platform (DSP) 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 Data Services Platform Console, you can use the security function extensions described in this section to determine:

- Whether a user associated with the current request context can access a specified resource.
- Whether the current user is in a specified role.
- Whether the current user is in a specified group.

This section describes the following DSP access control function extensions to the BEA implementation of XQuery:

- fn-bea:is-access-allowed
- fn-bea:is-user-in-group
- fn-bea:is-user-in-role
- fn-bea:userid

### fn-bea:is-access-allowed

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 `$data_service` 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("ssn", "ld:DataServices/CustomerProfile.ds"))

>             then fn:true()

### fn-bea:is-user-in-group

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.

### fn-bea:is-user-in-role

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.

### fn-bea:userid

The `fn-bea:userid()` function returns the identifier of the user making the request for the protected resource.

The function has the following signature:

`fn-bea:userid() as xs:string`

## Duration, Date, and Time Functions

This section describes the following duration, date, and time function extensions to the BEA implementation of XQuery:

- fn-bea:date-from-dateTime
- fn-bea:date-from-string-with-format
- fn-bea:date-to-string-with-format
- fn-bea:dateTime-from-string-with-format
- fn-bea:dateTime-to-string-with-format
- fn-bea:time-from-dateTime
- fn-bea:time-from-string-with-format
- fn-bea:time-to-string-with-format

### fn-bea:date-from-dateTime

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.

Examples:

- `fn-bea:date-from-dateTime(fn:dateTime("2005-07-15T21:09:44"))` returns a date value corresponding to July 15th, 2005 in the current time zone.
- `fn-bea:date-from-dateTime(())` returns an empty sequence.

### fn-bea:date-from-string-with-format

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.

Examples:

- `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.

### fn-bea:date-to-string-with-format

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.

Examples:

- `fn-bea:date-to-string-with-format("by-dd-mm", xf:date("2005-07-15"))` returns the string "05-15-07".
- `fn-bea:date-to-string-with-format("yyyy-mm-dd", xf:date("2005-07-15"))` returns the string "2005-07-15".

### fn-bea:dateTime-from-string-with-format

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.

Examples:

- `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.

### fn-bea:dateTime-to-string-with-format

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.

Examples:

- `fn-bea:dateTime-to-string-with-format("dd MMM yyyy hh:mm a G", xf:dateTime("2005-01-07T22:09:44"))` returns the string "07 JAN 2005 10:09 PM AD".
- `fn-bea:dateTime-to-string-with-format("MM-dd-yyyy", xf:dateTime("2005-01-07T22:09:44"))` returns the string "01-07-2005".

### fn-bea:time-from-dateTime

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.

Examples:

- `fn-bea:time-from-dateTime(fn:dateTime("2005-07-15T21:09:44"))` returns a time value corresponding to 9:09:44PM in the current time zone.
- `fn-bea:time-from-dateTime(())` returns an empty sequence.

### fn-bea:time-from-string-with-format

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.

Examples:

- `fn-bea:time-from-string-with-format("HH.mm.ss", "21.45.22")` returns the time 9:45:22PM in the current time zone.
- `fn-bea:time-from-string-with-format("hh:mm:ss a", "8:07:22 PM")` returns the time 8:07:22PM in the current time zone.

### fn-bea:time-to-string-with-format

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.

Examples:

- `fn-bea:time-to-string-with-format("hh:mm a", xf:time("22:09:44"))` returns the string "10:09 PM".
- `fn-bea:time-to-string-with-format("HH:mm a", xf:time("22:09:44"))` returns the string "22:09 PM".

### 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.

Table 2-2 Date and Time Patterns

This Symbol | Represents This Data | Produces This Result
G | Era | AD
y | Year | 1996
M | Month of year | July, 07
d | Day of the month | 19
h | Hour of the day (1-12) | 10
H | Hour of the day (0-23) | 22
m | Minute of the hour | 30
s | Second of the minute | 55
S | Millisecond | 978
E | Day of the week | Tuesday
D | Day of the year | 27
w | Week in the year | 27
W | Week in the month | 2
a | am/pm marker | AM, PM
k | Hour of the day (1-24) | 24
K | Hour of the day (0-11) | 0
z | Time zone | Pacific Standard Time Pacific Daylight Time

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.

## Execution Control Functions

This section describes the following DSP execution control function extensions to the BEA implementation of XQuery:

- fn-bea:async
- fn-bea:fence
- fn-bea:if-then-else
- fn-bea:timeout

### fn-bea:async

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()*, $cap as xs:integer) as item()*`

where `$expression` is the XQuery expression to evaluate asynchronously and `$cap` is the size of the buffer.

The `fn-bea:async` function enables asynchronous execution of Web services to reduce problems caused by the latency of these services. When used in this manner, a very small buffer size such as 1 or 2 is sufficient, as the time to produce the first token can be long while the production of subsequent tokens should be quicker.

Example:

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))`

### fn-bea:fence

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.

### fn-bea:if-then-else

The `fn-bea:if-then-else` function examines the value of the first parameter. If the condition is true, DSP returns the value of the second parameter (then). If the condition is false, DSP returns the value of the third parameter (else). If the returned condition is not a Boolean value, DSP generates an error.

The function has the following signature:

`fn-bea:if-then-else($condition as xs:boolean?, $ifValue as xdt:anyAtomicType, $elseValue as xdt:anyAtomicType)as xdt:anyAtomicType`

where `$condition` is the condition to test, `$ifValue` is the value to return when the condition evaluates to true, and `$elseValue` is the value to return when the condition evaluates to false.

Examples:

- `fn-bea:if-then-else (xf:true(), 3, "10")` returns the value 3.
- `fn-bea:if-then-else (xf:false(), 3, "10")` returns the string value 10.
- `fn-bea:if-then-else ("true", 3, "10")` generates a compile-time error because the condition is a string value and not a Boolean value.

### fn-bea:timeout

The `fn-bea:timeout` function returns either the full result of the primary expression, or the full result of the alternate expression in cases when the primary XQuery expression times out.

The function has the following signature:

`fn-bea:timeout($expression as item()*, $millisec as xs:integer, $alt as item()*) as item()*`

where `$expression` is the primary XQuery expression to evaluate, `$millisec` is the time out value in milliseconds, and `$alt` is an alternative XQuery expression to evaluate after a time out has occurred.

You can use the `fn-bea:timeout` function in the following ways:

- Around a region of an XQuery result which is optional, such as when you want the rest of the answer in any case.
- To select an available data source from among a set of possibly (very) heterogeneous sources that can provide the information of interest.

Note that the `fn-bea:timeout` function immediately returns the alternative expression in cases when accessing the data source causes an error. Also, an instance of `fn-bea:timeout` that has failed over to the alternate expression once will not re-evaluate the original expression during the same query evaluation.

Example:

$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()
)
)`

## Numeric Functions

This section describes the following numeric function extensions to the BEA implementation of XQuery:

- fn-bea:format-number
- fn-bea:decimal-round
- fn-bea:decimal-truncate

### fn-bea:format-number

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.4.2 `DecimalFormat` class. (For information on DecimalFormat and other JDK 1.4.2 Java classes see: http://java.sun.com/j2se/1.4.2.)

### fn-bea:decimal-round

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.

Examples:

- `fn-bea:decimal-round(127.444, 2)` returns 127.44.
- `fn-bea:decimal-round(0.1234567, 6)` returns 0.123457.

### fn-bea:decimal-truncate

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.

Examples:

- fn-bea:decimal-truncate(192.454, 2) returns 192.45.
- fn-bea:decimal-truncate(192.454) returns 192.
- fn-bea:decimal-truncate(0.1234567, 6) returns 0.123456.

## Other Functions

This section describes the following function extensions to the BEA implementation of XQuery:

- fn-bea:get-property
- fn-bea:inlinedXML
- fn-bea:rename

### fn-bea:get-property

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 DSP 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.

### fn-bea:inlinedXML

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.

Examples:

- `fn-bea:inlinedXML("<text</e>")` returns element "`e`".
- `fn-bea:inlinedXML("<?xml version="1.0"><e>text</e>")` returns a document with root element "`e`".

### fn-bea:rename

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:

- The same name and type as `$newname`
- The same content as the old element

Example:

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

The output value would be:

>     <CUSTOMER><FNAME>John</FNAME><LNAME>Jones</LNAME></CUSTOMER>

## QName Functions

This section describes the following QName function extensions to the BEA implementation of XQuery:

### fn-bea:QName-from-string

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.

## Sequence Functions

This section describes the following sequence function extensions to the BEA implementation of XQuery:

- fn-bea:interleave

### fn-bea:interleave

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:

`(<a/>, " ", <b/>, " ", </c>)`

## String Functions

This section describes the following string function extensions to the BEA implementation of XQuery:

- fn-bea:match
- fn-bea:sql-like
- fn-bea:trim
- fn-bea:trim-left
- fn-bea:trim-right

### fn-bea:match

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 starting at the first match. 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 the standard regular expression language.

Table 2-3 presents regular expression syntax examples.

Table 2-3 Regular Expression Syntax Examples

Category | Syntax Example | Description
Characters | unicode | Matches the specified unicode character.
\ | Used to escape metacharacters such as *, +, and ?.
\\ | Matches a single backslash ( \ ) character.
\0nnn | Matches the specified octal character.
\0xhh | Matches the specified 8-bit hexidecimal character.
\\uxhhh | Matches the specified 16-bit hexidecimal character.
\t | Matches an ASCII tab character.
Characters | \n | Matches an ASCII new line character.
\r | Matches an ASCII return character.
\f | Matches an ASCII form feed character.
Simple Character Classes | [bc] | Matches the characters b or c.
[a-f] | Matches any character between a and f.
[^bc] | Matches any character except b and c.
Predefined Character Classes | . | Matches any character except the new line character.
\w | Matches a word character: an alphanumeric character or the underscore ( _ ) character.
\W | Matches a non-word character.
\s | Matches a white space character.
\S | Matches a non-white space character.
\d | Matches a digit.
\D | Matches a non-digit.
Greedy Closures (Match as many characters as possible) | A* | Matches expression A zero or more times.
A+ | Matches expression A one or more times.
A? | Matches expression A zero or one times.
A(n) | Matches expression A exactly n times.
A(n,) | Matches expression A at least n times.
A(n, m) | Matches expression A between n and m times.
Reluctant Closures (Match as few characters as possible, and stops when a match is found) | A*? | Matches expression A zero or more times.
A+? | Matches expression A one or more times.
A?? | Matches expression A zero or one times.
Logical Operators | AB | Matches expression A followed by expression B.
A|B | Matches expression A or expression B.
(A) | Used for grouping expressions.

Examples:

- `fn-bea:match("abcde", "bcd")` evaluates to the sequence (2,3).
- `fn-bea:match("abcde", ())` evaluates to the empty sequence ().
- `fn-bea:match((), "bcd")` evaluates to the empty sequence ().
- `fn-bea:match("abc", 4)` generates an error at compile time because the second parameter is not a string.
- `fn-bea:match("abcccdee", "[bc]")` evaluates to the sequence (2,1).

### fn-bea:sql-like

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:

- Percent character (%). Represents a string of zero or more characters.
- Underscore character (_). Represents any single character.

You can include the % or _ characters in the pattern by specifying an escape character and preceding the % or _ characters in the pattern with this escape character. The function then reads the character literally, instead of interpreting it as a special pattern-matching character.

Examples:

- `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%`.

### fn-bea:trim

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. DSP generates an error when the parameter is not a string.

Examples:

- `fn-bea:trim("abc")` returns the string value "abc".
- `fn-bea:trim(" abc ")` returns the string value "abc".
- `fn-bea:trim(())` returns the empty sequence.
- `fn-bea:trim(5)` generates a compile-time error because the parameter is not a string.

### fn-bea:trim-left

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.

Examples:

- `fn-bea:trim-left(" abc ")` removes leading spaces and returns the string `"abc "`.
- `fn-bea:trim-left(())` outputs an error. The input is the empty sequence (similar to a SQL null) which is a sequence containing zero items.

### fn-bea:trim-right

The `fn-bea:trim-right` function removes the trailing white space.

The function has the following signature:

`fn-bea:trim-right($input as xs:string?) as xs:string?`

where `$input` is the string to trim.

Examples:

- `fn-bea:trim-right(" abc ")` removes trailing spaces and returns the string `" abc"`.
- `fn-bea:trim-right(())` outputs an error. The input is the empty sequence (similar to a SQL null) which is a sequence containing zero items.

## Unsupported XQuery Functions

The following functions from the XQuery 1.0 specification are not supported in current BEA XQuery engine implementation:

- fn:base-uri
- fn:normalize-unicode
- fn:id
- fn:idref
- fn:collection

## Implementation-Specific Functions and Operators

In addition to the support for XQuery functions and operators and the BEA extensions described previously, 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/ ) allows implementors to use their discretion in implementing various aspects of the specification, as listed in Table 2-4.

Table 2-4

Section | Description | DSP XQuery Engine
6.2—Operators on Numeric Values [Overflow and Underflow during Arithmetic Operations] | Choice between raising an error and other options for overflow or underflow of numeric operations. | Arithmetic overflow and underflow follows behavior of the underlying Application Server's JVM (Java Virtual Machine).
6.2—Operators on Numeric Values [xs:decimal value digit precision] | Number of digits of precision for xs:decimal results | 18 digits.
7.4.6—fn:normalize-unicode | In addition to supporting required normalization form "NFC", conforming implementations may also support implementation-defined semantics. | Not supported.
7.5—Functions Based on Substring Matching | Ability to decompose strings into collation units. | No collations supporting this feature are available.
10.1.1—Limits and Precision | Limits and precision for Durations, Dates and Times larger then those specified in XML Schema Part 2: Data Types | Fractional seconds are supported for more than 3 digits of accuracy: seven digits for serialized data (binXML package), 18 digits during computations.
15.5.4—Functions and Operators on Sequences [fn:doc] | Processing or document URI, usage of DTD or Schema for validation, handling of non-XML media types and construction of data model instances from non-XML resources and error handling for document processing. | fn:doc() function does not validate. DSP uses predefined external functions for access to external XML and non-XML data sources.

Implementation-Defined Values

# BEA XQuery Language Implementation

This section describes the BEA XQuery language implementation, and contains the following topics:

- XQuery Language Support (and Unsupported Features)
- Extensions to the XQuery Language in the DSP XQuery Engine
- Implementation-Defined Values for XQuery Language Processing

## XQuery Language Support (and Unsupported Features)

The Data Services Platform (Version: 2.0.1) 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:

- Modules are not supported
- xs:integer is represented by 64-bit values

## Extensions to the XQuery Language in the DSP XQuery Engine

Beyond compliance with the specification, BEA AquaLogic Data Services Platform's XQuery language implementation (the DSP XQuery engine) extends the XQuery language via the following:

- Generalized FLWGOR (group by)
- Optional Indicator in Direct Element and Attribute Constructors

### Generalized FLWGOR (group by)

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 case of grouping books by year, without loosing 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 the XQuery expression 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, 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>`

Table 2-5 Bindings Before Group By Clause is Applied

$book
`<book year="1994" ISBN="147...">...</book>`
`<book year="1994" ISBN="198..."> ...</book>`
`<book year="2000" ISBN="123..."> ...</book>`

Table 2-6 Bindings After Group By Clause is Applied

$year | $partition
--- | ---
1994 | `(<book year="1994" ISBN="147...">...</book>, <book year="1994" ISBN="198..."> ...</book>)`
2000 | `<book year="2000" ISBN="123..."> ...</book>`

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 (Table 1).

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` (Table 2).

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.

### Optional Indicator in Direct Element and Attribute Constructors

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>

instead of:

>     <a><b/><c foo=""/></a>

The extension uses the optional indicator '?' with direct element and attribute constructors. This mean 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) }"
...
/>`

## Implementation-Defined Values for XQuery Language Processing

In addition, for some aspects of language processing, the W3C working draft document leaves the details to the implementor's discretion, but requires each implementor to specify and document the implementation details. All such "implementation defined1" language features of the XQuery language as implemented in BEA AquaLogic Data Services Platform Version: 2.0.1 are listed in Table 2-7.

Table 2-7 Implementation-Defined Values

Section | Description | DSP XQuery Engine
2.1.2—Dynamic Context | Implicit timezone (value of type xdt:dayTimeDuration) that will be used when a date, time, or dateTime value that does not have a timezone is used in a comparison (or any other operation). | Timezone of the JVM of the underlying application server.
2.5.1—Kinds of Errors—Static Error | Mechanism for reporting static errors (errors that must be detected during the analysis phase, such as syntax errors). | Parser and compiler APIs throw Java exceptions
2.5.1—Kinds of Errors—Warnings | In addition to static, dynamic, and type errors, an XQuery implementation can (optionally) raise warnings during the analsyis or evaluation phases, in response to specific conditions. | Provides a WarningListener API, but has no special warnings defined for the core XQuery language implementation
2.6.3—Full Axis Feature | Set of optional axes when Full Axis Feature is not supported | None.
2.6.6.1—Must-Understand Extensions—XQuery Flagger | Mechanism by which the XQuery Flagger (which flags queries containing `must understand' extensions) is enabled, if at all—by default, it is disabled. | XQuery Flagger is not supported.
2.6.7.1—Static Typing Extensions—XQuery Static Flagger | Mechanism by which the XQuery Static Flagger is provided, if at all. | XQuery Static Flagger is not supported.
3.1.1—Literals | Choice of XML 1.0 or XML 1.1 for character references (the XML-style references for Unicode characters, such as &#0151; for an em-dash). | XML 1.0
3.7.1.2—Namespace Declaration Attributes | Support for XML Names 1.1 | No
3.8.3—Order By and Return Clauses | Ordering specification (orderspec) can be implemented as empty least or empty greatest (for evaluating greater-than relationship between two orderspec values in an order by clause of an XQuery). | Empty least.
4.10—Module Import | String literals following the `at` keyword are optional location hints in module import statements that can be interpreted (or disregarded) by the implementor. | Not applicable—Since the DSP XQuery engine does not support modules, there is no implementation.
4.13—Function Declaration | Protocol by which parameters are passed to an external function and the result of the function is returned to the invoking query. | Set of Java APIs provided.
A.2—Lexical structure | Lexical rules can follow XML 1.0 and XML Names, or XML 1.1 and XML Names 1.1. | XML 1.0 and XML Names