=Expressions=
{{MarkAnnounce|Introduced Removed with Version 9.1:11}} ternary if, elvis : Elvis operator<code>?:</code>, if without else Some in favor of the extensions that have been added to BaseX may also be made available in other XQuery processors in the near futurenew <code>[https://qt4cg.org/specifications/xquery-40/xquery-40.html#id-otherwise otherwise]</code> expression.
==Ternary If==
The [https://en.wikipedia.org/wiki/%3F: ternary if] operator provides a short syntax for conditions. It is also called '''conditional operator''' or '''ternary operator'''. In most languages, the syntax is <code>a ? b : c</code>. As <code>?</code> and <code>:</code> have already been taken in XQuery, the syntax of Perl 6 is used:
<pre classlang="brush:'xquery"'>(: if/then/else :)if ($ok) then 1 else 0,(: ternary if :)$test ok ?? 'ok' 1 !! 'fails'0
</pre>
The expression returns <code>ok</code> if the effective boolean value of <code>$test</code> is true, and it returns <code>fails</code> otherwise.
==Elvis Operator==
The Elvis operator is also available in other languages. It is sometimes called [https://en.wikipedia.org/wiki/Null_coalescing_operator null-coalescing operator]. In XQuery, the value of the first operand will be returned if it is a non-empty sequence. Otherwise, the value of the second operand will be returned.
<pre class="brush:xquery">
let $number := 123
return (
(: if/then/else :)
if (exists($number)) then $number else 0,
(: elvis operator :)
$number ?: 0
)
</pre>
The behavior of the operator is equivalent to the {{Function|Utility|util:or}} function.
==If Without Else==
In XQuery 3.1, both branches of the <code>if</code> expression need to be specified. In many cases, only one branch is required, so the <code>else</code> branch was made optional in BaseX. If the second branch is omitted, an empty sequence will be returned if the effective boolean value of the test expression is false. Some examples:
<pre classlang="brush:'xquery"'>
if (doc-available($doc)) then doc($doc),
if (file:exists($file)) then file:delete($file),
If conditions are nested, a trailing else branch will be associated with the innermost <code>if</code>:
<pre classlang="brush:'xquery"'>if ($a) then if($b) then '$a and $b is true' else 'only $b a is true'
</pre>
In general, if you have multiple or nested if expressions, additional parentheses can improve the readibility of your code:
<pre classlang="brush:'xquery"'>
if ($a) then (
if($b) then '$a and $b is true' else 'only $b a is true'
)
</pre>
The behavior of the if expression is equivalent to the {{Function|Utility|util:if}} function.
=Functions=
==Regular Expressions==
{{Mark|Introduced with Version 9.1:}}
In analogy with Saxon, you can specify the flag {{Code|j}} to revert to Java’s default regex parser. For example, this allows you to use the word boundary option {{Code|\b}}, which has not been included in the XQuery grammar for regular expressions:
'''Example:'''
<pre classlang="brush:'xquery"'>
(: yields "!Hi! !there!" :)
replace('Hi there', '\b', '!', 'j')
* <code>basex</code>is used as the default serialization method: nodes are serialized as XML, atomic values are serialized as string, and items of binary type are output in their native byte representation. Function items (including maps and arrays) are output just like with the [[XQuery 3.1#Adaptive Serialization|adaptive]] method.
* With {{Code|csv}}, you can output XML nodes as CSV data (see the [[CSV Module]] for more details).
* With {{Code|json}}, items are output as JSON as described in the [https://www.w3.org/TR/xslt-xquery-serialization-31/#json-output official specification]. If the root node is of type {{Code|element(json)}}, items are serialized as described for the {{Code|direct}} format in the [[JSON Module]].
For more information and some additional BaseX-specific parameters, see the article on [[Serialization]].
[[Options|Local database options]] can be set in the prolog of an XQuery main module. In the option declaration, options need to be bound to the [[Database Module]] namespace. All values will be reset after the evaluation of a query:
<pre classlang="brush:'xquery"'>declare option db:chop catalog 'falseetc/w3-catalog.xml';
doc('doc.xml')
</pre>
==XQuery Locks==
If [[Transactions#XQuery_Locks|XQuery Locks]] locks are defined declared in the query prolog of a modulevia the {{Code|basex:lock}} option, access to functions of this module locks will be controlled by the central transaction management. If the following XQuery code is called by two clients in parallel, the queries will be evaluated one after another: <pre class="brush:xquery">declare option basex:write-lock 'CONFIGLOCK';file:write('configSee [[Transaction Management#Options|Transaction Management]] for further details.xml', <config/>)</pre>
=Pragmas=
==BaseX Pragmas==
{{Announce|Updated with Version 11}}: Renamed from {{Code|non-deterministic}} to {{Code|nondeterministic}}. Many optimizations in BaseX will only be performed if an expression is ''deterministic'' (i. e., if it always yields the same output and does not have side effects). By flagging an expression as non-deterministicnondeterministic, optimizations and query rewritings can be suppressed:
<pre classlang="brush:'xquery"'>sum( (# basex:non-deterministic nondeterministic #) {
1 to 100000000
})
This pragma can be helpful when debugging your code.
{{Mark|Introduced with Version 9.1:}} In analogy with option declarations and function annotations, XQuery locks can also set via pragmas. See [[TransactionsTransaction Management#XQuery_LocksOptions|XQuery LocksTransaction Management]] can also set via pragmas:for details and examples.
<pre classlang="brush:'xquery"'>
(# basex:write-lock CONFIGLOCK #) {
file:write('config.xml', <config/>)
==Database Pragmas==
All [[Options|local Local database options]] can also be assigned via pragmas. Some examples:
* Enforce query to [[Indexes|Index access rewritings]] can be rewritten for index accessenforced. This can e. g. be is helpful if the name of a database is not static (see [[Indexes#Enforce Rewritings|Enforce Rewritings]] for more examplesdetails):
<pre classlang="brush:'xquery"'>
(# db:enforceindex #) {
for $db in ('persons1', 'persons2', 'persons3')
return db:openget($db)//name[text() = 'John']
}
</pre>
* Temporarily disable node Node copying in node constructors can be disabled (see {{Option|COPYNODE}} for more details). The following query will be evaluated faster, and take consume much less memory, than without pragma, because as the database nodes will not be fully copiedduplicated, but only attached to the new {{Code|xml}} parent element:
<pre classlang="brush:'xquery"'>
file:write(
'wrapped-db-nodes.xml',
(# db:copynode false #) {
<xml>{ db:openget('huge') }</xml>
}
)
</pre>
* An XML catalog can be specified for URI rewritings. See the [[Catalog Resolver]] section for an example.
=Annotations=
'''Query:'''
<pre classlang="brush:'xquery"'>
declare function local:square($a) { $a * $a };
for $i in 1 to 3
'''Query after function inlining:'''
<pre classlang="brush:'xquery"'>
for $i in 1 to 3
return
'''Query after further optimizations:'''
<pre classlang="brush:'xquery"'>
for $i in 1 to 3
return $i * $i
'''Example:'''
<pre classlang="brush:'xquery"'>
(: disable function inlining; the full stack trace will be shown... :)
declare %basex:inline(0) function local:e() { error() };
'''Result:'''
<pre classlang="brush:xml">
Stopped at query.xq, 1/53:
[FOER0000] Halted on error().
'''Example:'''
<pre classlang="brush:'xquery"'>declare %basex:lazy variable $january := doc('does-not-exist.xml');
if(month-from-date(current-date()) = 1) then $january else ()
</pre>
The annotation ensures that an error will is only be raised if the condition yields true. Without the annotation, the error will is always be raised, because if the referenced document is not found.
==XQuery Locks==
{{MarkIn analogy with option declarations and pragmas, locks can also set via annotations. See [[Transaction Management#Annotations|Introduced with Version 9Transaction Management]] for details and examples.1:}}
In analogy with option declarations and pragmas, [[Transactions#XQuery_Locks|XQuery Locks]] can also set via annotations:=Namespaces=
<pre class="brush:xquery">declare %basexIn XQuery, some namespaces are statically bound to prefixes. The following query requires no additional namespaces declarations in the query prolog:write-lock('CONFIGLOCK') function local:write() { file:write('config.xml', <config/>)};</pre>
=Non-Determinism= In [http://www.w3.org/TR/xpath-functions-31/#dt-deterministic XQuery], ''deterministic'' functions are “guaranteed to produce ·identical· results from repeated calls within a single ·execution scope· if the explicit and implicit arguments are identical”. In BaseX, many extension functions are non-deterministic or side-effecting. If an expression is internally flagged as non-deterministic, various optimizations that might change their execution order will not be applied. <pre classlang="brush:'xquery"'>(<xml: QUERY A... abc xmlns:)let $n prefix='uri' local:fn= 456for $i in 1 to 2return $n'x'/>,fn:exists(: ...will be optimized to :)for $i in 1 to 2return 456 (: QUERY B will not be rewritten :)let $n := random:integer()for $i in 1 to 2return $n
</pre>
In some casesBaseX, functions may contain non-deterministic codevarious other namespaces are predefined. Apart from the namespaces that are listed on the [[Module Library]] page, but the query compiler may not be able to detect this following namespaces are statically. See the following examplebound: <pre class="brush:xquery">for $read in (file:read-text#1, file:read-binary#1)let $ignored := non-deterministic $read('input.file')return ()</pre>
Two non{| class="wikitable sortable"|-! Description! Prefix! Namespace URI|-| [[#Annotations|BaseX Annotations]], [[#Pragmas|Pragmas]], …| <code>basex</code>| <code><nowiki>http://basex.org</nowiki></code>|-deterministic functions will be bound to | [[RESTXQ#Input Options|RESTXQ: Input Options]]| <code>$readinput</code>, and the result of the function call will be bound to | <code><nowiki>http://basex.org/modules/input</nowiki></code>|-| [[Repository#EXPath_Packaging|EXPath Packages]]| <code>$ignoredpkg</code>| <code><nowiki>http://expath. As the variable is not referenced in the subsequent org/ns/pkg</nowiki></code, the let clause would usually be discarded by the compiler>|-| [[XQuery Errors]]| <code>err</code>| <code><nowiki>http://www.w3. In the given query, however, execution will be enforced because of the BaseXorg/2005/xqt-errors</nowiki></code>|-specific {{Code| [[Serialization]]| <code>output</code>|non<code><nowiki>http://www.w3.org/2010/xslt-xquery-deterministic}serialization</nowiki></code>|} keyword.
=Suffixes=
* Main modules have an expression as query body. Here is a minimum example:
<pre classlang="brush:'xquery"'>
'Hello World!'
</pre>
* Library modules start with a module namespace declaration and have no query body:
<pre classlang="brush:'xquery"'>
module namespace hello = 'http://basex.org/examples/hello';
=Changelog=
;Version 11:
* Removed: Elvis operator <code>?:</code>, in favor of the new <code>[https://qt4cg.org/specifications/xquery-40/xquery-40.html#id-otherwise otherwise]</code> expression.
* Updated: Renamed from {{Code|non-deterministic}} to {{Code|nondeterministic}}.
;Version 9.1: