DataDirect XQuery Built-In Functions


This section describes the following DataDirect XQuery built-in functions:

In addition, DataDirect XQuery supports the DB2 V9.1 for Linux/UNIX/Windows, Microsoft SQL Server 2005, and
Oracle 10g R2 XQuery extensions through a set of built-in (predeclared) XQuery functions that map one-to-one to the database features. See Querying XML on Microsoft SQL Server 2005 and Querying XML on Oracle for examples.

ddtek:analyze-edi-from-string

ddtek:analyze-edi-from-string analyzes an EDI stream and provides an error report that describes any errors that will prevent EDI messages from being converted to XML using the ddtek:edi-to-xml-from-string function. The report generated by ddtek:analyze-edi-from-string is used by ddtek:edi-to-xml-from-string to filter messages that contain errors, allowing processing of EDI sources that contain errors.

This function is supported only for EDIFACT, HIPAA, and X12 EDI dialects.

Function Declaration

declare function ddtek:analyze-edi-from-string( 
  $url as xs:string,  
  $edi as xs:string)  
  as document-node(element(*, xs:untyped)) external; 

where:

$url specifies the properties you want the EDI conversion engine to use when converting the EDI stream to XML – EDI:tbl=yes, for example.

To learn more about conversion properties, see the section "EDI XML Converter Properties" in the DataDirect XML Converters User’s Guide and Reference manual. DataDirect XML Converters documentation is installed as part of the DataDirect Data Integration Suite, of which DataDirect XQuery is a part; you can also find DataDirect XML Converters product documentation on the DataDirect Web site.

$edi can be any EDI document in a supported dialect specified as a string.

Note: ddtek:analyze-edi-from-string requires that XML Converters are reachable in the current classpath and that a valid XML Converters license is available.

See Analyzing EDI to XML Conversions for more information.

ddtek:analyze-edi-from-url

ddtek:analyze-edi-from-url analyzes an EDI stream and provides an error report that describes any errors that will prevent EDI messages from being converted to XML using the ddtek:edi-to-xml-from-url function. The report generated by ddtek:analyze-edi-from-url is used by ddtek:edi-to-xml-from-url to filter messages that contain errors, allowing processing of EDI sources that contain errors.

This function is supported only for EDIFACT, HIPAA, and X12 EDI dialects.

Function Declaration

declare function ddtek:analyze-edi-from-url( 
  $url as xs:string)   
  as document-node(element(*, xs:untyped)) external; 

where:

$url specifies the full path of the EDI source you want to convert, as well as the properties you want the EDI conversion engine to use when converting the EDI stream to XML –
EDI:tbl=yes?file:///c:/EDI/code99.x12, for example.

To learn more about conversion properties, see the section "EDI XML Converter Properties" in the DataDirect XML Converters User’s Guide and Reference manual. DataDirect XML Converters documentation is installed as part of the DataDirect Data Integration Suite, of which DataDirect XQuery is a part; you can also find DataDirect XML Converters product documentation on the DataDirect Web site.

Note: ddtek:analyze-edi-from-url requires that XML Converters are reachable in the current classpath and that a valid XML Converters license is available.

See Analyzing EDI to XML Conversions for more information.

ddtek:convert-to-xml

ddtek:convert-to-xml allows you to convert non-XML data passed as xs:string into XML using DataDirect XML Converters expressed using the converter URI syntax. The source for the XML data might have been extracted from a database, XML document, or other sources.

Note: ddtek:convert-to-xml requires that XML Converters are reachable in the current classpath and that a valid XML Converters license is available.

Function Declaration

			ddtek:convert-to-xml($input as xs:string, $options as xs:string) as   
			document-node(element(*,xs:untyped)) 

where:

$input is a character string

$options are properties used by the conversion engine when converting to XML. Separate options with a colon (long=yes:tbl=no, for example).

To learn more about conversion properties, see the section "EDI XML Converter Properties" in the DataDirect XML Converters User’s Guide and Reference manual. DataDirect XML Converters documentation is installed as part of the DataDirect Data Integration Suite, of which DataDirect XQuery is a part; you can also find DataDirect XML Converters product documentation on the DataDirect Web site.

Example Using the EDI Converter

This example shows an EDI message being converted to XML using the EDI converter:

let $edimessage := "ISA+00+ +00+ +01+1515151515  
+01+5151515151 +041201+1217+^+00403+000032123+0+P+*' 
GS+CT+9988776655+1122334455+20041201+1217+128+X+004030' 
ST+831+00128001' 
BGN+00+88200001+20041201' 
N9+BT+88200001' 
TRN+1+88200001' 
AMT+2+100000' 
QTY+46+1' 
SE+7+00128001' 
GE+1+128' 
IEA+1+000032123'" 
return 
  ddtek:convert-to-xml($edimessage, "EDI:long=yes") 
Example Using the CSV Converter

This example shows the CSV converter being used to convert a simple comma-separated values file (submitted as a string) to XML:

declare option ddtek:serialize "indent=yes";
ddtek:convert-to-xml("a,b,c", "CSV")  

ddtek:decimal

ddtek:decimal allows you to specify precision and scale of a decimal value. For example:

	ddtek:decimal($v as xs:anyAtomicType?,$p as xs:integer,$s as xs:integer)  
	  as xs:decimal? 

ddtek:edi-to-xml-from-string

ddtek:edi-to-xml-from-string allows you to convert an EDI stream to XML when the EDI is stored in memory as a String datatype. The report used as an input to this function, which is generated by ddtek:analyze-edi-from-string, filters out errors in the EDI source that would otherwise cause the conversion to fail. This function is supported only for EDIFACT, HIPAA, and X12 EDI dialects.

