Thursday, October 20, 2011

Testing for an empty sequence in XQuery

In an XQuery code base I was maintaining recently, all external variables were strongly typed as strings (declare variable $input as xs:string external;). This saved some time and lines of code since we always knew the type of those variables and the code would fail fast if they were not strings.

Unfortunately, the writers of the calling code decided it was too hard to make sure an empty string was passed in for certain cases and they wanted to pass in null, which was translated to the empty sequence. Rather than make edits to many different functions, we edited the main modules to be more defensive.

For some reason I have a hard time remembering how to test for an empty sequence and I also wasn't sure if I could redefine a declared variable in a FLOWR so I wrote the little test snippet below.
xquery version "1.0-ml";
declare variable $input := ();

let $original-input := $input
let $input := if(fn:empty($input)) then "" else $input

return (
element results {
element original-input-empty { fn:empty($original-input) },
element revised-input-empty { fn:empty($input) }

No comments: