fix syntax error for 8.5

fix syntax error for 8.5

(:~
: This is the Care Services Discovery stored query registry
: @version 1.0
: @see https://github.com/openhie/openinfoman
:
:)
module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_psd = "https://github.com/openhie/openinfoman/csd_psd";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare function csd_lsc:get_document_name($name) {
  csd_dm:document_source($name)
(:  concat("local_services_cache/",$name,".xml") :)
};

declare function csd_lsc:directory_exists($name) {
  db:is-xml($csd_webconf:db,csd_lsc:get_document_name($name))
};

declare updating function csd_lsc:empty_cache($name)
{
  (
    csd_dm:empty($name)
    ,csd_lsc:set_service_directory_mtime($name,$csd_lsc:beginning_of_time)
   )

};

declare function csd_lsc:get_cache($name)
{
 if (csd_lsc:directory_exists($name)) then
    db:open($csd_webconf:db,csd_lsc:get_document_name($name))
  else csd_dm:blank_directory()
};

declare variable $csd_lsc:beginning_of_time := '1970-01-01T00:00:00+00:00';
declare variable $csd_lsc:cache_meta_doc := 'local_cache_meta.xml';

declare function csd_lsc:get_cache_data($name)
{
  if ( not( db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc)))  then
    if ($name) then
      ()
    else
      <cacheData/>
  else
    let $meta_doc :=  db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)
    return if ($name) then
      $meta_doc/cacheData/serviceCache[@name = $name]
    else
      $meta_doc/cacheData
};