Function Declaration

declare function ddtek:edi-to-xml-from-string(  
   $url as xs:string, 
   $edi as xs:string, 
   $report as document-node(element(*, xs:untyped)))  
   as document-node(element(*, xs:untyped)) external; 

where:

$url specifies the properties you want the EDI conversion engine to use when converting the EDI stream to XML – EDI:tbl=yes, for example.

To learn more about conversion properties, see the section "EDI XML Converter Properties" in the DataDirect XML Converters User’s Guide and Reference manual. DataDirect XML Converters documentation is installed as part of the DataDirect Data Integration Suite, of which DataDirect XQuery is a part; you can also find DataDirect XML Converters product documentation on the DataDirect Web site.

$edi is any EDI document in a supported dialect.

$report is the report generated by the ddtek:analyze-edi-from-string function.

Note: ddtek:edi-to-xml-from-string requires that XML Converters are reachable in the current classpath and that a valid XML Converters license is available.

See Analyzing EDI to XML Conversions for more information.

ddtek:edi-to-xml-from-url

ddtek:analyze-edi-from-url allows you to convert an EDI stream to XML.The report used as an input to this function, which is generated by ddtek:analyze-edi-from-url, filters out errors in the EDI source that would otherwise cause the conversion to fail. This function is supported only for EDIFACT, HIPAA, and X12 EDI dialects.

Function Declaration

declare function ddtek:edi-to-xml-from-url( 
  $url as xs:string  , 
  $report as document-node(element(*, xs:untyped)) )  
  as document-node(element(*, xs:untyped)) external; 

where:

$url specifies the full path of the EDI source you want to convert, as well as the properties you want the EDI conversion engine to use when converting the EDI stream to XML –
EDI:tbl=yes?file:///c:/EDI/code99.x12, for example.

To learn more about conversion properties, see the section "EDI XML Converter Properties" in the DataDirect XML Converters User’s Guide and Reference manual. DataDirect XML Converters documentation is installed as part of the DataDirect Data Integration Suite, of which DataDirect XQuery is a part; you can also find DataDirect XML Converters product documentation on the DataDirect Web site.

$report is the report generated by the ddtek:analyze-edi-from-url function.

Note: ddtek:edi-to-xml-from-url requires that XML Converters are reachable in the current classpath and that a valid XML Converters license is available.

See Analyzing EDI to XML Conversions for more information.

ddtek:format-date

The ddtek:format-date function can be used to format date strings. Depending on your requirements, the ddtek:format-date-time function can also be used for this purpose.

The ddtek:format-date function is based on XSLT 2.0 date formatting functions as defined in the XSL Transformations (XSLT) Version 2.0 W3C Recommendation 23 January 2007. See http://www.w3.org/TR/xslt20/#format-date for more information.

Function Declarations

declare function ddtek:format-date($value as xs:date?, $picture as xs:string) 
as xs:string? 
declare function ddtek:format-date( 
$value as xs:date?, 
$picture as xs:string, 
$language as xs:string?, 
$calendar as xs:string?, 
$country as xs:string?) as xs:string? 

where:

$value is the date string to be formatted.

$picture is a sequence of variable markers and literal substrings used to specify formatting of $value. See Picture Stringfor more information on specifying the $picture argument.

$language is the language to be used for the result of the ddtek:format-date function. It is used for names (days, for example), numbers when expressed as words, hour convention, and the first day of the week and month of the year (Sunday versus Monday, for example). If the language is not specified, DataDirect XQuery uses the language specified for the Java Virtual Machine (JVM) where DataDirect XQuery is installed.

$calendar is the type of calendar whose conventions are to be used to convert the string supplied in the $value argument to a value in that calendar. If the calendar is not specified, DataDirect XQuery uses the calendar specified for the Java Virtual Machine (JVM) where DataDirect XQuery is installed.

$country is the country in which the event represented by the date string occurs. Valid values are those specified by ISO 3166-1, ISO 3166-2, and ISO 3166-3. If the country is not specified, DataDirect XQuery uses the country specified for the Java Virtual Machine (JVM) where DataDirect XQuery is installed.

For more information on $language, $calendar, and $country arguments, see http://www.w3.org/TR/xslt20/#lang-cal-country in the XSLT 2.0 specification.

Picture String

As described previously, the $picture argument is a sequence of variable markers and literal substrings used to specify formatting of $value. Variable markers are indicated using bracket pairs to surround a specifier; values not in brackets are taken as literal substrings. Consider the following picture string:

"[M]-[D]-[Y]" 

Here, month (M), day (D), and year (Y) specifiers are separated by dash (-) literal substrings. Note that whitespace in literal substrings is preserved, so

"[M]-[D]-[Y]" 

and

"[M] - [D] - [Y]" 

yield different strings.

The following table summarizes commonly used specifiers:

Table 12-6. Common Picture String Specifiers
Specifier
Description
Y
Year
M
Month in year
D
Day in month
d
Day in year
f
Day of week
W
Week in year
w
Week in month
H
Hour in day (24 hours)
h
Hour in half-day (12 hours)
P
am/pm marker
m
Minute in hour
s
Second in minute
f
Fractional seconds
Z
Timezone as a time offset from Coordinated Universal Time (UTC); UTC+1, for example. Also accepts conventional timezone abbreviations (EST for Eastern Standard Timezone, for example)
z
Timezone as a time offset from Greenwich Mean Time (GMT)
C
Calendar (the name or abbreviation)
E
The name of a baseline for the numbering of years; the reign of a monarch, for example

