Prepare for the PgBouncer and IPv4 deprecations on 26th January 2024

Home

plv8: JavaScript Language

The plv8 extension allows you use JavaScript within Postgres.

Overview

While Postgres natively runs SQL, it can also run other "procedural languages". plv8 allows you to run JavaScript code - specifically any code that runs on the V8 JavaScript engine.

It can be used for database functions, triggers, queries and more.

Enable the extension

  1. Go to the Database page in the Dashboard.
  2. Click on Extensions in the sidebar.
  3. Search for "plv8" and enable the extension.

Create plv8 functions

Functions written in plv8 are written just like any other PostgreSQL functions, only with the language identifier set to plv8.


_10
create or replace function function_name()
_10
returns void as $$
_10
// V8 JavaScript
_10
// code
_10
// here
_10
$$ language plv8;

You can call plv8 functions like any other Postgres function:


_10
select function_name();

Examples

Scalar functions

A scalar function is anything that takes in some user input and returns a single result.


_10
create or replace function hello_world(name text)
_10
returns text as $$
_10
_10
let output = `Hello, ${name}!`;
_10
return output;
_10
_10
$$ language plv8;

Executing SQL

You can execute SQL within plv8 code using the plv8.execute function.


_10
create or replace function update_user(id bigint, first_name text)
_10
returns smallint as $$
_10
_10
var num_affected = plv8.execute(
_10
'update profiles set first_name = $1 where id = $2',
_10
[first_name, id]
_10
);
_10
_10
return num_affected;
_10
$$ language plv8;

Set-returning functions

A set-returning function is anything that returns a full set of results - for example, rows in a table.


_11
create or replace function get_messages()
_11
returns setof messages as $$
_11
_11
var json_result = plv8.execute(
_11
'select * from messages'
_11
);
_11
_11
return json_result;
_11
$$ language plv8;
_11
_11
select * from get_messages();

Resources