Events
From BaseX Documentation
This article is part of the Advanced User's Guide. it presents how to trigger database events and notify listening clients.
Contents |
[edit] Introduction
The events feature enables users with admin permissions to create events, which can then be watched by other clients. All clients that have registered for an event will be notified if an event is triggered by another client.
[edit] Managing Events
- CREATE EVENT [name]
- Creates an event [name].
- DROP EVENT [name]
- Drops the event with the specified [name].
- SHOW EVENTS
- Shows all events.
[edit] Watching/Unwatching Events
The events can currently be watched by the Java and C# clients. See the following Java code example:
Watch events:
// name of the event
String event = "call";
// create new client
BaseXClient client = new BaseXClient("localhost", 1984, "admin", "admin");
// register for an event
client.watch(event, new EventNotifier() {
@Override
public void notify(final String value) {
System.out.println("Received data: " + value);
}
});
Unwatch events:
// unregister from an event client.unwatch(event);
For a complete and self-contained example in Java, you may have a look [1].
[edit] Firing Events
Events are triggered via the XQuery function db:event():
db:event($name as xs:string, $query as item())
Executes a $query and sends the resulting value to all clients watching the event with the specified $name. No event will be sent to the client that fired the event.
[edit] Example Scenarios
[edit] Basic
- Client1 creates an event with the name "EVENT"
- Client2 and Client3 call the watch method for event "EVENT"
- Client1 executes XQuery
db:event("EVENT", "1 to 2") - Client2 and Client3 will receive the result
1 2 - Client2 executes XQuery
db:event("EVENT", "2 to 3") - Client3 will receive the result
2 3
[edit] Included in Update Expression
- Client1 creates an event with the name "DELETED"
- Client2 and Client3 call the watch method for event "DELETED"
- Client1 executes XQuery
let $deleted := //nodes return ( delete node $deleted, db:event( "DELETED", $deleted) )
- Client2 and Client3 will receive the deleted nodes.
[edit] Included in Update Expression with Payload
- Client1 creates an event with the name "DELETED"
- Client2 and Client3 call the watch method for event "DELETED"
- Client1 executes XQuery
let $deleted := //nodes return ( delete node $deleted, db:event( "DELETED", <message> <payload>{count($deleted)} items have been deleted.</payload> <items>{$deleted}</items> </message>) ) - Client2 and Client3 will receive the message with the payload and the deleted nodes.