For a complete description of the picture string, see http://www.w3.org/TR/xslt20/#date-picture-string in the XSLT 2.0 specification.

Examples

The following list shows pairs of ddtek:format-date function declarations and using an input value of $d, specified as xs:date(’2002-12-31’). The complete XQuery code might look like this, for example:

let $d := xs:date('2002-12-31') 
return ( 
  ddtek:format-date($d, "[Y0001]-[M01]-[D01]") 
) 

This XQuery returns this string:

2002-12-31 

Here are other examples of the ddtek:format-date function and the XQuery result:

ddtek:format-date($d, "[M]-[D]-[Y]") 
12-31-2002 
ddtek:format-date($d, "[D]-[M]-[Y]") 
31-12-2002 
ddtek:format-date($d, "[D1] [MI] [Y]") 
31 XII 2002 
ddtek:format-date($d, "[D1o] [MNn], [Y]", "en", (), ()) 
31st December, 2002 
ddtek:format-date($d, "[D01] [MN,*-3] [Y0001]", "en", (), 
()) 
31 DEC 2002 
ddtek:format-date($d, "[MNn] [D], [Y]", "en", (), ()) 
December 31, 2002 
ddtek:format-date($d, "[D] [MNn], [Y]", "de", (), ()) 
31 Dezember, 2002 
ddtek:format-date($d, "[FNn] [D] [MNn] [Y]", "sv", (), ()) 
tisdag 31 december 2002 
ddtek:format-date($d, "[[[Y0001]-[M01]-[D01]]]") 
[2002-12-31] 
ddtek:format-date($d, "[YWw]", "en", (), ()) 
Two Thousand and Two 
ddtek:format-date($d, "[Dwo] [MNn]", "de", (), ()) 
einunddreißßigste Dezember 

ddtek:format-date-time

The ddtek:format-date-time function can be used to format date-time strings. Depending on your requirements, the ddtek:format-date and ddtek:format-time functions can also be used for this purpose.

The ddtek:format-date-time function is based on XSLT 2.0 date formatting functions as defined in the XSL Transformations (XSLT) Version 2.0 W3C Recommendation 23 January 2007. See http://www.w3.org/TR/xslt20/#format-date for more information.

Function Declarations

declare function ddtek:format-dateTime($value as xs:dateTime?, 
$picture as xs:string) as xs:string? 
declare function ddtek:format-dateTime( 
$value as xs:dateTime?, 
$picture as xs:string, 
$language as xs:string?, 
$calendar as xs:string?, 
$country as xs:string?) as xs:string? 

See ddtek:format-date for a discussion of function arguments.

Examples

The following list shows pairs of ddtek:format-dateTime function declarations and using an input value of $dt, specified as xs:dateTime('2002-12-31T15:58:00'). The complete XQuery code might look like this, for example:

