2.9.4 XQuery Modules

MonetDB/XQuery has support for modules. It helps XQuery users to structure their query code, but are also the instrument for MonetDB/XQuery to implement prepared queries (see next section).

All XRPC requests benefit from the prepared query mechanism.

The below shows a simple example of an XQuery module test.xq, that just defines a single function countDescendants("uri"):

  module namespace test = "http://monetdb.cwi.nl/XQuery/Documentation/Language/Modules/";
  
  declare function test:countDescendants($doc as xs:string) as xs:integer
  {
    count(doc($doc)//*)
  };

You may type import module inside an XQuery query, after which you can use the functions (and variables) defined in it:

  import module namespace test = "http://monetdb.cwi.nl/XQuery/Documentation/Language/Modules/"
                              at "http://monetdb.cwi.nl/XQuery/Documentation/Language/Modules/test.xq";
  test:countDescendants("http://monetdb.cwi.nl/xmark/auctions.xml")

which basically does the same as the ad-hoc query, namely counting how many nodes the XMark document has:

  count(doc("http://monetdb.cwi.nl/xmark/auctions.xml")//*)

Warning: while highly similar, the module feature as implemented by MonetDB/XQuery deviates in the following respects from the XQuery formal semantics:

  • You must give a location hint in the "import module" statement. Each file hinted there will be loaded as a module. It has to match the namespace given in the "import module" statement, though.
  • Modules cannot see variables declared in other modules, regardless if they imported the module themselves or not. A module is not allowed, though, to override variable declarations of other modules (conforming to the specs).
  • Modules will see functions defined in other modules. They are not allowed to override them, though.
  • All modules and the main query share the same type definitions. So modules will see XML Schema definitions imported by the main query. (see also below for XML Schema import)
  • Pathfinder does allow cyclic importing of modules, regardless of their namespace.
  • The XQuery specifications state that two module import statements that use the same target namespace should produce an error. This is not the case in MonetDB/XQuery: the module will be loaded once, but its functions and variables will be available under both namespace identifiers.