declare updating function csd_lsc:drop_cache_data($name)
{
  if ( not(db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc)))  then
    ()
  else
    let $meta_doc :=  db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)
      return if ($name) then
	delete node $meta_doc/cacheData/serviceCache[@name = $name]
      else
	delete node $meta_doc/cacheData/*

};

declare  function csd_lsc:cache_meta_exists() {
  db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc)
};

declare updating function csd_lsc:init_cache_meta() {
  if ( not(csd_lsc:cache_meta_exists()))  then
    db:add($csd_webconf:db, <cacheData/>,$csd_lsc:cache_meta_doc)
  else
      ()
};

declare updating function csd_lsc:set_service_directory_mtime($name,$mtime)
{
  ( csd_lsc:init_cache_meta()
  ,
  try {
    let $dt :=  xs:dateTime($mtime) (: just to make sure it's valid :)
    let $meta :=  db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)/cacheData
    return
      if (not(exists($meta/serviceCache[@name = $name])))
      then insert node <serviceCache name="{$name}" mtime="{$csd_lsc:beginning_of_time}"/> into $meta
      else if (not(exists($meta/serviceCache[@name = $name]/@mtime)))
      then
        let $attr := attribute {"mtime"}{ $csd_lsc:beginning_of_time}
        return ( insert  node $attr into $meta/serviceCache[@name = $name])
      else
        replace value of node $meta/serviceCache[@name = $name]/@mtime with $mtime
  } catch * {
     ()  (: do nothing :)
  }
  )

};

declare function csd_lsc:get_service_directory_mtime($name)
{
  if ( db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc))  then
    let $mtime := text{db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)/cacheData/serviceCache[@name = $name]/@mtime}
    return if ($mtime) then
	$mtime
      else
	$csd_lsc:beginning_of_time
    else
      $csd_lsc:beginning_of_time

};

declare  updating  function csd_lsc:update_cache($name)
{

  let $mtime :=  csd_lsc:get_service_directory_mtime($name)
(:  querying against self during an update will cause a deadlock :)
(:  see or :)
(:  http://www.mail-archive.com/basex-talk@mailman.uni-konstanz.de/msg02999.htmlhttp://www.mail-archive.com/basex-talk@mailman.uni-konstanz.de/msg02999.html  :)
(:  possible work-around: http://docs.basex.org/wiki/Server_Protocol ? :)
  let $currtime := current-dateTime()
  let $result := csd_psd:poll_service_directory($name,$mtime)
  let $cache_doc := csd_lsc:get_cache($name)

  return (
    csd_lsc:refresh_doc($cache_doc,$result)
    ,csd_lsc:set_service_directory_mtime($name,$currtime)

  )

};

declare updating function csd_lsc:refresh_doc($cache_doc,$updates)
{
  csd_lsc:refresh_doc($cache_doc,$updates,true())
};

declare updating function csd_lsc:refresh_doc($cache_doc,$updates,$overwriteExisting)
{
  (
   csd_lsc:update_directory($cache_doc/csd:CSD/csd:organizationDirectory,$updates/(csd:CSD/csd:organizationDirectory|csd:organizationDirectory),$overwriteExisting)
  ,csd_lsc:update_directory($cache_doc/csd:CSD/csd:facilityDirectory,$updates/(csd:CSD/csd:facilityDirectory|csd:facilityDirectory),$overwriteExisting)
  ,csd_lsc:update_directory($cache_doc/csd:CSD/csd:serviceDirectory,$updates/(csd:CSD/csd:serviceDirectory|csd:serviceDirectory),$overwriteExisting)
  ,csd_lsc:update_directory($cache_doc/csd:CSD/csd:providerDirectory,$updates/(csd:CSD/csd:providerDirectory|csd:providerDirectory),$overwriteExisting)
  )
};

declare updating function csd_lsc:update_directory($oldDir,$newDir)  {
  csd_lsc:update_directory($oldDir,$newDir,true())
};

declare updating function csd_lsc:update_directory($oldDir,$newDir,$overwriteExisting)
{
  csd_lsc:update_directory_entities($oldDir,$newDir/*,$overwriteExisting)
};

declare updating function csd_lsc:update_directory_entities($dir,$entities)  {
  csd_lsc:update_directory_entities($dir,$entities,true())
};

declare updating function csd_lsc:update_directory_entities($dir,$entities,$overwriteExisting)
{
  for $new in  $entities
  let $old := $dir/*[@entityID = $new/@entityID] (:there may be more than one:)
  return (
     if ($overwriteExisting)
     then
       (
	 for $o in $old
	 return delete node $o
	 ,
	 insert node $new into $dir
       )
     else
       (
	 if (count($old) > 0)
	 then ()
	 else insert node $new into $dir
       )
   )
};

(:~
: This is the Care Services Discovery stored query registry
: @version 1.0
: @see https://github.com/openhie/openinfoman
:
:)
module namespace csd_lsc = "https://github.com/openhie/openinfoman/csd_lsc";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace csd_psd = "https://github.com/openhie/openinfoman/csd_psd";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare function csd_lsc:get_document_name($name) {
  csd_dm:document_source($name)
(:  concat("local_services_cache/",$name,".xml") :)
};

declare function csd_lsc:directory_exists($name) {
  db:is-xml($csd_webconf:db,csd_lsc:get_document_name($name))
};

declare updating function csd_lsc:empty_cache($name)
{
  (
    csd_dm:empty($name)
    ,csd_lsc:set_service_directory_mtime($name,$csd_lsc:beginning_of_time)
   )

};

declare function csd_lsc:get_cache($name)
{
 if (csd_lsc:directory_exists($name)) then
    db:open($csd_webconf:db,csd_lsc:get_document_name($name))
  else csd_dm:blank_directory()
};

declare variable $csd_lsc:beginning_of_time := '1970-01-01T00:00:00+00:00';
declare variable $csd_lsc:cache_meta_doc := 'local_cache_meta.xml';

declare function csd_lsc:get_cache_data($name)
{
  if ( not( db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc)))  then
    if ($name) then
      ()
    else
      <cacheData/>
  else
    let $meta_doc :=  db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)
    return if ($name) then
      $meta_doc/cacheData/serviceCache[@name = $name]
    else
      $meta_doc/cacheData
};

declare updating function csd_lsc:drop_cache_data($name)
{
  if ( not(db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc)))  then
    ()
  else
    let $meta_doc :=  db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)
      return if ($name) then
	delete node $meta_doc/cacheData/serviceCache[@name = $name]
      else
	delete node $meta_doc/cacheData/*

};

declare  function csd_lsc:cache_meta_exists() {
  db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc)
};

declare updating function csd_lsc:init_cache_meta() {
  if ( not(csd_lsc:cache_meta_exists()))  then
    db:add($csd_webconf:db, <cacheData/>,$csd_lsc:cache_meta_doc)
  else
      ()
};

declare updating function csd_lsc:set_service_directory_mtime($name,$mtime)
{
  ( csd_lsc:init_cache_meta()
  ,
  try {
    let $dt :=  xs:dateTime($mtime) (: just to make sure it's valid :)
    let $meta :=  db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)/cacheData
    return
      if (not(exists($meta/serviceCache[@name = $name])))
      then insert node <serviceCache name="{$name}" mtime="{$csd_lsc:beginning_of_time}"/> into $meta
      else if (not(exists($meta/serviceCache[@name = $name]/@mtime)))
      then
        let $attr := attribute {"mtime"}{ $csd_lsc:beginning_of_time}
        return ( insert  node $attr into $meta/serviceCache[@name = $name])
      else
        replace value of node $meta/serviceCache[@name = $name]/@mtime with $mtime
  } catch * {
    return ()  (: do nothing :)
  }
  )

};

declare function csd_lsc:get_service_directory_mtime($name)
{
  if ( db:is-xml($csd_webconf:db,$csd_lsc:cache_meta_doc))  then
    let $mtime := text{db:open($csd_webconf:db,$csd_lsc:cache_meta_doc)/cacheData/serviceCache[@name = $name]/@mtime}
    return if ($mtime) then
	$mtime
      else
	$csd_lsc:beginning_of_time
    else
      $csd_lsc:beginning_of_time

};

declare  updating  function csd_lsc:update_cache($name)
{

  let $mtime :=  csd_lsc:get_service_directory_mtime($name)
(:  querying against self during an update will cause a deadlock :)
(:  see or :)
(:  http://www.mail-archive.com/basex-talk@mailman.uni-konstanz.de/msg02999.htmlhttp://www.mail-archive.com/basex-talk@mailman.uni-konstanz.de/msg02999.html  :)
(:  possible work-around: http://docs.basex.org/wiki/Server_Protocol ? :)
  let $currtime := current-dateTime()
  let $result := csd_psd:poll_service_directory($name,$mtime)
  let $cache_doc := csd_lsc:get_cache($name)

  return (
    csd_lsc:refresh_doc($cache_doc,$result)
    ,csd_lsc:set_service_directory_mtime($name,$currtime)

  )

};

declare updating function csd_lsc:refresh_doc($cache_doc,$updates)
{
  csd_lsc:refresh_doc($cache_doc,$updates,true())
};

declare updating function csd_lsc:refresh_doc($cache_doc,$updates,$overwriteExisting)
{
  (
   csd_lsc:update_directory($cache_doc/csd:CSD/csd:organizationDirectory,$updates/(csd:CSD/csd:organizationDirectory|csd:organizationDirectory),$overwriteExisting)
  ,csd_lsc:update_directory($cache_doc/csd:CSD/csd:facilityDirectory,$updates/(csd:CSD/csd:facilityDirectory|csd:facilityDirectory),$overwriteExisting)
  ,csd_lsc:update_directory($cache_doc/csd:CSD/csd:serviceDirectory,$updates/(csd:CSD/csd:serviceDirectory|csd:serviceDirectory),$overwriteExisting)
  ,csd_lsc:update_directory($cache_doc/csd:CSD/csd:providerDirectory,$updates/(csd:CSD/csd:providerDirectory|csd:providerDirectory),$overwriteExisting)
  )
};

declare updating function csd_lsc:update_directory($oldDir,$newDir)  {
  csd_lsc:update_directory($oldDir,$newDir,true())
};

declare updating function csd_lsc:update_directory($oldDir,$newDir,$overwriteExisting)
{
  csd_lsc:update_directory_entities($oldDir,$newDir/*,$overwriteExisting)
};

declare updating function csd_lsc:update_directory_entities($dir,$entities)  {
  csd_lsc:update_directory_entities($dir,$entities,true())
};

declare updating function csd_lsc:update_directory_entities($dir,$entities,$overwriteExisting)
{
  for $new in  $entities
  let $old := $dir/*[@entityID = $new/@entityID] (:there may be more than one:)
  return (
     if ($overwriteExisting)
     then
       (
	 for $o in $old
	 return delete node $o
	 ,
	 insert node $new into $dir
       )
     else
       (
	 if (count($old) > 0)
	 then ()
	 else insert node $new into $dir
       )
   )
};


be more generous in extracting id_number and id_type from the careServicesRequest

import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)

let $id_number := ($careServicesRequest/id_number , $careServicesRequest/csd:id_number)[1]
let $id_type := ($careServicesRequest/id_type, $careServicesRequest/csd:id_type)[1]

let $provider :=
  if (exists($id_number) and exists($id_type))
  then
     let $provs :=   /csd:CSD/csd:providerDirectory/csd:provider[./csd:otherID[./@code = $id_type and ./text() = $id_number]]
     return $provs[1]
  else ()

return $provider

import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)

let $id_number := $careServicesRequest/id_number
let $id_type := $careServicesRequest/id_type

let $provider :=
  if (exists($id_number) and exists($id_type))
  then
     let $provs :=   /csd:CSD/csd:providerDirectory/csd:provider[./csd:otherID[./@code = $id_type and ./text() = $id_number]]
     return $provs[1]
  else ()

return $provider


fixed issue in facility read

fixed issue in facility read

import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)

let $facs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/facilityDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs0,$careServicesRequest/id) else ()
let $facs2 :=
  if (count($facs1) = 1)
    then
    let $facility :=  $facs1[1]
    return
      <facility entityID="{$facility/@entityID}">
	  {
	    (
	    <organizations>
	      {
		for $org in $facility/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID ) ]
		return
		<organization entityID="{$org/@entityID}"></organization>
	      }
	    </organizations>

	      ,
	      $facility/record
	    )
	  }
      </facility>
  else ()

return csd_bl:wrap_facilties($facs2)

import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)

let $facs0 := if (exists($careServicesRequest/organization/@entityID)) then /CSD/facilityDirectory/*  else ()
let $facs1 := if (exists($careServicesRequest/id/@entityID)) then csd_bl:filter_by_primary_id($facs0,$careServicesRequest/id) else ()
let $facs2 :=
  if (count($facs1) = 1)
    then
    let $facility :=  $facs1[1]
    return
      <facility entityID="{$facility/@entityID}">
	  {
	    (
	    <organizations>
	      {
		for $org in $facility/organizations/organization[upper-case(@entityID) = upper-case($careServicesRequest/organization/@entityID ) ]
		return
		<organization entityID="{$org/@entityID}"></organization>
	      }
	    </organizations>

	      ,
	      $facility/record
	    )
	  }
      </facility>
  else ()

return csd_bl:wrap_facilties($provs2)


Updates to smtp library.

Updates to smtp library.

  * Updated text_with_image.xq so that it assigns a name to the passed attachement.

(:~
 : This example uses the send function of the email/smtp module to send an email containing a simple text message with an image as attachement from a gmail account.
 : To make things really interesting, the image is made on the spot with the modules from the zorba imaging library.
 :)
import module namespace smtp = 'http://www.zorba-xquery.com/modules/email/smtp';

import module namespace basic = 'http://www.zorba-xquery.com/modules/image/basic';
import module namespace paint = 'http://www.zorba-xquery.com/modules/image/paint';
import schema namespace image = 'http://www.zorba-xquery.com/modules/image/image';

import schema namespace email = 'http://www.zorba-xquery.com/modules/email/email';
import schema namespace imaps = 'http://www.zorba-xquery.com/modules/email/imap';

(:~
 : This variable contains the information on the account from which the email should be sent.
 :)
declare variable $local:sender-host-info as element(imaps:hostInfo) := (<imaps:hostInfo><hostName>smtp.gmail.com:587/tls/novalidate-cert</hostName><userName>zorba.smtp.sender</userName><password>1openssl!</password></imaps:hostInfo>);

(: the send function takes the host info and a xml representation of the email to be sent as arguments, the schema describing the email xml can be found at http://www.zorba-xquery.com/modules/email/email. :)

let $image as xs:base64Binary := paint:paint(basic:create(xs:unsignedInt(200), xs:unsignedInt(200), "GIF"), <image:text><origin><x>20</x><y>50</y></origin><text>Zorba really rocks.</text>Arial14</image:text>)
return smtp:send($local:sender-host-info,
      <email:message>
        <envelope>
          <date>2010-11-26T15:50:39-04:01</date>
          <subject>An important message</subject>
          <recipient><to><name>Test Account</name><email>imaptest@28msec.com</email></to></recipient>
         </envelope>

          <multipart contentType="multipart/mixed" charset="UTF-8" contentTransferEncoding="ENC8BIT">
          <content contentType="text/plain" charset="UTF-8" contentTransferEncoding="ENC8BIT">
            Zorba really rocks.
          </content>
          <content contentType="image/gif" charset="UTF-8" contentTransferEncoding="ENCBASE64" contentDisposition="attachement" contentDisposition-filename="the-truth.gif">
            {$image}
          </content>
          </multipart>

      </email:message>);

(:~
 : This example uses the send function of the email/smtp module to send an email containing a simple text message with an image as attachement from a gmail account.
 : To make things really interesting, the image is made on the spot with the modules from the zorba imaging library.
 :)
import module namespace smtp = 'http://www.zorba-xquery.com/modules/email/smtp';

import module namespace basic = 'http://www.zorba-xquery.com/modules/image/basic';
import module namespace paint = 'http://www.zorba-xquery.com/modules/image/paint';
import schema namespace image = 'http://www.zorba-xquery.com/modules/image/image';

import schema namespace email = 'http://www.zorba-xquery.com/modules/email/email';
import schema namespace imaps = 'http://www.zorba-xquery.com/modules/email/imap';

(:~
 : This variable contains the information on the account from which the email should be sent.
 :)
declare variable $local:sender-host-info as element(imaps:hostInfo) := (<imaps:hostInfo><hostName>smtp.gmail.com:587/tls/novalidate-cert</hostName><userName>zorba.smtp.sender</userName><password>1openssl!</password></imaps:hostInfo>);

(: the send function takes the host info and a xml representation of the email to be sent as arguments, the schema describing the email xml can be found at http://www.zorba-xquery.com/modules/email/email. :)

let $image as xs:base64Binary := paint:paint(basic:create(xs:unsignedInt(200), xs:unsignedInt(200), "GIF"), <image:text><origin><x>20</x><y>50</y></origin><text>Zorba really rocks.</text>Arial14</image:text>)
return smtp:send($local:sender-host-info,
      <email:message>
        <envelope>
          <date>2010-11-26T15:50:39-04:01</date>
          <subject>An important message</subject>
          <recipient><to><name>Test Account</name><email>imaptest@28msec.com</email></to></recipient>
         </envelope>

          <multipart contentType="multipart/mixed" charset="UTF-8" contentTransferEncoding="ENC8BIT">
          <content contentType="text/plain" charset="UTF-8" contentTransferEncoding="ENC8BIT">
            Zorba really rocks.
          </content>
          <content contentType="image/gif" charset="UTF-8" contentTransferEncoding="ENCBASE64">
            {$image}
          </content>
          </multipart>

      </email:message>);


Added further XQuery 3.0 String Conatentaion Expression tests

xquery version "3.0";

declare namespace other = "http://other";

declare variable $local:straight-var1 := 'one';

declare %private variable $local:private-var := 'secret';
declare %public variable $local:public-var := 'not-secret';
declare %other:annotation('param1', "param2") variable $local:some-var := 'anything';

declare variable $local:straight-var2 := 'two';

(: Simple Map Operator example :)
declare function local:word-count($elms as element()*) as xs:integer {
	sum($elms ! count(tokenize(., '\s+')))
};

declare function local:add($a, $b) {
	$a + $b
};

declare function local:dispatch($node as node()) as item()* {
    typeswitch($node)
        case text() return $node
        case comment() return $node
        case element(bill) return local:bill($node)
        case element(btitle) return local:btitle($node)
        case element(section-id) return local:section-id($node)
        case element(bill-text) return local:bill-text($node)
        case element(strike) return local:strike($node)
        default return local:passthru($node)
};

(: `switch` expression example :)
declare function local:noise($animal) {
	let $duck := "Duck",
	$quack := "Quack"
	return
		switch ($animal)
			case "Cow" return "Moo"
			case 'Cat' return 'Meow'
			case $duck return $quack
			default return "What's that odd noise?"
};

(: `group by` expression with binding example :)
declare function local:a-to-z() {
	let $data as element()* := (
		<item>Apples</item>,
		<item>Bananas</item>,
		<item>Apricots</item>,
		<item>Pears</item>,
		<item>Brambles</item>
	) return
		<GroupedItems>{
			for $item in $data
			group by $key := upper-case(substring($item, 1, 1))
			order by $key
			return
				<Group key="{$key}">{$item}</Group>
		}</GroupedItems>
};

(: `group by` expression example :)
declare function local:plays-by-character() {
	let $plays := (
		document {
			<play>
				<title>Hamlet</title>
				<characters>
					<character>Hamlet</character>
					<character>Claudius</character>
					<character>Polonius</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Francisco</character>
					<character>Reynaldo</character>
				</characters>
			</play>
		},
		document {
			<play>
				<title>Rosenkrantz and Guildenstern are Dead</title>
				<characters>
					<character>Alfred</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Hamlet</character>
					<character>Claudius</character>
				</characters>
			</play>
		}
	) return

		for $play in $plays/play
		let $title := $play/title
		for $character in $play/characters/character
		group by $character
		return
			<character name="{$character}">
			{
				$title ! <play>{ . }</play>
     		}
			</character>
};

declare
	%other:a
	%private
	%other:b('1')
	%other:c("1", "2", "3", "4")
function local:very-annotated() {
	let $thing := "thing"
	return
		$thing
};

declare %public function local:slightly-annotated() {
	let $nothing := ()
	return
		$nothing
};

declare function local:ordered() {
	for $hit in doc("/db/doc-with-indexes.xml")//tei:p[other:query(., $search-expression)]
	let $score as xs:float := other:score($hit)
	order by $score descending
	return (

Score: {$score}:
,
		other:summarize($hit, <config width="40"/>)
	)
};

declare function local:concat-expr($postfix) {

	let $concatenated := other:uri() || "/" || $postfix
	return
		$concatenated
};

declare function local:human-units($bytes) {
	let $unit := if($bytes > math:pow(1024, 3)) then
		(math:pow(1024, 3), "GB")
	else if($bytes > math:pow(1024, 2)) then
		(math:pow(1024, 2), "MB")
	else
		(1024, "KB")
	return
		format-number($bytes div $unit[1], ".00") || " " || $unit[2]
};

declare function local:merge-simple($a as xs:string+, $b as xs:string+) as xs:string+ {
	($a, $b)
};

(: higher order function example 1 :)
declare function local:apply($func, $value) {
	$func($value)
};

(: higher order function example 2 :)
declare function local:apply-all($func, $list) {
	$list ! $func(.)
};

(: higher order function example 3 :)
declare function local:apply-all-long($func as function(xs:string) as xs:string, $list) {
	$list ! $func(.)
};

(: higher order function example 4 :)
declare function local:merge($func as function(xs:string+, xs:string+) as xs:string+, $a as xs:string+, $b as xs:string+) as xs:string+ {
	$func($a, $b)
};

let $to-upper := upper-case#1
let $to-upper-long as function(xs:string) as xs:string := upper-case#1
return
    <case>
    {
        local:apply-all($to-upper, ("Hello", "world!")) ! <upper>{.}</upper>,
        local:apply-all-long(lower-case#1, ("Hello", "world!")) ! <lower>{.}</lower>
    }
    </case>

xquery version "3.0";

declare namespace other = "http://other";

declare variable $local:straight-var1 := 'one';

declare %private variable $local:private-var := 'secret';
declare %public variable $local:public-var := 'not-secret';
declare %other:annotation('param1', "param2") variable $local:some-var := 'anything';

declare variable $local:straight-var2 := 'two';

(: Simple Map Operator example :)
declare function local:word-count($elms as element()*) as xs:integer {
	sum($elms ! count(tokenize(., '\s+')))
};

declare function local:add($a, $b) {
	$a + $b
};

declare function local:dispatch($node as node()) as item()* {
    typeswitch($node)
        case text() return $node
        case comment() return $node
        case element(bill) return local:bill($node)
        case element(btitle) return local:btitle($node)
        case element(section-id) return local:section-id($node)
        case element(bill-text) return local:bill-text($node)
        case element(strike) return local:strike($node)
        default return local:passthru($node)
};

(: `switch` expression example :)
declare function local:noise($animal) {
	let $duck := "Duck",
	$quack := "Quack"
	return
		switch ($animal)
			case "Cow" return "Moo"
			case 'Cat' return 'Meow'
			case $duck return $quack
			default return "What's that odd noise?"
};

(: `group by` expression with binding example :)
declare function local:a-to-z() {
	let $data as element()* := (
		<item>Apples</item>,
		<item>Bananas</item>,
		<item>Apricots</item>,
		<item>Pears</item>,
		<item>Brambles</item>
	) return
		<GroupedItems>{
			for $item in $data
			group by $key := upper-case(substring($item, 1, 1))
			order by $key
			return
				<Group key="{$key}">{$item}</Group>
		}</GroupedItems>
};

(: `group by` expression example :)
declare function local:plays-by-character() {
	let $plays := (
		document {
			<play>
				<title>Hamlet</title>
				<characters>
					<character>Hamlet</character>
					<character>Claudius</character>
					<character>Polonius</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Francisco</character>
					<character>Reynaldo</character>
				</characters>
			</play>
		},
		document {
			<play>
				<title>Rosenkrantz and Guildenstern are Dead</title>
				<characters>
					<character>Alfred</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Hamlet</character>
					<character>Claudius</character>
				</characters>
			</play>
		}
	) return

		for $play in $plays/play
		let $title := $play/title
		for $character in $play/characters/character
		group by $character
		return
			<character name="{$character}">
			{
				$title ! <play>{ . }</play>
     		}
			</character>
};

declare
	%other:a
	%private
	%other:b('1')
	%other:c("1", "2", "3", "4")
function local:very-annotated() {
	let $thing := "thing"
	return
		$thing
};

declare %public function local:slightly-annotated() {
	let $nothing := ()
	return
		$nothing
};

declare function local:ordered() {
	for $hit in doc("/db/doc-with-indexes.xml")//tei:p[other:query(., $search-expression)]
	let $score as xs:float := other:score($hit)
	order by $score descending
	return (

Score: {$score}:
,
		other:summarize($hit, <config width="40"/>)
	)
};

declare function local:merge-simple($a as xs:string+, $b as xs:string+) as xs:string+ {
	($a, $b)
};

(: higher order function example 1 :)
declare function local:apply($func, $value) {
	$func($value)
};

(: higher order function example 2 :)
declare function local:apply-all($func, $list) {
	$list ! $func(.)
};

(: higher order function example 3 :)
declare function local:apply-all-long($func as function(xs:string) as xs:string, $list) {
	$list ! $func(.)
};

(: higher order function example 4 :)
declare function local:merge($func as function(xs:string+, xs:string+) as xs:string+, $a as xs:string+, $b as xs:string+) as xs:string+ {
	$func($a, $b)
};

let $to-upper := upper-case#1
let $to-upper-long as function(xs:string) as xs:string := upper-case#1
return
    <case>
    {
        local:apply-all($to-upper, ("Hello", "world!")) ! <upper>{.}</upper>,
        local:apply-all-long(lower-case#1, ("Hello", "world!")) ! <lower>{.}</lower>
    }
    </case>


XQTS: small update results script

XQTS: small update results script

svn path=/trunk/eXist-1.0/; revision=4120

declare option exist:serialize "method=xml indent=yes";
declare option exist:output-size-limit "-1";
declare namespace response="http://exist-db.org/xquery/response";

let $product-version := util:system-property("product-version")
let $product-build := util:system-property("product-build")
let $test-suite := doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/@version
let $dummy := response:set-header("Content-Disposition", concat(
	"attachment; filename="results_XQTS-" , $test-suite , "_eXist-" ,
	$product-version , '_' , $product-build , ".xml"" ) )

return
<test-suite-result xmlns="http://www.w3.org/2005/02/query-test-XQTSResult"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

        <implementation name="eXist-{$product-version}" version="{$product-build}" anonymous-result-column="false">

                <organization name="eXist Open Source native XML database"  website="http://www.exist-db.org" anonymous="false"/>

                <submittor name="eXist XQTS testsuite runner" email="me@not.com"/>

                <description>

eXist is an Open Source native XML database featuring efficient,
                        index-based XQuery processing, automatic indexing, extensions for full-text
                        search,  XUpdate  support and tight integration with existing XML development tools.

                </description>

                <implementation-defined-items>

                </implementation-defined-items>

                <features>
{ for $feature in doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/*:features/*:feature
							return
							<feature name="{$feature/@name}" supported="true"/>
						}</features>

                <context-properties>

                </context-properties>

        </implementation>

        <syntax>XQuery</syntax>

        <test-run dateRun="{fn:current-dateTime()}">
                <test-suite version="{$test-suite}"/>
                <transformation>

No unusual transformations.

                </transformation>
                <comparison>

No unusual comparisons

                </comparison>
                <otherComments>

The test run took n seconds.

                </otherComments>
        </test-run>

{
		(: for $case in fn:collection(  '/db/XQTS' )//*:test-case :)
    for $case in fn:collection(  '/db/XQTS' )//test-case
    return <test-case name="{$case/@name}" result="{$case/@result}" />
}
</test-suite-result>

declare option exist:serialize "method=xml indent=yes";
declare option exist:output-size-limit "-1";
declare namespace response="http://exist-db.org/xquery/response";

let $product-version := util:system-property("product-version")
let $product-build := util:system-property("product-build")
let $test-suite := doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/@version
let $dummy := response:set-header("Content-Disposition", concat(
	"attachment; filename="results_XQTS-" , $test-suite , "_eXist-" ,
	$product-version , '_' , $product-build , ".xml"" ) )

return
<test-suite-result xmlns="http://www.w3.org/2005/02/query-test-XQTSResult"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

        <implementation name="{$product-version}" version="{$product-build}" anonymous-result-column="false">

                <organization name="eXist Open Source native XML database"  website="http://www.exist-db.org" anonymous="false"/>

                <submittor name="eXist XQTS testsuite runner" email="me@not.com"/>

                <description>

eXist is an Open Source native XML database featuring efficient,
                        index-based XQuery processing, automatic indexing, extensions for full-text
                        search,  XUpdate  support and tight integration with existing XML development tools.

                </description>

                <implementation-defined-items>

                </implementation-defined-items>

                <features>
{ for $feature in doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/*:features/*:feature
							return
							<feature name="{$feature/@name}" supported="true"/>
						}</features>

                <context-properties>

                </context-properties>

        </implementation>

        <syntax>XQuery</syntax>

        <test-run dateRun="{fn:current-dateTime()}">
                <test-suite version="{$test-suite}"/>
                <transformation>

No unusual transformations.

                </transformation>
                <comparison>

No unusual comparisons

                </comparison>
                <otherComments>

The test run took n seconds.

                </otherComments>
        </test-run>

{
		(: for $case in fn:collection(  '/db/XQTS' )//*:test-case :)
    for $case in fn:collection(  '/db/XQTS' )//test-case
    return <test-case name="{$case/@name}" result="{$case/@result}" />
}
</test-suite-result>


update name,ftype and parent when entityID found

import module namespace util = "https://github.com/openhie/openinfoman-dhis/util";
declare namespace csd = "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)

let $namespace_uuid := "7ee93e32-78da-4913-82f8-49eb0a618cfc"

let $uuid_generate := function($name) {
  concat('urn:uuid:' , util:uuid_generate($name,$namespace_uuid))
}

let $id := $careServicesRequest/facility/@id
let $pid := $careServicesRequest/facility/parent/@id
let $code := $careServicesRequest/facility/@code
let $urn := $uuid_generate($id)
let $parent := <csd:organizations><csd:organization entityID="{$pid}"/></csd:organizations>
let $name := $careServicesRequest/facility/name
let $type := $careServicesRequest/facility/type
let $time := current-dateTime()
let $fac :=
if (($name) and ($id)  and ($urn) )
     then
       <csd:facility entityID="{$urn}">
				 <csd:otherID assigningAuthorityName='http://hfrportal.ehealth.go.tz' code='id'>{string($id)}</csd:otherID>
			   <csd:otherID assigningAuthorityName='http://hfrportal.ehealth.go.tz' code='Fac_IDNumber'>{string($code)}</csd:otherID>
			   <csd:extension type='facilityType' urn='urn:uuid:hfrportal:ehealth:go:tz'><facilityType>{string($type)}</facilityType></csd:extension>
				 <csd:primaryName>{string($name)}</csd:primaryName>
				 {$parent}
			   <csd:record created="{$time}" updated="{$time}" status="Active" sourceDirectory="http://hfrportal.ehealth.go.tz"/>
       </csd:facility>
     else ()  (:no name or id or type :)

return insert node $fac into /CSD/facilityDirectory

let $existing := if (exists($fac/@entityID)) then csd_bl:filter_by_primary_id(/CSD/facilityDirectory/*,$fac) else ()
return
  if (exists($existing))
  then (
    if(exists($fac/extension[@type = "facilityType"]) and exists($existing/extension[@type = "facilityType"]) )
    then (replace node $existing/extension[@type = "facilityType"] with $fac/extension[@type = "facilityType"])
    else
      if(exists($fac/extension[@type = "facilityType"]))
      then insert node $fac/extension[@type = "facilityType"] into $existing
      else (),
    if(exists($fac/primaryName) and exists($existing/primaryName) )
    then (replace node $existing/primaryName with $fac/primaryName)
    else
      if(exists($fac/primaryName))
      then insert node $fac/primaryName into $existing
      else (),

    if(exists($fac/organizations) and exists($existing/organizations) )
    then (replace node $existing/organizations with $fac/organizations)
    else
      if(exists($fac/organizations))
      then insert node $fac/organizations into $existing
      else ()
  )
  else
  insert node $fac into /CSD/facilityDirectory


Don't generate a DBG-REQUESTRECORD error when resuming from the end of a query.

(:
 : Copyright (C) 2020 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "1.0-ml";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "marklogic/6.0";

(: Query the state of a request. :)

declare variable $requestId as xs:unsignedLong external;

try {
    (dbg:status($requestId)/dbg:request/dbg:request-status/text(), "none")[1]
} catch ($e) {
    (: The DBG-REQUESTRECORD "Request record not found" error may be raised in
     : the case when, e.g.:
     : 1.  the user has entered a breakpoint at the end of the query body;
     : 2.  the user then resumed the program.
     :
     : In this case, the run loop waits for 100ms before requessting the status,
     : by which time the request has stopped and has been cleaned up.
     :)
    "none"
}

(:
 : Copyright (C) 2020 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "1.0-ml";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "marklogic/6.0";

(: Query the state of a request. :)

declare variable $requestId as xs:unsignedLong external;

(dbg:status($requestId)/dbg:request/dbg:request-status/text(), "none")[1]


[BaseX] Fix extracting the version from localized version information.

(:
 : Copyright (C) 2018, 2020 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "3.0";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "basex/6.0";

(: Return the version string for BaseX. :)

let $info := db:system()
return if ($info instance of element(system)) then (: BaseX >= 7.1 :)
    (: NOTE: The element containing the version may be localized, so look for version-like strings. :)
    for $text in $info//*/text()
    where fn:matches($text, "^([789]|[1-9][0-9]+)\.[0-9]+(\.[0-9]+)?$")
    return $text
else (: BaseX == 7.0 :)
    for $line in fn:tokenize($info, "(\r\n?|\n)")
    where fn:starts-with($line, " Version: ")
    return fn:substring-after($line, " Version: ")

(:
 : Copyright (C) 2018 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "3.0";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "basex/6.0";

(: Return the version string for BaseX. :)

let $info := db:system()
return if ($info instance of element(system)) then (: BaseX >= 7.1 :)
    $info/generalinformation/version/string()
else (: BaseX == 7.0 :)
    for $line in fn:tokenize($info, "(\r\n?|\n)")
    where fn:starts-with($line, " Version: ")
    return fn:substring-after($line, " Version: ")


Mostly through the addition/removal annotations; still need to address the signature updates/modifications.

xquery version "3.0";
(:~
: BaseX Database Module functions
:
: @see http://docs.basex.org/wiki/Database_Module
:)
module namespace db = "http://basex.org/modules/db";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.0") function db:system() as element(system) external;
declare %a:since("basex", "9.0") function db:option($name as xs:string) as xs:string external;
declare %a:since("basex", "7.0") function db:info($db as xs:string) as element(database) external;
declare %a:since("basex", "8.6") function db:property($db as xs:string, $name as xs:string) as xs:anyAtomicType external;
declare %a:since("basex", "7.0") function db:list() as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string) as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string, $path as xs:string) as xs:string* external;
declare %a:since("basex", "7.1") function db:list-details() as element(database)* external;
declare %a:since("basex", "7.1") function db:list-details($db as xs:string) as element(resource)* external;
declare %a:since("basex", "7.1") function db:list-details($db as xs:string, $path as xs:string) as element(resource)* external;
declare %a:since("basex", "7.5") function db:backups() as element(backup)* external;
declare %a:since("basex", "7.5") function db:backups($db as xs:string) as element(backup)* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string, $path as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open-pre($db as xs:string, $pre as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:open-id($db as xs:string, $id as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:node-pre($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:node-id($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:text($db as xs:string, $strings as xs:string*) as text()* external;
declare %a:since("basex", "7.2.1") function db:text-range($db as xs:string, $min as xs:string, $max as xs:string) as text()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:strings*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.2.1") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string) as attribute()* external;
declare %a:since("basex", "7.2.1") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string, $name as xs:string) as attribute()* external;
declare %a:since("basex", "8.4") function db:token($db as xs:string, $tokens as xs:string*) as attribute()* external;
declare %a:since("basex", "8.4") function db:token($db as xs:string, $tokens as xs:string*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.5") function db:create($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:drop($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:delete($db as xs:string, $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:copy($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:alter($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:create-backup($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:drop-backup($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:restore($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:rename($db as xs:string, $source as xs:string, $target as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item(), $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:store($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.3") function db:flush($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.7") function db:name($node as node()) as xs:string external;
declare %a:since("basex", "7.7") function db:path($node as node()) as xs:string external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-raw($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-xml($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.1") function db:content-type($db as xs:string, $path as xs:string) as xs:string external;
declare %a:since("basex", "7.2.1") %a:until("basex", "9.0") %a:see-also("basex", "9.0", "update:output") function db:output() external;
declare %a:since("basex", "8.2") %a:until("basex", "9.0") %a:see-also("basex", "9.0", "update:cache") function db:output-cache() external;
declare %a:since("basex", "7.7") %a:until("basex", "..") function db:export() external;
declare %a:since("basex", "7.0") %a:until("basex", "7.8") %a:see-also("basex", "7.8", "ft:search") function db:fulltext() external;
declare %a:since("basex", "..") %a:until("basex", "8.2") function db:event() external;

xquery version "3.0";
(:~
: BaseX Database Module functions
:
: @see http://docs.basex.org/wiki/Database_Module
:)
module namespace db = "http://basex.org/modules/db";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.0") function db:system() as element(system) external;
declare %a:since("basex", "7.0") function db:option($name as xs:string) as xs:string external;
declare %a:since("basex", "7.0") function db:info($db as xs:string) as element(database) external;
declare %a:since("basex", "7.0") function db:property($db as xs:string, $name as xs:string) as xs:anyAtomicType external;
declare %a:since("basex", "7.0") function db:list() as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string) as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string, $path as xs:string) as xs:string* external;
declare %a:since("basex", "7.1") function db:list-details() as element(database)* external;
declare %a:since("basex", "7.1") function db:list-details($db as xs:string) as element(resource)* external;
declare %a:since("basex", "7.1") function db:list-details($db as xs:string, $path as xs:string) as element(resource)* external;
declare %a:since("basex", "7.5") function db:backups() as element(backup)* external;
declare %a:since("basex", "7.5") function db:backups($db as xs:string) as element(backup)* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string, $path as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open-pre($db as xs:string, $pre as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:open-id($db as xs:string, $id as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:node-pre($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:node-id($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:text($db as xs:string, $strings as xs:string*) as text()* external;
declare %a:since("basex", "7.2.1") function db:text-range($db as xs:string, $min as xs:string, $max as xs:string) as text()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:strings*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.2.1") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string) as attribute()* external;
declare %a:since("basex", "7.2.1") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.0") function db:token($db as xs:string, $tokens as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:token($db as xs:string, $tokens as xs:string*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.5") function db:create($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:drop($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:delete($db as xs:string, $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:copy($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:alter($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:create-backup($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:drop-backup($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:restore($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:rename($db as xs:string, $source as xs:string, $target as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item(), $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:store($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.3") function db:flush($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.7") function db:name($node as node()) as xs:string external;
declare %a:since("basex", "7.7") function db:path($node as node()) as xs:string external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-raw($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-xml($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.1") function db:content-type($db as xs:string, $path as xs:string) as xs:string external;
declare %a:since("basex", "7.2.1") %a:until("basex", "9.0") %a:see-also("basex", "9.0", "update:output") function db:output() external;
declare %a:since("basex", "8.2") %a:until("basex", "9.0") %a:see-also("basex", "9.0", "update:cache") function db:output-cache() external;
declare %a:since("basex", "7.7") %a:until("basex", "..") function db:export() external;
declare %a:since("basex", "7.0") %a:until("basex", "7.8") %a:see-also("basex", "7.8", "ft:search") function db:fulltext() external;
declare %a:since("basex", "..") %a:until("basex", "8.2") function db:event() external;