let $dt := xs:dateTime('2002-12-31T15:58:00') 
return ( 
  ddtek:format-dateTime($dt, "[h].[m01][Pn] on [FNn], [D1o] 
[MNn]") 
) 

This XQuery returns this string:

3.58p.m. on Tuesday, 31st December 

Here is another example of the ddtek:format-dateTime function and the XQuery result:

		 ddtek:format-dateTime($dt, "[M01]/[D01]/[Y0001] at [H01]:[m01]:[s01]") 
		 12/31/2002 at 15:58:00 

ddtek:format-number

The ddtek:format-number function is used to format numbers.

The ddtek:format-number function is based on XSLT 2.0 format-number function as defined in the XSL Transformations (XSLT) Version 2.0 W3C Recommendation 23 January 2007. See http://www.w3.org/TR/xslt20/#format-number for more information.

Function Declarations

declare function ddtek:format-number($number as numeric?, $format 
as xs:string) as xs:string 
declare function ddtek:format-number( 
$number as numeric?, 
$format as xs:string, 
$decimal-separator as xs:string?, 
$grouping-separator as xs:string?, 
$infinity as xs:string?, 
$minus-sign as xs:string?, 
$NaN as xs:string?, 
$percent as xs:string?, 
$per-mille as xs:string?, 
$zero-digit as xs:string?, 
$digit as xs:string?, 
$pattern-separator as xs:string?) as xs:string 

where:

$number is the string representing the number you wantt o format.

$format is the format to be used for the digit representation. The default is #, but if you use the second function declaration you can use the value specified for the digit parameter.

The second function declaration takes additional parameters, as summarized in the following table.

Table 12-7. ddtek:format-number Function Parameters
Parameter
Value
Description
decimal-separator
char
Character used as the decimal character. Default is ".".
grouping-separator
char
Character used as the thousands separator. Default is ",".
infinity
string
String used to represent infinity. Default is "Infinity".
minus-sign
char
Character used to indicate negative numbers. Default is "-".
NaN
string
String used when the value is not a number. Default is "NaN".
percent
char
Character used as the precent sign. Default is "%".
per-mille
char
Character used as the per-thousand sign character. Defaule is "".
zero-digit
char
Character used as the zero digit. Decault is "0".
digit
char
Character used to indicate a place where a digit is required. Default is "#".
pattern-separator
char
Character used to separate positive and negative subpatterns in a format pattern. Default is ";".

Note that when you use the second function declaration for ddtek:format-number, you must specify all parameters, even those for which you wish to use the default values. To indicate that you wish to use a default value, specify the parameter as ().

Examples

Here are a few paired examples that show how to use the ddtek:format-number function. The function is shown on the first line; the result is shown on the second line.

These examples use the first function declaration:

ddtek:format-number(500100, "#") 
500100 
ddtek:format-number(500100, "###,###.00") 
500,100.00 
ddtek:format-number(0.23456, "#%") 
23% 

The following examples use the second function declaration. Here is an example that uses European style formatting for numbers – that is, using the comma for the decimal point and the period for the thousands separator:

ddtek:format-number(26825.8, "#.###,00", ",", ".", (), (), (), (), (), (), 
(), ()) 
26.825,80 

In this example, the $format argument is defined using a custom digit format, D:

ddtek:format-number(123456789, "$DDD,DDD,DDD.DD", (), (), (), (), (), (), (), 
(), 'D', ()) 
$123,456,789 

Note that in both of these examples all parameters for the ddtek:format-number declaration are specified.

ddtek:format-time

The ddtek:format-time function can be used to format time strings. Depending on your requirements, the ddtek:format-date-time function can also be used for this purpose.

The ddtek:format-time function is based on XSLT 2.0 date formatting functions as defined in the XSL Transformations (XSLT) Version 2.0 W3C Recommendation 23 January 2007. See http://www.w3.org/TR/xslt20/#format-date for more information.

Function Declarations

declare function ddtek:format-time($value as xs:time?, $picture as 
xs:string) as xs:string? 
declare function ddtek:format-time( 
$value as xs:time?, 
$picture as xs:string, 
$language as xs:string?, 
$calendar as xs:string?, 
$country as xs:string?) as xs:string? 

See ddtek:format-date for a discussion of function arguments.

Examples

The following list shows pairs of ddtek:format-time function declarations and using an input value of $t, specified as xs:time('15:58:00'). The complete XQuery code might look like this, for example:

let $t := xs:time('15:58:00') 
return ( 
  ddtek:format-time($t, "[h]:[m01] [PN]", "en", (), ()) 
) 

This XQuery returns this string:

3.58 P.M. 

Here are other examples of the ddtek:format-time function and the XQuery result:

ddtek:format-time($t, "[h]:[m01]:[s01] [Pn]", "en", (), ()) 
3:58:00 p.m. 
ddtek:format-time($t, "[h]:[m01]:[s01] [PN] [ZN,*-3]", "en", (), ()) 
3:58:00 P.M. 
ddtek:format-time($t, "[h]:[m01]:[s01] o'clock [PN] [ZN,*-3]", "en", (), ()) 
3:58:00 o'clock P.M. 
ddtek:format-time($t,"[H01]:[m01]") 
15:58 
ddtek:format-time($t,"[H01]:[m01]:[s01].[f001]") 
15:58:00.000 
ddtek:format-time($t,"[H01]:[m01]:[s01] [z]", "en", (), ()) 
15:58:00 
ddtek:format-time($t,"[H01]:[m01] Uhr [z]", "de", (), ()) 
15:58 Uhr 

ddtek:http-delete

The ddtek:http-delete function requests that the server delete the resource identified by the request URI. This function can be overridden by human intervention (or other means) on the server. Because of this, the client cannot be guaranteed that the operation has been carried out, even if the status code returned from the server indicates that the action has been completed successfully. However, the server should not indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

Successful responses are:

Note that responses to this function are not cacheable.

If the request passes through a cache and the URI identifies one or more currently cached entities, those entries should be treated as stale.

Function Declarations

declare function ddtek:http-delete($url as xs:string) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-delete($url as xs:string, 
$request as element()?) as 
document-node(element(*,xs:untyped)) external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example).

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:http-get

The ddtek:http-get function retrieves whatever information (in the form of an entity) is identified by the Request-URI. For example, if the Request-URI refers to a data-producing process, it is the produced data that is returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). This reduces unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.

If a Range header field is included, the request is for only the part of the entity specified by the range header. This allows partially retrieved entities to be completed without transferring previously received data.

Function Declarations

declare function ddtek:http-get($url as xs:string) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-get($url as xs:string, $request 
as element()?) as document-node(element(*,xs:untyped)) 
external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example).

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:http-head

The ddtek:http-head function is identical to the GET method except that the server must not return a message-body in the response. The meta-information contained in the HTTP headers in response to a HEAD request should be identical to the information sent in response to a GET request. This allows a client to obtain meta-information about a resource without actually transferring the resource itself.

The head function is often used for testing hyperlinks, accessibility and for determining if a document has been recently modified.

When your program is implementing caching, it is important to note that if the HEAD response indicates that the cached entity differs from the current entity, such as by a change in the Content-Length, Content-MD5, ETag or Last-Modified, the cache must treat the cached entry as stale.

Function Declarations

declare function ddtek:http-head($url as xs:string) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-head($url as xs:string, 
$request as element()?) as 
document-node(element(*,xs:untyped)) external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example).

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:http-options

The ddtek:http-options function represents a request for information about the communication options available on the request/response chain identified by the request URI.

This function allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating resource retrieval.

Function Declarations

declare function ddtek:http-options($url as xs:string) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-options($url as xs:string, 
$request as element()?) as 
document-node(element(*,xs:untyped)) external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example).

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:http-post

The ddtek:http-post function is used to request that the origin server (that is, the server hosting the resource) accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. Essentially this means that the POST data will be stored by the server and usually will be processed by a server side application.

The ddtek:http-post function is designed to allow a uniform approach to the following types of Web service application activities:

It is generally expected that a POST request will have some side effect on the server, such as writing to a database, and the HTTP specification suggests that user agents represent user actions which result in a POST request in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested. This however, is not a requirement.

Function Declarations

declare function ddtek:http-post($url as xs:string, 
$payload as item()?) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-post($url as xs:string, 
$payload as item()?, $request as element()?) as 
document-node(element(*,xs:untyped)) external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example).

