Search code examples
recursionxqueryexist-db

How to list collections/resources recursivelly in XQuery


I would like to list all collections from a particular point recursively:

declare function local:list-collections($collection as xs:string) {
    for $child in xmldb:get-child-collections($collection)
    return
        local:list-collections(concat($collection, '/', $child))
};

local:list-collections('/db/apps/tested-bunny/data/')

This returns nothing (no errors, no results). I am inspired by this article and consider it as a good starting point for recursive setting of permissions and so on.


Solution

  • See the dbutil:scan-*() functions in Wolfgang Meier's article on higher order functions with XQuery in eXist-db 2.0+. The article is very instructive article in general. These days the dbutil module is available in the shared-resources package that is installed by default with eXist, so you can make use of it as follows:

    xquery version "3.0";
    
    import module namespace dbutil="http://exist-db.org/xquery/dbutil" 
        at "/db/apps/shared-resources/content/dbutils.xql";
    
    dbutil:scan-collections(
        xs:anyURI('/db'), 
        function($collection) { $collection } 
    )
    

    These functions perform well. I just ran this in eXide and the query returned 4125 collection names in 0.699s.