/******************************************************************************
How to load Javascript modules into postgres
******************************************************************************/
CREATE EXTENSION IF NOT EXISTS plv8

curl -O https://raw.githubusercontent.com/jkbrzt/rrule/master/lib/rrule.js

/******************************************************************************
Open postgres console and set runtime variable to 
use the code later
******************************************************************************/

psql -d scout
\set rrule `cat rrule.js`

/******************************************************************************
Now that we have set variable containing the code
we need to create a table to store each of them in
postgres. 
******************************************************************************/

create table plv8_modules(modname text primary key, load_on_start boolean, code text);

insert into plv8_modules values ('rrule',true,:'rrule');

/******************************************************************************
Create a a startup function to create a plv8 function
that will be used to load the modules, Executing it 
will register the plv8 function
******************************************************************************/

create or replace function plv8_startup()
returns void
language plv8
as
$$
load_module = function(modname) {
  var rows = plv8.execute("SELECT code from plv8_modules " +" where modname = $1", [modname]);
  for (var r = 0; r < rows.length; r++) {
    var code = rows[r].code;
    eval("(function() { " + code + "})")();
  }      
};
$$;

select plv8_startup();

/******************************************************************************
Load both modules into postgres using the previously created plv8 function
******************************************************************************/

do language plv8 ' load_module("rrule"); ';