$payload is an element that contains the service response.

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:http-put

The ddtek:http-put function requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, the enclosed entity should be considered as a modified version of the one residing on the origin server. If the URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.

If the request passes through a cache and the URI identifies one or more currently cached entities, those entries should be treated as stale. Responses to this function are not cacheable.

The fundamental difference between POST and PUT requests is reflected in the different meaning of the request URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request – the user agent knows what URI is intended and the server must not attempt to apply the request to some other resource.

Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request should be applied to the resource created or modified by the PUT.

Function Declarations

declare function ddtek:http-put($url as xs:string, $payload 
as item()?, $request as element()?) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-put($url as xs:string, $payload 
as item()?) as document-node(element(*,xs:untyped)) 
external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example).

$payload is an element that contains the service response.

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:http-trace

The ddtek:http-trace function is primarily used for debugging and testing purposes, and simply requests that the server echo back the request it received. This can be useful for identifying any changes to the request that is made by proxies.

The http-trace function is used to invoke a remote, application-layer loop-back of the request message. The final recipient of the request should reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a max-Forwards value of zero (0) in the request (see section 14.31 of RFC2616).

Function Declarations

declare function ddtek:http-trace($url as xs:string) as 
document-node(element(*,xs:untyped)) external; 
declare function ddtek:http-trace($url as xs:string, 
$request as element()?) as 
document-node(element(*,xs:untyped)) external; 

where:

