Monday, January 14, 2008

Oracle XQuery and the fn:doc-available Function

When using Oracle XQuery implementation, one important point to understand is that the fn:doc function returns an empty sequence if the specified resource is not found. This would be a problem if there was no way of knowing the difference between a resource that could not be found and an XQuery that did not match any results. Fortunately, Oracle's implementation of fn:doc-available function can be used to test for the availability of the resource. The screen shot shown next (click on it to see larger version) shows use of fn:doc-available against a URL with file:/// that returns true because the resource is found. However, as shown in the screen shot, when I fail to specify the file:/// protocol, false is returned. I also showed trying to use fn:doc against this same URL to demonstrate the return of the empty sequence rather than an error message. This behavior is as documented in Using XQuery with Oracle XML DB (Chapter 18 of Oracle XML DB Developer's Guide).

The screen shot specifically demonstrates use of XQLPlus to show use of fn:doc and fn:doc-available, but this behavior should be the same for all Oracle XQuery implementations.

Had I included the file:/// protocol in the URI to fn:doc, but with an invalid file location, an error would have been returned as shown in the next screen shot image:

So, Oracle XQuery implementations that are told to look for a file (with the file:/// protocol) and cannot find that file will report an error. On the other hand, if the URL resolves to something other than the file system (such as the default XML DB repository) with a non-valid value, an empty sequence is returned. The function doc-available returns false in both cases (file not found and non-file URI with no matching resource). Note that the XQuery implementations can also find documents in the database's XML DB repository and this is why file:/// is not a default (and C:\ cannot be found in the repository).

Use of doc-available is also recommended before fn:doc that accesses file system files (with file:///) because doc-available returns "false" for files that are wrong format (such as binary files or files with encoding other than UTF-8) and for files that are text but not XML. If fn:doc is used directly on the binary files an exception will be thrown with the message "Invalid UTF8 encoding." Likewise, if fn:doc is used directly on a non-XML text file, an exception will be thrown with the message "Start of root element expected." Using fn:doc-available in a conditional before using fn:doc in an XQuery script helps avoid these exceptions.

Specification details on fn:doc and fn:doc-available can be found in the XQuery 1.0 and XPath 2.0 Functions and Operators document.

No comments: