# Using Zorba

The parts of Zorba that are not the language itself: how to run queries, which libraries ship with it, the in-memory store, and the C++ API.

## The command line

`zorba` runs one or more queries and writes the results to standard output. A query is either given inline or, with `-f`, read from a file. Which language a query is written in is decided in this order: a `jsoniq version "1.0";` or `xquery version "3.0";` declaration at the start of the query; else the extension of the file (`.jq` is JSONiq, `.xq` is XQuery); else `--language`, which is XQuery unless set. Inline queries and other extensions fall under `--language`.

| Option | Effect |
|----|----|
| `-q <query>` | The query text, or a file name with `-f`. |
| `-f`, `--as-files` | Treat the `-q` arguments as file names. |
| `-i`, `--indent` | Indent the output. |
| `-r`, `--omit-xml-declaration` | Do not print `<?xml ...?>`. |
| `--language xquery|jsoniq` | The language of a query that has no declaration and is not read from a `.jq` or `.xq` file. Default `xquery`. |
| `-j`, `--jsoniq` | The same as `--language jsoniq`. |
| `-e name:=value` | Bind an external variable to a string; `-e name=file` binds it to the parsed XML document in a file. |
| `--context-item <file>` | Make the XML document in a file the context item. |
| `-z name=value` | Set a serialization parameter, for example `-z method=json` or `-z method=xhtml`. |
| `--serialize-text`, `--serialize-html` | Shortcuts for the text and HTML output methods. |
| `-o <file>` | Write the result to a file. |
| `--module-path <dirs>` | Directories to search for imported modules. |
| `--base-uri <uri>` | Set the static base URI used to resolve relative paths. |
| `-t`, `--timing` | Print compilation and execution times. |
| `--compile-only`, `--parse-only` | Check a query without running it. |

`zorba --help` lists everything, including optimizer and debugging switches. By default the output method is `json-xml-hybrid`: XML nodes are serialized as XML, JSON items as JSON, and atomic values separated by spaces, which is what you see in the examples on this site.

## Restricting a query

By default `zorba` trusts the query: it may read and write files, use the network, read environment variables, expand external entities in XML input and load modules implemented in C++. To run a query you do not trust, start from `--secure`, which allows none of that, and allow only what the query needs. The capabilities are `external-entities`, `file-read`, `file-write`, `network`, `remote-import` (module and schema import over the network), `environment`, `native-modules` (for example the file and http-client modules) and `all`.

| Option | Effect |
|----|----|
| `--secure` | Start from a policy that allows no capability. |
| `--allow <caps>`, `--deny <caps>` | Allow or deny a comma-separated list of capabilities, applied in command-line order. |
| `--read-path <dir>`, `--write-path <dir>` | Limit file reads or writes to a directory (repeatable). |
| `--network-prefix <url>` | Limit network access to URLs under a prefix (repeatable). |
| `--private-addresses allow|deny` | Whether the network capability reaches loopback, private and link-local addresses; denied by default with `--secure`. |
| `--timeout <s>`, `--max-call-depth <n>` | Stop the query after a time (`zerr:ZXQP0068`) or a function call depth (`zerr:ZXQP0069`). |

```sh
zorba --secure --allow file-read --read-path /srv/data --timeout 10 -f -q report.xq
```

A denied file or network access raises the error of the function that made it (for example `err:FODC0002` from `fn:doc` or `file:FOFL9999` from the file module) whose message contains "access denied by security policy", and importing a module that needs a denied capability raises `zerr:ZXQP0067`; denied environment functions return the empty sequence. Modules and schemas in the URI and library paths can always be imported; with `--secure` the current directory is not one of them (add it with `--module-path` and an absolute path). The files named on the command line (queries, `--context-item`, `-e name=file`, `-o`) are opened by `zorba` itself and are not restricted.

**Why it matters:** a query from a user, a request or a file you did not write cannot read `/etc/passwd`, reach an internal service or run forever.

## External variables

A query declares the inputs it expects with `declare variable ... external`, optionally with a type and a default. The command line or the C++ API supplies the values.

**XQuery**: `zorba/external-var.xq`

```xquery
declare variable $name external;
declare variable $times as xs:integer external := 2;

string-join(for $i in 1 to $times return concat("hi ", $name), ", ")
```

**Result**: `zorba -i -r -e name:=Rodolfo -e times:=3 -f -q external-var.xq`

```
hi Rodolfo, hi Rodolfo, hi Rodolfo
```

**Why it matters:** a query becomes a reusable program with parameters instead of a string you edit.

## Built-in modules