$url is the URI of the origin server resource (http://www.examples.xquery.com, for example)

$request is a set of options specified as <request> element attributes to be consumed by the origin server (a username and password, for example). See HTTP Functions <request> Element for more information.

ddtek:info

Simple function that returns DataDirect XQuery version and build information and Java system properties for your DataDirect XQuery installation.

The function declaration for ddtek:info is:

declare function ddtek:info() as document-node() external; 

The ddtek:info function returns <ddxq> and <java> elements, a sample of which is shown here:

<info xmlns=""> 
    <ddxq> 
       <name>DataDirect XQuery</name> 
       <version>4.0</version> 
       <build>R0693</build> 
       <build-date>Wed May 27 20:03:55 CEST 2009</build-date> 
    </ddxq> 
    <java> 
       <java.runtime.name>Java(TM) SE Runtime Environment</java.runtime.name> 
       <sun.boot.library.path>C:\Program 
Files\Java\jre1.6.0_03\bin</sun.boot.library.path> 
       <java.vm.version>1.6.0_03-b05</java.vm.version> 
       <java.vm.vendor>Sun Microsystems Inc.</java.vm.vendor> 
       <java.vendor.url>http://java.sun.com/</java.vendor.url> 
       <path.separator>;</path.separator> 
       <java.vm.name>Java HotSpot(TM) Client VM</java.vm.name> 
       <file.encoding.pkg>sun.io</file.encoding.pkg> 
       <user.country>US</user.country> 
       <sun.os.patch.level>Service Pack 3</sun.os.patch.level>  
		... 
	</java> 
</info> 

NOTE: The specific subelements of the <java> element vary based on your installation.

ddtek:isValid

This function is similar to ddtek:validate but instead of returning $arg1 unchanged, it returns a boolean indicating whether it is valid for the specified XML Schema. Unlike ddtek:validate, ddtek:isValid does not cause the XQuery execution to throw an exception when the validation fails. An exception is thrown, however, if $schema does not resolve to a valid XML Schema resource.

The function declaration for ddtek:isValid is:

	declare function ddtek:isValid($arg1 as node(), $schema as xs:string) as
	xs:boolean external;  

NOTE: Using this function can degrade performance, depending on the size of the node to be validated and the complexity of the XML schema used to do the validation.

ddtek:javaCast

When possible, DataDirect XQuery keeps track of the exact Java class that is associated with a given ddtek:javaObject-typed expression. This is needed to map a given function call to a Java method. When DataDirect XQuery is unable to resolve the exact Java class statically, for example when passing ddtek:javaObject as a parameter to or a result from recursive XQuery functions, you can help DataDirect XQuery resolve the Java class by specifying the exact class through ddtek:javaCast. See Notes About Using Java Instance Methods for information about tracking Java classes.

When you use ddtek:javaCast, DataDirect XQuery assumes statically that the Java class of the expression that is cast is the class specified in the second argument of the call to the function. At runtime, the object is cast to the specified class. For example:

declare namespace A = "ddtekjava:com.ddtek.ejf.A"; 
declare namespace B = "ddtekjava:com.ddtek.ejf.B"; 
declare function A:A() as ddtek:javaObject external; 
declare function A:f($this as ddtek:javaObject) as 
xs:string external; 
declare function local:f($arg1 as ddtek:javaObject, $count
  as xs:integer)  
  as ddtek:javaObject { 
if ( $count eq 0 )  
then 
  $arg1 
else 
  local:f($arg1, $count - 1) 
}; 
let $a := local:f(A:A(), 1) 
return A:f(ddtek:javaCast($a, "com.ddtek.qa.ejf.A"))  

In this example, DataDirect XQuery cannot determine the class of the object that is returned by the local:f (recursive) function. By using ddtek:javaCast, any possible ambiguity is resolved. If, at runtime, the ddtek:javaCast operation fails, DataDirect XQuery raises an error.

ddtek:ltrim, ddtek:rtrim, and ddtek:trim

These three built-in functions trim whitespaces:

The function declarations for the DataDirect XQuery trim functions is:

ddtek:ltrim($string as xs:string?) as xs:string? 
ddtek:rtrim($string as xs:string?) as xs:string? 
ddtek:trim($string as xs:string?) as xs:string? 

where $string is the character string that is to be trimmed.

For example:

ddtek:rtrim("   Gustavo     ") 

returns:

"   Gustavo" 

and

ddtek:trim("   Gustavo     ") 

returns:

"Gustavo" 

ddtek:parse

ddtek:parse creates an XQuery Data Model instance from a string value, assuming the string contains well-formed XML. You can use this function to query XML information stored in character columns in database tables. When a database does not support an XML data type, sometimes XML information is stored in character columns. In such cases, ddtek:parse allows you to query the XML character data and use it as an XML data source.

The function declaration for ddtek:parse is:

ddtek:parse($arg as xs:string) as document-node(element(*,xs:untyped)) 

where $arg is a well-formed XML document. If $arg is not a well-formed XML document, the query execution is aborted and an exception can be handled at the XQJ level.

Assume a database table is created as:

create table xmltab (key int primary key, xmlval varchar(2000)) 
insert into xmltab values(1,'<a><b>1</b><b>11</b></a>') 
insert into xmltab values(2,'<a><b>2</b><b>22</b></a>') 

The following query returns the key value and b elements from the xmlval column for every b element that contains a value greater than 10:

for $x  in collection('xmltab')/xmltab 
let $y := ddtek:parse($x/xmlval)//b[xs:integer(.) > 10] 
return (data($x/key),$y) 

ddtek:serialize

This built-in function controls the process of serializing the query results into XML, XHTML, or HTML notation as specified by XQuery 1.0: An XML Query Language, W3C Recommendation 23 January 2007 located at: http://www.w3.org/TR/2007/REC-xquery-20070123/

The function declaration for ddtek:serialize is:

ddtek:serialize($items as item()*, $options as xs:string) as xs:string 

where:

$items specifies the sequence that is to be serialized.

$options specifies the serialization options. See Serialization Support for the serialization parameters that you can set using this function.

For example:

ddtek:serialize(<books><book/></books>, "indent=yes, omit-xml-declaration=no") 

returns the xs:string instance:

<?xml version="1.0"?> 
<books> 
  <book/> 
</books> 

ddtek:serialize-to-url

ddtek:serialize-to-url is equivalent to ddtek:serialize except that instead of returning a string of characters, it writes the result to I/O, allowing you to serialize XML nodes to a specified URI. This function takes advantage of DataDirect XQuery Streaming XML technique, avoiding the need to load the entire input value into memory. See Querying Large XML Documents to learn more about Streaming XML.

The function declaration for ddtek:serialize-to-url is:

ddtek:serialize-to-url(($items as item()*, $url as 
xs:string, $options as xs:string)) 

where:

$items specifies the input that is to be serialized.

$url specifies the URI where the result needs to be written. $url must be one of the standard URL schemes supported by Java. If no URL scheme is used, "file:" is implied. If the specified URI references an existing file, the file is overwritten; otherwise it is created.

To specify a ZIP as the target for ddtek:serialize-to-url, prefix the file URI with zip:. You can use the auto-create="yes" option to specify the creation of a new ZIP file. See Working with ZIP Files for more information.

$options specifies the serialization options. See Serialization Support for the serialization parameters that you can set using this function.

For example:

ddtek:serialize-to-url(<books><book/></books>, file:///c:/result.xml, 
"indent=yes, omit-xml-declaration=no")  

creates a file c:/result.xml on the file system with content:

<?xml version="1.0"?>  
<books>  
  <book/>  
</books> 

Working with ZIP Files

In addition to creating new XML documents, you can use ddtek:serialize-to-url to create ZIP files, and to create new entries in existing ZIP files.

This example shows how to add a new entry to an existing ZIP file. Note the use of the zip: prefix for the file URL:

ddtek:serialize-to-url(<e/>, "zip:file:///C:/tmp/test.zip!/dir/file.xml", "") 

This example shows how to add a new entry to a new ZIP file, which results from specifying the auto-create="yes" option:

ddtek:serialize-to-url(<e/>, 
"zip:file:///C:/tmp/test.zip!/dir/file.xml?auto-create=yes", "")  

ddtek:sql-delete

The ddtek:sql-delete built-in function deletes records in a database table.

The function declaration for ddtek:sql-delete is:

declare updating function ddtek:sql-delete( 
    row as element()*) external; 

where:

row identifies the records to be deleted. Each item in the sequence must be a row element of the database table returned by a previous fn:collection call.

The following example deletes all of the records in the holdings database table where the userid column equals Minollo.

ddtek:sql-delete(collection("holdings")/holdings[userid = "Minollo"]) 

Other examples can be found in the RDBMSUpdate example.

ddtek:sql-insert

The ddtek:sql-insert built-in function inserts a single record in a database table.

The function declaration for ddtek:sql-insert is:

declare updating function ddtek:sql-insert( 
    table as xs:string, 
    column as xs:string, 
    value as item()*, 
    ...) external; 

where:

table is the database table in which to insert the record. The semantics of table are equivalent to those for fn:collection; see Specifying Relational Database Tables.

column is the column of the database table in which to insert a value.

value is the value to insert into the specified column.

column and value are a pair in a variable argument list. If column is specified without value, an error is raised. You can specify multiple values for this pair, as shown in the example.

The following example inserts a new record with three columns into the holdings table. The columns and their values are
userid=Minollo, stockticker=TIVO, and shares=200.

ddtek:sql-insert("holdings", "userid", "Minollo", "stockticker", "TIVO", 
  "shares", 200) 

Other examples can be found in the RDBMSUpdate example.

ddtek:sql-update

The ddtek:sql-update built-in function updates records in a database table.

The function declaration for ddtek:sql-update is:

declare updating function ddtek:sql-update( 
    row as element()*, 
    column as xs:string, 
    value as item()*, 
    ...) external; 

where:

row identifies the records in the database table to update. Each item in the sequence must be a row element of the database table returned by a previous fn:collection call.

column is the column of the database table to update.

value is the new value for the specified column.

column and value are a pair in a variable argument list. If column is specified without value, an error is raised.

The following example updates a record in the holdings table – in particular, the record where the userid column equals Minollo and the stockticker column equals PRGS. In this record, the shares column is updated to 500.

ddtek:sql-update( 
  collection("holdings")/holdings[userid="Minollo" and stockticker="PRGS"], 
  "shares", 500) 

Other examples can be found in the RDBMSUpdate example.

ddtek:validate

ddtek:validate allows you to validate an XML element or document node against an element declaration in an XML Schema. Use this function if it is important to validate that:

NOTE: Using this function can degrade performance, depending on the size of the node to be validated and the complexity of the XML Schema used to do the validation.

See the section ddtek:isValidto learn about alternatives to the ddtek:validate function

The function declaration for ddtek:validate is:

ddtek:validate($arg1 as node(), $arg2 as xs:string)as node() external; 

where:

$arg1 is either an XML element or a document node.

$arg2 is a valid URI. If $arg2 is a relative URI, it is resolved using the base URI of the XQuery expression.

The function attempts to validate $arg1 against the XML Schema referred to by $arg2. If the validation succeeds, the function returns $arg1 unchanged. If the validation fails, DataDirect XQuery raises an error.

The following example first validates the input (req.xml) against the input XML Schema, req.xsd. Then, before returning the results, validates the results against the output XML Schema, reply.xsd.

Assume an XML document, req.xml, containing the following data:

<request-user-holdings> 
      <user id="Minollo"/> 
      <user id="Jonathan"/> 
      <user id="Bill"/> 
</request-user-holdings> 

Also, assume an associated input XML Schema, req.xsd:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
 elementFormDefault="qualified"> 
  <xs:element name="request-user-holdings"> 
    <xs:complexType> 
      <xs:sequence> 
        <xs:element maxOccurs="unbounded" ref="user"/> 
      </xs:sequence> 
    </xs:complexType> 
  </xs:element> 
  <xs:element name="user"> 
    <xs:complexType> 
      <xs:attribute name="id" use="required" type="xs:NCName"/> 
    </xs:complexType> 
  </xs:element> 
</xs:schema> 

Lastly, assume a second schema, reply.xsd, which is an output XML Schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"  
  elementFormDefault="qualified"> 
  <xs:element name="reply"> 
    <xs:complexType> 
      <xs:sequence> 
        <xs:element maxOccurs="unbounded" ref="user"/> 
      </xs:sequence> 
    </xs:complexType> 
  </xs:element> 
  <xs:element name="user"> 
    <xs:complexType> 
      <xs:sequence minOccurs="0"> 
        <xs:element ref="name"/> 
        <xs:element maxOccurs="unbounded" ref="holding"/> 
      </xs:sequence> 
      <xs:attribute name="id" use="required" type="xs:NCName"/> 
    </xs:complexType> 
  </xs:element> 
  <xs:element name="name" type="xs:string"/> 
  <xs:element name="holding"> 
    <xs:complexType> 
      <xs:attribute name="shares" use="required" type="xs:double"/> 
      <xs:attribute name="ticker" use="required" type="xs:NCName"/> 
    </xs:complexType> 
  </xs:element> 
</xs:schema> 

The following query returns holding information for each of the users in the input document, req.xml. The query first validates the input against the input XML Schema, req.xsd. Then, before returning the results, the query validates the results against the output XML Schema, reply.xsd.

declare base-uri "file:///c:/requests/"; 
let $validInput := ddtek:validate(doc('req.xml'),'req.xsd') 
let $output := 
  <reply>{ 
    for $req-user in $validInput//user 
    let $userid := xs:string($req-user/@id) 
    return 
      <user id='{$userid}'>{ 
        for $db-user in collection('users')/users[userid = $userid] 
        return ( 
          <name>{concat($db-user/firstname,' ',$db-user/lastname)}</name>, 
          for $holding in collection('holdings')/holdings  
          where $holding/userid = $userid 
          return 
            <holding ticker='{$holding/stockticker}' 
                     shares='{$holding/shares}'/> 
          ) 
      }</user> 
  }</reply> 
let $validatedOutput := ddtek:validate($output,'reply.xsd') 
return $validatedOutput 

ddtek:validate-and-report

The validate-and-report built-in function provides full error reporting.

The function declaration for ddtek:validate-and-report:

declare function ddtek:validate-and-report( 
 $arg1 as node(), $schema as xs:string) 
 as document-node(element(*,xs:untyped))  

Other built-in functions that provide validation support are ddtek:isValid and ddtek:validate.

Consider the following example. Given this XML Schema:

<?xml version="1.0"?> 
<xsd:schema  
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
 targetNamespace="http://www.xquery.com/examples"  
 xmlns="http://www.xquery.com/examples"> 
 <xsd:element name="books"> 
  <xsd:complexType> 
   <xsd:sequence> 
    <xsd:element name="book"> 
     <xsd:complexType> 
      <xsd:sequence> 
       <xsd:element name="title"/> 
      </xsd:sequence> 
     </xsd:complexType> 
    </xsd:element> 
   </xsd:sequence> 
  </xsd:complexType> 
 </xsd:element> 
</xsd:schema> 

This XML document is invalid, because it is missing the <title> element:

          <?xml version="1.0"?> 
          <p1:books xmlns:p1="http://www.xquery.com/examples"  
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
              xsi:schemaLocation="http://www.xquery.com/examples books.xsd"> 
              <book> 
                  <!--<title>My Title</title>--> 
              </book> 
          </p1:books> 

To capture such validation errors, the validate-and-report function can be employed in an XQuery like this one:

declare variable $books as document-node(element(*, xs:untyped)) external; 
 
 
ddtek:serialize-to-url( 
ddtek:validate-and-report($books, "books.xsd"), 
"file:///c:/errors/validation-result.xml","") 

Which results in the following XML:

<p1:validation-result  
    xmlns:p1="http://www.datadirect.com/xquery"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.datadirect.com/xquery 
                        validate-and-report.xsd"> 
 <error> 
  <exception> 
   <message>The content of element 'book' is not complete. One of '{title}' 
            is expected.</message> 
   <stack-trace/> 
  </exception> 
  <location> 
   <publicID/> 
   <systemID>file:/c:/DDXQ5.0/books-validation.xml</systemID> 
   <lineNumber>7</lineNumber> 
   <columnNumber>12</columnNumber> 
  </location> 
 </error> 
</p1:validation-result> 
 

ddtek:wscall

This built-in function allows you to invoke a Web service operation synchronously using SOAP over HTTP. (See http://www.w3.org/TR/soap11 for details about SOAP.)

The function declarations for ddtek:wscall are:

ddtek:wscall($location as element(), $payload as element())  
  as document-node( element(*, xs:untyped) ) 
ddtek:wscall($location as element(), $header as element(), 
  $payload as element())  
  as document-node( element(*, xs:untyped) ) 

where:

$location is an element named location as defined in the following XML Schema:

<?xml version="1.0"?> 
<xsd:schema  
 xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
 targetNamespace="http://www.datadirect.com/xquery"> 
  <xsd:element name="location"> 
    <xsd:complexType> 
       <xsd:attribute name="address" type="xsd:anyURI"/> 
       <xsd:attribute name="soapaction" type="xsd:string" 
         use="optional"/> 
       <xsd:attribute name="timeout" type="xsd:unsignedInt" 
         use="optional" default="30000"/> 
       <xsd:attribute name="user" type="xsd:string"  
         use="optional"/> 
       <xsd:attribute name="password" type="xsd:string" 
         use="optional"/> 
       <xsd:attribute name="http.proxyHost"  
         type="xsd:anyURI" use="optional"/> 
       <xsd:attribute name="http.proxyPort"  
         type="xsd:unsignedInt" use="optional"/> 
       <xsd:attribute name="http.proxyUser"  
         type="xsd:string" use="optional"/> 
       <xsd:attribute name="http.proxyPassword"  
         type="xsd:string" use="optional"/> 
       <xsd:attribute name="http.version" 
         type="xsd:string" use="optional" default="1.1"/ 
       <xsd:attribute name="compression" 
         type="xsd:string" use="optional" default=""/ 
       <xsd:attribute name="wrapAnyErrorsAsSOAPFault"  
         type="xsd:boolean" use="optional" default="true"/> 
    </xsd:complexType> 
  </xsd:element> 
</xsd:schema>  

For example:

<ddtek:location  
  address="http://www.ejse.com/WeatherService/Service.asmx" 
  soapaction="http://ejse.com/WeatherService/GetWeatherInfo"/> 

The following table defines the attributes in the XML schema.

Attribute Name
Description
address
Web service end point
soapaction
The SOAPAction HTTP header field
timeout
The connection timeout in milliseconds
user
User name for the HTTP connection, if required
password
Password for the HTTP connection if required
http:proxyHost
Proxy host address
http:proxyPort
Proxy port number
http:proxyUser
Proxy user name
http:proxyPassword
Proxy password
http:version
Version of the HTTP protocol to use when communicating with the server
compression
The type of file compression used to transmit the message. The default is off; you can specify "gzip".
wrapAnyErrorsAsSOAPFault
Determines if exceptions are returned

$header is the SOAP Header payload. See the SOAP Header specification at http://www.w3.org/TR/soap11/#_Toc478383497 for details. For example:

<tns:UserCreds xmlns:tns="http://ejse.com/WeatherService/"> 
    <tns:UserName>marypelle@acme.org</tns:UserName> 
    <tns:Password>30Mp75Y8p49s</tns:Password> 
</tns:UserCreds> 

$payload is an element that defines the payload expected by the web service, which is usually in a format defined by the Web Services Description Language (WSDL). See http://www.w3.org/TR/wsdl for details about WSDL. For example:

<tns:GetWeatherInfo xmlns:tns="http://ejse.com/WeatherService/"> 
    <tns:zipCode>01803</tns:zipCode> 
</tns:GetWeatherInfo> 

The return value is a document node that contains the web service response.

The following example invokes a web service that requires registration and uses the SOAP header to specify the user’s credentials:

ddtek:wscall( 
<ddtek:location  
  address="http://www.ejse.com/WeatherService/Service.asmx" 
  soapaction="http://ejse.com/WeatherService/GetWeatherInfo"/>, 
<tns:UserCreds xmlns:tns="http://ejse.com/WeatherService/"> 
    <tns:UserName>marypelle@acme.org</tns:UserName> 
    <tns:Password>30Mp75Y8p49s</tns:Password> 
</tns:UserCreds>, 
<tns:GetWeatherInfo xmlns:tns="http://ejse.com/WeatherService/"> 
    <tns:zipCode>01803</tns:zipCode> 
</tns:GetWeatherInfo>  
)