Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can plv8 JavaScript language extension call 3rd party libraries?

In Postgresql, I want to call 3rd party libraries like moment.js or AWS lambda JS Client to invoke serverless functions from within the DB. I don't see any docs or examples how to do so: https://github.com/plv8/plv8/blob/master/README.md

Is this possible and where can I find examples of how to 'import' or 'require' additional libraries?

like image 951
Jason Avatar asked Jul 16 '17 16:07

Jason


Video Answer


1 Answers

The plv8 language is trusted so there is no way to load anything from the file system. However you can load modules from the database.

Create a table with source code of a module and load it using select and eval(). A simple example to illustrate the idea:

create table js_modules (
    name text primary key,
    source text
);

insert into js_modules values
('test', 'function test() { return "this is a test"; }' );

Load the module from js_modules in your function:

create or replace function my_function()
returns text language plv8 as $$
//  load module 'test' from the table js_modules
    var res = plv8.execute("select source from js_modules where name = 'test'");
    eval(res[0].source);
//  now the function test() is defined
    return test();
$$;

select my_function();

CREATE FUNCTION
  my_function   
----------------
 this is a test
(1 row) 

You can find a more elaborate example with an elegant require() function in this post: A Deep Dive into PL/v8.. Its is based on plv8.start_proc (see also a short example here).

like image 93
klin Avatar answered Sep 20 '22 11:09

klin