https://docs.basex.org/api.php?action=feedcontributions&user=Dirk&feedformat=atomBaseX Documentation - User contributions [en]2024-03-29T09:50:29ZUser contributionsMediaWiki 1.34.0https://docs.basex.org/index.php?title=RESTXQ&diff=11930RESTXQ2015-08-13T14:54:00Z<p>Dirk: </p>
<hr />
<div>This page presents one of the [[Web Application]] services. It describes how to use the RESTXQ API of BaseX.<br />
<br />
RESTXQ, introduced by [http://www.adamretter.org.uk/ Adam Retter], is an API that facilitates the use of XQuery<br />
as a server-side processing language for the Web. RESTXQ has been inspired by Java’s<br />
[http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services JAX-RS API]: it defines a pre-defined set of<br />
XQuery 3.0 annotations for mapping HTTP requests to XQuery functions, which in turn generate and return<br />
HTTP responses.<br />
<br />
Please note that BaseX provides various extensions to the official draft of the specification:<br />
<br />
* Multipart types are supported, including {{Code|multipart/form-data}}<br />
* A {{Code|%rest:error}} annotation can be used to catch XQuery errors<br />
* Servlet errors can be redirected to other RESTXQ pages<br />
* A [[RESTXQ Module]] provides some helper functions<br />
* Parameters are implicitly cast to the type of the function argument<br />
* The [[#Paths|Path Annotation]] can contain regular expressions<br />
* Quality factors in the [[#Content Negotiation|Accept header]] will be evaluated<br />
* <code>%input</code> annotations, support for input-specific content-type parameters<br />
<br /><br />
<br />
=Introduction=<br />
<br />
==Preliminaries==<br />
<br />
The RESTXQ service is accessible via {{Code|http://localhost:8984/}}.<br />
<br />
All RESTXQ [[XQuery 3.0#Annotations|annotations]] are assigned to the <code><nowiki>http://exquery.org/ns/restxq</nowiki></code> namespace, which is statically bound to the {{Code|rest}} prefix. A ''Resource Function'' is an XQuery function that has been marked up with RESTXQ annotations. When an HTTP request comes in, a resource function will be invoked that matches the constraints indicated by its annotations.<br />
<br />
Whenever a RESTXQ URL is requested, the [[Options#RESTXQPATH|RESTXQPATH]] module directory and its sub-directories will be parsed for functions with RESTXQ annotations in library modules (detected by the extension {{Code|.xqm}}) and main modules (detected by {{Code|.xq}}). In main expressions, the main module will never be evaluated. All modules will be cached and parsed again when their timestamp changes.<br />
<br />
The following features will be available with {{Version|8.3}}:<br />
<br />
* A sub-directory will not be parsed for RESTXQ files if it contains a file named {{Code|.ignore}}.<br />
* Module caching can be turned on by setting [[Options#CACHERESTXQ|CACHERESTXQ]] to true. The option is helpful in productive environments with a high load, but files should not be replaced while the web server is running.<br />
* If files are still replaced at runtime, the RESTXQ module cache can be invalidated by calling the static root path {{Code|/.init}}.<br />
<br />
==Examples==<br />
<br />
A first RESTXQ function is shown below:<br />
<br />
<pre class="brush:xquery"><br />
module namespace page = 'http://basex.org/examples/web-page';<br />
<br />
declare %rest:path("hello/{$who}") %rest:GET function page:hello($who) {<br />
<response><br />
<title>Hello { $who }!</title><br />
</response><br />
};</pre><br />
<br />
If the URI http://localhost:8984/hello/World is accessed, the result will be:<br />
<br />
<pre class="brush:xml"><br />
&lt;response&gt;<br />
&lt;title&gt;Hello World!&lt;/title&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
The next function demonstrates a POST request:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/form")<br />
%rest:POST<br />
%rest:form-param("message","{$message}", "(no message)")<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello-postman(<br />
$message as xs:string,<br />
$agent as xs:string*)<br />
as element(response)<br />
{<br />
&lt;response type='form'&gt;<br />
&lt;message&gt;{ $message }&lt;/message&gt;<br />
&lt;user-agent&gt;{ $agent }&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
};<br />
</pre><br />
<br />
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...<br />
<br />
<pre class="brush:shell"><br />
curl -i -X POST --data "message='CONTENT'" http://localhost:8984/form<br />
</pre><br />
<br />
...you will receive something similar to the following result:<br />
<br />
<pre class="brush:shell"><br />
HTTP/1.1 200 OK<br />
Content-Type: application/xml; charset=UTF-8<br />
Content-Length: 107<br />
Server: Jetty(8.1.11.v20130520)<br />
</pre><br />
<br />
<pre class="brush:xml"><br />
<response type="form"><br />
<message>'CONTENT'</message><br />
<user-agent>curl/7.31.0</user-agent><br />
</response><br />
</pre><br />
<br />
=Request=<br />
<br />
This section shows how annotations are used to handle and process HTTP requests.<br />
<br />
==Constraints==<br />
<br />
Constraints restrict the HTTP requests that a resource function may process.<br />
<br />
===Paths===<br />
<br />
A resource function must have a single ''Path Annotation'' with a single string as argument. The function will be called if a URL matches the path segments and templates of the argument. ''Path templates'' contain variables in curly brackets, and map the corresponding segments of the request path to the arguments of the resource function. The first slash in the path is optional.<br />
<br />
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/a/path/{$with}/some/{$variable}")<br />
function page:test($with, $variable as xs:integer) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
Variables can be enhanced by regular expressions:<br />
<br />
<pre class="brush:xquery"><br />
(: Matches all paths with "app" as first, a number as second, and "order" as third segment :)<br />
declare %rest:path("app/{$code=[0-9]+}/order")<br />
function page:order($full-path) { ... };<br />
<br />
(: Matches all other all paths starting with "app/" :)<br />
declare %rest:path("app/{$path=.+}")<br />
function page:others($path) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
===Content Negotiation===<br />
<br />
Two following annotations can be used to restrict functions to specific content types:<br />
<br />
* '''HTTP Content Types''': a function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given mime types. Example:<br />
<pre class="brush:xquery">%rest:consumes("application/xml", "text/xml")</pre><br />
* '''HTTP Accept''': a function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined mime types. Example:<br />
<pre class="brush:xquery">%rest:produces("application/atom+xml")</pre><br />
<br />
By default, both mime types are {{Code|*/*}}. Quality factors supplied by a client will also be considered in the path selection process.<br />
If a client supplies the following accept header…<br />
<br />
<pre><br />
*/*;q=0.5,text/html;q=1.0<br />
</pre><br />
<br />
…and if two RESTXQ functions exist with the same {{Code|path}} annotation and the {{Code|produces}} annotations <code>*/*</code> and <code>text/html</code>, respectively, the function with the second annotation will be called, because the quality factor for <code>text/html</code> documents is higher than the one for arbitrary other mime types.<br />
<br />
Note that this annotation will ''not'' affect the content-type of the HTTP response. Instead, you will need to add a <code>[[#Output|%output:media-type]]</code> annotation.<br />
<br />
===HTTP Methods===<br />
<br />
====Default Methods====<br />
<br />
The HTTP method annotations are equivalent to all [http://en.wikipedia.org/wiki/HTTP#Request_methods HTTP request methods] except TRACE and CONNECT. Zero or more methods may be used on a function; if none is specified, the function will be invoked for each method.<br />
<br />
The following function will be called if GET or POST is used as request method:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:GET %rest:POST %rest:path("/post")<br />
function page:post() { "This was a GET or POST request" };<br />
</pre><br />
<br />
The POST and PUT annotations may optionally take a string literal in order to map the HTTP request body to a [[#Parameters|function argument]]. Once again, the target variable must be embraced by curly brackets:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:PUT("{$body}") %rest:path("/put")<br />
function page:put($body) { "Request body: " || $body };<br />
</pre><br />
<br />
====Custom Methods====<br />
<br />
Custom HTTP methods can be specified with the {{Code|%rest:method}} annotation:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:method("RETRIEVE")<br />
function page:retrieve() { "RETRIEVE was specified as request method." };<br />
</pre><br />
<br />
==Content Types==<br />
<br />
The body of a POST or PUT request will be converted to an XQuery item. Conversion can be<br />
controlled by specifying a content type. It can be further influenced<br />
by specifying additional content-type parameters:<br />
<br />
{| class="wikitable" width="100%"<br />
|- valign="top"<br />
! Content-Type<br />
! Parameters (<code>;name=value</code>)<br />
! Type of resulting XQuery item<br />
|-<br />
| {{Code|text/xml}}, {{Code|application/xml}}<br />
|<br />
| {{Code|document-node()}}<br />
|-<br />
| {{Code|text/*}}<br />
|<br />
| {{Code|xs:string}}<br />
|-<br />
| {{Code|application/json}}<br />
| [[JSON Module#Options|JSON Options]]<br />
| {{Code|document-node()}} or {{Code|map(*)}}<br />
|-<br />
| {{Code|text/html}}<br />
| [[HTML Module#Options|HTML Options]]<br />
| {{Code|document-node()}}<br />
|-<br />
| {{Code|text/comma-separated-values}}<br />
| [[CSV Module#Options|CSV Options]]<br />
| {{Code|document-node()}} or {{Code|map(*)}}<br />
|-<br />
| ''others''<br />
|<br />
| {{Code|xs:base64Binary}}<br />
|-<br />
| {{Code|multipart/*}}<br />
|<br />
| sequence (see next paragraph)<br />
|}<br />
<br />
For example, if <code>application/json;lax=yes</code> is specified as content type, the input will be transformed to JSON, and the lax QName conversion rules will be applied, as described in the [[JSON Module]].<br />
<br />
===Input options===<br />
<br />
Conversion options for JSON, CSV and HTML can also be specified via annotations using the <code>input</code> prefix. The following function treats the first line of the textual input as CSV header:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/store.csv")<br />
%rest:POST("{$csv}")<br />
%input:csv("header=true")<br />
function page:store-csv($csv as document-node())<br />
{<br />
"Number of rows: " || count($csv/csv/record)<br />
};<br />
</pre><br />
<br />
===Multipart Types===<br />
<br />
The single parts of a multipart message are represented as a sequence,<br />
and each part is converted to an XQuery item as described in the last paragraph.<br />
<br />
A function that is capable of handling multipart types is identical to other RESTXQ functions:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/multipart")<br />
%rest:POST("{$data}")<br />
%rest:consumes("multipart/mixed") (: optional :)<br />
function page:multipart($data as item()*)<br />
{<br />
"Number of items: " || count($data)<br />
};<br />
</pre><br />
<br />
==Parameters==<br />
<br />
The following annotations can be used to bind request values to function arguments. Values will implicitly be cast to the type of the argument.<br />
<br />
===Query Parameters===<br />
<br />
The value of the ''first parameter'', if found in the [[Request_Module#Conventions|query component]], will be assigned to the variable specified as ''second parameter''. If no value is specified in the HTTP request, all additional parameters will be bound to the variable (if no additional parameter is given, an empty sequence will be bound):<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/params")<br />
%rest:query-param("id", "{$id}")<br />
%rest:query-param("add", "{$add}", 42, 43, 44)<br />
function page:params($id as xs:string?, $add as xs:integer+)<br />
{<br />
<result id="{ $id }" sum="{ sum($add) }"/><br />
};<br />
</pre><br />
<br />
===HTML Form Fields===<br />
<br />
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are the result of HTML forms submitted with the content type <code>application/x-www-form-urlencoded</code>.<br />
<br />
<pre class="brush:xquery"><br />
%rest:form-param("parameter", "{$value}", "default")<br />
</pre><br />
<br />
====File Uploads====<br />
<br />
Files can be uploaded to the server by using the content type {{Code|multipart/form-data}} (the HTML5 {{Code|multiple}} attribute enables the upload of multiple files):<br />
<br />
<pre class="brush:xml"><br />
<form action="/upload" method="POST" enctype="multipart/form-data"><br />
<input type="file" name="files" multiple="multiple"/><br />
<input type="submit"/><br />
</form><br />
</pre><br />
<br />
The file contents are placed in a [[Map Module|map]], with the filename serving as key. The following example shows how uploaded files can be stored in a temporary directory:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:POST<br />
%rest:path("/upload")<br />
%rest:form-param("files", "{$files}")<br />
function page:upload($files)<br />
{<br />
for $name in map:keys($files)<br />
let $content := $files($name)<br />
let $path := file:temp-dir() || $name<br />
return (<br />
file:write-binary($path, $content),<br />
<file name="{ $name }" size="{ file:size($path) }"/><br />
)<br />
};<br />
</pre><br />
<br />
===HTTP Headers===<br />
<br />
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:header-param("User-Agent", "{$user-agent}")<br />
%rest:header-param("Referer", "{$referer}", "none")<br />
</pre><br />
<br />
===Cookies===<br />
<br />
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:cookie-param("username", "{$user}")<br />
%rest:cookie-param("authentication", "{$auth}", "no_auth")<br />
</pre><br />
<br />
=Response=<br />
<br />
By default, a successful request is answered with the HTTP status code {{Code|200}} (OK) and is followed by the given content. An erroneous request leads to an error code and an optional error message (e.g. {{Code|404}} for “resource not found”).<br />
<br />
==Custom Response==<br />
<br />
Custom responses can be built from within XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and more optional child nodes that will be serialized as usual. A function that reacts on an unknown resource may look as follows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("") function page:error404() {<br />
<rest:response><br />
<http:response status="404" message="I was not found."><br />
<http:header name="Content-Language" value="en"/><br />
<http:header name="Content-Type" value="text/html; charset=utf-8"/><br />
</http:response><br />
</rest:response><br />
};<br />
</pre><br />
<br />
==Forwards and Redirects==<br />
<br />
The two XML elements <code>rest:forward</code> and <code>rest:redirect</code> can be used in the context of [[Web Application]]s, precisely in the context of RESTXQ. These nodes allow e.g. multiple [[XQuery Update]]s in a row by redirecting to the RESTXQ path of updating functions. Both wrap a URL to a RESTXQ path. The wrapped URL should be properly encoded via <code>fn:encode-for-uri()</code>.<br />
<br />
Note that, currently, these elements are not part of RESTXQ specification.<br />
<br />
===rest:forward===<br />
<br />
Usage: wrap the location as follows<br />
<pre class="brush:xml"><rest:forward>{ $location }</rest:forward></pre><br />
<br />
This results in a server-side forwarding, which as well reduces traffic among client and server. A forwarding of this kind will not change the URL seen from the client's perspective.<br />
<br />
As an example, returning<br />
<pre class="brush:xml"><br />
<rest:forward>/hello/universe</rest:forward><br />
</pre><br />
would internally forward to http://localhost:8984/hello/universe<br />
<br />
===rest:redirect===<br />
<br />
The function <code>[[Web Module#web:redirect|web:redirect]]</code> can be used to create a redirect response element. Alternatively, the following element can be sent:<br />
<br />
<pre class="brush:xml"><rest:redirect>{ $location }</rest:redirect></pre><br />
<br />
It is an abbreviation for:<br />
<br />
<pre class="brush:xml"><br />
<rest:response><br />
<http:response status="302"><br />
<http:header name="location" value="{ $location }"/><br />
</http:response><br />
</rest:response><br />
</pre><br />
<br />
The client decides whether to follow this redirection. Browsers usually will, tools like [http://curl.haxx.se/ curl] won’t unless {{Code|-L}} is specified.<br />
<br />
==Output==<br />
<br />
The content-type of a response can be influenced by the user via [[Serialization|Serialization Parameters]]. The steps are described in the [[REST#Content Type|REST]] chapter. In RESTXQ, serialization parameters can be specified in the query prolog, via annotations, or within the REST response element:<br />
<br />
===Query Prolog===<br />
<br />
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:<br />
<br />
<pre class="brush:xquery"><br />
declare option output:media-type 'text/plain';<br />
<br />
declare %rest:path("version1") function page:version1() {<br />
'Keep it simple, stupid'<br />
};<br />
</pre><br />
<br />
===Annotations===<br />
<br />
Global serialization parameters can be overwritten via <code>%output</code> annotations. The following example serializes XML nodes as JSON, using the [[JSON Module|JsonML]] format:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("cities")<br />
%output:method("json")<br />
%output:json("format=jsonml")<br />
function page:cities()<br />
{<br />
element cities {<br />
db:open('factbook')//city/name<br />
}<br />
};<br />
</pre><br />
<br />
The next function, when called, generates XHTML headers, and {{Code|text/html}} will be set as content type:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("")<br />
%output:method("xhtml")<br />
%output:omit-xml-declaration("no")<br />
%output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN") <br />
%output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")<br />
function page:html()<br />
{<br />
<html xmlns="http://www.w3.org/1999/xhtml"><br />
<body>done</body><br />
</html><br />
};<br />
</pre><br />
<br />
===Response Element===<br />
<br />
Serialization parameters can also be specified in a REST reponse element in a query. Serialization parameters will be overwritten:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("version3") function page:version3() {<br />
<rest:response><br />
<output:serialization-parameters><br />
<output:media-type value='text/plain'/><br />
</output:serialization-parameters><br />
</rest:response>,<br />
'Not that simple anymore'<br />
};<br />
</pre><br />
<br />
=Error Handling=<br />
<br />
==XQuery Errors==<br />
<br />
XQuery runtime errors can be processed via ''error annotations''.<br />
Error annotations have one or more arguments, which represent the error codes to be caught.<br />
The codes equal the names of the XQuery 3.0 [[XQuery 3.0#Try.2FCatch|try/catch]] construct:<br />
<br />
{| class="wikitable"<br />
|- valign="top"<br />
! Priority<br />
! Syntax<br />
! Example<br />
|-<br />
| 1<br />
| <code>prefix:name</code><br/><code>Q{uri}name</code><br />
| <code>err:FORG0001</code><br/><code><nowiki>Q{http://www.w3.org/2005/xqt-errors}FORG0001</nowiki></code><br />
|-<br />
| 2<br />
| <code>prefix:*</code><br/><code>Q{uri}*</code><br />
| <code>err:*</code><br/><code><nowiki>Q{http://www.w3.org/2005/xqt-errors}*</nowiki></code><br />
|-<br />
| 3<br />
| <code>*:name</code><br />
| <code>*:FORG0001</code><br />
|-<br />
| 4<br />
| <code>*</code><br />
| <code>*</code><br />
|}<br />
<br />
All error codes that are specified for a function must be of the same priority.<br />
The following rules apply when catching errors:<br />
<br />
* Codes with a higher priority will be preferred.<br />
* A global RESTXQ error will be raised if two functions with conflicting codes are found.<br />
<br />
Similar to try/catch, the pre-defined variables ({{Code|code}}, {{Code|description}}, {{Code|value}}, {{Code|module}}, {{Code|line-number}}, {{Code|column-number}}, {{Code|additional}}) can be bound to variables via ''error parameter annotations'', which are specified the same way as [[#Query Parameters|query parameters]].<br />
<br />
Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/check/{$user}")<br />
function page:check($user)<br />
{<br />
if($user = ('jack', 'lisa'))<br />
then 'User exists'<br />
else fn:error(xs:QName('err:user'), $user)<br />
};<br />
<br />
declare <br />
%rest:error("err:user")<br />
%rest:error-param("description", "{$user}")<br />
function page:user-error($user)<br />
{<br />
'User "' || $user || '" is unknown'<br />
};<br />
</pre><br />
<br />
An XQuery error in a RESTXQ context delivers by default a HTTP status code 400 error back to the client. However, you can also define a custom error code by using the third argument of the error function:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/teapot")<br />
function page:teapot()<br />
{<br />
fn:error(xs:QName('error'), "I'm a teapot", 418)<br />
};<br />
</pre><br />
<br />
==HTTP Errors==<br />
<br />
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):<br />
<br />
<pre class="brush:xml"><br />
<error-page><br />
<error-code>404</error-code><br />
<location>/error404</location><br />
</error-page><br />
</pre><br />
<br />
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/error404") function page:error404() {<br />
"URL: " || request:attribute("javax.servlet.error.request_uri") || ", " || <br />
"Error message: " || request:attribute("javax.servlet.error.message")<br />
};<br />
</pre><br />
<br />
=Functions=<br />
<br />
The [[Request Module]] contains functions for accessing data related to the current HTTP request. Two modules exist for setting and retrieving server-side session data of the current user ([[Session Module]]) and all users known to the HTTP server ([[Sessions Module]]). The [[RESTXQ Module]] provides functions for requesting RESTXQ base URIs and generating a [http://www.w3.org/Submission/wadl/ WADL description] of all services. Please note that the namespaces of all of these modules must be explicitly specified via module imports in the query prolog.<br />
<br />
The following example returns the current host name:<br />
<br />
<pre class="brush:xquery"><br />
import module namespace request = "http://exquery.org/ns/request";<br />
<br />
declare %rest:path("/host-name") function page:host() {<br />
'Remote host name: ' || request:remote-hostname()<br />
};<br />
</pre><br />
<br />
=References=<br />
<br />
Currently, the following external resources on RESTXQ exist:<br />
<br />
* [http://exquery.org/spec/restxq RESTXQ Specification], First Draft<br />
* [http://www.adamretter.org.uk/papers/restful-xquery_january-2012.pdf RESTful XQuery, Standardised XQuery 3.0 Annotations for REST]. Paper, XMLPrague, 2012<br />
* [http://www.adamretter.org.uk/presentations/restxq_mugl_20120308.pdf RESTXQ]. Slides, MarkLogic User Group London, 2012<br />
* [http://files.basex.org/publications/xmlprague/2013/Develop-RESTXQ-WebApps-with-BaseX.pdf Web Application Development]. Slides from XMLPrague 2013<br />
<br />
=Changelog=<br />
<br />
;Version 8.1<br />
<br />
* Added: support for input-specific content-type parameters<br />
* Added: <code>%input</code> annotations<br />
<br />
;Version 8.0<br />
<br />
* Added: Support for regular expresssions in the [[#Paths|Path Annotation]]<br />
* Added: Evaluation of quality factors that are supplied in the [[#Content Negotiation|Accept header]]<br />
<br />
;Version 7.9<br />
<br />
* Updated: [[#XQuery Errors|XQuery Errors]], extended error annotations<br />
* Added: {{Code|%rest:method}}<br />
<br />
;Version 7.7<br />
<br />
* Added: [[#Error Handling|Error Handling]], [[#File Uploads|File Uploads]], [[#Multipart Types|Multipart Types]]<br />
* Updated: RESTXQ function may now also be specified in main modules (suffix: {{Code|*.xq}}).<br />
* Updated: the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
* Updated: parameters are implicitly cast to the type of the function argument<br />
* Updated: the RESTXQ root url has been changed to {{Code|http://localhost:8984/}}<br />
<br />
;Version 7.5<br />
<br />
* Added: new XML elements {{Code|<rest:redirect/>}} and {{Code|<rest:forward/>}}<br />
<br />
[[Category:HTTP]]<br />
[[Category:Developer]]</div>Dirkhttps://docs.basex.org/index.php?title=RESTXQ&diff=11929RESTXQ2015-08-13T14:53:24Z<p>Dirk: </p>
<hr />
<div>This page presents one of the [[Web Application]] services. It describes how to use the RESTXQ API of BaseX.<br />
<br />
RESTXQ, introduced by [http://www.adamretter.org.uk/ Adam Retter], is an API that facilitates the use of XQuery<br />
as a server-side processing language for the Web. RESTXQ has been inspired by Java’s<br />
[http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services JAX-RS API]: it defines a pre-defined set of<br />
XQuery 3.0 annotations for mapping HTTP requests to XQuery functions, which in turn generate and return<br />
HTTP responses.<br />
<br />
Please note that BaseX provides various extensions to the official draft of the specification:<br />
<br />
* Multipart types are supported, including {{Code|multipart/form-data}}<br />
* A {{Code|%rest:error}} annotation can be used to catch XQuery errors<br />
* Servlet errors can be redirected to other RESTXQ pages<br />
* A [[RESTXQ Module]] provides some helper functions<br />
* Parameters are implicitly cast to the type of the function argument<br />
* The [[#Paths|Path Annotation]] can contain regular expressions<br />
* Quality factors in the [[#Content Negotiation|Accept header]] will be evaluated<br />
* <code>%input</code> annotations, support for input-specific content-type parameters<br />
<br /><br />
<br />
=Introduction=<br />
<br />
==Preliminaries==<br />
<br />
The RESTXQ service is accessible via {{Code|http://localhost:8984/}}.<br />
<br />
All RESTXQ [[XQuery 3.0#Annotations|annotations]] are assigned to the <code><nowiki>http://exquery.org/ns/restxq</nowiki></code> namespace, which is statically bound to the {{Code|rest}} prefix. A ''Resource Function'' is an XQuery function that has been marked up with RESTXQ annotations. When an HTTP request comes in, a resource function will be invoked that matches the constraints indicated by its annotations.<br />
<br />
Whenever a RESTXQ URL is requested, the [[Options#RESTXQPATH|RESTXQPATH]] module directory and its sub-directories will be parsed for functions with RESTXQ annotations in library modules (detected by the extension {{Code|.xqm}}) and main modules (detected by {{Code|.xq}}). In main expressions, the main module will never be evaluated. All modules will be cached and parsed again when their timestamp changes.<br />
<br />
The following features will be available with {{Version|8.3}}:<br />
<br />
* A sub-directory will not be parsed for RESTXQ files if it contains a file named {{Code|.ignore}}.<br />
* Module caching can be turned on by setting [[Options#CACHERESTXQ|CACHERESTXQ]] to true. The option is helpful in productive environments with a high load, but files should not be replaced while the web server is running.<br />
* If files are still replaced at runtime, the RESTXQ module cache can be invalidated by calling the static root path {{Code|/.init}}.<br />
<br />
==Examples==<br />
<br />
A first RESTXQ function is shown below:<br />
<br />
<pre class="brush:xquery"><br />
module namespace page = 'http://basex.org/examples/web-page';<br />
<br />
declare %rest:path("hello/{$who}") %rest:GET function page:hello($who) {<br />
<response><br />
<title>Hello { $who }!</title><br />
</response><br />
};</pre><br />
<br />
If the URI http://localhost:8984/hello/World is accessed, the result will be:<br />
<br />
<pre class="brush:xml"><br />
&lt;response&gt;<br />
&lt;title&gt;Hello World!&lt;/title&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
The next function demonstrates a POST request:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/form")<br />
%rest:POST<br />
%rest:form-param("message","{$message}", "(no message)")<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello-postman(<br />
$message as xs:string,<br />
$agent as xs:string*)<br />
as element(response)<br />
{<br />
&lt;response type='form'&gt;<br />
&lt;message&gt;{ $message }&lt;/message&gt;<br />
&lt;user-agent&gt;{ $agent }&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
};<br />
</pre><br />
<br />
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...<br />
<br />
<pre class="brush:shell"><br />
curl -i -X POST --data "message='CONTENT'" http://localhost:8984/form<br />
</pre><br />
<br />
...you will receive something similar to the following result:<br />
<br />
<pre class="brush:shell"><br />
HTTP/1.1 200 OK<br />
Content-Type: application/xml; charset=UTF-8<br />
Content-Length: 107<br />
Server: Jetty(8.1.11.v20130520)<br />
</pre><br />
<br />
<pre class="brush:xml"><br />
<response type="form"><br />
<message>'CONTENT'</message><br />
<user-agent>curl/7.31.0</user-agent><br />
</response><br />
</pre><br />
<br />
=Request=<br />
<br />
This section shows how annotations are used to handle and process HTTP requests.<br />
<br />
==Constraints==<br />
<br />
Constraints restrict the HTTP requests that a resource function may process.<br />
<br />
===Paths===<br />
<br />
A resource function must have a single ''Path Annotation'' with a single string as argument. The function will be called if a URL matches the path segments and templates of the argument. ''Path templates'' contain variables in curly brackets, and map the corresponding segments of the request path to the arguments of the resource function. The first slash in the path is optional.<br />
<br />
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/a/path/{$with}/some/{$variable}")<br />
function page:test($with, $variable as xs:integer) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
Variables can be enhanced by regular expressions:<br />
<br />
<pre class="brush:xquery"><br />
(: Matches all paths with "app" as first, a number as second, and "order" as third segment :)<br />
declare %rest:path("app/{$code=[0-9]+}/order")<br />
function page:order($full-path) { ... };<br />
<br />
(: Matches all other all paths starting with "app/" :)<br />
declare %rest:path("app/{$path=.+}")<br />
function page:others($path) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
===Content Negotiation===<br />
<br />
Two following annotations can be used to restrict functions to specific content types:<br />
<br />
* '''HTTP Content Types''': a function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given mime types. Example:<br />
<pre class="brush:xquery">%rest:consumes("application/xml", "text/xml")</pre><br />
* '''HTTP Accept''': a function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined mime types. Example:<br />
<pre class="brush:xquery">%rest:produces("application/atom+xml")</pre><br />
<br />
By default, both mime types are {{Code|*/*}}. Quality factors supplied by a client will also be considered in the path selection process.<br />
If a client supplies the following accept header…<br />
<br />
<pre><br />
*/*;q=0.5,text/html;q=1.0<br />
</pre><br />
<br />
…and if two RESTXQ functions exist with the same {{Code|path}} annotation and the {{Code|produces}} annotations <code>*/*</code> and <code>text/html</code>, respectively, the function with the second annotation will be called, because the quality factor for <code>text/html</code> documents is higher than the one for arbitrary other mime types.<br />
<br />
Note that this annotation will ''not'' affect the content-type of the HTTP response. Instead, you will need to add a <code>[[#Output|%output:media-type]]</code> annotation.<br />
<br />
===HTTP Methods===<br />
<br />
====Default Methods====<br />
<br />
The HTTP method annotations are equivalent to all [http://en.wikipedia.org/wiki/HTTP#Request_methods HTTP request methods] except TRACE and CONNECT. Zero or more methods may be used on a function; if none is specified, the function will be invoked for each method.<br />
<br />
The following function will be called if GET or POST is used as request method:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:GET %rest:POST %rest:path("/post")<br />
function page:post() { "This was a GET or POST request" };<br />
</pre><br />
<br />
The POST and PUT annotations may optionally take a string literal in order to map the HTTP request body to a [[#Parameters|function argument]]. Once again, the target variable must be embraced by curly brackets:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:PUT("{$body}") %rest:path("/put")<br />
function page:put($body) { "Request body: " || $body };<br />
</pre><br />
<br />
====Custom Methods====<br />
<br />
Custom HTTP methods can be specified with the {{Code|%rest:method}} annotation:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:method("RETRIEVE")<br />
function page:retrieve() { "RETRIEVE was specified as request method." };<br />
</pre><br />
<br />
==Content Types==<br />
<br />
The body of a POST or PUT request will be converted to an XQuery item. Conversion can be<br />
controlled by specifying a content type. It can be further influenced<br />
by specifying additional content-type parameters:<br />
<br />
{| class="wikitable" width="100%"<br />
|- valign="top"<br />
! Content-Type<br />
! Parameters (<code>;name=value</code>)<br />
! Type of resulting XQuery item<br />
|-<br />
| {{Code|text/xml}}, {{Code|application/xml}}<br />
|<br />
| {{Code|document-node()}}<br />
|-<br />
| {{Code|text/*}}<br />
|<br />
| {{Code|xs:string}}<br />
|-<br />
| {{Code|application/json}}<br />
| [[JSON Module#Options|JSON Options]]<br />
| {{Code|document-node()}} or {{Code|map(*)}}<br />
|-<br />
| {{Code|text/html}}<br />
| [[HTML Module#Options|HTML Options]]<br />
| {{Code|document-node()}}<br />
|-<br />
| {{Code|text/comma-separated-values}}<br />
| [[CSV Module#Options|CSV Options]]<br />
| {{Code|document-node()}} or {{Code|map(*)}}<br />
|-<br />
| ''others''<br />
|<br />
| {{Code|xs:base64Binary}}<br />
|-<br />
| {{Code|multipart/*}}<br />
|<br />
| sequence (see next paragraph)<br />
|}<br />
<br />
For example, if <code>application/json;lax=yes</code> is specified as content type, the input will be transformed to JSON, and the lax QName conversion rules will be applied, as described in the [[JSON Module]].<br />
<br />
===Input options===<br />
<br />
Conversion options for JSON, CSV and HTML can also be specified via annotations using the <code>input</code> prefix. The following function treats the first line of the textual input as CSV header:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/store.csv")<br />
%rest:POST("{$csv}")<br />
%input:csv("header=true")<br />
function page:store-csv($csv as document-node())<br />
{<br />
"Number of rows: " || count($csv/csv/record)<br />
};<br />
</pre><br />
<br />
===Multipart Types===<br />
<br />
The single parts of a multipart message are represented as a sequence,<br />
and each part is converted to an XQuery item as described in the last paragraph.<br />
<br />
A function that is capable of handling multipart types is identical to other RESTXQ functions:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/multipart")<br />
%rest:POST("{$data}")<br />
%rest:consumes("multipart/mixed") (: optional :)<br />
function page:multipart($data as item()*)<br />
{<br />
"Number of items: " || count($data)<br />
};<br />
</pre><br />
<br />
==Parameters==<br />
<br />
The following annotations can be used to bind request values to function arguments. Values will implicitly be cast to the type of the argument.<br />
<br />
===Query Parameters===<br />
<br />
The value of the ''first parameter'', if found in the [[Request_Module#Conventions|query component]], will be assigned to the variable specified as ''second parameter''. If no value is specified in the HTTP request, all additional parameters will be bound to the variable (if no additional parameter is given, an empty sequence will be bound):<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/params")<br />
%rest:query-param("id", "{$id}")<br />
%rest:query-param("add", "{$add}", 42, 43, 44)<br />
function page:params($id as xs:string?, $add as xs:integer+)<br />
{<br />
<result id="{ $id }" sum="{ sum($add) }"/><br />
};<br />
</pre><br />
<br />
===HTML Form Fields===<br />
<br />
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are the result of HTML forms submitted with the content type <code>application/x-www-form-urlencoded</code>.<br />
<br />
<pre class="brush:xquery"><br />
%rest:form-param("parameter", "{$value}", "default")<br />
</pre><br />
<br />
====File Uploads====<br />
<br />
Files can be uploaded to the server by using the content type {{Code|multipart/form-data}} (the HTML5 {{Code|multiple}} attribute enables the upload of multiple files):<br />
<br />
<pre class="brush:xml"><br />
<form action="/upload" method="POST" enctype="multipart/form-data"><br />
<input type="file" name="files" multiple="multiple"/><br />
<input type="submit"/><br />
</form><br />
</pre><br />
<br />
The file contents are placed in a [[Map Module|map]], with the filename serving as key. The following example shows how uploaded files can be stored in a temporary directory:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:POST<br />
%rest:path("/upload")<br />
%rest:form-param("files", "{$files}")<br />
function page:upload($files)<br />
{<br />
for $name in map:keys($files)<br />
let $content := $files($name)<br />
let $path := file:temp-dir() || $name<br />
return (<br />
file:write-binary($path, $content),<br />
<file name="{ $name }" size="{ file:size($path) }"/><br />
)<br />
};<br />
</pre><br />
<br />
===HTTP Headers===<br />
<br />
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:header-param("User-Agent", "{$user-agent}")<br />
%rest:header-param("Referer", "{$referer}", "none")<br />
</pre><br />
<br />
===Cookies===<br />
<br />
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:cookie-param("username", "{$user}")<br />
%rest:cookie-param("authentication", "{$auth}", "no_auth")<br />
</pre><br />
<br />
=Response=<br />
<br />
By default, a successful request is answered with the HTTP status code {{Code|200}} (OK) and is followed by the given content. An erroneous request leads to an error code and an optional error message (e.g. {{Code|404}} for “resource not found”).<br />
<br />
==Custom Response==<br />
<br />
Custom responses can be built from within XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and more optional child nodes that will be serialized as usual. A function that reacts on an unknown resource may look as follows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("") function page:error404() {<br />
<rest:response><br />
<http:response status="404" message="I was not found."><br />
<http:header name="Content-Language" value="en"/><br />
<http:header name="Content-Type" value="text/html; charset=utf-8"/><br />
</http:response><br />
</rest:response><br />
};<br />
</pre><br />
<br />
==Forwards and Redirects==<br />
<br />
The two XML elements <code>rest:forward</code> and <code>rest:redirect</code> can be used in the context of [[Web Application]]s, precisely in the context of RESTXQ. These nodes allow e.g. multiple [[XQuery Update]]s in a row by redirecting to the RESTXQ path of updating functions. Both wrap a URL to a RESTXQ path. The wrapped URL should be properly encoded via <code>fn:encode-for-uri()</code>.<br />
<br />
Note that, currently, these elements are not part of RESTXQ specification.<br />
<br />
===rest:forward===<br />
<br />
Usage: wrap the location as follows<br />
<pre class="brush:xml"><rest:forward>{ $location }</rest:forward></pre><br />
<br />
This results in a server-side forwarding, which as well reduces traffic among client and server. A forwarding of this kind will not change the URL seen from the client's perspective.<br />
<br />
As an example, returning<br />
<pre class="brush:xml"><br />
<rest:forward>/hello/universe</rest:forward><br />
</pre><br />
would internally forward to http://localhost:8984/hello/universe<br />
<br />
===rest:redirect===<br />
<br />
The function <code>[[Web Module#web:redirect|web:redirect]]</code> can be used to create a redirect response element. Alternatively, the following element can be sent:<br />
<br />
<pre class="brush:xml"><rest:redirect>{ $location }</rest:redirect></pre><br />
<br />
It is an abbreviation for:<br />
<br />
<pre class="brush:xml"><br />
<rest:response><br />
<http:response status="302"><br />
<http:header name="location" value="{ $location }"/><br />
</http:response><br />
</rest:response><br />
</pre><br />
<br />
The client decides whether to follow this redirection. Browsers usually will, tools like [http://curl.haxx.se/ curl] won’t unless {{Code|-L}} is specified.<br />
<br />
==Output==<br />
<br />
The content-type of a response can be influenced by the user via [[Serialization|Serialization Parameters]]. The steps are described in the [[REST#Content Type|REST]] chapter. In RESTXQ, serialization parameters can be specified in the query prolog, via annotations, or within the REST response element:<br />
<br />
===Query Prolog===<br />
<br />
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:<br />
<br />
<pre class="brush:xquery"><br />
declare option output:media-type 'text/plain';<br />
<br />
declare %rest:path("version1") function page:version1() {<br />
'Keep it simple, stupid'<br />
};<br />
</pre><br />
<br />
===Annotations===<br />
<br />
Global serialization parameters can be overwritten via <code>%output</code> annotations. The following example serializes XML nodes as JSON, using the [[JSON Module|JsonML]] format:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("cities")<br />
%output:method("json")<br />
%output:json("format=jsonml")<br />
function page:cities()<br />
{<br />
element cities {<br />
db:open('factbook')//city/name<br />
}<br />
};<br />
</pre><br />
<br />
The next function, when called, generates XHTML headers, and {{Code|text/html}} will be set as content type:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("")<br />
%output:method("xhtml")<br />
%output:omit-xml-declaration("no")<br />
%output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN") <br />
%output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")<br />
function page:html()<br />
{<br />
<html xmlns="http://www.w3.org/1999/xhtml"><br />
<body>done</body><br />
</html><br />
};<br />
</pre><br />
<br />
===Response Element===<br />
<br />
Serialization parameters can also be specified in a REST reponse element in a query. Serialization parameters will be overwritten:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("version3") function page:version3() {<br />
<rest:response><br />
<output:serialization-parameters><br />
<output:media-type value='text/plain'/><br />
</output:serialization-parameters><br />
</rest:response>,<br />
'Not that simple anymore'<br />
};<br />
</pre><br />
<br />
=Error Handling=<br />
<br />
==XQuery Errors==<br />
<br />
XQuery runtime errors can be processed via ''error annotations''.<br />
Error annotations have one or more arguments, which represent the error codes to be caught.<br />
The codes equal the names of the XQuery 3.0 [[XQuery 3.0#Try.2FCatch|try/catch]] construct:<br />
<br />
{| class="wikitable"<br />
|- valign="top"<br />
! Priority<br />
! Syntax<br />
! Example<br />
|-<br />
| 1<br />
| <code>prefix:name</code><br/><code>Q{uri}name</code><br />
| <code>err:FORG0001</code><br/><code><nowiki>Q{http://www.w3.org/2005/xqt-errors}FORG0001</nowiki></code><br />
|-<br />
| 2<br />
| <code>prefix:*</code><br/><code>Q{uri}*</code><br />
| <code>err:*</code><br/><code><nowiki>Q{http://www.w3.org/2005/xqt-errors}*</nowiki></code><br />
|-<br />
| 3<br />
| <code>*:name</code><br />
| <code>*:FORG0001</code><br />
|-<br />
| 4<br />
| <code>*</code><br />
| <code>*</code><br />
|}<br />
<br />
All error codes that are specified for a function must be of the same priority.<br />
The following rules apply when catching errors:<br />
<br />
* Codes with a higher priority will be preferred.<br />
* A global RESTXQ error will be raised if two functions with conflicting codes are found.<br />
<br />
Similar to try/catch, the pre-defined variables ({{Code|code}}, {{Code|description}}, {{Code|value}}, {{Code|module}}, {{Code|line-number}}, {{Code|column-number}}, {{Code|additional}}) can be bound to variables via ''error parameter annotations'', which are specified the same way as [[#Query Parameters|query parameters]].<br />
<br />
Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/check/{$user}")<br />
function page:check($user)<br />
{<br />
if($user = ('jack', 'lisa'))<br />
then 'User exists'<br />
else fn:error(xs:QName('err:user'), $user)<br />
};<br />
<br />
declare <br />
%rest:error("err:user")<br />
%rest:error-param("description", "{$user}")<br />
function page:user-error($user)<br />
{<br />
'User "' || $user || '" is unknown'<br />
};<br />
</pre><br />
<br />
An XQuery error in a RESTXQ context delivers by default a HTTP status code 400 error back to the client. However, you can also define a custom error code by using the third argument of the error function <br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/teapot")<br />
function page:teapot()<br />
{<br />
fn:error(xs:QName('error'), "I'm a teapot", 418)<br />
};<br />
</pre><br />
<br />
==HTTP Errors==<br />
<br />
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):<br />
<br />
<pre class="brush:xml"><br />
<error-page><br />
<error-code>404</error-code><br />
<location>/error404</location><br />
</error-page><br />
</pre><br />
<br />
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/error404") function page:error404() {<br />
"URL: " || request:attribute("javax.servlet.error.request_uri") || ", " || <br />
"Error message: " || request:attribute("javax.servlet.error.message")<br />
};<br />
</pre><br />
<br />
=Functions=<br />
<br />
The [[Request Module]] contains functions for accessing data related to the current HTTP request. Two modules exist for setting and retrieving server-side session data of the current user ([[Session Module]]) and all users known to the HTTP server ([[Sessions Module]]). The [[RESTXQ Module]] provides functions for requesting RESTXQ base URIs and generating a [http://www.w3.org/Submission/wadl/ WADL description] of all services. Please note that the namespaces of all of these modules must be explicitly specified via module imports in the query prolog.<br />
<br />
The following example returns the current host name:<br />
<br />
<pre class="brush:xquery"><br />
import module namespace request = "http://exquery.org/ns/request";<br />
<br />
declare %rest:path("/host-name") function page:host() {<br />
'Remote host name: ' || request:remote-hostname()<br />
};<br />
</pre><br />
<br />
=References=<br />
<br />
Currently, the following external resources on RESTXQ exist:<br />
<br />
* [http://exquery.org/spec/restxq RESTXQ Specification], First Draft<br />
* [http://www.adamretter.org.uk/papers/restful-xquery_january-2012.pdf RESTful XQuery, Standardised XQuery 3.0 Annotations for REST]. Paper, XMLPrague, 2012<br />
* [http://www.adamretter.org.uk/presentations/restxq_mugl_20120308.pdf RESTXQ]. Slides, MarkLogic User Group London, 2012<br />
* [http://files.basex.org/publications/xmlprague/2013/Develop-RESTXQ-WebApps-with-BaseX.pdf Web Application Development]. Slides from XMLPrague 2013<br />
<br />
=Changelog=<br />
<br />
;Version 8.1<br />
<br />
* Added: support for input-specific content-type parameters<br />
* Added: <code>%input</code> annotations<br />
<br />
;Version 8.0<br />
<br />
* Added: Support for regular expresssions in the [[#Paths|Path Annotation]]<br />
* Added: Evaluation of quality factors that are supplied in the [[#Content Negotiation|Accept header]]<br />
<br />
;Version 7.9<br />
<br />
* Updated: [[#XQuery Errors|XQuery Errors]], extended error annotations<br />
* Added: {{Code|%rest:method}}<br />
<br />
;Version 7.7<br />
<br />
* Added: [[#Error Handling|Error Handling]], [[#File Uploads|File Uploads]], [[#Multipart Types|Multipart Types]]<br />
* Updated: RESTXQ function may now also be specified in main modules (suffix: {{Code|*.xq}}).<br />
* Updated: the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
* Updated: parameters are implicitly cast to the type of the function argument<br />
* Updated: the RESTXQ root url has been changed to {{Code|http://localhost:8984/}}<br />
<br />
;Version 7.5<br />
<br />
* Added: new XML elements {{Code|<rest:redirect/>}} and {{Code|<rest:forward/>}}<br />
<br />
[[Category:HTTP]]<br />
[[Category:Developer]]</div>Dirkhttps://docs.basex.org/index.php?title=File_Module&diff=11352File Module2015-02-08T15:56:39Z<p>Dirk: </p>
<hr />
<div>This [[Module Library|XQuery Module]] contains functions related to file system operations, such as listing, reading, or writing files.<br />
<br />
This module is based on the [http://expath.org/spec/file EXPath File Module].<br />
<br />
=Conventions=<br />
<br />
All functions and errors in this module are assigned to the {{Code|http://expath.org/ns/file}} namespace, which is statically bound to the {{Code|file}} prefix.<br/><br />
<br />
For serialization parameters, the {{Code|http://www.w3.org/2010/xslt-xquery-serialization}} namespace is used, which is statically bound to the {{Code|output}} prefix.<br/><br />
<br />
Returned strings that refer to existing directories are suffixed with a directory separator. The error <code>[[#Errors|invalid-path]]</code> is raised if a path is invalid.<br />
<br />
=Read Operations=<br />
<br />
==file:list==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:list|$dir as xs:string|xs:string*}}<br />{{Func|file:list|$dir as xs:string, $recursive as xs:boolean|xs:string*}}<br />{{Func|file:list|$dir as xs:string, $recursive as xs:boolean, $pattern as xs:string|xs:string*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Lists all files and directories found in the specified {{Code|$dir}}. The returned paths are relative to the provided path.<br />The optional parameter {{Code|$recursive}} specifies whether sub-directories will be traversed, too.<br />The optional parameter {{Code|$pattern}} defines a file name pattern in the [[Commands#Glob_Syntax|Glob Syntax]]. If present, only those files and directories are returned that correspond to the pattern. Several patterns can be separated with a comma ({{Code|,}}).<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br />{{Error|no-dir|#Errors}} the specified path does not point to a directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:children==<br />
<br />
{{Mark|Introduced with Version 8.0:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:children|$dir as xs:string|xs:string*}}<br />
|-<br />
| '''Summary'''<br />
|Returns the full paths to all files and directories found in the specified {{Code|$dir}}.<br/>The inverse function is [[#file:parent|file:parent]]. The related function [[#file:list|file:list]] returns relative file paths.<br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br />{{Error|no-dir|#Errors}} the specified path does not point to a directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:read-binary==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:read-binary|$path as xs:string|xs:base64Binary}}<br />{{Func|file:read-binary|$path as xs:string, $offset as xs:integer|xs:base64Binary}}<br />{{Func|file:read-binary|$path as xs:string, $offset as xs:integer, $length as xs:integer|xs:base64Binary}}<br />
|-<br />
| '''Summary'''<br />
|Reads the binary content of the file specified by {{Code|$path}} and returns it as [[Streaming Module|streamable]] {{Code|xs:base64Binary}}.<br />The optional parameters {{Code|$offset}} and {{Code|$length}} can be used to read chunks of a file.<br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|out-of-range|#Errors}} the offset or length is negative, or the chosen values would exceed the file bounds.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|-<br />
| '''Examples'''<br />
|<br />
* <code><nowiki>stream:materialize(file:read-binary("config.data"))</nowiki></code> returns a materialized representation of the streamable result.<br />
|}<br />
<br />
==file:read-text==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:read-text|$path as xs:string|xs:string}}<br />{{Func|file:read-text|$path as xs:string, $encoding as xs:string|xs:string}}<br /><br />
|-<br />
| '''Summary'''<br />
|Reads the textual contents of the file specified by {{Code|$path}} and returns it as [[Streaming Module|streamable]] {{Code|xs:string}}.<br />The optional parameter {{Code|$encoding}} defines the encoding of the file.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|unknown-encoding|#Errors}} the specified encoding is not supported, or unknown.<br />{{Error|io-error|#Errors}} the operation fails for some other reason. Invalid XML characters will be ignored if the <code>[[Options#CHECKSTRINGS|CHECKSTRINGS]]</code> option is turned off.<br /><br />
|-<br />
| '''Examples'''<br />
|<br />
* <code><nowiki>stream:materialize(file:read-text("config.txt"))</nowiki></code> returns a materialized representation of the streamable result.<br />
|}<br />
<br />
==file:read-text-lines==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:read-text-lines|$path as xs:string|xs:string}}<br />{{Func|file:read-text-lines|$path as xs:string, $encoding as xs:string|xs:string*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Reads the textual contents of the file specified by {{Code|$path}} and returns it as a sequence of {{Code|xs:string}} items.<br />The optional parameter {{Code|$encoding}} defines the encoding of the file.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|unknown-encoding|#Errors}} the specified encoding is not supported, or unknown.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
=Write Operations=<br />
<br />
==file:create-dir==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:create-dir|$dir as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Creates the directory specified by {{Code|$dir}}, including all non-existing parent directories.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|exists|#Errors}} a file with the same path already exists.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:create-temp-dir==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:create-temp-dir|$prefix as xs:string, $suffix as xs:string|xs:string}}<br />{{Func|file:create-temp-dir|$prefix as xs:string, $suffix as xs:string, $dir as xs:string|xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Creates a new temporary directory that did not exist before this function was called, and returns its full file path. The directory name begins and ends with the specified {{Code|$prefix}} and {{Code|$suffix}}. If no directory is specified via {{Code|$dir}}, the directory will be placed in the system’s default temporary directory. The operation will create all non-existing parent directories.<br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the specified directory points to a file.<br />{{Error|io-error|#Errors}} the directory could not be created.<br />
|}<br />
<br />
==file:create-temp-file==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:create-temp-file|$prefix as xs:string, $suffix as xs:string|xs:string}}<br />{{Func|file:create-temp-file|$prefix as xs:string, $suffix as xs:string, $dir as xs:string|xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Creates a new temporary file that did not exist before this function was called, and returns its full file path. The file name begins and ends with the specified {{Code|$prefix}} and {{Code|$suffix}}. If no directory is specified via {{Code|$dir}}, the file will be placed in the system’s default temporary directory. The operation will create all non-existing parent directories.<br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the specified directory points to a file.<br />{{Error|io-error|#Errors}} the directory could not be created.<br />
|}<br />
<br />
==file:delete==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:delete|$path as xs:string|empty-sequence()}}<br />{{Func|file:delete|$path as xs:string, $recursive as xs:boolean|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Recursively deletes a file or directory specified by {{Code|$path}}.<br />The optional parameter {{Code|$recursive}} specifies whether sub-directories will be deleted, too.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified path does not exist.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:write==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:write|$path as xs:string, $items as item()*|empty-sequence()}}<br />{{Func|file:write|$path as xs:string, $items as item()*, $params as item()|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Writes a serialized sequence of items to the specified file. If the file already exists, it will be overwritten.<br />The {{Code|$params}} argument contains serialization parameters (see [[Serialization]] for more details), which can either be specified<br /><br />
* as children of an {{Code|&lt;output:serialization-parameters/&gt;}} element, as defined for the [http://www.w3.org/TR/xpath-functions-30/#func-serialize fn:serialize()] function; e.g.:<br />
<pre class="brush:xml"><br />
<output:serialization-parameters><br />
<output:method value='xml'/><br />
<output:cdata-section-elements value="div"/><br />
...<br />
</output:serialization-parameters><br />
</pre><br />
* as map, which contains all key/value pairs:<br />
<pre class="brush:xml"><br />
map { "method": "xml", "cdata-section-elements": "div", ... }<br />
</pre><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:write-binary==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:write-binary|$path as xs:string, $value as xs:anyAtomicType|empty-sequence()}}<br />{{Func|file:write-binary|$path as xs:string, $value as xs:anyAtomicType, $offset as xs:integer|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Writes a binary item (xs:base64Binary, xs:hexBinary) to the specified file. If the file already exists, it will be overwritten.<br />If {{Code|$offset}} is specified, data will be written at this file position. An existing file may be resized by that operation.<br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|out-of-range|#Errors}} the offset is negative, or it exceeds the current file size.<br/>{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:write-text==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:write-text|$path as xs:string, $value as xs:string|empty-sequence()}}<br />{{Func|file:write-text|$path as xs:string, $value as xs:string, $encoding as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Writes a string to the specified file. If the file already exists, it will be overwritten.<br />The optional parameter {{Code|$encoding}} defines the output encoding (default: UTF-8).<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|unknown-encoding|#Errors}} the specified encoding is not supported, or unknown.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:write-text-lines==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:write-text-lines|$path as xs:string, $values as xs:string*|empty-sequence()}}<br />{{Func|file:write-text-lines|$path as xs:string, $values as xs:string*, $encoding as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Writes a sequence of strings to the specified file, each followed by the system specific newline character. If the file already exists, it will be overwritten.<br />The optional parameter {{Code|$encoding}} defines the output encoding (default: UTF-8).<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|unknown-encoding|#Errors}} the specified encoding is not supported, or unknown.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:append==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:append|$path as xs:string, $items as item()*|empty-sequence()}}<br />{{Func|file:append|$path as xs:string, $items as item()*, $params as item()|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Appends a serialized sequence of items to the specified file. If the file does not exists, a new file is created.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:append-binary==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:append-binary|$path as xs:string, $value as xs:anyAtomicType|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Appends a binary item (xs:base64Binary, xs:hexBinary) to the specified file. If the file does not exists, a new one is created.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:append-text==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:append-text|$path as xs:string, $value as xs:string|empty-sequence()}}<br />{{Func|file:append-text|$path as xs:string, $value as xs:string, $encoding as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Appends a string to a file specified by {{Code|$path}}. If the specified file does not exists, a new file is created.<br />The optional parameter {{Code|$encoding}} defines the output encoding (default: UTF-8).<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|unknown-encoding|#Errors}} the specified encoding is not supported, or unknown.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:append-text-lines==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:append-text-lines|$path as xs:string, $values as xs:string*|empty-sequence()}}<br />{{Func|file:append-text-lines|$path as xs:string, $values as xs:string*, $encoding as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Appends a sequence of strings to the specified file, each followed by the system specific newline character. If the specified file does not exists, a new file is created.<br />The optional parameter {{Code|$encoding}} defines the output encoding (default: UTF-8).<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|no-dir|#Errors}} the parent of specified path is no directory.<br />{{Error|is-dir|#Errors}} the specified path is a directory.<br />{{Error|unknown-encoding|#Errors}} the specified encoding is not supported, or unknown.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
<br />
==file:copy==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:copy|$source as xs:string, $target as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Copies a file or directory specified by {{Code|$source}} to the file or directory specified by {{Code|$target}}. If the target file already exists, it will be overwritten. No operation will be performed if the source and target path are equal.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified source does not exist.<br />{{Error|exists|#Errors}} the specified source is a directory and the target is a file.<br />{{Error|no-dir|#Errors}} the parent of the specified target is no directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
==file:move==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:move|$source as xs:string, $target as xs:string|empty-sequence()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Moves or renames the file or directory specified by {{Code|$source}} to the path specified by {{Code|$target}}. If the target file already exists, it will be overwritten. No operation will be performed if the source and target path are equal.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified source does not exist.<br />{{Error|exists|#Errors}} the specified source is a directory and the target is a file.<br />{{Error|no-dir|#Errors}} the parent of the specified target is no directory.<br />{{Error|io-error|#Errors}} the operation fails for some other reason.<br /><br />
|}<br />
<br />
=File Properties=<br />
<br />
==file:exists==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:exists|$path as xs:string|xs:boolean}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an {{Code|xs:boolean}} indicating whether a file or directory specified by {{Code|$path}} exists in the file system.<br /><br />
|}<br />
<br />
==file:is-dir==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:is-dir|$path as xs:string|xs:boolean}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an {{Code|xs:boolean}} indicating whether the argument {{Code|$path}} points to an existing directory.<br /><br />
|}<br />
<br />
==file:is-file==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:is-file|$path as xs:string|xs:boolean}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an {{Code|xs:boolean}} indicating whether the argument {{Code|$path}} points to an existing file.<br /><br />
|}<br />
<br />
==file:last-modified==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:last-modified|$path as xs:string|xs:dateTime}}<br /><br />
|-<br />
| '''Summary'''<br />
|Retrieves the timestamp of the last modification of the file or directory specified by {{Code|$path}}.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified path does not exist.<br /><br />
|}<br />
<br />
==file:size==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:size|$file as xs:string|xs:integer}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns the size, in bytes, of the file specified by {{Code|$path}}, or {{Code|0}} for directories.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br /><br />
|}<br />
<br />
=Path Functions=<br />
<br />
==file:name==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:name|$path as xs:string|xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Returns the name of a file or directory specified by {{Code|$path}}. An empty string is returned if the path points to the root directory.<br />
|}<br />
<br />
==file:parent==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:parent|$path as xs:string|xs:string?}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns the absolute path to the parent directory of a file or directory specified by {{Code|$path}}. An empty sequence is returned if the path points to a root directory.<br/>The inverse function is [[#file:children|file:children]].<br /><br />
|-<br />
| '''Examples'''<br />
|<br />
* <code><nowiki>file:parent(static-base-uri())</nowiki></code> returns the directory of the current XQuery module.<br />
|}<br />
<br />
==file:path-to-native==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:path-to-native|$path as xs:string|xs:string}}<br /><br />
|-<br />
| '''Summary'''<br />
|Transforms the {{Code|$path}} argument to its native representation on the operating system.<br /><br />
|-<br />
| '''Errors'''<br />
|{{Error|not-found|#Errors}} the specified file does not exist.<br />{{Error|io-error|#Errors}} the specified path cannot be transformed to its native representation.<br /><br />
|}<br />
<br />
==file:resolve-path==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:resolve-path|$path as xs:string|xs:string}}<br /><br />
|-<br />
| '''Summary'''<br />
|Transforms the {{Code|$path}} argument to an absolute operating system path.<br /><br />
|}<br />
<br />
==file:path-to-uri==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:path-to-uri|$path as xs:string|xs:string}}<br /><br />
|-<br />
| '''Summary'''<br />
|Transforms the path specified by {{Code|$path}} into a URI with the {{Code|file://}} scheme.<br /><br />
|}<br />
<br />
=System Properties=<br />
<br />
==file:dir-separator==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Code|'''file:dir-separator'''() as xs:string}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns the directory separator used by the operating system, such as {{Code|/}} or {{Code|\}}.<br /><br />
|}<br />
<br />
==file:path-separator==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Code|'''file:path-separator'''() as xs:string}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns the path separator used by the operating system, such as {{Code|;}} or {{Code|:}}.<br /><br />
|}<br />
<br />
==file:line-separator==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:line-separator||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Returns the line separator used by the operating system, such as {{Code|&amp;#10;}}, {{Code|&amp;#13;&amp;#10;}} or {{Code|&amp;#13;}}.<br /><br />
|}<br />
<br />
==file:temp-dir==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:temp-dir||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Returns the system’s default temporary-file directory.<br /><br />
|}<br />
<br />
==file:current-dir==<br />
<br />
{{Mark|Introduced with Version 8.0:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:current-dir||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Returns the current working directory. - This function returns the same result as the function call {{Code|file:resolve-path('')}}<br /><br />
|}<br />
<br />
==file:base-dir==<br />
<br />
{{Mark|Introduced with Version 8.0:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|file:base-dir||xs:string?}}<br />
|-<br />
| '''Summary'''<br />
|Returns the parent directory of the static base URI. If the Base URI property is undefined, the empty sequence is returned. - If a static base URI exists, and if points to a local file path, this function returns the same result as the expression {{Code|file:parent(static-base-uri())}}.<br />
|}<br />
<br />
=Errors=<br />
<br />
{| class="wikitable" width="100%"<br />
! width="160"|Code<br />
|Description<br />
|-<br />
|{{Code|not-found}}<br />
|A specified path does not exist.<br />
|-<br />
|{{Code|invalid-path}}<br />
|A specified path is invalid.<br />
|-<br />
|{{Code|exists}}<br />
|A file with the same path already exists.<br />
|-<br />
|{{Code|no-dir}}<br />
|The specified path does not point to a directory.<br />
|-<br />
|{{Code|is-dir}}<br />
|The specified path is a directory.<br />
|-<br />
|{{Code|unknown-encoding}}<br />
|The specified encoding is not supported, or unknown.<br />
|-<br />
|{{Code|out-of-range}}<br />
|The specified offset or length is negative, or the chosen values would exceed the file bounds.<br />
|-<br />
|{{Code|io-error}}<br />
|The operation fails for some other reason specific to the operating system.<br />
|}<br />
<br />
=Changelog=<br />
<br />
;Version 8.0<br />
* Added: [[#file:current-dir|file:current-dir]], [[#file:base-dir|file:base-dir]], [[#file:children|file:children]]<br />
<br />
;Version 7.8<br />
* Added: [[#file:parent|file:parent]], [[#file:name|file:name]]<br />
* Updated: error codes; [[#file:read-binary|file:read-binary]], [[#file:write-binary|file:write-binary]]: {{Code|$offset}} and {{Code|$length}} arguments added.<br />
* Deleted: file:base-name, file:dir-name<br />
<br />
;Version 7.7<br />
* Added: [[#file:create-temp-dir|file:create-temp-dir]], [[#file:create-temp-file|file:create-temp-file]], [[#file:temp-dir|file:temp-dir]]<br />
* Updated: all returned strings that refer to existing directories will be suffixed with a directory separator.<br />
<br />
;Version 7.3<br />
* Added: [[#file:append-text|file:append-text]], [[#file:write-text|file:write-text]], [[#file:append-text-lines|file:append-text-lines]], [[#file:write-text-lines|file:write-text-lines]], [[#file:line-separator|file:line-separator]]<br />
* Aligned with latest specification: $file:directory-separator → [[#file:dir-separator|file:dir-separator]], $file:path-separator → [[#file:path-separator|file:path-separator]], file:is-directory → [[#file:is-dir|file:is-dir]], file:create-directory → [[#file:create-dir|file:create-dir]]<br />
* Updated: [[#file:write-binary|file:write-binary]], [[#file:append-binary|file:append-binary]]: output limited to a single value<br />
<br />
;Version 7.2.1<br />
* Updated: [[#file:delete|file:delete]]: {{Code|$recursive}} parameter added to prevent sub-directories from being accidentally deleted.<br />
* Fixed: [[#file:list|file:list]] now returns relative instead of absolute paths.<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=RESTXQ&diff=11279RESTXQ2015-01-15T08:08:38Z<p>Dirk: Fix mistake pointed out on the ML</p>
<hr />
<div>This page presents one of the [[Web Application]] services. It describes how to use the RESTXQ API of BaseX.<br />
<br />
RESTXQ, introduced by [http://www.adamretter.org.uk/ Adam Retter], is an API that facilitates the use of XQuery<br />
as a server-side processing language for the Web. RESTXQ has been inspired by Java’s<br />
[http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services JAX-RS API]: it defines a pre-defined set of<br />
XQuery 3.0 annotations for mapping HTTP requests to XQuery functions, which in turn generate and return<br />
HTTP responses.<br />
<br />
Please note that BaseX provides various extensions to the official draft of the specification:<br />
<br />
* Multipart types are supported, including {{Code|multipart/form-data}}<br />
* A {{Code|%rest:error}} annotation can be used to catch XQuery errors<br />
* Servlet errors can be redirected to other RESTXQ pages<br />
* A [[RESTXQ Module]] provides some helper functions<br />
* Parameters are implicitly cast to the type of the function argument<br />
<br />
The following features are available since {{Version|8.0}}:<br />
<br />
* Regular expresssions in the [[#Paths|Path Annotation]]<br />
* Evaluation of quality factors that are supplied in the [[#Content Negotiation|Accept header]]<br />
* BaseX is now shipped with a Database Administration Interface (DBA). It will automatically be launched when requesting the RESTXQ root page.<br />
<br /><br />
<br />
=Introduction=<br />
<br />
The RESTXQ service is accessible via {{Code|http://localhost:8984/}}.<br />
<br />
All RESTXQ [[XQuery 3.0#Annotations|annotations]] are assigned to the {{Code|<nowiki>http://exquery.org/ns/restxq</nowiki>}} namespace, which is statically bound to the {{Code|rest}} prefix. A ''Resource Function'' is an XQuery function that has been marked up with RESTXQ annotations. When an HTTP request comes in, a resource function will be invoked that matches the constraints indicated by its annotations.<br />
<br />
Whenever a RESTXQ URL is requested, the [[Options#RESTXQPATH|RESTXQPATH]] module directory and its sub-directories will be parsed for functions with RESTXQ annotations in library modules (detected by the extension {{Code|.xqm}}) and main modules (detected by {{Code|.xq}}). In main expressions, the main module will never be evaluated. All modules will be cached and parsed again when their timestamp changes.<br />
<br />
A first RESTXQ function is shown below:<br />
<br />
<pre class="brush:xquery"><br />
module namespace page = 'http://basex.org/examples/web-page';<br />
<br />
declare %rest:path("hello/{$who}") %rest:GET function page:hello($who) {<br />
<response><br />
<title>Hello { $who }!</title><br />
</response><br />
};</pre><br />
<br />
If the URI http://localhost:8984/hello/World is accessed, the result will be:<br />
<br />
<pre class="brush:xml"><br />
&lt;response&gt;<br />
&lt;title&gt;Hello World!&lt;/title&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
The next function demonstrates a POST request:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/form")<br />
%rest:POST<br />
%rest:form-param("message","{$message}", "(no message)")<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello-postman(<br />
$message as xs:string,<br />
$agent as xs:string*)<br />
as element(response)<br />
{<br />
&lt;response type='form'&gt;<br />
&lt;message&gt;{ $message }&lt;/message&gt;<br />
&lt;user-agent&gt;{ $agent }&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
};<br />
</pre><br />
<br />
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...<br />
<br />
<pre class="brush:shell"><br />
curl -i -X POST --data "message='CONTENT'" http://localhost:8984/form<br />
</pre><br />
<br />
...you will receive something similar to the following result:<br />
<br />
<pre class="brush:shell"><br />
HTTP/1.1 200 OK<br />
Content-Type: application/xml; charset=UTF-8<br />
Content-Length: 107<br />
Server: Jetty(8.1.11.v20130520)<br />
</pre><br />
<br />
<pre class="brush:xml"><br />
<response type="form"><br />
<message>'CONTENT'</message><br />
<user-agent>curl/7.31.0</user-agent><br />
</response><br />
</pre><br />
<br />
=Requests=<br />
<br />
This section shows how annotations are used to handle and process HTTP requests.<br />
<br />
==Constraints==<br />
<br />
Constraints restrict the HTTP requests that a resource function may process.<br />
<br />
===Paths===<br />
<br />
A resource function must have a single ''Path Annotation'' with a single string as argument. The function will be called if a URL matches the path segments and templates of the argument. ''Path templates'' contain variables in curly brackets, and map the corresponding segments of the request path to the arguments of the resource function. The first slash in the path is optional;<br />
<br />
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/a/path/{$with}/some/{$variable}")<br />
function page:test($with, $variable as xs:integer) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
Since {{Version|8.0}}, variables can be extended by regular expressions:<br />
<br />
<pre class="brush:xquery"><br />
(: Matches all paths with "app" as first, a number as second, and "order" as third segment :)<br />
declare %rest:path("app/{$code=[0-9]+}/order")<br />
function page:order($full-path) { ... };<br />
<br />
(: Matches all other all paths starting with "app/" :)<br />
declare %rest:path("app/{$path=.+}")<br />
function page:others($path) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
===Content Negotiation===<br />
<br />
Two following annotations can be used to restrict functions to specific content types:<br />
<br />
* '''HTTP Content Types''': a function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given mime types. Example:<br />
<pre class="brush:xquery">%rest:consumes("application/xml", "text/xml")</pre><br />
* '''HTTP Accept''': a function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined mime types. Example:<br />
<pre class="brush:xquery">%rest:produces("application/atom+xml")</pre><br />
<br />
By default, both mime types are {{Code|*/*}}.<br />
<br />
Since {{Version|8.0}}, quality factors supplied by a client will also be considered in the path selection process. If a client supplies the following accept header…<br />
<br />
<pre><br />
*/*;q=0.5,text/html;q=1.0<br />
</pre><br />
<br />
…and if two RESTXQ functions exist with the same {{Code|path}} annotation and the {{Code|produces}} annotations <code>*/*</code> and <code>text/html</code>, respectively, the function with the second annotation will be called, because the quality factor for <code>text/html</code> documents is higher than the one for arbitrary other mime types.<br />
<br />
Note that this annotation will ''not'' affect the content-type of the HTTP response. Instead, you will need to add a <code>[[#Output|%output:media-type]]</code> annotation.<br />
<br />
===HTTP Methods===<br />
<br />
====Fixed Methods====<br />
<br />
The HTTP method annotations are equivalent to all [http://en.wikipedia.org/wiki/HTTP#Request_methods HTTP request methods] except for TRACE and CONNECT. Zero or more methods may be used on a function; if none is specified, the function will be invoked for each method.<br />
<br />
The following function will be called if GET or POST is used as request method:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:GET %rest:POST %rest:path("/post")<br />
function page:post() { "This was a GET or POST request" };<br />
</pre><br />
<br />
The POST and PUT annotations may optionally take a string literal in order to map the HTTP request body to a [[#Parameters|function argument]]. Once again, the target variable must be embraced by curly brackets:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:PUT("{$body}") %rest:path("/put")<br />
function page:put($body) { "Request body: " || $body };<br />
</pre><br />
<br />
====Custom Methods====<br />
<br />
Since {{Version|7.9}}, custom HTTP methods can be specified with the {{Code|%rest:method}} annotation:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:method("RETRIEVE")<br />
function page:retrieve() { "RETRIEVE was specified as request method." };<br />
</pre><br />
<br />
===Content Types===<br />
<br />
If a content-type is specified in the request, the content is converted to the following XQuery type:<br />
<br />
{| class="wikitable" width="100%"<br />
|- valign="top"<br />
! Content-Type<br />
! XQuery type<br />
|-<br />
| {{Code|application/json}}, {{Code|application/jsonml+json}}<br />
| {{Code|document-node()}} (conversion is described in the [[JSON Module]])<br />
|-<br />
| {{Code|text/html}}<br />
| {{Code|document-node()}} (conversion is described in the [[HTML Module]])<br />
|-<br />
| {{Code|text/comma-separated-values}}<br />
| {{Code|document-node()}}<br />
|-<br />
| {{Code|text/xml}}, {{Code|application/xml}}<br />
| {{Code|document-node()}}<br />
|-<br />
| {{Code|text/*}}<br />
| {{Code|xs:string}}<br />
|-<br />
| ''others''<br />
| {{Code|xs:base64Binary}}<br />
|-<br />
| {{Code|multipart/*}}<br />
| sequence (see next paragraph)<br />
|}<br />
<br />
====Multipart Types====<br />
<br />
The single parts of a multipart message are represented as a sequence,<br />
and each part is converted to an XQuery item as described in the last paragraph.<br />
<br />
A function that is capable of handling multipart types is identical to other RESTXQ functions:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/multipart")<br />
%rest:POST("{$data}")<br />
%rest:consumes("multipart/mixed") (: optional :)<br />
function page:multipart($data as item()*)<br />
{<br />
"Number of items: " || count($data)<br />
};<br />
</pre><br />
<br />
Please note that support for multipart types is still experimental,<br />
and it may change in a future version BaseX. Your feedback is welcome.<br />
<br />
==Parameters==<br />
<br />
The following annotations can be used to bind request values to function arguments. Values will implicitly be cast to the type of the argument.<br />
<br />
===Query Parameters===<br />
<br />
The value of the ''first parameter'', if found in the [[Request_Module#Conventions|query component]], will be assigned to the variable specified as ''second parameter''. If no value is specified in the HTTP request, all additional parameters will be bound to the variable (if no additional parameter is given, an empty sequence will be bound):<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/params")<br />
%rest:query-param("id", "{$id}")<br />
%rest:query-param("add", "{$add}", 42, 43, 44)<br />
function page:params($id as xs:string?, $add as xs:integer+)<br />
{<br />
<result id="{ $id }" sum="{ sum($add) }"/><br />
};<br />
</pre><br />
<br />
===HTML Form Fields===<br />
<br />
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are extracted from GET or POST requests.<br />
<br />
<pre class="brush:xquery"><br />
%rest:form-param("parameter", "{$value}", "default")<br />
</pre><br />
<br />
====File Uploads====<br />
<br />
Files can be uploaded to the server by using the content type {{Code|multipart/form-data}} (the HTML5 {{Code|multiple}} attribute enables the upload of multiple files):<br />
<br />
<pre class="brush:xml"><br />
<form action="/upload" method="POST" enctype="multipart/form-data"><br />
<input type="file" name="files" multiple="multiple"/><br />
<input type="submit"/><br />
</form><br />
</pre><br />
<br />
The file contents are placed in a [[Map Module|map]], with the filename serving as key. The following example shows how uploaded files can be stored in a temporary directory:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:POST<br />
%rest:path("/upload")<br />
%rest:form-param("files", "{$files}")<br />
function page:upload($files)<br />
{<br />
for $name in map:keys($files)<br />
let $content := $files($name)<br />
let $path := file:temp-dir() || $name<br />
return (<br />
file:write-binary($path, $content),<br />
<file name="{ $name }" size="{ file:size($path) }"/><br />
)<br />
};<br />
</pre><br />
<br />
===HTTP Headers===<br />
<br />
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:header-param("User-Agent", "{$user-agent}")<br />
%rest:header-param("Referer", "{$referer}", "none")<br />
</pre><br />
<br />
===Cookies===<br />
<br />
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:cookie-param("username", "{$user}")<br />
%rest:cookie-param("authentication", "{$auth}", "no_auth")<br />
</pre><br />
<br />
=Responses=<br />
<br />
By default, a successful request is answered with the HTTP status code {{Code|200}} (OK) and is followed by the given content. An erroneous request leads to an error code and an optional error message (e.g. {{Code|404}} for “resource not found”).<br />
<br />
==Custom Responses==<br />
<br />
Custom responses can be built from within XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and more optional child nodes that will be serialized as usual. A function that reacts on an unknown resource may look as follows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("") function page:error404() {<br />
<rest:response><br />
<http:response status="404" message="I was not found."><br />
<http:header name="Content-Language" value="en"/><br />
<http:header name="Content-Type" value="text/html; charset=utf-8"/><br />
</http:response><br />
</rest:response><br />
};<br />
</pre><br />
<br />
==Forwards and Redirects==<br />
<br />
The two XML elements <code>rest:forward</code> and <code>rest:redirect</code> can be used in the context of [[Web Application]]s, precisely in the context of RESTXQ. These nodes allow e.g. multiple [[XQuery Update]]s in a row by redirecting to the RESTXQ path of updating functions. Both wrap a URL to a RESTXQ path. The wrapped URL should be properly encoded via <code>fn:encode-for-uri()</code>.<br />
<br />
Note that, currently, these elements are not part of RESTXQ specification.<br />
<br />
===rest:forward===<br />
<br />
Usage: wrap the location as follows<br />
<pre class="brush:xml"><rest:forward>{ $location }</rest:forward></pre><br />
<br />
This results in a server-side forwarding, which as well reduces traffic among client and server. A forwarding of this kind will not change the URL seen from the client's perspective.<br />
<br />
As an example, returning<br />
<pre class="brush:xml"><br />
<rest:forward>/hello/universe</rest:forward><br />
</pre><br />
would internally forward to http://localhost:8984/hello/universe<br />
<br />
===rest:redirect===<br />
<br />
<pre class="brush:xml"><rest:redirect>{ $location }</rest:redirect></pre><br />
<br />
…is basically an abbreviation for…<br />
<br />
<pre class="brush:xml"><br />
<rest:response><br />
<http:response status="302" message="Temporary Redirect"><br />
<http:header name="location" value="{ $location }"/><br />
</http:response><br />
</rest:response><br />
</pre><br />
<br />
The client decides whether to follow this redirection. Browsers usually will, tools like [http://curl.haxx.se/ curl] won’t unless {{Code|-L}} is specified.<br />
<br />
==Output==<br />
<br />
Similar to the [[REST#Content Type|REST]] interface, result serialization can be modified via [[XQuery 3.0#Serialization|XQuery 3.0 serialization parameters]]; in RESTXQ, serialization parameters may be specified in the query prolog, via annotations, or within REST response element. Global parameters are overwritten by more local parameters.<br />
<br />
===Query Prolog===<br />
<br />
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:<br />
<br />
<pre class="brush:xquery"><br />
declare option output:media-type 'text/plain';<br />
<br />
declare %rest:path("version1") function page:version1() {<br />
'Keep it simple, stupid'<br />
};<br />
</pre><br />
<br />
===Annotations===<br />
<br />
The serialization can also be parameterized via annotations:<br />
<br />
<pre class="brush:xquery"><br />
declare %output:media-type("text/plain") %rest:path("version2") function page:version2() {<br />
'Still somewhat simple.'<br />
};<br />
</pre><br />
<br />
===Response Element===<br />
<br />
The following example demonstrates how serialization parameters can be dynamically set within a query:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("version3") function page:version3() {<br />
<rest:response><br />
<output:serialization-parameters><br />
<output:media-type value='text/plain'/><br />
</output:serialization-parameters><br />
</rest:response>,<br />
'Not that simple anymore'<br />
};<br />
</pre><br />
<br />
The content type can also be overwritten by specifying an output {{Code|method}}. The following method mappings are available:<br />
<br />
* <code>xml</code> → <code>application/xml</code><br />
* <code>xhtml</code> → <code>text/html</code><br />
* <code>html</code> → <code>text/html</code><br />
* <code>text</code> → <code>text/plain</code><br />
* <code>json</code> or <code>jsonml</code> → <code>application/json</code><br />
* <code>raw</code> → <code>application/octet-stream</code><br />
<br />
When using <code>raw</code>, binary data will be sent in its original byte representation, i. e., without further conversion.<br />
<br />
By default, {{Code|application/xml}} is returned as content type. In the following example, XHTML headers will be generated, and {{Code|text/html}} will be set as content type:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("")<br />
%output:method("xhtml")<br />
%output:omit-xml-declaration("no")<br />
%output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN") <br />
%output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")<br />
function page:start()<br />
{<br />
<html xmlns="http://www.w3.org/1999/xhtml"><br />
<body>done</body><br />
</html><br />
};<br />
</pre><br />
<br />
=Error Handling=<br />
<br />
==XQuery Errors==<br />
<br />
{{Mark|Updated with Version 7.9:}}<br />
<br />
XQuery runtime errors can be processed via ''error annotations''.<br />
Error annotations have one or more arguments, which represent the error codes to be caught.<br />
The codes equal the names of the XQuery 3.0 [[XQuery 3.0#Try.2FCatch|try/catch]] construct:<br />
<br />
{| class="wikitable"<br />
|- valign="top"<br />
! Priority<br />
! Syntax<br />
! Example<br />
|-<br />
| 1<br />
| <code>prefix:name</code><br/><code>Q{uri}name</code><br />
| <code>err:FORG0001</code><br/><code><nowiki>Q{http://www.w3.org/2005/xqt-errors}FORG0001</nowiki></code><br />
|-<br />
| 2<br />
| <code>prefix:*</code><br/><code>Q{uri}*</code><br />
| <code>err:*</code><br/><code><nowiki>Q{http://www.w3.org/2005/xqt-errors}*</nowiki></code><br />
|-<br />
| 3<br />
| <code>*:name</code><br />
| <code>*:FORG0001</code><br />
|-<br />
| 4<br />
| <code>*</code><br />
| <code>*</code><br />
|}<br />
<br />
All error codes that are specified for a function must be of the same priority.<br />
The following rules apply when catching errors:<br />
<br />
* Codes with a higher priority will be preferred.<br />
* A global RESTXQ error will be raised if two functions with conflicting codes are found.<br />
<br />
Similar to try/catch, the pre-defined variables ({{Code|code}}, {{Code|description}}, {{Code|value}}, {{Code|module}}, {{Code|line-number}}, {{Code|column-number}}, {{Code|additional}}) can be bound to variables via ''error parameter annotations'', which are specified the same way as [[#Query Parameters|query parameters]].<br />
<br />
Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/check/{$user}")<br />
function page:check($user)<br />
{<br />
if($user = ('jack', 'lisa'))<br />
then 'User exists'<br />
else fn:error(xs:QName('err:user'), $user)<br />
};<br />
<br />
declare <br />
%rest:error("err:user")<br />
%rest:error-param("description", "{$user}")<br />
function page:user-error($user)<br />
{<br />
'User "' || $user || '" is unknown'<br />
};<br />
</pre><br />
<br />
==HTTP Errors==<br />
<br />
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):<br />
<br />
<pre class="brush:xml"><br />
<error-page><br />
<error-code>404</error-code><br />
<location>/error404</location><br />
</error-page><br />
</pre><br />
<br />
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/error404") function page:error404() {<br />
"URL: " || request:attribute("javax.servlet.error.request_uri") || ", " || <br />
"Error message: " || request:attribute("javax.servlet.error.message")<br />
};<br />
</pre><br />
<br />
=Functions=<br />
<br />
The [[Request Module]] contains functions for accessing data related to the current HTTP request. Two modules exist for setting and retrieving server-side session data of the current user ([[Session Module]]) and all users known to the HTTP server ([[Sessions Module]]). The [[RESTXQ Module]] provides functions for requesting RESTXQ base URIs and generating a [http://www.w3.org/Submission/wadl/ WADL description] of all services. Please note that the namespaces of all of these modules must be explicitly specified via module imports in the query prolog.<br />
<br />
The following example returns the current host name:<br />
<br />
<pre class="brush:xquery"><br />
import module namespace request = "http://exquery.org/ns/request";<br />
<br />
declare %rest:path("/host-name") function page:host() {<br />
'Remote host name: ' || request:remote-hostname()<br />
};<br />
</pre><br />
<br />
=References=<br />
<br />
RESTXQ has been proposed by [http://www.adamretter.org.uk/ Adam Retter].<br />
More information on all specifics can be found in the following two documents:<br />
<br />
* [http://www.adamretter.org.uk/papers/restful-xquery_january-2012.pdf RESTful XQuery, Standardised XQuery 3.0 Annotations for REST]. Paper, XMLPrague, 2012<br />
* [http://www.adamretter.org.uk/presentations/restxq_mugl_20120308.pdf RESTXQ]. Slides, MarkLogic User Group London, 2012<br />
* [http://exquery.github.com/exquery/exquery-restxq-specification/restxq-1.0-specification.html RESTXQ Specification], Unofficial Draft<br />
* [http://files.basex.org/xmlprague2013/slides/Develop-RESTXQ-WebApps-with-BaseX.pdf Web Application, RESTXQ Development]. Web Application Development with RESTXQ Slides from XMLPrague 2013<br />
<br />
=Changelog=<br />
<br />
;Version 8.0<br />
<br />
* Added: DBA (Database Administration Interface, written with RESTXQ)<br />
* Added: Support of regular expresssions in the [[#Paths|Path Annotation]]<br />
* Added: Evaluation of quality factors that are supplied in the [[#Content Negotiation|Accept header]]<br />
<br />
;Version 7.9<br />
<br />
* Updated: [[#XQuery Errors|XQuery Errors]], extended error annotations<br />
* Added: {{Code|%rest:method}}<br />
<br />
;Version 7.7<br />
<br />
* Added: [[#Error Handling|Error Handling]], [[#File Uploads|File Uploads]], [[#Multipart Types|Multipart Types]]<br />
* Updated: RESTXQ function may now also be specified in main modules (suffix: {{Code|*.xq}}).<br />
* Updated: the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
* Updated: parameters are implicitly cast to the type of the function argument<br />
* Updated: the RESTXQ root url has been changed to {{Code|http://localhost:8984/}}<br />
<br />
;Version 7.5<br />
<br />
* Added: new XML elements {{Code|<rest:redirect/>}} and {{Code|<rest:forward/>}}<br />
<br />
[[Category:HTTP]]<br />
[[Category:Developer]]</div>Dirkhttps://docs.basex.org/index.php?title=Databases&diff=11146Databases2014-12-05T15:42:21Z<p>Dirk: </p>
<hr />
<div>This page is part of the [[Getting Started]] Section.<br />
<br />
In BaseX, a ''database'' is a pretty light-weight concept and can be compared<br />
to a ''collection''. It contains an arbitrary number of '''resources''',<br />
addressed by their unique database path. Resources can either be<br />
'''XML documents''' or '''raw files''' (binaries).<br />
Some information on [[Binary Data|binary data]] can be found on an extra page.<br />
<br />
=Create Databases=<br />
<br />
New databases can be created via commands, in the GUI, or with any of our<br />
[[Developing|APIs]]. If some input is specified along with the create operation, it will be added to the database in a bulk operation:<br />
<br />
* [[Startup#BaseX Standalone|Console]]: <code>CREATE DB db /path/to/resources</code> will add initial documents to a database<br />
* [[Startup#BaseX GUI|GUI]]: Go to ''Database'' → ''New'', press ''Browse'' to choose an initial file or directory, and press ''OK''<br />
<br />
Database must follow the [[Valid Names|valid names constraints]].<br />
Various [[parsers]] can be chosen to influence the database creation, or to convert different formats to XML.<br />
<br />
'''Note:''' A main-memory only database can be created using the the <code>SET MAINMEM true</code> command before calling <code>CREATE DB</code> ([[Databases#In Memory Database|see below]] for more).<br />
<br />
=Access Resources=<br />
<br />
Stored resources and external documents can be accessed in different ways:<br />
<br />
==XML Documents==<br />
<br />
Various XQuery functions exist to access XML documents in databases:<br />
<br />
{| class="wikitable"<br />
|-<br />
!Function<br />
!Example<br />
!Description<br />
|-<br />
|<code>[[Database Module#db:open|db:open]]</code><br />
|{{Code|db:open("db", "path/to/docs")}}<br />
|Returns all documents that are found in the database {{Code|db}} at the (optional) path {{Code|path/to/docs}}.<br />
|-<br />
|<code>[http://www.xqueryfunctions.com/xq/fn_collection.html fn:collection]</code><br />
|{{Code|collection("db/path/to/docs")}}<br />
|Returns all documents at the location {{Code|path/to/docs}} in the database {{Code|db}}.<br/>If no path is specified after the database, all documents in the database will be returned.<br/>If no argument is specified, all documents of the database will be returned that has been opened in the global context.<br />
|-<br />
|<code>[http://www.xqueryfunctions.com/xq/fn_doc.html fn:doc]</code><br />
|{{Code|doc("db/path/to/doc.xml")}}<br />
|Returns the document at the location {{Code|path/to/docs}} in the database {{Code|db}}.<br/>An error is raised if the specified yields zero or more than one document.<br />
|}<br />
<br />
If the [[Options#DEFAULTDB|DEFAULTDB]] option is turned on, the path argument of the {{Code|fn:doc}} or {{Code|fn:collection}} function will first be resolved against the globally opened database.<br />
<br />
Two more functions are available for retrieving information on database nodes:<br />
<br />
{| class="wikitable"<br />
|-<br />
!Function<br />
!Example<br />
!Description<br />
|-<br />
|<code>[[Database Module#db:name|db:name]]</code><br />
|{{Code|db:name($node)}}<br />
|Returns the name of the database in which the specified {{Code|$node}} is stored.<br />
|-<br />
|<code>[[Database Module#db:path|db:path]]</code><br />
|{{Code|db:path($node)}}<br />
|Returns the path of the database document in which the specified {{Code|$node}} is stored.<br />
|}<br />
<br />
The {{Code|fn:document-uri}} and {{Code|fn:base-uri}} functions return URIs that can also be reused as arguments for the {{Code|fn:doc}} and {{Code|fn:collection}} functions. As a result, the following example query always returns {{Code|true}}:<br />
<br />
<pre class="brush:xquery"><br />
every $c in collection('anyDB')<br />
satisfies doc-available(document-uri($c))<br />
</pre><br />
<br />
If the argument of {{Code|fn:doc}} or {{Code|fn:collection}} does not start with a valid database name, or if the addressed database does not exist, the string is interpreted as URI reference, and the documents found at this location will be returned. Examples:<br />
<br />
* {{Code|doc("http://web.de")}}: retrieves the addressed URI and returns it as a main-memory document node.<br />
* {{Code|doc("myfile.xml")}}: retrieves the given file from the file system and returns it as a main-memory document node. Note, that updates to main-memory nodes are not automatically written back to disk unless the <code>[[Options#WRITEBACK|WRITEBACK]]</code> option is set.<br />
* {{Code|collection("/path/to/docs")}}: returns a main-memory collection with all XML documents found at the addressed file path.<br />
<br />
==Raw Files==<br />
<br />
* XQuery: <code>db:retrieve("dbname", "path/to/docs")</code> returns raw files in their Base64 representation. By choosing <code>"method=raw"</code> as [[Serialization|Serialization Option]], the data is returned in its original byte representation:<br />
<br />
<pre class="brush:xquery"><br />
declare option output:method "raw";<br />
db:retrieve('multimedia', 'sample.avi')<br />
</pre><br />
<br />
* Commands: <code>[[Commands#RETRIEVE|RETRIEVE]]</code> returns raw files without modifications.<br />
<br />
==HTTP Services==<br />
<br />
* With [[REST]] and [[WebDAV]], all database resources can be requested in a uniform way, no matter if they are well-formed XML documents or binary files.<br />
<br />
=Update Resources=<br />
<br />
Once you have created a database, additional commands exist to modify its contents:<br />
<br />
* XML documents can be added with the <code>[[Commands#ADD|ADD]]</code> command.<br />
* Raw files are added with <code>[[Commands#STORE|STORE]]</code>.<br />
* Existing resources can be replaced with the <code>[[Commands#REPLACE|REPLACE]]</code> command.<br />
* Resources can be deleted via <code>[[Commands#DELETE|DELETE]]</code>.<br />
<br />
The [[Options#AUTOFLUSH|AUTOFLUSH]] option can be turned off before ''bulk operations'' (i.e. before a large number of new resources is added to the database).<br />
<br />
The [[Options#ADDCACHE|ADDCACHE]] option will first cache the input before adding it to the database. This is helpful when the input documents to be added are expected to eat up too much main memory.<br />
<br />
The following commands create an empty database, add two resources, explicitly flush data structures to disk, and finally delete all inserted data:<br />
<br />
<pre><br />
CREATE DB example<br />
SET AUTOFLUSH false<br />
ADD example.xml<br />
SET ADDCACHE true<br />
ADD /path/to/xml/documents<br />
STORE TO images/ 123.jpg<br />
FLUSH<br />
DELETE /<br />
</pre><br />
<br />
You may as well use the BaseX-specific [[Database Module|XQuery Database Functions]] to create, add, replace, and delete XML documents:<br />
<br />
<pre class="brush:xquery"><br />
let $root := "/path/to/xml/documents/"<br />
for $file in file:list($root)<br />
return db:add("database", $root || $file)<br />
</pre><br />
<br />
Last but not least, XML documents can also be added via the GUI and the ''Database'' menu.<br />
<br />
=Export Data=<br />
<br />
All resources stored in a database can be ''exported'', i.e., written back to disk. This can be done in several ways:<br />
<br />
* Commands: <code>[[Commands#EXPORT|EXPORT]]</code> writes all resources to the specified target directory<br />
* GUI: Go to ''Database'' → ''Export'', choose the target directory and press ''OK''<br />
* WebDAV: Locate the database directory (or a sub-directory of it) and copy all contents to another location<br />
<br />
=In Memory Database=<br />
<br />
* In the standalone context, a main-memory database can be created (using <code>CREATE DB</code>), which can then be accessed by subsequent commands.<br />
* If a BaseX server instance is started, and if a database is created in its context (using <code>CREATE DB</code>), other BaseX client instances can access (and update) this database (using OPEN, db:open, etc.) as long as no other database is opened/created by the server.<br />
<br />
'''Note:''' main-memory database instances are also created by the invocation of <code>doc(...)</code> or <code>collection(...)</code>, if the argument is not a<br />
database (no matter which value is set for MAINMEM). In other words:<br />
the same internal representation is used for main-memory databases and<br />
documents/collections generated via XQuery.<br />
<br />
=Changelog=<br />
<br />
;Version 7.2.1<br />
<br />
* Updated: {{Code|fn:document-uri}} and {{Code|fn:base-uri}} now return strings that can be reused with {{Code|fn:doc}} or {{Code|fn:collection}} to reopen the original document.<br />
<br />
[[Category:Beginner]]</div>Dirkhttps://docs.basex.org/index.php?title=SQL_Module&diff=11128SQL Module2014-11-28T11:07:43Z<p>Dirk: add JDBC driver information</p>
<hr />
<div>This [[Module Library|XQuery Module]] contains functions to access relational databases from XQuery using SQL. With this module, you can execute query, update and prepared statements, and the result sets are returned as sequences of XML elements representing tuples. Each element has children representing the columns returned by the SQL statement.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/sql}} namespace, which is statically bound to the {{Code|sql}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br/><br />
This module uses JDBC to connect to a SQL server. Hence, you have to put the JDBC driver so that it is loaded into Basex. Most likely you want to put the connector into the {{Code|lib/}} folder, where it will be automatically included. So to connect to MySQL, download the [https://dev.mysql.com/downloads/connector/j/ Connector/J driver from their website] and extract the archive into the {{Code|lib/}} folder.<br />
<br />
=Functions=<br />
<br />
==sql:init==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:init|$class as xs:string|empty-sequence()}}<br />
|-<br />
| '''Summary'''<br />
|This function initializes a JDBC driver specified via {{Code|$class}}. This step might be superfluous if the SQL database is not embedded.<br/ ><br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0007|XQuery Errors#SQL Functions Errors}} the specified driver class is not found.<br />
|}<br />
<br />
==sql:connect==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:connect|$url as xs:string|xs:integer}}<br/ >{{Func|sql:connect|$url as xs:string, $user as xs:string, $password as xs:string|xs:integer}}<br/ >{{Func|sql:connect|$url as xs:string, $user as xs:string, $password as xs:string, $options as item()|xs:integer}}<br/ ><br />
|-<br />
| '''Summary'''<br />
|This function establishes a connection to a relational database. As a result a connection handle is returned. The parameter {{Code|$url}} is the URL of the database and shall be of the form: {{Code|jdbc:<driver name>:[//<server>[/<database>]]}}. If the parameters {{Code|$user}} and {{Code|$password}} are specified, they are used as credentials for connecting to the database. The {{Code|$options}} parameter can be used to set connection options, which can either be specified<br/><br />
* as children of an {{Code|&lt;sql:options/&gt;}} element, e.g.:<br />
<pre class="brush:xml"><br />
<sql:options><br />
<sql:autocommit value='true'/><br />
...<br />
</sql:options><br />
</pre><br />
* as map, which contains all key/value pairs:<br />
<pre class="brush:xml"><br />
map { "autocommit": "true", ... }<br />
</pre><br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs, e.g. missing JDBC driver or not existing relation.<br />
|}<br />
<br />
==sql:execute==<br />
<br />
Once a connection is established, the returned connection handle can be used to execute queries on the database. Our SQL module supports both direct queries and prepared statements.<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:execute|$connection as xs:integer, $query as xs:string|element()*}}<br />
|-<br />
| '''Summary'''<br />
| This function executes a query or update statement. The parameter {{Code|$connection}} specifies a connection handle. The parameter {{Code|$query}} is a string representing an SQL statement.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs, e.g. not existing relation is retrieved.<br/ ><br />
{{Error|BXSQ0002|XQuery Errors#SQL Functions Errors}} a wrong connection handle is passed.<br/ ><br />
|}<br />
<br />
==sql:execute-prepared==<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:execute-prepared|$id as xs:integer, $params as element(sql:parameters)|element()*}}<br />
|-<br />
| '''Summary'''<br />
| This function executes a prepared statement. The parameter {{Code|$id}} specifies a prepared statement handle. The optional parameter {{Code|$params}} is an element {{Code|<sql:parameters/>}} representing the parameters for a prepared statement along with their types and values. The following schema shall be used:<br/ ><br />
<pre class="brush:xml"><br />
element sql:parameters {<br />
element sql:parameter {<br />
attribute type { "int"|"string"|"boolean"|"date"|"double"|"float"|"short"|"time"|"timestamp" },<br />
attribute null { "true"|"false" }?,<br />
text }+ }?<br />
</pre><br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs, e.g. not existing relation is retrieved.<br/ ><br />
{{Error|BXSQ0002|XQuery Errors#SQL Functions Errors}} a wrong prepared statement handle is passed.<br/ ><br />
{{Error|BXSQ0003|XQuery Errors#SQL Functions Errors}} the number of {{Code|<sql:parameter/>}} elements in {{Code|<sql:parameters/>}} differs from the number of placeholders in the prepared statement.<br/ ><br />
{{Error|BXSQ0004|XQuery Errors#SQL Functions Errors}} the type of a parameter for a prepared statement is not specified.<br/ ><br />
{{Error|BXSQ0005|XQuery Errors#SQL Functions Errors}} an attribute different from {{Code|type}} and {{Code|null}} is set for a {{Code|<sql:parameter/>}} element.<br/ ><br />
{{Error|BXSQ0006|XQuery Errors#SQL Functions Errors}} a parameter is from type date, time or timestamp and its value is in an invalid format.<br/ ><br />
|}<br />
<br />
==sql:prepare==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:prepare|$connection as xs:integer, $statement as xs:string|xs:integer}}<br />
|-<br />
| '''Summary'''<br />
|This function prepares a statement and returns a handle to it. The parameter {{Code|$connection}} indicates the connection handle to be used. The parameter {{Code|$statement}} is a string representing an SQL statement with one or more '?' placeholders. If the value of a field has to be set to {{Code|NULL}}, then the attribute {{Code|null}} of the element {{Code|<sql:parameter/>}} has to be {{Code|true}}.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs.<br/ ><br />
{{Error|BXSQ0002|XQuery Errors#SQL Functions Errors}} a wrong connection handle is passed.<br/ ><br />
|}<br />
<br />
==sql:commit==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:commit|$connection as xs:integer|empty-sequence()}}<br />
|-<br />
| '''Summary'''<br />
| This function commits the changes made to a relational database. {{Code|$connection}} specifies the connection handle.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs.<br/ ><br />
{{Error|BXSQ0002|XQuery Errors#SQL Functions Errors}} a wrong connection handle is passed.<br/ ><br />
|}<br />
<br />
==sql:rollback==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:rollback|$connection as xs:integer|empty-sequence()}}<br />
|-<br />
| '''Summary'''<br />
| This function rolls back the changes made to a relational database. {{Code|$connection}} specifies the connection handle.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs.<br/ ><br />
{{Error|BXSQ0002|XQuery Errors#SQL Functions Errors}} a wrong connection handle is passed.<br/ ><br />
|}<br />
<br />
==sql:close==<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|sql:close|$connection as xs:integer|empty-sequence()}}<br />
|-<br />
| '''Summary'''<br />
| This function closes a connection to a relational database. {{Code|$connection}} specifies the connection handle.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXSQ0001|XQuery Errors#SQL Functions Errors}} an SQL exception occurs.<br/ ><br />
{{Error|BXSQ0002|XQuery Errors#SQL Functions Errors}} a wrong connection handle is passed.<br/ ><br />
|}<br />
<br />
=Examples=<br />
<br />
==Direct queries==<br />
A simple select statement can be executed on the following way:<br />
<br />
<pre class="brush:xquery"><br />
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")<br />
return sql:execute($conn, "SELECT * FROM coffees WHERE price < 10")<br />
</pre><br />
<br />
The result will look like:<br />
<br />
<pre class="brush:xml"><br />
<sql:row xmlns:sql="http://basex.org/modules/sql"><br />
<sql:column name="cof_name">French_Roast</sql:column><br />
<sql:column name="sup_id">49</sql:column><br />
<sql:column name="price">9.5</sql:column><br />
<sql:column name="sales">15</sql:column><br />
<sql:column name="total">30</sql:column><br />
</sql:row><br />
<sql:row xmlns:sql="http://basex.org/modules/sql"><br />
<sql:column name="cof_name">French_Roast_Decaf</sql:column><br />
<sql:column name="sup_id">49</sql:column><br />
<sql:column name="price">7.5</sql:column><br />
<sql:column name="sales">10</sql:column><br />
<sql:column name="total">14</sql:column><br />
</sql:row><br />
<sql:row xmlns:sql="http://basex.org/modules/sql"><br />
<sql:column name="cof_name">Colombian_Decaf</sql:column><br />
<sql:column name="sup_id">101</sql:column><br />
<sql:column name="price">8.75</sql:column><br />
<sql:column name="sales">6</sql:column><br />
<sql:column name="total">12</sql:column><br />
<sql:column name="date">2010-10-10 13:56:11.0</sql:column><br />
</sql:row><br />
</pre><br />
<br />
==Prepared Statements==<br />
A prepared select statement can be executed in the following way:<br />
<br />
<pre class="brush:xquery"><br />
(: Establish a connection :)<br />
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")<br />
(: Obtain a handle to a prepared statement :)<br />
let $prep := sql:prepare($conn, "SELECT * FROM coffees WHERE price < ? AND cof_name = ?")<br />
(: Values and types of prepared statement parameters :)<br />
let $params := <sql:parameters><br />
<sql:parameter type='double'>10</sql:parameter><br />
<sql:parameter type='string'>French_Roast</sql:parameter><br />
</sql:parameters><br />
(: Execute prepared statement :)<br />
return sql:execute-prepared($prep, $params)<br />
</pre><br />
<br />
==SQLite==<br />
<br />
The following expression demonstrates how SQLite can be addressed using the [http://bitbucket.org/xerial/sqlite-jdbc Xerial SQLite JDBC driver]:<br />
<br />
<pre class="brush:xquery"><br />
(: Initialize driver :)<br />
sql:init("org.sqlite.JDBC"),<br />
(: Establish a connection :)<br />
let $conn := sql:connect("jdbc:sqlite:database.db")<br />
return (<br />
(: Create a new table :)<br />
sql:execute($conn, "drop table if exists person"),<br />
sql:execute($conn, "create table person (id integer, name string)"),<br />
(: Run 10 updates :)<br />
for $i in 1 to 10<br />
let $q := "insert into person values(" || $i || ", '" || $i || "')"<br />
return sql:execute($conn, $q),<br />
(: Return table contents :)<br />
sql:execute($conn, "select * from person"),<br />
sql:close($conn)<br />
)<br />
</pre><br />
<br />
=Errors=<br />
<br />
{| class="wikitable" width="100%"<br />
! width="110"|Code<br />
|Description<br />
|-<br />
|{{Code|BXSQ0001}}<br />
|An SQL exception occurred (e.g.: a non-existing relation is retrieved).<br />
|-<br />
|{{Code|BXSQ0002}}<br />
|A wrong connection handle or prepared statement handle is passed.<br />
|-<br />
|{{Code|BXSQ0003}}<br />
|The number of {{Code|&lt;sql:parameter/&gt;}} elements in {{Code|&lt;sql:parameters/&gt;}} differs from the number of placeholders in the prepared statement.<br />
|-<br />
|{{Code|BXSQ0004}}<br />
|The type of a parameter for a prepared statement is not specified.<br />
|-<br />
|{{Code|BXSQ0005}}<br />
|An attribute different from {{Code|type}} and {{Code|null}} is set for a {{Code|&lt;sql:parameter/&gt;}} element.<br />
|-<br />
|{{Code|BXSQ0006}}<br />
|A parameter is from type date, time or timestamp and its value is in an invalid format.<br />
|-<br />
|{{Code|BXSQ0007}}<br />
|A specified database driver class is not found.<br />
|}<br />
<br />
=Changelog=<br />
<br />
;Version 7.5<br />
* Updated: prepared statements are now executed via [[#sql:execute-prepared|sql:execute-prepared]]<br />
<br />
The module was introduced with Version 7.0.<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=Java_Examples&diff=11047Java Examples2014-10-10T16:09:06Z<p>Dirk: </p>
<hr />
<div>This page is part of the [[Developer Section]].<br />
The following Java code snippets demonstrate how easy it is to run database commands, create collections, perform queries, etc. by integrating the BaseX code. Most examples are taken from our [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples basex-examples] repository, in which you will find some more use cases.<br />
<br />
<div style="float:left; width:48%;"><br />
==Local Examples==<br />
<br />
The following code snippets work in ''embedded'' mode; they do not rely on an additional server instance:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/RunCommands.java RunCommands.java]<br/>creates and drops database and index instances, prints a list of all existing databases.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/RunQueries.java RunQueries.java]<br/>shows three variants of running queries.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/BindContext.java BindContext.java]<br/>demonstrates how a value can be bound as context item.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/BindVariables.java BindVariables.java]<br/>demonstrates how a value can be bound to a variable.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/CreateCollection.java CreateCollection.java]<br/>creates and manages a collection.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/QueryCollection.java QueryCollection.java]<br/>creates, runs queries against it and drops a collection.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/WikiExample.java WikiExample.java]<br/>creates a database from an url (wiki instance), runs a query against it and drops the database.<br />
<br />
==Server Examples==<br />
<br />
The examples below take advantage of the client/server architecture:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerCommands.java ServerCommands.java]<br/>launches server-side commands using a client session.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerAndLocal.java ServerAndLocal.java]<br/>processes server results locally.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerConcurrency.java ServerConcurrency.java]<br/>runs concurrent queries.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerQueries.java ServerQueries.java]<br/>shows how iterative queries can be performed.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerEventsGUI.java ServerEventsGUI.java]<br/>is a little GUI example for demonstrating database events.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/UserExample.java UserExample.java]<br/>manages database users.<br />
<br />
==XQuery Module Examples==<br />
<br />
BaseX provides [[Java Bindings]] for accessing external Java code via XQuery functions. The following examples show how this feature can be utilized:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/FruitsExample.java FruitsExample.java]<br/>demonstrates how Java classes can be imported as XQuery modules.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/FruitsModule.java FruitsModule.java]<br/>is a simple demo module called by {{Code|FruitsExample}}.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/ModuleDemo.java ModuleDemo.java]<br/>is a simple XQuery demo module that demonstrates how XQuery items can be processed from Java. It is derived from the {{Code|QueryModule}} class.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-core/src/main/java/org/basex/query/QueryModule.java QueryModule.java]<br/>is located in the BaseX core. Java query modules can extend this class to get access to the current query context and enrich functions with properties ().<br />
<br />
</div><div style="float:left; width:4%;">&nbsp;<br />
</div><div style="float:left; width:48%;"><br />
<br />
==XQJ API==<br />
<br />
The implementation of the [http://xqj.net/basex/ BaseX XQJ API] (closed-source) has been written by Charles Foster. It uses the client/server architecture.<br />
The basex-examples repository contains [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/xqj various examples] on how to use XQJ.<br />
<br />
==[[Clients|Client API]]==<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/BaseXClient.java BaseXClient.java]<br/>provides an implementation of the [[Server Protocol]].<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/Example.java Example.java]<br/>demonstrates how commands can be executed on a server.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/QueryExample.java QueryExample.java]<br/>shows how queries can be executed in an iterative manner.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/QueryBindExample.java QueryBindExample.java]<br/>shows how external variables can be bound to XQuery expressions.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/CreateExample.java CreateExample.java]<br/>shows how new databases can be created.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/AddExample.java AddExample.java]<br/>shows how documents can be added to databases, and how existing documents can be replaced.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/EventExample.java EventExample.java]<br/>demonstrates how to trigger and receive database events.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/BinaryExample.java BinaryExample.java]<br/>shows how binary resource can be added to and retrieved from the database.<br />
<br />
==[[REST API]]==<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTGet.java RESTGet.java]<br/>presents the HTTP GET method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTPost.java RESTPost.java]<br/>presents the HTTP POST method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTPut.java RESTPut.java]<br/>presents the HTTP PUT method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTAll.java RESTAll.java]<br/>runs all examples at one go.<br />
<br />
==XML:DB API (deprecated)==<br />
<br />
Note that the XML:DB API does not talk to the server and can thus only be used in embedded mode.<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBCreate.java XMLDBCreate.java]<br/>creates a collection using XML:DB.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBQuery.java XMLDBQuery.java]<br/>runs a query using XML:DB.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBInsert.java XMLDBInsert.java]<br/>inserts a document into a database using XML:DB.<br />
</div><br />
<br />
[[Category:Developer]]<br />
__NOTOC__</div>Dirkhttps://docs.basex.org/index.php?title=Java_Examples&diff=11046Java Examples2014-10-10T16:08:34Z<p>Dirk: </p>
<hr />
<div>This page is part of the [[Developer Section]].<br />
The following Java code snippets demonstrate how easy it is to run database commands, create collections, perform queries, etc. by integrating the BaseX code. Most examples are taken from our [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples basex-examples] repository, in which you will find some more use cases.<br />
<br />
<div style="float:left; width:48%;"><br />
==Local Examples==<br />
<br />
The following code snippets work in ''embedded'' mode; they do not rely on an additional server instance:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/RunCommands.java RunCommands.java]<br/>creates and drops database and index instances, prints a list of all existing databases.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/RunQueries.java RunQueries.java]<br/>shows three variants of running queries.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/BindContext.java BindContext.java]<br/>demonstrates how a value can be bound as context item.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/BindVariables.java BindVariables.java]<br/>demonstrates how a value can be bound to a variable.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/CreateCollection.java CreateCollection.java]<br/>creates and manages a collection.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/QueryCollection.java QueryCollection.java]<br/>creates, runs queries against it and drops a collection.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/WikiExample.java WikiExample.java]<br/>creates a database from an url (wiki instance), runs a query against it and drops the database.<br />
<br />
==Server Examples==<br />
<br />
The examples below take advantage of the client/server architecture:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerCommands.java ServerCommands.java]<br/>launches server-side commands using a client session.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerAndLocal.java ServerAndLocal.java]<br/>processes server results locally.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerConcurrency.java ServerConcurrency.java]<br/>runs concurrent queries.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerQueries.java ServerQueries.java]<br/>shows how iterative queries can be performed.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerEventsGUI.java ServerEventsGUI.java]<br/>is a little GUI example for demonstrating database events.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/UserExample.java UserExample.java]<br/>manages database users.<br />
<br />
==XQuery Module Examples==<br />
<br />
BaseX provides [[Java Bindings]] for accessing external Java code via XQuery functions. The following examples show how this feature can be utilized:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/FruitsExample.java FruitsExample.java]<br/>demonstrates how Java classes can be imported as XQuery modules.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/FruitsModule.java FruitsModule.java]<br/>is a simple demo module called by {{Code|FruitsExample}}.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/ModuleDemo.java ModuleDemo.java]<br/>is a simple XQuery demo module that demonstrates how XQuery items can be processed from Java. It is derived from the {{Code|QueryModule}} class.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-core/src/main/java/org/basex/query/QueryModule.java]<br/>is located in the BaseX core. Java query modules can extend this class to get access to the current query context and enrich functions with properties ().<br />
<br />
</div><div style="float:left; width:4%;">&nbsp;<br />
</div><div style="float:left; width:48%;"><br />
<br />
==XQJ API==<br />
<br />
The implementation of the [http://xqj.net/basex/ BaseX XQJ API] (closed-source) has been written by Charles Foster. It uses the client/server architecture.<br />
The basex-examples repository contains [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/xqj various examples] on how to use XQJ.<br />
<br />
==[[Clients|Client API]]==<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/BaseXClient.java BaseXClient.java]<br/>provides an implementation of the [[Server Protocol]].<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/Example.java Example.java]<br/>demonstrates how commands can be executed on a server.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/QueryExample.java QueryExample.java]<br/>shows how queries can be executed in an iterative manner.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/QueryBindExample.java QueryBindExample.java]<br/>shows how external variables can be bound to XQuery expressions.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/CreateExample.java CreateExample.java]<br/>shows how new databases can be created.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/AddExample.java AddExample.java]<br/>shows how documents can be added to databases, and how existing documents can be replaced.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/EventExample.java EventExample.java]<br/>demonstrates how to trigger and receive database events.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/BinaryExample.java BinaryExample.java]<br/>shows how binary resource can be added to and retrieved from the database.<br />
<br />
==[[REST API]]==<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTGet.java RESTGet.java]<br/>presents the HTTP GET method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTPost.java RESTPost.java]<br/>presents the HTTP POST method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTPut.java RESTPut.java]<br/>presents the HTTP PUT method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTAll.java RESTAll.java]<br/>runs all examples at one go.<br />
<br />
==XML:DB API (deprecated)==<br />
<br />
Note that the XML:DB API does not talk to the server and can thus only be used in embedded mode.<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBCreate.java XMLDBCreate.java]<br/>creates a collection using XML:DB.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBQuery.java XMLDBQuery.java]<br/>runs a query using XML:DB.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBInsert.java XMLDBInsert.java]<br/>inserts a document into a database using XML:DB.<br />
</div><br />
<br />
[[Category:Developer]]<br />
__NOTOC__</div>Dirkhttps://docs.basex.org/index.php?title=Git&diff=11042Git2014-09-29T09:13:14Z<p>Dirk: added a short tutorial how to push a new feature</p>
<hr />
<div>This page is part of the [[Developer Section]]. It describes how to use [http://git-scm.com/ git] to manage the BaseX sources.<br />
<br />
==Using Git to contribute to BaseX ==<br />
<br />
Our team uses git and [https://github.com GitHub] to manage the source code.<br />
All team members have read+write access to the repository, and external<br />
contributors are welcome to fork the project. <br />
<br />
Git makes it easy to retain a full copy of the repository for yourself.<br />
To get started and running, simply ''fork'' BaseX:<br />
<br />
# Head over to https://github.com and create an account<br />
# Fork https://github.com/BaseXdb/basex, so you have a version on your own<br />
# The forked project can then be cloned on your local machine, and changes can be pushed back to your remote repository<br />
# Open Eclipse<br />
# Install egit (Eclipse: ''Help'' → ''Marketplace'' → Search for ''egit'' '''or''' get it from http://www.eclipse.org/egit/)<br />
<br />
==Using Git & Eclipse==<br />
<br />
To clone the project from within Eclipse, you may need to install EGit first (Eclipse: ''Help'' → ''Marketplace'' → Search for ''egit'' '''or''' get it from http://www.eclipse.org/egit/).<br />
<br />
<table cellspacing='0' cellpadding='0' width='100%'><br />
<tr><td valign='top'><br />
[[File:Git01.png|border|300px|left]]<br />
[[File:Git02.png|border|300px|left]]<br />
[[File:Git03.png|border|300px|left]]<br />
[[File:Git04.png|border|300px|left]]<br />
[[File:Git05.png|border|300px|left]]<br />
[[File:Git06.png|border|300px|left]]<br />
[[File:Git07.png|border|300px|left]]<br />
[[File:Git08.png|border|300px|left]]<br />
[[File:Git09.png|border|300px|left]]<br />
[[File:Git10.png|border|300px|left]] <br />
</td><td valign='top'><br />
<br />
===Clone===<br />
<br />
* In the '''Package Explorer''' to the left use right-click and choose Import...<br />
* Select "'''Projects from Git'''" and click Next &gt;<br />
* Click "'''Clone...'''" to create a local copy of the remote repository. This copy will include the full project history<br />
* Copy & Paste the GitHub URI in the Location field. If you want to use SSH make sure you provided GitHub with your public key to allow write-access. If in doubt use the HTTPS URI and authenticate yourself with your GitHub credentials. The read-only URI of the repository is {{Code|https://github.com/BaseXdb/basex.git}}.<br />
* Select the master branch (or arbitrary branches you like) <br />
* Now choose a location where the local repository is stored: Create &lt;workspace&gt;'''/repos/BaseX''' and click "'''Finish'''". <br />
<br />
===Create the project ===<br />
<br />
* Select our newly cloned repository and click Next<br />
* Select "'''Import Existing Projects'''" and depending on your Eclipse version enable automatic sharing. More recent versions will not offer this feature as sharing is enabled by default.<br />
* Click next to select the Project to import<br />
* Check "basex" to checkout and click finish<br />
* You are now ready to contribute. <br />
<br />
===EGit & SSH===<br />
<br />
EGit uses the [http://www.jcraft.com/jsch JSch] library which is, however, [https://bugs.eclipse.org/bugs/show_bug.cgi?id=326526 reported] to have problems with RSA SSH keys in linux and possibly other platforms. A solution would be to use the variable GIT_SSH and assign it a path to the native SSH executable. According to [http://egit.eclipse.org/r/#change,2037 this] change in EGit, the plugin will try to use a native SSH implementation instead of JSch (this, however, may not always work either :( ).<br />
<br />
==Using Git on Command-Line==<br />
<br />
'''Note''': this is not intended to be a complete git reference; it's purpose is to quickly introduce BaseX developers to the most commonly used git commands in the context of the BaseX project.<br />
<br />
===Preparation===<br />
<br />
# Create a GitHub user account: [https://github.com/signup/free here] (your github user name will be referenced as $username)<br />
# Set up SSH access to GitHub as described [http://help.github.com/key-setup-redirect here]<br />
# Create a fork of one of the BaseXdb projects (it will be referenced as $project)<br />
# Choose a directory where the project will be created and make it your working directory (e. g. /home/user/myprojects)<br />
<br />
===Clone Your Personal Repository===<br />
<br />
<pre class="brush:shell"><br />
$ git clone git@github.com:$username/$project.git<br />
Cloning into $project...<br />
Enter passphrase for key '/home/user/.ssh/id_rsa': <br />
...<br />
<br />
$ ls -d -1 $PWD/*<br />
/home/user/myprojects/$project<br />
</pre><br />
Note that git automatically creates a directory where the repository content will be checked out.<br />
<br />
===List Remote Repositories===<br />
<br />
<pre class="brush:shell"><br />
$ git remote -v<br />
origin git@github.com:$username/$project.git (fetch)<br />
origin git@github.com:$username/$project.git (push)<br />
</pre><br />
Currently, there is only one remote repository; it is automatically registered during the clone operation. Git remembers this repository as the default repository for push/pull operations.<br />
<br />
===List Local Changes===<br />
<br />
After some files have been changed locally, the changes can be seen as follows:<br />
<pre class="brush:shell"><br />
$ git diff<br />
diff --git a/readme.txt b/readme.txt<br />
index fabaeaa..cd09568 100644<br />
--- a/readme.txt<br />
+++ b/readme.txt<br />
@@ -49,6 +49,10 @@ ADDING CHECKSTYLE --------------------------------------------------------------<br />
- Enter the URL: http://eclipse-cs.sourceforge.net/update<br />
- Follow the installation procedure and restart Eclipse<br />
<br />
+USING GIT ----------------------------------------------------------------------<br />
<br />
Any kind of feedback is welcome; please check out the online documentation at<br />
</pre><br />
<br />
===Commit to Local Repository===<br />
<br />
'''Note''': this commit operation does '''not''' commit into the remote repository!<br />
<br />
First, it is needed to select the modified files which should be committed:<br />
<pre class="brush:shell"><br />
$ git add readme.txt<br />
</pre><br />
<br />
Then perform the actual commit:<br />
<pre class="brush:shell"><br />
$ git commit<br />
[master 0fde1fb] Added TODO in section "USING GIT"<br />
1 files changed, 4 insertions(+), 0 deletions(-)<br />
</pre><br />
Before executing the actual commit, git will open the default shell editor (determined using the $EDITOR variable, usually vi) to enter a message describing the commit changes.<br />
<br />
Alternative way is to commit all changed files, i. e. it is not needed to explicitly add the changed files:<br />
<pre class="brush:shell"><br />
$ git commit -a<br />
[master 0fde1fb] Added TODO in section "USING GIT"<br />
1 files changed, 4 insertions(+), 0 deletions(-)<br />
</pre><br />
<br />
===Pushing Local Changes to Remote Repository===<br />
<br />
<pre class="brush:shell"><br />
$ git push<br />
Enter passphrase for key '/home/user/.ssh/id_rsa': <br />
Everything up-to-date<br />
</pre><br />
<br />
===Pulling Changes from Remote Repository===<br />
<br />
<pre class="brush:shell"><br />
$ git pull<br />
Enter passphrase for key '/home/user/.ssh/id_rsa': <br />
Already up-to-date.<br />
</pre><br />
<br />
===Add BaseXdb Upstream Repository===<br />
<br />
The upstream repository is the one from which the BaseX releases are made and the one from which the personal repository was forked.<br />
<br />
<pre class="brush:shell"><br />
$ git remote add upstream git@github.com:BaseXdb/$project.git<br />
<br />
$ git remote -v<br />
origin git@github.com:$username/$project.git (fetch)<br />
origin git@github.com:$username/$project.git (push)<br />
upstream git@github.com:BaseXdb/$project.git (fetch)<br />
upstream git@github.com:BaseXdb/$project.git (push)<br />
</pre><br />
<br />
===Pulling Changes from Upstream to Local Repository===<br />
<br />
When some changes are made in the upstream repository, they can be pulled to the local repository as follows:<br />
<br />
<pre class="brush:shell"><br />
$ git pull upstream master<br />
Enter passphrase for key '/home/user/.ssh/id_rsa': <br />
From github.com:BaseXdb/$project<br />
* branch master -> FETCH_HEAD<br />
Already up-to-date.<br />
</pre><br />
<br />
The changes can then be pushed in the personal repository:<br />
<pre class="brush:shell"><br />
$ git push<br />
</pre><br />
<br />
Check out the links at the end of the page for more git options.<br />
</td></tr></table><br />
<br />
===Developing a new feature or bug fix using git===<br />
<br />
It is always a good idea to create a new branch for a new feature or a big fix you are working on. So first, let's make sure you have the most up-to-date source code. We assume, that you added BaseX as upstream repository as described above and you are currently in the ''master'' branch:<br />
<br />
<pre class="brush:shell"><br />
$ git pull upstream master<br />
</pre><br />
<br />
Now, we create a new branch, based on the master branch<br />
<br />
<pre class="brush:shell"><br />
$ git checkout -b new-feature<br />
Switched to a new branch 'new-feature'<br />
</pre><br />
<br />
Your are now automatically switched to the ''new-feature'' branch. Now you can make all your changes in one or several commits. You can commit all changes using<br />
<br />
<pre class="brush:shell"><br />
$ git commit -a<br />
</pre><br />
<br />
Now, you want to push these changes to the repository on GitHub. Remember, that up to now your changes just reside on your local drive, so now you want to push it to your remote fork of BaseX. Simply do:<br />
<br />
<pre class="brush:shell"><br />
$ git push origin new-featuCounting objects: 318, done.<br />
Delta compression using up to 4 threads.<br />
Compressing objects: 100% (107/107), done.<br />
Writing objects: 100% (154/154), 22.96 KiB | 0 bytes/s, done.<br />
Total 154 (delta 93), reused 81 (delta 26)<br />
To git@github.com:$username/basex.git<br />
* [new branch] new-feature -> new-featurere<br />
</pre><br />
<br />
You can now use your web browser and go to your fork of BaseX. You will see the following message:<br />
<br />
[[File:Git11.png]]<br />
<br />
You can now click the "Compare & pull request" button. You can now review the changes you are going to push. <br />
<br />
'''Please review them carefully. Also, please give a meaningful comment so we can quickly determine what your changes are doing.''' After clicking the "Create Pull request" button you are done and we will review your changes and either merge the pull request or get back to you.<br />
<br />
<br />
==Need help using git?==<br />
<br />
===Installing===<br />
<br />
For information on how to install git on various platforms please refer to: [http://help.github.com/git-installation-redirect/ GitHub: git Installation Guide]<br />
<br />
===Documentation===<br />
<br />
* [http://help.github.com/ Comprehensive Getting Starting Guide on GitHub]<br />
* [http://book.git-scm.com/index.html The git book]<br />
* [http://gitcasts.com/ Gitcasts.com – Video Guides]</div>Dirkhttps://docs.basex.org/index.php?title=File:Git11.png&diff=11041File:Git11.png2014-09-29T09:10:39Z<p>Dirk: </p>
<hr />
<div></div>Dirkhttps://docs.basex.org/index.php?title=Options&diff=10569Options2014-04-11T10:33:04Z<p>Dirk: STRIPNS added</p>
<hr />
<div>This page is linked from the [[Getting Started]] Section.<br />
<br />
The options listed on this page influence the way how database [[Commands|commands]] are executed and XQuery expressions are evaluated. Options are divided into [[#Global Options|'''global options''']], which are valid for all BaseX instances, and '''local options''', which are specific to a client or session. Values of options are either ''strings'', ''numbers'' or ''booleans''.<br />
<br />
The {{Code|.basex}} [[Configuration#Configuration Files|configuration file]] is parsed by every new local BaseX instance. It contains all global options and, optionally, local options at the end of the file.<br />
<br />
Various ways exist to access and change options:<br />
<br />
* The current value of an option can be requested with the [[Commands#GET|GET]] and changed with the [[Commands#SET|SET]] command. All values are ''static'': they stay valid until they are changed once again by another operation. If an option is of type ''boolean'', and if no value is specified, its existing value will be inverted.<br />
<br />
* Initial values for options can also be specified via system properties, which can e.g. be passed on with the [http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#options -D flag] on command line, or using [http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#setProperty(java.lang.String,%20java.lang.String) System.setProperty()] before creating a BaseX instance. The specified keys needs to be prefixed with {{Code|org.basex.}}. An example:<br />
<br />
<pre class="brush:bash"><br />
java -Dorg.basex.CHOP=false -cp basex.jar org.basex.BaseX -c"get chop"<br />
CHOP: false<br />
</pre><br />
<br />
* Options can also be set in the prolog of an XQuery expression. 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:<br />
<br />
<pre class="brush:xquery"><br />
declare option db:chop 'false';<br />
...<br />
</pre><br />
<br />
* Options can also be applied locally by using pragmas:<br />
<br />
<pre class="brush:xquery"><br />
(# db:chop false #) { parse-xml('<xml> hi </xml>') }<br />
</pre><br />
<br />
If options are implicitly changed by operations in the [[GUI]], the underlying commands will be listed in the [[GUI#Visualizations|Info View]].<br/><br/><br />
<br />
=Global Options=<br />
<br />
Global options are constants. They can only be set in the configuration file or via system properties (see above). One exception (since {{Version|7.8}}) is the [[#debug|DEBUG]] option, which can also be changed at runtime by users with [[User Management|admin permissions]].<br />
<br />
==General==<br />
<br />
===DEBUG===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DEBUG [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Sends internal debug info to STDERR. This option can be turned on to get additional information for development and debugging purposes. It can also be triggered on [[Command-Line Options#BaseX Standalone|command line]] via <code>-d</code>.<br />
|}<br />
<br />
===DBPATH===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DBPATH [path]}}<br />
|-<br />
| '''Default'''<br />
|<code>[[Configuration#Database Directory|{home}/BaseXData]]</code> or <code>[[Configuration#Database Directory|{home}/data]]</code><br />
|-<br />
| '''Summary'''<br />
|Points to the directory in which all databases are located.<br />
|}<br />
<br />
===REPOPATH===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|REPOPATH [path]}}<br />
|-<br />
| '''Default'''<br />
|<code>[[Configuration#Database Directory|{home}/BaseXRepo]]</code><br />
|-<br />
| '''Summary'''<br />
|Points to the [[Repository]], in which all XQuery modules are located.<br />
|}<br />
<br />
===LANG===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|LANG [language]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|English}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the interface language. Currently, seven languages are available: 'English', 'German', 'French', 'Dutch', 'Italian', 'Japanese', and 'Vietnamese'.<br />
|}<br />
<br />
===LANGKEY===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|LANGKEY [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Prefixes all texts with the internal language keys. This option is helpful if BaseX is translated into another language, and if you want to see where particular texts are displayed.<br />
|}<br />
<br />
===GLOBALLOCK===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|GLOBALLOCK [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Controls if local (database) or global (process) locking will be used for managing read and write operations. The article on [[Transaction Management]] provides more details on concurrency control.<br />
|}<br />
<br />
==Client/Server Architecture==<br />
<br />
===HOST===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|HOST [host]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|localhost}}<br />
|-<br />
| '''Summary'''<br />
|This host name is used by the client when connecting to a server. This option can also be changed when running the client on [[Command-Line Options#BaseX Client|command line]] via <code>-n</code>.<br />
|}<br />
<br />
===PORT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|PORT [port]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|1984}}<br />
|-<br />
| '''Summary'''<br />
|This port is used by the client when connecting to a server. This option can also be changed when running the client on [[Command-Line Options#BaseX Client|command line]] via <code>-p</code>.<br />
|}<br />
<br />
===SERVERPORT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|SERVERPORT [port]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|1984}}<br />
|-<br />
| '''Summary'''<br />
|This is the port the database server will be listening to. This option can also be changed when running the server on [[Command-Line Options#BaseX Server|command line]] via <code>-p</code>.<br />
|}<br />
<br />
===EVENTPORT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|EVENTPORT [port]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|1985}}<br />
|-<br />
| '''Summary'''<br />
|This port is used by the client to listen for [[Events|server events]]. It will only be bound if a client attaches itself to a database event. This option can also be changed when running the server on [[Command-Line Options#BaseX Server|command line]] via <code>-e</code>.<br />
|}<br />
<br />
===USER===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|USER [name]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Represents a user name, which is used for accessing the server or an HTTP service:<br />
* The default value will be overwritten if a client specifies its own credentials.<br />
* If the default value is empty, login will only be possible if the client specifies credentials.<br />
* The option can also be changed on [[Command-Line Options#BaseX Client|command line]] via <code>-U</code>.<br />
|}<br />
<br />
===PASSWORD===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|PASSWORD [password]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Represents a password, which is used for accessing the server or an HTTP service:<br />
* The default value will be overwritten if a client specifies its own credentials.<br />
* If the default value is empty, login will only be possible if the client specifies credentials.<br />
* The option can also be changed on [[Command-Line Options#BaseX Client|command line]] via <code>-P</code>.<br />
* Please note that it is a security risk to specify your password in plain text.<br />
|}<br />
<br />
===SERVERHOST===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|SERVERHOST [host&#x7c;ip]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|This is the host name or ip address the server is bound to. If the option is set to an empty string (which is the default), the server will be open to all clients.<br />
|}<br />
<br />
===PROXYHOST===<br />
{| width='100%' width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|PROXYHOST [host]}}<br />
|-<br />
| '''Default'''<br />
|''empty'' <br />
|-<br />
| '''Summary'''<br />
|This is the host name of a proxy server.<br />
|}<br />
<br />
===PROXYPORT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|PROXYPORT [port]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|80}}<br />
|-<br />
| '''Summary'''<br />
|This is the port number of a proxy server.<br />
|}<br />
<br />
===NONPROXYHOSTS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|NONPROXYHOSTS [hosts]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|This is a list of hosts that should be directly accessed.<br />
|}<br />
<br />
===TIMEOUT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|TIMEOUT [seconds]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|30}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum time a read-only transaction may take. If an operation takes longer than the specified timeout, it will be aborted. Write operations will not be affected by this timeout, as this would corrupt the integrity of the database. The timeout is deactivated if the timeout is set to {{Code|0}}. It is ignored for {{Code|ADMIN}} operations.<br />
|}<br />
<br />
===KEEPALIVE===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|KEEPALIVE [seconds]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|600}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum time a client will be remembered by the server. If there has been no interaction with a client for a longer time than specified by this timeout, it will be disconnected. Running operations will not be affected by this option. The keepalive check is deactivated if the value is set to {{Code|0}}.<br />
|}<br />
<br />
===PARALLEL===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|PARALLEL [number]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|8}}<br />
|-<br />
| '''Summary'''<br />
|Denotes the maximum allowed {{Code|number}} of parallel [[Transaction Management|transactions]].<br/>Note that a higher number of parallel operations may increase disk activity and thus slow down queries. In some cases, a single transaction may even give you better results than any parallel activity.<br />
|}<br />
<br />
===LOG===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|LOG [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Turns [[Logging]] of server operations and HTTP requests on/off. This option can also be changed when running the server on [[Command-Line Options#BaseX Server|command line]] via <code>-z</code>.<br />
|}<br />
<br />
===LOGMSGMAXLEN===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|LOGMSGMAXLEN [length]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|1000}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum length of a single [[Logging|log message]].<br />
|}<br />
<br />
==HTTP Options==<br />
<br />
If BaseX is run as [[Web Application]], the HTTP options are either determined by the web server, or specified in the <code>[https://github.com/BaseXdb/basex-api/tree/master/src/main/webapp/WEB-INF webapp/WEB-INF]</code> directory and the {{Code|jetty.xml}} and {{Code|web.xml}} configuration files.<br />
<br />
===WEBPATH===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|WEBPATH [path]}}<br />
|-<br />
| '''Default'''<br />
|<code>[[Configuration#Database Directory|{home}/BaseXWeb]]</code> or <code>[[Configuration#Database Directory|{home}/webapp]]</code><br />
|-<br />
| '''Summary'''<br />
|Points to the directory in which all the [[Web Application]] contents are stored, including XQuery, Script, [[RESTXQ]] and configuration files.<br />
|}<br />
<br />
===RESTXQPATH===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|RESTXQPATH [path]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Points to the directory which contains the [[RESTXQ]] modules of a web application. Relative paths will be resolved against the [[#WEBPATH|WEBPATH]] directory.<br />
|}<br />
<br />
===HTTPLOCAL===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|HTTPLOCAL [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|By default, a database server instance will be opened along with the web server. If the flag is set to {{Code|true}}, all commands will be executed in an embedded database context.<br/>If BaseX is run as [[Web Application]], and if the flag is {{Code|false}}, the server will be started as soon as the first HTTP service is called.<br />
|}<br />
<br />
===STOPPORT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|STOPPORT [port]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|8985}}<br />
|-<br />
| '''Summary'''<br />
|This is the port on which the [[Startup#BaseX HTTP Server|HTTP Server]] can be locally closed:<br />
* The listener for stopping the web server will only be started if the specified value is greater than {{Code|0}}.<br />
* The option is ignored if BaseX is used as a [[Web Application]] or started via [[Web Application#Maven|Maven]].<br />
* This option can also be changed when running the HTTP server on [[Command-Line Options#BaseX Server|command line]] via <code>-s</code>.<br />
|}<br />
<br />
=Create Options=<br />
<br />
==General==<br />
<br />
===MAINMEM===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|MAINMEM [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|If this option is turned on, new databases will be exclusively created in main memory. Most queries will be evaluated faster in main memory mode, but all data is lost if BaseX is shut down. The value of this option will be assigned once to a new database, and cannot be changed after that.<br />
|}<br />
<br />
===ADDCACHE===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|ADDCACHE [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|If this option is activated, documents that are added via [[Commands#ADD|ADD]] will first be cached to disk before being added to the final database. This option is helpful when larger documents are to be imported, and if the existing heuristics cannot estimate the size of the input (e.g. when adding directories).<br />
|}<br />
<br />
==Parsing==<br />
<br />
===CREATEFILTER===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CREATEFILTER [filter]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|*.xml}}<br />
|-<br />
| '''Summary'''<br />
|File filter in the [[Commands#Glob Syntax|Glob Syntax]], which is applied whenever new databases are created, or resources are added to a database.<br />
|}<br />
<br />
===ADDARCHIVES===<br />
<br />
* Since {{Version|7.8.1}}, also TAR and TGZ files will be parsed.<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|ADDARCHIVES [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|If this option is set to {{Code|true}}, files within archives (ZIP, GZIP, TAR, TGZ, DOCX, etc.) are parsed whenever new database are created or resources are added to a database.<br />
|}<br />
<br />
===SKIPCORRUPT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|SKIPCORRUPT [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Skips corrupt (i.e., not well-formed) files while creating a database or adding new documents. If this option is activated, document updates are slowed down, as all files will be parsed twice. Next, main memory consumption will be higher as parsed files will be cached in main memory.<br />
|}<br />
<br />
===ADDRAW===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|ADDRAW [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|If this option is activated, and if new resources are added to a database, all files that are not filtered by the [[#CREATEFILTER|CREATEFILTER]] option will be added as ''raw'' files (i.e., in their binary representation).<br />
|}<br />
<br />
===PARSER===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|PARSER [type]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|XML}}<br />
|-<br />
| '''Summary'''<br />
|Defines a [[Parsers|parser]] for importing new files to the database. Currently, 'XML', 'JSON', 'CSV', 'TEXT', 'HTML' are available as parsers. HTML will be parsed as normal XML files if [http://home.ccil.org/~cowan/XML/tagsoup/ Tagsoup] is not found in the classpath.<br />
|}<br />
<br />
===CSVPARSER===<br />
<br />
Introduced with {{Mark|Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CSVPARSER [options]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Specifies the way how CSV data is to be parsed. The available options are listed in the [[CSV Module#Options|CSV Module]].<br />
|}<br />
<br />
===JSONPARSER===<br />
<br />
Introduced with {{Mark|Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|JSONPARSER [options]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Specifies the way how JSON data is to be parsed. The available options are listed in the [[JSON Module#Options|JSON Module]].<br />
|}<br />
<br />
===TEXTPARSER===<br />
<br />
Introduced with {{Mark|Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|TEXTPARSER [options]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Specifies the way how TEXT data is to be parsed. Available options are listed in the article on [[Parsers]].<br />
|}<br />
<br />
==XML Parsing==<br />
<br />
===CHOP===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CHOP [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Many XML documents include whitespaces that have been added to improve readability. The {{Code|CHOP}} option controls the [http://www.w3.org/TR/REC-xml/#sec-white-space white-space processing mode] of the XML parser:<br />
* By default, this option is set to {{Code|true}}. This way, leading and trailing whitespaces from text nodes will be chopped and all empty text nodes will be discarded.<br />
* The flag should be turned off if a document contains [[Full-Text#Mixed Content|mixed content]].<br />
* The flag can also be turned off on [[Command-Line Options#BaseX Standalone|command line]] via <code>-w</code>.<br />
* If the <code>xml:space="preserve"</code> attribute is attached to an element, chopping will be turned of for all descendant text nodes. In the following example document, the whitespaces in the text nodes of the {{Code|text}} element will not be chopped:<br />
<pre class="brush:xml"><br />
<xml><br />
<title><br />
Demonstrating the CHOP flag<br />
</title><br />
<text xml:space="preserve">To <b>be</b>, or not to <b>be</b>, that is the question.</text><br />
</xml><br />
</pre><br />
|}<br />
<br />
===STRIPNS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|STRIPNS [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Strips all namespaces from an XML document and all elements while parsing.<br />
|}<br />
<br />
===INTPARSE===<br />
<br />
{{Mark|Updated with Version 7.8}}: default is now {{Code|false}}.<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|INTPARSE [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Uses the internal XML parser instead of the standard Java XML parser. The internal parser is faster, more fault tolerant and supports common HTML entities out-of-the-box, but it does not support all features needed for parsing DTDs.<br />
|}<br />
<br />
===DTD===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DTD [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Parses referenced DTDs and resolves XML entities. By default, this option is switched to {{Code|false}}, as many DTDs are located externally, which may completely block the process of creating new databases. The [[#CATFILE|CATFILE]] option can be changed to locally resolve DTDs.<br />
|}<br />
<br />
===CATFILE===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CATFILE [path]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Specifies a catalog file to locally resolve DTDs; see the entry on [[Catalog Resolver]]s for more details.<br />
|}<br />
<br />
==Indexing==<br />
<br />
The current index and full-text index options will be stored in a new database, and take effect if indexes are rebuilt via the [[Commands#OPTIMIZE|OPTIMIZE]].<br />
<br />
===TEXTINDEX===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|TEXTINDEX [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Creates a text index whenever a new database is created. A text index speeds up queries with equality comparisons on text nodes; see [[Indexes]] for more details.<br />
|}<br />
<br />
===ATTRINDEX===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|ATTRINDEX [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Creates an attribute index whenever a new database is created. An attribute index speeds up queries with equality comparisons on attribute values; see [[Indexes]] for more details.<br />
|}<br />
<br />
===FTINDEX===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|FTINDEX [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Creates a full-text index whenever a new database is created. A full-text index speeds up queries with full-text expressions; see [[Indexes]] for more details.<br />
|}<br />
<br />
===MAXLEN===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|MAXLEN [int]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|96}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum length of strings that are to be indexed by the name, path, value, and full-text index structures. The value of this option will be assigned once to a new database, and cannot be changed after that.<br />
|}<br />
<br />
===MAXCATS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|MAXCATS [int]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|100}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum number of distinct values (categories) that will be stored together with the element/attribute names or unique paths in the [[Index#Name Index|Name Index]] or [[Index#Path Index|Path Index]]. The value of this option will be assigned once to a new database, and cannot be changed after that.<br />
|}<br />
<br />
===UPDINDEX===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|UPDINDEX [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|If turned on, incremental indexing will be activated:<br />
* with each update, the text and attribute value indexes will be updated as well.<br />
* The value of this option will be assigned once to a new database, and cannot be changed after that.<br />
* The advantage of incremental indexes is that the value index structures will always be up-to-date.<br />
* The downside is that updates will take longer. The article on [[Index#Updates|Index Structures]] includes additional details.<br />
|}<br />
<br />
===INDEXSPLITSIZE===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|INDEXSPLITSIZE [num]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|0}}<br />
|-<br />
| '''Summary'''<br />
|This option affects the [[Indexes#Index Construction|construction]] of new text and attribute indexes. It specifies the number of index build operations that are performed before writing partial index data to disk. By default, if the value is set to 0, some dynamic split heuristics are applied.<br />
|}<br />
<br />
===FTINDEXSPLITSIZE===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|FTINDEXSPLITSIZE [num]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|0}}<br />
|-<br />
| '''Summary'''<br />
|This option affects the [[Indexes#Index Construction|construction]] of new full-text indexes. It specifies the number of index build operations that are performed before writing partial index data to disk. By default, if the value is set to 0, some dynamic split heuristics are applied.<br />
|}<br />
<br />
==Full-Text==<br />
<br />
===STEMMING===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|STEMMING [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|A new full-text index will stem all tokens and speed up queries on stemmed tokens. The same stemming normalization will be applied to all query tokens that are checked against tokens in this index.<br />
|}<br />
<br />
===CASESENS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CASESENS [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|A new full-text index will preserve the case of all tokens. The same case normalization will be applied to all query tokens that are checked against tokens in this index.<br />
|}<br />
<br />
===DIACRITICS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DIACRITICS [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|A new full-text index will preserve the diacritics of all tokens. The same diacritics normalization will be applied to all query tokens that are checked against tokens in this index.<br />
|}<br />
<br />
===LANGUAGE===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|LANGUAGE [lang]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|en}}<br />
|-<br />
| '''Summary'''<br />
|A new full-text index will use the given language to normalize all tokens. This option is mainly important if tokens are to be stemmed, or if the tokenization of a language differs from Western languages.<br />
|}<br />
<br />
===STOPWORDS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|STOPWORDS [path]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|A new full-text index will drop tokens that are listed in the specified stopword list. A stopword list may decrease the size of the full text index. A standard stopword list for English texts is provided in the directory {{Code|etc/stopwords.txt}} in the official releases.<br />
|}<br />
<br />
=Query Options=<br />
<br />
===QUERYINFO===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|QUERYINFO [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Prints more information on internal query rewritings, optimizations, and performance. By default, this info is shown in the [[GUI#Visualizations|Info View]] in the GUI. It can also be activated on [[Command-Line Options#BaseX Standalone|command line]] via <code>-V</code>. <br />
|}<br />
<br />
===XQUERY3===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|XQUERY3}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Enables all [[XQuery 3.0]] features supported by BaseX. If this option is set to {{Code|false}}, the XQuery parser will only accept expressions of the XQuery 1.0 specification.<br />
|}<br />
<br />
===MIXUPDATES===<br />
<br />
{{Mark|Added with Version 8.0:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|MIXUPDATES}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Allows queries to both contain updating and non-updating expressions. All updating constraints will be turned off, and nodes to be returned will be copied before they are modified by an updating expression. – By default, this option is set to {{Code|false}}, because the XQuery Update Facility does not allow to [[XQuery Update#Returning Results|return results]].<br />
|}<br />
<br />
===BINDINGS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|BINDINGS [vars]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Contains external variables to be bound to a query:<br />
* Variable names and values are separated by equality signs, and multiple variables are delimited by commas.<br />
* Variables may optionally be introduced with a leading dollar sign.<br />
* Commas that occur in the value itself are encoded by duplication.<br />
* If a variable uses a namespace different to the default namespace, it can be specified with the [http://www.jclark.com/xml/xmlns.htm Clark Notation] or [http://www.w3.org/TR/xquery-30/#id-basics Expanded QName Notation].<br />
* This option can also be used on [[Command-Line Options#BaseX Standalone|command line]] with the flag <code>-b</code>.<br />
|-<br />
| '''Examples'''<br />
|<code>$a=1,$b=2</code> &nbsp; binds the values {{Code|1}} and {{Code|2}} to the variables $a and $b<br/> <code>a=1,,2</code> &nbsp; binds the value {{Code|1,2}} to the variable $a<br/> <code>{URI}a=x</code> &nbsp; binds the value {{Code|x}} to the variable $a with the namespace {{Code|URI}}. <pre class="brush:xml"><br />
SET BINDINGS BIND-VAR="hello world!"<br />
XQUERY declare variable $BIND-VAR external; $BIND-VAR<br />
</pre> &nbsp; binds the value {{Code|hello world!}} to the variable $BIND-VAR and shows how it can be used in a [[Commands#Command_Scripts| Command Script]].<br />
<br />
|}<br />
<br />
===QUERYPATH===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|QUERYPATH [path]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Contains the path (''base URI'') to the executed query (default: ''empty''). This directory will be used to resolve relative paths to documents, query modules, and other resources addressed in a query.<br />
|}<br />
<br />
===INLINELIMIT===<br />
<br />
{{Mark|Introduced with Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|INLINELIMIT}}<br />
|-<br />
| '''Default'''<br />
|{{Code|100}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum size the body of a function may have in order to be inlined. Function inlining can be turned off by setting this value to {{Code|-1}}.<br />
|}<br />
<br />
===TAILCALLS===<br />
<br />
{{Mark|Introduced with Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|TAILCALLS}}<br />
|-<br />
| '''Default'''<br />
|{{Code|256}}<br />
|-<br />
| '''Summary'''<br />
|Specifies how many stack frames of [http://en.wikipedia.org/wiki/Tail_call tail-calls] are allowed on the stack at any time. When this limit is reached, tail-call optimization takes place and some call frames are eliminated. The feature can be turned off by setting the value to {{Code|-1}}.<br />
|}<br />
<br />
===DEFAULTDB===<br />
<br />
{{Mark|Introduced with Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DEFAULTDB}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|If this option is turned on, paths specified in the {{Code|fn:doc}} and {{Code|fn:collections}} functions will first be resolved against a database that has been opened in the global context outside the query (e.g. by the [[Commands#OPEN|OPEN]] command). If the path does not match any existing resources, it will be resolved as described in the article on [[Databases#Access Resources|accessing database resources]].<br />
|}<br />
<br />
===CACHEQUERY===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CACHEQUERY [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Caches the query results before returning them to the client. This option may be set to {{Code|true}} if the whole result is needed for further operations (such as is e.g. the case in the GUI of BaseX).<br />
|}<br />
<br />
===FORCECREATE===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|FORCECREATE [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|By activating this option, the XQuery {{Code|doc()}} and {{Code|collection()}} functions will create database instances for the addressed input files.<br />
|}<br />
<br />
===CHECKSTRINGS===<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|CHECKSTRINGS [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|If this option is turned off, strings from external sources will be adopted as is, i. e., without being checked for valid XML characters:<br />
* This option affects [[Java Bindings]] and the string conversion and input functions [[Archive Module#archive:create|archive:create]], [[Archive Module#archive:extract-text|archive:extract-text]], [[Archive Module#archive:update|archive:update]], [[Conversion Module#convert:binary-to-string|convert:binary-to-string]], [[Fetch Module#fetch:text|fetch:text]], [[File Module#file:read-text|file:read-text]], and [[ZIP Module#zip:text-entry|zip:text-entry]].<br />
* Please be aware that an inconsiderate use of this option may cause unexpected behavior when storing or outputting strings.<br />
|}<br />
<br />
===LSERROR===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|LSERROR [error]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|0}}<br />
|-<br />
| '''Summary'''<br />
|This option specifies the maximum Levenshtein error for the BaseX-specific fuzzy match option. See the page on [[Full-Text#Fuzzy_Querying|Full-Texts]] for more information on fuzzy querying.<br />
|}<br />
<br />
===RUNQUERY===<br />
<br />
{{Mark|Introduced with Version 7.8:}}<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|RUNQUERY [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Specifies if a query will be executed or parsed only. This option can also be changed on [[Command-Line Options#BaseX Standalone|command line]] via <code>-R</code>.<br />
|}<br />
<br />
===RUNS===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|RUNS [num]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|1}}<br />
|-<br />
| '''Summary'''<br />
|Specifies how often a query will be evaluated. The result is serialized only once, and the measured times are averages of all runs. This option can also be changed on [[Command-Line Options#BaseX Standalone|command line]] via <code>-r</code>.<br />
|}<br />
<br />
=Serialization Options=<br />
<br />
===SERIALIZE===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|SERIALIZE [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Results of XQuery expressions will be serialized if this option is turned on. For debugging purposes and performance measurements, this option can be set to {{Code|false}}. It can also be turned off on [[Command-Line Options#BaseX Standalone|command line]] via <code>-z</code>. <br />
|}<br />
<br />
===SERIALIZER===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|SERIALIZER [params]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Contains parameters for [[Serialization|serializing]] query results:<br />
* Keys and values are separated by equality signs.<br />
* Multiple parameters are delimited by commas.<br />
* The option can also be used on [[Command-Line Options#BaseX Standalone|command line]] with the flag <code>-s</code>.<br />
|-<br />
| '''Example'''<br />
|<code>encoding=US-ASCII,omit-xml-declaration=no</code> : sets the encoding to {{Code|US-ASCII}} and prints the XML declaration.<br />
|}<br />
<br />
===EXPORTER===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|EXPORTER [params]}}<br />
|-<br />
| '''Default'''<br />
|''empty''<br />
|-<br />
| '''Summary'''<br />
|Contains parameters for exporting all resources of a database; see [[Serialization]] for more details. Keys and values are separated by equality signs, multiple parameters are delimited by commas.<br />
|}<br />
<br />
===XMLPLAN===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|XMLPLAN [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Prints the execution plan of an XQuery expression in its XML representation. This option can also be activated on [[Command-Line Options#BaseX Standalone|command line]] via <code>-x</code>. <br />
|}<br />
<br />
===COMPPLAN===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|COMPPLAN [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Creates the query plan before or after query compilation. Query plans might change due to optimizations.<br />
|}<br />
<br />
===DOTPLAN===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DOTPLAN [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Visualizes the execution plan of an XQuery expression with [http://www.graphviz.org dotty] and saves its dot file in the query directory.<br />
|}<br />
<br />
===DOTCOMPACT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|DOTCOMPACT [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Chooses a compact dot representation.<br />
|}<br />
<br />
=Other Options=<br />
<br />
===AUTOFLUSH===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|AUTOFLUSH [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|true}}<br />
|-<br />
| '''Summary'''<br />
|Flushes database buffers to disk after each update. If this option is set to {{Code|false}}, bulk operations (multiple single updates) will be evaluated faster. As a drawback, the chance of data loss increases if the database is not explicitly flushed via the [[Commands#FLUSH|FLUSH]] command.<br />
|}<br />
<br />
===WRITEBACK===<br />
<br />
{{Mark|Updated with Version 7.8:}} only applies to main-memory document instances.<br />
<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|WRITEBACK [boolean]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|false}}<br />
|-<br />
| '''Summary'''<br />
|Propagates updates on main-memory instances of files that have been retrieved via {{Code|fn:doc}} or {{Code|fn:collection}} back to disk. No backups of your original files will be created if this option is turned on. This option can also be activated on [[Command-Line Options#BaseX Standalone|command line]] via <code>-u</code>.<br />
|}<br />
<br />
===MAXSTAT===<br />
{| width='100%'<br />
|-<br />
| width='120' | '''Signature'''<br />
|{{Code|MAXSTAT [num]}}<br />
|-<br />
| '''Default'''<br />
|{{Code|30}}<br />
|-<br />
| '''Summary'''<br />
|Specifies the maximum number of index occurrences printed by the <code>[[Commands#INFO|INFO INDEX]]</code> command.<br />
|}<br />
<br />
=Changelog=<br />
<br />
;Version 7.8<br />
<br />
* Added: <code>[[#MIXUPDATES|MIXUPDATES]]</code><br />
<br />
;Version 7.8.1<br />
* Updated: <code>[[#ADDARCHIVES|ADDARCHIVES]]</code>: parsing of TAR and TGZ files.<br />
<br />
;Version 7.8<br />
<br />
* Added: <code>[[#CSVPARSER|CSVPARSER]]</code>, <code>[[#JSONPARSER|JSONPARSER]]</code>, <code>[[#TEXTPARSER|TEXTPARSER]]</code>, <code>[[#HTMLPARSER|HTMLPARSER]]</code>, <code>[[#INLINELIMIT|INLINELIMIT]]</code>, <code>[[#TAILCALLS|TAILCALLS]]</code>, <code>[[#DEFAULTDB|DEFAULTDB]]</code>, <code>[[#RUNQUERY|RUNQUERY]]</code><br />
* Updated: <code>[[#WRITEBACK|WRITEBACK]]</code> only applies to main-memory document instances.<br />
* Updated: <code>[[#DEBUG|DEBUG]]</code> option can be changed at runtime by users with admin permissions.<br />
* Updated: default of <code>[[#INTPARSE|INTPARSE]]</code> is now {{Code|false}}.<br />
* Removed: <code>HTMLOPT</code> (replaced with <code>[[#HTMLPARSER|HTMLPARSER]]</code>), <code>PARSEROPT</code> (replaced with parser-specific options), <code>DOTDISPLAY</code>, <code>DOTTY</code><br />
<br />
;Version 7.7<br />
<br />
* Added: <code>[[#ADDCACHE|ADDCACHE]]</code>, <code>[[#CHECKSTRINGS|CHECKSTRINGS]]</code>, <code>[[#FTINDEXSPLITSIZE|FTINDEXSPLITSIZE]]</code>, <code>[[#INDEXSPLITSIZE|INDEXSPLITSIZE]]</code><br />
<br />
;Version 7.6<br />
<br />
* Added: <code>[[#GLOBALLOCK|GLOBALLOCK]]</code><br />
* Added: store local options in configuration file after {{Code|# Local Options}} comments.<br />
<br />
;Version 7.5<br />
<br />
* Added: options can now be set via system properties<br />
* Added: a pragma expression can be used to locally change database options<br />
* Added: <code>[[#USER|USER]]</code>, <code>[[#PASSWORD|PASSWORD]]</code>, <code>[[#LOG|LOG]]</code>, <code>[[#LOGMSGMAXLEN|LOGMSGMAXLEN]]</code>, <code>[[#WEBPATH|WEBPATH]]</code>, <code>[[#RESTXQPATH|RESTXQPATH]]</code><code>[[#HTTPLOCAL|HTTPLOCAL]]</code>, <code>[[#CREATEONLY|CREATEONLY]]</code>, <code>[[#STRIPNS|STRIPNS]]</code><br />
* Removed: {{Code|HTTPPATH}}; {{Code|HTTPPORT}}: {{Code|jetty.xml}} configuration file is used instead<br />
* Removed: global options cannot be changed anymore during the lifetime of a BaseX instance<br />
<br />
;Version 7.3<br />
<br />
* Updated: <code>[[#KEEPALIVE|KEEPALIVE]]</code>, <code>[[#TIMEOUT|TIMEOUT]]</code>: default values changed<br />
* Removed: {{Code|WILDCARDS}}; new index supports both fuzzy and wildcard queries<br />
* Removed: {{Code|SCORING}}; new scoring model will focus on lengths of text nodes and match options<br />
<br />
;Version 7.2<br />
<br />
* Added: <code>[[#PROXYHOST|PROXYHOST]]</code>, <code>[[#PROXYPORT|PROXYPORT]]</code>, <code>[[#NONPROXYHOSTS|NONPROXYHOSTS]]</code>, <code>[[#HTMLOPT|HTMLOPT]]</code><br />
* Updated: <code>[[#TIMEOUT|TIMEOUT]]</code>: ignore timeout for admin users<br />
<br />
;Version 7.1<br />
<br />
* Added: <code>[[#ADDRAW|ADDRAW]]</code>, <code>[[#MAXLEN|MAXLEN]]</code>, <code>[[#MAXCATS|MAXCATS]]</code>, <code>[[#UPDINDEX|UPDINDEX]]</code><br />
* Updated: <code>[[#BINDINGS|BINDINGS]]</code><br />
<br />
;Version 7.0<br />
<br />
* Added: <code>[[#SERVERHOST|SERVERHOST]]</code>, <code>[[#KEEPALIVE|KEEPALIVE]]</code>, <code>[[#AUTOFLUSH|AUTOFLUSH]]</code>, <code>[[#QUERYPATH|QUERYPATH]]</code></div>Dirkhttps://docs.basex.org/index.php?title=User:Dirk/Replica_Set&diff=10535User:Dirk/Replica Set2014-03-26T15:47:02Z<p>Dirk: setup</p>
<hr />
<div><div style="float:left; width:100%;"><br />
This page presents the replica set, internal communication and mechanism within a replica set and means to communicate with a replica set including protocol information.<br />
<br />
==Overview==<br />
<br />
A replica set consist of at most one primary and a theoretically unlimited number of secondaries.<br />
<br />
==MemberSession==<br />
<br />
===Protocol===<br />
<br />
A client can communicate with the members within a replica set by using a MemberSession. After establishing a TCP connection to the TCP port of a BaseXMember the authentication process works as follows:<br />
<br />
</div></div>Dirkhttps://docs.basex.org/index.php?title=Java_Examples&diff=10528Java Examples2014-03-20T10:21:19Z<p>Dirk: Updates links toi GitHub</p>
<hr />
<div>This page is part of the [[Developer Section]].<br />
The following Java code snippets demonstrate how easy it is to run database commands, create collections, perform queries, etc. by integrating the BaseX code. Most examples are taken from our [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples basex-examples] repository, in which you will find some more use cases.<br />
<br />
<div style="float:left; width:48%;"><br />
==Local Examples==<br />
<br />
The following code snippets work in ''embedded'' mode; they do not rely on an additional server instance:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/RunCommands.java RunCommands.java]<br/>creates and drops database and index instances, prints a list of all existing databases.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/RunQueries.java RunQueries.java]<br/>shows three variants of running queries.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/BindContext.java BindContext.java]<br/>demonstrates how a value can be bound as context item.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/BindVariables.java BindVariables.java]<br/>demonstrates how a value can be bound to a variable.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/CreateCollection.java CreateCollection.java]<br/>creates and manages a collection.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/QueryCollection.java QueryCollection.java]<br/>creates, runs queries against it and drops a collection.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/local/WikiExample.java WikiExample.java]<br/>creates a database from an url (wiki instance), runs a query against it and drops the database.<br />
<br />
==Server Examples==<br />
<br />
The examples below take advantage of the client/server architecture:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerCommands.java ServerCommands.java]<br/>launches server-side commands using a client session.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerAndLocal.java ServerAndLocal.java]<br/>processes server results locally.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerConcurrency.java ServerConcurrency.java]<br/>runs concurrent queries.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerQueries.java ServerQueries.java]<br/>shows how iterative queries can be performed.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/ServerEventsGUI.java ServerEventsGUI.java]<br/>is a little GUI example for demonstrating database events.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/server/UserExample.java UserExample.java]<br/>manages database users.<br />
<br />
==XQuery Module Examples==<br />
<br />
BaseX provides [[Java Bindings]] for accessing external Java code via XQuery functions. The following examples show how this feature can be utilized:<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/FruitsExample.java FruitsExample.java]<br/>demonstrates how Java classes can be imported as XQuery modules.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/FruitsModule.java FruitsModule.java]<br/>is a simple demo module called by {{Code|FruitsExample}}.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/module/ModuleDemo.java ModuleDemo.java]<br/>is a simple XQuery demo module that demonstrates how XQuery items can be processed from Java. It is derived from the {{Code|QueryModule}} class.<br />
* [https://github.com/BaseXdb/basex/blob/master/src/main/java/org/basex/query/QueryModule.java QueryModule.java]<br/>is located in the BaseX core. Java query modules can extend this class to get access to the current query context and enrich functions with properties ().<br />
<br />
</div><div style="float:left; width:4%;">&nbsp;<br />
</div><div style="float:left; width:48%;"><br />
<br />
==XQJ API==<br />
<br />
The implementation of the [http://xqj.net/basex/ BaseX XQJ API] (closed-source) has been written by Charles Foster. It uses the client/server architecture.<br />
The basex-examples repository contains [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/xqj various examples] on how to use XQJ.<br />
<br />
==[[Clients|Client API]]==<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/BaseXClient.java BaseXClient.java]<br/>provides an implementation of the [[Server Protocol]].<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/Example.java Example.java]<br/>demonstrates how commands can be executed on a server.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/QueryExample.java QueryExample.java]<br/>shows how queries can be executed in an iterative manner.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/QueryBindExample.java QueryBindExample.java]<br/>shows how external variables can be bound to XQuery expressions.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/CreateExample.java CreateExample.java]<br/>shows how new databases can be created.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/AddExample.java AddExample.java]<br/>shows how documents can be added to databases, and how existing documents can be replaced.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/EventExample.java EventExample.java]<br/>demonstrates how to trigger and receive database events.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/api/BinaryExample.java BinaryExample.java]<br/>shows how binary resource can be added to and retrieved from the database.<br />
<br />
==[[REST API]]==<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTGet.java RESTGet.java]<br/>presents the HTTP GET method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTPost.java RESTPost.java]<br/>presents the HTTP POST method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTPut.java RESTPut.java]<br/>presents the HTTP PUT method.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/rest/RESTAll.java RESTAll.java]<br/>runs all examples at one go.<br />
<br />
==XML:DB API (deprecated)==<br />
<br />
Note that the XML:DB API does not talk to the server and can thus only be used in embedded mode.<br />
<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBCreate.java XMLDBCreate.java]<br/>creates a collection using XML:DB.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBQuery.java XMLDBQuery.java]<br/>runs a query using XML:DB.<br />
* [https://github.com/BaseXdb/basex/blob/master/basex-examples/src/main/java/org/basex/examples/xmldb/XMLDBInsert.java XMLDBInsert.java]<br/>inserts a document into a database using XML:DB.<br />
</div><br />
<br />
[[Category:Developer]]<br />
__NOTOC__</div>Dirkhttps://docs.basex.org/index.php?title=Commands&diff=9956Commands2013-09-30T15:34:57Z<p>Dirk: [MIN] trailing / not needed</p>
<hr />
<div>This article is part of the [[Getting Started]] Section.<br />
It lists all database commands supported by BaseX.<br />
Commands can e.g. be executed from the [[Startup_Options#BaseX_Standalone|Command Line]],<br />
[[#Command Scripts|Scripts]], the [[Clients]], [[REST]], the input field in the [[GUI]]<br />
and other ways. If the GUI is used, all commands that are triggered by the GUI itself<br />
will show up in the [[GUI#Visualizations|Info View]].<br />
The [[User_Management|Permission]] fields indicate which<br />
rights are required by a user to perform a command in the client/server architecture.<br />
<br />
=Basics=<br />
<br />
==Command Scripts==<br />
<br />
Database commands in both the string and XML syntax can be placed in a text file and stored on disk. The default extension for BaseX command scripts is {{Code|.bxs}}. If the path to a command script is passed on to BaseX, it will automatically be recognized and evaluated as such.<br />
<br />
==String Syntax==<br />
<br />
Multiple commands can be written in a single line and separated by semicolons, or stored as command script. Lines starting with <code>#</code> are interpreted as comments and are skipped. The following script creates a database, adds two documents to it and performs a query:<br />
<br />
<pre class="brush:xml"><br />
CREATE DB test<br />
ADD input.xml<br />
ADD TO embedded.xml <root>embedded</root><br />
# run query<br />
XQUERY count(//text())<br />
</pre><br />
<br />
==XML Syntax==<br />
<br />
The string syntax is limited when XML snippets need to be embedded in a command,<br />
or when complex queries are to be specified.<br />
<br />
This is why database commands can also be specified in XML.<br />
Multiple commands can be enclosed by a {{Code|<commands/>}} root element:<br />
<br />
<pre class="brush:xml"><br />
<commands><br />
<create-db name='test'/><br />
<add>input.xml</add><br />
<add path='embedded.xml'><root>embedded</root></add><br />
<xquery>count(//text())</xquery><br />
</commands><br />
</pre><br />
<br />
==Glob Syntax==<br />
<br />
Some commands support the glob syntax to address more than one database or user. Question marks and asterisks can be used to match one or more characters, and commas can be used to separate multiple patterns. Some examples:<br />
<br />
* {{Code|AB?}} addresses all names with the characters {{Code|AB}} and one more character.<br />
* {{Code|*AB}} addresses all names ending with the characters {{Code|AB}}.<br />
* {{Code|X*,Y*,Z*}} addresses all names starting with the characters {{Code|X}}, {{Code|Y}}, or {{Code|Z}}.<br />
<br />
==Valid Names==<br />
<br />
{{Mark|Updated with Version 7.7}}:<br />
<br />
Database, user and event names follow the same naming constraints: Names are restricted to ASCII characters. They must at least have one character, and they may contain letters, numbers and any of the special characters <code>!#$%&'()+-=@[]^_`{}~</code>. The following characters are reserved for other features:<br />
<br />
* <code>,?*</code>: [[#Glob Syntax|glob syntax]]<br />
* <code>;</code>: Separator for multiple database commands on the [[Startup Options|command line]]<br />
* <code>\/</code>: Directory path separators<br />
* <code>.</code>: hidden folders (e.g. the [[Logging|.logs directory]])<br />
* <code>:*?\"<>|}</code>: invalid filename characters on Windows<br />
<br />
Before {{Version|7.7}}, names were restricted to letters, numbers, underscores and dashes, matching the regular expression <code>[-_a-zA-Z0-9]{1,128}</code>.<br />
<br />
==Aliases==<br />
<br />
In all commands, the {{Code|DB}} keyword can be replaced by {{Code|DATABASE}}.<br />
<br />
=Database Operations=<br />
<br />
==CREATE DB==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CREATE DB [name] ([input])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><create-db name='...'>([input])</create-db></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Creates the database {{Code|[name]}} with an optional {{Code|[input]}} and opens it.<br />The input may either be a reference to a single XML document, a directory, a remote URL, or a string containing XML:<br />
* {{Code|[name]}} must be a [[#Valid Names|valid database name]]<br />
* several additional [[Options#Create Options|Create Options]] can be set to influence the creation process.<br />
|-<br />
| '''Errors'''<br />
|The command fails if a database with the specified name is currently used by another process, if one of the documents to be added is not well-formed or if it cannot be parsed for some other reason.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|CREATE DB input}}<br/>creates an empty database {{Code|input}}.<br />
* {{Code|CREATE DB xmark http://files.basex.org/xml/xmark.xml}}<br/>creates the database {{Code|xmark}}, containing a single initial document called {{Code|xmark.xml}}.<br />
* {{Code|CREATE DATABASE coll /path/to/input}}<br/>creates the database {{Code|coll}} with all documents found in the {{Code|input}} directory.<br />
* {{Code|SET INTPARSE false; CREATE DB input input.xml}}<br/>creates a database {{Code|input}} with {{Code|input.xml}} as initial document, which will be parsed with Java's [[Parsers#XML Parsers|default XML parser]].<br />
* <code><create-db name='simple'><hello>Universe</hello></create-db></code><br/>creates a database named {{Code|simple}} with an initial document {{Code|<hello>Universe</hello>}}.<br />
|}<br />
<br />
==OPEN==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|OPEN [name]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><open name='...'/></code><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Opens the database specified by {{Code|[name]}}.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified database does not exist, is currently being updated by another process or cannot be opened for some other reason.<br />
|}<br />
<br />
==CHECK==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CHECK [input]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><check input='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ/CREATE''<br />
|-<br />
| '''Summary'''<br />
|This convenience command combines [[#OPEN|OPEN]] and [[#CREATE DB|CREATE DB]]: if a database with the name {{Code|[input]}} exists, it is opened. Otherwise, a new database is created; if the specified input points to an existing resource, it is stored as initial content.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the addressed database could neither be opened nor created.<br />
|}<br />
<br />
==CLOSE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CLOSE }}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><close/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Closes the currently opened database.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the database files could not be closed for some reason.<br />
|}<br />
<br />
==EXPORT==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|EXPORT [path]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><export path='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Exports all documents in the database to the specified {{Code|[path]}}, using the serializer options specified by the <code>[[Options#EXPORTER|EXPORTER]]</code> option.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the target path points to a file or is invalid, if the serialization parameters are invalid, or if the documents cannot be serialized for some other reason.<br />
|}<br />
<br />
==CREATE INDEX==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CREATE INDEX [TEXT&#x7c;ATTRIBUTE&#x7c;FULLTEXT]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code>&lt;create-index type='text&#x7c;attribute&#x7c;fulltext'/&gt;</code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Creates the specified database [[Indexes|index]].<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the specified index is unknown, or if indexing fails for some other reason.<br />
|}<br />
<br />
==DROP INDEX==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|DROP INDEX [TEXT&#x7c;ATTRIBUTE&#x7c;FULLTEXT]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><drop-index type='text&#x7c;attribute&#x7c;fulltext'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Drops the specified database [[Indexes|index]].<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the specified index is unknown, or if it could not be deleted for some other reason.<br />
|}<br />
<br />
=Administration=<br />
<br />
==ALTER DB==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|ALTER DB [name] [newname]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><alter-db name='...' newname='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Renames the database specified by {{Code|[name]}} to {{Code|[newname]}}. {{Code|[newname]}} must be a [[#Valid Names|valid database name]].<br />
|-<br />
| '''Errors'''<br />
|The command fails if the target database already exists, if the source database does not exist or is currently locked, or if it could not be renamed for some other reason.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|ALTER DB db tempdb}}<br/>renames the database {{Code|db}} into {{Code|tempdb}}.<br />
|}<br />
<br />
==DROP DB==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|DROP DB [name]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><drop-db name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Drops the database with the specified {{Code|[name]}}. The [[#Glob Syntax|Glob Syntax]] can be used to address more than one database.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified database does not exist or is currently locked, or if the database could not be deleted for some other reason.<br />
|}<br />
<br />
==CREATE BACKUP==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CREATE BACKUP [name]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><create-backup name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Creates a zipped backup of the database specified by {{Code|[name]}}. The backup file will be suffixed with the current timestamp and stored in the database directory. The [[#Glob Syntax|Glob Syntax]] can be used to address more than one database.<br/>Please note that Java 7 is required to handle ''ZIP files larger than 4 GB''.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified database does not exist, or if it could not be zipped for some other reason.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|BACKUP db}}<br/>creates a zip archive of the database {{Code|db}} (e.g. {{Code|db-2011-04-01-12-27-28.zip}}) in the [[Configuration#Database_Directory|database directory]].<br />
|}<br />
<br />
==RESTORE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|RESTORE [name]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><restore name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Restores a database with the specified {{Code|[name]}}. The name may include the timestamp of the backup file.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified backup does not exist, if the database to be restored is currently locked, or if it could not be restored for some other reason.<br />
|}<br />
<br />
==INSPECT==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|INSPECT}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><inspect/></code><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Performs some integrity checks on the opened database and returns a brief summary.<br />
|}<br />
<br />
==DROP BACKUP==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|DROP BACKUP [name]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><drop-backup name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Drops all backups of the database with the specified {{Code|[name]}}. The [[#Glob Syntax|Glob Syntax]] can be used to address more than one database.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|DROP BACKUP abc*}}<br/>deletes the backups of all databases starting with the characters {{Code|abc}}.<br />
|}<br />
<br />
==SHOW BACKUPS==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|SHOW BACKUPS}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><show-backups/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Shows all database backups.<br />
|}<br />
<br />
==COPY==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|COPY [name] [newname]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><copy name='...' newname='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
|Creates a copy of the database specified by {{Code|[name]}}. {{Code|[newname]}} must be a [[#Valid Names|valid database name]].<br />
|-<br />
| '''Errors'''<br />
|The command fails if the target database already exists, or if the source database does not exist.<br />
|}<br />
<br />
==INFO DB==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|INFO DB}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><info-db/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Shows information on the currently opened database.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened.<br />
|}<br />
<br />
==INFO INDEX==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|INFO INDEX ([TAG&#x7c;ATTNAME&#x7c;PATH&#x7c;TEXT&#x7c;ATTRIBUTE&#x7c;FULLTEXT])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><info-index type='tag&#x7c;attname&#x7c;path&#x7c;text&#x7c;attribute&#x7c;fulltext'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Shows information on the existing [[Indexes|index]] structures. The output can be optionally limited to the specified index.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, or if the specified index is unknown.<br />
|}<br />
<br />
==INFO STORAGE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|INFO STORAGE [start end] &#x7c; [query]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><info-storage>([query])</info-storage></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Shows the internal main table of the currently opened database. An integer range or a query may be specified as argument.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, or if one of the specified arguments is invalid.<br />
|}<br />
<br />
= Querying =<br />
<br />
==LIST==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|LIST ([name] ([path]))}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><list (name='...' (path='...'))/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''NONE''<br />
|-<br />
| '''Summary'''<br />
|Lists all available databases. If {{Code|[name]}} is specified, the resources of a database are listed. The output can be further restricted to the resources matching the specified {{Code|[path]}}.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the optional database cannot be opened, or if the existing databases cannot be listed for some other reason.<br />
|}<br />
<br />
==XQUERY==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|XQUERY [query]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><xquery>[query]</xquery></code><br/><br />
|-<br />
| '''Permission'''<br />
|''depends on query''<br />
|-<br />
| '''Summary'''<br />
|Runs the specified {{Code|[query]}} and prints the result.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified query is invalid.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|XQUERY 1 to 10}}<br/>returns the sequence {{Code|(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)}}.<br />
* {{Code|SET RUNS 10; XQUERY 1 to 10}}<br/>runs the query 10 times, returns the result and prints the average execution time.<br />
* {{Code|SET XMLPLAN true; XQUERY 1 to 10}}<br/>returns the result and prints the query plan as XML.<br />
|}<br />
<br />
==RETRIEVE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|RETRIEVE [path]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><retrieve path='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Retrieves a raw file from the opened database at the specified {{Code|[path]}}.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the source path is invalid or if the data cannot not be retrieved for some other reason.<br />
|}<br />
<br />
==FIND==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|FIND [query]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><find>[query]</find></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Builds and runs a query for the specified {{Code|[query]}} terms. Keywords can be enclosed in quotes to look for phrases. The following modifiers can be used to further limit search:<br />
<code>=</code> looks for exact text nodes<br/><code>~</code> looks for approximate hits<br/><code>@=</code> looks for exact attribute values<br/><code>@</code> looks for attributes<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened.<br />
|}<br />
<br />
==CS==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CS [query]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><cs>[query]</cs></code><br/><br />
|-<br />
| '''Permission'''<br />
|''depends on query''<br />
|-<br />
| '''Summary'''<br />
|Evaluates the specified {{Code|[query]}} and declares the resulting nodes as new ''context set''. In subsequent queries, the context set will be available via the context item expression of XQuery ({{Code|.}}).<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the specified query is invalid or if it does not return nodes of the currently opened database.<br />
|}<br />
<br />
==REPO INSTALL==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|REPO INSTALL [path]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><repo-install path='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
| Installs the package with path {{Code|[path]}}.<br />
|-<br />
| '''Errors'''<br />
| The command fails in the following cases:<br />
* The package to be installed is not a xar file.<br />
* The package to be installed does not exist or is already installed.<br />
* The package descriptor is with invalid syntax.<br />
* The package to be installed depends on a package which is not installed.<br />
* The package is not supported by the current version of BaseX.<br />
* A component of the package is already installed as part of another package.<br />
|}<br />
<br />
==REPO LIST==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|REPO LIST}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><repo-list/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
| Lists all installed packages.<br />
|}<br />
<br />
==REPO DELETE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|REPO DELETE [name]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><repo-delete name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''CREATE''<br />
|-<br />
| '''Summary'''<br />
| Deletes the package with name {{Code|[name]}}, optionally followed by a version.<br />
|-<br />
| '''Errors'''<br />
| The command fails if the package to be deleted participates in a dependency.<br />
|}<br />
<br />
=Updates=<br />
<br />
==ADD==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|ADD (TO [path]) [input]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><add (path='...')>[input]</add></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Adds a file, directory or XML string specified by {{Code|[input]}} to the currently opened database at the specified {{Code|[path]}}.<br/>{{Code|[input]}} may either be a single XML document, a directory, a remote URL or a plain XML string.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if one of the documents to be added is not well-formed, or if it could not be parsed for some other reason.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|ADD input.xml}}<br/>adds the file {{Code|input.xml}} to the database.<br />
* {{Code|ADD TO temp/one.xml input.xml}}<br/>adds {{Code|input.xml}} to the database and moves it to {{Code|temp/one.xml}}.<br />
* {{Code|ADD TO target/ xmldir}}<br/>adds all files from the {{Code|xmldir}} directory to the database in the {{Code|target}} path.<br />
|}<br />
<br />
==DELETE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|DELETE [path]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><delete path='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Deletes all documents from the currently opened database that start with the specified {{Code|[path]}}.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened.<br />
|}<br />
<br />
==RENAME==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|RENAME [path] [newpath]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><rename path='...' newpath='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Renames all document paths in the currently opened database that start with the specified {{Code|[path]}}. The command may be used to either rename single documents or directories.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, or if the target path is empty.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|RENAME one.xml two.xml}}<br/>renames the document {{Code|one.xml}} to {{Code|two.xml}}.<br />
* {{Code|RENAME / TOP}}<br/>moves all documents to a {{Code|TOP}} root directory.<br />
|}<br />
<br />
==REPLACE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|REPLACE [path] [input]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><replace path='...'>[input]</replace></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Replaces a document in the currently opened database, addressed by {{Code|[path]}}, with the file or XML string specified by {{Code|[input]}}, or adds it as a new document.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the specified path points to a database directory, or if the input is not found.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|REPLACE one.xml input.xml}}<br/>replaces the document {{Code|one.xml}} with the contents of the file {{Code|input.xml}}.<br />
* {{Code|REPLACE top.xml &lt;xml/&gt;}}<br/>replaces the document {{Code|top.xml}} with the document {{Code|&lt;xml/&gt;}}.<br />
|}<br />
<br />
==STORE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|STORE (TO [path]) [input]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><store (path='...')>[input]</store></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Stores a raw file in the opened database to the specified {{Code|[path]}}. {{Code|[input]}} may either be a file reference, a remote URL, or a plain string. If the path denotes a directory, it needs to be suffixed with a slash ({{Code|/}}).<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, if the specified resource is not found, if the target path is invalid or if the data cannot not be written for some other reason.<br />
|}<br />
<br />
==OPTIMIZE==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|OPTIMIZE (ALL)}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><optimize/></code><br/><code><optimize-all/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Optimizes the index structures, meta data and statistics of the currently opened database. If the {{Code|ALL}} flag is specified, the internal database structures are completely rebuilt; this often leads to a reduction of the total database size.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened, or if the currently opened database is a main-memory instance.<br />
|}<br />
<br />
==FLUSH==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|FLUSH}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><flush/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''WRITE''<br />
|-<br />
| '''Summary'''<br />
|Explicitly flushes the buffers of the currently opened database to disk. This command is applied if [[Options#AUTOFLUSH|AUTOFLUSH]] has been set to {{Code|false}}.<br />
|-<br />
| '''Errors'''<br />
|The command fails if no database is opened.<br />
|}<br />
<br />
=Server Administration=<br />
<br />
==SHOW SESSIONS==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|SHOW SESSIONS}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><show-sessions/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Shows all sessions that are connected to the current server instance.<br />
|}<br />
<br />
==SHOW USERS==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|SHOW USERS (ON [database])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><show-users (database='...')/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Shows all users that are registered in the database. If a {{Code|[database]}} is specified, local users are shown.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the optional database could not be opened.<br />
|}<br />
<br />
==KILL==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|KILL [target]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><kill target='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Kills sessions of a user or an IP:port combination, specified by {{Code|[target]}}. The [[#Glob Syntax|Glob Syntax]] can be used to address more than one user.<br />
|-<br />
| '''Errors'''<br />
|The command fails if a user tried to kill his/her own session.<br />
|}<br />
<br />
==CREATE EVENT==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CREATE EVENT [NAME]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><create-event name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Creates the specified [[Events|event]].<br />
|-<br />
| '''Errors'''<br />
|The command fails if event already exists.<br />
|}<br />
<br />
==SHOW EVENTS==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|SHOW EVENTS}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><show-events/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Shows all [[Events|events]] that have been registered in the database.<br />
|}<br />
<br />
==DROP EVENT==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|DROP EVENT [NAME]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><drop-event name='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Drops the specified [[Events|event]].<br />
|-<br />
| '''Errors'''<br />
|The command fails if the event doesn't exist.<br />
|}<br />
<br />
=User Management=<br />
<br />
==CREATE USER==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|CREATE USER [name] ([password])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><create-user name='...'>([password])</create-user></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Creates a user with the specified {{Code|[name]}} and {{Code|[password]}}. {{Code|[name]}} must be a [[#Valid Names|valid user name]]. The password must be a valid MD5 hash value. If no password is specified in the console mode, it is requested via standard input.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified user already exists, or if the password is no valid MD5 hash value.<br />
|}<br />
<br />
==ALTER USER==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|ALTER USER [name] ([password])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><alter-user name='...'>([password])</alter-user></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Alters the {{Code|[password]}} of the user specified by {{Code|[name]}}. The password must be a valid MD5 hash value. If no password is specified in the console mode, it is requested via standard input.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified user does not exist, or if the password is no valid MD5 hash value.<br />
|}<br />
<br />
==DROP USER==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|DROP USER [name] (ON [database])}}:<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><drop-user name='...' (database='...')/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Drops the user with the specified {{Code|[name]}}. If a {{Code|[database]}} is specified, the user is only dropped locally. The [[#Glob Syntax|Glob Syntax]] can be used to address more than one database or user.<br />
|-<br />
| '''Errors'''<br />
|The command fails if {{Code|admin}} is specified as user name, if the specified user does not exist or is logged in, or if the optional database could not be opened for modification.<br />
|}<br />
<br />
==GRANT==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|GRANT [NONE&#x7c;READ&#x7c;WRITE&#x7c;CREATE&#x7c;ADMIN] (ON [database]) TO [user]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><grant name='...' permission='none&#x7c;read&#x7c;write&#x7c;create&#x7c;admin' (database='...')/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''ADMIN''<br />
|-<br />
| '''Summary'''<br />
|Grants the specified [[User_Management|permission]] to the specified {{Code|[user]}}. If a {{Code|[database]}} is specified, the permissions are only granted locally. The [[#Glob Syntax|Glob Syntax]] can be used to address more than one database or user.<br />
|-<br />
| '''Errors'''<br />
|The command fails if {{Code|admin}} is specified as user name, if the specified user does not exist, or if the optional database could not be opened for modification.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|GRANT READ TO JoeWinson}}<br/>grants {{Code|READ}} permission to the user {{Code|JoeWinson}}.<br />
* {{Code|GRANT WRITE ON Wiki TO editor*}}<br/>grants {{Code|WRITE}} permissions on the {{Code|Wiki}} database to all users starting with the characters {{Code|editor*}}.<br />
|}<br />
<br />
==PASSWORD==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|PASSWORD ([password])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><password>([password])</password></code><br/><br />
|-<br />
| '''Permission'''<br />
|''NONE''<br />
|-<br />
| '''Summary'''<br />
|Changes the {{Code|[password]}} of the current user. The password must be a valid MD5 hash value. If no password is specified in the console mode, it is requested via standard input.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the password is no valid MD5 hash value.<br />
|}<br />
<br />
=General Commands=<br />
<br />
==RUN==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|RUN [file]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><run file='...'/></code><br />
|-<br />
| '''Permission'''<br />
|''depends on input''<br />
|-<br />
| '''Summary'''<br />
|Evaluates the contents of {{Code|[file]}} as XQuery expression. If the file ends with the suffix {{Code|.bxs}}, the file content will be evaluated as [[#Basics|command script]]. This command can be used to run several commands in a single transaction.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified file does not exist, or if the retrieved input is invalid. It will be canceled as soon as one of the executed commands fails.<br />
|-<br />
| '''Examples'''<br />
|<br />
* <code>RUN query.xq</code><br/>will evaluated the specified file as XQuery expression<br />
* <code>RUN commands.bxs</code><br/>will evaluated the specified file as command script<br />
|}<br />
<br />
==EXECUTE==<br />
<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|EXECUTE [input]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><execute>[input]</execute></code><br />
|-<br />
| '''Permission'''<br />
|''depends on input''<br />
|-<br />
| '''Summary'''<br />
|Evaluates the specified {{Code|[input]}} as [[#Basics|command script]]. This command can be used to run several commands in a single transaction.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the syntax of the specified input is invalid. It will be canceled as soon as one of the executed commands fails.<br />
|-<br />
| '''Examples'''<br />
|<br />
* <code>EXECUTE "create db db1; create db db2"</code><br/><br />
* <code>EXECUTE "<commands><create-db name='db1'/><create-db name='db2'/></commands>"</code><br/>both commands will create two databases {{Code|db1}} and {{Code|db2}} in a single transaction.<br />
|}<br />
<br />
==GET==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|GET [option]}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><get option='...'/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''NONE''<br />
|-<br />
| '''Summary'''<br />
|Returns the current value of the [[Options|Option]] specified via {{Code|[option]}}. Global options can only be requested by users with ADMIN permissions.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified option is unknown.<br />
|}<br />
<br />
==SET==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|SET [option] ([value])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><set option='...'>([value])</set></code><br/><br />
|-<br />
| '''Permission'''<br />
|''NONE''<br />
|-<br />
| '''Summary'''<br />
|Sets the [[Options|Option]] specified by {{Code|[option]}} to a new {{Code|[value]}}. Only local options can be modified. If no value is specified, and if the value is boolean, it will be inverted.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified option is unknown or if the specified value is invalid.<br />
|}<br />
<br />
==INFO==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|INFO}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><info/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''READ''<br />
|-<br />
| '''Summary'''<br />
|Shows global information.<br />
|}<br />
<br />
==HELP==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|HELP ([command])}}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><help>([command])</help></code><br/><br />
|-<br />
| '''Permission'''<br />
|''NONE''<br />
|-<br />
| '''Summary'''<br />
|If {{Code|[command]}} is specified, information on the specific command is printed; otherwise, all commands are listed.<br />
|-<br />
| '''Errors'''<br />
|The command fails if the specified command is unknown.<br />
|}<br />
<br />
==EXIT==<br />
{| width='100%'<br />
|-<br />
|width='130'|'''Syntax'''<br />
|{{Code|EXIT }}<br />
|-<br />
| '''XML&nbsp;Syntax'''&nbsp;&nbsp;&nbsp;<br />
|<code><exit/></code><br/><br />
|-<br />
| '''Permission'''<br />
|''NONE''<br />
|-<br />
| '''Summary'''<br />
|Exits the console mode.<br />
|}<br />
<br />
=Changelog=<br />
<br />
;Version 7.7<br />
<br />
* Updated: syntax of [[#Valid Names|valid names]]<br />
<br />
;Version 7.5<br />
<br />
* Added: <code>[[#EXECUTE|EXECUTE]]</code> executes a command script<br />
* Added: <code>[[#INSPECT|INSPECT]]</code> performs integrity checks<br />
* Added: automatic detection of [[#Basics|Command Scripts]]<br />
* Removed: {{Code|SHOW DATABASES}}; information is also returned by <code>[[#SHOW SESSIONS|SHOW SESSIONS]]</code><br />
* Removed: <code>[[#OPEN|OPEN]]</code>: path argument<br />
<br />
;Version 7.3<br />
<br />
* Added: [[#XML Syntax|XML Syntax]] added<br />
* Updated: <code>[[#CHECK|CHECK]]</code> can now be used to create empty databases<br />
* Updated: Names and paths in <code>[[#OPEN|OPEN]]</code> and <code>[[#LIST|LIST]]</code> are now specified as separate arguments<br />
<br />
;Version 7.2.1<br />
<br />
* Updated: permissions for <code>[[#GET|GET]]</code> and <code>[[#SET|SET]]</code> changed from {{Code|READ}} to {{Code|NONE}}<br />
<br />
;Version 7.2<br />
<br />
* Updated: <code>[[#CREATE INDEX|CREATE INDEX]]</code>, <code>[[#DROP INDEX|DROP INDEX]]</code> ({{Code|PATH}} argument removed. Path summary is always available now and updated with [[#OPTIMIZE|OPTIMIZE]])<br />
* Updated: permissions for <code>[[#REPO DELETE|REPO DELETE]]</code>, <code>[[#REPO INSTALL|REPO INSTALL]]</code> and <code>[[#REPO LIST|REPO LIST]]</code><br />
<br />
;Version 7.1<br />
<br />
* Updated: <code>[[#KILL|KILL]]</code> (killing sessions by specifying IP:port)<br />
<br />
;Version 7.0<br />
<br />
* Added: <code>[[#FLUSH|FLUSH]]</code>, <code>[[#RETRIEVE|RETRIEVE]]</code>, <code>[[#STORE|STORE]]</code><br />
* Updated: <code>[[#ADD|ADD]]</code>: simplified arguments<br />
<br />
[[Category:Beginner]]<br />
[[Category:Server]]</div>Dirkhttps://docs.basex.org/index.php?title=RESTXQ&diff=9753RESTXQ2013-07-31T14:48:41Z<p>Dirk: </p>
<hr />
<div>This page presents one of the [[Web Application]] services. It describes how to use the RESTXQ API of BaseX.<br />
<br />
RESTXQ, introduced by [http://www.adamretter.org.uk/ Adam Retter], is a new API that facilitates the use of XQuery<br />
as a Server Side processing language for the Web. RESTXQ has been inspired by Java’s<br />
[http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services JAX-RS API]: it defines a pre-defined set of<br />
XQuery 3.0 annotations for mapping HTTP requests to XQuery functions, which in turn generate and return<br />
HTTP responses.<br />
<br />
Note that various details of the specification may be subject to change due to the early state of the API. Next, with {{Version|7.7}}, the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
<br />
=Usage=<br />
<br />
Since {{Version|7.7}}, the RESTXQ service is by default available at {{Code|http://localhost:8984/}}.<br />
<br />
All RESTXQ [[XQuery 3.0#Annotations|annotations]] are assigned to the {{Code|<nowiki>http://exquery.org/ns/restxq</nowiki>}} namespace, which is statically bound to the {{Code|restxq}} prefix (and since {{Version|7.7}}: {{Code|rest}}). A ''Resource Function'' is an XQuery function that has been marked up with RESTXQ annotations. When an HTTP request comes in, a resource function will be invoked that matches the constraints indicated by its annotations.<br />
<br />
Whenever a RESTXQ URL is requested, the [[Options#RESTXQPATH|RESTXQPATH]] module directory and its sub-directories will be parsed for library modules (detected by the extension {{Code|.xqm}}) and functions with RESTXQ annotations. Since {{Version|7.7}}, also main modules (detected by {{Code|.xq}}) will be parsed. All modules will be cached and parsed again when their timestamp changes.<br />
<br />
A simple RESTXQ module is shown below. It is part of a clean installation and available at http://localhost:8984/ .<br />
<br />
<pre class="brush:xquery">(: simplified version of the function found in webapp/restxq.xqm :)<br />
module namespace page = 'http://basex.org/examples/web-page';<br />
<br />
declare %rest:path("hello/{$world}")<br />
%rest:GET<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello($world as xs:string, $agent as xs:string*) {<br />
<response><br />
<title>Hello { $world }!</title><br />
<info>You requested this page with { $agent }.</info><br />
</response><br />
};</pre><br />
<br />
If the URI http://localhost:8984/hello/world is accessed, the result will be similar to:<br />
<br />
<pre class="brush:xml"><br />
&lt;response&gt;<br />
&lt;title&gt;Hello World!&lt;/title&gt;<br />
&lt;time&gt;The current time is: 18:42:02.306+02:00&lt;/time&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
The RESTXQ module contains yet another function:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/form")<br />
%rest:POST<br />
%rest:form-param("message","{$message}", "(no message)")<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello-postman(<br />
$message as xs:string,<br />
$agent as xs:string*)<br />
as element(response)<br />
{<br />
&lt;response type='form'&gt;<br />
&lt;message&gt;{ $message }&lt;/message&gt;<br />
&lt;user-agent&gt;{ $agent }&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
};<br />
</pre><br />
<br />
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...<br />
<br />
<pre class="brush:shell"><br />
curl -i -X POST --data "content='CONTENT'" http://localhost:8984/form<br />
</pre><br />
<br />
...you will receive something similar to the following result:<br />
<br />
<pre class="brush:xml"><br />
&lt;response type="form"&gt;<br />
&lt;message&gt;CONTENT&lt;/message&gt;<br />
&lt;user-agent&gt;Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML<br />
like Gecko) Chrome/28.0.1500.72 Safari/537.36&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
=Annotations=<br />
<br />
This section lists all annotations provided by RESTXQ.<br />
<br />
==Constraints==<br />
<br />
Constraints restrict the HTTP requests that a resource function may process.<br />
<br />
===Paths===<br />
<br />
A resource function must have a single ''Path Annotation'' with a single string as argument. The function will be called if a URL matches the path segments and templates of the argument. ''Path templates'' contain variables in curly brackets, and map the corresponding segments of the request path to the arguments of the resource function.<br />
<br />
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/a/path/{$with}/some/{$variable}")<br />
function page:test($with, $variable as xs:integer) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
===HTTP Methods===<br />
<br />
The HTTP method annotations are equivalent to all [http://en.wikipedia.org/wiki/HTTP#Request_methods HTTP request methods] except for TRACE and CONNECT. Zero or more methods may be used on a function; if none is specified, the function will be invoked for each method.<br />
<br />
The following function will be called if GET or POST is used as request method:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:GET %rest:POST %rest:path("")<br />
function page:root() { <html/> };<br />
</pre><br />
<br />
The POST and PUT annotations may optionally take a string literal, which will be mapped to a named function parameter. Once again, the target variable must be embraced by curly brackets:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:PUT("{$data}") %rest:path("")<br />
function page:put($data) { "Data: " || $data };<br />
</pre><br />
<br />
===Content Negotiation===<br />
<br />
Two following annotations can be used to restrict functions to specific content types:<br />
<br />
* '''HTTP Content Types''': a function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given mime types. Example:<br />
<pre class="brush:xquery">%rest:consumes("application/xml", "text/xml")</pre><br />
* '''HTTP Accept''': a function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined mime types. Example:<br />
<pre class="brush:xquery">%rest:produces("application/atom+xml")</pre><br />
<br />
By default, both mime types are {{Code|*/*}}. Note that this annotation will ''not'' affect the content-type of the HTTP response. Instead, you will need to add a <code>[[#Output|%output:media-type]]</code> annotation.<br />
<br />
==Parameters==<br />
<br />
Parameters are optional annotations that can be used to bind additional values to function arguments:<br />
<br />
===Query Parameters===<br />
<br />
The value of the <em>first parameter</em>, if found in the [http://en.wikipedia.org/wiki/Query_string query string], will be assigned to the variable specified as <em>second parameter</em>. If no value is specified in the HTTP request, all additional parameters, if available, will be bound to the variable:<br />
<br />
<pre class="brush:xquery"><br />
%rest:query-param("parameter", "{$value}", "default")<br />
%rest:query-param("answer", "{$answer}", 42, 43, 44)<br />
%rest:query-param("search", "{$search-param}")<br />
</pre><br />
<br />
===HTML Form Fields===<br />
<br />
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are extracted from GET or POST requests.<br />
<br />
<pre class="brush:xquery"><br />
%rest:form-param("parameter", "{$value}", "default")<br />
</pre><br />
<br />
===HTTP Headers===<br />
<br />
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:header-param("User-Agent", "{$user-agent}")<br />
%rest:header-param("Referer", "{$referer}", "none")<br />
</pre><br />
<br />
===Cookies===<br />
<br />
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:cookie-param("username", "{$user}")<br />
%rest:cookie-param("authentication", "{$auth}", "no_auth")<br />
</pre><br />
<br />
=Response=<br />
<br />
By default, a successful request is answered with the HTTP status code {{Code|200}} (OK), and is followed by the given content; an erroneous request leads to an error code and an optional error message (e.g. {{Code|404}} for “resource not found”).<br />
<br />
==Custom Responses==<br />
<br />
Custom responses can be built from within XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and more optional child nodes that will be serialized as usual. A function that reacts on an unknown resource may look as follows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("") function page:404() {<br />
<rest:response><br />
<http:response status="404" message="I was not found."><br />
<http:header name="Content-Language" value="en"/><br />
<http:header name="Content-Type" value="text/html; charset=utf-8"/><br />
</http:response><br />
</rest:response><br />
};<br />
</pre><br />
<br />
==Forwards and Redirects==<br />
<br />
The two XML elements <code>rest:forward</code> and <code>rest:redirect</code> can be used in the context of [[Web Application]]s, precisely in the context of RESTXQ. These nodes allow e.g. multiple [[XQuery Update]]s in a row by redirecting to the RESTXQ path of updating functions. Both wrap a URL to a RESTXQ path. The wrapped URL should be properly encoded via <code>fn:encode-for-uri()</code>.<br />
<br />
Note that, currently, these elements are not part of RESTXQ specification.<br />
<br />
===rest:forward===<br />
<br />
Usage: wrap the location as follows<br />
<pre class="brush:xml"><rest:forward>{ $location }</rest:forward></pre><br />
<br />
This results in a server-side forwarding, which as well reduces traffic among client and server. A forwarding of this kind will not change the URL seen from the client's perspective.<br />
<br />
As an example, returning<br />
<pre class="brush:xml"><br />
<rest:forward>/hello/universe</rest:forward><br />
</pre><br />
would internally forward to http://localhost:8984/hello/universe<br />
<br />
===rest:redirect===<br />
<br />
<pre class="brush:xml"><rest:redirect>{ $location }</rest:redirect></pre><br />
<br />
…is basically an abbreviation for…<br />
<br />
<pre class="brush:xml"><br />
<rest:response><br />
<http:response status="302" message="Temporary Redirect"><br />
<http:header name="location" value="{ $location }"/><br />
</http:response><br />
</rest:response><br />
</pre><br />
<br />
The client decides whether to follow this redirection. Browsers usually will, tools like [http://curl.haxx.se/ curl] won’t unless {{Code|-L}} is specified.<br />
<br />
=Output=<br />
<br />
Similar to the [[REST#Content Type|REST]] interface, result serialization can be modified via [[XQuery 3.0#Serialization|XQuery 3.0 serialization parameters]]; in RESTXQ, serialization parameters may be specified in the query prolog, via annotations, or within REST response element. Global parameters are overwritten by more local parameters.<br />
<br />
==Query Prolog==<br />
<br />
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:<br />
<br />
<pre class="brush:xquery"><br />
declare option output:media-type 'text/plain';<br />
<br />
declare %rest:path("version1") function page:version1() {<br />
'Keep it simple, stupid'<br />
};<br />
</pre><br />
<br />
==Annotations==<br />
<br />
The serialization can also be parameterized via annotations:<br />
<br />
<pre class="brush:xquery"><br />
declare %output:media-type("text/plain") %rest:path("version2") function page:version2() {<br />
'Still somewhat simple.'<br />
};<br />
</pre><br />
<br />
==Response Element==<br />
<br />
The following example demonstrates how serialization parameters can be dynamically set within a query:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("version3") function page:version3() {<br />
<rest:response><br />
<output:serialization-parameters><br />
<output:media-type value='text/plain'/><br />
</output:serialization-parameters><br />
</rest:response>,<br />
'Well, not that simple anymore'<br />
};<br />
</pre><br />
<br />
The content type can also be overwritten by specifying an output {{Code|method}}. The following method mappings are available:<br />
<br />
* <code>xml</code> → <code>application/xml</code><br />
* <code>xhtml</code> → <code>text/html</code><br />
* <code>html</code> → <code>text/html</code><br />
* <code>text</code> → <code>text/plain</code><br />
* <code>raw</code> → <code>application/octet-stream</code><br />
* <code>json</code> or <code>jsonml</code> → <code>application/json</code><br />
<br />
By default, {{Code|application/xml}} is returned as content type. In the following example, XHTML headers will be generated, and {{Code|text/html}} will be set as content type:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("")<br />
%output:method("xhtml")<br />
%output:omit-xml-declaration("no")<br />
%output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN") <br />
%output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")<br />
function page:start()<br />
{<br />
<html xmlns="http://www.w3.org/1999/xhtml"><br />
<body>done</body><br />
</html><br />
};<br />
</pre><br />
<br />
=Error Handling=<br />
<br />
{{Mark|Introduced with Version 7.7:}}<br />
<br />
XQuery runtime errors can be processed via ''error annotations''. A single argument must be supplied, which represents the QName of the error to be caught. A wildcard {{Code|*}} may be specified to catch all possible errors. A function can only have a single error annotation:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:error("*") function page:error() {<br />
"An error occurred while processing your RESTXQ code!"<br />
};<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
The XQuery [[XQuery 3.0#Try.2FCatch|try/catch]] construct assigns error information to a number of pre-defined variables ({{Code|code}}, {{Code|description}}, {{Code|value}}, {{Code|module}}, {{Code|line-number}}, {{Code|column-number}}, {{Code|additional}}). These variables can be bound to variables via ''error parameter annotations'', which are specified the same way as [[#Query Parameters|query parameters]].<br />
<br />
Errors may occur unexpectedly. However, they can also be triggered by a query, as the following example shows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/check/{$user}") function page:check($user) {<br />
if($user = ('jack', 'lisa'))<br />
then 'User exists'<br />
else fn:error(xs:QName('err:user'), $user)<br />
};<br />
<br />
declare %rest:error("err:user") %rest:error-param("description", "{$user}")<br />
function page:user-error($user) {<br />
'User "' || $user || '" is unknown'<br />
};<br />
</pre><br />
<br />
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):<br />
<br />
<pre class="brush:xml"><br />
<error-page><br />
<error-code>404</error-code><br />
<location>/error404</location><br />
</error-page><br />
</pre><br />
<br />
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/error404") function page:error404() {<br />
"URL: " || request:attribute("javax.servlet.error.request_uri") || ", " || <br />
"Error message: " || request:attribute("javax.servlet.error.message")<br />
};<br />
</pre><br />
<br />
=Functions=<br />
<br />
The [[Request Module]] contains functions for accessing data related to the current HTTP request. Two additional modules exist for setting and retrieving server-side session data of the current user ([[Session Module]]) and all users known to the HTTP server ([[Sessions Module]]). With {{Version|7.7}}, a [[RESTXQ Module]] was added that provides functions for requesting RESTXQ base URIs and generating a [http://www.w3.org/Submission/wadl/ WADL description] of all services. Please note that the namespaces of all of these modules must be explicitly specified via module imports in the query prolog.<br />
<br />
The following example returns the current host name:<br />
<br />
<pre class="brush:xquery"><br />
import module namespace request = "http://exquery.org/ns/request";<br />
<br />
declare %rest:path("/host-name") function page:host() {<br />
'Remote host name: ' || request:remote-hostname()<br />
};<br />
</pre><br />
<br />
=File Upload=<br />
<br />
{{Mark|Introduced with Version 7.7:}}<br />
<br />
By using the content type {{Code|multipart/form-data}} uploaded files can be handled at server-side using RestXQ. A user is therefore able to upload files using a standard file upload input element. Suppose you have a simple form:<br />
<br />
<pre><br />
<form name="myForm" action="/upload" method="POST" enctype="multipart/form-data"><br />
<input type="hidden" name="example1" value="test" /><br />
<input type="file" name="files[]" multiple="multiple" /><br />
</form><br />
</pre><br />
<br />
All input elements will be put into a [[#Map module|map]] using the element name as key. File elements will be treated differently, as multiple files can be uploaded at once using the {{Code|multiple}} attribute. All files will be put into a map using the file name as key and this map is accessible using {{Code|files}} as key of the original map. See the following example to store all uploaded files into a specific directory and reports the size and the name of the file:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%restxq:POST("{$data}")<br />
%restxq:path("/upload")<br />
function page:upload($data)<br />
{<br />
let $example1 := $data('example1')<br />
let $files := $data('files')<br />
for $name in map:keys($files)<br />
let $content := $files($name)<br />
let $size := count(convert:binary-to-bytes($content))<br />
return (<br />
file:write-binary("files/", $content),<br />
<file size="{$size}">{$name}</file><br />
)<br />
};<br />
</pre><br />
<br />
The value of the hidden form element {{Code|example1}} is stored into {{Code|$example1}}. Additionally, you can calculate the size of the uploaded file using {{Code|count(convert:binary-to-bytes($content))}}.<br />
<br />
=References=<br />
<br />
RESTXQ has been proposed by [http://www.adamretter.org.uk/ Adam Retter].<br />
More information on all specifics can be found in the following two documents:<br />
<br />
* [http://www.adamretter.org.uk/papers/restful-xquery_january-2012.pdf RESTful XQuery, Standardised XQuery 3.0 Annotations for REST]. Paper, XMLPrague, 2012<br />
* [http://www.adamretter.org.uk/presentations/restxq_mugl_20120308.pdf RESTXQ]. Slides, MarkLogic User Group London, 2012<br />
* [http://exquery.github.com/exquery/exquery-restxq-specification/restxq-1.0-specification.html RESTXQ Specification], Unofficial Draft<br />
* [http://files.basex.org/xmlprague2013/slides/Develop-RESTXQ-WebApps-with-BaseX.pdf Web Application, RESTXQ Development]. Web Application Development with RESTXQ Slides from XMLPrague 2013<br />
<br />
=Changelog=<br />
<br />
;Version 7.7<br />
<br />
* Updated: RESTXQ function may now also be specified in main modules (suffix: {{Code|*.xq}}).<br />
* Updated: the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
* Added: [[#Error Handling|Error Handling]]<br />
<br />
;Version 7.5<br />
<br />
* Added: new XML elements {{Code|<rest:redirect/>}} and {{Code|<rest:forward/>}}<br />
<br />
[[Category:HTTP]]<br />
[[Category:Developer]]</div>Dirkhttps://docs.basex.org/index.php?title=RESTXQ&diff=9748RESTXQ2013-07-28T08:33:49Z<p>Dirk: </p>
<hr />
<div>This page presents one of the [[Web Application]] services. It describes how to use the RESTXQ API of BaseX.<br />
<br />
RESTXQ, introduced by [http://www.adamretter.org.uk/ Adam Retter], is a new API that facilitates the use of XQuery<br />
as a Server Side processing language for the Web. RESTXQ has been inspired by Java’s<br />
[http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services JAX-RS API]: it defines a pre-defined set of<br />
XQuery 3.0 annotations for mapping HTTP requests to XQuery functions, which in turn generate and return<br />
HTTP responses.<br />
<br />
Note that various details of the specification may be subject to change due to the early state of the API. Next, with {{Version|7.7}}, the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
<br />
=Usage=<br />
<br />
Since {{Version|7.7}}, the RESTXQ service is by default available at {{Code|http://localhost:8984/}}.<br />
<br />
All RESTXQ [[XQuery 3.0#Annotations|annotations]] are assigned to the {{Code|<nowiki>http://exquery.org/ns/restxq</nowiki>}} namespace, which is statically bound to the {{Code|restxq}} prefix (and since {{Version|7.7}}: {{Code|rest}}). A ''Resource Function'' is an XQuery function that has been marked up with RESTXQ annotations. When an HTTP request comes in, a resource function will be invoked that matches the constraints indicated by its annotations.<br />
<br />
Whenever a RESTXQ URL is requested, the [[Options#RESTXQPATH|RESTXQPATH]] module directory and its sub-directories will be parsed for library modules (detected by the extension {{Code|.xqm}}) and functions with RESTXQ annotations. Since {{Version|7.7}}, also main modules (detected by {{Code|.xq}}) will be parsed. All modules will be cached and parsed again when their timestamp changes.<br />
<br />
A simple RESTXQ module is shown below. It is part of a clean installation and available at http://localhost:8984/ .<br />
<br />
<pre class="brush:xquery">(: simplified version of the function found in webapp/restxq.xqm :)<br />
module namespace page = 'http://basex.org/examples/web-page';<br />
<br />
declare %rest:path("hello/{$world}")<br />
%rest:GET<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello($world as xs:string, $agent as xs:string*) {<br />
<response><br />
<title>Hello { $world }!</title><br />
<info>You requested this page with { $agent }.</info><br />
</response><br />
};</pre><br />
<br />
If the URI http://localhost:8984/hello/world is accessed, the result will be similar to:<br />
<br />
<pre class="brush:xml"><br />
&lt;response&gt;<br />
&lt;title&gt;Hello World!&lt;/title&gt;<br />
&lt;time&gt;The current time is: 18:42:02.306+02:00&lt;/time&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
The RESTXQ module contains yet another function:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("/form")<br />
%rest:POST<br />
%rest:form-param("message","{$message}", "(no message)")<br />
%rest:header-param("User-Agent", "{$agent}")<br />
function page:hello-postman(<br />
$message as xs:string,<br />
$agent as xs:string*)<br />
as element(response)<br />
{<br />
&lt;response type='form'&gt;<br />
&lt;message&gt;{ $message }&lt;/message&gt;<br />
&lt;user-agent&gt;{ $agent }&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
};<br />
</pre><br />
<br />
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...<br />
<br />
<pre class="brush:shell"><br />
curl -i -X POST --data "content='CONTENT'" http://localhost:8984/form<br />
</pre><br />
<br />
...you will receive something similar to the following result:<br />
<br />
<pre class="brush:xml"><br />
&lt;response type="form"&gt;<br />
&lt;message&gt;CONTENT&lt;/message&gt;<br />
&lt;user-agent&gt;Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML<br />
like Gecko) Chrome/28.0.1500.72 Safari/537.36&lt;/user-agent&gt;<br />
&lt;/response&gt;<br />
</pre><br />
<br />
=Annotations=<br />
<br />
This section lists all annotations provided by RESTXQ.<br />
<br />
==Constraints==<br />
<br />
Constraints restrict the HTTP requests that a resource function may process.<br />
<br />
===Paths===<br />
<br />
A resource function must have a single ''Path Annotation'' with a single string as argument. The function will be called if a URL matches the path segments and templates of the argument. ''Path templates'' contain variables in curly brackets, and map the corresponding segments of the request path to the arguments of the resource function.<br />
<br />
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/a/path/{$with}/some/{$variable}")<br />
function page:test($with, $variable as xs:integer) { ... };<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
===HTTP Methods===<br />
<br />
The HTTP method annotations are equivalent to all [http://en.wikipedia.org/wiki/HTTP#Request_methods HTTP request methods] except for TRACE and CONNECT. Zero or more methods may be used on a function; if none is specified, the function will be invoked for each method.<br />
<br />
The following function will be called if GET or POST is used as request method:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:GET %rest:POST %rest:path("")<br />
function page:root() { <html/> };<br />
</pre><br />
<br />
The POST and PUT annotations may optionally take a string literal, which will be mapped to a named function parameter. Once again, the target variable must be embraced by curly brackets:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:PUT("{$data}") %rest:path("")<br />
function page:put($data) { "Data: " || $data };<br />
</pre><br />
<br />
===Content Negotiation===<br />
<br />
Two following annotations can be used to restrict functions to specific content types:<br />
<br />
* '''HTTP Content Types''': a function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given mime types. Example:<br />
<pre class="brush:xquery">%rest:consumes("application/xml", "text/xml")</pre><br />
* '''HTTP Accept''': a function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined mime types. Example:<br />
<pre class="brush:xquery">%rest:produces("application/atom+xml")</pre><br />
<br />
By default, both mime types are {{Code|*/*}}. Note that this annotation will ''not'' affect the content-type of the HTTP response. Instead, you will need to add a <code>[[#Output|%output:media-type]]</code> annotation.<br />
<br />
==Parameters==<br />
<br />
Parameters are optional annotations that can be used to bind additional values to function arguments:<br />
<br />
===Query Parameters===<br />
<br />
The value of the <em>first parameter</em>, if found in the [http://en.wikipedia.org/wiki/Query_string query string], will be assigned to the variable specified as <em>second parameter</em>. If no value is specified in the HTTP request, all additional parameters, if available, will be bound to the variable:<br />
<br />
<pre class="brush:xquery"><br />
%rest:query-param("parameter", "{$value}", "default")<br />
%rest:query-param("answer", "{$answer}", 42, 43, 44)<br />
%rest:query-param("search", "{$search-param}")<br />
</pre><br />
<br />
===HTML Form Fields===<br />
<br />
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are extracted from GET or POST requests.<br />
<br />
<pre class="brush:xquery"><br />
%rest:form-param("parameter", "{$value}", "default")<br />
</pre><br />
<br />
===HTTP Headers===<br />
<br />
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:header-param("User-Agent", "{$user-agent}")<br />
%rest:header-param("Referer", "{$referer}", "none")<br />
</pre><br />
<br />
===Cookies===<br />
<br />
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:<br />
<br />
<pre class="brush:xquery"><br />
%rest:cookie-param("username", "{$user}")<br />
%rest:cookie-param("authentication", "{$auth}", "no_auth")<br />
</pre><br />
<br />
=Response=<br />
<br />
By default, a successful request is answered with the HTTP status code {{Code|200}} (OK), and is followed by the given content; an erroneous request leads to an error code and an optional error message (e.g. {{Code|404}} for “resource not found”).<br />
<br />
==Custom Responses==<br />
<br />
Custom responses can be built from within XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and more optional child nodes that will be serialized as usual. A function that reacts on an unknown resource may look as follows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("") function page:404() {<br />
<rest:response><br />
<http:response status="404" message="I was not found."><br />
<http:header name="Content-Language" value="en"/><br />
<http:header name="Content-Type" value="text/html; charset=utf-8"/><br />
</http:response><br />
</rest:response><br />
};<br />
</pre><br />
<br />
==Forwards and Redirects==<br />
<br />
The two XML elements <code>rest:forward</code> and <code>rest:redirect</code> can be used in the context of [[Web Application]]s, precisely in the context of RESTXQ. These nodes allow e.g. multiple [[XQuery Update]]s in a row by redirecting to the RESTXQ path of updating functions. Both wrap a URL to a RESTXQ path. The wrapped URL should be properly encoded via <code>fn:encode-for-uri()</code>.<br />
<br />
Note that, currently, these elements are not part of RESTXQ specification.<br />
<br />
===rest:forward===<br />
<br />
Usage: wrap the location as follows<br />
<pre class="brush:xml"><rest:forward>{ $location }</rest:forward></pre><br />
<br />
This results in a server-side forwarding, which as well reduces traffic among client and server. A forwarding of this kind will not change the URL seen from the client's perspective.<br />
<br />
As an example, returning<br />
<pre class="brush:xml"><br />
<rest:forward>/hello/universe</rest:forward><br />
</pre><br />
would internally forward to http://localhost:8984/hello/universe<br />
<br />
===rest:redirect===<br />
<br />
<pre class="brush:xml"><rest:redirect>{ $location }</rest:redirect></pre><br />
<br />
…is basically an abbreviation for…<br />
<br />
<pre class="brush:xml"><br />
<rest:response><br />
<http:response status="302" message="Temporary Redirect"><br />
<http:header name="location" value="{ $location }"/><br />
</http:response><br />
</rest:response><br />
</pre><br />
<br />
The client decides whether to follow this redirection. Browsers usually will, tools like [http://curl.haxx.se/ curl] won’t unless {{Code|-L}} is specified.<br />
<br />
=Output=<br />
<br />
Similar to the [[REST#Content Type|REST]] interface, result serialization can be modified via [[XQuery 3.0#Serialization|XQuery 3.0 serialization parameters]]; in RESTXQ, serialization parameters may be specified in the query prolog, via annotations, or within REST response element. Global parameters are overwritten by more local parameters.<br />
<br />
==Query Prolog==<br />
<br />
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:<br />
<br />
<pre class="brush:xquery"><br />
declare option output:media-type 'text/plain';<br />
<br />
declare %rest:path("version1") function page:version1() {<br />
'Keep it simple, stupid'<br />
};<br />
</pre><br />
<br />
==Annotations==<br />
<br />
The serialization can also be parameterized via annotations:<br />
<br />
<pre class="brush:xquery"><br />
declare %output:media-type("text/plain") %rest:path("version2") function page:version2() {<br />
'Still somewhat simple.'<br />
};<br />
</pre><br />
<br />
==Response Element==<br />
<br />
The following example demonstrates how serialization parameters can be dynamically set within a query:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("version3") function page:version3() {<br />
<rest:response><br />
<output:serialization-parameters><br />
<output:media-type value='text/plain'/><br />
</output:serialization-parameters><br />
</rest:response>,<br />
'Well, not that simple anymore'<br />
};<br />
</pre><br />
<br />
The content type can also be overwritten by specifying an output {{Code|method}}. The following method mappings are available:<br />
<br />
* <code>xml</code> → <code>application/xml</code><br />
* <code>xhtml</code> → <code>text/html</code><br />
* <code>html</code> → <code>text/html</code><br />
* <code>text</code> → <code>text/plain</code><br />
* <code>raw</code> → <code>application/octet-stream</code><br />
* <code>json</code> or <code>jsonml</code> → <code>application/json</code><br />
<br />
By default, {{Code|application/xml}} is returned as content type. In the following example, XHTML headers will be generated, and {{Code|text/html}} will be set as content type:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%rest:path("")<br />
%output:method("xhtml")<br />
%output:omit-xml-declaration("no")<br />
%output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN") <br />
%output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")<br />
function page:start()<br />
{<br />
<html xmlns="http://www.w3.org/1999/xhtml"><br />
<body>done</body><br />
</html><br />
};<br />
</pre><br />
<br />
=Error Handling=<br />
<br />
{{Mark|Introduced with Version 7.7:}}<br />
<br />
XQuery runtime errors can be processed via ''error annotations''. A single argument must be supplied, which represents the QName of the error to be caught. A wildcard {{Code|*}} may be specified to catch all possible errors. A function can only have a single error annotation:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:error("*") function page:error() {<br />
"An error occurred while processing your RESTXQ code!"<br />
};<br />
</pre><br />
<!-- TODO how matching works --><br />
<br />
The XQuery [[XQuery 3.0#Try.2FCatch|try/catch]] construct assigns error information to a number of pre-defined variables ({{Code|code}}, {{Code|description}}, {{Code|value}}, {{Code|module}}, {{Code|line-number}}, {{Code|column-number}}, {{Code|additional}}). These variables can be bound to variables via ''error parameter annotations'', which are specified the same way as [[#Query Parameters|query parameters]].<br />
<br />
Errors may occur unexpectedly. However, they can also be triggered by a query, as the following example shows:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/check/{$user}") function page:check($user) {<br />
if($user = ('jack', 'lisa'))<br />
then 'User exists'<br />
else fn:error(xs:QName('err:user'), $user)<br />
};<br />
<br />
declare %rest:error("err:user") %rest:error-param("description", "{$user}")<br />
function page:user-error($user) {<br />
'User "' || $user || '" is unknown'<br />
};<br />
</pre><br />
<br />
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):<br />
<br />
<pre class="brush:xml"><br />
<error-page><br />
<error-code>404</error-code><br />
<location>/error404</location><br />
</error-page><br />
</pre><br />
<br />
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:<br />
<br />
<pre class="brush:xquery"><br />
declare %rest:path("/error404") function page:error404() {<br />
"URL: " || request:attribute("javax.servlet.error.request_uri") || ", " || <br />
"Error message: " || request:attribute("javax.servlet.error.message")<br />
};<br />
</pre><br />
<br />
=Functions=<br />
<br />
The [[Request Module]] contains functions for accessing data related to the current HTTP request. Two additional modules exist for setting and retrieving server-side session data of the current user ([[Session Module]]) and all users known to the HTTP server ([[Sessions Module]]). With {{Version|7.7}}, a [[RESTXQ Module]] was added that provides functions for requesting RESTXQ base URIs and generating a [http://www.w3.org/Submission/wadl/ WADL description] of all services. Please note that the namespaces of all of these modules must be explicitly specified via module imports in the query prolog.<br />
<br />
The following example returns the current host name:<br />
<br />
<pre class="brush:xquery"><br />
import module namespace request = "http://exquery.org/ns/request";<br />
<br />
declare %rest:path("/host-name") function page:host() {<br />
'Remote host name: ' || request:remote-hostname()<br />
};<br />
</pre><br />
<br />
=File Upload=<br />
<br />
{{Mark|Introduced with Version 7.7:}}<br />
<br />
By using the content type {{Code|multipart/form-data}} uploaded files can be handled at server-side using RestXQ. A user is therefore able to upload files using a standard file upload input element. Suppose you have a simple form:<br />
<br />
<pre><br />
<form name="myForm" action="/upload" method="POST" enctype="multipart/form-data"><br />
<input type="hidden" name="example1" value="test" /><br />
<input type="file" name="files[]" multiple="multiple" /><br />
</form><br />
</pre><br />
<br />
All input elements will be put into a [[#Map module|map]] by using the element name as key. File elements will be treated differently as multiple files can be uploaded at once using the {{Code|multiple}} attribute. All files will be put into a map using the file name as key and this map is accessible using {{Code|files}} as key of the original map. See the following example to store all uploaded files into a specific directory:<br />
<br />
<pre class="brush:xquery"><br />
declare<br />
%restxq:POST("{$data}")<br />
%restxq:path("/upload")<br />
function page:upload($data)<br />
{<br />
let $example1 := $data('example1')<br />
let $files := $data('files')<br />
for $name in map:keys($files)<br />
let $content := $files($name)<br />
let $size := count(convert:binary-to-bytes($content))<br />
return file:write-binary("files/", $content)<br />
};<br />
</pre><br />
<br />
The value of the hidden form element {{Code|example1}} is stored into {{Code|$example1}}. Additionally, you can calculate the size of the uploaded file using {{Code|count(convert:binary-to-bytes($content))}}.<br />
<br />
=References=<br />
<br />
RESTXQ has been proposed by [http://www.adamretter.org.uk/ Adam Retter].<br />
More information on all specifics can be found in the following two documents:<br />
<br />
* [http://www.adamretter.org.uk/papers/restful-xquery_january-2012.pdf RESTful XQuery, Standardised XQuery 3.0 Annotations for REST]. Paper, XMLPrague, 2012<br />
* [http://www.adamretter.org.uk/presentations/restxq_mugl_20120308.pdf RESTXQ]. Slides, MarkLogic User Group London, 2012<br />
* [http://exquery.github.com/exquery/exquery-restxq-specification/restxq-1.0-specification.html RESTXQ Specification], Unofficial Draft<br />
* [http://files.basex.org/xmlprague2013/slides/Develop-RESTXQ-WebApps-with-BaseX.pdf Web Application, RESTXQ Development]. Web Application Development with RESTXQ Slides from XMLPrague 2013<br />
<br />
=Changelog=<br />
<br />
;Version 7.7<br />
<br />
* Updated: RESTXQ function may now also be specified in main modules (suffix: {{Code|*.xq}}).<br />
* Updated: the RESTXQ prefix has been changed from {{Code|restxq}} to {{Code|rest}}.<br />
* Added: [[#Error Handling|Error Handling]]<br />
<br />
;Version 7.5<br />
<br />
* Added: new XML elements {{Code|<rest:redirect/>}} and {{Code|<rest:forward/>}}<br />
<br />
[[Category:HTTP]]<br />
[[Category:Developer]]</div>Dirkhttps://docs.basex.org/index.php?title=Higher-Order_Functions&diff=9724Higher-Order Functions2013-07-11T22:50:33Z<p>Dirk: correct new signature</p>
<hr />
<div>This page talks about ''higher-order functions'' introduced with [[XQuery 3.0]]. The BaseX-specific <code>hof</code> module containing some more very usful functions can be found at [[Higher-Order Functions Module]].<br />
<br />
{{Version|7.7}}: In the upcoming version of the [http://www.w3.org/TR/xpath-functions-30 XQuery Functions and Operators] specification, some functions will be modified! Function arguments are now placed last in the function signature. Details are found below.<br />
<br />
=Function Items=<br />
<br />
Probably the most important new feature in XQuery 3.0 are ''function items'', i. e. items that act as functions, but can also be passed to and from other functions and expressions, making functions ''first-class citizens'' of the language.<br />
<br />
The [[XQuery_3.0#Function_Items|XQuery 3.0]] page goes into details on how function items can be obtained.<br />
<br />
== Function Types ==<br />
<br />
Like every XQuery item, function items have a ''sequence type''. It can be<br />
used to specify the ''arity'' (number of arguments the function takes) and<br />
the argument and result types.<br />
<br />
The most general function type is <code>function(*)</code>. It's the type of all<br />
function items. The following query for example goes through a list of XQuery<br />
items and, if it is a function item, prints its arity:<br />
<br />
<pre class="brush:xquery"><br />
for $item in (1, 'foo', fn:concat#3, function($a) { 42 * $a })<br />
where $item instance of function(*)<br />
return fn:function-arity($item)<br />
</pre><br />
''Result:'' <code>3 1</code><br />
<br />
The notation for specifying argument and return types is quite intuitive, as it<br />
closely resembles the function declaration. The XQuery function<br />
<br />
<pre class="brush:xquery"><br />
declare function local:char-at(<br />
$str as xs:string,<br />
$pos as xs:integer<br />
) as xs:string {<br />
fn:substring($str, $pos, 1)<br />
};<br />
</pre><br />
<br />
for example has the type <code>function(xs:string, xs:integer) as xs:string</code>. It isn't possible to specify only the argument and not the result<br />
type or the other way round. A good place-holder to use when no restriction<br />
is wanted is <code>item()*</code>, as it matches any XQuery value.<br />
<br />
Function types can also be nested. As an example we take <code>local:on-sequences</code>, which takes a function defined on single items and makes it work on sequences as well:<br />
<br />
<pre class="brush:xquery"><br />
declare function local:on-sequences(<br />
$fun as function(item()) as item()*<br />
) as function(item()*) as item()* {<br />
fn:for-each($fun, ?)<br />
};<br />
</pre><br />
We'll see later how <code>fn:for-each(...)</code> works. The type of <code>local:on-sequences(...)</code> on the other hand is easily constructed, if a bit long:<br />
<br />
<code>function(function(item()) as item()*) as function(item()*) as item()*</code>.<br />
<br />
=Higher-Order Functions=<br />
<br />
A ''higher-order function'' is a function that takes other functions as arguments and/or returns them as results. <code>fn:for-each</code> and <code>local:on-sequences</code> from the last chapter are nice examples.<br />
<br />
With the help of higher-order functions, one can extract common patterns of<br />
''behaviour'' and abstract them into a library function.<br />
<br />
== Higher-Order Functions on Sequences ==<br />
<br />
Some usage patterns on sequences are so common that the higher-order functions<br />
describing them are in the XQuery standard libraries. They are listed here, together<br />
with their possible XQuery implementation and some motivating examples.<br />
<br />
===fn:for-each===<br />
<br />
{{Mark|Updated with Version 7.7:}} the function has been renamed, and the arguments have been swapped.<br/><br />
<br />
{|<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|fn:for-each|$seq as item()*, $fun as function(item()) as item()*)|item()*}}<br/><font color='gray'>Old signature: fn:map($fun as function(item()) as item()*, $seq as item()*) as item()*</font><br />
|-<br />
| '''Summary'''<br />
|Applies the function item <code>$fun</code> to every element of the sequence <code>$seq</code> and returns all of the results as a sequence.<br />
|-<br />
| '''Examples'''<br />
|<br />
<ul><li>Squaring all numbers from 1 to 10:<br />
<pre class="brush:xquery"><br />
fn:for-each(1 to 10, math:pow(?, 2))<br />
</pre><br />
''Result:'' <code>1 4 9 16 25 36 49 64 81 100</code><br />
</li><br />
<li>Applying a list of functions to a string:<br />
<pre class="brush:xquery"><br />
let $fs := (<br />
fn:upper-case#1,<br />
fn:substring(?, 4),<br />
fn:string-length#1<br />
)<br />
return fn:for-each($fs, function($f) { $f('foobar') })<br />
</pre><br />
''Result:'' <code>FOOBAR bar 6</code><br />
</li></ul><br />
|-<br />
| '''XQuery 1.0'''<br />
|<pre class="brush:xquery"><br />
declare function local:for-each(<br />
$seq as item()*,<br />
$fun as function(item()) as item()*<br />
) as item()* {<br />
for $s in $seq<br />
return $fun($s)<br />
};<br />
</pre><br />
|}<br />
<br />
===fn:filter===<br />
<br />
{{Mark|Updated with Version 7.7:}} the arguments have been swapped.<br/><br />
<br />
{|<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|fn:filter|$seq as item()*, $pred as function(item()) as xs:boolean)|item()*}}<br /><font color='gray'>fn:filter($pred as function(item()) as xs:boolean, $seq as item()*) as item()*</font><br />
|-<br />
| '''Summary'''<br />
|Applies the boolean predicate <code>$pred</code> to all elements of the sequence <code>$seq</code>, returning those for which it returns <code>true()</code>.<br />
|-<br />
| '''Examples'''<br />
|<ul><li>All even integers until 10:<br />
<pre class="brush:xquery"><br />
fn:filter(1 to 10, function($x) { $x mod 2 eq 0 })<br />
</pre><br />
''Result:'' <code>2 4 6 8 10</code><br />
</li><br />
<li>Strings that start with an upper-case letter:<br />
<pre class="brush:xquery"><br />
let $first-upper := function($str) {<br />
let $first := fn:substring($str, 1, 1)<br />
return $first eq fn:upper-case($first)<br />
}<br />
return fn:filter(('FooBar', 'foo', 'BAR'), $first-upper)<br />
</pre><br />
''Result:'' <code>FooBar BAR</code><br />
</li><br />
<li>Inefficient prime number generator:<br />
<pre class="brush:xquery"><br />
let $is-prime := function($x) {<br />
$x gt 1 and (every $y in 2 to ($x - 1) satisfies $x mod $y ne 0)<br />
}<br />
return filter(1 to 20, $is-prime)<br />
</pre><br />
''Result:'' <code>2 3 5 7 11 13 17 19</code><br />
</li></ul><br />
|-<br />
| '''Note'''<br />
|<code>fn:filter</code> can be easily implemented with <code>fn:for-each</code>:<br />
<pre class="brush:xquery"><br />
declare function local:filter($seq, $pred) {<br />
for-each(<br />
$seq,<br />
function($x) {<br />
if($pred($x)) then $x else ()<br />
}<br />
)<br />
};<br />
</pre><br />
|-<br />
| '''XQuery 1.0'''<br />
|<pre class="brush:xquery"><br />
declare function local:filter(<br />
$seq as item()*,<br />
$pred as function(item()) as xs:boolean<br />
) as item()* {<br />
$seq[$pred(.)]<br />
};<br />
</pre><br />
|}<br />
<br />
===fn:for-each-pair===<br />
<br />
{{Mark|Updated with Version 7.7:}} the function has been renamed, and the arguments have been swapped.<br/><br />
<br />
{|<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|fn:for-each-pair|$seq1 as item()*, $seq2 as item()*, $fun as function(item(), item()) as item()*|item()*}}<br /><font color='gray'>Old signature: fn:map-pairs($fun as function(item(), item()) as item()*, $seq1 as item()*, $seq2 as item()*) as item()*</font><br />
|-<br />
| '''Summary'''<br />
|''zips'' the elements from the two sequences <code>$seq1</code> and <code>$seq2</code> together with the function <code>$f</code>. It stops after the shorter sequence ends.<br />
|-<br />
| '''Examples'''<br />
|<ul><li>Adding one to the numbers at odd positions:<br />
<pre class="brush:xquery"><br />
fn:for-each-pair(<br />
fn:for-each(1 to 10, function($x) { $x mod 2 }),<br />
(1, 1, 1, 1, 1),<br />
function($a, $b) { $a + $b }<br />
)<br />
</pre><br />
''Result:'' <code>2 1 2 1 2</code><br />
</li><br />
<li>Line numbering:<br />
<pre class="brush:xquery"><br />
let $number-lines := function($str) {<br />
fn:string-join(<br />
fn:for-each-pair(<br />
1 to 1000,<br />
tokenize($str, '\r?\n|\r'),<br />
concat(?, ': ', ?)<br />
),<br />
'&amp;#xa;'<br />
)<br />
}<br />
return $number-lines('hello world,<br />
how are you?')<br />
</pre><br />
''Result:''<br />
<pre><br />
1: hello world,<br />
2: how are you?<br />
</pre><br />
</li><br />
<li>Checking if a sequence is sorted:<br />
<pre class="brush:xquery"><br />
let $is-sorted := function($seq) {<br />
every $b in<br />
fn:for-each-pair(<br />
$seq,<br />
fn:tail($seq),<br />
function($a, $b) { $a le $b }<br />
)<br />
satisfies $b<br />
}<br />
return (<br />
$is-sorted(1 to 10),<br />
$is-sorted((1, 2, 42, 4, 5))<br />
)<br />
</pre><br />
''Result:'' <code>true false</code></li></ul><br />
|-<br />
| '''XQuery 1.0'''<br />
|<pre class="brush:xquery"><br />
declare function local:for-each-pair(<br />
$seq1 as item()*,<br />
$seq2 as item()*,<br />
$fun as function(item(), item()) as item()*<br />
) as item()* {<br />
for $pos in 1 to min((count($seq1), count($seq2)))<br />
return $fun($seq1[$pos], $seq2[$pos])<br />
};<br />
</pre><br />
|}<br />
<br />
== Folds ==<br />
<br />
A ''fold'', also called ''reduce'' or ''accumulate'' in other languages, is a very<br />
basic higher-order function on sequences. It starts from a seed value and incrementally<br />
builds up a result, consuming one element from the sequence at a time and combining it with<br />
the aggregate with a user-defined function.<br />
<br />
Folds are one solution to the problem of not having ''state'' in functional programs.<br />
Solving a problem in ''imperative'' programming languages often means repeatedly updating<br />
the value of variables, which isn't allowed in functional languages.<br />
<br />
Calculating the ''product'' of a sequence of integers for example is easy in <code>Java</code>:<br />
<pre class="brush:java"><br />
public int product(int[] seq) {<br />
int result = 1;<br />
for(int i : seq) {<br />
result = result * i;<br />
}<br />
return result;<br />
}<br />
</pre><br />
Nice and efficient implementations using folds will be given below.<br />
<br />
The ''linear'' folds on sequences come in two flavours. They differ in the direction in which they traverse the sequence:<br />
<br />
===fn:fold-left===<br />
<br />
{{Mark|Updated with Version 7.7:}} the <code>$seq</code> and <code>$fun</code> arguments have been swapped.<br/><br />
<br />
{|<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|fn:fold-left|$seq as item()*, $seed as item()*, $fun as function(item()*, item()) as item()*|item()*}}<br /><font color='gray'>Old signature: fn:fold-left</b>($fun as function(item()*, item()) as item()*, $seed as item()*, $seq as item()*) as item()*</font><br />
|-<br />
| '''Summary'''<br />
|The ''left fold'' traverses the sequence from the left.<br />
The query <code>fn:fold-left(1 to 5, 0, $f)</code> for example would be evaluated as:<br />
<pre class="brush:xquery"><br />
$f($f($f($f($f(0, 1), 2), 3), 4), 5)<br />
</pre><br />
|-<br />
| '''Examples'''<br />
|<ul><li>Product of a sequence of integers:<br />
<pre class="brush:xquery"><br />
let $product := fn:fold-left(?, 1,<br />
function($result, $i) { $result * $i }<br />
)<br />
return $product(1 to 5)<br />
</pre><br />
''Result:'' <code>120</code><br />
</li><br />
<li>Illustrating the evaluation order:<br />
<pre class="brush:xquery"><br />
fn:fold-left(1 to 5, '$seed',<br />
concat('$f(', ?, ', ', ?, ')')<br />
)<br />
</pre><br />
''Result:'' <code>$f($f($f($f($f($seed, 1), 2), 3), 4), 5)</code><br />
</li><br />
<li>Building a decimal number from digits:<br />
<pre class="brush:xquery"><br />
let $from-digits := fold-left(?, 0,<br />
function($n, $d) { 10 * $n + $d }<br />
)<br />
return (<br />
$from-digits(1 to 5),<br />
$from-digits((4, 2))<br />
)<br />
</pre><br />
''Result:'' <code>12345 42</code><br />
</li></ul><br />
|-<br />
| '''XQuery 1.0'''<br />
|As folds are more general than ''FLWOR'' expressions, the implementation isn't as concise as the former ones:<br />
<pre class="brush:xquery"><br />
declare function local:fold-left(<br />
$seq as item()*,<br />
$seed as item()*,<br />
$fun as function(item()*, item()) as item()*<br />
) as item()* {<br />
if(empty($seq)) then $seed<br />
else local:fold-left(<br />
fn:tail($seq),<br />
$fun($seed, fn:head($seq)),<br />
$fun<br />
) <br />
};<br />
</pre><br />
|}<br />
<br />
===fn:fold-right===<br />
<br />
{{Mark|Updated with Version 7.7:}} the {{Code|$seq}} and {{Code|$fun}} arguments have been swapped.<br/><br />
<br />
{|<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|fn:fold-right|$seq as item()*, $seed as item()*, $fun as function(item(), item()*|item()*}}<br /><font color='gray'>Old signature: fn:fold-right</b>($fun as function(item(), item()*) as item()*, $seed as item()*, $seq as item()*) as item()*</font><br />
|-<br />
| '''Summary'''<br />
|The ''right fold'' <code>fn:fold-right($seq, $seed, $fun)</code> traverses the from the right.<br />
The query <code>fn:fold-right(1 to 5, 0, $f)</code> for example would be evaluated as:<br />
<pre class="brush:xquery"><br />
$f(1, $f(2, $f(3, $f(4, $f(5, 0)))))<br />
</pre><br />
|-<br />
| '''Examples'''<br />
|<ul><li>Product of a sequence of integers:<br />
<pre class="brush:xquery"><br />
let $product := fn:fold-right(?, 1,<br />
function($i, $result) { $result * $i }<br />
)<br />
return $product(1 to 5)<br />
</pre><br />
''Result:'' <code>120</code><br />
</li><br />
<li>Illustrating the evaluation order:<br />
<pre class="brush:xquery"><br />
fn:fold-right(1 to 5, '$seed',<br />
concat('$f(', ?, ', ', ?, ')')<br />
)<br />
</pre><br />
''Result:'' <code>$f(1, $f(2, $f(3, $f(4, $f(5, $seed)))))</code><br />
</li><br />
<li>Reversing a sequence of items:<br />
<pre class="brush:xquery"><br />
let $reverse := fn:fold-right(?, (),<br />
function($item, $rev) {<br />
$rev, $item<br />
}<br />
)<br />
return $reverse(1 to 10)<br />
</pre><br />
''Result:'' <code>10 9 8 7 6 5 4 3 2 1</code><br />
</li></ul><br />
|-<br />
| '''XQuery 1.0'''<br />
|<pre class="brush:xquery"><br />
declare function local:fold-right(<br />
$seq as item()*,<br />
$seed as item()*,<br />
$fun as function(item(), item()*) as item()*<br />
) as item()* {<br />
if(empty($seq)) then $seed<br />
else $fun(<br />
fn:head($seq),<br />
local:fold-right(tail($seq), $seed, $fun)<br />
)<br />
};<br />
</pre><br />
Note that the order of the arguments of <code>$fun</code> are inverted compared to that in <code>fn:fold-left(...)</code>.<br />
|}<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=User:Dirk/Cluster&diff=9653User:Dirk/Cluster2013-06-22T08:36:45Z<p>Dirk: Created page with "This page talks about the BaseX-speficic <code>cluster</code> module to interact with the clustered mode of BaseX. It contains functionality to store and retrieve data in the clu..."</p>
<hr />
<div>This page talks about the BaseX-speficic <code>cluster</code> module to interact with the clustered mode of BaseX. It contains functionality to store and retrieve data in the cluster and to execute XQuery functions distributed over several nodes in the cluster.<br />
<br />
=Introduction=<br />
=Data-related functions=<br />
<br />
==cluster:store==<br />
<br />
{|<br />
|-<br />
| width='120' | '''Signatures'''<br />
|{{Func|cluster:store|$seq as item()*|item()*}}<br />
|-<br />
| '''Summary'''<br />
|summary<br />
|-<br />
| '''Examples'''<br />
|<br />
<ul><li>Explanation:<br />
<pre class="brush:xquery"><br />
cluster:store<br />
</pre><br />
''Result:'' <code>true</code><br />
</li></ul><br />
|<br />
|<br />
|<br />
|}<br />
<br />
==cluster:retrieve==<br />
<br />
=Query-related functions=<br />
<br />
==cluster:query==<br />
<br />
==cluster:for-each==<br />
<br />
=Config=</div>Dirkhttps://docs.basex.org/index.php?title=XQuery_Module&diff=9058XQuery Module2013-03-08T13:22:08Z<p>Dirk: added context example</p>
<hr />
<div>This [[Module Library|XQuery Module]] contains functions to evaluate XQuery strings and modules at runtime.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/xquery}} namespace, which is statically bound to the {{Code|xquery}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=Functions=<br />
<br />
==xquery:eval==<br />
{| width='100%'<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|xquery:eval|$query as xs:string|item()*}}<br />{{Func|xquery:eval|$query as xs:string, $bindings as map(*)|item()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Evaluates {{Code|$query}} as XQuery expression at runtime and returns the resulting items.<br />Variables and context items can be declared via {{Code|$bindings}}. The specified keys must be QNames or strings, the values can be arbitrary item sequences:<br />
* variables specified as QNames will be directly interpreted as variable name.<br />
* variables specified as xs:string may be prefixed with a dollar sign. Namespace can be specified using the [http://www.jclark.com/xml/xmlns.htm Clark Notation].<br />
* If the specified string is empty, the value will be bound to the context item.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXXQ0001|#Errors}} the query contains [[XQuery Update#Updating Expressions|updating expressions]].<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|xquery:eval("1+3")}} returns {{Code|4}}.<br /><br />
* You can bind the context and e.g. operate on a certain database only:<br /><br />
<pre class='brush:xquery'><br />
xquery:eval("//country", map{ '' := db:open('factbook') })<br />
</pre><br />
* The following expressions use strings as keys. All of them return 'XML':<br/><br />
<pre class='brush:xquery'><br />
xquery:eval(".", map{ '' := 'XML' })<br />
xquery:eval("$xml", map{ 'xml' := 'XML' }),<br />
xquery:eval("$xml", map{ '$xml' := 'XML' }),<br />
xquery:eval("declare namespace pref='URI'; $pref:xml", map{ '{URI}xml' := 'XML' }),<br />
</pre><br />
* The following expressions use QNames as keys. All of them return 'XML':<br/><br />
<pre class='brush:xquery'><br />
declare namespace pref = 'URI';<br />
xquery:eval("$xml", map{ xs:QName('xml') := 'XML' })<br />
xquery:eval("declare namespace pref='URI'; $pref:xml", map{ xs:QName('pref:xml') := 'XML' }),<br />
</pre><br />
|}<br />
<br />
==xquery:invoke==<br />
{| width='100%'<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|xquery:invoke|$uri as xs:string|item()*}}<br />{{Func|xquery:invoke|$expr as xs:string, $bindings as map(*)|item()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Opens {{Code|$uri}} as file, evaluates it as XQuery expression at runtime, and returns the resulting items.<br />The semantics of the {{Code|$bindings}} parameter is the same as for [[#xquery:eval|xquery:eval]].<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXXQ0001|#Errors}} the query contains [[XQuery Update#Updating Expressions|updating expressions]].<br />
|}<br />
<br />
==xquery:type==<br />
<br />
{| width='100%'<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|xquery:type|$expr as item()*|item()*}}<br />
|-<br />
| '''Summary'''<br />
|Similar to {{Code|fn:trace($expr, $msg)}}, but instead of a user-defined message, it emits the compile-time type and estimated result size of its argument.<br />
|}<br />
<br />
=Errors=<br />
<br />
{| width='100%' class="wikitable" width="100%"<br />
! width="5%"|Code<br />
! width="95%"|Description<br />
|-<br />
|{{Code|BXXQ0001}}<br />
|A dynamically evaluated query must not contain any [[XQuery Update#Updating Expressions|updating expressions]].<br />
|}<br />
<br />
=Changelog=<br />
<br />
This module was introduced with Version 7.3. Functions have been adopted from the obsolete Utility Module.<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=JSON_Module&diff=8404JSON Module2012-11-20T10:56:58Z<p>Dirk: </p>
<hr />
<div>This [[Module Library|XQuery Module]] contains functions to parse and serialize JSON documents. [http://www.json.org/ JSON (JavaScript Object Notation)] is a popular data exchange format for applications written in JavaScript. As there are notable differences between JSON and XML, no mapping exists that guarantees a lossless, bidirectional conversion between JSON and XML. For this reason, we offer two sets of functions in this module:<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/json}} namespace, which is statically bound to the {{Code|json}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=JSON Functions=<br />
<br />
[[#json:parse|json:parse]] and [[#json:serialize|json:serialize]] facilitate a lossless conversion from JSON to XML and back. The transformation is based on the following rules:<br />
# The resulting document has a {{Code|<json/>}} root node. <br />
# Names (keys) of objects are represented as elements:<br />
## Empty names are represented by a single underscore ({{Code|&lt;_&gt;...&lt;/_&gt;}}).<br />
## Underscore characters are rewritten to two underscores ({{Code|__}}).<br />
## A character that cannot be represented as NCName character is rewritten to an underscore and its four-digit Unicode.<br />
# As the members of arrays have no names, {{Code|&lt;value/&gt;}} is used as element name.<br />
# JSON values are represented as text nodes.<br />
# The types of values are represented in attributes:<br />
## The value types ''number'', ''boolean'', ''null'', ''object'' and ''array'' are represented by a {{Code|type}} attribute.<br />
## The ''string'' type is omitted, as it is treated as default type.<br />
## If a name has the same type throughout the document, the {{Code|type}} attribute will be omitted. Instead, the name will be listed in additional, type-specific attributes in the root node. The attributes are named by their type in the plural (''numbers'', ''booleans'', ''nulls'', ''objects'' and ''arrays''), and the attribute value contains all names with that type, separated by whitespaces.<br />
<br />
==json:parse==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|json:parse|$input as xs:string|element(json)}}<br />
|-<br />
| '''Summary'''<br />
|Converts the JSON document specified by {{Code|$input}} to XML, and returns the result as {{Code|element(json)}} instance. The converted XML document is both well readable and lossless, i.e., the converted document can be serialized back to the original JSON representation.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXJS0001|#Errors}} the specified input cannot be parsed as JSON document.<br />
|}<br />
<br />
==json:serialize==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|json:serialize|$input as node()|xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Serializes the node specified by {{Code|$input}} as JSON, and returns the result as {{Code|xs:string}} instance. The serialized node must conform to the syntax specified by the [[#json:parse|json:parse()]] function.<br />XML documents can also be serialized as JSON if the [[Serialization|Serialization Option]] {{Code|"method"}} is set to {{Code|"json"}}.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXJS0002|#Errors}} the specified node cannot be serialized as JSON document.<br />
|}<br />
<br />
==Examples==<br />
<br />
'''Example 1: Adds all JSON documents in a directory to a database'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
let $database := "database"<br />
for $name in file:list('.', false(), '*.json')<br />
let $file := file:read-text($name)<br />
let $json := json:parse($file)<br />
return db:add($database, document { $json }, $name) <br />
</pre><br />
<br />
'''Example 2: Converts a simple JSON string to XML'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
json:parse('{}')<br />
</pre><br />
<br />
'''Result:'''<br />
<pre class="brush:xml"><br />
<json objects="json"/><br />
</pre><br />
<br />
'''Example 3: Converts a JSON string with simple objects and arrays'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
json:parse('{<br />
"title": "Talk On Travel Pool",<br />
"link": "http://www.flickr.com/groups/talkontravel/pool/",<br />
"description": "Travel and vacation photos from around the world.",<br />
"modified": "2009-02-02T11:10:27Z",<br />
"generator": "http://www.flickr.com/"<br />
}')<br />
</pre><br />
<br />
'''Result:'''<br />
<pre class="brush:xml"><br />
<json objects="json"><br />
<title>Talk On Travel Pool</title><br />
<link>http://www.flickr.com/groups/talkontravel/pool/</link><br />
<description>Travel and vacation photos from around the world.</description><br />
<modified>2009-02-02T11:10:27Z</modified><br />
<generator>http://www.flickr.com/</generator><br />
</json><br />
</pre><br />
<br />
'''Example 4: Converts a JSON string with different data types'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
json:parse('{<br />
"first_name": "John",<br />
"last_name": "Smith",<br />
"age": 25,<br />
"address": {<br />
"street": "21 2nd Street",<br />
"city": "New York",<br />
"code": 10021<br />
},<br />
"phone": [<br />
{<br />
"type": "home",<br />
"number": "212 555-1234"<br />
},<br />
{<br />
"type": "mobile",<br />
"number": 1327724623<br />
}<br />
]<br />
}')<br />
</pre><br />
<br />
'''Result:'''<br />
<pre class="brush:xml"><br />
<json numbers="age code" arrays="phone" objects="json address value"><br />
<first__name>John</first__name><br />
<last__name>Smith</last__name><br />
<age>25</age><br />
<address><br />
<street>21 2nd Street</street><br />
<city>New York</city><br />
<code>10021</code><br />
</address><br />
<phone><br />
<value><br />
<type>home</type><br />
<number>212 555-1234</number><br />
</value><br />
<value><br />
<type>mobile</type><br />
<number type="number">1327724623</number><br />
</value><br />
</phone><br />
</json><br />
</pre><br />
<br />
=JsonML Functions=<br />
<br />
[[#json:serialize-ml|json:serialize-ml]] and [[#json:parse-ml|json:parse-ml]] are used to transform XML to JSON and back, using the [http://jsonml.org JsonML] dialect. JsonML can be used to transform arbitrary XML documents, but namespaces, comments and processing instructions will be discarded in the transformation process. More details are found in the official [http://jsonml.org/XML JsonML documentation].<br />
<br />
==json:serialize-ml==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|json:serialize-ml|$input as node()|xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Serializes the node specified by {{Code|$input}} and returns the result as {{Code|xs:string}} instance.<br />XML documents can also be output in the JsonML format by setting the [[Serialization|Serialization Option]] {{Code|"method"}} to {{Code|"jsonml"}}.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXJS0002|#Errors}} the specified value cannot be serialized.<br />
|}<br />
<br />
==json:parse-ml==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|json:parse-ml|$input as xs:string|element()}}<br />
|-<br />
| '''Summary'''<br />
|Converts the [http://jsonml.org JsonML] document specified by {{Code|$input}} to XML, and returns the result as {{Code|element()}} instance. The JSON input must conform to the JsonML specification to be successfully converted.<br />
|-<br />
| '''Errors'''<br />
|{{Error|BXJS0001|#Errors}} the specified input cannot be parsed as JsonML instance.<br />
|}<br />
<br />
==Examples==<br />
<br />
'''Example 1: Converts all XML documents in a database to JsonML and writes them to disk'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
for $doc in collection('json')<br />
let $name := document-uri($doc)<br />
let $json := json:serialize($doc)<br />
return file:write($name, $json)<br />
</pre><br />
<br />
'''Example 2: Converts a simple XML fragment to the JsonML format'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
json:serialize-ml(<xml/>)<br />
</pre><br />
<br />
'''Result:'''<br />
<pre><br />
["xml"]<br />
</pre><br />
<br />
'''Example 3: Converts an XML document with elements and text'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
json:serialize-ml(doc('flickr.xml'))<br />
</pre><br />
<br />
'''flickr.xml:'''<br />
<pre class="brush:xml"><br />
<flickr><br />
<title>Talk On Travel Pool</title><br />
<link>http://www.flickr.com/groups/talkontravel/pool/</link><br />
<description>Travel and vacation photos from around the world.</description><br />
<modified>2009-02-02T11:10:27Z</modified><br />
<generator>http://www.flickr.com/</generator><br />
</flickr><br />
</pre><br />
<br />
'''Result:'''<br />
<pre><br />
["flickr",<br />
["title",<br />
"Talk On Travel Pool"],<br />
["link",<br />
"http:\/\/www.flickr.com\/groups\/talkontravel\/pool\/"],<br />
["description",<br />
"Travel and vacation photos from around the world."],<br />
["modified",<br />
"2009-02-02T11:10:27Z"],<br />
["generator",<br />
"http:\/\/www.flickr.com\/"]]<br />
</pre><br />
<br />
'''Example 4: Converts a document with nested elements and attributes'''<br />
<br />
'''Query:'''<br />
<pre class="brush:xquery"><br />
json:serialize-ml(doc('input.xml'))<br />
</pre><br />
<br />
'''input.xml:'''<br />
<pre class="brush:xml"><br />
<address id='1'><br />
<!-- comments will be discarded --><br />
<last_name>Smith</last_name><br />
<age>25</age><br />
<address xmlns='will be dropped as well'><br />
<street>21 2nd Street</street><br />
<city>New York</city><br />
<code>10021</code><br />
</address><br />
<phone type='home'>212 555-1234</phone><br />
</address><br />
</pre><br />
<br />
'''Result:'''<br />
<pre><br />
["address", {"id":"1"},<br />
["last_name",<br />
"Smith"],<br />
["age",<br />
"25"],<br />
["address",<br />
["street",<br />
"21 2nd Street"],<br />
["city",<br />
"New York"],<br />
["code",<br />
"10021"]],<br />
["phone", {"type":"home"},<br />
"212 555-1234"]]<br />
</pre><br />
<br />
=Errors=<br />
<br />
{| class="wikitable" width="100%"<br />
! width="5%"|Code<br />
! width="95%"|Description<br />
|-<br />
|{{Code|BXJS0001}}<br />
|The specified input cannot be parsed as JSON document.<br />
|-<br />
|{{Code|BXJS0002}}<br />
|The specified node cannot be serialized as JSON document.<br />
|}<br />
<br />
=Changelog=<br />
<br />
The module was introduced with Version 7.0.<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=Random_Module&diff=7857Random Module2012-07-20T10:17:25Z<p>Dirk: </p>
<hr />
<div>This [[Module Library|XQuery Module]] contains non-deterministic functions for returning random values.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/random}} namespace, which is statically bound to the {{Code|random}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=Functions=<br />
<br />
==random:double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:double||xs:double}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a double value between 0.0 (inclusive) and 1.0 (exclusive).<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:integer==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:integer||xs:integer}}<br />{{Func|random:integer|$max as xs:integer|xs:integer}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an integer value, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive)<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-double|$seed as xs:integer, $num as xs:integer|xs:double*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values between 0.0 (inclusive) and 1.0 (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-integer==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-integer|$seed as xs:integer, $num as xs:integer|xs:integer*}}<br />{{Func|random:seeded-integer|$seed as xs:integer, $num as xs:integer, $max as xs:integer|xs:integer*}}<br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} integer values, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:gaussian==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:gaussian|$num as xs:integer|xs:double*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values. The random values are Gaussian (i.e. normally) distributed with the mean 0.0. and the derivation 1.0.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:uuid==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:uuid||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Creates a random universally unique identifier (UUID), represented as 128-bit value.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|math:uuid() eq math:uuid()}} will (most probably) return the boolean value {{Code|false}}.<br />
|}<br />
<br />
=Changelog=<br />
<br />
The module was introduced with Version 7.4. It includes some functionality which was previously located in the [[Math_Module|Math Module]].<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=Random_Module&diff=7848Random Module2012-07-19T17:09:44Z<p>Dirk: </p>
<hr />
<div>This [[Module Library|XQuery Module]] contains non-deterministic functions for returning random values.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/random}} namespace, which is statically bound to the {{Code|random}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=Functions=<br />
<br />
==random:double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:double||xs:double}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a double value between 0.0 (inclusive) and 1.0 (exclusive).<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:integer==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:integer||xs:integer}}<br />{{Func|random:integer|$max as xs:integer|xs:integer}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an integer value, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive)<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-double|$seed as xs:integer, $num as xs:integer|xs:double*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values between 0.0 (inclusive) and 1.0 (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-integer==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-integer|$seed as xs:integer, $num as xs:integer|xs:integer*}}<br />{{Func|random:seeded-integer|$seed as xs:integer, $num as xs:integer, $max as xs:integer|xs:integer*}}<br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} integer values, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:gaussian==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:gaussian|$num as xs:integer|xs:double*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values. The random values are Gaussian (i.e. normally) distributed with the mean 0.0. and the derivation 1.0.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:uuid==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:uuid||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Creates a random universally unique identifier (UUID), represented as 128-bit value.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|math:uuid() eq math:uuid()}} will (most probably) return the boolean value {{Code|false}}.<br />
|}<br />
<br />
=Changelog=<br />
<br />
The module was introduced with Version X. It includes functionality which was previously located in the [[Math_Module|Math Module]].<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=Random_Module&diff=7847Random Module2012-07-19T14:40:46Z<p>Dirk: </p>
<hr />
<div>This [[Module Library|XQuery Module]] contains non-deterministic functions for returning random values.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/random}} namespace, which is statically bound to the {{Code|random}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=Functions=<br />
<br />
==random:double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:double||xs:double()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a double value between 0.0 (inclusive) and 1.0 (exclusive).<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:integer==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:integer|$max as xs:integer?|xs:integer()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an integer value, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive)<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-double|$seed as xs:integer, $num as xs:integer|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values between 0.0 (inclusive) and 1.0 (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-integer==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-integer|$seed as xs:integer, $num as xs:integer, $max as xs:integer?|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} integer values, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:gaussian==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:gaussian|$num as xs:integer|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values. The random values are Gaussian (i.e. normally) distributed with the mean 0.0. and the derivation 1.0.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:uuid==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:uuid||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Creates a random universally unique identifier (UUID), represented as 128-bit value.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|math:uuid() eq math:uuid()}} will (most probably) return the boolean value {{Code|false}}.<br />
|}<br />
<br />
=Changelog=<br />
<br />
The module was introduced with Version X. It includes functionality which was previously located in the [[Math_Module|Math Module]].<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=User:Dirk&diff=7846User:Dirk2012-07-19T13:53:47Z<p>Dirk: </p>
<hr />
<div>Under Construction:<br />
<br />
* http://docs.basex.org/wiki/User:Dirk/Random_Module</div>Dirkhttps://docs.basex.org/index.php?title=Random_Module&diff=7845Random Module2012-07-19T13:53:02Z<p>Dirk: </p>
<hr />
<div>This [[Module Library|XQuery Module]] contains non-deterministic functions for returning random values.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/random}} namespace, which is statically bound to the {{Code|random}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=Functions=<br />
<br />
==random:random-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:random-double||xs:double()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a double value between 0.0 (inclusive) and 1.0 (exclusive).<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:random-int==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:random-int|$max as xs:integer?|xs:integer()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an integer value, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive)<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-random-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-random-int|$seed as xs:integer, $num as xs:integer|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values between 0.0 (inclusive) and 1.0 (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-random-int==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-random-int|$seed as xs:integer, $num as xs:integer, $max as xs:integer?|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} integer values, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:random-gaussian==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:random-gaussian|$num as xs:integer|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a sequence with {{Code|$num}} double values. The random values are Gaussian (i.e. normally) distributed with the mean 0.0. and the derivation 1.0.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:uuid==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:uuid||xs:string}}<br />
|-<br />
| '''Summary'''<br />
|Creates a random universally unique identifier (UUID), represented as 128-bit value.<br />
|-<br />
| '''Examples'''<br />
|<br />
* {{Code|math:uuid() eq math:uuid()}} will (most probably) return the boolean value {{Code|false}}.<br />
|}<br />
<br />
=Changelog=<br />
<br />
The module was introduced with Version X. It includes functionality which was previously located in the [[Math_Module|Math Module]].<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=Random_Module&diff=7844Random Module2012-07-19T13:50:33Z<p>Dirk: Created page with "This XQuery Module contains non-deterministic functions for returning random values. =Conventions= All functions in this module are assigned to the {{Code|ht..."</p>
<hr />
<div>This [[Module Library|XQuery Module]] contains non-deterministic functions for returning random values.<br />
<br />
=Conventions=<br />
<br />
All functions in this module are assigned to the {{Code|http://basex.org/modules/random}} namespace, which is statically bound to the {{Code|random}} prefix.<br/><br />
All errors are assigned to the {{Code|http://basex.org/errors}} namespace, which is statically bound to the {{Code|bxerr}} prefix.<br />
<br />
=Functions=<br />
<br />
==random:random-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:random-double||xs:double()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns a double value between 0.0 (inclusive) and 1.0 (exclusive).<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:random-int==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:random-int|$max as xs:integer?|xs:integer()}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an integer value, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive)<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-random-double==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-random-int|$seed as xs:integer, $num as xs:integer|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an sequence with {{Code|$num}} double values between 0.0 (inclusive) and 1.0 (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
==random:seeded-random-int==<br />
{|<br />
|-<br />
| width='90' | '''Signatures'''<br />
|{{Func|random:seeded-random-int|$seed as xs:integer, $num as xs:integer, $max as xs:integer?|xs:items()*}}<br /><br />
|-<br />
| '''Summary'''<br />
|Returns an sequence with {{Code|$num}} integer values, either in the whole integer range or between 0 (inclusive) and the given maximum (exclusive). The random values are created using the initial seed given in {{Code|$seed}}.<br /><br />
|-<br />
| <br />
|<br />
|}<br />
<br />
=Changelog=<br />
<br />
The module was introduced with Version X. It includes functionality which was previously located in the [[Math_Module|Math Module]].<br />
<br />
[[Category:XQuery]]</div>Dirkhttps://docs.basex.org/index.php?title=Command-Line_Options&diff=7814Command-Line Options2012-07-04T16:00:09Z<p>Dirk: </p>
<hr />
<div>This article is part of the [[Getting Started]] Guide.<br />
It gives more details on the command-line options of all BaseX [[Start Scripts|start scripts]].<br />
<br />
=BaseX GUI=<br />
;Launch the GUI:<br />
<pre><br />
$ basexgui [file]<br />
</pre><br />
<br />
One or more XML and XQuery files can be passed on as parameters. If an XML file is specified, a database instance is created from this file, or an existing database is opened. XQuery files are opened in the XQuery editor.<br />
<br />
=BaseX Standalone=<br />
;Launch the console mode:<br />
<pre><br />
$ basex<br />
BaseX [Standalone]<br />
Try "help" to get more information.<br />
> _</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basex -h<br />
BaseX [Standalone]<br />
Usage: basex [-bcdiLosuvVwxz] [query]<br />
[query] Execute query file or expression<br />
-b<pars> Bind external query variables<br />
-c<input> Execute commands from file or string<br />
-d Activate debugging mode<br />
-i<input> Open initial file or database<br />
-L Append newlines to query results<br />
-o<output> Write output to file<br />
-s<pars> Set serialization parameter(s)<br />
-u Write updates back to original files<br />
-v/V Show (all) process info<br />
-w Preserve whitespaces from input files<br />
-x Show query execution plan<br />
-z Skip output of results<br />
</pre><br />
<br />
The meaning of all flags is listed in the following. If an equivalent database option exists (which can be specified via the [[Commands#SET|SET]] command), it is listed as well:<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Examples<br />
|- valign="top"<br />
| {{Code|[query]}}<br />
| Evaluates an XQuery expression. If the specified input is a valid file reference or URL, its content will be evaluated instead.<br />
|<br />
|• {{Code|"doc('X')//head"}}<br/>• {{Code|query.xq}}<br/><br />
|- valign="top"<br />
| {{Code|-b&lt;pars&gt;}}<br />
| Binds external variables to XQuery expressions. This flag may be specified multiple times. Variables names and their values are delimited by equality signs (<code>=</code>). The names may be optionally prefixed with dollar signs. If a variable uses a namespace different to the default namespace, it can be specified with the [http://www.jclark.com/xml/xmlns.htm Clark Notation].<br />
| <code>[[Options#BINDINGS|BINDINGS]]</code><br />
|• <code>-b$v=example -q$v</code><br/>• <code>-b{URL}ln=value<br/>-q"declare namespace ns='URL'; $ns:ln"</code><br />
|- valign="top"<br />
| {{Code|-c&lt;input&gt;}}<br />
| Executes [[commands]]:<br />
* Several commands in the input can be separated by semicolons.<br />
* If the specified input is a valid file reference or URL, its content will be executed instead. Empty lines and lines starting with the number sign {{Code|#}} will be ignored.<br />
* Since {{Version|7.3}}, commands can also be specified in the [[Commands#XML Syntax|XML Syntax]].<br />
|<br />
|• {{Code|-c"list;info"}}<br/>• {{Code|-ccommands.txt}}<br/>• {{Code|-c"<info/>"}}<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Toggles the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-i&lt;input&gt;}}<br />
| Opens a database or XML document specified by the argument. The opened input may be further processed by an XQuery expression.<br />
|<br />
| {{Code|-iitems.xml -q"//item"}}<br />
|- valign="top"<br />
| {{Code|-L}}<br />
| Separates returned query items by newlines (instead of spaces) and appends a newline to the end of a result.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-o&lt;file&gt;}}<br />
| All command and query output is written to the specified file.<br />
|<br />
| {{Code|-o output.txt}}<br />
|- valign="top"<br />
| {{Code|-s&lt;pars&gt;}}<br />
| Specifies parameters for serializing XQuery results; see [[Serialization]] for more details. This flag may be specified multiple times. Key and values are separated by the equality sign (<code>=</code>).<br />
| <code>[[Options#SERIALIZER|SERIALIZER]]</code><br />
| <code>-smethod=text</code><br />
|- valign="top"<br />
| {{Code|-u}}<br />
| Modifies original files after evaluating XQuery Update expressions.<br />
| <code>[[Options#WRITEBACK|WRITEBACK]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-v}}<br />
| Prints process and timing information to the ''standard output''.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-V}}<br />
| Prints detailed query information to the ''standard output'', including details on the compilation and profiling steps.<br />
| <code>[[Options#QUERYINFO|QUERYINFO]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-w}}<br />
| By default, whitespaces around text nodes are chopped when a database is created. This flag can be specified to preserve whitespaces.<br />
| <code>[[Options#CHOP|CHOP]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-x}}<br />
| This flags turn on the output of the query execution plan, formatted in [[Options#XMLPLAN|XML]].<br />
| <code>[[Options#XMLPLAN|XMLPLAN]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Skips the serialization of XQuery results. This flag is useful if the query is profiled or analyzed.<br />
| <code>[[Options#SERIALIZE|SERIALIZE]]</code><br />
|<br />
|}<br />
<br />
Alls options can be specified multiple times. With {{Version|7.3}}, all options will be evaluated in the given order (in earlier versions, the sequential evaluation was limited to the specified inputs, query files, queries and commands, while all other options were initially set). The standard input can be parsed by specifying a single dash ({{Code|-}}) as argument.<br />
<br />
=BaseX Server=<br />
;Launch the server<br />
<pre><br />
$ basexserver<br />
BaseX [Server]<br />
Server was started.<br />
</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basexserver -h<br />
BaseX [Server]<br />
Usage: basexserver [-cdeipSz] [stop]<br />
stop Stop running server<br />
-c<cmds> Execute initial database commands<br />
-d Activate debugging mode<br />
-e<num> Set event port<br />
-i Enter interactive mode<br />
-p<num> Set server port<br />
-S Start as service<br />
-z Suppress logging<br />
</pre><br />
<br />
The flags have the following meaning (equivalent database options are shown in the table as well):<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Default<br />
! width='165' | Examples<br />
|- valign="top"<br />
| {{Code|stop}}<br />
| Stops an existing server instance and quits.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-c&lt;cmd&gt;}}<br />
| Launches database commands before the server itself is started. Several commands can be separated by semicolons.<br />
|<br />
|<br />
| {{Code|-c"open database;info"}}<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Turns on the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-e&lt;num&gt;}}<br />
| Specifies the port on which the server will send events to clients.<br />
| <code>[[Options#EVENTPORT|EVENTPORT]]</code><br />
| {{Code|1985}}<br />
| {{Code|-e9998}}<br />
|- valign="top"<br />
| {{Code|-i}}<br />
| Starts the interactive console mode, which can be used to enter database commands. This mode is similar to the default standalone and client mode.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-p&lt;num&gt;}}<br />
| Specifies the port on which the server will be addressable.<br />
| <code>[[Options#PORT|PORT]]</code><br />
| {{Code|1984}}<br />
| {{Code|-p9999}}<br />
|- valign="top"<br />
| {{Code|-S}}<br />
| Starts the server as service (i.e., in the background).<br />
|<br />
| <br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Does not generate any [[Logging|log files]].<br />
|<br />
| <br />
|}<br />
<br />
Multiple {{Code|-c}} and {{Code|-i}} flags can be specified. All other options will be set before any other operation takes place. The specified inputs, query files, queries and commands will be subsequently evaluated after that in the given order. The standard input can be parsed by specifying a single dash ({{Code|-}}) as argument.<br />
<br />
=BaseX Client=<br />
<br />
;Launch the console mode communicating with the server<br />
<br />
The user name and password will be requested. The default user/password combination is '''admin'''/'''admin''':<br />
<pre><br />
$ basexclient<br />
Username: admin<br />
Password: *****<br />
BaseX [Client]<br />
Try "help" to get more information.<br />
&gt; _<br />
</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basexclient -h<br />
BaseX [Client]<br />
Usage: basexclient [-bcdiLnopPsUvVwxz] [query]<br />
[query] Execute query file or expression<br />
-b<pars> Bind external query variables<br />
-c<input> Execute commands from file or string<br />
-d Activate debugging mode<br />
-i<input> Open initial file or database<br />
-L Append newlines to query results<br />
-n<name> Set server (host) name<br />
-o<output> Write output to file<br />
-p<num> Set server port<br />
-P<pass> Specify user password<br />
-s<pars> Set serialization parameter(s)<br />
-U<name> Specify user name<br />
-v/V Show (all) process info<br />
-w Preserve whitespaces from input files<br />
-x Show query execution plan<br />
-z Skip output of results<br />
</pre><br />
<br />
The flags have the following meaning (equivalent database options are shown in the table as well):<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Default<br />
! width='165' | Examples<br />
|- valign="top"<br />
| {{Code|[query]}}<br />
| Evaluates an XQuery expression. If the specified input is a valid file reference or URL, its content will be evaluated instead.<br />
|<br />
|<br />
|• {{Code|"doc('X')//head"}}<br/>• {{Code|query.xq}}<br/><br />
|- valign="top"<br />
| {{Code|-b&lt;pars&gt;}}<br />
| Binds external variables to XQuery expressions. This flag may be specified multiple times. Variables names and their values are delimited by equality signs (<code>=</code>). The names may be optionally prefixed with dollar signs. If a variable uses a namespace different to the default namespace, it can be specified with the [http://www.jclark.com/xml/xmlns.htm Clark Notation] or [http://www.w3.org/TR/xquery-30/#id-basics Expanded QName Notation].<br />
| <code>[[Options#BINDINGS|BINDINGS]]</code><br />
|<br />
|• <code>-b$v=example -q$v</code><br/>• <code>-b{URL}ln=value<br/>-q"declare namespace ns='URL'; $ns:ln"</code><br />
|- valign="top"<br />
| {{Code|-c&lt;input&gt;}}<br />
| Executes [[commands]]:<br />
* Several commands in the input can be separated by semicolons.<br />
* If the specified input is a valid file reference or URL, its content will be executed instead. Empty lines and lines starting with the number sign {{Code|#}} will be ignored.<br />
* Since {{Version|7.3}}, commands can also be specified in the [[Commands#XML Syntax|XML Syntax]].<br />
|<br />
|<br />
|• {{Code|-c"list;info"}}<br/>• {{Code|-ccommands.txt}}<br/>• {{Code|-c"<info/>"}}<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Toggles the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-i&lt;input&gt;}}<br />
| Opens a database or XML document specified by the argument. The opened input may be further processed by an XQuery expression.<br />
|<br />
|<br />
| {{Code|-iitems.xml -q"//item"}}<br />
|- valign="top"<br />
| {{Code|-L}}<br />
| Separates returned query items by newlines (instead of spaces) and appends a newline to the end of a result.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-n&lt;name&gt;}}<br />
| Specifies the host name on which the server is running.<br />
| <code>[[Options#HOST|HOST]]</code><br />
| {{Code|localhost}}<br />
| {{Code|-nserver.basex.org}}<br />
|- valign="top"<br />
| {{Code|-o&lt;file&gt;}}<br />
| All command and query output is written to the specified file.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-p&lt;num&gt;}}<br />
| Specifies the port on which the server is running.<br />
| <code>[[Options#PORT|PORT]]</code><br />
| {{Code|1984}}<br />
| {{Code|-p9999}}<br />
|- valign="top"<br />
| {{Code|-P&lt;pass&gt;}}<br />
| Specifies the user password. If this flag is omitted, the password will be requested on command line. ''Warning'': when the password is specified via this flag, it may be visible to others.<br />
|<br />
|<br />
| {{Code|-Uadmin -Padmin}}<br />
|- valign="top"<br />
| {{Code|-s&lt;pars&gt;}}<br />
| Specifies parameters for serializing XQuery results; see [[Serialization]] for more details. This flag may be specified multiple times. Key and values are separated by the equality sign (<code>=</code>).<br />
| <code>[[Options#SERIALIZER|SERIALIZER]]</code><br />
|<br />
| <code>-smethod=text</code><br />
|- valign="top"<br />
| {{Code|-U&lt;name&gt;}}<br />
| Specifies the user name. If this flag is omitted, the user name will be requested on command line. <br />
|<br />
|<br />
| {{Code|-Uadmin}}<br />
|- valign="top"<br />
| {{Code|-v}}<br />
| Prints process and timing information to the ''standard output''.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-V}}<br />
| Prints detailed query information to the ''standard output'', including details on the compilation and profiling steps.<br />
| <code>[[Options#QUERYINFO|QUERYINFO]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-w}}<br />
| By default, whitespaces around text nodes are chopped when a database is created. This flag can be specified to preserve whitespaces.<br />
| <code>[[Options#CHOP|CHOP]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-x}}<br />
| This flags turn on the output of the query execution plan, formatted in [[Options#XMLPLAN|XML]].<br />
| <code>[[Options#XMLPLAN|XMLPLAN]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Skips the serialization of XQuery results. This flag is useful if the query is profiled or analyzed.<br />
| <code>[[Options#SERIALIZE|SERIALIZE]]</code><br />
|<br />
|<br />
|}<br />
<br />
Alls options can be specified multiple times. With {{Version|7.3}}, all options will be evaluated in the given order (in earlier versions, the sequential evaluation was limited to the specified inputs, query files, queries and commands, while all other options were initially set). The standard input can be parsed by specifying a single dash ({{Code|-}}) as argument.<br />
<br />
=BaseX HTTP Server=<br />
<br />
;Launch the HTTP server:<br />
<pre><br />
$ basexhttp<br />
BaseX [Server]<br />
Server was started.<br />
2011-01-02 03:04:05.600:INFO::Logging to STDERR via org.mortbay.log.StdErrLog<br />
2011-01-02 03:04:05.700:INFO::jetty-6.1.26<br />
2011-01-02 03:04:05.800:INFO::Started SocketConnector@0.0.0.0:8984</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basexhttp -h<br />
BaseX [HTTP]<br />
Usage: basexhttp [-aAbdehkKlnpPRsStTUWXz] [stop]<br />
stop Stop running server<br />
-a Deactive SSL support<br />
-A Set https port<br />
-b<pass> Specify SSL password<br />
-d Activate debugging mode<br />
-e<num> Set event port<br />
-h<num> Set port of HTTP server<br />
-k<path> Path to the keystore<br />
-K<pass> Specify keystore password<br />
-l Start in local mode<br />
-n<name> Set host name of database server<br />
-p<num> Set port of database server<br />
-P<pass> Specify user password<br />
-R Deactivate REST service<br />
-s Specify port to stop HTTP server<br />
-S Start as service<br />
-t Path to the truststore<br />
-T Specify truststore password<br />
-U<name> Specify user name<br />
-W Deactivate WebDAV service<br />
-X Deactivate RESTXQ service<br />
-z Suppress logging<br />
</pre><br />
<br />
The flags have the following meaning (equivalent database options are shown in the table as well):<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Default<br />
! width='145' | Examples<br />
|- valign="top"<br />
| {{Code|stop}}<br />
| Stops a running HTTP server. By default, the database server will be stopped as well, unless one of the flags {{Code|-c}} or {{Code|-l}} is specified.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-a}}<br />
| Deactive the support for SSL connections.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-A}}<br />
| Specify the port used for HTTPS connections.<br />
| <code>[[Options#HTTPSPORT|HTTPSPORT]]</code><br />
| 8989<br />
| -A8988<br />
|- valign="top"<br />
| {{Code|-b}}<br />
| Specify the password for this SSL certificate.<br />
| <code>[[Options#SSLPASSWORD|SSLPASSWORD]]</code><br />
|<br />
| -bPassword<br />
|- valign="top"<br />
| {{Code|-c}}<br />
| Starts the server in ''client mode'', and sends all commands to a database server instance.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Turns on the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-e&lt;num&gt;}}<br />
| Specifies the port on which the server will send events to clients.<br />
| <code>[[Options#EVENTPORT|EVENTPORT]]</code><br />
| {{Code|1985}}<br />
| {{Code|-e9998}}<br />
|- valign="top"<br />
| {{Code|-h&lt;num&gt;}}<br />
| Specifies the port on which the HTTP server will be addressable. This port is e.g. specified in the HTTP URLs.<br />
| <code>[[Options#HTTPPORT|HTTPPORT]]</code><br />
| {{Code|8984}}<br />
| {{Code|-h9999}}<br />
|- valign="top"<br />
| {{Code|-k}}<br />
| Path to the keystore file<br />
| <code>[[Options#KEYSTORE|KEYSTORE]]</code><br />
| BaseXSSL/keystore<br />
| -k/temp/certify<br />
|- valign="top"<br />
| {{Code|-K}}<br />
| Specify the password for the keystore.<br />
| <code>[[Options#KEYSTOREPASSWORD|KEYSTOREPASSWORD]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-l}}<br />
| Starts the server in ''local mode'', and executes all commands in the embedded database context.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-n&lt;name&gt;}}<br />
| Specifies the host name on which the server is running.<br />
| <code>[[Options#HOST|HOST]]</code><br />
| {{Code|localhost}}<br />
| {{Code|-nserver.basex.org}}<br />
|- valign="top"<br />
| {{Code|-p&lt;num&gt;}}<br />
| Specifies the port on which the BaseX Server will be addressable.<br />
| <code>[[Options#SERVERPORT|SERVERPORT]]</code><br />
| {{Code|1984}}<br />
| {{Code|-p9998}}<br />
|- valign="top"<br />
| {{Code|-P&lt;pass&gt;}}<br />
| Specifies the user password, which will be used by the HTTP services to open a new session. If this flag is omitted, the password will be requested on command line. ''Warning'': when the password is specified on command-line, it may be visible to others.<br />
|<br />
| {{Code|admin}}<br />
| {{Code|-Uadmin -Padmin}}<br />
|- valign="top"<br />
| {{Code|-R}}<br />
| Deactivates the [[REST]] service.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-s&lt;num&gt;}}<br />
| Specifies the port that will be used to stop the HTTP server.<br />
| <code>[[Options#STOPPORT|STOPPORT]]</code><br />
|<br />
| <br />
|- valign="top"<br />
| {{Code|-S}}<br />
| Starts the server as service (i.e., in the background).<br />
|<br />
| <br />
|- valign="top"<br />
| {{Code|-t}}<br />
| Path to the truststore file.<br />
| <code>[[Options#TRUSTSTORE|TRUSTSTORE]]</code><br />
| BaseXSSL/keystore<br />
| -t/temp/keystore<br />
|- valign="top"<br />
| {{Code|-T}}<br />
| Specify the password for the truststore.<br />
| <code>[[Options#TRUSTSTOREPASSWORD|TRUSTSTOREPASSWORD]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-U&lt;name&gt;}}<br />
| Specifies the user name, which will be used by the HTTP services for opening a new session. If this flag is omitted, the password will be requested on command line.<br />
|<br />
| {{Code|admin}}<br />
| {{Code|-Uadmin}}<br />
|- valign="top"<br />
| {{Code|-W}}<br />
| Deactivates the [[WebDAV]] service.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-X}}<br />
| Deactivates the [[RESTXQ]] service.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Does not generate any [[Logging|log files]].<br />
|<br />
| <br />
|}<br />
<br />
Some options can also be triggered by setting the following system properties:<br />
<br />
* {{Code|org.basex.user}}: user name for opening new sessions<br />
* {{Code|org.basex.password}}: user password for opening new sessions<br />
* {{Code|org.basex.mode}}: by default, the HTTP server also starts an instance of the database server. If the mode is set to {{Code|local}}, an embedded database context is used for executing commands. If the mode is set to {{Code|client}}, all commands are sent to an existing database server instance.<br />
* {{Code|org.basex.path}}: path to the BaseX [[Configuration|Home Directory]]<br />
<br />
=Changelog=<br />
<br />
; Upcoming version<br />
<br />
* Added: Support for SSL, added relevant Options {{Code|-a}}, {{Code|-A}}, {{Code|-b}}, {{Code|-k}}, {{Code|-K}}, {{Code|-t}}, {{Code|-T}}<br />
<br />
; Version 7.3:<br />
<br />
* Updated: all options are now evaluated in the given order<br />
* Updated: {{Code|-i}} creates main-memory representations for specified sources<br />
* Updated: Options {{Code|-C}}/{{Code|-c}} and {{Code|-q}}/{{Code|[query]}} merged<br />
* Updated: Option {{Code|-L}} also separates serialized items with newlines (instead of spaces)<br />
<br />
; Version 7.2:<br />
<br />
* Added: RESTXQ Service<br />
<br />
; Version 7.1.1:<br />
<br />
* Added: Options {{Code|-C}} and {{Code|-L}} in standalone and client mode<br />
<br />
; Version 7.1:<br />
<br />
* Updated: Multiple query files and {{Code|-c}}/{{Code|-i}}/{{Code|-q}} flags can be specified.<br />
<br />
[[Category:Beginner]]</div>Dirkhttps://docs.basex.org/index.php?title=Command-Line_Options&diff=7813Command-Line Options2012-07-04T11:37:44Z<p>Dirk: </p>
<hr />
<div>This article is part of the [[Getting Started]] Guide.<br />
It gives more details on the command-line options of all BaseX [[Start Scripts|start scripts]].<br />
<br />
=BaseX GUI=<br />
;Launch the GUI:<br />
<pre><br />
$ basexgui [file]<br />
</pre><br />
<br />
One or more XML and XQuery files can be passed on as parameters. If an XML file is specified, a database instance is created from this file, or an existing database is opened. XQuery files are opened in the XQuery editor.<br />
<br />
=BaseX Standalone=<br />
;Launch the console mode:<br />
<pre><br />
$ basex<br />
BaseX [Standalone]<br />
Try "help" to get more information.<br />
> _</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basex -h<br />
BaseX [Standalone]<br />
Usage: basex [-bcdiLosuvVwxz] [query]<br />
[query] Execute query file or expression<br />
-b<pars> Bind external query variables<br />
-c<input> Execute commands from file or string<br />
-d Activate debugging mode<br />
-i<input> Open initial file or database<br />
-L Append newlines to query results<br />
-o<output> Write output to file<br />
-s<pars> Set serialization parameter(s)<br />
-u Write updates back to original files<br />
-v/V Show (all) process info<br />
-w Preserve whitespaces from input files<br />
-x Show query execution plan<br />
-z Skip output of results<br />
</pre><br />
<br />
The meaning of all flags is listed in the following. If an equivalent database option exists (which can be specified via the [[Commands#SET|SET]] command), it is listed as well:<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Examples<br />
|- valign="top"<br />
| {{Code|[query]}}<br />
| Evaluates an XQuery expression. If the specified input is a valid file reference or URL, its content will be evaluated instead.<br />
|<br />
|• {{Code|"doc('X')//head"}}<br/>• {{Code|query.xq}}<br/><br />
|- valign="top"<br />
| {{Code|-b&lt;pars&gt;}}<br />
| Binds external variables to XQuery expressions. This flag may be specified multiple times. Variables names and their values are delimited by equality signs (<code>=</code>). The names may be optionally prefixed with dollar signs. If a variable uses a namespace different to the default namespace, it can be specified with the [http://www.jclark.com/xml/xmlns.htm Clark Notation].<br />
| <code>[[Options#BINDINGS|BINDINGS]]</code><br />
|• <code>-b$v=example -q$v</code><br/>• <code>-b{URL}ln=value<br/>-q"declare namespace ns='URL'; $ns:ln"</code><br />
|- valign="top"<br />
| {{Code|-c&lt;input&gt;}}<br />
| Executes [[commands]]:<br />
* Several commands in the input can be separated by semicolons.<br />
* If the specified input is a valid file reference or URL, its content will be executed instead. Empty lines and lines starting with the number sign {{Code|#}} will be ignored.<br />
* Since {{Version|7.3}}, commands can also be specified in the [[Commands#XML Syntax|XML Syntax]].<br />
|<br />
|• {{Code|-c"list;info"}}<br/>• {{Code|-ccommands.txt}}<br/>• {{Code|-c"<info/>"}}<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Toggles the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-i&lt;input&gt;}}<br />
| Opens a database or XML document specified by the argument. The opened input may be further processed by an XQuery expression.<br />
|<br />
| {{Code|-iitems.xml -q"//item"}}<br />
|- valign="top"<br />
| {{Code|-L}}<br />
| Separates returned query items by newlines (instead of spaces) and appends a newline to the end of a result.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-o&lt;file&gt;}}<br />
| All command and query output is written to the specified file.<br />
|<br />
| {{Code|-o output.txt}}<br />
|- valign="top"<br />
| {{Code|-s&lt;pars&gt;}}<br />
| Specifies parameters for serializing XQuery results; see [[Serialization]] for more details. This flag may be specified multiple times. Key and values are separated by the equality sign (<code>=</code>).<br />
| <code>[[Options#SERIALIZER|SERIALIZER]]</code><br />
| <code>-smethod=text</code><br />
|- valign="top"<br />
| {{Code|-u}}<br />
| Modifies original files after evaluating XQuery Update expressions.<br />
| <code>[[Options#WRITEBACK|WRITEBACK]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-v}}<br />
| Prints process and timing information to the ''standard output''.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-V}}<br />
| Prints detailed query information to the ''standard output'', including details on the compilation and profiling steps.<br />
| <code>[[Options#QUERYINFO|QUERYINFO]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-w}}<br />
| By default, whitespaces around text nodes are chopped when a database is created. This flag can be specified to preserve whitespaces.<br />
| <code>[[Options#CHOP|CHOP]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-x}}<br />
| This flags turn on the output of the query execution plan, formatted in [[Options#XMLPLAN|XML]].<br />
| <code>[[Options#XMLPLAN|XMLPLAN]]</code><br />
|<br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Skips the serialization of XQuery results. This flag is useful if the query is profiled or analyzed.<br />
| <code>[[Options#SERIALIZE|SERIALIZE]]</code><br />
|<br />
|}<br />
<br />
Alls options can be specified multiple times. With {{Version|7.3}}, all options will be evaluated in the given order (in earlier versions, the sequential evaluation was limited to the specified inputs, query files, queries and commands, while all other options were initially set). The standard input can be parsed by specifying a single dash ({{Code|-}}) as argument.<br />
<br />
=BaseX Server=<br />
;Launch the server<br />
<pre><br />
$ basexserver<br />
BaseX [Server]<br />
Server was started.<br />
</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basexserver -h<br />
BaseX [Server]<br />
Usage: basexserver [-cdeipSz] [stop]<br />
stop Stop running server<br />
-c<cmds> Execute initial database commands<br />
-d Activate debugging mode<br />
-e<num> Set event port<br />
-i Enter interactive mode<br />
-p<num> Set server port<br />
-S Start as service<br />
-z Suppress logging<br />
</pre><br />
<br />
The flags have the following meaning (equivalent database options are shown in the table as well):<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Default<br />
! width='165' | Examples<br />
|- valign="top"<br />
| {{Code|stop}}<br />
| Stops an existing server instance and quits.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-c&lt;cmd&gt;}}<br />
| Launches database commands before the server itself is started. Several commands can be separated by semicolons.<br />
|<br />
|<br />
| {{Code|-c"open database;info"}}<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Turns on the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-e&lt;num&gt;}}<br />
| Specifies the port on which the server will send events to clients.<br />
| <code>[[Options#EVENTPORT|EVENTPORT]]</code><br />
| {{Code|1985}}<br />
| {{Code|-e9998}}<br />
|- valign="top"<br />
| {{Code|-i}}<br />
| Starts the interactive console mode, which can be used to enter database commands. This mode is similar to the default standalone and client mode.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-p&lt;num&gt;}}<br />
| Specifies the port on which the server will be addressable.<br />
| <code>[[Options#PORT|PORT]]</code><br />
| {{Code|1984}}<br />
| {{Code|-p9999}}<br />
|- valign="top"<br />
| {{Code|-S}}<br />
| Starts the server as service (i.e., in the background).<br />
|<br />
| <br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Does not generate any [[Logging|log files]].<br />
|<br />
| <br />
|}<br />
<br />
Multiple {{Code|-c}} and {{Code|-i}} flags can be specified. All other options will be set before any other operation takes place. The specified inputs, query files, queries and commands will be subsequently evaluated after that in the given order. The standard input can be parsed by specifying a single dash ({{Code|-}}) as argument.<br />
<br />
=BaseX Client=<br />
<br />
;Launch the console mode communicating with the server<br />
<br />
The user name and password will be requested. The default user/password combination is '''admin'''/'''admin''':<br />
<pre><br />
$ basexclient<br />
Username: admin<br />
Password: *****<br />
BaseX [Client]<br />
Try "help" to get more information.<br />
&gt; _<br />
</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basexclient -h<br />
BaseX [Client]<br />
Usage: basexclient [-bcdiLnopPsUvVwxz] [query]<br />
[query] Execute query file or expression<br />
-b<pars> Bind external query variables<br />
-c<input> Execute commands from file or string<br />
-d Activate debugging mode<br />
-i<input> Open initial file or database<br />
-L Append newlines to query results<br />
-n<name> Set server (host) name<br />
-o<output> Write output to file<br />
-p<num> Set server port<br />
-P<pass> Specify user password<br />
-s<pars> Set serialization parameter(s)<br />
-U<name> Specify user name<br />
-v/V Show (all) process info<br />
-w Preserve whitespaces from input files<br />
-x Show query execution plan<br />
-z Skip output of results<br />
</pre><br />
<br />
The flags have the following meaning (equivalent database options are shown in the table as well):<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Default<br />
! width='165' | Examples<br />
|- valign="top"<br />
| {{Code|[query]}}<br />
| Evaluates an XQuery expression. If the specified input is a valid file reference or URL, its content will be evaluated instead.<br />
|<br />
|<br />
|• {{Code|"doc('X')//head"}}<br/>• {{Code|query.xq}}<br/><br />
|- valign="top"<br />
| {{Code|-b&lt;pars&gt;}}<br />
| Binds external variables to XQuery expressions. This flag may be specified multiple times. Variables names and their values are delimited by equality signs (<code>=</code>). The names may be optionally prefixed with dollar signs. If a variable uses a namespace different to the default namespace, it can be specified with the [http://www.jclark.com/xml/xmlns.htm Clark Notation] or [http://www.w3.org/TR/xquery-30/#id-basics Expanded QName Notation].<br />
| <code>[[Options#BINDINGS|BINDINGS]]</code><br />
|<br />
|• <code>-b$v=example -q$v</code><br/>• <code>-b{URL}ln=value<br/>-q"declare namespace ns='URL'; $ns:ln"</code><br />
|- valign="top"<br />
| {{Code|-c&lt;input&gt;}}<br />
| Executes [[commands]]:<br />
* Several commands in the input can be separated by semicolons.<br />
* If the specified input is a valid file reference or URL, its content will be executed instead. Empty lines and lines starting with the number sign {{Code|#}} will be ignored.<br />
* Since {{Version|7.3}}, commands can also be specified in the [[Commands#XML Syntax|XML Syntax]].<br />
|<br />
|<br />
|• {{Code|-c"list;info"}}<br/>• {{Code|-ccommands.txt}}<br/>• {{Code|-c"<info/>"}}<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Toggles the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-i&lt;input&gt;}}<br />
| Opens a database or XML document specified by the argument. The opened input may be further processed by an XQuery expression.<br />
|<br />
|<br />
| {{Code|-iitems.xml -q"//item"}}<br />
|- valign="top"<br />
| {{Code|-L}}<br />
| Separates returned query items by newlines (instead of spaces) and appends a newline to the end of a result.<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-n&lt;name&gt;}}<br />
| Specifies the host name on which the server is running.<br />
| <code>[[Options#HOST|HOST]]</code><br />
| {{Code|localhost}}<br />
| {{Code|-nserver.basex.org}}<br />
|- valign="top"<br />
| {{Code|-o&lt;file&gt;}}<br />
| All command and query output is written to the specified file.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-p&lt;num&gt;}}<br />
| Specifies the port on which the server is running.<br />
| <code>[[Options#PORT|PORT]]</code><br />
| {{Code|1984}}<br />
| {{Code|-p9999}}<br />
|- valign="top"<br />
| {{Code|-P&lt;pass&gt;}}<br />
| Specifies the user password. If this flag is omitted, the password will be requested on command line. ''Warning'': when the password is specified via this flag, it may be visible to others.<br />
|<br />
|<br />
| {{Code|-Uadmin -Padmin}}<br />
|- valign="top"<br />
| {{Code|-s&lt;pars&gt;}}<br />
| Specifies parameters for serializing XQuery results; see [[Serialization]] for more details. This flag may be specified multiple times. Key and values are separated by the equality sign (<code>=</code>).<br />
| <code>[[Options#SERIALIZER|SERIALIZER]]</code><br />
|<br />
| <code>-smethod=text</code><br />
|- valign="top"<br />
| {{Code|-U&lt;name&gt;}}<br />
| Specifies the user name. If this flag is omitted, the user name will be requested on command line. <br />
|<br />
|<br />
| {{Code|-Uadmin}}<br />
|- valign="top"<br />
| {{Code|-v}}<br />
| Prints process and timing information to the ''standard output''.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-V}}<br />
| Prints detailed query information to the ''standard output'', including details on the compilation and profiling steps.<br />
| <code>[[Options#QUERYINFO|QUERYINFO]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-w}}<br />
| By default, whitespaces around text nodes are chopped when a database is created. This flag can be specified to preserve whitespaces.<br />
| <code>[[Options#CHOP|CHOP]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-x}}<br />
| This flags turn on the output of the query execution plan, formatted in [[Options#XMLPLAN|XML]].<br />
| <code>[[Options#XMLPLAN|XMLPLAN]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Skips the serialization of XQuery results. This flag is useful if the query is profiled or analyzed.<br />
| <code>[[Options#SERIALIZE|SERIALIZE]]</code><br />
|<br />
|<br />
|}<br />
<br />
Alls options can be specified multiple times. With {{Version|7.3}}, all options will be evaluated in the given order (in earlier versions, the sequential evaluation was limited to the specified inputs, query files, queries and commands, while all other options were initially set). The standard input can be parsed by specifying a single dash ({{Code|-}}) as argument.<br />
<br />
=BaseX HTTP Server=<br />
<br />
;Launch the HTTP server:<br />
<pre><br />
$ basexhttp<br />
BaseX [Server]<br />
Server was started.<br />
2011-01-02 03:04:05.600:INFO::Logging to STDERR via org.mortbay.log.StdErrLog<br />
2011-01-02 03:04:05.700:INFO::jetty-6.1.26<br />
2011-01-02 03:04:05.800:INFO::Started SocketConnector@0.0.0.0:8984</pre><br />
<br />
Available command-line flags can be listed with {{Code|-h}}:<br />
<pre><br />
$ basexhttp -h<br />
BaseX [HTTP]<br />
Usage: basexhttp [-aAbdehkKlnpPRsStTUWXz] [stop]<br />
stop Stop running server<br />
-a Deactive SSL support<br />
-A Set https port<br />
-b<pass> Specify SSL password<br />
-d Activate debugging mode<br />
-e<num> Set event port<br />
-h<num> Set port of HTTP server<br />
-k<path> Path to the keystore<br />
-K<pass> Specify keystore password<br />
-l Start in local mode<br />
-n<name> Set host name of database server<br />
-p<num> Set port of database server<br />
-P<pass> Specify user password<br />
-R Deactivate REST service<br />
-s Specify port to stop HTTP server<br />
-S Start as service<br />
-t Path to the truststore<br />
-T Specify truststore password<br />
-U<name> Specify user name<br />
-W Deactivate WebDAV service<br />
-X Deactivate RESTXQ service<br />
-z Suppress logging<br />
</pre><br />
<br />
The flags have the following meaning (equivalent database options are shown in the table as well):<br />
<br />
{| class="wikitable" <br />
|- valign="top"<br />
! width='90' | Flag<br />
! Description<br />
! Option<br />
! Default<br />
! width='145' | Examples<br />
|- valign="top"<br />
| {{Code|stop}}<br />
| Stops a running HTTP server. By default, the database server will be stopped as well, unless one of the flags {{Code|-c}} or {{Code|-l}} is specified.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-a}}<br />
| Deactive the support for SSL connections.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-A}}<br />
| Specify the port used for HTTPS connections.<br />
| <code>[[Options#HTTPSPORT|HTTPSPORT]]</code><br />
| 8989<br />
| -A8988<br />
|- valign="top"<br />
| {{Code|-b}}<br />
| Specify the password for this SSL certificate.<br />
| <code>[[Options#SSLPASSWORD|SSLPASSWORD]]</code><br />
|<br />
| -bPassword<br />
|- valign="top"<br />
| {{Code|-c}}<br />
| Starts the server in ''client mode'', and sends all commands to a database server instance.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-d}}<br />
| Turns on the debugging mode. Debugging information is output to ''standard error''.<br />
| <code>[[Options#DEBUG|DEBUG]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-e&lt;num&gt;}}<br />
| Specifies the port on which the server will send events to clients.<br />
| <code>[[Options#EVENTPORT|EVENTPORT]]</code><br />
| {{Code|1985}}<br />
| {{Code|-e9998}}<br />
|- valign="top"<br />
| {{Code|-h&lt;num&gt;}}<br />
| Specifies the port on which the HTTP server will be addressable. This port is e.g. specified in the HTTP URLs.<br />
| <code>[[Options#HTTPPORT|HTTPPORT]]</code><br />
| {{Code|8984}}<br />
| {{Code|-h9999}}<br />
|- valign="top"<br />
| {{Code|-k}}<br />
| Path to the keystore file<br />
| <code>[[Options#KEYSTORE|KEYSTORE]]</code><br />
| BaseXSSL/keystore<br />
| -k/temp/certify<br />
|- valign="top"<br />
| {{Code|-K}}<br />
| Specify the password for the keystore.<br />
| <code>[[Options#KEYPASSWORD|KEYPASSWORD]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-l}}<br />
| Starts the server in ''local mode'', and executes all commands in the embedded database context.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-n&lt;name&gt;}}<br />
| Specifies the host name on which the server is running.<br />
| <code>[[Options#HOST|HOST]]</code><br />
| {{Code|localhost}}<br />
| {{Code|-nserver.basex.org}}<br />
|- valign="top"<br />
| {{Code|-p&lt;num&gt;}}<br />
| Specifies the port on which the BaseX Server will be addressable.<br />
| <code>[[Options#SERVERPORT|SERVERPORT]]</code><br />
| {{Code|1984}}<br />
| {{Code|-p9998}}<br />
|- valign="top"<br />
| {{Code|-P&lt;pass&gt;}}<br />
| Specifies the user password, which will be used by the HTTP services to open a new session. If this flag is omitted, the password will be requested on command line. ''Warning'': when the password is specified on command-line, it may be visible to others.<br />
|<br />
| {{Code|admin}}<br />
| {{Code|-Uadmin -Padmin}}<br />
|- valign="top"<br />
| {{Code|-R}}<br />
| Deactivates the [[REST]] service.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-s&lt;num&gt;}}<br />
| Specifies the port that will be used to stop the HTTP server.<br />
| <code>[[Options#STOPPORT|STOPPORT]]</code><br />
|<br />
| <br />
|- valign="top"<br />
| {{Code|-S}}<br />
| Starts the server as service (i.e., in the background).<br />
|<br />
| <br />
|- valign="top"<br />
| {{Code|-t}}<br />
| Path to the truststore file.<br />
| <code>[[Options#TRUSTSTORE|TRUSTSTORE]]</code><br />
| BaseXSSL/keystore<br />
| -t/temp/keystore<br />
|- valign="top"<br />
| {{Code|-T}}<br />
| Specify the password for the truststore.<br />
| <code>[[Options#TRUSTSTOREPASSWORD|TRUSTSTOREPASSWORD]]</code><br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-U&lt;name&gt;}}<br />
| Specifies the user name, which will be used by the HTTP services for opening a new session. If this flag is omitted, the password will be requested on command line.<br />
|<br />
| {{Code|admin}}<br />
| {{Code|-Uadmin}}<br />
|- valign="top"<br />
| {{Code|-W}}<br />
| Deactivates the [[WebDAV]] service.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-X}}<br />
| Deactivates the [[RESTXQ]] service.<br />
|<br />
|<br />
|<br />
|- valign="top"<br />
| {{Code|-z}}<br />
| Does not generate any [[Logging|log files]].<br />
|<br />
| <br />
|}<br />
<br />
Some options can also be triggered by setting the following system properties:<br />
<br />
* {{Code|org.basex.user}}: user name for opening new sessions<br />
* {{Code|org.basex.password}}: user password for opening new sessions<br />
* {{Code|org.basex.mode}}: by default, the HTTP server also starts an instance of the database server. If the mode is set to {{Code|local}}, an embedded database context is used for executing commands. If the mode is set to {{Code|client}}, all commands are sent to an existing database server instance.<br />
* {{Code|org.basex.path}}: path to the BaseX [[Configuration|Home Directory]]<br />
<br />
=Changelog=<br />
<br />
; Upcoming version<br />
<br />
* Added: Support for SSL, added relevant Options {{Code|-a}}, {{Code|-A}}, {{Code|-b}}, {{Code|-k}}, {{Code|-K}}, {{Code|-t}}, {{Code|-T}}<br />
<br />
; Version 7.3:<br />
<br />
* Updated: all options are now evaluated in the given order<br />
* Updated: {{Code|-i}} creates main-memory representations for specified sources<br />
* Updated: Options {{Code|-C}}/{{Code|-c}} and {{Code|-q}}/{{Code|[query]}} merged<br />
* Updated: Option {{Code|-L}} also separates serialized items with newlines (instead of spaces)<br />
<br />
; Version 7.2:<br />
<br />
* Added: RESTXQ Service<br />
<br />
; Version 7.1.1:<br />
<br />
* Added: Options {{Code|-C}} and {{Code|-L}} in standalone and client mode<br />
<br />
; Version 7.1:<br />
<br />
* Updated: Multiple query files and {{Code|-c}}/{{Code|-i}}/{{Code|-q}} flags can be specified.<br />
<br />
[[Category:Beginner]]</div>Dirk