Database Reference
In-Depth Information
Example 16-1. Simple module for producing identifiers (id.xqm)
xquery
version
"3.0"
;
module
namespace
id
=
"http://example.com/record/id"
;
import
module
namespace
util
=
"http://exist-db.org/xquery/util"
;
declare
variable
$
id:ERR-PRESENT
:=
xs:QName
(
"id:ERR-PRESENT"
);
declare
function
id:insert
(
$
record
as
element
(
record
))
as
element
(
record
)
{
if
(
$
record
/
id
)
then
fn:error
(
$
id:ERR-PRESENT
,
"<id> is already present in record!"
,
$
record
/
id
)
else
<record>
{
$
record
/
@
*
,
<id>
{
id:generate
()}
</id>
,
$
record
/
node
()
}
</record>
};
declare
function
id:generate
()
as
xs:string
{
let
$
id
:=
id:random
()
return
if
(
exists
(
collection
(
"/db/records"
)/
record
/
id
[.
eq
$
id
]))
then
id:generate
()
else
$
id
};
declare
function
id:random
()
as
xs:string
{
codepoints-to-string
(
((
1
to
8
)
!
util:random
(
26
))
!
(.[.
lt
10
]
+
48
,
.[.
ge
10
]
+
87
)
)
};
Let's first write some test cases for the function
id:insert
. Here are three things that
leap to mind that we might like to write test cases for:
• If we send it a document that already has an
id
element, it raises the error
id:ERR-PRESENT
.
• If we send it a document without an
id
element, it adds an
id
element for us with
some sort of identifier.
Search WWH ::
Custom Search