Back to top

ReQL command: setWriteHook

Command syntax

table.setWriteHook(function | binary | null) → object

Description

Sets the write hook on a table or overwrites it if one already exists.

The function can be an anonymous function with the signature (context: object, oldVal: object, newVal: object) -> object or a binary representation obtained from the function field of getWriteHook. The function must be deterministic, and so cannot use a subquery or the r.js command.

The first argument, context, is a ReQL object containing the following properties:

  • primary_key: primary key of the document being deleted, inserted, or modified
  • timestamp: a ReQL time object representing the current query execution time

As is the case when creating secondary index functions using indexCreate, r.now() is considered non-deterministic and is thus not allowed in the context of write hooks. If you need to reference the current timestamp, context('timestamp') should be used instead.

Whenever a write operation on the table inserts, deletes or modifies a given document, the write hook function will be called with the context parameter, the old value of the document (or null on inserts) and the new value of the document (or null on deletes). It then returns the value that should actually be inserted and/or replaced instead of newVal. It can also return r.error(...) to abort the write.

For simplicity, the write hook function is allowed to return null exactly if and only if newVal is null. This is just a safeguard to ensure you don’t accidentally turn an insert/update into a deletion, or a deletion into an update.

If successful, setWriteHook returns an object of the form:

{
  "created": 1,
}

or

{
  "replaced": 1,
}

or

{
  "deleted": 1,
}

Example: Create a write hook that sets modified_at to the current time on each write operation.

r.table('comments').setWriteHook(function(context, oldVal, newVal) {
  return newVal.merge({
    modified_at: context('timestamp')
  });
}).run(conn, callback)

Example: Delete the write hook associated with the comments table.

r.table('comments').setWriteHook(null).run(conn, callback)

Example: Recreate an outdated write hook on a table.

r.table('posts').getWriteHook().do(function(writeHook) {
  return r.table('posts').setWriteHook(writeHook('function'));
}).run(conn, callback)

Get more help

Couldn't find what you were looking for?