These library modules ship with Zorba and are imported by namespace URI, with no `at` clause. Older Zorba releases had many more modules in separate repositories (archives, images, databases, and so on); those are not part of this code base.

| Namespace URI | What it offers |
|----|----|
| `http://expath.org/ns/file` | Read, write, list and delete files and directories (EXPath File). |
| `http://zorba.io/modules/http-client` | HTTP requests with JSON-shaped requests and responses. |
| `http://www.zorba-xquery.com/modules/http-client` | The older, XML-shaped HTTP client interface. |
| `http://zorba.io/modules/fetch` | Fetch the content of a URI as text or binary. |
| `http://zorba.io/modules/string` | Splitting and other string helpers. |
| `http://zorba.io/modules/math` | Spreadsheet-style math and statistics (median, standard deviation, Roman numerals, ...). |
| `http://zorba.io/modules/random` | Random numbers and UUIDs. |
| `http://zorba.io/modules/base64` | Base64 encoding and decoding. |
| `http://zorba.io/modules/datetime` | Current time, timestamps, parsing dates with a pattern. |
| `http://zorba.io/modules/sequence` | Set operations on atomic values. |
| `http://zorba.io/modules/uri` | Parsing, serializing and decoding URIs. |
| `http://zorba.io/modules/xml` | Parsing XML with options, and canonicalization. |
| `http://zorba.io/modules/schema` | Schema types of validated nodes, validation in place. |
| `http://zorba.io/modules/json-xml` | Generic conversion between JSON and XML (JsonML and other formats). |
| `http://zorba.io/modules/json-csv` | CSV to JSON objects and back. |
| `http://jsoniq.org/functions`, `http://jsoniq.org/function-library` | The JSONiq function libraries (`keys`, `members`, `parse-json`, `descendant-objects`, ...). |
| `http://jsound.io/modules/jsound` | Validating JSON against JSound schemas. |
| `http://zorba.io/modules/full-text` | Tokenizing, stemming, stop words and thesaurus lookups outside `contains text`. |
| `http://zorba.io/modules/node`, `.../node-position`, `.../reference` | Structural relationships between nodes (ancestor-of, level, ...), node positions and stable node references. |
| `http://zorba.io/modules/item` | The size of an item. |
| `http://zorba.io/modules/reflection` | Calling functions by name, evaluating query strings. |
| `http://zorba.io/modules/zorba-query` | Compiling and running queries from inside a query. |
| `http://zorba.io/modules/sctx`, `http://zorba.io/modules/dctx` | Inspecting the static and dynamic context. |
| `http://zorba.io/modules/store/...` | Collections, indexes and integrity constraints (below), named documents, and key-value maps in the store. |
| `http://zorba.io/modules/sleep` | Pausing a query. |
| `http://zorba.io/modules/xqdoc` | Generating xqDoc documentation for modules. |
| `http://www.functx.com` | The FunctX library of general-purpose XQuery functions. |

**XQuery**: `zorba/modules.xq`

```xquery
import module namespace string = "http://zorba.io/modules/string";
import module namespace math = "http://zorba.io/modules/math";
import module namespace seq = "http://zorba.io/modules/sequence";
import module namespace ft = "http://zorba.io/modules/full-text";

(
  <split>{ string:split("a,b,,c", ",") ! concat("[", ., "]") }</split>,
  <roman>{ math:roman(2026) }</roman>,
  <union>{ seq:value-union((1, 2, 3), (2, 3, 4)) }</union>,
  <stem>{ ft:stem("running", xs:language("en")) }</stem>
)
```

**Result**: `zorba -i -r -f -q modules.xq`

```
<split>[a] [b] [] [c]</split>
<roman>MMXXVI</roman>
<union>1 2 3 4</union>
<stem>run</stem>
```

**JSONiq**: `zorba/csv.jq`

```jsoniq
import module namespace csv = "http://zorba.io/modules/json-csv";

let $text := "sku,qty
A1,2
B7,1"
return [ csv:parse($text) ]
```

**Result**: `zorba -i -r -f -q csv.jq`

```
[ {
  "sku" : "A1", 
  "qty" : 2
}, {
  "sku" : "B7", 
  "qty" : 1
} ]
```

**Why it matters:** common chores (files, HTTP, CSV, statistics) are a module import away, without writing C++ extensions.

## Collections

A collection is a named, ordered set of documents or JSON items kept in Zorba's store for the life of the process. The dynamic collection modules create collections by QName at run time; the data manipulation functions insert and delete whole items. These are updating functions, and in a program with several statements (see [scripting](#scripting)) each statement's updates are applied when it ends.

