Search code examples
xqueryexist-db

How to solve empty parameters passed to an XQuery function in eXist-db


I am passing a parameter ('articles-counter') from a form to a function in an eXist-db app.

If there is nothing passed (the field is not filled in), this works:

let $xmldb-food := 
    (
        let $articles-counter := 
            (
                let $counter-passed := request:get-parameter('articles-counter', '')
                return
                    if ($counter-passed) then
                        $counter-passed
                    else ()
            )
        for $uri at $count in (1 to xs:integer($articles-counter))
        let $param := request:get-parameter(concat('article-uri-', $count), '')
        return
            if ($param ne '') then
                string-join($param, ',')
            else ()
    )

The next example does not. It throws xs:integer is expected (in the for range) but got ''. What is going on here? I would think it is almost the same:

let $xmldb-food := 
    (
        let $articles-counter := request:get-parameter('articles-counter', '')
        for $uri at $count in (1 to xs:integer($articles-counter))
        let $param := request:get-parameter(concat('article-uri-', $count), '')
        return
            if ($param ne '') then
                string-join($param, ',')
            else ()
    )

What is the difference between '' and () (empty sequence)?


Solution

  • Invoking the xs:integer() constructor with an empty string will throw a (dynamic runtime) error. Invoking with an empty sequence returns an empty sequence.

    You could filter out the empty string (and any other invalid integer values) with a predicate to avoid the dynamic error condition:

    for $uri at $count in (1 to xs:integer($articles-counter[. castable as xs:integer]))