NoSQL Zone is brought to you in partnership with:

Developer with experience in a variety of different systems and technologies, with a customer focus and balance with business goals. Particularly interested in backend and large scale systems, and also interested in high level architecture, and API design. Always open to feedback in order to keep learning and improving as a professional. Rodrigo is a DZone MVB and is not an employee of DZone and has posted 39 posts at DZone. You can read more from them at their website. View Full User Profile

How to Use a Precommit Hook in Riak

  • submit to reddit

Book "Seven Databases in Seven Weeks" has an example of how to use a precommit hook in Riak. However, it did not work for me (Riak 1.1.4). The issue is that I was getting the following message for every single commit:

PUT aborted by pre-commit hook

After enabling debug logging in the app.config (*), I realized that it was failing with the following error: 

Problem invoking pre-commit hook: [{<<"lineno">>,1},{<<"message">>,<<"ReferenceError: good_scores is not defined">>},{<<"source">>,<<"unknown">>}]

The problem is that the command to set the precommit hook MUST specify the language, otherwise it doesn't work properly. In order to get the book's example fixed then, do the following: 

curl -i -X PUT http://localhost:8091/riak/animals -H "content-type: application/json" -d '{"props":{"precommit":[{"name":"good_score","language":"javascript"}]}}' 

Once enabled, I was getting the proper error messages. Most importantly, valid data was being accepted and committed by Riak.

You may be wondering how the Javascript looks like. Since I can't copy the book's example due to copyright, this is an example of function that works the same: 

// Makes sure the object has JSON contents
function precommitMustBeJSON(object){
  try {
    return object;
  } catch(e) {
    return {"fail":"Object is not JSON"};

Unfortunately Riak does not have a good tutorial or example on that and it was hard to find the reason for the error. Maybe it'll get better as it matures.

One final thing: don't forget that you need to put your function in a .js file in a directory configured in your app.config. For instance, my file is called "my_validators.js" and it's located in the directory I configured in app.config: 

{js_source_dir, "/home/rdcastro/riak/js_source"}, 

(*) To enable debug logging, make sure your "lager" section has the following settings: 

            {handlers, [
                {lager_console_backend, debug},
                {lager_file_backend, [
                    {"./log/error.log", error, 10485760, "$D0", 5},
                    {"./log/console.log", debug, 10485760, "$D0", 5}




Published at DZone with permission of Rodrigo De Castro, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)