**XQuery**: `zorba/dynamic-collection.xq`

```xquery
import module namespace ddl = "http://zorba.io/modules/store/dynamic/collections/ddl";
import module namespace dml = "http://zorba.io/modules/store/dynamic/collections/dml";

variable $notes := xs:QName("notes");

ddl:create($notes);
dml:insert-last($notes, (<note n="1">buy milk</note>, <note n="2">call mom</note>));
dml:insert-last($notes, <note n="3">fix bug</note>);
dml:delete(dml:collection($notes)[@n = "2"]);

<notes count="{count(dml:collection($notes))}">{ dml:collection($notes) }</notes>
```

**Result**: `zorba -i -r -f -q dynamic-collection.xq`

```
<notes count="2">
  <note n="1">buy milk</note>
  <note n="3">fix bug</note>
</notes>
```

**Why it matters:** `dml:delete` is needed because the items of a collection are roots. The Update Facility's `delete node` has no effect on a node without a parent.

## Static collections and indexes

XQDDF, Zorba's data definition facility, declares collections, indexes and constraints in the prolog of a library module, much as SQL DDL declares tables. A declared collection has a type, and a declared index is maintained by the store as the collection changes.

**XQuery module**: `zorba/lib/shop.xqm`

```xqm
module namespace shop = "http://example.org/shop";

import module namespace dml = "http://zorba.io/modules/store/static/collections/dml";

declare namespace an = "http://zorba.io/annotations";

(: A statically declared collection of <product> elements :)
declare collection shop:products as element(product)*;
declare variable $shop:products := xs:QName("shop:products");

(: A value index on the product category, kept up to date automatically :)
declare %an:value-equality %an:nonunique %an:automatic index shop:by-category
  on nodes dml:collection(xs:QName("shop:products"))
  by string(@category) as xs:string;
declare variable $shop:by-category := xs:QName("shop:by-category");

(: No two products may share a sku :)
declare integrity constraint shop:unique-sku
  on collection shop:products node $p check unique key $p/@sku;
declare variable $shop:unique-sku := xs:QName("shop:unique-sku");
```

**XQuery**: `zorba/static-collection.xq`

```xquery
import module namespace shop = "http://example.org/shop" at "lib/shop.xqm";
import module namespace ddl = "http://zorba.io/modules/store/static/collections/ddl";
import module namespace dml = "http://zorba.io/modules/store/static/collections/dml";
import module namespace iddl = "http://zorba.io/modules/store/static/indexes/ddl";
import module namespace idml = "http://zorba.io/modules/store/static/indexes/dml";

ddl:create($shop:products);
iddl:create($shop:by-category);

dml:insert($shop:products, (
  <product sku="A1" category="tea">Green tea</product>,
  <product sku="B7" category="coffee">Espresso beans</product>,
  <product sku="C3" category="tea">Rooibos</product>));

<tea>{ idml:probe-index-point-value($shop:by-category, "tea")/string() }</tea>
```

**Result**: `zorba -i -r -f -q static-collection.xq`

```
<tea>Green tea Rooibos</tea>
```

**Why it matters:** an index probe finds the matching items without scanning the collection. Zorba does not choose indexes automatically: you probe them by name, as above.

## Integrity constraints

Integrity constraints declared on a collection are checked when updates are applied, once activated. Here the second insert of the same `sku` violates a unique key, the whole update is rejected, and the collection keeps one product.

**XQuery**: `zorba/integrity.xq`

```xquery
import module namespace shop = "http://example.org/shop" at "lib/shop.xqm";
import module namespace ddl = "http://zorba.io/modules/store/static/collections/ddl";
import module namespace dml = "http://zorba.io/modules/store/static/collections/dml";
import module namespace icddl = "http://zorba.io/modules/store/static/integrity-constraints/ddl";

declare namespace err = "http://www.w3.org/2005/xqt-errors";

ddl:create($shop:products);
icddl:activate($shop:unique-sku);
dml:insert($shop:products, <product sku="A1" category="tea">Green tea</product>);

variable $outcome :=
  try {
    {
      dml:insert($shop:products, <product sku="A1" category="tea">Duplicate</product>);
      "inserted"
    }
  }
  catch * {
    concat("rejected: ", local-name-from-QName($err:code))
  };

<second-insert>{ $outcome }</second-insert>,
<products>{ count(dml:collection($shop:products)) }</products>
```

**Result**: `zorba -i -r -f -q integrity.xq`

```
<second-insert>rejected: ZDDY0033</second-insert>
<products>1</products>
```

