Transaction Management

This article is part of the Advanced User's Guide. The BaseX client-server architecture offers ACID-safe transactions, with multiple readers and writers. Here is some more information about the transaction management.

=Introduction=

In a nutshell, a transaction is equal to a command or query. So each command or query sent to the server becomes a transaction.

Incoming requests are parsed and checked for errors on the server. If the command or query is not correct, the request will not be executed, and the user will receive an error message. Otherwise the request becomes a transaction and gets into the transaction monitor.

Please note that:


 * Locks cannot be synchronized across BaseX instances that run in different JVMs. If concurrent write operations are to be performed, we generally recommend working with the client/server or the HTTP architecture.
 * An unexpected abort of the server during a transaction, caused by a hardware failure or power cut, may lead to an inconsistent database state if a transaction was active at shutdown time. So it is advisable to use the BACKUP command to regularly backup your database. If the worst case occurs, you can try the INSPECT command to check if your database has obvious inconsistencies, and use RESTORE to restore the last backed up version of the database.

XQuery Update
Many update operations are triggered by XQuery Update expressions. When executing an updating query, all update operations of the query are stored in a pending update list. They will be executed all at once, so the database is updated atomically. If any of the update sub-operations is erroneous, the overall transaction will be aborted.

=Concurrency Control=

BaseX provides support for multiple read and single write operations (using preclaiming and starvation-free two phase locking). This means that:


 * Read transactions are executed in parallel.
 * If an updating transaction comes in, it will be queued and executed after all previous read transaction have been executed.
 * Subsequent operations (read or write) will be queued until the updating transaction has completed.
 * Jobs without database access will never be locked. Globally locking jobs can now be executed in parallel with non-locking jobs.
 * Each database has its own queue: An update on database A will not block operations on database B. This is under the premise that it can be statically determined, i.e., before the transaction is evaluated, which databases will be accessed by a transaction (see below).
 * The number of maximum parallel transactions can be adjusted with the option.
 * By default, read transactions are favored, and transactions that access no databases can be evaluated even if the transactions limit has been reached. This behavior can be changed via the option.

XQuery Locks
By default, access to external resources (files on hard disk, HTTP requests, ...) is not controlled by the transaction monitor of BaseX. You can use custom XQuery locks to do so:

Options, Pragmas, Annotations

 * You can declare custom read and write locks via options, pragmas or function annotations.
 * The value of the lock may contain one or multiple lock keys (separated with commas). The default value is an empty string.
 * Similar to the internal database locks, write locks block all other operations while read locks allow parallel access.
 * The internal locks and XQuery locks can co-exist (there will be no conflicts, even if your lock string equals the name of a database that will be locked by the transaction manager).

In the following module, lock annotations are used to prevent concurrent write operations on the same file:

 module namespace config = 'config';

declare %basex:read-lock('CONFIG') function config:read { file:read-text('config.txt') };

declare %basex:write-lock('CONFIG') function config:write($data) { file:write-text('config.txt', $data) };

Some explanations:


 * If a query calls the  function, a read lock will be acquired for the user-defined CONFIG lock string before query evaluation.
 * If  is called by a query, a write lock on this lock string will be set for this query.
 * If a query calls, it will be queued until there is no running query left that has CONFIG locked.
 * If the writing query will be evaluated, all other queries that will set a CONFIG lock (reading or writing) will have to wait.

Local locks can also be declared via pragmas:

 (# basex:write-lock CONFIG #) { file:write('config.xml', ) }

Locks for the functions of a module can be assigned via option declarations:

 declare option basex:write-lock 'CONFIG'; file:write('config.xml', )

Java Modules
Locks can also be acquired on Java functions which are imported and invoked from an XQuery expression. It is advisable to explicitly lock Java code whenever it performs sensitive read and write operations.

Commands
Database locking works with all commands unless the glob syntax is used, such as in the following command call:


 * DROP DB new*: drop all databases starting with "new"

XQuery
Deciding which databases will be accessed by a complex XQuery expression is a non-trivial task. Database detection works for the following types of queries:


 * //item, read-locking of the database opened by a client
 * doc('factbook'), read-locking of "factbook"
 * collection('db/path/to/docs'), read-locking of "db"
 * fn:sum(1 to 100), locking nothing at all
 * delete nodes db:open('test')//*[string-length(local-name(.)) > 5], write-locking of "test"

A global lock will be assigned if the name of the database is not a static string:


 * for $db in ('db1', 'db2') return db:open($db)
 * doc(doc('test')/reference/text)

The functions fn:doc and fn:collection can also be used to address that are not stored in a database. However, this may lead to unwanted locks, and you have two options to reduce the number of locks: No database lookups will take place if option is disabled, or if $$ is used instead of fn:doc.

You can consult the query info output (which you find in the Info View of the GUI or which you can turn on by setting to true) to find out which databases have been locked by a query.

=File-System Locks=

Update Operations
During a database update, a locking file upd.basex will reside in that database directory. If the update fails for some unexpected reason, or if the process is killed ungracefully, this file will not be deleted. In this case, the database cannot be opened anymore, and the message "Database ... is being updated, or update was not completed" will be shown instead.

If the locking file is manually removed, you may be able to reopen the database, but you should be aware that database may have got corrupt due to the interrupted update process, and you should revert to the most recent database backup.

Database Locks
To avoid database corruptions that are caused by accidental write operations from different JVMs, a shared lock is requested on the database table file (tbl.basex) whenever a database is opened. If an update operation is triggered, and if no exclusive lock can be acquired, it will be rejected with the message "Database ... is currently opened by another process.".

Please note that you cannot 100% rely on this mechanism, as it is not possible to synchronize operations across different JVMs. You will be safe when using the client/server or HTTP architecture.

=Changelog=


 * Version 9.1
 * Updated: Query lock options were moved from query to basex namespace.


 * Version 8.6
 * Updated: New option, improved detection of lock patterns.


 * Version 7.8
 * Added: Locks can also be acquired on Java functions.


 * Version 7.6
 * Added: database locking introduced, replacing process locking.


 * Version 7.2.1
 * Updated: pin files replaced with shared/exclusive filesystem locking.


 * Version 7.2
 * Added: pin files to mark open databases.


 * Version 7.1
 * Added: update lock files.