**Why it matters:** invariants live next to the data definition instead of being re-checked by every query that writes.

## Scripting

Zorba's scripting extension adds imperative constructs to XQuery and JSONiq: statements separated by semicolons, mutable variables declared with `variable`, assignment with `:=`, blocks in braces, `while` loops, `exit returning`, and functions annotated `%an:sequential` that may have side effects. The updates of each statement are applied before the next one runs.

**XQuery**: `zorba/scripting.xq`

```xquery
(: Zorba's scripting extension: mutable variables, assignment, loops. :)
variable $total := 0;
variable $i := 1;
while ($i le 5) {
  $total := $total + $i * $i;
  $i := $i + 1;
}
$total
```

**Result**: `zorba -i -r -f -q scripting.xq`

```
55
```

**Why it matters:** programs that create collections, load data, update it and then query it can be written in one file, as in the collection examples above.

`break` and `continue` are not implemented inside FLWOR expressions; use `while` loops when you need them.

## Embedding in C++

The C++ API is in `include/zorba`. The usual pattern: create a store and a `Zorba` instance, compile a query into an `XQuery` object, bind external variables on its dynamic context, iterate over the result, and shut down in reverse order. Compilation errors and runtime errors are thrown as `ZorbaException`. This program is compiled against the installed headers and linked with `libzorba_simplestore` as part of the site build.

**C++**: `zorba/embed.cpp`

```cpp
// Embedding Zorba in a C++ program: compile a query, bind an external
// variable, iterate over the result items, and catch a static error.
#include <iostream>

#include <zorba/store_manager.h>
#include <zorba/zorba.h>
#include <zorba/zorba_exception.h>

using namespace zorba;

int main() {
  void* store = StoreManager::getStore();
  Zorba* engine = Zorba::getInstance(store);
  {
    XQuery_t query = engine->compileQuery(
        "declare variable $n external;\n"
        "for $i in 1 to $n return $i * $i");
    query->getDynamicContext()->setVariable(
        "n", engine->getItemFactory()->createInteger(5));

    Iterator_t it = query->iterator();
    it->open();
    Item item;
    while (it->next(item)) {
      std::cout << item.getStringValue() << '\n';
    }
    it->close();

    try {
      engine->compileQuery("for $x in (1, 2, 3)");
    } catch (ZorbaException const& e) {
      std::cout << "error " << e.diagnostic().qname().localname() << '\n';
    }
  }
  engine->shutdown();
  StoreManager::shutdownStore(store);
  return 0;
}
```

**Result**: `g++ -std=c++23 embed.cpp -lzorba_simplestore && ./a.out`

```
1
4
9
16
25
error XPST0003
```

Save the program as `embed.cpp` and compile it against an installed Zorba (here installed with `cmake --install build --prefix "$HOME/zorba"`). A prefix that is not a system directory needs `LD_LIBRARY_PATH` so that the program finds `libzorba_simplestore`:

```sh
g++ -std=c++23 -I"$HOME/zorba/include" embed.cpp -L"$HOME/zorba/lib" -lzorba_simplestore -o embed
LD_LIBRARY_PATH="$HOME/zorba/lib" ./embed
```

Unlike the command line, an embedded engine starts from the secure policy: queries cannot read or write files, use the network, expand external entities, load native modules or read environment variables until the application allows it, for example `engine->setSecurityPolicy(SecurityPolicy::secure().allow(Capability::FileRead).addReadPath("/srv/data"))`. `engine->setSecurityPolicy(SecurityPolicy::unrestricted())` restores the behavior of Zorba 4.x. The policy is declared in `include/zorba/security.h`.

**Why it matters:** a compiled query can be executed many times with different variables, which is how an application uses Zorba as its query engine. More examples are in [`doc/cxx/examples`](https://github.com/zorba-processor/zorba/tree/master/doc/cxx/examples).

### Threading

Zorba 5.0 is not thread-safe, and there is one engine and one store per process (`Zorba::getInstance` returns a singleton). Use Zorba, and every object created from it, from one thread at a time; if several threads need it, serialize all calls with your own mutex. For parallel queries, run separate processes.

## Limits

- The store is in memory and not persistent: collections disappear when the process ends.
- No XQuery 3.1 (maps, arrays, `=>`, `?`). Use JSONiq.
- Full Text is mostly, not completely, implemented; serialization character maps are not implemented.
- XQueryX needs a build with `ZORBA_XQUERYX` enabled.
- No XSLT.

The source, the issue tracker and build instructions are in the [GitHub repository](https://github.com/zorba-processor/zorba).
